From f8e767eeb50ac32dd05f4e5e42257c2c194da0fd Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 11:11:28 -0800 Subject: [PATCH 1/2] feat(workflows): dry runs stub reads that depend on a stubbed write, and flag MCP tools servers call read-only Placeholder values are distinctive: the dry-run sample mints each string it makes up as dryRunId(, n) and each number as dryRunNumber(n) (above 900000000), beside the ids dryRunOutput hooks mint. The policy registers the placeholders of every answer it returns (stubbed writes, derived reads, blocks answered whole; never mocks or real results), per run and with no hook signature change. A read that would send a registered placeholder (a token anywhere in a string, in any case and ending at its _, or a number whole or as a digit run) is not sent and is listed in stubbed with dependsOnStub: a read tool's declared params, an HTTP GET/HEAD/OPTIONS (readsWhen reads go through the same check), an MCP call's arguments, and a GET/HEAD/OPTIONS fetch code makes in the isolate (its URL or body; answered with the empty stubbed 200 and left out of the --allow hint). Create-then-read chains, by id or by number, no longer reach the provider; free text quoting a placeholder counts too. Runs without a side-effect policy do no extra work. MCP tools keep their readOnlyHint/destructiveHint annotations, but a dry run never acts on them: annotations are the server's unverified claim. A held-back MCP call is still authorized and checked against an uncached tools/list without being sent; the check reports what it learned of the tool, so the stubbed entry carries readOnlyHint (read-only and not destructive), the CLI says --allow '' sends it, and the placeholder samples the tool's outputSchema as structuredContent (integer as number, a union as its first non-null member, untyped fields left out). MCP block entries (stubbed and allowed) record the MCP server and tool they named, and allowed ones are deduplicated by it. Workflow test reports keep mcp, dependsOnStub and readOnlyHint. The v2 MCP tools route projects the strict contract fields, since discovered tools now carry annotations. Effect labels reviewed, unchanged: firecrawl_crawl and firecrawl_extract start async provider jobs with their own ids (write); slack_message_reader opens a DM conversation via conversations.open when given a user (param-dependent, write). --- .agents/skills/add-tools/SKILL.md | 10 +- .../api-reference/build-and-run-workflows.mdx | 2 +- apps/docs/content/docs/cli/reference.mdx | 2 +- apps/docs/content/docs/cli/workflows.mdx | 2 +- apps/docs/openapi-v2-workflows.json | 74 +++- .../mcp-servers/[mcpServerId]/tools/route.ts | 13 +- apps/sim/executor/execution/types.ts | 48 ++- apps/sim/lib/api/contracts/v2/workflows.ts | 28 +- apps/sim/lib/internal/mcp/execute-tool.ts | 13 +- .../application/execute-managed-tool.test.ts | 39 +- .../mcp/application/execute-managed-tool.ts | 9 +- .../lib/mcp/application/execute-tool.test.ts | 15 +- apps/sim/lib/mcp/application/execute-tool.ts | 31 +- apps/sim/lib/mcp/client.ts | 15 + apps/sim/lib/mcp/types.ts | 12 + apps/sim/lib/mothership/tools/server/tests.ts | 17 +- apps/sim/lib/workflow-tests/protocol.ts | 11 +- apps/sim/lib/workflow-tests/session.ts | 17 +- .../application/dry-run.integration.ts | 377 +++++++++++++++++- .../workflows/dry-run/placeholders.test.ts | 42 ++ .../sim/lib/workflows/dry-run/placeholders.ts | 99 +++++ apps/sim/lib/workflows/dry-run/samples.ts | 122 +++++- .../sim/lib/workflows/dry-run/side-effects.ts | 80 +++- apps/sim/tools/dry-run.ts | 12 + apps/sim/tools/index.test.ts | 42 ++ apps/sim/tools/index.ts | 42 +- apps/sim/tools/side-effects.test.ts | 22 +- apps/sim/tools/side-effects.ts | 131 ++++-- .../protocol/workflow-run-follow.test.ts | 28 +- .../commands/protocol/workflow-run-follow.ts | 57 ++- packages/sim-cli/src/generated/v2-api.ts | 10 + 31 files changed, 1247 insertions(+), 175 deletions(-) create mode 100644 apps/sim/lib/workflows/dry-run/placeholders.test.ts create mode 100644 apps/sim/lib/workflows/dry-run/placeholders.ts diff --git a/.agents/skills/add-tools/SKILL.md b/.agents/skills/add-tools/SKILL.md index c9c89e11a45..8cf74244641 100644 --- a/.agents/skills/add-tools/SKILL.md +++ b/.agents/skills/add-tools/SKILL.md @@ -225,10 +225,12 @@ search that returns no email or phone, and an email verifier. `sim workflows run --dry --input '{…}'`. Each `write` call must appear in the result's `sideEffects.stubbed` with the request you expect (an HTTP tool's `method`, `url` and `body`, or an in-process operation's input, credentials redacted), and each `read` must run for real and return - live data; a read listed there is labelled `write`. A write missing from `stubbed` may not have - been reached (an untaken branch, or a block answered by `--mock`), so first confirm its block ran - in the trace: a reached write is absent only when its block was `--allow`ed and sent it for real, - so a reached, unallowed write missing from `stubbed` is labelled `read`. `stubbed` keeps at most + live data; a read listed there is labelled `write`, unless its entry has `dependsOnStub: true` + (it would have sent a stubbed write's placeholder id, so give it a real id). A write missing + from `stubbed` may not have been reached (an untaken branch, or a block answered by `--mock`), + so first confirm its block ran in the trace: a reached write is absent only when its block was + `--allow`ed and sent it for real, so a reached, unallowed write missing from `stubbed` is + labelled `read`. `stubbed` keeps at most 50 entries and counts the rest in `sideEffects.omitted.stubbed`, so a write past the cap is counted, not missing: test one tool per run, or few enough to fit. An entry's `request` is `null` when the run cannot vouch that no secret remains in it, or cannot build it once secrets are diff --git a/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx b/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx index ebfefe57d91..2f69fe4bd21 100644 --- a/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx +++ b/apps/docs/content/docs/api-reference/build-and-run-workflows.mdx @@ -166,7 +166,7 @@ Apply without `dryRun`. Set `atomic: true` in the body to write nothing when any ## 7. Test the draft [#test-run] -Run the saved draft with `run.source: "manual"` and `run.dry: true`. A dry run sends no writes: every tool call not declared `read` (table writes, sends, HTTP calls, custom and MCP tools) returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written before the table coerces it, secrets masked, so a block reading `row.data` gets the values it wrote), and the result lists it under `sideEffects.stubbed` with the request it would have sent, credentials, secrets and password fields redacted. Check those payloads instead of cleaning up test data. Reads and model calls run for real, child workflows run dry too, and custom blocks are answered whole. Code runs for real (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) and is listed under `sideEffects.unchecked`. A dry run keeps nothing beyond its own log, which is under the `test` trigger: Agents read their memory but write none, and it raises no workspace event and does not count as a run of the workflow. Human in the loop and Wait blocks are answered whole, so a dry run never pauses, and a test run is never resumed. A failed dry run still returns its `sideEffects`, and only another dry run can use it, or a workflow test's run, as `run.entry.sourceRunId`. Allowing an Agent with `run.allowBlocks` sends only its own tool calls, not a workflow or custom block it calls. A mock is data: it cannot replace a locked block or set a field the run's execution, trace or billing reads (such as `cost`, `tokens`, `model` or a field starting with `_`), and the run records only which blocks were mocked, so a rerun passes `run.mocks` again, while the run's log shows a mocked block's output like any other block's. `run.mocks` names at most 50 blocks. Manual runs are synchronous or streamed, never `async`; a dry run is synchronous only. +Run the saved draft with `run.source: "manual"` and `run.dry: true`. A dry run sends no writes: every tool call not declared `read` (table writes, sends, HTTP calls, custom and MCP tools) returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written before the table coerces it, secrets masked, so a block reading `row.data` gets the values it wrote), and the result lists it under `sideEffects.stubbed` with the request it would have sent, credentials, secrets and password fields redacted. Check those payloads instead of cleaning up test data. Placeholder ids, and values the request cannot determine, are distinctive: strings shaped `dry_run__` and numbers above 900000000. A read that would send one the run returned (such as a placeholder row's id or issue number, or free text quoting one, so a create-then-read chain does not fail) is answered with a placeholder too and listed there with `dependsOnStub: true`. Every MCP call is stubbed, even one its server declares read-only, since Sim cannot verify that claim: its entry carries `readOnlyHint: true`, and `run.allowBlocks` sends it. Other reads and model calls run for real, child workflows run dry too, and custom blocks are answered whole. Code runs for real (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) and is listed under `sideEffects.unchecked`. A dry run keeps nothing beyond its own log, which is under the `test` trigger: Agents read their memory but write none, and it raises no workspace event and does not count as a run of the workflow. Human in the loop and Wait blocks are answered whole, so a dry run never pauses, and a test run is never resumed. A failed dry run still returns its `sideEffects`, and only another dry run can use it, or a workflow test's run, as `run.entry.sourceRunId`. Allowing an Agent with `run.allowBlocks` sends only its own tool calls, not a workflow or custom block it calls. A mock is data: it cannot replace a locked block or set a field the run's execution, trace or billing reads (such as `cost`, `tokens`, `model` or a field starting with `_`), and the run records only which blocks were mocked, so a rerun passes `run.mocks` again, while the run's log shows a mocked block's output like any other block's. `run.mocks` names at most 50 blocks. Manual runs are synchronous or streamed, never `async`; a dry run is synchronous only. diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 33b58e17ebd..d5796cf7729 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8535,7 +8535,7 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --deployment-version <n> runs that deployed version instead, as a pin for comparing or reproducing (it needs workspace write access, through a full-access API key or an OAuth token with api:write); the child workflows it calls still run their own active deployment. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls other than GET/HEAD/OPTIONS, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs: its GET/HEAD/OPTIONS fetches are sent (an API that writes on a GET is not stubbed), and any other fetch, or one with a method-override header, gets an empty 200 and is listed in sideEffects.stubbed. Code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked, since its network cannot be seen. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes (a Function's fetches included) for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls other than GET/HEAD/OPTIONS, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Placeholder ids are distinctive (dry_run_row_1, numbers above 900000000); a read (a GET included, a Function's fetch too) that would send one (a row a stubbed insert never made, or text quoting one) is not sent either and is listed there with dependsOnStub. MCP calls are stubbed even when the server declares the tool read-only, which Sim cannot verify: such an entry has readOnlyHint, and --allow <block> sends it. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs: its other GET/HEAD/OPTIONS fetches are sent (an API that writes on a GET is not stubbed), and any other fetch, or one with a method-override header, gets an empty 200 and is listed in sideEffects.stubbed. Code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked, since its network cannot be seen. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes (a Function's fetches included) for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index c038e50e73b..139a8ec7169 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -852,7 +852,7 @@ sim workflows run [options] Without --manual (or a flag that implies it) this runs the active deployment; a workflow never deployed has none. --deployment-version <n> runs that deployed version instead, as a pin for comparing or reproducing (it needs workspace write access, through a full-access API key or an OAuth token with api:write); the child workflows it calls still run their own active deployment. --manual runs the saved draft, as the source loop leaves it. ---dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls other than GET/HEAD/OPTIONS, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs: its GET/HEAD/OPTIONS fetches are sent (an API that writes on a GET is not stubbed), and any other fetch, or one with a method-override header, gets an empty 200 and is listed in sideEffects.stubbed. Code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked, since its network cannot be seen. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes (a Function's fetches included) for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. +--dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls other than GET/HEAD/OPTIONS, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check those payloads. Placeholder ids are distinctive (dry_run_row_1, numbers above 900000000); a read (a GET included, a Function's fetch too) that would send one (a row a stubbed insert never made, or text quoting one) is not sent either and is listed there with dependsOnStub. MCP calls are stubbed even when the server declares the tool read-only, which Sim cannot verify: such an entry has readOnlyHint, and --allow <block> sends it. Code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes) runs: its other GET/HEAD/OPTIONS fetches are sent (an API that writes on a GET is not stubbed), and any other fetch, or one with a method-override header, gets an empty 200 and is listed in sideEffects.stubbed. Code in a remote sandbox (shell, Python, imports) is listed in sideEffects.unchecked, since its network cannot be seen. Child workflows run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read memory but write none, and the run raises no workspace event. --allow <block> sends that block's writes (a Function's fetches included) for real (use a test resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it calls. --mock <block>=<json> answers a block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model or a field starting with _). A dry run is the --source-run only of another dry run, and is never resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: branch on status, or on the exit code. With --follow it is the stream's final frame instead: success and output. diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 67c0d390361..8100ee5f1ca 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -17279,12 +17279,53 @@ "description": "Placeholder field." }, "description": "Placeholder output the block or tool call returned to the run instead." + }, + "mcp": { + "anyOf": [ + { + "type": "object", + "properties": { + "server": { + "type": "string", + "description": "MCP server or managed connection id." + }, + "tool": { + "type": "string", + "description": "MCP tool name." + } + }, + "required": ["server", "tool"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "The MCP server and tool an MCP block's call named; null for any other call." + }, + "dependsOnStub": { + "type": "boolean", + "description": "True for a read that was not sent because what it would send holds a placeholder the run returned earlier (a `dry_run__` string or a number above 900000000, such as a placeholder row id), so it depends on a write that was never sent." + }, + "readOnlyHint": { + "type": "boolean", + "description": "True for an MCP call whose server declares the tool read-only and not destructive (`readOnlyHint`, not `destructiveHint`). That is the server's claim, which Sim cannot verify, so the call was not sent; name its block in `run.allowBlocks` to send it." } }, - "required": ["workflowId", "blockId", "block", "tool", "request", "returned"], + "required": [ + "workflowId", + "blockId", + "block", + "tool", + "request", + "returned", + "mcp", + "dependsOnStub", + "readOnlyHint" + ], "additionalProperties": false }, - "description": "Writes that were not sent, in the order the run reached them." + "description": "Calls that were not sent, in the order the run reached them: writes, and reads that depend on one (`dependsOnStub`)." }, "allowed": { "type": "array", @@ -17327,12 +17368,35 @@ } ], "description": "Tool sent; null when the whole block ran." + }, + "mcp": { + "anyOf": [ + { + "type": "object", + "properties": { + "server": { + "type": "string", + "description": "MCP server or managed connection id." + }, + "tool": { + "type": "string", + "description": "MCP tool name." + } + }, + "required": ["server", "tool"], + "additionalProperties": false + }, + { + "type": "null" + } + ], + "description": "The MCP server and tool an MCP block's call named; null for any other call." } }, - "required": ["workflowId", "blockId", "block", "tool"], + "required": ["workflowId", "blockId", "block", "tool", "mcp"], "additionalProperties": false }, - "description": "Writes sent for real because `run.allowBlocks` named their block, once per block and tool." + "description": "Writes sent for real because `run.allowBlocks` named their block, once per block and tool (an MCP block's per MCP tool)." }, "unchecked": { "type": "array", @@ -17761,7 +17825,7 @@ "minLength": 1 }, "dry": { - "description": "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls other than a GET, HEAD or OPTIONS without a method-override header, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written, secrets masked) and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes): JavaScript without imports sends its GET, HEAD and OPTIONS `fetch` calls (an API that writes on a GET is not stubbed), while any other request, or one carrying a method-override header, gets an empty 200 response (header `x-sim-dry-run: stubbed`) and is listed in `sideEffects.stubbed` as tool `function_execute`; code in a remote sandbox (shell, Python, JavaScript with imports, a selected sandbox or files) has network the run cannot see and is listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`.", + "description": "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls other than a GET, HEAD or OPTIONS without a method-override header, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written, secrets masked) and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Placeholder ids and values the request cannot determine are distinctive: strings shaped `dry_run__` and numbers above 900000000. A read (a `read` tool, an HTTP GET, HEAD or OPTIONS, or code's GET, HEAD or OPTIONS `fetch`) that would send one the run returned (such as a placeholder row's id or issue number in a URL, or free text quoting one) is not sent either: it gets a placeholder (code's `fetch` an empty 200) and is listed there with `dependsOnStub`. Every MCP call is stubbed, even one its server declares read-only, a claim Sim cannot verify: its entry carries `readOnlyHint`, and `allowBlocks` sends it. Other reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes): JavaScript without imports sends its other GET, HEAD and OPTIONS `fetch` calls (an API that writes on a GET is not stubbed), while any other request, or one carrying a method-override header, gets an empty 200 response (header `x-sim-dry-run: stubbed`) and is listed in `sideEffects.stubbed` as tool `function_execute`; code in a remote sandbox (shell, Python, JavaScript with imports, a selected sandbox or files) has network the run cannot see and is listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`.", "type": "boolean" }, "allowBlocks": { diff --git a/apps/sim/app/api/v2/mcp-servers/[mcpServerId]/tools/route.ts b/apps/sim/app/api/v2/mcp-servers/[mcpServerId]/tools/route.ts index 4265ea60b5a..f54bb539639 100644 --- a/apps/sim/app/api/v2/mcp-servers/[mcpServerId]/tools/route.ts +++ b/apps/sim/app/api/v2/mcp-servers/[mcpServerId]/tools/route.ts @@ -30,5 +30,16 @@ export const GET = defineV2JsonRoute({ refresh: query.refresh, }), useCase: discoverMcpServerToolsUseCase, - present: ({ tools }) => ({ data: tools, nextCursor: null }), + /** Only the fields the contract publishes: a discovered tool also carries hints Sim reads. */ + present: ({ tools }) => ({ + data: tools.map(({ name, description, inputSchema, outputSchema, serverId, serverName }) => ({ + name, + description, + inputSchema, + outputSchema, + serverId, + serverName, + })), + nextCursor: null, + }), }) diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index c4cd785cec8..7a3bf84a8b1 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -342,9 +342,33 @@ export interface SideEffectBlockSite extends SideEffectSite { blockType: string } -/** A write tool call the run answers instead of sending, with the request it would have sent. */ -export interface StubbedToolCall extends SideEffectSite { +/** The MCP server and tool an MCP block's operation names. */ +export interface McpCallTarget { + server: string + tool: string +} + +/** A tool call made at a block of one executing workflow. */ +export interface ToolCallSite extends SideEffectSite { toolId: string + /** The MCP server and tool, for the MCP block's `mcp_run_operation`; null for any other tool. */ + mcp: McpCallTarget | null +} + +/** A tool call the run answers instead of sending, with the request it would have sent. */ +export interface StubbedToolCall extends ToolCallSite { + /** + * A read held back because what it sends holds a placeholder + * ({@link SideEffectPolicy.sendsPlaceholder}). + */ + dependsOnStub: boolean + /** An MCP call whose server declares the tool read-only and not destructive, unverified. */ + readOnlyHint: boolean + /** + * JSON Schemas of outputs the call learned beside the tool's declared ones, sampled into its + * placeholder too: an MCP tool's discovered `outputSchema`, as `structuredContent`. + */ + discoveredOutputs?: Record /** The request with credentials, secrets and PII redacted; null when that cannot be vouched for. */ request: Record | null /** @@ -369,6 +393,12 @@ interface CodeNetworkRequest { method: string /** The names of the headers it carries, never their values. */ headerNames: string[] + /** + * The URL and body it sends, unredacted: only searched for the run's placeholders (a read that + * would send one is stubbed), never recorded. + */ + url: string + body: string | undefined /** * What the request would send (method, capped origin and path with query parameter names, header * names, a capped body; never a header value), redacted like a stubbed write's request; null @@ -400,18 +430,24 @@ export interface CodeNetworkPolicy { */ export interface SideEffectPolicy { /** - * Whether this write tool call is sent or answered with {@link stubWrite}. Records an allowed + * Whether this write tool call is sent or answered with {@link stubCall}. Records an allowed * block's sent write. */ - decideWrite(call: SideEffectSite & { toolId: string }): 'send' | 'stub' + decideWrite(call: ToolCallSite): 'send' | 'stub' /** * The network policy of code about to run at `site`: code run through `function_execute` (a * Function block's, a Condition's expressions, or code an Agent's model wrote), or a While or Do * While loop's condition. */ codeNetwork(site: SideEffectSite): CodeNetworkPolicy - /** Records a write that was not sent and returns the placeholder output answering it. */ - stubWrite(call: StubbedToolCall): Record + /** Records a call that was not sent and returns the placeholder output answering it. */ + stubCall(call: StubbedToolCall): Record + /** + * Whether `sent`, what a read would send, holds a value one of the run's placeholders returned + * (a placeholder row's id): such a read depends on a write that was never sent, so it is answered + * with {@link stubCall} instead. + */ + sendsPlaceholder(sent: unknown): boolean /** Whether this block is answered with {@link answerBlock} instead of running its handler. */ answersBlock(block: SideEffectBlockSite): boolean /** The output answering a block that does not run: its mock, or a recorded placeholder. */ diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 3bcca7f573f..5e5a0c178fe 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -1709,7 +1709,7 @@ export const v2WorkflowRunSelectionSchema = z.discriminatedUnion('source', [ .boolean() .optional() .describe( - "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls other than a GET, HEAD or OPTIONS without a method-override header, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written, secrets masked) and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes): JavaScript without imports sends its GET, HEAD and OPTIONS `fetch` calls (an API that writes on a GET is not stubbed), while any other request, or one carrying a method-override header, gets an empty 200 response (header `x-sim-dry-run: stubbed`) and is listed in `sideEffects.stubbed` as tool `function_execute`; code in a remote sandbox (shell, Python, JavaScript with imports, a selected sandbox or files) has network the run cannot see and is listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`." + "Dry run: every tool call not declared `read` (sends, table writes, HTTP calls other than a GET, HEAD or OPTIONS without a method-override header, custom and MCP tools) is not sent; it returns a correctly shaped placeholder (a table row insert, upsert or update echoes the data it would have written, secrets masked) and is listed in `sideEffects.stubbed` with the request it would have sent, credentials, secrets and (when the workspace redacts it) PII redacted. Placeholder ids and values the request cannot determine are distinctive: strings shaped `dry_run__` and numbers above 900000000. A read (a `read` tool, an HTTP GET, HEAD or OPTIONS, or code's GET, HEAD or OPTIONS `fetch`) that would send one the run returned (such as a placeholder row's id or issue number in a URL, or free text quoting one) is not sent either: it gets a placeholder (code's `fetch` an empty 200) and is listed there with `dependsOnStub`. Every MCP call is stubbed, even one its server declares read-only, a claim Sim cannot verify: its entry carries `readOnlyHint`, and `allowBlocks` sends it. Other reads, model calls and credential resolution run for real, and so does code (a Function block's, a Condition's expressions, a While or Do While loop's condition, or code an Agent's model writes): JavaScript without imports sends its other GET, HEAD and OPTIONS `fetch` calls (an API that writes on a GET is not stubbed), while any other request, or one carrying a method-override header, gets an empty 200 response (header `x-sim-dry-run: stubbed`) and is listed in `sideEffects.stubbed` as tool `function_execute`; code in a remote sandbox (shell, Python, JavaScript with imports, a selected sandbox or files) has network the run cannot see and is listed in `sideEffects.unchecked`. Child workflows inherit it. Custom, Mothership, Pi, Human in the loop and Wait blocks are answered whole with placeholders. Agents read their memory but write none, and nothing else beyond the run's own log is kept: it raises no workspace event and does not count as a run of the workflow. Logged under the `test` trigger. Synchronous only: cannot be combined with `stream` or `waitTimeoutSeconds`." ), allowBlocks: z .array(z.string().min(1, 'run.allowBlocks entries cannot be empty')) @@ -1993,6 +1993,14 @@ const sideEffectBlockFields = { block: z.string().nullable().describe('Block display name; null when the call named no block.'), } +const mcpCallTargetSchema = z + .object({ + server: z.string().describe('MCP server or managed connection id.'), + tool: z.string().describe('MCP tool name.'), + }) + .nullable() + .describe("The MCP server and tool an MCP block's call named; null for any other call.") + const v2RunSideEffectsSchema = z .object({ stubbed: z @@ -2014,18 +2022,32 @@ const v2RunSideEffectsSchema = z returned: z .record(z.string(), z.unknown().describe('Placeholder field.')) .describe('Placeholder output the block or tool call returned to the run instead.'), + mcp: mcpCallTargetSchema, + dependsOnStub: z + .boolean() + .describe( + 'True for a read that was not sent because what it would send holds a placeholder the run returned earlier (a `dry_run__` string or a number above 900000000, such as a placeholder row id), so it depends on a write that was never sent.' + ), + readOnlyHint: z + .boolean() + .describe( + "True for an MCP call whose server declares the tool read-only and not destructive (`readOnlyHint`, not `destructiveHint`). That is the server's claim, which Sim cannot verify, so the call was not sent; name its block in `run.allowBlocks` to send it." + ), }) ) - .describe('Writes that were not sent, in the order the run reached them.'), + .describe( + 'Calls that were not sent, in the order the run reached them: writes, and reads that depend on one (`dependsOnStub`).' + ), allowed: z .array( z.object({ ...sideEffectBlockFields, tool: z.string().nullable().describe('Tool sent; null when the whole block ran.'), + mcp: mcpCallTargetSchema, }) ) .describe( - 'Writes sent for real because `run.allowBlocks` named their block, once per block and tool.' + "Writes sent for real because `run.allowBlocks` named their block, once per block and tool (an MCP block's per MCP tool)." ), unchecked: z .array( diff --git a/apps/sim/lib/internal/mcp/execute-tool.ts b/apps/sim/lib/internal/mcp/execute-tool.ts index 73be8b83101..306d0a6a418 100644 --- a/apps/sim/lib/internal/mcp/execute-tool.ts +++ b/apps/sim/lib/internal/mcp/execute-tool.ts @@ -196,12 +196,15 @@ export const executeMcpTool: InternalToolOperationHandler = async (request) => { result = await executeManagedMcpToolUseCase.execute({ principal, input }) } request.signal?.throwIfAborted() + /** A checked call's output is what the check learned, for the executor's placeholder. */ const body = - request.toolId === 'mcp_run_operation' || 'checked' in result - ? result - : result.success - ? { success: true, data: { success: true, output: result.output } } - : { success: false, error: result.error } + 'checked' in result + ? { success: true, output: result } + : request.toolId === 'mcp_run_operation' + ? result + : result.success + ? { success: true, data: { success: true, output: result.output } } + : { success: false, error: result.error } return createResponse( body, result.success ? 200 : 400, diff --git a/apps/sim/lib/mcp/application/execute-managed-tool.test.ts b/apps/sim/lib/mcp/application/execute-managed-tool.test.ts index 550cabb9777..34df6a0bb32 100644 --- a/apps/sim/lib/mcp/application/execute-managed-tool.test.ts +++ b/apps/sim/lib/mcp/application/execute-managed-tool.test.ts @@ -326,7 +326,7 @@ describe('executeManagedMcpToolUseCase', () => { await expect( executeManagedMcpToolUseCase.execute({ principal, input: { ...input, checkOnly: true } }) - ).resolves.toEqual({ success: true, checked: true }) + ).resolves.toMatchObject({ success: true, checked: true }) expect(mocks.executeTool).not.toHaveBeenCalled() expect(mocks.saveToolSnapshot).not.toHaveBeenCalled() @@ -341,4 +341,41 @@ describe('executeManagedMcpToolUseCase', () => { expect(mocks.saveToolSnapshot).toHaveBeenCalledOnce() expect(auditWrites.some((write) => write.mock.calls.length > 0)).toBe(true) }) + + it('reports a checked call’s discovered hints, never sending a destructive or read-only one', async () => { + const outputSchema = { type: 'object', properties: { total: { type: 'number' } } } + const input = { + workspaceId: context.workspaceId, + credentialId: context.credentialId, + toolName: 'search_transcripts', + checkOnly: true, + } + const discovered = (annotations: Record) => [ + { + name: 'search_transcripts', + inputSchema: { type: 'object', properties: {} }, + outputSchema, + annotations, + }, + ] + + mocks.discoverTools.mockResolvedValue(discovered({ readOnlyHint: true })) + await expect(executeManagedMcpToolUseCase.execute({ principal, input })).resolves.toEqual({ + success: true, + checked: true, + tool: { name: 'search_transcripts', outputSchema, readOnlyHint: true }, + }) + mocks.discoverTools.mockResolvedValue(discovered({ readOnlyHint: true, destructiveHint: true })) + const savedWorkflow = await mocks.loadWorkflow() + queueTableRows(schemaMock.workflowDeploymentVersion, [{ state: savedWorkflow }]) + queueTableRows(schemaMock.workflowDeploymentVersion, [{ state: savedWorkflow }]) + await expect(executeManagedMcpToolUseCase.execute({ principal, input })).resolves.toMatchObject( + { + tool: { readOnlyHint: false }, + } + ) + + expect(mocks.executeTool).not.toHaveBeenCalled() + for (const write of auditWrites) expect(write).not.toHaveBeenCalled() + }) }) diff --git a/apps/sim/lib/mcp/application/execute-managed-tool.ts b/apps/sim/lib/mcp/application/execute-managed-tool.ts index fca62c5bedf..6e356d878fe 100644 --- a/apps/sim/lib/mcp/application/execute-managed-tool.ts +++ b/apps/sim/lib/mcp/application/execute-managed-tool.ts @@ -12,6 +12,7 @@ import { } from '@/lib/credentials/managed-mcp' import { SIM_VIA_HEADER, serializeCallChain } from '@/lib/execution/call-chain' import { + checkedMcpToolCall, coerceToolArguments, type ExecuteMcpToolResult, transformToolResult, @@ -119,6 +120,8 @@ export const executeManagedMcpToolUseCase = defineAuthorizedWorkspaceUseCase({ name: discovered.name, ...(discovered.description ? { description: discovered.description } : {}), inputSchema: requireToolSchema(discovered.inputSchema), + ...(discovered.outputSchema ? { outputSchema: discovered.outputSchema } : {}), + ...(discovered.annotations ? { annotations: discovered.annotations } : {}), serverId: runtime.credentialId, serverName: runtime.mcpServerName, } @@ -156,7 +159,7 @@ export const executeManagedMcpToolUseCase = defineAuthorizedWorkspaceUseCase({ context, credentialOperations.useManagedMcp.resourcePolicy ) - if (input.checkOnly) return { success: true, checked: true } + if (input.checkOnly) return checkedMcpToolCall(tool) const providerResult = await mcpService.executeManagedMcpTool({ connectionId: runtime.credentialId, serverId: runtime.mcpServerId, @@ -170,8 +173,8 @@ export const executeManagedMcpToolUseCase = defineAuthorizedWorkspaceUseCase({ input.signal?.throwIfAborted() return transformToolResult(providerResult) }, - projectAudit: ({ input, context }) => - input.checkOnly + projectAudit: ({ input, context, result }) => + 'checked' in result ? [] : { action: AuditAction.CREDENTIAL_ACCESSED, diff --git a/apps/sim/lib/mcp/application/execute-tool.test.ts b/apps/sim/lib/mcp/application/execute-tool.test.ts index 82baea986da..245e5c4f932 100644 --- a/apps/sim/lib/mcp/application/execute-tool.test.ts +++ b/apps/sim/lib/mcp/application/execute-tool.test.ts @@ -307,7 +307,12 @@ describe('executeMcpToolUseCase', () => { expect(mocks.executeTool).toHaveBeenCalledOnce() }) - it('checks a held-back call against the server’s tools without sending it', async () => { + it('checks a held-back call against the server’s tools without sending it, reporting its hints', async () => { + const outputSchema = { type: 'object' as const, properties: { total: { type: 'number' } } } + const [lookup] = await mocks.discoverServerTools() + mocks.discoverServerTools.mockResolvedValue([ + { ...lookup, outputSchema, annotations: { readOnlyHint: true } }, + ]) const input = { workspaceId: WORKSPACE.workspaceId, serverId: SERVER.id, @@ -323,9 +328,13 @@ describe('executeMcpToolUseCase', () => { principal: PRINCIPAL, input: { ...input, arguments: { count: 1 } }, }) - ).resolves.toEqual({ success: true, checked: true }) + ).resolves.toEqual({ + success: true, + checked: true, + tool: { name: 'lookup', outputSchema, readOnlyHint: true }, + }) - expect(mocks.discoverServerTools).toHaveBeenCalledTimes(2) + expect(mocks.discoverServerTools).toHaveBeenCalledTimes(3) expect(mocks.executeTool).not.toHaveBeenCalled() }) diff --git a/apps/sim/lib/mcp/application/execute-tool.ts b/apps/sim/lib/mcp/application/execute-tool.ts index cb318632e21..3156695809b 100644 --- a/apps/sim/lib/mcp/application/execute-tool.ts +++ b/apps/sim/lib/mcp/application/execute-tool.ts @@ -16,7 +16,7 @@ import { import { mcpServerOperations } from '@/lib/mcp/application/operations' import { mcpService } from '@/lib/mcp/service' import { compileMcpToolSchema } from '@/lib/mcp/tool-schema' -import type { McpTool, McpToolCall, McpToolResult } from '@/lib/mcp/types' +import type { McpTool, McpToolCall, McpToolResult, McpToolSchema } from '@/lib/mcp/types' import { assertPermissionsAllowed, McpToolsNotAllowedError, @@ -45,11 +45,34 @@ export interface ExecuteMcpToolInput { checkOnly?: boolean } +/** What a `checkOnly` call learned of the tool it would have called. */ +interface McpCheckedTool { + name: string + /** The `structuredContent` shape the tool declares, absent when it declares none. */ + outputSchema?: McpToolSchema + /** The server declares the tool read-only and not destructive: a claim Sim cannot verify. */ + readOnlyHint: boolean +} + export type ExecuteMcpToolResult = | { success: true; output: McpToolResult } | { success: false; error: string } - /** A `checkOnly` call that would have been sent. */ - | { success: true; checked: true } + /** A `checkOnly` call that would have been sent, and what it learned of the tool. */ + | { success: true; checked: true; tool: McpCheckedTool } + +/** The result of a `checkOnly` call to `tool` that checked out. */ +export function checkedMcpToolCall(tool: McpTool): ExecuteMcpToolResult { + return { + success: true, + checked: true, + tool: { + name: tool.name, + ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}), + readOnlyHint: + tool.annotations?.readOnlyHint === true && tool.annotations.destructiveHint !== true, + }, + } +} function hasType(value: unknown): value is SchemaProperty { return typeof value === 'object' && value !== null && 'type' in value @@ -197,7 +220,7 @@ export const executeMcpToolUseCase = defineAuthorizedWorkspaceUseCase({ ), input.toolName ) - if (input.checkOnly) return { success: true, checked: true } + if (input.checkOnly) return checkedMcpToolCall(tool) const providerResult = await mcpService.executeTool( userId, context.server.id, diff --git a/apps/sim/lib/mcp/client.ts b/apps/sim/lib/mcp/client.ts index f87b1e8952b..b2864dc0a6b 100644 --- a/apps/sim/lib/mcp/client.ts +++ b/apps/sim/lib/mcp/client.ts @@ -10,6 +10,7 @@ import { import { createLogger } from '@sim/logger' import { isPrivateIp } from '@sim/security/ssrf' import { getErrorMessage } from '@sim/utils/errors' +import { isRecordLike } from '@sim/utils/object' import { getMaxExecutionTimeout } from '@/lib/core/execution-limits' import { captureOutboundScopeFallback } from '@/lib/core/network/context.server' import { getMcpSafeErrorDiagnostics } from '@/lib/mcp/error-diagnostics' @@ -31,6 +32,7 @@ import { type McpSecurityPolicy, type McpServerConfig, type McpTool, + type McpToolAnnotations, type McpToolCall, type McpToolResult, type McpToolsChangedCallback, @@ -80,6 +82,17 @@ interface McpToolCallOptions { timeoutMs?: number } +/** A tool's declared `annotations`, only the boolean hints Sim reads; undefined when none. */ +function readMcpToolAnnotations(value: unknown): McpToolAnnotations | undefined { + if (!isRecordLike(value)) return undefined + const annotations: McpToolAnnotations = {} + if (typeof value.readOnlyHint === 'boolean') annotations.readOnlyHint = value.readOnlyHint + if (typeof value.destructiveHint === 'boolean') { + annotations.destructiveHint = value.destructiveHint + } + return Object.keys(annotations).length > 0 ? annotations : undefined +} + export class McpClient { private client: Client private transport: StreamableHTTPClientTransport @@ -388,11 +401,13 @@ export class McpClient { break } const outputSchema = readMcpToolOutputSchema(tool.outputSchema) + const annotations = readMcpToolAnnotations(tool.annotations) tools.push({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema as McpTool['inputSchema'], ...(outputSchema ? { outputSchema } : {}), + ...(annotations ? { annotations } : {}), serverId: this.config.id, serverName: this.config.name, }) diff --git a/apps/sim/lib/mcp/types.ts b/apps/sim/lib/mcp/types.ts index 8d42c71a77a..8e367c82835 100644 --- a/apps/sim/lib/mcp/types.ts +++ b/apps/sim/lib/mcp/types.ts @@ -88,11 +88,23 @@ export interface McpToolSchema { [key: string]: unknown } +/** + * The behaviour hints a server declares for a tool, only those Sim reads and only as booleans. + * Hints are the server's claim, which Sim cannot verify, so a dry run reports them and never acts + * on them. + */ +export interface McpToolAnnotations { + readOnlyHint?: boolean + destructiveHint?: boolean +} + /** SDK `Tool` plus the server context Sim tracks. */ export interface McpTool extends Pick { inputSchema: McpToolSchema /** The `structuredContent` shape the tool declares, absent when it declares none. */ outputSchema?: McpToolSchema + /** Absent when the tool declares no hint Sim reads. */ + annotations?: McpToolAnnotations canonicalServerId?: string serverId: string serverName: string diff --git a/apps/sim/lib/mothership/tools/server/tests.ts b/apps/sim/lib/mothership/tools/server/tests.ts index 79e3f4aadbe..54ce4468fa7 100644 --- a/apps/sim/lib/mothership/tools/server/tests.ts +++ b/apps/sim/lib/mothership/tools/server/tests.ts @@ -47,19 +47,22 @@ function failures(report: StoredTestReport | null) { } /** - * Each write a run stubbed because no mock answered it, once, as `block → tool` (a block answered - * whole by its name alone): a test that passes may still lean on a placeholder. The list is partial - * when `omittedCalls` (stubbed calls a run's full list left out) or `omittedRuns` (runs past the - * per-file cap, whose writes went unrecorded) is nonzero, and unknown (null) for a run with no - * report, such as one that errored before the sandbox returned. + * Each call a run stubbed because no mock answered it, once, as `block → tool` (an MCP block's by + * the MCP tool it named, a block answered whole by its name alone, and a read marked when it was + * stubbed for sending an earlier stub's placeholder): a test that passes may still lean on a + * placeholder. The list is partial when `omittedCalls` (stubbed calls a run's full list left out) + * or `omittedRuns` (runs past the per-file cap, whose writes went unrecorded) is nonzero, and + * unknown (null) for a run with no report, such as one that errored before the sandbox returned. */ function unmockedWrites(report: StoredTestReport | null) { if (!report) return null const executions = Object.values(report.sideEffects?.executions ?? {}) const sites = executions.flatMap((execution) => - execution.stubbed.map(({ block, blockId, tool }) => { + execution.stubbed.map(({ block, blockId, tool, mcp, dependsOnStub }) => { const site = block ?? blockId ?? 'unnamed block' - return tool ? `${site} → ${tool}` : site + const called = mcp ? mcp.tool : tool + const label = called ? `${site} → ${called}` : site + return dependsOnStub ? `${label} (read of a placeholder)` : label }) ) return { diff --git a/apps/sim/lib/workflow-tests/protocol.ts b/apps/sim/lib/workflow-tests/protocol.ts index de0ead44b86..2485d3f0502 100644 --- a/apps/sim/lib/workflow-tests/protocol.ts +++ b/apps/sim/lib/workflow-tests/protocol.ts @@ -130,13 +130,22 @@ export const testReportSchema = z.object({ /** What one workflow run of a test did with the writes it reached, without their payloads. */ const testRunSideEffectsSchema = z.object({ - /** Writes no mock answered, stubbed with a placeholder; `tool` is null for a block answered whole. */ + /** + * Calls no mock answered, stubbed with a placeholder: writes, and reads that would have sent a + * placeholder (`dependsOnStub`). `tool` is null for a block answered whole. + */ stubbed: z.array( z.object({ workflowId: z.string(), blockId: z.string().nullable(), block: z.string().nullable(), tool: z.string().nullable(), + /** The MCP server and tool an MCP block's call named; null for any other call. */ + mcp: z.object({ server: z.string(), tool: z.string() }).nullable(), + /** A read that would have sent a placeholder an earlier stub returned. */ + dependsOnStub: z.boolean(), + /** An MCP call whose server declares the tool read-only, unverified, so it was not sent. */ + readOnlyHint: z.boolean(), /** Calls folded into this entry. */ count: z.number().int().positive(), }) diff --git a/apps/sim/lib/workflow-tests/session.ts b/apps/sim/lib/workflow-tests/session.ts index 47ac25af5b1..3f630d85f15 100644 --- a/apps/sim/lib/workflow-tests/session.ts +++ b/apps/sim/lib/workflow-tests/session.ts @@ -75,12 +75,17 @@ function tally(entries: readonly T[]) { /** A run's side effects as a report keeps them: who did what and how often, never a payload. */ function compactSideEffects(summary: SideEffectsSummary): TestRunSideEffects { const stubbed = tally( - summary.stubbed.map(({ workflowId, blockId, block, tool }) => ({ - workflowId, - blockId, - block, - tool, - })) + summary.stubbed.map( + ({ workflowId, blockId, block, tool, mcp, dependsOnStub, readOnlyHint }) => ({ + workflowId, + blockId, + block, + tool, + mcp, + dependsOnStub, + readOnlyHint, + }) + ) ) const unchecked = tally(summary.unchecked.map(({ block, reason }) => ({ block, reason }))) return { diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index df66777d5fb..184c6990b00 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -17,6 +17,9 @@ */ import { createServer, type Server } from 'node:http' import type { AddressInfo } from 'node:net' +import { Server as McpServer } from '@modelcontextprotocol/sdk/server/index.js' +import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js' +import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js' import { db } from '@sim/db' import { agentMemoryTurn, @@ -531,7 +534,7 @@ describe('a dry run', () => { score: 82, email: 'a@b.co', note: 'key={{DRY_SECRET}}', - notified: 42, + notified: 900_000_001, }) expect(JSON.stringify(result)).not.toContain(SECRET) const [save, sent] = result.sideEffects?.stubbed ?? [] @@ -551,11 +554,11 @@ describe('a dry run', () => { createdAt: '1970-01-01T00:00:00.000Z', updatedAt: '1970-01-01T00:00:00.000Z', }, - operation: 'mock_operation', + operation: 'dry_run_operation_1', ignoredColumns: [], - message: 'mock_message', + message: 'dry_run_message_1', }) - expect(sent).toMatchObject({ tool: 'http_request', returned: { status: 42 } }) + expect(sent).toMatchObject({ tool: 'http_request', returned: { status: 900_000_001 } }) }) it('masks a run secret wherever it appears, though a secret-named column holds part of it', async () => { @@ -644,7 +647,7 @@ describe('a dry run', () => { success: true, row: { ...placeholderRow('dry_run_row_1', { email: 'a@b.co' }, 0), executions: {} }, ignoredColumns: [], - message: 'mock_message', + message: 'dry_run_message_1', }, table_batch_insert_rows: { success: true, @@ -654,21 +657,21 @@ describe('a dry run', () => { ], insertedCount: 2, ignoredColumns: [], - message: 'mock_message', + message: 'dry_run_message_1', }, table_update_row: { success: true, row: placeholderRow('row_named', { score: 7 }, 0), ignoredColumns: [], - message: 'mock_message', + message: 'dry_run_message_1', }, file_write: { - id: 'mock_id', + id: 'dry_run_id_1', name: 'report.txt', size: 6, - url: 'mock_url', - version: 42, - revision: 'mock_revision', + url: 'dry_run_url_1', + version: 900_000_002, + revision: 'dry_run_revision_1', }, }) }) @@ -696,10 +699,10 @@ describe('a dry run', () => { expect(batch.request).toMatchObject({ rows: { email: 'a@b.co' } }) expect(batch.returned).toEqual({ success: true, - rows: [{ id: 'item_1', name: 'Sample Item', value: 'Sample Value' }], - insertedCount: 42, - ignoredColumns: ['mock_ignoredColumns_item'], - message: 'mock_message', + rows: [{ id: 'dry_run_id_1', name: 'dry_run_name_1', value: 'dry_run_value_1' }], + insertedCount: 900_000_001, + ignoredColumns: ['dry_run_ignored_columns_1'], + message: 'dry_run_message_1', }) }) @@ -740,6 +743,7 @@ describe('a dry run', () => { blockId: parent.idOf('save'), block: 'save', tool: 'table_upsert_row', + mcp: null, }, ]) expect(allowed.sideEffects?.stubbed.map((entry) => entry.block)).toEqual([ @@ -980,8 +984,12 @@ describe('a dry run', () => { expect(write).toMatchObject({ tool: 'knowledge_create_document', returned: { - message: 'mock_message', - data: { documentId: 'mock_documentId', documentName: 'notes.txt', type: 'mock_type' }, + message: 'dry_run_message_1', + data: { + documentId: 'dry_run_document_id_1', + documentName: 'notes.txt', + type: 'dry_run_type_1', + }, }, }) const [document] = toArray(toRecord(write.request).documents) @@ -1275,6 +1283,9 @@ describe('a dry run', () => { blockId: fixture.idOf('save'), block: 'save', tool: 'table_upsert_row', + mcp: null, + dependsOnStub: false, + readOnlyHint: false, count: 1, }, ], @@ -1376,6 +1387,300 @@ async function pausedExecutionsOf(workflowId: string) { .where(eq(pausedExecutions.workflowId, workflowId)) } +/** + * Tools of the MCP fixture: a read the server declares read-only, a write it declares nothing for, + * and a call it declares read-only but destructive. Each declares the reply shape it sends. + */ +const MCP_TOOLS = [ + { + name: 'read_file', + inputSchema: { type: 'object', properties: { path: { type: 'string' } } }, + outputSchema: { + type: 'object', + properties: { path: { type: 'string' }, size: { type: 'number' } }, + }, + annotations: { readOnlyHint: true }, + }, + { + name: 'delete_file', + inputSchema: { type: 'object', properties: { path: { type: 'string' } } }, + outputSchema: { type: 'object', properties: { deleted: { type: 'boolean' } } }, + }, + { + name: 'purge_cache', + inputSchema: { type: 'object', properties: { path: { type: 'string' } } }, + annotations: { readOnlyHint: true, destructiveHint: true }, + }, +] + +/** The tool calls the MCP fixture received, in order. */ +const mcpCalls: Array<{ name: string; arguments: unknown }> = [] + +/** A stateless Streamable HTTP MCP server listing {@link MCP_TOOLS}, answering every call. */ +function mcpFixture(): Server { + return createServer(async (request, response) => { + const server = new McpServer( + { name: 'dry-run-fixture', version: '1.0.0' }, + { capabilities: { tools: {} } } + ) + server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: MCP_TOOLS })) + server.setRequestHandler(CallToolRequestSchema, async (call) => { + mcpCalls.push({ name: call.params.name, arguments: call.params.arguments }) + const reply = { path: String(call.params.arguments?.path), size: 12 } + return { content: [{ type: 'text', text: JSON.stringify(reply) }], structuredContent: reply } + }) + const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined }) + response.on('close', () => { + void transport.close() + void server.close() + }) + await server.connect(transport) + await transport.handleRequest(request, response) + }) +} + +/** An MCP block running `tool` of `serverId` with `args`. */ +function mcpCall(name: string, serverId: string, tool: string, args: Record) { + return block(name, 'mcp', { + operation: 'run', + serverSelector: serverId, + serverReference: serverId, + toolSelector: tool, + toolReference: tool, + arguments: args, + }) +} + +describe('a dry run’s reads', () => { + let fixture: Server + let serverId = '' + + beforeAll(async () => { + fixture = mcpFixture() + const port = await new Promise((resolve, reject) => { + fixture.listen(0, '127.0.0.1', () => { + const address = fixture.address() + if (address === null || typeof address === 'string') reject(new Error('No port')) + else resolve(address.port) + }) + }) + serverId = generateId() + await db.insert(mcpServers).values({ + id: serverId, + workspaceId, + createdBy: ownerId, + name: 'Files', + transport: 'streamable-http', + url: `http://127.0.0.1:${port}/mcp`, + connectionStatus: 'connected', + statusConfig: { consecutiveFailures: 0 }, + }) + }) + + afterEach(() => { + mcpCalls.length = 0 + }) + + afterAll(async () => { + await new Promise((resolve) => fixture.close(resolve)) + }) + + it('sends no MCP call, even one its server declares read-only, until its block is allowed', async () => { + const { state, idOf } = graph( + [ + block('start', 'start_trigger'), + mcpCall('read', serverId, 'read_file', { path: '/reports/q3.csv' }), + mcpCall('remove', serverId, 'delete_file', { path: '/reports/q3.csv' }), + mcpCall('purge', serverId, 'purge_cache', { path: '/reports' }), + ], + [ + ['start', 'read'], + ['read', 'remove'], + ['remove', 'purge'], + ] + ) + const workflowId = await saveWorkflow(state) + + const result = await run(workflowId, { + dry: true, + selectedOutputs: ['read.structuredContent', 'remove.structuredContent'], + }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(mcpCalls).toEqual([]) + const stubbed = result.sideEffects?.stubbed ?? [] + expect( + stubbed.map((entry) => [entry.block, entry.mcp, entry.readOnlyHint, entry.dependsOnStub]) + ).toEqual([ + ['read', { server: serverId, tool: 'read_file' }, true, false], + ['remove', { server: serverId, tool: 'delete_file' }, false, false], + ['purge', { server: serverId, tool: 'purge_cache' }, false, false], + ]) + expect(result.blockOutputs?.['read.structuredContent']).toEqual({ + path: 'dry_run_path_1', + size: 900_000_001, + }) + expect(result.blockOutputs?.['remove.structuredContent']).toEqual({ deleted: true }) + + const allowed = await run(workflowId, { + dry: true, + allowBlocks: ['read'], + selectedOutputs: ['read.structuredContent'], + }) + expect(allowed.status, JSON.stringify(allowed.error)).toBe('completed') + expect(mcpCalls).toEqual([{ name: 'read_file', arguments: { path: '/reports/q3.csv' } }]) + expect(allowed.blockOutputs?.['read.structuredContent']).toEqual({ + path: '/reports/q3.csv', + size: 12, + }) + expect(allowed.sideEffects?.allowed).toEqual([ + { + workflowId, + blockId: idOf('read'), + block: 'read', + tool: 'mcp_run_operation', + mcp: { server: serverId, tool: 'read_file' }, + }, + ]) + }) + + it('answers a read that would send a stubbed write’s placeholder id, through a chain of reads', async () => { + const tableId = await createTable() + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + upsertLead('save', tableId, 'a@b.co'), + block('fetch', 'table', { + operation: 'get_row', + tableSelector: tableId, + rowId: '', + }), + block('refetch', 'table', { + operation: 'get_row', + tableSelector: tableId, + rowId: '', + }), + mcpCall('read', serverId, 'read_file', { path: '/rows/file__copy.json' }), + queryLeads('lookup', tableId), + ], + [ + ['start', 'save'], + ['save', 'fetch'], + ['fetch', 'refetch'], + ['refetch', 'read'], + ['read', 'lookup'], + ] + ).state + ) + + const result = await run(workflowId, { dry: true, selectedOutputs: ['lookup.totalCount'] }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(await tableRows(tableId)).toEqual([]) + expect(mcpCalls).toEqual([]) + const stubbed = result.sideEffects?.stubbed ?? [] + expect(stubbed.map((entry) => [entry.block, entry.tool, entry.dependsOnStub])).toEqual([ + ['save', 'table_upsert_row', false], + ['fetch', 'table_get_row', true], + ['refetch', 'table_get_row', true], + ['read', 'mcp_run_operation', true], + ]) + expect(stubbed[1].request).toMatchObject({ rowId: 'dry_run_row_1' }) + expect(result.blockOutputs?.['lookup.totalCount']).toBe(0) + + const live = await run(workflowId, { selectedOutputs: ['refetch.row'] }) + expect(live.status, JSON.stringify(live.error)).toBe('completed') + expect(live.sideEffects).toBeUndefined() + expect(JSON.stringify(live.blockOutputs?.['refetch.row'])).toContain('a@b.co') + expect(mcpCalls.map((call) => call.name)).toEqual(['read_file']) + }) + + it('answers a read by the number a stubbed create would have assigned', async () => { + const github = (name: string, values: Record) => + block(name, 'github', { + owner: 'octo', + repo: 'tracker', + apiKey: 'ghp_dry_run_fixture', + ...values, + }) + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + github('file', { operation: 'github_create_issue', title: 'Broken build' }), + github('reread', { + operation: 'github_get_issue', + issue_number: '', + }), + ], + [ + ['start', 'file'], + ['file', 'reread'], + ] + ).state + ) + + const result = await run(workflowId, { dry: true }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + const stubbed = result.sideEffects?.stubbed ?? [] + expect(stubbed.map((entry) => [entry.block, entry.tool, entry.dependsOnStub])).toEqual([ + ['file', 'github_create_issue', false], + ['reread', 'github_get_issue', true], + ]) + expect(JSON.stringify(stubbed[1].request)).toMatch(/\/issues\/9000000\d\d/) + }) + + it('sends a read of a row a stubbed write was given, which exists', async () => { + const tableId = await createTable() + const seeded = await run( + await saveWorkflow( + graph( + [block('start', 'start_trigger'), upsertLead('seed', tableId, 'a@b.co')], + [['start', 'seed']] + ).state + ) + ) + expect(seeded.status, JSON.stringify(seeded.error)).toBe('completed') + const [row] = await db + .select({ id: userTableRows.id }) + .from(userTableRows) + .where(eq(userTableRows.tableId, tableId)) + const workflowId = await saveWorkflow( + graph( + [ + block('start', 'start_trigger'), + block('rescore', 'table', { + operation: 'update_row', + tableSelector: tableId, + rowId: row.id, + data: JSON.stringify({ score: 99 }), + }), + block('fetch', 'table', { + operation: 'get_row', + tableSelector: tableId, + rowId: '', + }), + ], + [ + ['start', 'rescore'], + ['rescore', 'fetch'], + ] + ).state + ) + + const result = await run(workflowId, { dry: true, selectedOutputs: ['fetch.row'] }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(result.sideEffects?.stubbed.map((entry) => entry.block)).toEqual(['rescore']) + expect(result.blockOutputs?.['fetch.row']).toMatchObject({ + id: row.id, + data: { email: 'a@b.co', score: 82 }, + }) + }) +}) + describe('a test run', () => { it('is not the source of a Copilot run from a block, named or as the latest run', async () => { const { tableId, workflowId, afterId, dryRunId } = await dryRunSource() @@ -1968,4 +2273,42 @@ return created.id.toString()` ['override', 'http_request'], ]) }) + + it('sends no GET that would carry a stubbed write’s placeholder id, from code or an API block', async () => { + const prefix = `/${generateId()}` + const tableId = await createTable() + const fixture = graph( + [ + block('start', 'start_trigger'), + upsertLead('save', tableId, 'a@b.co'), + block('code', 'function', { + language: 'javascript', + code: `const res = await fetch('${server.url}${prefix}/code/' + ) +return { status: res.status, stubbed: res.headers.get('x-sim-dry-run') }`, + }), + block('fetch', 'api', { url: `${server.url}${prefix}/api/`, method: 'GET' }), + block('real', 'api', { url: `${server.url}${prefix}/api/row_8f3a2c`, method: 'GET' }), + ], + [ + ['start', 'save'], + ['save', 'code'], + ['code', 'fetch'], + ['fetch', 'real'], + ] + ) + const workflowId = await saveWorkflow(fixture.state) + + const result = await run(workflowId, { dry: true, selectedOutputs: ['code.result'] }) + + expect(result.status, JSON.stringify(result.error)).toBe('completed') + expect(arrivalsUnder(prefix)).toEqual([`GET ${prefix}/api/row_8f3a2c`]) + expect(result.blockOutputs?.['code.result']).toEqual({ status: 200, stubbed: 'stubbed' }) + expect( + result.sideEffects?.stubbed.map((entry) => [entry.block, entry.tool, entry.dependsOnStub]) + ).toEqual([ + ['save', 'table_upsert_row', false], + ['code', 'function_execute', true], + ['fetch', 'http_request', true], + ]) + }) }) diff --git a/apps/sim/lib/workflows/dry-run/placeholders.test.ts b/apps/sim/lib/workflows/dry-run/placeholders.test.ts new file mode 100644 index 00000000000..8b5791d5283 --- /dev/null +++ b/apps/sim/lib/workflows/dry-run/placeholders.test.ts @@ -0,0 +1,42 @@ +/** + * @vitest-environment node + */ +import { describe, expect, it } from 'vitest' +import { PlaceholderTokens } from '@/lib/workflows/dry-run/placeholders' + +/** Tokens holding the placeholders of one answer: a row id, a title and an issue number. */ +function registered() { + const tokens = new PlaceholderTokens() + tokens.register({ + row: { id: 'dry_run_row_1', data: { email: 'a@b.co' } }, + title: 'dry_run_title_2', + number: 900_000_003, + realId: 'row_8f3a2c', + status: 200, + }) + return tokens +} + +describe('a dry run’s placeholder tokens', () => { + it.each([ + ['whole', 'dry_run_row_1'], + ['inside a path, after a word', '/files/file_dry_run_row_1.json'], + ['followed by a word', 'dry_run_row_1_copy'], + ['in another case', 'Row DRY_RUN_ROW_1 was archived'], + ['quoted in free text', 'Re: dry_run_title_2'], + ['as a number', 900_000_003], + ['as digits in a URL', 'https://api.github.com/repos/o/r/issues/900000003'], + ])('are found %s', (_, sent) => { + expect(registered().occursIn({ sent })).toBe(true) + }) + + it.each([ + ['a longer token number', 'dry_run_row_10'], + ['a real value the answer echoed', 'row_8f3a2c'], + ['a number the answer did not mint', 200], + ['digits that only start with a placeholder number', '9000000031'], + ['a token no answer returned', 'dry_run_row_2'], + ])('are not found in %s', (_, sent) => { + expect(registered().occursIn({ sent })).toBe(false) + }) +}) diff --git a/apps/sim/lib/workflows/dry-run/placeholders.ts b/apps/sim/lib/workflows/dry-run/placeholders.ts new file mode 100644 index 00000000000..e287d88bd2d --- /dev/null +++ b/apps/sim/lib/workflows/dry-run/placeholders.ts @@ -0,0 +1,99 @@ +import { isPlainRecord } from '@sim/utils/object' +import { DRY_RUN_NUMBER_BASE } from '@/tools/dry-run' + +/** Placeholders a run tracks at most; placeholders returned past it are not tracked. */ +const MAX_TRACKED = 10_000 +/** Nesting a scan follows, and values it reads, before it stops looking. */ +const MAX_SCAN_DEPTH = 20 +const MAX_SCAN_VALUES = 2000 +/** Placeholder numbers run from just above {@link DRY_RUN_NUMBER_BASE} up to this many above it. */ +const MAX_NUMBER_OFFSET = 1_000_000 + +/** The shape `dryRunId` mints, and the prefix that finds it inside a longer string. */ +const TOKEN = /^dry_run_[a-z0-9_]+_\d+$/ +const TOKEN_PREFIX = 'dry_run_' +const TOKEN_RUN = /^[a-z0-9_]+/ +/** Where a token can end inside a run: after a whole `_`. */ +const TOKEN_END = /_\d+/g +const DIGIT_RUN = /\d+/g +/** Longest token a scan reads at one `dry_run_`. */ +const MAX_TOKEN_LENGTH = 256 + +/** Whether `value` is shaped like a number `dryRunNumber` mints. */ +function isPlaceholderNumber(value: number): boolean { + return ( + Number.isInteger(value) && + value > DRY_RUN_NUMBER_BASE && + value <= DRY_RUN_NUMBER_BASE + MAX_NUMBER_OFFSET + ) +} + +/** The strings and numbers `value` holds, at any depth within the scan's bounds. */ +function leavesOf(value: unknown): Array { + const found: Array = [] + const visit = (node: unknown, depth: number): void => { + if (found.length >= MAX_SCAN_VALUES || depth > MAX_SCAN_DEPTH) return + if (typeof node === 'string' || typeof node === 'number') found.push(node) + else if (Array.isArray(node)) for (const item of node) visit(item, depth + 1) + else if (isPlainRecord(node)) for (const item of Object.values(node)) visit(item, depth + 1) + } + visit(value, 0) + return found +} + +/** + * Every token `text` could hold: at each `dry_run_` (any case, anywhere, even mid-word), each + * candidate the following run of token characters holds up to a `_` end, so + * `file_dry_run_row_1.json` and `dry_run_row_1_copy` both hold `dry_run_row_1`, while + * `dry_run_row_10` does not. + */ +function* tokensIn(text: string): Generator { + const lower = text.toLowerCase() + let start = lower.indexOf(TOKEN_PREFIX) + while (start !== -1) { + const run = lower.slice(start, start + MAX_TOKEN_LENGTH).match(TOKEN_RUN)?.[0] ?? '' + for (const end of run.matchAll(TOKEN_END)) yield run.slice(0, end.index + end[0].length) + start = lower.indexOf(TOKEN_PREFIX, start + 1) + } +} + +/** + * The placeholders a dry run's answers returned: every `dry_run__` string (see + * `dryRunId`) and every placeholder number (see `dryRunNumber`), minted by a tool's `dryRunOutput` + * for an id the provider would assign, or by the sample for a field the request cannot know. Only + * placeholder answers are registered, so a placeholder is a value the run made up, never one a + * real call returned or the workflow was given. A read that would send one, as an id or inside + * free text (a message quoting a placeholder title), depends on a write that was never sent. + */ +export class PlaceholderTokens { + private readonly tokens = new Set() + private readonly numbers = new Set() + + /** Registers the placeholders of a placeholder answer. */ + register(returned: unknown): void { + for (const value of leavesOf(returned)) { + if (this.tokens.size + this.numbers.size >= MAX_TRACKED) return + if (typeof value === 'number') { + if (isPlaceholderNumber(value)) this.numbers.add(value) + } else if (TOKEN.test(value.toLowerCase())) { + this.tokens.add(value.toLowerCase()) + } + } + } + + /** + * Whether `sent` holds a registered placeholder: a token anywhere in a string, or a number whole + * or as a run of digits in a string (`/issues/900000001`). + */ + occursIn(sent: unknown): boolean { + if (this.tokens.size === 0 && this.numbers.size === 0) return false + return leavesOf(sent).some((value) => { + if (typeof value === 'number') return this.numbers.has(value) + for (const token of tokensIn(value)) if (this.tokens.has(token)) return true + for (const digits of value.match(DIGIT_RUN) ?? []) { + if (this.numbers.has(Number(digits))) return true + } + return false + }) + } +} diff --git a/apps/sim/lib/workflows/dry-run/samples.ts b/apps/sim/lib/workflows/dry-run/samples.ts index 08ffe265c38..64e1d4c8900 100644 --- a/apps/sim/lib/workflows/dry-run/samples.ts +++ b/apps/sim/lib/workflows/dry-run/samples.ts @@ -2,11 +2,48 @@ import { isPlainRecord } from '@sim/utils/object' import { getEffectiveBlockOutputs } from '@/lib/workflows/blocks/outputs' import { generateMockPayloadFromOutputsDefinition } from '@/lib/workflows/triggers/mock-payload' import { isRunControlledOutputField } from '@/executor/utils/mock-output' +import { dryRunId, dryRunNumber } from '@/tools/dry-run' import { getToolOutputsMetadata } from '@/tools/metadata-outputs' +/** A field name as a placeholder token's kind: `rowId` is `row_id`. */ +function tokenKind(field: string): string { + const kind = field + .replace(/([a-z0-9])([A-Z])/g, '$1_$2') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '_') + .replace(/^_+|_+$/g, '') + return kind || 'value' +} + /** - * Placeholder output shaped like a block's real one, for the operation its params configure. - * Data only, like a mock: no field the run's execution, trace or billing reads. + * `sample` with every string a placeholder token (`dry_run__`, numbered per field) and + * every number a placeholder number (`dryRunNumber`), so a value the sample made up is + * recognisably not real wherever it flows, and a read that would send it is known to depend on a + * stub. An array item's fields are named by their own keys. + */ +function mintPlaceholders(sample: Record): Record { + const counts = new Map() + let numbers = 0 + const mint = (field: string): string => { + const kind = tokenKind(field) + const n = (counts.get(kind) ?? 0) + 1 + counts.set(kind, n) + return dryRunId(kind, n) + } + const visit = (value: unknown, field: string): unknown => { + if (typeof value === 'string') return mint(field) + if (typeof value === 'number') return dryRunNumber(++numbers) + if (Array.isArray(value)) return value.map((item) => visit(item, field)) + if (!isPlainRecord(value)) return value + return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, visit(item, key)])) + } + return Object.fromEntries(Object.entries(sample).map(([key, item]) => [key, visit(item, key)])) +} + +/** + * Placeholder output shaped like a block's real one, for the operation its params configure, its + * strings and numbers placeholders. Data only, like a mock: no field the run's execution, trace or + * billing reads. */ export function sampleBlockOutput(block: { type: string @@ -15,7 +52,10 @@ export function sampleBlockOutput(block: { const subBlocks: Record = {} for (const [key, value] of Object.entries(block.params)) subBlocks[key] = { value } const outputs = getEffectiveBlockOutputs(block.type, subBlocks) - const sample = withEmptyFileLists(outputs, generateMockPayloadFromOutputsDefinition(outputs)) + const sample = withEmptyFileLists( + outputs, + mintPlaceholders(generateMockPayloadFromOutputsDefinition(outputs)) + ) return Object.fromEntries( Object.entries(sample).filter(([field]) => !isRunControlledOutputField(field)) ) @@ -89,17 +129,79 @@ function overlayFields( ) } +/** Nesting of a discovered JSON Schema an output declaration follows. */ +const MAX_SCHEMA_DEPTH = 10 + /** - * Placeholder output shaped like a tool's declared outputs; empty for a tool that declares none. - * `echoed`, the tool's `dryRunOutput`, is laid over the sample by the declared schema (see - * `ToolConfig.dryRunOutput`). + * A discovered JSON Schema (an MCP tool's `outputSchema`) as an output declaration the sample + * reads: `integer` is a `number`, a union reads as its first non-null member, and a field whose + * type cannot be told is left out rather than sampled as a guess. + */ +function outputFromJsonSchema(schema: unknown, depth = 0): Record | undefined { + if (!isPlainRecord(schema) || depth > MAX_SCHEMA_DEPTH) return undefined + const variants = Array.isArray(schema.anyOf) ? schema.anyOf : schema.oneOf + if (Array.isArray(variants)) { + const member = variants.find((variant) => !(isPlainRecord(variant) && variant.type === 'null')) + return outputFromJsonSchema(member, depth + 1) + } + const declared = Array.isArray(schema.type) + ? schema.type.find((type) => type !== 'null') + : schema.type + const type = + typeof declared === 'string' + ? declared + : isPlainRecord(schema.properties) + ? 'object' + : schema.items !== undefined + ? 'array' + : undefined + switch (type) { + case 'object': { + const properties: Record = {} + for (const [field, child] of Object.entries( + isPlainRecord(schema.properties) ? schema.properties : {} + )) { + const output = outputFromJsonSchema(child, depth + 1) + if (output) properties[field] = output + } + return { type: 'object', properties } + } + case 'array': { + const items = outputFromJsonSchema(schema.items, depth + 1) + return items ? { type: 'array', items } : undefined + } + case 'integer': + case 'number': + return { type: 'number' } + case 'string': + case 'boolean': + return { type } + default: + return undefined + } +} + +/** + * Placeholder output shaped like a tool's declared outputs, and the `discovered` outputs a call + * learned beside them as JSON Schemas (an MCP tool's `outputSchema`, as `structuredContent`), its + * strings and numbers placeholders; empty for a tool that declares none. `echoed`, the tool's + * `dryRunOutput`, is laid over the sample by the declared schema (see `ToolConfig.dryRunOutput`). */ export function sampleToolOutput( toolId: string, - echoed: Record | null = null + echoed: Record | null = null, + discovered?: Record ): Record { - const outputs = getToolOutputsMetadata(toolId) - if (!outputs) return {} - const sample = withEmptyFileLists(outputs, generateMockPayloadFromOutputsDefinition(outputs)) + const declared = getToolOutputsMetadata(toolId) + if (!declared && !discovered) return {} + const outputs: Record = { ...declared } + for (const [field, schema] of Object.entries(discovered ?? {})) { + const output = outputFromJsonSchema(schema) + if (output) outputs[field] = output + } + const sample = withEmptyFileLists( + outputs, + mintPlaceholders(generateMockPayloadFromOutputsDefinition(outputs)) + ) return echoed ? overlayFields(outputs, sample, echoed) : sample } diff --git a/apps/sim/lib/workflows/dry-run/side-effects.ts b/apps/sim/lib/workflows/dry-run/side-effects.ts index 7bb12bbb07b..d227f7f2c0a 100644 --- a/apps/sim/lib/workflows/dry-run/side-effects.ts +++ b/apps/sim/lib/workflows/dry-run/side-effects.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import { isReadRequest } from '@/lib/core/utils/http-methods' +import { PlaceholderTokens } from '@/lib/workflows/dry-run/placeholders' import { sampleBlockOutput, sampleToolOutput } from '@/lib/workflows/dry-run/samples' import { isCustomBlockType } from '@/blocks/custom/build-config' import { BlockType, HUMAN_IN_THE_LOOP_BLOCK_TYPES } from '@/executor/constants' @@ -7,10 +8,12 @@ import type { AnsweredBlockCall, CodeNetworkPolicy, DryRunOptions, + McpCallTarget, SideEffectBlockSite, SideEffectPolicy, SideEffectSite, StubbedToolCall, + ToolCallSite, } from '@/executor/execution/types' import type { NormalizedBlockOutput } from '@/executor/types' @@ -54,17 +57,25 @@ interface RecordedSite { block: string | null } -/** A write the run did not send: the request it would have sent and the placeholder it got. */ +/** A call the run did not send: the request it would have sent and the placeholder it got. */ interface StubbedSideEffect extends RecordedSite { /** The tool called; null when the whole block was answered instead of run. */ tool: string | null request: Record | null returned: Record + /** The MCP server and tool the MCP block's operation names; null for any other call. */ + mcp: McpCallTarget | null + /** A read held back because what it sends holds a placeholder an answer returned. */ + dependsOnStub: boolean + /** An MCP call whose server declares the tool read-only, a claim Sim cannot verify. */ + readOnlyHint: boolean } /** A write sent for real because its block was allowed. */ interface AllowedSideEffect extends RecordedSite { tool: string | null + /** The MCP server and tool the MCP block's operation names; null for any other call. */ + mcp: McpCallTarget | null } /** Code that ran for real in a remote sandbox, whose network the run cannot see. */ @@ -143,9 +154,13 @@ class RecordedList { * write tool call is answered with a placeholder shaped like the tool's output, holding what the * request determines where the tool declares it (`dryRunOutput`), and recorded with * the request it would have sent, except an allowed block's, which are sent and recorded once per - * block and tool. Reads always run. Code runs too: in the isolate its reads (`isReadRequest`) are - * sent and any other request is answered with an empty 200 and recorded like a write, while code - * in a remote sandbox, whose network the run cannot see, is listed unchecked. Custom blocks and + * block and tool (an MCP block's by the MCP tool it names). Reads run, except one that would send + * a placeholder an answer returned (a `dry_run__` token or a placeholder number), which + * is answered with a placeholder too, and is listed with `dependsOnStub`. Every MCP call is a write + * here, even one its server declares read-only, since Sim cannot verify that claim. Code runs too: + * in the isolate its reads (`isReadRequest`) are sent, unless they would send a placeholder, and any + * other request is answered with an empty 200 and recorded like a write, while code in a remote + * sandbox, whose network the run cannot see, is listed unchecked. Custom blocks and * {@link PAUSING_BLOCK_TYPES} are answered whole, as is a block that acts outside the tool seam * unless it is allowed, and `blockMocks` answers its blocks with fixed outputs. Allowed and mocked * blocks are blocks of the workflow the run started, never of a child it calls, and an allowed @@ -157,6 +172,7 @@ export class WriteStubPolicy implements SideEffectPolicy { private readonly unchecked = new RecordedList() private readonly allowBlockIds: ReadonlySet private readonly blockMocks: ReadonlyMap + private readonly placeholders = new PlaceholderTokens() constructor( private readonly options: { @@ -195,7 +211,7 @@ export class WriteStubPolicy implements SideEffectPolicy { * own code (a Function block's, a Condition's expressions, or code an Agent's model wrote), * which is sent, its network decided by {@link codeNetwork}. */ - decideWrite(call: SideEffectSite & { toolId: string }): 'send' | 'stub' { + decideWrite(call: ToolCallSite): 'send' | 'stub' { switch (call.toolId) { case 'deployed_block_executor': return 'stub' @@ -204,9 +220,10 @@ export class WriteStubPolicy implements SideEffectPolicy { return 'send' } if (!this.allows(call)) return 'stub' + const mcpKey = call.mcp ? `:${call.mcp.server}:${call.mcp.tool}` : '' this.allowed.add( - { ...recordedSite(call), tool: call.toolId }, - `${call.workflowId}:${call.blockId}:${call.toolId}` + { ...recordedSite(call), tool: call.toolId, mcp: call.mcp }, + `${call.workflowId}:${call.blockId}:${call.toolId}${mcpKey}` ) return 'send' } @@ -225,9 +242,14 @@ export class WriteStubPolicy implements SideEffectPolicy { key ), onRequest: async (request) => { - if (isReadRequest(request.method, request.headerNames)) return 'send' - if (allowed) { - this.allowed.add({ ...recordedSite(site), tool: CODE_TOOL_ID }, `${key}:${CODE_TOOL_ID}`) + const reads = isReadRequest(request.method, request.headerNames) + const dependsOnStub = reads && this.placeholders.occursIn([request.url, request.body]) + if (reads && !dependsOnStub) return 'send' + if (allowed && !dependsOnStub) { + this.allowed.add( + { ...recordedSite(site), tool: CODE_TOOL_ID, mcp: null }, + `${key}:${CODE_TOOL_ID}` + ) return 'send' } this.stubbed.add({ @@ -235,25 +257,44 @@ export class WriteStubPolicy implements SideEffectPolicy { tool: CODE_TOOL_ID, request: this.stubbed.full ? null : await describeOrNull(request.describe), returned: { status: 200, body: {} }, + mcp: null, + dependsOnStub, + readOnlyHint: false, }) return 'stub' }, } } - stubWrite(call: StubbedToolCall): Record { - const returned = sampleToolOutput(call.toolId, call.echoed) - this.stubbed.add({ ...recordedSite(call), tool: call.toolId, request: call.request, returned }) + stubCall(call: StubbedToolCall): Record { + const returned = sampleToolOutput(call.toolId, call.echoed, call.discoveredOutputs) + this.placeholders.register(returned) + this.stubbed.add({ + ...recordedSite(call), + tool: call.toolId, + request: call.request, + returned, + mcp: call.mcp, + dependsOnStub: call.dependsOnStub, + readOnlyHint: call.readOnlyHint, + }) return returned } + sendsPlaceholder(sent: unknown): boolean { + return this.placeholders.occursIn(sent) + } + answersBlock(block: SideEffectBlockSite): boolean { if (this.mockOf(block)) return true if (PAUSING_BLOCK_TYPES.has(block.blockType)) return true if (isCustomBlockType(block.blockType)) return true if (!SELF_DIRECTED_BLOCK_TYPES.has(block.blockType)) return false if (!this.allows(block)) return true - this.allowed.add({ ...recordedSite(block), tool: null }, `${block.workflowId}:${block.blockId}`) + this.allowed.add( + { ...recordedSite(block), tool: null, mcp: null }, + `${block.workflowId}:${block.blockId}` + ) return false } @@ -262,7 +303,16 @@ export class WriteStubPolicy implements SideEffectPolicy { if (mock) return structuredClone(mock) const input = await call.input() const returned = sampleBlockOutput({ type: call.blockType, params: input ?? {} }) - this.stubbed.add({ ...recordedSite(call), tool: null, request: input, returned }) + this.placeholders.register(returned) + this.stubbed.add({ + ...recordedSite(call), + tool: null, + request: input, + returned, + mcp: null, + dependsOnStub: false, + readOnlyHint: false, + }) return returned } diff --git a/apps/sim/tools/dry-run.ts b/apps/sim/tools/dry-run.ts index 5dbb86c40cb..2de29cbba46 100644 --- a/apps/sim/tools/dry-run.ts +++ b/apps/sim/tools/dry-run.ts @@ -6,3 +6,15 @@ export function dryRunId(kind: string, n = 1): string { return `dry_run_${kind}_${n}` } + +/** + * The first number a dry run's placeholder carries where the provider would assign one (an issue + * number, a count it cannot know): every placeholder number is above it, recognisably not real yet + * within a 32-bit integer. + */ +export const DRY_RUN_NUMBER_BASE = 900_000_000 + +/** The `n`th placeholder number, counting from 1: `900000001`. */ +export function dryRunNumber(n = 1): number { + return DRY_RUN_NUMBER_BASE + n +} diff --git a/apps/sim/tools/index.test.ts b/apps/sim/tools/index.test.ts index c6bbfaa439d..8d77a05fad6 100644 --- a/apps/sim/tools/index.test.ts +++ b/apps/sim/tools/index.test.ts @@ -7534,6 +7534,48 @@ describe('MCP Tool Execution', () => { expect(allowed.summary().stubbed).toEqual([]) }) + it('stubs an MCP tool its server declares read-only, marking it and answering from its outputSchema', async () => { + const dryRun = new WriteStubPolicy({ workflowId: 'test-workflow' }) + mockExecuteInternalToolOperation.mockResolvedValueOnce( + Response.json({ + success: true, + output: { + success: true, + checked: true, + tool: { + name: 'count_files', + outputSchema: { + type: 'object', + properties: { + total: { type: 'integer' }, + label: { type: ['null', 'string'] }, + owner: { anyOf: [{ type: 'null' }, { type: 'string' }] }, + untyped: {}, + }, + }, + readOnlyHint: true, + }, + }, + }) + ) + + const held = await executeTool( + 'mcp-123-count_files', + { path: '/test', _context: { blockId: 'agent-1' } }, + { + executionContext: createToolExecutionContext({ sideEffects: dryRun }), + resolvedSecretTraceRegistry: new ResolvedSecretTraceRegistry(), + } + ) + + expect(held.output).toEqual({ + structuredContent: { total: 900_000_001, label: 'dry_run_label_1', owner: 'dry_run_owner_1' }, + }) + expect(dryRun.summary().stubbed).toMatchObject([ + { tool: 'mcp-123-count_files', readOnlyHint: true, dependsOnStub: false }, + ]) + }) + it('fails an MCP write in a dry run as it would live when its server refuses the call', async () => { const dryRun = new WriteStubPolicy({ workflowId: 'test-workflow' }) mockExecuteInternalToolOperation.mockResolvedValueOnce( diff --git a/apps/sim/tools/index.ts b/apps/sim/tools/index.ts index d028e6bd459..9340f6fddb5 100644 --- a/apps/sim/tools/index.ts +++ b/apps/sim/tools/index.ts @@ -136,12 +136,13 @@ import { } from '@/tools/request-transport' import { AWS_CREDENTIAL_OAUTH, AWS_SESSION_SIGNED_TOOL_IDS } from '@/tools/shared/saved-credentials' import { - answerUnsentMcpWrite, - answerUnsentWrite, + answerCheckedMcpCall, + answerUnsentCall, type CodeNetwork, codeNetworkFor, describeMcpToolRequest, describeToolRequest, + unsentReadFor, unsentWriteFor, } from '@/tools/side-effects' import type { @@ -1960,19 +1961,18 @@ async function executeToolImplementation( logger.error(`Custom tool not found: ${normalizedToolId}`, { requestId }) } } else if (isMcpTool(normalizedToolId)) { - // An MCP tool declares no effect, so a run's side-effect policy decides every one. An unsent - // one is still authorized and checked against the server's tools, so it fails as live would. - const unsentMcpWrite = unsentWriteFor({ toolId: normalizedToolId, params, executionContext }) + // An MCP tool declares no effect, so a run's side-effect policy decides every one. + const unsentMcpCall = unsentWriteFor({ toolId: normalizedToolId, params, executionContext }) const response = await executeMcpTool( normalizedToolId, params, - unsentMcpWrite ? checkOnlyContext(operationContext) : operationContext, + unsentMcpCall ? checkOnlyContext(operationContext) : operationContext, requestId, startTimeISO, effectiveSignal ) - if (!unsentMcpWrite || !response.success) return response - return await answerUnsentMcpWrite(unsentMcpWrite, { + if (!unsentMcpCall) return response + return await answerCheckedMcpCall(unsentMcpCall, response, { params, registry: resolvedSecretTraceRegistry, describe: describeMcpToolRequest, @@ -2015,13 +2015,15 @@ async function executeToolImplementation( await resolveToolEnvReferences(tool, contextParams, scope, resolvedSecretTraceRegistry) /** - * Decided before a hosted key is drawn, so a write the run's side-effect policy will not send + * Decided before a hosted key is drawn, so a call the run's side-effect policy will not send * spends no rate-limit slot. */ - const unsentWrite = - tool.effect !== 'read' && !(executionContext?.sideEffects && tool.readsWhen?.(contextParams)) - ? unsentWriteFor({ toolId: normalizedToolId, params: contextParams, executionContext }) - : null + const readsOnly = + tool.effect === 'read' || + Boolean(executionContext?.sideEffects && tool.readsWhen?.(contextParams)) + const unsentCall = readsOnly + ? unsentReadFor({ tool, params: contextParams, executionContext }) + : unsentWriteFor({ toolId: normalizedToolId, params: contextParams, executionContext }) const hostedKeyInfo = await injectHostedKeyIfNeeded( tool, @@ -2029,7 +2031,7 @@ async function executeToolImplementation( executionContext, requestId, effectiveSignal, - { drawKey: !unsentWrite } + { drawKey: !unsentCall } ) if (hostedKeyInfo.isUsingHostedKey) { @@ -2264,7 +2266,7 @@ async function executeToolImplementation( } // After credentials resolve, so an unsent write still proves them. - if (unsentWrite) { + if (unsentCall) { const unsentTool = tool const unsent = { params: contextParams, @@ -2274,11 +2276,11 @@ async function executeToolImplementation( echo: unsentTool.dryRunOutput, } if (normalizedToolId !== mcpRunOperationTool.id || !tool.operation) { - return await answerUnsentWrite(unsentWrite, unsent) + return await answerUnsentCall(unsentCall, unsent) } - // The MCP block's operation is authorized and checked against the server's tools first, so - // an unusable one fails as live would; a failed check throws like a failed call. - await executeDeclaredInternalOperation({ + // The MCP block's operation is checked like an MCP tool's; a failed check throws like a + // failed call. + const checked = await executeDeclaredInternalOperation({ toolId: normalizedToolId, tool, params: contextParams, @@ -2290,7 +2292,7 @@ async function executeToolImplementation( internalSandboxProfile, authorizedServiceAccountCredential, }) - return await answerUnsentMcpWrite(unsentWrite, unsent) + return await answerCheckedMcpCall(unsentCall, checked, unsent) } // Custom blocks (deploy-as-block) run in-process through WorkflowBlockHandler. diff --git a/apps/sim/tools/side-effects.test.ts b/apps/sim/tools/side-effects.test.ts index bc8d8d72b5a..de972f08376 100644 --- a/apps/sim/tools/side-effects.test.ts +++ b/apps/sim/tools/side-effects.test.ts @@ -9,8 +9,8 @@ import type { PiiBlockOutputRedaction } from '@/executor/execution/types' import type { ExecutionContext } from '@/executor/types' import { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry' import { - answerUnsentMcpWrite, - answerUnsentWrite, + answerCheckedMcpCall, + answerUnsentCall, codeNetworkFor, describeMcpToolRequest, unsentWriteFor, @@ -57,7 +57,7 @@ async function stubSlackMessage( _context: { blockId: 'notify' }, } const { write, policy } = unsentWrite('slack_message', params, piiBlockOutputRedaction) - const response = await answerUnsentWrite(write, { params, registry, describe: () => request }) + const response = await answerUnsentCall(write, { params, registry, describe: () => request }) return { response, stubbed: policy.summary().stubbed } } @@ -127,7 +127,7 @@ describe('a write a dry run does not send', () => { } const { write, policy } = unsentWrite('slack_message', params) - await answerUnsentWrite(write, { + await answerUnsentCall(write, { params, registry: new ResolvedSecretTraceRegistry(), describe: (masked) => ({ body: Buffer.from(String(masked.content)).toString('base64') }), @@ -150,11 +150,15 @@ describe('a write a dry run does not send', () => { const params = { arguments: args, _context: { blockId: 'notify' } } const { write, policy } = unsentWrite('mcp-server-1-create_issue', params) - await answerUnsentMcpWrite(write, { - params, - registry: new ResolvedSecretTraceRegistry(), - describe: describeMcpToolRequest, - }) + await answerCheckedMcpCall( + write, + { success: true, output: {} }, + { + params, + registry: new ResolvedSecretTraceRegistry(), + describe: describeMcpToolRequest, + } + ) const [{ request }] = policy.summary().stubbed expect(request).toEqual({ diff --git a/apps/sim/tools/side-effects.ts b/apps/sim/tools/side-effects.ts index e9c3a65bb56..b47fc9172ff 100644 --- a/apps/sim/tools/side-effects.ts +++ b/apps/sim/tools/side-effects.ts @@ -1,8 +1,10 @@ /** * Where a run's side-effect policy (a dry run, or a workflow test's unmocked writes) meets a tool - * call: `executeTool` asks {@link unsentWriteFor} about every call not declared `read` before a - * hosted key is drawn for it, and answers an unsent one with {@link answerUnsentWrite} after - * credentials resolve and before anything is sent. + * call: `executeTool` asks {@link unsentWriteFor} about every call not declared `read`, and + * {@link unsentReadFor} about every read, before a hosted key is drawn for it, and answers an + * unsent one with {@link answerUnsentCall} after credentials resolve and before anything is sent. + * An MCP call declares no effect, so a held one is checked against the server's tools first and + * answered with {@link answerCheckedMcpCall}. */ import { createLogger } from '@sim/logger' import { isPlainRecord, toRecord } from '@sim/utils/object' @@ -12,13 +14,20 @@ import { REDACTED_MARKER, redactExactSensitiveValues, } from '@/lib/core/security/redaction' +import { isReadRequest } from '@/lib/core/utils/http-methods' import type { IsolatedFetchPolicy } from '@/lib/execution/isolated-vm' import { redactObjectStrings } from '@/lib/logs/execution/pii-redaction' +import { readMcpToolOutputSchema } from '@/lib/mcp/output-schema' import { parseMcpToolArguments, RUN_CONTEXT_PARAMS } from '@/lib/mcp/tool-arguments' import { getBlock, getBlockByToolName, getBlockRegistry } from '@/blocks/registry' import type { BlockConfig } from '@/blocks/types' import { isCustomTool } from '@/executor/constants' -import type { SideEffectPolicy, SideEffectSite } from '@/executor/execution/types' +import type { + SideEffectPolicy, + SideEffectSite, + StubbedToolCall, + ToolCallSite, +} from '@/executor/execution/types' import type { ExecutionContext } from '@/executor/types' import { projectResolvedSecretModelContent } from '@/executor/utils/resolved-secret-content-projection' import { isNonIdentifyingSecretLiteral } from '@/executor/utils/resolved-secret-match-policy' @@ -47,11 +56,30 @@ function sideEffectSite( } } -/** A write tool call the run's policy answers instead of sending. */ -interface UnsentWrite { +/** A tool call the run's policy answers instead of sending. */ +interface UnsentCall { policy: SideEffectPolicy executionContext: ExecutionContext - call: SideEffectSite & { toolId: string } + call: Omit +} + +/** + * A tool call of the executing workflow, at the block that made it; the MCP block's operation + * also by the MCP server and tool it names. + */ +function toolCallSite( + executionContext: ExecutionContext, + toolId: string, + params: Record +): ToolCallSite { + const { server, tool } = params + const namesMcpTool = + toolId === 'mcp_run_operation' && typeof server === 'string' && typeof tool === 'string' + return { + ...sideEffectSite(executionContext, params), + toolId, + mcp: namesMcpTool ? { server, tool } : null, + } } /** @@ -62,12 +90,37 @@ export function unsentWriteFor(input: { toolId: string params: Record executionContext: ExecutionContext | undefined -}): UnsentWrite | null { +}): UnsentCall | null { const { executionContext } = input const policy = executionContext?.sideEffects if (!executionContext || !policy) return null - const call = { ...sideEffectSite(executionContext, input.params), toolId: input.toolId } - return policy.decideWrite(call) === 'stub' ? { policy, executionContext, call } : null + const call = toolCallSite(executionContext, input.toolId, input.params) + return policy.decideWrite(call) === 'stub' + ? { policy, executionContext, call: { ...call, dependsOnStub: false, readOnlyHint: false } } + : null +} + +/** + * The read the run's side-effect policy will not send because a param the tool declares holds a + * value one of the run's placeholders returned, so it would read what a stubbed write never made; + * null when the run has no policy (at no cost) or the read is sent. + */ +export function unsentReadFor(input: { + tool: ExecutableToolConfig + params: Record + executionContext: ExecutionContext | undefined +}): UnsentCall | null { + const { executionContext, tool, params } = input + const policy = executionContext?.sideEffects + if (!executionContext || !policy) return null + const sent = Object.entries(params).filter(([key]) => Object.hasOwn(tool.params, key)) + if (!policy.sendsPlaceholder(Object.fromEntries(sent))) return null + const call = toolCallSite(executionContext, tool.id, params) + return { + policy, + executionContext, + call: { ...call, dependsOnStub: true, readOnlyHint: false }, + } } /** A string body as the JSON it carries, when it carries JSON. */ @@ -308,7 +361,7 @@ export async function redactSideEffectPayload(input: { } /** - * The response answering a write tool call the run's side-effect policy does not send, after the + * The response answering a tool call the run's side-effect policy does not send, after the * policy recorded the request it would have sent: `describe` builds it, and `echo` (a tool's * `dryRunOutput`) the output that request determines, both from params whose secrets are already * masked ({@link maskRequestParams}). Both are redacted again in one {@link redactSideEffectPayload} @@ -317,13 +370,15 @@ export async function redactSideEffectPayload(input: { * masked params. The write is answered either way, its placeholder the sample alone without an * echo. */ -export async function answerUnsentWrite( - write: UnsentWrite, +export async function answerUnsentCall( + write: UnsentCall, input: { params: Record registry: ResolvedSecretTraceRegistry | undefined describe: (maskedParams: Record) => unknown echo?: (maskedParams: Record) => Record + /** Outputs the call learned beside the tool's declared ones (see `StubbedToolCall`). */ + discoveredOutputs?: Record } ): Promise { const { call } = write @@ -356,10 +411,11 @@ export async function answerUnsentWrite( : null return { success: true, - output: write.policy.stubWrite({ + output: write.policy.stubCall({ ...call, request: isPlainRecord(redacted?.request) ? redacted.request : null, echoed: isPlainRecord(redacted?.echoed) ? redacted.echoed : null, + discoveredOutputs: input.discoveredOutputs, }), } } @@ -386,22 +442,39 @@ function buildFromMaskedParams( } /** - * {@link answerUnsentWrite} for a call that reaches an MCP server (a workspace MCP tool, or the MCP - * block's operation): a JSON-string `arguments` param is read first, so a secret nested in it is - * found and masked like any other. + * {@link answerUnsentCall} for an MCP call (a workspace MCP tool, or the MCP block's operation) + * once `checked`, the response of checking it against the server's tools without sending it, + * succeeded; a failed check is the answer itself, as a live call would fail. The placeholder is + * shaped by the tool's `outputSchema`, and a tool its server declares read-only is still held back, + * since Sim cannot verify that claim: its entry says so, for the author to allow its block. A + * JSON-string `arguments` param is read first, so a secret nested in it is masked like any other. */ -export function answerUnsentMcpWrite( - write: UnsentWrite, - input: Parameters[1] +export async function answerCheckedMcpCall( + unsent: UnsentCall, + checked: ToolResponse, + input: Omit[1], 'discoveredOutputs'> ): Promise { + if (!checked.success) return checked const { params } = input - return answerUnsentWrite(write, { - ...input, - params: - typeof params.arguments === 'string' - ? { ...params, arguments: parseMcpToolArguments(params) } - : params, - }) + const tool = checked.output.checked === true ? toRecord(checked.output.tool) : {} + const readOnlyHint = tool.readOnlyHint === true + const outputSchema = readMcpToolOutputSchema(tool.outputSchema) + const args = parseMcpToolArguments(params) + return answerUnsentCall( + { + ...unsent, + call: { + ...unsent.call, + readOnlyHint, + dependsOnStub: readOnlyHint && unsent.policy.sendsPlaceholder(args), + }, + }, + { + ...input, + params: typeof params.arguments === 'string' ? { ...params, arguments: args } : params, + discoveredOutputs: outputSchema ? { structuredContent: outputSchema } : undefined, + } + ) } /** The longest URL and body a stubbed network request of code is recorded with. */ @@ -470,6 +543,8 @@ export function codeNetworkFor(input: { const decision = await code.onRequest({ method: request.method, headerNames: request.headerNames, + url: request.url, + body: request.body, describe: async () => { const redacted = await redactSideEffectPayload({ payload: { @@ -493,7 +568,7 @@ export function codeNetworkFor(input: { ) }, }) - if (decision === 'stub') stubbed++ + if (decision === 'stub' && !isReadRequest(request.method, request.headerNames)) stubbed++ return decision }, failureHint: () => diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts index 0d048e3463a..9fe3dec2b11 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.test.ts @@ -681,7 +681,21 @@ describe('sim workflows run --dry', () => { block: 'Save lead', tool: 'table_upsert_row', request: { tableId: 'tbl_1', data: { email: 'a@b.co' } }, - returned: { row: { id: 'item_1' } }, + returned: { row: { id: 'dry_run_row_1' } }, + mcp: null, + dependsOnStub: false, + readOnlyHint: false, + }, + { + workflowId: WORKFLOW_ID, + blockId: 'docs', + block: 'Docs', + tool: 'mcp_run_operation', + request: { arguments: { path: '/q3.csv' } }, + returned: {}, + mcp: { server: 'mcp-files', tool: 'read_file' }, + dependsOnStub: false, + readOnlyHint: true, }, ], allowed: [], @@ -792,7 +806,10 @@ describe('sim workflows run --dry', () => { stderr = [] output.format = 'table' await run(WORKFLOW_ID, '--dry') - expect(stderr.join('')).toContain('Dry run: 1 not sent, 0 sent (allowed), 1 unchecked') + expect(stderr.join('')).toContain('Dry run: 2 not sent, 0 sent (allowed), 1 unchecked') + expect(stderr.join('')).toContain( + "not sent Docs → read_file (server says read-only: --allow 'Docs' sends it)" + ) }) it('counts the writes each list left out once it was full', async () => { @@ -803,7 +820,10 @@ describe('sim workflows run --dry', () => { runId: 'run-1', workflowId: WORKFLOW_ID, status: 'completed', - sideEffects: { ...sideEffects, omitted: { stubbed: 60, allowed: 0, unchecked: 2 } }, + sideEffects: { + ...sideEffects, + omitted: { stubbed: 60, allowed: 0, unchecked: 2 }, + }, }, }) ) @@ -811,7 +831,7 @@ describe('sim workflows run --dry', () => { await run(WORKFLOW_ID, '--dry') - expect(stderr.join('')).toContain('Dry run: 61 not sent, 0 sent (allowed), 3 unchecked') + expect(stderr.join('')).toContain('Dry run: 62 not sent, 0 sent (allowed), 3 unchecked') expect(stderr.join('')).toContain('… 62 more') }) }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts index e5cb3bafd49..acd5d79978b 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-run-follow.ts @@ -234,10 +234,12 @@ async function resolveWorkflowRunSelection( } /** - * A dry run's side effects in a few lines on stderr, for the human formats: each write that was - * not sent, sent because its block was allowed, or code in a remote sandbox the run cannot see, - * and a note for an allowed block whose writes all stayed stubbed (an Agent's call to a custom - * block). The request payloads are in the result itself (`--output json`). + * A dry run's side effects in a few lines on stderr, for the human formats: each call that was + * not sent (a read that depends on a stubbed write marked as such, and an MCP call its server + * declares read-only with how to send it), sent because its block was allowed, or code in a remote + * sandbox the run cannot see, and a note for an allowed block whose writes all stayed stubbed (an + * Agent's call to a custom block). The request payloads are in the result itself + * (`--output json`). */ function printSideEffects(sideEffects: unknown, dryRun: unknown): void { if (!isRecordLike(sideEffects)) return @@ -252,11 +254,21 @@ function printSideEffects(sideEffects: unknown, dryRun: unknown): void { return typeof count === 'number' ? count : 0 } const total = (key: string, entries: unknown[]) => entries.length + omittedOf(key) - const label = (entry: Record) => - safeOneLine(`${String(entry.block)}${typeof entry.tool === 'string' ? ` → ${entry.tool}` : ''}`) + /** An MCP block's call is named by the MCP tool it called, any other by its tool. */ + const label = (entry: Record) => { + const mcpTool = toRecord(entry.mcp).tool + const tool = typeof mcpTool === 'string' ? mcpTool : entry.tool + return safeOneLine(`${String(entry.block)}${typeof tool === 'string' ? ` → ${tool}` : ''}`) + } + const why = (entry: Record) => { + if (entry.dependsOnStub === true) return ' (reads a placeholder from a stubbed write)' + if (entry.readOnlyHint !== true) return '' + const block = safeOneLine(String(entry.block ?? entry.blockId)) + return ` (server says read-only: --allow '${block}' sends it)` + } const lines = [ `Dry run: ${total('stubbed', stubbed)} not sent, ${total('allowed', allowed)} sent (allowed), ${total('unchecked', unchecked)} unchecked`, - ...stubbed.map((entry) => ` not sent ${label(entry)}`), + ...stubbed.map((entry) => ` not sent ${label(entry)}${why(entry)}`), ...allowed.map((entry) => ` sent ${label(entry)}`), ...unchecked.map( (entry) => ` unchecked ${label(entry)}: ${safeOneLine(String(entry.reason))}` @@ -784,19 +796,24 @@ OAuth token with api:write); the child workflows it calls still run their own ac --dry runs the saved draft without its side effects: every tool call not declared read (sends, table writes, HTTP calls other than GET/HEAD/OPTIONS, custom and MCP tools) returns a placeholder and is listed in sideEffects.stubbed with the request it would have sent; check -those payloads. Code (a Function block's, a Condition's expressions, a While or Do While loop's -condition, or code an Agent's model writes) runs: its GET/HEAD/OPTIONS fetches are sent (an API -that writes on a GET is not stubbed), and any other fetch, or one with a method-override header, -gets an empty 200 and is listed in sideEffects.stubbed. Code in a remote sandbox (shell, Python, -imports) is listed in sideEffects.unchecked, since its network cannot be seen. Child workflows -run dry too; custom, Human in the loop and Wait blocks are answered whole, so the run never -pauses. Agents read memory but write none, and the run raises no workspace event. --allow - sends that block's writes (a Function's fetches included) for real (use a test -resource); allowing an Agent sends only its own tool calls, not a workflow or custom block it -calls. --mock = answers a block with fixed output, to steer a branch; a locked block -cannot be mocked, and a mock is data, so it cannot set a field the run's execution, trace or -billing reads (such as cost, tokens, model or a field starting with _). A dry run is the ---source-run only of another dry run, and is never resumed. +those payloads. Placeholder ids are distinctive (dry_run_row_1, numbers above 900000000); a read +(a GET included, a Function's fetch too) that would send one (a row a stubbed insert never made, +or text quoting one) is not sent either and is listed there with dependsOnStub. MCP calls are +stubbed even when the server declares the tool read-only, which Sim cannot verify: such an entry +has readOnlyHint, and --allow sends it. Code (a Function block's, a Condition's +expressions, a While or Do While loop's condition, or code an Agent's model writes) runs: its +other GET/HEAD/OPTIONS fetches are sent (an API that writes on a GET is not stubbed), and any +other fetch, or one with a method-override header, gets an empty 200 and is listed in +sideEffects.stubbed. Code in a remote sandbox (shell, Python, imports) is listed in +sideEffects.unchecked, since its network cannot be seen. Child workflows run dry too; custom, +Human in the loop and Wait blocks are answered whole, so the run never pauses. Agents read +memory but write none, and the run raises no workspace event. --allow sends that block's +writes (a Function's fetches included) for real (use a test resource); allowing an Agent sends +only its own tool calls, not a workflow or custom block it calls. --mock = answers a +block with fixed output, to steer a branch; a locked block cannot be mocked, and a mock is data, +so it cannot set a field the run's execution, trace or billing reads (such as cost, tokens, model +or a field starting with _). A dry run is the --source-run only of another dry run, and is never +resumed. The result is the run: runId, status (completed, failed, paused or cancelled), error, output (the workflow's final output) and blockOutputs (what --select-output named). It has no success field: diff --git a/packages/sim-cli/src/generated/v2-api.ts b/packages/sim-cli/src/generated/v2-api.ts index 4837a15594e..bd1c8a2d6cc 100644 --- a/packages/sim-cli/src/generated/v2-api.ts +++ b/packages/sim-cli/src/generated/v2-api.ts @@ -7168,12 +7168,22 @@ type ExecuteWorkflowResponseRef1 = { tool: string | null request: Record | null returned: Record + mcp: { + server: string + tool: string + } | null + dependsOnStub: boolean + readOnlyHint: boolean }> allowed: Array<{ workflowId: string blockId: string | null block: string | null tool: string | null + mcp: { + server: string + tool: string + } | null }> unchecked: Array<{ workflowId: string From 439ee54138c57ab19670590b6e273ab7ff55f350 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Wed, 25 Nov 2026 13:14:32 -0800 Subject: [PATCH 2/2] fix(workflows): dry-run placeholders skip echoed request numbers, scan code header values, and old test reports still parse --- apps/docs/openapi-v2-workflows.json | 4 +-- apps/sim/executor/execution/types.ts | 5 +-- apps/sim/lib/api/contracts/v2/workflows.ts | 4 +-- apps/sim/lib/execution/isolated-vm.ts | 5 ++- apps/sim/lib/workflow-tests/protocol.test.ts | 36 ++++++++++++++++++- apps/sim/lib/workflow-tests/protocol.ts | 11 +++--- .../application/dry-run.integration.ts | 15 ++++++-- .../workflows/dry-run/placeholders.test.ts | 9 +++++ .../sim/lib/workflows/dry-run/placeholders.ts | 19 ++++++---- .../sim/lib/workflows/dry-run/side-effects.ts | 5 +-- apps/sim/tools/dry-run.test.ts | 4 +-- apps/sim/tools/side-effects.test.ts | 7 ++++ apps/sim/tools/side-effects.ts | 1 + 13 files changed, 100 insertions(+), 25 deletions(-) diff --git a/apps/docs/openapi-v2-workflows.json b/apps/docs/openapi-v2-workflows.json index 8100ee5f1ca..3aeb83326e4 100644 --- a/apps/docs/openapi-v2-workflows.json +++ b/apps/docs/openapi-v2-workflows.json @@ -17305,7 +17305,7 @@ }, "dependsOnStub": { "type": "boolean", - "description": "True for a read that was not sent because what it would send holds a placeholder the run returned earlier (a `dry_run__` string or a number above 900000000, such as a placeholder row id), so it depends on a write that was never sent." + "description": "True for a read that was not sent because what it would send holds a placeholder the run returned earlier (a `dry_run__` string or a number above 900000000, such as a placeholder row id), so it depends on a call that was never sent." }, "readOnlyHint": { "type": "boolean", @@ -17325,7 +17325,7 @@ ], "additionalProperties": false }, - "description": "Calls that were not sent, in the order the run reached them: writes, and reads that depend on one (`dependsOnStub`)." + "description": "Calls that were not sent, in the order the run reached them: writes, every MCP call (`readOnlyHint` marks one its server declares read-only), and reads that would send a placeholder (`dependsOnStub`)." }, "allowed": { "type": "array", diff --git a/apps/sim/executor/execution/types.ts b/apps/sim/executor/execution/types.ts index 7a3bf84a8b1..6ec1fd8db5e 100644 --- a/apps/sim/executor/execution/types.ts +++ b/apps/sim/executor/execution/types.ts @@ -394,10 +394,11 @@ interface CodeNetworkRequest { /** The names of the headers it carries, never their values. */ headerNames: string[] /** - * The URL and body it sends, unredacted: only searched for the run's placeholders (a read that - * would send one is stubbed), never recorded. + * The URL, header values and body it sends, unredacted: only searched for the run's placeholders + * (a read that would send one is stubbed), never recorded. */ url: string + headerValues: string[] body: string | undefined /** * What the request would send (method, capped origin and path with query parameter names, header diff --git a/apps/sim/lib/api/contracts/v2/workflows.ts b/apps/sim/lib/api/contracts/v2/workflows.ts index 5e5a0c178fe..d91e1b0bf32 100644 --- a/apps/sim/lib/api/contracts/v2/workflows.ts +++ b/apps/sim/lib/api/contracts/v2/workflows.ts @@ -2026,7 +2026,7 @@ const v2RunSideEffectsSchema = z dependsOnStub: z .boolean() .describe( - 'True for a read that was not sent because what it would send holds a placeholder the run returned earlier (a `dry_run__` string or a number above 900000000, such as a placeholder row id), so it depends on a write that was never sent.' + 'True for a read that was not sent because what it would send holds a placeholder the run returned earlier (a `dry_run__` string or a number above 900000000, such as a placeholder row id), so it depends on a call that was never sent.' ), readOnlyHint: z .boolean() @@ -2036,7 +2036,7 @@ const v2RunSideEffectsSchema = z }) ) .describe( - 'Calls that were not sent, in the order the run reached them: writes, and reads that depend on one (`dependsOnStub`).' + 'Calls that were not sent, in the order the run reached them: writes, every MCP call (`readOnlyHint` marks one its server declares read-only), and reads that would send a placeholder (`dependsOnStub`).' ), allowed: z .array( diff --git a/apps/sim/lib/execution/isolated-vm.ts b/apps/sim/lib/execution/isolated-vm.ts index d5541ae1992..d913f6f3e83 100644 --- a/apps/sim/lib/execution/isolated-vm.ts +++ b/apps/sim/lib/execution/isolated-vm.ts @@ -82,8 +82,10 @@ interface IsolatedFetchRequest { /** As sent ({@link normalizeFetchMethod}); GET when the code named none. */ method: string url: string - /** The names of the headers it carries, never their values. */ + /** The names of the headers it carries. */ headerNames: string[] + /** Their values, which may hold credentials: for the policy to search, never to record. */ + headerValues: string[] body: string | undefined } @@ -450,6 +452,7 @@ async function decideFetch( method: fetchOptions.method ?? 'GET', url, headerNames: Object.keys(fetchOptions.headers ?? {}), + headerValues: Object.values(fetchOptions.headers ?? {}), body: typeof fetchOptions.body === 'string' ? fetchOptions.body : undefined, }) return decision === 'stub' diff --git a/apps/sim/lib/workflow-tests/protocol.test.ts b/apps/sim/lib/workflow-tests/protocol.test.ts index 72b23d6d016..a9f3662296e 100644 --- a/apps/sim/lib/workflow-tests/protocol.test.ts +++ b/apps/sim/lib/workflow-tests/protocol.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest' -import { testReplyArgsSchema } from '@/lib/workflow-tests/protocol' +import { storedTestReportSchema, testReplyArgsSchema } from '@/lib/workflow-tests/protocol' describe('testReplyArgsSchema', () => { it('keeps the error of a mock that threw', () => { @@ -18,3 +18,37 @@ describe('testReplyArgsSchema', () => { expect(testReplyArgsSchema.safeParse(reply).success).toBe(false) }) }) + +describe('storedTestReportSchema', () => { + it('still reads a report stored before a stubbed call recorded its MCP target and flags', () => { + const stored = { + topLevel: [], + tests: [], + sideEffects: { + executions: { + 'exec-1': { + stubbed: [{ workflowId: 'wf', blockId: 'b', block: 'Send', tool: 'slack', count: 1 }], + unchecked: [], + omitted: { stubbed: 0, unchecked: 0 }, + }, + }, + omittedExecutions: 0, + }, + } + + const parsed = storedTestReportSchema.parse(stored) + + expect(parsed.sideEffects?.executions['exec-1'].stubbed).toEqual([ + { + workflowId: 'wf', + blockId: 'b', + block: 'Send', + tool: 'slack', + mcp: null, + dependsOnStub: false, + readOnlyHint: false, + count: 1, + }, + ]) + }) +}) diff --git a/apps/sim/lib/workflow-tests/protocol.ts b/apps/sim/lib/workflow-tests/protocol.ts index 2485d3f0502..df9f8e5b588 100644 --- a/apps/sim/lib/workflow-tests/protocol.ts +++ b/apps/sim/lib/workflow-tests/protocol.ts @@ -140,12 +140,15 @@ const testRunSideEffectsSchema = z.object({ blockId: z.string().nullable(), block: z.string().nullable(), tool: z.string().nullable(), - /** The MCP server and tool an MCP block's call named; null for any other call. */ - mcp: z.object({ server: z.string(), tool: z.string() }).nullable(), + /** + * The MCP server and tool an MCP block's call named; null for any other call. This and the + * two flags below default for reports stored before they were recorded. + */ + mcp: z.object({ server: z.string(), tool: z.string() }).nullable().default(null), /** A read that would have sent a placeholder an earlier stub returned. */ - dependsOnStub: z.boolean(), + dependsOnStub: z.boolean().default(false), /** An MCP call whose server declares the tool read-only, unverified, so it was not sent. */ - readOnlyHint: z.boolean(), + readOnlyHint: z.boolean().default(false), /** Calls folded into this entry. */ count: z.number().int().positive(), }) diff --git a/apps/sim/lib/workflows/application/dry-run.integration.ts b/apps/sim/lib/workflows/application/dry-run.integration.ts index 184c6990b00..65d2ea3f02f 100644 --- a/apps/sim/lib/workflows/application/dry-run.integration.ts +++ b/apps/sim/lib/workflows/application/dry-run.integration.ts @@ -2285,6 +2285,11 @@ return created.id.toString()` language: 'javascript', code: `const res = await fetch('${server.url}${prefix}/code/' + ) return { status: res.status, stubbed: res.headers.get('x-sim-dry-run') }`, + }), + block('header', 'function', { + language: 'javascript', + code: `const res = await fetch('${server.url}${prefix}/header', { headers: { 'X-Record-Id': } }) +return res.headers.get('x-sim-dry-run')`, }), block('fetch', 'api', { url: `${server.url}${prefix}/api/`, method: 'GET' }), block('real', 'api', { url: `${server.url}${prefix}/api/row_8f3a2c`, method: 'GET' }), @@ -2292,22 +2297,28 @@ return { status: res.status, stubbed: res.headers.get('x-sim-dry-run') }`, [ ['start', 'save'], ['save', 'code'], - ['code', 'fetch'], + ['code', 'header'], + ['header', 'fetch'], ['fetch', 'real'], ] ) const workflowId = await saveWorkflow(fixture.state) - const result = await run(workflowId, { dry: true, selectedOutputs: ['code.result'] }) + const result = await run(workflowId, { + dry: true, + selectedOutputs: ['code.result', 'header.result'], + }) expect(result.status, JSON.stringify(result.error)).toBe('completed') expect(arrivalsUnder(prefix)).toEqual([`GET ${prefix}/api/row_8f3a2c`]) expect(result.blockOutputs?.['code.result']).toEqual({ status: 200, stubbed: 'stubbed' }) + expect(result.blockOutputs?.['header.result']).toBe('stubbed') expect( result.sideEffects?.stubbed.map((entry) => [entry.block, entry.tool, entry.dependsOnStub]) ).toEqual([ ['save', 'table_upsert_row', false], ['code', 'function_execute', true], + ['header', 'function_execute', true], ['fetch', 'http_request', true], ]) }) diff --git a/apps/sim/lib/workflows/dry-run/placeholders.test.ts b/apps/sim/lib/workflows/dry-run/placeholders.test.ts index 8b5791d5283..941ed39a0d8 100644 --- a/apps/sim/lib/workflows/dry-run/placeholders.test.ts +++ b/apps/sim/lib/workflows/dry-run/placeholders.test.ts @@ -39,4 +39,13 @@ describe('a dry run’s placeholder tokens', () => { ])('are not found in %s', (_, sent) => { expect(registered().occursIn({ sent })).toBe(false) }) + + it('leave out a number the answer echoed from its request, even one in the placeholder range', () => { + const tokens = new PlaceholderTokens() + const echoed = { row: { data: { customerId: 900_000_123 } } } + tokens.register({ row: { id: 'dry_run_row_1', data: { customerId: 900_000_123 } } }, echoed) + + expect(tokens.occursIn({ sent: '/customers/900000123' })).toBe(false) + expect(tokens.occursIn({ sent: 'dry_run_row_1' })).toBe(true) + }) }) diff --git a/apps/sim/lib/workflows/dry-run/placeholders.ts b/apps/sim/lib/workflows/dry-run/placeholders.ts index e287d88bd2d..e0a46d1c353 100644 --- a/apps/sim/lib/workflows/dry-run/placeholders.ts +++ b/apps/sim/lib/workflows/dry-run/placeholders.ts @@ -59,22 +59,27 @@ function* tokensIn(text: string): Generator { /** * The placeholders a dry run's answers returned: every `dry_run__` string (see - * `dryRunId`) and every placeholder number (see `dryRunNumber`), minted by a tool's `dryRunOutput` - * for an id the provider would assign, or by the sample for a field the request cannot know. Only - * placeholder answers are registered, so a placeholder is a value the run made up, never one a - * real call returned or the workflow was given. A read that would send one, as an id or inside + * `dryRunId`), minted by a tool's `dryRunOutput` for an id the provider would assign or by the + * sample for a field the request cannot know, and every placeholder number (see `dryRunNumber`), + * which only the sample mints. Only placeholder answers are registered, and a number the answer + * echoes from its request is not, so a placeholder is a value the run made up, never one a real + * call returned or the workflow was given. A read that would send one, as an id or inside * free text (a message quoting a placeholder title), depends on a write that was never sent. */ export class PlaceholderTokens { private readonly tokens = new Set() private readonly numbers = new Set() - /** Registers the placeholders of a placeholder answer. */ - register(returned: unknown): void { + /** + * Registers the placeholders of a placeholder answer, `returned`, except a number `echoed` (the + * part of it a tool's `dryRunOutput` echoed from the request) carries: that one was given. + */ + register(returned: unknown, echoed: unknown = null): void { + const given = new Set(leavesOf(echoed).filter((value) => typeof value === 'number')) for (const value of leavesOf(returned)) { if (this.tokens.size + this.numbers.size >= MAX_TRACKED) return if (typeof value === 'number') { - if (isPlaceholderNumber(value)) this.numbers.add(value) + if (isPlaceholderNumber(value) && !given.has(value)) this.numbers.add(value) } else if (TOKEN.test(value.toLowerCase())) { this.tokens.add(value.toLowerCase()) } diff --git a/apps/sim/lib/workflows/dry-run/side-effects.ts b/apps/sim/lib/workflows/dry-run/side-effects.ts index d227f7f2c0a..29a1a7c1fd2 100644 --- a/apps/sim/lib/workflows/dry-run/side-effects.ts +++ b/apps/sim/lib/workflows/dry-run/side-effects.ts @@ -243,7 +243,8 @@ export class WriteStubPolicy implements SideEffectPolicy { ), onRequest: async (request) => { const reads = isReadRequest(request.method, request.headerNames) - const dependsOnStub = reads && this.placeholders.occursIn([request.url, request.body]) + const dependsOnStub = + reads && this.placeholders.occursIn([request.url, request.headerValues, request.body]) if (reads && !dependsOnStub) return 'send' if (allowed && !dependsOnStub) { this.allowed.add( @@ -268,7 +269,7 @@ export class WriteStubPolicy implements SideEffectPolicy { stubCall(call: StubbedToolCall): Record { const returned = sampleToolOutput(call.toolId, call.echoed, call.discoveredOutputs) - this.placeholders.register(returned) + this.placeholders.register(returned, call.echoed) this.stubbed.add({ ...recordedSite(call), tool: call.toolId, diff --git a/apps/sim/tools/dry-run.test.ts b/apps/sim/tools/dry-run.test.ts index 5312d0c93f8..4deb1377bca 100644 --- a/apps/sim/tools/dry-run.test.ts +++ b/apps/sim/tools/dry-run.test.ts @@ -13,7 +13,7 @@ import { hubspotUpdateContactTool } from '@/tools/hubspot/update_contact' import { hubspotUpdateDealTool } from '@/tools/hubspot/update_deal' import { knowledgeUpsertDocumentTool } from '@/tools/knowledge/upsert_document' import { resendSendTool } from '@/tools/resend/send' -import { answerUnsentWrite, describeToolRequest, unsentWriteFor } from '@/tools/side-effects' +import { answerUnsentCall, describeToolRequest, unsentWriteFor } from '@/tools/side-effects' import { slackMessageTool } from '@/tools/slack/message' import type { ExecutableToolConfig } from '@/tools/types' @@ -48,7 +48,7 @@ async function placeholderFor(toolId: string, params: Record) { } as ExecutionContext, }) if (!write) throw new Error('The policy sent the write') - const response = await answerUnsentWrite(write, { + const response = await answerUnsentCall(write, { params: callParams, registry: new ResolvedSecretTraceRegistry(), describe: (masked) => describeToolRequest(tool, masked), diff --git a/apps/sim/tools/side-effects.test.ts b/apps/sim/tools/side-effects.test.ts index de972f08376..c50111cd528 100644 --- a/apps/sim/tools/side-effects.test.ts +++ b/apps/sim/tools/side-effects.test.ts @@ -221,6 +221,7 @@ describe('code a dry run runs', () => { method: 'POST', url: 'https://hook.example/x', headerNames: [], + headerValues: [], body, }) @@ -241,7 +242,10 @@ describe('code a dry run runs', () => { const decision = await code.onRequest({ method: 'POST', + url: 'https://hook.example/x', headerNames: [], + headerValues: [], + body: undefined, describe: async () => { throw new Error('redaction failed') }, @@ -262,7 +266,10 @@ describe('code a dry run runs', () => { let described = 0 const request = { method: 'POST', + url: 'https://hook.example/x', headerNames: [], + headerValues: [], + body: undefined, describe: async () => { described++ return { method: 'POST' } diff --git a/apps/sim/tools/side-effects.ts b/apps/sim/tools/side-effects.ts index b47fc9172ff..1cfbd4ee55c 100644 --- a/apps/sim/tools/side-effects.ts +++ b/apps/sim/tools/side-effects.ts @@ -544,6 +544,7 @@ export function codeNetworkFor(input: { method: request.method, headerNames: request.headerNames, url: request.url, + headerValues: request.headerValues, body: request.body, describe: async () => { const redacted = await redactSideEffectPayload({