From d1dc9e0efcda68d06dc7fb29038e8bcac61f36d6 Mon Sep 17 00:00:00 2001 From: doudouOUC Date: Mon, 3 Aug 2026 00:17:14 +0800 Subject: [PATCH 1/2] fix(core): Avoid replaying unsafe MCP tool calls Co-authored-by: Qwen-Coder --- docs/design/mcp-safe-replay.md | 34 +++ docs/developers/tools/mcp-server.md | 2 + docs/users/features/mcp.md | 8 + packages/core/src/tools/mcp-tool.test.ts | 314 ++++++++++++++++++++++- packages/core/src/tools/mcp-tool.ts | 33 +++ 5 files changed, 382 insertions(+), 9 deletions(-) create mode 100644 docs/design/mcp-safe-replay.md diff --git a/docs/design/mcp-safe-replay.md b/docs/design/mcp-safe-replay.md new file mode 100644 index 00000000000..7d2ff287ba5 --- /dev/null +++ b/docs/design/mcp-safe-replay.md @@ -0,0 +1,34 @@ +# Safe replay after MCP connection loss + +## Problem + +An MCP tool can complete a side effect before its response connection fails. Reconnecting and sending the same `tools/call` again can therefore repeat a write while the user sees only the second result. MCP tool annotations are optional and default to non-idempotent behavior, so missing annotations cannot justify automatic replay. + +## Replay policy + +Qwen Code automatically replays a failed invocation only when all of the following are true: + +- The failure is classified as a connection loss by the existing MCP connection checks. +- The MCP server has `trust: true`. +- The current workspace passes the workspace trust gate. +- The tool declares `idempotentHint: true`, or declares `readOnlyHint: true` without `destructiveHint: true` or `idempotentHint: false`. + +Conflicting annotations are not treated as safe. In particular, a tool that declares itself read-only while also declaring destructive or non-idempotent behavior is not replayed. An explicit idempotency declaration can cover a mutating operation, but it does not override contradictory read-only annotations. + +The same decision is applied to both execution paths: the direct MCP client used for progress-aware calls and the callable fallback. Abort errors, non-connection errors, and MCP `isError: true` protocol results retain their existing behavior. + +## Failure behavior + +When a connection failure is not safe to replay, the current invocation does not reconnect or construct a second invocation. It returns a stable error explaining that the operation may have completed and must not be retried automatically. The error does not include tool arguments or the upstream transport error. + +Connection recovery for later, independent calls remains the responsibility of the existing health monitor, an explicit reconnect, or normal discovery on a later call. Safe calls retain the existing bounded reconnect behavior. + +## Compatibility + +This is an intentional conservative change. Tools without annotations no longer receive transparent connection-loss replay, even when an older Qwen Code release retried them. Servers that want replay must provide accurate annotations, and administrators must opt into server trust in a trusted workspace. + +MCP annotations are behavior hints supplied by the server, not an authorization boundary. Qwen Code uses them for replay only after both server and workspace trust gates pass. + +## Verification + +Tests cover the direct client and callable fallback, safe idempotent and read-only declarations, missing and contradictory annotations, both trust gates, connection error classification, aborts, protocol errors, reconnect failure, and the retry limit. A separate local E2E record exercises a server that commits a side effect before dropping the response connection and verifies that an unsafe call reaches the server only once. diff --git a/docs/developers/tools/mcp-server.md b/docs/developers/tools/mcp-server.md index 73cbba4f38f..4e8121841d4 100644 --- a/docs/developers/tools/mcp-server.md +++ b/docs/developers/tools/mcp-server.md @@ -37,6 +37,8 @@ Each discovered MCP tool is wrapped in a `DiscoveredMCPTool` instance that: - **Processes responses** for both the LLM context and user display - **Maintains connection state** and handles timeouts +After a connection loss, the current invocation is replayed only for a trusted server in a trusted workspace when the tool explicitly declares `idempotentHint: true`, or declares `readOnlyHint: true` without a conflicting `destructiveHint: true` or `idempotentHint: false`. Missing, conflicting, or untrusted annotations are treated as unsafe because the server may have completed a side effect before the response was lost. Tool authors should publish accurate MCP annotations; administrators should still verify them before enabling server trust. + ### Transport Mechanisms The CLI supports three MCP transport types: diff --git a/docs/users/features/mcp.md b/docs/users/features/mcp.md index d2cc1547a41..b06fe6d6d64 100644 --- a/docs/users/features/mcp.md +++ b/docs/users/features/mcp.md @@ -273,6 +273,14 @@ environment. This is kept as an escape hatch for at least one release. - **Server trust** (`trust: true`): bypasses confirmation prompts for that server (use sparingly). +### Connection-loss replay + +Qwen Code only reconnects and replays the current MCP tool call when the server has `trust: true`, the workspace is trusted, and the tool explicitly declares either `idempotentHint: true` or a consistent read-only annotation. Read-only annotations conflict with `destructiveHint: true` or `idempotentHint: false` and are not replayed. + +Calls with missing annotations, conflicting annotations, an untrusted server, or an untrusted workspace are not replayed after a connection failure. Qwen Code reports that the result may be unknown because the server could have completed the operation before the response was lost. Verify the outcome before trying again. This conservative behavior can differ from earlier releases that transparently retried unannotated tools. + +Annotations are server-provided behavior hints, not permissions or an authorization boundary. Only configure `trust: true` for servers you control and whose annotations you have verified. + ### OAuth authentication Qwen Code supports OAuth 2.0 authentication for MCP servers. This is useful when accessing remote servers that require authentication. diff --git a/packages/core/src/tools/mcp-tool.test.ts b/packages/core/src/tools/mcp-tool.test.ts index f613b9089f3..381afcb4875 100644 --- a/packages/core/src/tools/mcp-tool.test.ts +++ b/packages/core/src/tools/mcp-tool.test.ts @@ -12,6 +12,7 @@ import { DiscoveredMCPTool, generateValidName, type McpDirectClient, + type McpToolAnnotations, } from './mcp-tool.js'; import type { ToolResult } from './tools.js'; import { ToolConfirmationOutcome } from './tools.js'; @@ -1494,6 +1495,11 @@ describe('DiscoveredMCPTool', () => { }); describe('auto-reconnect on connection error', () => { + const idempotentAnnotations = { idempotentHint: true } as const; + const readOnlyAnnotations = { readOnlyHint: true } as const; + const unsafeReplayErrorMessage = + 'MCP tool execution may have completed before the connection failed. Automatic replay was skipped because the call was not declared safe to replay. Do not retry automatically; verify the outcome before trying again.'; + it('should attempt reconnect and retry on connection error', async () => { const params = { param: 'test' }; const reconnectServerToolName = 'literature.search_pubmed'; @@ -1515,10 +1521,13 @@ describe('DiscoveredMCPTool', () => { reconnectServerToolName, baseDescription, inputSchema, - undefined, + true, undefined, undefined, newMockMcpClient, + undefined, + undefined, + idempotentAnnotations, ); const discoverToolsForServer = vi.fn().mockResolvedValue(undefined); @@ -1544,10 +1553,13 @@ describe('DiscoveredMCPTool', () => { reconnectServerToolName, baseDescription, inputSchema, - undefined, + true, undefined, mockConfig as any, mockMcpClient, + undefined, + undefined, + idempotentAnnotations, ); const invocation = reconnectTool.build(params); @@ -1560,6 +1572,194 @@ describe('DiscoveredMCPTool', () => { expect(result.llmContent).toEqual([{ text: 'Success after reconnect' }]); }); + it('should reconnect consistent read-only calls through the callable fallback', async () => { + const initialCallable = { + tool: vi.fn(), + callTool: vi.fn().mockRejectedValueOnce(new Error('Connection closed')), + } as unknown as Mocked; + const retryCallable = { + tool: vi.fn(), + callTool: vi.fn().mockResolvedValueOnce([ + { + functionResponse: { + name: serverToolName, + response: { content: [{ type: 'text', text: 'OK' }] }, + }, + }, + ]), + } as unknown as Mocked; + const retryTool = new DiscoveredMCPTool( + retryCallable, + serverName, + serverToolName, + baseDescription, + inputSchema, + true, + undefined, + undefined, + undefined, + undefined, + undefined, + readOnlyAnnotations, + ); + const discoverToolsForServer = vi.fn().mockResolvedValue(undefined); + const mockConfig = { + isTrustedFolder: () => true, + getToolRegistry: () => ({ + discoverToolsForServer, + ensureTool: vi.fn().mockResolvedValue(retryTool), + }), + getTruncateToolOutputThreshold: () => 0, + getTruncateToolOutputLines: () => 0, + }; + const reconnectTool = new DiscoveredMCPTool( + initialCallable, + serverName, + serverToolName, + baseDescription, + inputSchema, + true, + undefined, + mockConfig as any, + undefined, + undefined, + undefined, + readOnlyAnnotations, + ); + + updateMCPServerStatus(serverName, MCPServerStatus.CONNECTED); + const result = await reconnectTool + .build({ param: 'test' }) + .execute(new AbortController().signal); + + expect(initialCallable.callTool).toHaveBeenCalledTimes(1); + expect(retryCallable.callTool).toHaveBeenCalledTimes(1); + expect(discoverToolsForServer).toHaveBeenCalledTimes(1); + expect(result.llmContent).toEqual([{ text: 'OK' }]); + }); + + it('should not replay unsafe calls through the callable fallback', async () => { + const initialCallable = { + tool: vi.fn(), + callTool: vi.fn().mockRejectedValueOnce(new Error('Connection closed')), + } as unknown as Mocked; + const discoverToolsForServer = vi.fn(); + const mockConfig = { + isTrustedFolder: () => true, + getToolRegistry: () => ({ + discoverToolsForServer, + ensureTool: vi.fn(), + }), + }; + const unsafeTool = new DiscoveredMCPTool( + initialCallable, + serverName, + serverToolName, + baseDescription, + inputSchema, + true, + undefined, + mockConfig as any, + undefined, + undefined, + undefined, + { idempotentHint: false }, + ); + + updateMCPServerStatus(serverName, MCPServerStatus.CONNECTED); + await expect( + unsafeTool + .build({ param: 'test' }) + .execute(new AbortController().signal), + ).rejects.toThrow(unsafeReplayErrorMessage); + + expect(initialCallable.callTool).toHaveBeenCalledTimes(1); + expect(discoverToolsForServer).not.toHaveBeenCalled(); + }); + + it.each<{ + name: string; + trust: boolean | undefined; + trustedFolder: boolean; + annotations: McpToolAnnotations | undefined; + }>([ + { + name: 'missing annotations', + trust: true, + trustedFolder: true, + annotations: undefined, + }, + { + name: 'explicitly non-idempotent annotations', + trust: true, + trustedFolder: true, + annotations: { idempotentHint: false }, + }, + { + name: 'conflicting read-only and destructive annotations', + trust: true, + trustedFolder: true, + annotations: { readOnlyHint: true, destructiveHint: true }, + }, + { + name: 'conflicting read-only and non-idempotent annotations', + trust: true, + trustedFolder: true, + annotations: { readOnlyHint: true, idempotentHint: false }, + }, + { + name: 'an untrusted server', + trust: false, + trustedFolder: true, + annotations: idempotentAnnotations, + }, + { + name: 'an untrusted workspace', + trust: true, + trustedFolder: false, + annotations: idempotentAnnotations, + }, + ])('should not replay $name', async (testCase) => { + const initialClient: McpDirectClient = { + callTool: vi + .fn() + .mockRejectedValueOnce( + new Error('Connection closed after side effect completed'), + ), + }; + const discoverToolsForServer = vi.fn(); + const ensureTool = vi.fn(); + const mockConfig = { + isTrustedFolder: () => testCase.trustedFolder, + getToolRegistry: () => ({ discoverToolsForServer, ensureTool }), + }; + const unsafeTool = new DiscoveredMCPTool( + mockCallableToolInstance, + serverName, + serverToolName, + baseDescription, + inputSchema, + testCase.trust, + undefined, + mockConfig as any, + initialClient, + undefined, + undefined, + testCase.annotations, + ); + + updateMCPServerStatus(serverName, MCPServerStatus.CONNECTED); + await expect( + unsafeTool + .build({ param: 'test' }) + .execute(new AbortController().signal), + ).rejects.toThrow(unsafeReplayErrorMessage); + + expect(initialClient.callTool).toHaveBeenCalledTimes(1); + expect(discoverToolsForServer).not.toHaveBeenCalled(); + expect(ensureTool).not.toHaveBeenCalled(); + }); + it('should not retry on non-connection errors', async () => { const params = { param: 'test' }; const mockMcpClient: McpDirectClient = { @@ -1682,7 +1882,85 @@ describe('DiscoveredMCPTool', () => { expect(retryClient.callTool).not.toHaveBeenCalled(); }); - it('should not retry after reconnection attempt fails', async () => { + it('should not reconnect for an MCP isError result', async () => { + const initialClient: McpDirectClient = { + callTool: vi.fn().mockResolvedValueOnce({ + content: [{ type: 'text', text: 'Validation failed' }], + isError: true, + }), + }; + const discoverToolsForServer = vi.fn(); + const mockConfig = { + isTrustedFolder: () => true, + getToolRegistry: () => ({ + discoverToolsForServer, + ensureTool: vi.fn(), + }), + getTruncateToolOutputThreshold: () => 0, + getTruncateToolOutputLines: () => 0, + }; + const safeTool = new DiscoveredMCPTool( + mockCallableToolInstance, + serverName, + serverToolName, + baseDescription, + inputSchema, + true, + undefined, + mockConfig as any, + initialClient, + undefined, + undefined, + idempotentAnnotations, + ); + + const result = await safeTool + .build({ param: 'test' }) + .execute(new AbortController().signal); + + expect(result.error?.type).toBe(ToolErrorType.MCP_TOOL_ERROR); + expect(initialClient.callTool).toHaveBeenCalledTimes(1); + expect(discoverToolsForServer).not.toHaveBeenCalled(); + }); + + it('should preserve the connection error when reconnect discovery fails', async () => { + const connectionError = new Error('Connection closed'); + const initialClient: McpDirectClient = { + callTool: vi.fn().mockRejectedValueOnce(connectionError), + }; + const discoverToolsForServer = vi + .fn() + .mockRejectedValueOnce(new Error('Discovery failed')); + const ensureTool = vi.fn(); + const mockConfig = { + isTrustedFolder: () => true, + getToolRegistry: () => ({ discoverToolsForServer, ensureTool }), + }; + const safeTool = new DiscoveredMCPTool( + mockCallableToolInstance, + serverName, + serverToolName, + baseDescription, + inputSchema, + true, + undefined, + mockConfig as any, + initialClient, + undefined, + undefined, + idempotentAnnotations, + ); + + await expect( + safeTool.build({ param: 'test' }).execute(new AbortController().signal), + ).rejects.toBe(connectionError); + + expect(initialClient.callTool).toHaveBeenCalledTimes(1); + expect(discoverToolsForServer).toHaveBeenCalledTimes(1); + expect(ensureTool).not.toHaveBeenCalled(); + }); + + it('should stop after the maximum reconnection retries', async () => { const params = { param: 'test' }; const mockMcpClient: McpDirectClient = { callTool: vi.fn(), @@ -1698,10 +1976,13 @@ describe('DiscoveredMCPTool', () => { serverToolName, baseDescription, inputSchema, - undefined, + true, undefined, undefined, secondMockMcpClient, + undefined, + undefined, + idempotentAnnotations, ); const discoverToolsForServer = vi.fn().mockResolvedValue(undefined); @@ -1723,10 +2004,13 @@ describe('DiscoveredMCPTool', () => { serverToolName, baseDescription, inputSchema, - undefined, + true, undefined, mockConfig as any, mockMcpClient, + undefined, + undefined, + idempotentAnnotations, ); const invocation = reconnectTool.build(params); @@ -1770,10 +2054,13 @@ describe('DiscoveredMCPTool', () => { serverToolName, baseDescription, inputSchema, - undefined, + true, undefined, undefined, newMockMcpClient, + undefined, + undefined, + idempotentAnnotations, ); const discoverToolsForServer = vi.fn().mockResolvedValue(undefined); @@ -1793,10 +2080,13 @@ describe('DiscoveredMCPTool', () => { serverToolName, baseDescription, inputSchema, - undefined, + true, undefined, mockConfig as any, mockMcpClient, + undefined, + undefined, + idempotentAnnotations, ); const invocation = reconnectTool.build(params); @@ -1829,10 +2119,13 @@ describe('DiscoveredMCPTool', () => { serverToolName, baseDescription, inputSchema, - undefined, + true, undefined, undefined, newMockMcpClient, + undefined, + undefined, + idempotentAnnotations, ); const discoverToolsForServer = vi.fn().mockResolvedValue(undefined); @@ -1854,10 +2147,13 @@ describe('DiscoveredMCPTool', () => { serverToolName, baseDescription, inputSchema, - undefined, + true, undefined, mockConfig as any, mockMcpClient, + undefined, + undefined, + idempotentAnnotations, ); const invocation = reconnectTool.build(params); diff --git a/packages/core/src/tools/mcp-tool.ts b/packages/core/src/tools/mcp-tool.ts index 19baf76a631..39bba1a782c 100644 --- a/packages/core/src/tools/mcp-tool.ts +++ b/packages/core/src/tools/mcp-tool.ts @@ -143,6 +143,8 @@ class DiscoveredMCPToolInvocation extends BaseToolInvocation< ToolResult > { private static readonly MAX_RECONNECT_RETRIES = 3; + private static readonly UNSAFE_REPLAY_ERROR_MESSAGE = + 'MCP tool execution may have completed before the connection failed. Automatic replay was skipped because the call was not declared safe to replay. Do not retry automatically; verify the outcome before trying again.'; constructor( private readonly mcpTool: CallableTool, @@ -263,6 +265,14 @@ class DiscoveredMCPToolInvocation extends BaseToolInvocation< throw error; } + if (!this.cliConfig) { + throw error; + } + + if (!this.canSafelyReplay()) { + throw new Error(DiscoveredMCPToolInvocation.UNSAFE_REPLAY_ERROR_MESSAGE); + } + if (this.retryCount < DiscoveredMCPToolInvocation.MAX_RECONNECT_RETRIES) { debugLogger.info( `Reconnection attempt ${this.retryCount + 1}/${DiscoveredMCPToolInvocation.MAX_RECONNECT_RETRIES} for MCP server '${this.serverName}'`, @@ -299,6 +309,29 @@ class DiscoveredMCPToolInvocation extends BaseToolInvocation< throw error; } + private canSafelyReplay(): boolean { + if ( + this.trust !== true || + this.cliConfig?.isTrustedFolder() !== true || + !this.annotations + ) { + return false; + } + + if ( + this.annotations.readOnlyHint === true && + (this.annotations.destructiveHint === true || + this.annotations.idempotentHint === false) + ) { + return false; + } + + return ( + this.annotations.idempotentHint === true || + this.annotations.readOnlyHint === true + ); + } + private shouldAttemptReconnect(error: unknown): boolean { if (isAbortError(error)) { return false; From 15bf1e492341c6f123becd8a8b6bfc840123aee1 Mon Sep 17 00:00:00 2001 From: doudouOUC Date: Mon, 3 Aug 2026 00:41:55 +0800 Subject: [PATCH 2/2] fix(core): Revalidate MCP replay after reconnect Co-authored-by: Qwen-Coder --- docs/design/mcp-safe-replay.md | 6 +- docs/developers/tools/mcp-server.md | 13 ++-- docs/users/configuration/settings.md | 2 +- docs/users/features/mcp.md | 6 +- packages/cli/src/commands/mcp/add.ts | 2 +- packages/core/src/tools/mcp-tool.test.ts | 92 +++++++++++++++++++++++- packages/core/src/tools/mcp-tool.ts | 11 ++- 7 files changed, 115 insertions(+), 17 deletions(-) diff --git a/docs/design/mcp-safe-replay.md b/docs/design/mcp-safe-replay.md index 7d2ff287ba5..a78fe8062a0 100644 --- a/docs/design/mcp-safe-replay.md +++ b/docs/design/mcp-safe-replay.md @@ -17,11 +17,13 @@ Conflicting annotations are not treated as safe. In particular, a tool that decl The same decision is applied to both execution paths: the direct MCP client used for progress-aware calls and the callable fallback. Abort errors, non-connection errors, and MCP `isError: true` protocol results retain their existing behavior. +After reconnecting, Qwen Code applies the same trust and annotation checks to the newly discovered tool before sending the replay. It does not carry a previous server process's trust or annotations into the new invocation. + ## Failure behavior When a connection failure is not safe to replay, the current invocation does not reconnect or construct a second invocation. It returns a stable error explaining that the operation may have completed and must not be retried automatically. The error does not include tool arguments or the upstream transport error. -Connection recovery for later, independent calls remains the responsibility of the existing health monitor, an explicit reconnect, or normal discovery on a later call. Safe calls retain the existing bounded reconnect behavior. +Connection recovery for later, independent calls remains the responsibility of the existing health monitor, an explicit reconnect, or the normal discovery lifecycle. Safe calls retain the existing bounded reconnect behavior. ## Compatibility @@ -31,4 +33,4 @@ MCP annotations are behavior hints supplied by the server, not an authorization ## Verification -Tests cover the direct client and callable fallback, safe idempotent and read-only declarations, missing and contradictory annotations, both trust gates, connection error classification, aborts, protocol errors, reconnect failure, and the retry limit. A separate local E2E record exercises a server that commits a side effect before dropping the response connection and verifies that an unsafe call reaches the server only once. +Tests cover the direct client and callable fallback, safe idempotent and read-only declarations, missing and contradictory annotations, both trust gates, re-discovered tools that lose trust or annotations, connection error classification, aborts, protocol errors, reconnect failure, and the retry limit. A separate local E2E record exercises a server that commits a side effect before dropping the response connection and verifies that an unsafe call reaches the server only once. diff --git a/docs/developers/tools/mcp-server.md b/docs/developers/tools/mcp-server.md index 4e8121841d4..519c0f7a6a3 100644 --- a/docs/developers/tools/mcp-server.md +++ b/docs/developers/tools/mcp-server.md @@ -37,7 +37,7 @@ Each discovered MCP tool is wrapped in a `DiscoveredMCPTool` instance that: - **Processes responses** for both the LLM context and user display - **Maintains connection state** and handles timeouts -After a connection loss, the current invocation is replayed only for a trusted server in a trusted workspace when the tool explicitly declares `idempotentHint: true`, or declares `readOnlyHint: true` without a conflicting `destructiveHint: true` or `idempotentHint: false`. Missing, conflicting, or untrusted annotations are treated as unsafe because the server may have completed a side effect before the response was lost. Tool authors should publish accurate MCP annotations; administrators should still verify them before enabling server trust. +After a connection loss, the current invocation is replayed only for a trusted server in a trusted workspace when the tool explicitly declares `idempotentHint: true`, or declares `readOnlyHint: true` without a conflicting `destructiveHint: true` or `idempotentHint: false`. Missing or conflicting annotations, and annotations from an untrusted server or workspace, are treated as unsafe because the server may have completed a side effect before the response was lost. Tool authors should publish accurate MCP annotations; administrators should still verify them before enabling server trust. ### Transport Mechanisms @@ -116,7 +116,7 @@ Each server configuration supports the following properties: - **`env`** (object): Environment variables for the server process. Values can reference environment variables using `$VAR_NAME` or `${VAR_NAME}` syntax - **`cwd`** (string): Working directory for Stdio transport - **`timeout`** (number): Request timeout in milliseconds (default: 600,000ms = 10 minutes) -- **`trust`** (boolean): When `true`, bypasses all tool call confirmations for this server (default: `false`) +- **`trust`** (boolean): When `true`, bypasses tool call confirmations for this server in a trusted workspace (default: `false`) - **`includeTools`** (string[]): List of tool names to include from this MCP server. When specified, only the tools listed here will be available from this server (allowlist behavior). If not specified, all tools from the server are enabled by default. - **`excludeTools`** (string[]): List of tool names to exclude from this MCP server. Tools listed here will not be available to the model, even if they are exposed by the server. **Note:** `excludeTools` takes precedence over `includeTools` - if a tool is in both lists, it will be excluded. - **`targetAudience`** (string): The OAuth Client ID allowlisted on the IAP-protected application you are trying to access. Used with `authProviderType: 'service_account_impersonation'`. @@ -448,9 +448,10 @@ Each `DiscoveredMCPTool` implements sophisticated confirmation logic: #### Trust-based Bypass ```typescript -if (this.trust) { - return false; // No confirmation needed +if (this.trust === true && this.cliConfig?.isTrustedFolder()) { + return 'allow'; } +return 'ask'; ``` #### Dynamic Allow-listing @@ -620,7 +621,7 @@ The MCP integration tracks several states: ### Security Considerations -- **Trust settings:** The `trust` option bypasses all confirmation dialogs. Use cautiously and only for servers you completely control +- **Trust settings:** The `trust` option bypasses tool confirmation dialogs only in a trusted workspace. Use cautiously and only for servers you completely control - **Access tokens:** Be security-aware when configuring environment variables containing API keys or tokens - **Sandbox compatibility:** When using sandboxing, ensure MCP servers are available within the sandbox environment - **Private data:** Using broadly scoped personal access tokens can lead to information leakage between repositories @@ -791,7 +792,7 @@ qwen mcp add [options] [args...] - `-e, --env`: Set environment variables (e.g. -e KEY=value). - `-H, --header`: Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123"). - `--timeout`: Set connection timeout in milliseconds. -- `--trust`: Trust the server (bypass all tool call confirmation prompts). +- `--trust`: Trust the server (bypass its tool call confirmations in a trusted workspace). - `--description`: Set the description for the server. - `--include-tools`: A comma-separated list of tools to include. - `--exclude-tools`: A comma-separated list of tools to exclude. diff --git a/docs/users/configuration/settings.md b/docs/users/configuration/settings.md index 0591a099d99..1fbcce738c6 100644 --- a/docs/users/configuration/settings.md +++ b/docs/users/configuration/settings.md @@ -593,7 +593,7 @@ Configures connections to one or more Model-Context Protocol (MCP) servers for d | `mcpServers..httpUrl` | string | The URL of an MCP server that uses streamable HTTP for communication. | Yes | | `mcpServers..headers` | object | A map of HTTP headers to send with requests to `url` or `httpUrl`. | Yes | | `mcpServers..timeout` | number | Timeout in milliseconds for requests to this MCP server. | Yes | -| `mcpServers..trust` | boolean | Trust this server and bypass all tool call confirmations. | Yes | +| `mcpServers..trust` | boolean | Trust this server and bypass its tool call confirmations in a trusted workspace. | Yes | | `mcpServers..description` | string | A brief description of the server, which may be used for display purposes. | Yes | | `mcpServers..includeTools` | array of strings | List of tool names to include from this MCP server. When specified, only the tools listed here will be available from this server (allowlist behavior). If not specified, all tools from the server are enabled by default. | Yes | | `mcpServers..excludeTools` | array of strings | List of tool names to exclude from this MCP server. Tools listed here will not be available to the model, even if they are exposed by the server. **Note:** `excludeTools` takes precedence over `includeTools` - if a tool is in both lists, it will be excluded. | Yes | diff --git a/docs/users/features/mcp.md b/docs/users/features/mcp.md index b06fe6d6d64..3c58396ee4b 100644 --- a/docs/users/features/mcp.md +++ b/docs/users/features/mcp.md @@ -271,7 +271,7 @@ environment. This is kept as an escape hatch for at least one release. ### Trust (skip confirmations) -- **Server trust** (`trust: true`): bypasses confirmation prompts for that server (use sparingly). +- **Server trust** (`trust: true`): bypasses confirmation prompts for that server only in a trusted workspace (use sparingly). ### Connection-loss replay @@ -461,7 +461,7 @@ Optional: | `env` | object | Environment variables for the server process. Values can reference environment variables using `$VAR_NAME` or `${VAR_NAME}` syntax | | `cwd` | string | Working directory for Stdio transport | | `timeout` | number
(default: 600,000) | Request timeout in milliseconds (default: 600,000ms = 10 minutes) | -| `trust` | boolean
(default: false) | When `true`, bypasses all tool call confirmations for this server (default: `false`) | +| `trust` | boolean
(default: false) | When `true`, bypasses tool call confirmations for this server in a trusted workspace (default: `false`) | | `includeTools` | array | List of tool names to include from this MCP server. When specified, only the tools listed here will be available from this server (allowlist behavior). If not specified, all tools from the server are enabled by default. | | `excludeTools` | array | List of tool names to exclude from this MCP server. Tools listed here will not be available to the model, even if they are exposed by the server.
Note: `excludeTools` takes precedence over `includeTools` - if a tool is in both lists, it will be excluded. | | `targetAudience` | string | The OAuth Client ID allowlisted on the IAP-protected application you are trying to access. Used with `authProviderType: 'service_account_impersonation'`. | @@ -489,7 +489,7 @@ qwen mcp add [options] [args...] | `-e`, `--env` | Set environment variables. | — | `-e KEY=value` | | `-H`, `--header` | Set HTTP headers for SSE and HTTP transports. | — | `-H "X-Api-Key: abc123"` | | `--timeout` | Set connection timeout in milliseconds. | — | `--timeout 30000` | -| `--trust` | Trust the server (bypass all tool call confirmation prompts). | — (`false`) | `--trust` | +| `--trust` | Trust the server; skip confirmations in trusted workspaces. | — (`false`) | `--trust` | | `--description` | Set the description for the server. | — | `--description "Local tools"` | | `--include-tools` | A comma-separated list of tools to include. | all tools included | `--include-tools mytool,othertool` | | `--exclude-tools` | A comma-separated list of tools to exclude. | none | `--exclude-tools mytool` | diff --git a/packages/cli/src/commands/mcp/add.ts b/packages/cli/src/commands/mcp/add.ts index b316cd8f146..30a900497f6 100644 --- a/packages/cli/src/commands/mcp/add.ts +++ b/packages/cli/src/commands/mcp/add.ts @@ -249,7 +249,7 @@ export const addCommand: CommandModule = { }) .option('trust', { describe: - 'Trust the server (bypass all tool call confirmation prompts)', + 'Trust the server (bypass its tool call confirmations in a trusted workspace)', type: 'boolean', }) .option('description', { diff --git a/packages/core/src/tools/mcp-tool.test.ts b/packages/core/src/tools/mcp-tool.test.ts index 381afcb4875..9bdee70e6fe 100644 --- a/packages/core/src/tools/mcp-tool.test.ts +++ b/packages/core/src/tools/mcp-tool.test.ts @@ -1498,7 +1498,7 @@ describe('DiscoveredMCPTool', () => { const idempotentAnnotations = { idempotentHint: true } as const; const readOnlyAnnotations = { readOnlyHint: true } as const; const unsafeReplayErrorMessage = - 'MCP tool execution may have completed before the connection failed. Automatic replay was skipped because the call was not declared safe to replay. Do not retry automatically; verify the outcome before trying again.'; + 'MCP tool execution may have completed before the connection failed. Automatic replay was skipped because the call could not be verified as safe to replay. Do not retry automatically; verify the outcome before trying again.'; it('should attempt reconnect and retry on connection error', async () => { const params = { param: 'test' }; @@ -1572,6 +1572,96 @@ describe('DiscoveredMCPTool', () => { expect(result.llmContent).toEqual([{ text: 'Success after reconnect' }]); }); + it.each<{ + name: string; + trust: boolean; + trustedFolderAfterReconnect: boolean; + annotations: McpToolAnnotations | undefined; + }>([ + { + name: 'loses its annotations', + trust: true, + trustedFolderAfterReconnect: true, + annotations: undefined, + }, + { + name: 'is no longer trusted', + trust: false, + trustedFolderAfterReconnect: true, + annotations: idempotentAnnotations, + }, + { + name: 'is now in an untrusted workspace', + trust: true, + trustedFolderAfterReconnect: false, + annotations: idempotentAnnotations, + }, + ])( + 'should not replay when the re-discovered tool $name', + async (testCase) => { + const initialClient: McpDirectClient = { + callTool: vi + .fn() + .mockRejectedValueOnce(new Error('Connection closed')), + }; + const retryClient: McpDirectClient = { + callTool: vi.fn().mockResolvedValueOnce({ + content: [{ type: 'text', text: 'Unexpected replay' }], + }), + }; + const rediscoveredTool = new DiscoveredMCPTool( + mockCallableToolInstance, + serverName, + serverToolName, + baseDescription, + inputSchema, + testCase.trust, + undefined, + undefined, + retryClient, + undefined, + undefined, + testCase.annotations, + ); + const discoverToolsForServer = vi.fn().mockResolvedValue(undefined); + const ensureTool = vi.fn().mockResolvedValue(rediscoveredTool); + const isTrustedFolder = vi + .fn() + .mockReturnValueOnce(true) + .mockReturnValue(testCase.trustedFolderAfterReconnect); + const mockConfig = { + isTrustedFolder, + getToolRegistry: () => ({ discoverToolsForServer, ensureTool }), + }; + const originalTool = new DiscoveredMCPTool( + mockCallableToolInstance, + serverName, + serverToolName, + baseDescription, + inputSchema, + true, + undefined, + mockConfig as any, + initialClient, + undefined, + undefined, + idempotentAnnotations, + ); + + updateMCPServerStatus(serverName, MCPServerStatus.CONNECTED); + await expect( + originalTool + .build({ param: 'test' }) + .execute(new AbortController().signal), + ).rejects.toThrow(unsafeReplayErrorMessage); + + expect(initialClient.callTool).toHaveBeenCalledTimes(1); + expect(discoverToolsForServer).toHaveBeenCalledTimes(1); + expect(ensureTool).toHaveBeenCalledTimes(1); + expect(retryClient.callTool).not.toHaveBeenCalled(); + }, + ); + it('should reconnect consistent read-only calls through the callable fallback', async () => { const initialCallable = { tool: vi.fn(), diff --git a/packages/core/src/tools/mcp-tool.ts b/packages/core/src/tools/mcp-tool.ts index 39bba1a782c..9fcda0a4319 100644 --- a/packages/core/src/tools/mcp-tool.ts +++ b/packages/core/src/tools/mcp-tool.ts @@ -144,7 +144,7 @@ class DiscoveredMCPToolInvocation extends BaseToolInvocation< > { private static readonly MAX_RECONNECT_RETRIES = 3; private static readonly UNSAFE_REPLAY_ERROR_MESSAGE = - 'MCP tool execution may have completed before the connection failed. Automatic replay was skipped because the call was not declared safe to replay. Do not retry automatically; verify the outcome before trying again.'; + 'MCP tool execution may have completed before the connection failed. Automatic replay was skipped because the call could not be verified as safe to replay. Do not retry automatically; verify the outcome before trying again.'; constructor( private readonly mcpTool: CallableTool, @@ -286,16 +286,21 @@ class DiscoveredMCPToolInvocation extends BaseToolInvocation< this.displayName, newTool.name, newTool.permissionAliases, - this.trust, + newTool.trust, this.params, this.cliConfig, newTool['mcpClient'], this.mcpTimeout, this.mcpToolIdleTimeoutMs, - this.annotations, + newTool.annotations, newTool['allowInvocationContext'] === true, this.retryCount + 1, ); + if (!newInvocation.canSafelyReplay()) { + throw new Error( + DiscoveredMCPToolInvocation.UNSAFE_REPLAY_ERROR_MESSAGE, + ); + } return newInvocation.execute(signal, updateOutput); } } else if (