From 6020ef0daf4ea9e8389c909512693b1a0f4345e2 Mon Sep 17 00:00:00 2001 From: Laxman Reddy Aileni Date: Tue, 17 Nov 2026 02:23:15 +0000 Subject: [PATCH 1/3] fix(amazonq): require approval of the configuration that an MCP registry server starts with Install from the MCP registry now shows the command, arguments, environment variables, URL and headers of the server before it installs the server. A registry server asks for approval before it starts with a configuration that the user has not approved, including once for a server that was installed before this change. The registry sync asks before it replaces an approved server, and it does not reinstall a server that the user turned off. The consent prompt shows the package index of a server, and the URLs in its command without a user name or password. Adds tests. --- chat-client/src/client/mcpMynahUi.test.ts | 68 ++ chat-client/src/client/mcpMynahUi.ts | 16 +- .../agenticChat/textFormatting.test.ts | 26 +- .../agenticChat/textFormatting.ts | 21 +- .../tools/mcp/mcpConsentStore.test.ts | 133 +++ .../agenticChat/tools/mcp/mcpConsentStore.ts | 38 + .../tools/mcp/mcpEventHandler.test.ts | 361 +++++++- .../agenticChat/tools/mcp/mcpEventHandler.ts | 195 ++++- .../agenticChat/tools/mcp/mcpManager.test.ts | 775 +++++++++++++++++- .../agenticChat/tools/mcp/mcpManager.ts | 417 +++++++--- .../agenticChat/tools/mcp/mcpTypes.ts | 1 + .../agenticChat/tools/mcp/mcpUtils.test.ts | 4 + .../agenticChat/tools/mcp/mcpUtils.ts | 3 + 13 files changed, 1926 insertions(+), 132 deletions(-) diff --git a/chat-client/src/client/mcpMynahUi.test.ts b/chat-client/src/client/mcpMynahUi.test.ts index 019140bd40..9e5c1401ca 100644 --- a/chat-client/src/client/mcpMynahUi.test.ts +++ b/chat-client/src/client/mcpMynahUi.test.ts @@ -681,4 +681,72 @@ describe('McpMynahUi', () => { assert.strictEqual(detailedList.list[0].children[0].icon, 'mocked-icon') }) }) + + describe('registry server install', () => { + const openRegistryView = (params: Record) => { + mcpMynahUi.mcpServerClick({ id: 'add-new-mcp', isMcpRegistry: true, list: [], ...params } as any) + return (mynahUi.openDetailedList as sinon.SinonStub).lastCall.args[0] + } + + it('asks for the install preview when Install is clicked in the registry list', () => { + const { events } = openRegistryView({ + header: { title: 'Add MCP Server' }, + filterOptions: [], + list: [{ children: [{ title: 'docs-server 1.2.3', actions: [{ id: 'install-registry-server' }] }] }], + }) + + events.onActionClick( + { id: 'install-registry-server' } as ChatItemButton, + { + title: 'docs-server 1.2.3', + } as DetailedListItem + ) + + sinon.assert.calledWith(mynahUi.toggleSplashLoader as sinon.SinonStub, true, '**Loading MCP Server**') + sinon.assert.calledOnceWithExactly( + messager.onMcpServerClick as sinon.SinonStub, + 'install-registry-server', + 'docs-server 1.2.3' + ) + }) + + it('installs the previewed server when Install is clicked in the preview', () => { + const { detailedList, events } = openRegistryView({ + header: { title: 'Install MCP Server', description: 'Review this server before you install it.' }, + filterOptions: [{ type: 'textinput', id: 'name', title: 'Name', value: 'docs-server' }], + filterActions: [ + { id: 'cancel-mcp', text: 'Cancel' }, + { id: 'confirm-install-registry-server', text: 'Install' }, + ], + }) + assert.strictEqual(detailedList.header.title, 'Install MCP Server') + assert.deepStrictEqual( + detailedList.filterActions.map((action: any) => action.id), + ['cancel-mcp', 'confirm-install-registry-server'] + ) + + // The server name comes from the preview that the server sent, not from the form values + events.onFilterActionClick({ id: 'confirm-install-registry-server' }, { name: 'other-server' }) + + sinon.assert.calledWith(mynahUi.toggleSplashLoader as sinon.SinonStub, true, '**Installing MCP Server**') + sinon.assert.calledOnceWithExactly( + messager.onMcpServerClick as sinon.SinonStub, + 'confirm-install-registry-server', + 'docs-server' + ) + sinon.assert.notCalled(messager.onListMcpServers as sinon.SinonStub) + }) + + it('goes back to the server list when Cancel is clicked in the preview', () => { + const { events } = openRegistryView({ + header: { title: 'Install MCP Server' }, + filterOptions: [{ type: 'textinput', id: 'name', title: 'Name', value: 'docs-server' }], + }) + + events.onFilterActionClick({ id: 'cancel-mcp' }, { name: 'docs-server' }) + + sinon.assert.calledOnce(messager.onListMcpServers as sinon.SinonStub) + sinon.assert.notCalled(messager.onMcpServerClick as sinon.SinonStub) + }) + }) }) diff --git a/chat-client/src/client/mcpMynahUi.ts b/chat-client/src/client/mcpMynahUi.ts index ab227c928f..0a0938bb2d 100644 --- a/chat-client/src/client/mcpMynahUi.ts +++ b/chat-client/src/client/mcpMynahUi.ts @@ -34,6 +34,10 @@ export const MCP_IDS = { // Permission actions PERMISSION_CHANGE: 'mcp-permission-change', SAVE_PERMISSION_CHANGE: 'save-permission-change', + + // Registry actions + INSTALL_REGISTRY_SERVER: 'install-registry-server', + CONFIRM_INSTALL_REGISTRY_SERVER: 'confirm-install-registry-server', } // MCP UI display constants @@ -535,8 +539,9 @@ export class McpMynahUi { return { onBackClick: () => this.messager.onListMcpServers(), onActionClick: (action: ChatItemButton, item?: DetailedListItem) => { - if (action.id === 'install-registry-server') { - this.mynahUi.toggleSplashLoader(true, '**Installing MCP Server**') + // Install in the registry list opens the install preview of the server + if (action.id === MCP_IDS.INSTALL_REGISTRY_SERVER) { + this.mynahUi.toggleSplashLoader(true, '**Loading MCP Server**') this.messager.onMcpServerClick(action.id, item?.title) } }, @@ -546,6 +551,13 @@ export class McpMynahUi { return } + // Install in the install preview installs the server + if (actionParams.id === MCP_IDS.CONFIRM_INSTALL_REGISTRY_SERVER) { + this.mynahUi.toggleSplashLoader(true, '**Installing MCP Server**') + this.messager.onMcpServerClick(actionParams.id, serverName) + return + } + if (actionParams.id === MCP_IDS.SAVE) { this.mynahUi.toggleSplashLoader(true, '**Installing MCP Server**') this.messager.onMcpServerClick(actionParams.id, serverName, filterValues) diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/textFormatting.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/textFormatting.test.ts index b940c1dc6d..8ee4057692 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/textFormatting.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/textFormatting.test.ts @@ -1,5 +1,5 @@ import * as assert from 'assert' -import { codeBlockLines, codeFence, shellCommandBlock, shellCommandBlockStart } from './textFormatting' +import { codeBlockLines, codeFence, codeSpan, shellCommandBlock, shellCommandBlockStart } from './textFormatting' import { AgenticChatResultStream } from './agenticChatResultStream' describe('textFormatting', () => { @@ -23,6 +23,30 @@ describe('textFormatting', () => { }) }) + describe('code spans', () => { + it('wrap text with no backticks in single backticks', () => { + assert.strictEqual(codeSpan('npx -y pkg@1'), '`npx -y pkg@1`') + }) + + it('use a delimiter longer than the longest run of backticks in the text', () => { + assert.strictEqual(codeSpan('a`b'), '``a`b``') + assert.strictEqual(codeSpan('a```b `c` d'), '````a```b `c` d````') + }) + + it('add a space between the delimiter and a backtick at the start or the end', () => { + assert.strictEqual(codeSpan('`x'), '`` `x ``') + assert.strictEqual(codeSpan('x`'), '`` x` ``') + assert.strictEqual(codeSpan('``'), '``` `` ```') + }) + + it('leave markdown and HTML in the text unchanged', () => { + assert.strictEqual( + codeSpan('[docs](https://example.com) x **y**'), + '`[docs](https://example.com) x **y**`' + ) + }) + }) + describe('text inside a code block', () => { it('indents each line that starts with three or more backticks, after up to three spaces, to four spaces', () => { assert.strictEqual( diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/textFormatting.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/textFormatting.ts index 31f8886dca..f832b94129 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/textFormatting.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/textFormatting.ts @@ -29,13 +29,30 @@ export function toolErrorMessage(toolUse: ToolUse, errorMessage: string) { \`Error: ${errorMessage}\`` } +function longestBacktickRun(text: string): number { + return (String(text).match(/`+/g) ?? []).reduce((longest, run) => Math.max(longest, run.length), 0) +} + /** * Fence for a markdown code block that holds the text. It is longer than any run of backticks * in the text, so no line of the text can end the block. */ export function codeFence(text: string): string { - const longestRun = (String(text).match(/`+/g) ?? []).reduce((longest, run) => Math.max(longest, run.length), 0) - return '`'.repeat(Math.max(3, longestRun + 1)) + return '`'.repeat(Math.max(3, longestBacktickRun(text) + 1)) +} + +/** + * A markdown code span for the text, so markdown makes no links or emphasis in it. Its delimiter is + * longer than any run of backticks in the text, so the text cannot end the span. Give the text on + * one line: if the text has a line end, a delimiter of three or more backticks could open a fenced + * code block, and markdown turns line ends in a code span into spaces anyway. Escape <, > and & + * first if the text can contain them, as formatServerConfigForReview does. + */ +export function codeSpan(text: string): string { + const delimiter = '`'.repeat(longestBacktickRun(text) + 1) + // A space separates a backtick at the start or end of the text from the delimiter. Markdown removes it again. + const padding = text.startsWith('`') || text.endsWith('`') ? ' ' : '' + return `${delimiter}${padding}${text}${padding}${delimiter}` } /** Start of a shell code block that shows the full command, for output to follow */ diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.test.ts index b638968139..53ab179e69 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.test.ts @@ -12,6 +12,7 @@ import { effectiveHeaders, fingerprintServerConfig, fingerprintWorkspace, + formatServerConfigForReview, hasApproval, recordApproval, removeApproval, @@ -143,6 +144,138 @@ describe('mcpConsentStore', () => { }) }) + describe('formatServerConfigForReview', () => { + it('shows the command, arguments and merged environment of a stdio server as JSON', () => { + const cfg: MCPServerConfig = { + command: 'npx', + args: ['-y', '@example/server@1.0.0', '--flag=a b'], + env: { B_VAR: 'b', A_VAR: 'a' }, + __additionalEnv__: { B_VAR: 'override' }, + url: 'https://ignored.example.com', + timeout: 60000, + } + + const text = formatServerConfigForReview(cfg) + + expect(JSON.parse(text)).to.deep.equal({ + command: 'npx', + args: ['-y', '@example/server@1.0.0', '--flag=a b'], + env: { A_VAR: 'a', B_VAR: 'override' }, + }) + expect(text).to.equal( + '{\n "command": "npx",\n "args": [\n "-y",\n "@example/server@1.0.0",\n "--flag=a b"\n ],\n "env": {\n "A_VAR": "a",\n "B_VAR": "override"\n }\n}' + ) + }) + + it('shows the URL and merged headers of an HTTP server as JSON', () => { + const cfg: MCPServerConfig = { + url: 'https://mcp.example.com/path?x=1', + headers: { 'X-Team': 'docs' }, + __additionalHeaders__: { Authorization: 'Bearer abc' }, + } + + expect(JSON.parse(formatServerConfigForReview(cfg))).to.deep.equal({ + url: 'https://mcp.example.com/path?x=1', + headers: { Authorization: 'Bearer abc', 'X-Team': 'docs' }, + }) + }) + + it('leaves out empty arguments, environment variables and headers', () => { + expect(JSON.parse(formatServerConfigForReview({ command: 'uvx', args: [], env: {} }))).to.deep.equal({ + command: 'uvx', + }) + expect( + JSON.parse(formatServerConfigForReview({ url: 'https://mcp.example.com', headers: {} })) + ).to.deep.equal({ + url: 'https://mcp.example.com', + }) + }) + + it('writes characters that a reader would not see as escapes, and keeps the exact values', () => { + const hidden = [ + '\u202E', + '\u2066', + '\u200B', + '\u200D', + '\u2028', + '\u2029', + '\u00AD', + '\uFEFF', + '\uFE0F', + '\u0085', + '\u001B', + '\u{E0041}', + // A format character that is not default ignorable + '\uFFF9', + ] + const cfg: MCPServerConfig = { + command: 'npx', + args: hidden.map(character => `a${character}b`), + env: { [`NAME\u202E`]: `x\ny\tz` }, + } + + const text = formatServerConfigForReview(cfg) + + for (const character of hidden) { + expect(text).to.not.include(character) + } + expect(text).to.include('a\\u202eb') + expect(text).to.include('a\\udb40\\udc41b') + expect(text).to.include('"NAME\\u202e": "x\\ny\\tz"') + expect(JSON.parse(text)).to.deep.equal({ + command: 'npx', + args: hidden.map(character => `a${character}b`), + env: { [`NAME\u202E`]: `x\ny\tz` }, + }) + }) + + it('writes <, > and & as escapes, and keeps the exact values', () => { + const values = ['', '--verbose', '', 'a", "b', '&]/) + expect(text).to.include('"\\u003cspan\\u003e"') + expect(text).to.include('"a\\u0026quot;, \\"b"') + expect(text).to.include('"A\\u003cB": "x\\u0026y"') + expect(JSON.parse(text)).to.deep.equal({ command: 'npx', args: values, env: { 'A and & in a URL and headers as escapes', () => { + const cfg: MCPServerConfig = { url: 'https://mcp.example.com/?a=1&b=<2>', headers: { 'X-A&B': '' } } + + const text = formatServerConfigForReview(cfg) + + expect(text).to.not.match(/[<>&]/) + expect(text).to.include('"https://mcp.example.com/?a=1\\u0026b=\\u003c2\\u003e"') + expect(JSON.parse(text)).to.deep.equal({ url: cfg.url, headers: cfg.headers }) + }) + + it('writes spaces other than U+0020 as escapes', () => { + const spaces = ['\u00A0', '\u1680', '\u2003', '\u202F', '\u205F', '\u3000'] + const args = [...spaces.map(space => `a${space}b`), 'a b'] + + const text = formatServerConfigForReview({ command: 'npx', args }) + + for (const space of spaces) { + expect(text).to.not.include(space) + } + expect(text).to.include('"a\\u00a0b"') + expect(text).to.include('"a\\u3000b"') + expect(text).to.include('"a b"') + expect(JSON.parse(text)).to.deep.equal({ command: 'npx', args }) + }) + + it('keeps visible non-ASCII characters', () => { + const text = formatServerConfigForReview({ command: 'npx', args: ['Größe', 'データ', '✓'] }) + + expect(text).to.include('"Größe"') + expect(text).to.include('"データ"') + expect(text).to.include('"✓"') + }) + }) + describe('fingerprintWorkspace', () => { it('is keyed on the directory of the config, not the filename', () => { const a = fingerprintWorkspace('/foo/bar/.amazonq/mcp.json') diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.ts index 45a4f252fc..5692b4bdba 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.ts @@ -74,6 +74,44 @@ export function fingerprintServerConfig(cfg: MCPServerConfig): string { return 'sha256:' + createHash('sha256').update(JSON.stringify(canonical)).digest('hex') } +/** + * Characters that formatServerConfigForReview writes as \u escapes: + * - control and format characters (such as bidirectional overrides and zero-width characters), line and paragraph + * separators, and the other default ignorable characters + * - spaces other than U+0020 + * - <, > and &, as JSON encoders that make text safe to put in HTML escape them + * Line feeds and U+0020 are left alone: JSON.stringify uses them for the layout, it already escapes a line feed in a + * string, and U+0020 in a string is shown as it is. The other characters can occur only in strings, where a \u escape + * keeps the value. + */ +const ESCAPED_CHARACTERS = /(?![\n ])[\p{Cc}\p{Cf}\p{Zs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}<>&]/gu + +/** + * The fields of a server config that fingerprintServerConfig covers, as JSON in the format of mcp.json, for a person + * to review: the command, arguments and environment variables of a stdio server, or the URL and headers of an HTTP + * server. The characters in ESCAPED_CHARACTERS are written as \u escapes, so the text shows and parses to the + * exact values. + */ +export function formatServerConfigForReview(cfg: MCPServerConfig): string { + const env = effectiveEnv(cfg) + const headers = effectiveHeaders(cfg) + const args = cfg.args ?? [] + // As in McpManager, a config with a command starts a stdio server + const reviewed = cfg.command + ? { + command: cfg.command, + ...(args.length > 0 ? { args } : {}), + ...(Object.keys(env).length > 0 ? { env } : {}), + } + : { url: cfg.url ?? '', ...(Object.keys(headers).length > 0 ? { headers } : {}) } + return JSON.stringify(reviewed, undefined, 1).replace(ESCAPED_CHARACTERS, character => + Array.from( + { length: character.length }, + (_, i) => `\\u${character.charCodeAt(i).toString(16).padStart(4, '0')}` + ).join('') + ) +} + /** Hash of the workspace path so approval is scoped to (workspace, config). * Normalizes the path to forward slashes for cross-platform consistency. */ export function fingerprintWorkspace(configPath: string): string { diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpEventHandler.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpEventHandler.test.ts index 9c7aa7b2d8..6b88e4cb88 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpEventHandler.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpEventHandler.test.ts @@ -7,7 +7,7 @@ import { expect } from 'chai' import * as sinon from 'sinon' import { McpEventHandler } from './mcpEventHandler' import { McpManager } from './mcpManager' -import { MCPServerConfig, McpServerStatus } from './mcpTypes' +import { McpRegistryServer, MCPServerConfig, McpServerStatus } from './mcpTypes' import { ProfileStatusMonitor } from './profileStatusMonitor' import * as mcpUtils from './mcpUtils' import { getGlobalAgentConfigPath } from './mcpUtils' @@ -733,6 +733,365 @@ describe('McpEventHandler error handling', () => { }) }) + describe('installing a registry server', () => { + const localServer: McpRegistryServer = { + name: 'docs-server', + description: 'Searches the team docs', + version: '1.2.3', + packages: [ + { + registryType: 'npm', + registryBaseUrl: 'https://npm.example.com', + identifier: '@example/docs-server', + transport: { type: 'stdio' }, + runtimeArguments: [{ type: 'positional', value: '--prefer-offline' }], + packageArguments: [{ type: 'positional', value: '--read-only' }], + environmentVariables: [{ name: 'DOCS_REGION', value: 'us-east-1' }], + }, + ], + } + const localArgs = ['-y', '--prefer-offline', '@example/docs-server@1.2.3', '--read-only'] + const localEnv = { NPM_CONFIG_REGISTRY: 'https://npm.example.com', DOCS_REGION: 'us-east-1' } + const remoteServer: McpRegistryServer = { + name: 'remote-docs', + description: 'Hosted docs search', + version: '2.0.0', + remotes: [ + { + type: 'streamable-http', + url: 'https://mcp.example.com/docs', + headers: [{ name: 'X-Team', value: 'docs' }], + }, + ], + } + const plainServer: McpRegistryServer = { + name: 'plain-server', + description: 'A server with no index, variables or headers', + version: '0.1.0', + packages: [{ registryType: 'pypi', identifier: 'plain-server', transport: { type: 'stdio' } }], + } + const plainRemoteServer: McpRegistryServer = { + name: 'plain-remote', + description: 'A remote server with no headers', + version: '1.0.0', + remotes: [{ type: 'sse', url: 'https://mcp.example.com/sse' }], + } + + let addRegistryServer: sinon.SinonStub + let recordApproval: sinon.SinonStub + let registryServers: Map + + const field = (view: any, id: string) => view.filterOptions.find((option: any) => option.id === id) + const rows = (view: any, id: string) => field(view, id).value.map((row: any) => row.value) + // The configuration that the status shows in a code span on one line + const reviewJson = (view: any) => { + const match = /^(`+)([^\n]*)\1$/.exec(view.header.status.description) + expect(match, 'the status shows the configuration in a code span on one line').to.not.be.null + return JSON.parse(match![2]) + } + const preview = (title: string) => eventHandler.onMcpServerClick({ id: 'install-registry-server', title }) + const confirm = (title: string) => + eventHandler.onMcpServerClick({ id: 'confirm-install-registry-server', title }) + + beforeEach(async () => { + sinon.stub(ProfileStatusMonitor, 'getMcpState').returns(true) + const mgr = await McpManager.init([], features) + registryServers = new Map( + [localServer, remoteServer, plainServer, plainRemoteServer].map(server => [ + server.name, + JSON.parse(JSON.stringify(server)), + ]) + ) + sinon.stub(mgr, 'getRegistryService').returns({ + isRegistryActive: () => true, + getInMemoryRegistry: () => ({ + servers: [...registryServers.values()], + lastFetched: new Date(), + url: 'https://registry.example.com/registry.json', + }), + getServerByName: (name: string) => registryServers.get(name), + } as any) + sinon.stub(mgr, 'getAllServerConfigs').returns(new Map()) + sinon.stub(mgr, 'getAllToolsWithPermissions').returns([]) + addRegistryServer = sinon.stub(mgr, 'addRegistryServer').resolves() + recordApproval = sinon.stub(mgr, 'recordRegistryServerApproval').resolves() + }) + + it('shows the command, arguments and environment variables of a local server before installing it', async () => { + const view = await preview('docs-server 1.2.3') + + sinon.assert.notCalled(addRegistryServer) + expect(view.id).to.equal('add-new-mcp') + expect(view.isMcpRegistry).to.be.true + expect(view.header.title).to.equal('Install MCP Server') + expect(view.header.status).to.include({ + title: 'Installing this server runs this command on your computer:', + status: 'info', + }) + // The status shows the whole configuration as text, so no long value is cut off + expect(reviewJson(view)).to.deep.equal({ command: 'npx', args: localArgs, env: localEnv }) + expect(field(view, 'args').value.every((row: any) => row.persistent === true)).to.be.true + expect(field(view, 'name').value).to.equal('docs-server') + expect(field(view, 'version').value).to.equal('1.2.3') + expect(field(view, 'transport').value).to.equal('stdio') + expect(field(view, 'command').value).to.equal('npx') + expect(rows(view, 'args')).to.deep.equal(localArgs.map(arg => ({ arg_key: arg }))) + expect(rows(view, 'env_variables')).to.deep.equal( + Object.entries(localEnv).map(([name, value]) => ({ env_var_name: name, env_var_value: value })) + ) + expect(field(view, 'url')).to.be.undefined + expect(view.filterOptions.every((option: any) => option.disabled === true)).to.be.true + expect(view.filterActions.map((action: any) => action.id)).to.deep.equal([ + 'cancel-mcp', + 'confirm-install-registry-server', + ]) + }) + + it('shows the URL and headers of a remote server before installing it', async () => { + const view = await preview('remote-docs 2.0.0') + + sinon.assert.notCalled(addRegistryServer) + expect(view.header.title).to.equal('Install MCP Server') + expect(view.header.status).to.include({ + title: 'Installing this server connects Amazon Q to this URL:', + status: 'info', + }) + expect(reviewJson(view)).to.deep.equal({ + url: 'https://mcp.example.com/docs', + headers: { 'X-Team': 'docs' }, + }) + expect(field(view, 'transport').value).to.equal('http') + expect(field(view, 'url').value).to.equal('https://mcp.example.com/docs') + expect(rows(view, 'headers')).to.deep.equal([{ key: 'X-Team', value: 'docs' }]) + expect(field(view, 'command')).to.be.undefined + expect(field(view, 'args')).to.be.undefined + expect(view.filterOptions.every((option: any) => option.disabled === true)).to.be.true + }) + + it('leaves out the environment variables and headers when a server has none', async () => { + const local = await preview('plain-server 0.1.0') + expect(field(local, 'command').value).to.equal('uvx') + expect(rows(local, 'args')).to.deep.equal([{ arg_key: 'plain-server@0.1.0' }]) + expect(field(local, 'env_variables')).to.be.undefined + + const remote = await preview('plain-remote 1.0.0') + expect(field(remote, 'url').value).to.equal('https://mcp.example.com/sse') + expect(field(remote, 'headers')).to.be.undefined + }) + + it('shows a long value in full and hidden characters as escapes in the status text', async () => { + const longIndex = `https://npm.example.com/${'a'.repeat(300)}` + const server = registryServers.get('docs-server')! + server.packages![0].registryBaseUrl = longIndex + server.packages![0].packageArguments!.push({ type: 'positional', value: 'a\u202Eb' }) + + const view = await preview('docs-server 1.2.3') + + const description: string = view.header.status.description + expect(description).to.include(longIndex) + expect(description).to.not.include('\u202E') + expect(description).to.include('a\\u202eb') + expect(reviewJson(view).env.NPM_CONFIG_REGISTRY).to.equal(longIndex) + }) + + it('keeps backticks, markdown and HTML in a value as text in the code span', async () => { + const values = [ + 'a```b', + '````', + '[docs](https://other.example.com)', + 'bold', + '', + 'a", "b', + ] + registryServers + .get('docs-server')! + .packages![0].packageArguments!.push(...values.map(value => ({ type: 'positional' as const, value }))) + + const view = await preview('docs-server 1.2.3') + + const description: string = view.header.status.description + expect(description.startsWith('`````{')).to.be.true + expect(description.endsWith('}`````')).to.be.true + // The status has these characters only as escapes + expect(description).to.not.match(/[<>&]/) + expect(reviewJson(view).args.slice(-values.length)).to.deep.equal(values) + }) + + it('installs the previewed server when the user confirms, and only once', async () => { + await preview('docs-server 1.2.3') + const result = await confirm('docs-server') + + sinon.assert.calledOnce(addRegistryServer) + const [name, config, agentPath] = addRegistryServer.firstCall.args + expect(name).to.equal('docs-server') + expect(config).to.deep.equal({ command: 'npx', args: localArgs, env: localEnv, __cachedVersion__: '1.2.3' }) + expect(agentPath).to.equal(getGlobalAgentConfigPath('/fake/home')) + expect(result.id).to.equal('open-mcp-server') + expect(result.header.title).to.equal('docs-server') + + // The confirmation is used up: a second Install shows the preview again + const again = await confirm('docs-server') + sinon.assert.calledOnce(addRegistryServer) + expect(again.header.title).to.equal('Install MCP Server') + }) + + it('ignores form values that the chat client sends with the confirmation', async () => { + await preview('docs-server 1.2.3') + await eventHandler.onMcpServerClick({ + id: 'confirm-install-registry-server', + title: 'docs-server', + optionsValues: { + name: 'other-server', + command: 'other-command', + args: [{ arg_key: '--other-flag' }] as any, + env_variables: [{ env_var_name: 'OTHER_VAR', env_var_value: 'other-value' }] as any, + }, + }) + + sinon.assert.calledOnce(addRegistryServer) + const [name, config] = addRegistryServer.firstCall.args + expect(name).to.equal('docs-server') + expect(config).to.deep.equal({ command: 'npx', args: localArgs, env: localEnv, __cachedVersion__: '1.2.3' }) + }) + + it('installs a remote server with the previewed URL and headers', async () => { + await preview('remote-docs 2.0.0') + await confirm('remote-docs') + + sinon.assert.calledOnce(addRegistryServer) + expect(addRegistryServer.firstCall.args[1]).to.deep.equal({ + url: 'https://mcp.example.com/docs', + headers: { 'X-Team': 'docs' }, + __cachedVersion__: '2.0.0', + }) + }) + + it('shows the preview instead of installing a server that the user did not review', async () => { + const view = await confirm('docs-server') + + sinon.assert.notCalled(addRegistryServer) + expect(view.header.title).to.equal('Install MCP Server') + expect(view.header.status).to.include({ status: 'info' }) + sinon.assert.calledWithMatch(features.logging.info, /it was not the server in the preview/) + + await confirm('docs-server') + sinon.assert.calledOnce(addRegistryServer) + }) + + it('does not install a server when the preview showed another server', async () => { + await preview('docs-server 1.2.3') + await preview('remote-docs 2.0.0') + const view = await confirm('docs-server') + + sinon.assert.notCalled(addRegistryServer) + expect(field(view, 'name').value).to.equal('docs-server') + expect(view.header.status).to.include({ status: 'info' }) + }) + + const changes: [string, string, (server: McpRegistryServer) => void][] = [ + [ + 'an argument', + 'docs-server', + server => server.packages![0].packageArguments!.push({ type: 'positional', value: '--verbose' }), + ], + [ + 'an environment variable', + 'docs-server', + server => (server.packages![0].environmentVariables![0].value = 'eu-west-1'), + ], + [ + 'the package registry', + 'docs-server', + server => (server.packages![0].registryBaseUrl = 'https://npm.other.example.com'), + ], + ['the version', 'docs-server', server => (server.version = '1.2.4')], + ['the version of a remote server', 'remote-docs', server => (server.version = '2.0.1')], + ['the URL', 'remote-docs', server => (server.remotes![0].url = 'https://mcp.other.example.com/docs')], + ['a header', 'remote-docs', server => (server.remotes![0].headers![0].value = 'other')], + ] + for (const [change, serverName, mutate] of changes) { + it(`shows the preview again when the registry changed ${change} after the preview`, async () => { + const before = await preview(serverName) + mutate(registryServers.get(serverName)!) + const after = await confirm(serverName) + + sinon.assert.notCalled(addRegistryServer) + expect(after.header.title).to.equal('Install MCP Server') + expect(after.header.status).to.include({ + title: 'This server changed in the registry. Review it again before you install it.', + status: 'warning', + }) + expect(after.filterOptions).to.not.deep.equal(before.filterOptions) + sinon.assert.calledWithMatch(features.logging.info, /its registry entry changed/) + + await confirm(serverName) + sinon.assert.calledOnce(addRegistryServer) + }) + } + + it('records the approval of the previewed configuration before it installs the server', async () => { + await preview('docs-server 1.2.3') + await confirm('docs-server') + + sinon.assert.calledOnce(recordApproval) + const [name, config, agentPath] = recordApproval.firstCall.args + expect(name).to.equal('docs-server') + // The approval covers the configuration that is installed and that the preview showed + expect(config).to.deep.equal({ command: 'npx', args: localArgs, env: localEnv, __cachedVersion__: '1.2.3' }) + expect(addRegistryServer.firstCall.args[1]).to.deep.equal(config) + expect(agentPath).to.equal(getGlobalAgentConfigPath('/fake/home')) + sinon.assert.callOrder(recordApproval, addRegistryServer) + }) + + it('records no approval when the registry changed the server after the preview', async () => { + await preview('docs-server 1.2.3') + registryServers.get('docs-server')!.version = '1.2.4' + await confirm('docs-server') + + sinon.assert.notCalled(recordApproval) + sinon.assert.notCalled(addRegistryServer) + }) + + const leaveActions: [string, () => Promise][] = [ + ['Cancel or Back, which list the servers', () => eventHandler.onListMcpServers({})], + ['another view', () => eventHandler.onMcpServerClick({ id: 'add-new-mcp' })], + ['an action on another server', () => eventHandler.onMcpServerClick({ id: 'refresh-mcp-list' })], + ] + for (const [leave, action] of leaveActions) { + it(`does not install a server after the user leaves its preview with ${leave}`, async () => { + await preview('docs-server 1.2.3') + await action().catch(() => undefined) + const view = await confirm('docs-server') + + sinon.assert.notCalled(addRegistryServer) + sinon.assert.notCalled(recordApproval) + // The server shows the preview again instead + expect(view.header.title).to.equal('Install MCP Server') + expect(view.header.status).to.include({ status: 'info' }) + }) + } + + it('does not install a server that left the registry after the preview', async () => { + await preview('docs-server 1.2.3') + registryServers.delete('docs-server') + const view = await confirm('docs-server') + + sinon.assert.notCalled(addRegistryServer) + expect(view.header.title).to.equal('Add MCP Server') + sinon.assert.calledWithMatch(features.logging.error, /Registry server not found: docs-server/) + }) + + it('shows the registry list for a registry entry that cannot be converted', async () => { + registryServers.set('broken', { name: 'broken', description: 'No package', version: '1.0.0' }) + const view = await preview('broken 1.0.0') + + expect(view.header.title).to.equal('Add MCP Server') + sinon.assert.calledWithMatch(features.logging.error, /Invalid registry server 'broken'/) + await confirm('broken') + sinon.assert.notCalled(addRegistryServer) + }) + }) + it('handles server click events for fixing failed servers', async () => { // Make sure previous stubs are restored sinon.restore() diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpEventHandler.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpEventHandler.ts index 4db41e3bcf..4276659c7d 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpEventHandler.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpEventHandler.ts @@ -24,11 +24,14 @@ import { } from './mcpUtils' import { McpPermissionType, + McpRegistryServer, MCPServerConfig, MCPServerPermission, McpServerRuntimeState, McpServerStatus, } from './mcpTypes' +import { fingerprintServerConfig, formatServerConfigForReview } from './mcpConsentStore' +import { codeSpan } from '../../textFormatting' import { TelemetryService } from '../../../../shared/telemetry/telemetryService' import { ProfileStatusMonitor } from './profileStatusMonitor' import { McpRegistryService } from './mcpRegistryService' @@ -49,6 +52,9 @@ enum TransportType { HTTP = 'http', } +/** Button of the install preview of a registry server that installs the server */ +const CONFIRM_INSTALL_REGISTRY_SERVER = 'confirm-install-registry-server' + export class McpEventHandler { private static readonly FILE_WATCH_DEBOUNCE_MS = 2000 #features: Features @@ -66,6 +72,8 @@ export class McpEventHandler { #lastProgrammaticState: boolean = false #serverNameBeforeUpdate: string | undefined #converter: McpServerConfigConverter = new McpServerConfigConverter() + /** The registry server configuration that the install preview showed. Install installs only this configuration. */ + #previewedRegistryInstall: { serverName: string; version: string; fingerprint: string } | undefined #releaseProgrammaticAfterDebounce(padMs = 500) { setTimeout(() => { @@ -115,6 +123,9 @@ export class McpEventHandler { */ async onListMcpServers(params: ListMcpServersParams) { this.#currentEditingServerName = undefined + // Cancel and Back in the install preview of a registry server open the server list, so the preview is + // withdrawn: a confirmation that arrives later installs nothing + this.#previewedRegistryInstall = undefined let mcpManager try { mcpManager = McpManager.instance @@ -421,11 +432,17 @@ export class McpEventHandler { 'mcp-disable-server': () => this.#handleDisableMcpServer(params), 'mcp-delete-server': () => this.#handleDeleteMcpServer(params), 'mcp-fix-server': () => this.#handleEditMcpServer(params), - 'install-registry-server': () => this.#handleInstallRegistryServer(params), + 'install-registry-server': () => this.#handleShowRegistryInstallPreview(params), + [CONFIRM_INSTALL_REGISTRY_SERVER]: () => this.#handleInstallRegistryServer(params), } // Execute the appropriate handler or return default response const handler = handlers[params.id] + // Any other action in the MCP views leaves the install preview of a registry server, so the preview is + // withdrawn. Install in the registry list shows a new preview. + if (params.id !== CONFIRM_INSTALL_REGISTRY_SERVER) { + this.#previewedRegistryInstall = undefined + } if (handler) { return await handler() } @@ -2287,26 +2304,188 @@ export class McpEventHandler { } /** - * Installs a server from the registry + * The registry entry named `serverName` and the configuration that the server starts with when it is installed. + * Undefined when the registry has no such entry or the entry cannot be converted. */ - async #handleInstallRegistryServer(params: McpServerClickParams) { + #resolveRegistryServer( + serverName: string + ): { registryServer: McpRegistryServer; config: MCPServerConfig } | undefined { + const registryServer: McpRegistryServer | undefined = McpManager.instance + .getRegistryService() + ?.getServerByName(serverName) + if (!registryServer) { + this.#features.logging.error(`Registry server not found: ${serverName}`) + return undefined + } + try { + return { registryServer, config: this.#converter.convertRegistryServer(registryServer) } + } catch (error) { + this.#features.logging.error(`Invalid registry server '${serverName}': ${error}`) + return undefined + } + } + + /** + * Shows what a registry server runs, or what it connects to, before the user installs it: the command, + * arguments, environment variables, URL and headers that the registry lists for it. + */ + async #handleShowRegistryInstallPreview(params: McpServerClickParams, changedInRegistry: boolean = false) { const serverName = params.title?.split(' ')[0] if (!serverName) return - const registryService = McpManager.instance.getRegistryService() - const registryServer = registryService?.getServerByName(serverName) - if (!registryServer) { - this.#features.logging.error(`Registry server not found: ${serverName}`) + const resolved = this.#resolveRegistryServer(serverName) + if (!resolved) { return this.#handleShowRegistryServers(params) } + const { registryServer, config } = resolved + this.#previewedRegistryInstall = { + serverName, + version: registryServer.version, + fingerprint: fingerprintServerConfig(config), + } + + const isRemote = !!config.url + const readOnlyRows = (values: T[]) => values.map(value => ({ persistent: true, value })) + const args = readOnlyRows((config.args ?? []).map(arg => ({ arg_key: arg }))) + const envVariables = readOnlyRows( + Object.entries(config.env ?? {}).map(([name, value]) => ({ env_var_name: name, env_var_value: value })) + ) + const headers = readOnlyRows(Object.entries(config.headers ?? {}).map(([key, value]) => ({ key, value }))) + + const definition = isRemote + ? [ + { type: 'textinput', id: 'url', title: 'URL', value: config.url, disabled: true }, + ...(headers.length > 0 + ? [ + { + type: 'list', + id: 'headers', + title: 'Headers', + items: [ + { id: 'key', title: 'Key', type: 'textinput' }, + { id: 'value', title: 'Value', type: 'textinput' }, + ], + value: headers, + disabled: true, + }, + ] + : []), + ] + : [ + { type: 'textinput', id: 'command', title: 'Command', value: config.command ?? '', disabled: true }, + ...(args.length > 0 + ? [ + { + type: 'list', + id: 'args', + title: 'Arguments', + items: [{ id: 'arg_key', type: 'textinput' }], + value: args, + disabled: true, + }, + ] + : []), + ...(envVariables.length > 0 + ? [ + { + type: 'list', + id: 'env_variables', + title: 'Environment variables', + items: [ + { id: 'env_var_name', title: 'Name', type: 'textinput' }, + { id: 'env_var_value', title: 'Value', type: 'textinput' }, + ], + value: envVariables, + disabled: true, + }, + ] + : []), + ] + + let statusTitle = 'Installing this server runs this command on your computer:' + if (changedInRegistry) { + statusTitle = 'This server changed in the registry. Review it again before you install it.' + } else if (isRemote) { + statusTitle = 'Installing this server connects Amazon Q to this URL:' + } - const config = this.#converter.convertRegistryServer(registryServer) + return { + id: 'add-new-mcp', + isMcpRegistry: true, + header: { + title: 'Install MCP Server', + description: + 'Review this server before you install it. If the registry changes it later, Amazon Q asks you again before the server starts.', + // The fields below cut off long values, so the status also shows the whole configuration. The chat + // client shows the status as markdown. In a code span, markdown is not applied and the text wraps, + // and formatServerConfigForReview writes the characters in ESCAPED_CHARACTERS as escapes. + // A code block would not wrap, and its Copy and Insert buttons do nothing in this view. + status: { + title: statusTitle, + // On one line, so that a delimiter of three or more backticks cannot open a fenced code block. + // In a code span, markdown turns line ends into spaces anyway. + description: codeSpan(formatServerConfigForReview(config).replace(/\n */g, ' ')), + icon: changedInRegistry ? 'warning' : 'info', + status: (changedInRegistry ? 'warning' : 'info') as Status, + }, + }, + list: [], + filterOptions: [ + { type: 'textinput', id: 'name', title: 'Name', value: serverName, disabled: true }, + { type: 'textinput', id: 'version', title: 'Version', value: registryServer.version, disabled: true }, + { + type: 'textinput', + id: 'transport', + title: 'Transport', + value: isRemote ? TransportType.HTTP : TransportType.STDIO, + disabled: true, + }, + ...definition, + ], + filterActions: [ + { id: 'cancel-mcp', text: 'Cancel' }, + { id: CONFIRM_INSTALL_REGISTRY_SERVER, text: 'Install', status: 'primary' }, + ], + } + } + + /** + * Installs a registry server after the user reviewed it in the install preview. If the registry changed the + * server's configuration after the preview, or there was no preview, shows the preview instead. + */ + async #handleInstallRegistryServer(params: McpServerClickParams) { + const serverName = params.title?.split(' ')[0] + if (!serverName) return + + const resolved = this.#resolveRegistryServer(serverName) + if (!resolved) { + return this.#handleShowRegistryServers(params) + } + const { registryServer, config } = resolved + const previewed = this.#previewedRegistryInstall + if ( + previewed?.serverName !== serverName || + previewed.version !== registryServer.version || + previewed.fingerprint !== fingerprintServerConfig(config) + ) { + const changedInRegistry = previewed?.serverName === serverName + this.#features.logging.info( + `MCP Registry: showing the install preview of '${serverName}' again because ${ + changedInRegistry ? 'its registry entry changed' : 'it was not the server in the preview' + }` + ) + return this.#handleShowRegistryInstallPreview(params, changedInRegistry) + } + this.#previewedRegistryInstall = undefined config.__cachedVersion__ = registryServer.version const agentPath = await this.#getAgentPath(true) this.#isProgrammaticChange = true try { + // The user approved this configuration in the preview. Later changes in the registry need approval again + // before the server starts. + await McpManager.instance.recordRegistryServerApproval(serverName, config, agentPath) await McpManager.instance.addRegistryServer(serverName, config, agentPath) this.#releaseProgrammaticAfterDebounce() return this.#handleOpenMcpServer({ id: 'open-mcp-server', title: serverName }) diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.test.ts index 47833b15a9..e235f867ab 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.test.ts @@ -1877,7 +1877,13 @@ describe('Registry Synchronization', () => { }) describe('version checking', () => { - it('should detect version mismatch for local servers', async () => { + it('should detect version mismatch for local servers, and reinstall after the user allows the new version', async () => { + // The reinstall asks for the new configuration before it removes the running server + const consentStore = require('./mcpConsentStore') + sandbox.stub(consentStore, 'hasApproval').resolves(false) + const recordApprovalStub = sandbox.stub(consentStore, 'recordApproval').resolves() + const showMessageRequest = sandbox.stub().resolves({ title: 'Allow for this server' }) + mockFeatures.lsp.window = { showMessageRequest, showDocument: sandbox.stub().resolves({}) } ;(mgr as any).mcpServers.set('test-server', { command: 'npx', args: ['-y', '@test/server@1.0.0'], @@ -1929,6 +1935,8 @@ describe('Registry Synchronization', () => { await mgr.updateRegistryUrl('https://example.com/registry.json', true) + sinon.assert.calledOnce(showMessageRequest) + sinon.assert.calledOnce(recordApprovalStub) expect(removeServerStub.called).to.be.true expect(addRegistryServerStub.called).to.be.true }) @@ -1985,6 +1993,8 @@ describe('addRegistryServer with additional headers/env', () => { const storedCfg = (mgr as any).mcpServers.get('httpServer') expect(storedCfg.__additionalHeaders__).to.deep.equal(additionalHeaders) + // The consent gate checks this mark before the server starts + expect(storedCfg.__registryServer__).to.equal(true) const agentCfg = (mgr as any).agentConfig.mcpServers['httpServer'] expect(agentCfg.headers).to.deep.equal(additionalHeaders) @@ -2303,6 +2313,769 @@ describe('consent gate for workspace-scoped MCP servers (P417451767)', () => { }) }) +describe('consent gate for MCP registry servers', () => { + const fakeHome = '/home/testuser' + const globalAgent = mcpUtils.getGlobalAgentConfigPath(fakeHome) + // The loader and addRegistryServer mark a configuration that comes from the registry + const localCfg = (): MCPServerConfig => ({ + command: 'npx', + args: ['-y', '@example/docs-server@1.2.4'], + env: { DOCS_REGION: 'hidden-env-value' }, + __configPath__: globalAgent, + __registryServer__: true, + }) + + let showMessageStub: sinon.SinonStub + let hasApprovalStub: sinon.SinonStub + let recordApprovalStub: sinon.SinonStub + let setStateSpy: sinon.SinonSpy + + async function buildMgr(): Promise { + const consentStore = require('./mcpConsentStore') + hasApprovalStub = sinon.stub(consentStore, 'hasApproval').resolves(false) + recordApprovalStub = sinon.stub(consentStore, 'recordApproval').resolves() + + showMessageStub = sinon.stub() + const featuresWithPrompt = { + ...features, + workspace: { + ...fakeWorkspace, + fs: { ...fakeWorkspace.fs, getUserHomeDir: () => fakeHome }, + }, + lsp: { window: { showMessageRequest: showMessageStub, showDocument: sinon.stub().resolves({}) } }, + } + const mgr = await McpManager.init([], featuresWithPrompt as any) + await mgr.setWorkspaceTrust('trusted') + setStateSpy = sinon.spy(mgr as any, 'setState') + // Stops a start right after the consent gate, so no test starts a real process + sinon.stub(mgr as any, 'cleanupExistingServer').rejects(new Error('PASSED_THE_GATE')) + return mgr + } + + afterEach(async () => { + sinon.restore() + try { + await McpManager.instance.close() + } catch {} + }) + + it('asks before a registry server starts with a configuration that the user has not allowed', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const cfg = localCfg() + + await (mgr as any).initOneServerInternal('docs-server', cfg) + + expect(showMessageStub.calledOnce).to.be.true + const request = showMessageStub.firstCall.args[0] + expect(request.message).to.include('Amazon Q — MCP Server from the Registry') + expect(request.message).to.include('Server: docs-server\n') + expect(request.message).to.include('Command: npx -y @example/docs-server@1.2.4\n') + expect(request.message).to.include('Environment variables: DOCS_REGION\n') + expect(request.message).to.include('Running this server executes the above command') + expect(request.message).to.not.include('hidden-env-value') + // The command of a registry server comes from the registry, not from its agent config file + expect(request.actions.map((a: { title: string }) => a.title)).to.deep.equal(['Allow for this server', 'Deny']) + sinon.assert.calledWith(hasApprovalStub, sinon.match.any, sinon.match.any, 'docs-server', cfg, globalAgent) + expect(setStateSpy.calledWith('docs-server', McpServerStatus.DISABLED, 0, 'consent not granted')).to.be.true + expect(recordApprovalStub.called).to.be.false + }) + + it('shows the URL and header names of a remote registry server', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const cfg: MCPServerConfig = { + url: 'https://mcp.example.com/docs', + headers: { 'X-Team': 'hidden-header-value' }, + __configPath__: globalAgent, + __registryServer__: true, + } + + await (mgr as any).initOneServerInternal('docs-server', cfg) + + const message = showMessageStub.firstCall.args[0].message as string + expect(message).to.include('Command: https://mcp.example.com/docs\n') + expect(message).to.include('Headers: X-Team\n') + expect(message).to.include('Starting this server connects Amazon Q to the above URL') + expect(message).to.not.include('hidden-header-value') + }) + + for (const [credentials, registry] of [ + ['user name and password', 'https://index-user:hidden-password@npm.example.com/'], + ['user name', 'https://index-user@npm.example.com/'], + ]) { + it(`shows the package index of an npm server without its ${credentials}`, async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const cfg: MCPServerConfig = { + ...localCfg(), + env: { NPM_CONFIG_REGISTRY: registry, DOCS_REGION: 'hidden-env-value' }, + } + + await (mgr as any).initOneServerInternal('docs-server', cfg) + + const message = showMessageStub.firstCall.args[0].message as string + expect(message).to.include('Environment variables: DOCS_REGION, NPM_CONFIG_REGISTRY\n') + expect(message).to.include('Package index: https://npm.example.com/\n') + expect(message).to.not.include('hidden-password') + expect(message).to.not.include('index-user') + expect(message).to.not.include('hidden-env-value') + }) + } + + it('shows the URLs in the command without their user name and password', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const local: MCPServerConfig = { + command: 'uvx', + args: [ + '--default-index=https://index-user:hidden-password@pypi.example.com/simple', + 'docs-server@1.2.4', + '--docs-url=https://docs.example.com/v1@latest', + ], + __configPath__: globalAgent, + __registryServer__: true, + } + const remote: MCPServerConfig = { + url: 'https://url-user:hidden-password@mcp.example.com/docs', + __configPath__: globalAgent, + __registryServer__: true, + } + + await (mgr as any).initOneServerInternal('docs-server', local) + await (mgr as any).initOneServerInternal('remote-docs', remote) + + const [localMessage, remoteMessage] = showMessageStub + .getCalls() + .map((call: sinon.SinonSpyCall) => call.args[0].message as string) + expect(localMessage).to.include( + 'Command: uvx --default-index=https://pypi.example.com/simple docs-server@1.2.4 ' + + '--docs-url=https://docs.example.com/v1@latest\n' + ) + expect(remoteMessage).to.include('Command: https://mcp.example.com/docs\n') + for (const message of [localMessage, remoteMessage]) { + expect(message).to.not.include('hidden-password') + expect(message).to.not.match(/index-user|url-user/) + } + }) + + it('leaves a URL in the command as it is when a backslash comes before its @', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const cfg: MCPServerConfig = { + command: 'uvx', + args: ['--default-index=https://index.example.com\\@pypi.example.com/simple', 'docs-server@1.2.4'], + __configPath__: globalAgent, + __registryServer__: true, + } + + await (mgr as any).initOneServerInternal('docs-server', cfg) + + const message = showMessageStub.firstCall.args[0].message as string + expect(message).to.include( + 'Command: uvx --default-index=https://index.example.com\\@pypi.example.com/simple docs-server@1.2.4\n' + ) + }) + + it('builds the consent prompt for a long command argument in linear time', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const cfg: MCPServerConfig = { + command: 'uvx', + args: ['a.'.repeat(100000)], + __configPath__: globalAgent, + __registryServer__: true, + } + + const start = Date.now() + await (mgr as any).initOneServerInternal('docs-server', cfg) + + expect(Date.now() - start).to.be.lessThan(1000) + expect(showMessageStub.calledOnce).to.be.true + }) + + for (const [kind, configPath] of [ + ['a registry server', globalAgent], + ['a server from a workspace config', '/tmp/ws-a/.amazonq/agents/default.json'], + ]) { + it(`shows a package index that is not a URL as a placeholder for ${kind}`, async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const cfg: MCPServerConfig = { + ...localCfg(), + env: { UV_DEFAULT_INDEX: 'hidden-index-value' }, + __configPath__: configPath, + } + + await (mgr as any).initOneServerInternal('docs-server', cfg) + + const message = showMessageStub.firstCall.args[0].message as string + expect(message).to.include('Package index: (not a URL)\n') + expect(message).to.not.include('hidden-index-value') + }) + } + + it('keeps the workspace prompt for a registry server in the agent config of a workspace folder', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const workspaceAgent = '/tmp/ws-a/.amazonq/agents/default.json' + + await (mgr as any).initOneServerInternal('docs-server', { ...localCfg(), __configPath__: workspaceAgent }) + + const request = showMessageStub.firstCall.args[0] + expect(request.message).to.include('Amazon Q — Untrusted MCP Server') + expect(request.message).to.include(`• Source: ${workspaceAgent}`) + expect(request.actions.map((a: { title: string }) => a.title)).to.deep.equal([ + 'View full configuration', + 'Allow for this server', + 'Deny', + ]) + }) + + it('starts a registry server whose configuration the user allowed without asking', async () => { + const mgr = await buildMgr() + hasApprovalStub.resolves(true) + + let error: Error | undefined + try { + await (mgr as any).initOneServerInternal('docs-server', localCfg()) + } catch (e: any) { + error = e + } + + expect(error?.message).to.equal('PASSED_THE_GATE') + expect(showMessageStub.called).to.be.false + }) + + it('records the approval when the user allows a registry server', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Allow for this server' }) + const cfg = localCfg() + + let error: Error | undefined + try { + await (mgr as any).initOneServerInternal('docs-server', cfg) + } catch (e: any) { + error = e + } + + expect(error?.message).to.equal('PASSED_THE_GATE') + sinon.assert.calledOnce(recordApprovalStub) + sinon.assert.calledWith(recordApprovalStub, sinon.match.any, sinon.match.any, 'docs-server', cfg, globalAgent) + }) + + it('asks again in the same session when the registry changes a configuration that the user denied', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + await (mgr as any).initOneServerInternal('docs-server', localCfg()) + + showMessageStub.resetHistory() + const changed = { ...localCfg(), args: ['-y', '@example/docs-server@1.2.5'] } + await (mgr as any).initOneServerInternal('docs-server', changed) + + expect(showMessageStub.calledOnce).to.be.true + }) + + it('does not ask for a server in the global agent config that is not from the registry', async () => { + const mgr = await buildMgr() + const cfg: MCPServerConfig = { command: 'sh', args: [], __configPath__: globalAgent } + + let error: Error | undefined + try { + await (mgr as any).initOneServerInternal('own-server', cfg) + } catch (e: any) { + error = e + } + + expect(error?.message).to.equal('PASSED_THE_GATE') + expect(showMessageStub.called).to.be.false + }) + + for (const [kind, configPath] of [ + ['a registry server', globalAgent], + ['a server from a workspace config', '/tmp/ws-a/.amazonq/agents/default.json'], + ]) { + it(`does not start ${kind} when the consent prompt cannot be shown`, async () => { + const mgr = await buildMgr() + showMessageStub.rejects(new Error('no window')) + + await (mgr as any).initOneServerInternal('docs-server', { ...localCfg(), __configPath__: configPath }) + + expect(setStateSpy.calledWith('docs-server', McpServerStatus.FAILED, 0, 'consent prompt failed')).to.be.true + expect(recordApprovalStub.called).to.be.false + }) + } + + it('records an approval from the install preview under the name and path that the server starts with', async () => { + const mgr = await buildMgr() + const cfg = localCfg() + + await mgr.recordRegistryServerApproval('docs-server', cfg, globalAgent) + + sinon.assert.calledOnce(recordApprovalStub) + sinon.assert.calledWith(recordApprovalStub, sinon.match.any, sinon.match.any, 'docs-server', cfg, globalAgent) + }) + + it('asks again when the user installs or saves a server whose configuration they denied in the session', async () => { + const mgr = await buildMgr() + sinon.stub(mcpUtils, 'saveServerSpecificAgentConfig').resolves() + ;(mgr as any).agentConfig = { + name: 'default', + description: 'default', + mcpServers: {}, + tools: [], + allowedTools: [], + toolsSettings: {}, + resources: [], + } + showMessageStub.resolves({ title: 'Deny' }) + await (mgr as any).initOneServerInternal('docs-server', localCfg()) + sinon.assert.calledOnce(showMessageStub) + + // Install in the preview and Save in the edit view call addRegistryServer with the same configuration + const { __registryServer__, __configPath__, ...registryCfg } = localCfg() + await mgr.addRegistryServer('docs-server', registryCfg, globalAgent) + + sinon.assert.calledTwice(showMessageStub) + }) +}) + +describe('registry sync of a new version of an installed registry server', () => { + const fakeHome = '/home/testuser' + const globalAgent = mcpUtils.getGlobalAgentConfigPath(fakeHome) + const registryServer = (version: string) => ({ + name: 'docs-server', + description: 'Searches the team docs', + version, + packages: [{ registryType: 'npm', identifier: '@example/docs-server', transport: { type: 'stdio' } }], + }) + const { McpServerConfigConverter } = require('./mcpServerConfigConverter') + const { fingerprintServerConfig } = require('./mcpConsentStore') + // The configuration of version 1.2.3, which the user approved and which runs now + const runningCfg = (): MCPServerConfig => ({ + ...new McpServerConfigConverter().convertRegistryServer(registryServer('1.2.3')), + __configPath__: globalAgent, + __registryServer__: true, + __cachedVersion__: '1.2.3', + }) + + let showMessageStub: sinon.SinonStub + let removeServerSpy: sinon.SinonSpy + let addRegistryServerSpy: sinon.SinonSpy + // The consent store, as the keys of its approvals + let approvals: Set + + async function buildMgr(): Promise { + const consentStore = require('./mcpConsentStore') + approvals = new Set() + const approvalKey = (name: string, cfg: MCPServerConfig, configPath: string) => + `${name}|${configPath}|${fingerprintServerConfig(cfg)}` + sinon + .stub(consentStore, 'hasApproval') + .callsFake(async (_w: any, _l: any, name: any, cfg: any, p: any) => + approvals.has(approvalKey(name, cfg, p)) + ) + sinon.stub(consentStore, 'recordApproval').callsFake(async (_w: any, _l: any, name: any, cfg: any, p: any) => { + approvals.add(approvalKey(name, cfg, p)) + }) + sinon.stub(consentStore, 'removeApproval').callsFake(async (_w: any, _l: any, name: any, p: any) => { + for (const key of [...approvals]) { + if (key.startsWith(`${name}|${p}|`)) { + approvals.delete(key) + } + } + }) + sinon.stub(mcpUtils, 'saveServerSpecificAgentConfig').resolves() + + showMessageStub = sinon.stub() + const mgr = await McpManager.init([], { + ...features, + workspace: { ...fakeWorkspace, fs: { ...fakeWorkspace.fs, getUserHomeDir: () => fakeHome } }, + lsp: { window: { showMessageRequest: showMessageStub, showDocument: sinon.stub().resolves({}) } }, + } as any) + await mgr.setWorkspaceTrust('trusted') + // Stops a start right after the consent gate, so no test starts a real process + sinon.stub(mgr as any, 'cleanupExistingServer').rejects(new Error('PASSED_THE_GATE')) + + const running = runningCfg() + ;(mgr as any).mcpServers.set('docs-server', running) + ;(mgr as any).serverNameMapping.set('docs-server', 'docs-server') + ;(mgr as any).agentConfig = { + name: 'default', + description: 'default', + mcpServers: { 'docs-server': { type: 'registry' } }, + tools: ['@docs-server'], + allowedTools: [], + toolsSettings: {}, + resources: [], + useLegacyMcpJson: false, + } + approvals.add(approvalKey('docs-server', running, globalAgent)) + removeServerSpy = sinon.spy(mgr, 'removeServer') + addRegistryServerSpy = sinon.spy(mgr, 'addRegistryServer') + return mgr + } + + afterEach(async () => { + sinon.restore() + try { + await McpManager.instance.close() + } catch {} + }) + + it('asks before it replaces the server, and keeps the approved configuration when the user denies', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const running = (mgr as any).mcpServers.get('docs-server') + + const updated = await (mgr as any).checkAndUpdateVersion( + 'docs-server', + 'docs-server', + registryServer('1.2.4'), + running + ) + + expect(updated).to.be.false + sinon.assert.calledOnce(showMessageStub) + const message = showMessageStub.firstCall.args[0].message as string + expect(message).to.include('Amazon Q — MCP Server from the Registry') + expect(message).to.include('@example/docs-server@1.2.4') + sinon.assert.notCalled(removeServerSpy) + sinon.assert.notCalled(addRegistryServerSpy) + expect((mgr as any).mcpServers.get('docs-server')).to.equal(running) + expect(approvals.size).to.equal(1) + }) + + it('does not ask again in the same session after the user denied the new version', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const running = (mgr as any).mcpServers.get('docs-server') + + await (mgr as any).checkAndUpdateVersion('docs-server', 'docs-server', registryServer('1.2.4'), running) + await (mgr as any).checkAndUpdateVersion('docs-server', 'docs-server', registryServer('1.2.4'), running) + + sinon.assert.calledOnce(showMessageStub) + sinon.assert.notCalled(removeServerSpy) + }) + + it('keeps the server when the prompt cannot be shown', async () => { + const mgr = await buildMgr() + showMessageStub.rejects(new Error('no window')) + const running = (mgr as any).mcpServers.get('docs-server') + + const updated = await (mgr as any).checkAndUpdateVersion( + 'docs-server', + 'docs-server', + registryServer('1.2.4'), + running + ) + + expect(updated).to.be.false + sinon.assert.notCalled(removeServerSpy) + expect((mgr as any).mcpServers.get('docs-server')).to.equal(running) + expect(approvals.size).to.equal(1) + + // A prompt that could not be shown is not a denial, so the next sync asks again + showMessageStub.reset() + showMessageStub.resolves({ title: 'Deny' }) + await (mgr as any).checkAndUpdateVersion('docs-server', 'docs-server', registryServer('1.2.4'), running) + sinon.assert.calledOnce(showMessageStub) + }) + + it('does not ask about a new version of a disabled server, and does not turn it on', async () => { + const mgr = await buildMgr() + const running = (mgr as any).mcpServers.get('docs-server') + running.disabled = true + + const updated = await (mgr as any).checkAndUpdateVersion( + 'docs-server', + 'docs-server', + registryServer('1.2.4'), + running + ) + + expect(updated).to.be.false + sinon.assert.notCalled(showMessageStub) + sinon.assert.notCalled(removeServerSpy) + sinon.assert.notCalled(addRegistryServerSpy) + }) + + it('does not reinstall a server that the user turned off while the prompt was open', async () => { + const mgr = await buildMgr() + const running = (mgr as any).mcpServers.get('docs-server') + showMessageStub.callsFake(async () => { + // Turning a server off in the MCP settings changes its configuration in place + running.disabled = true + return { title: 'Allow for this server' } + }) + + const updated = await (mgr as any).checkAndUpdateVersion( + 'docs-server', + 'docs-server', + registryServer('1.2.4'), + running + ) + + expect(updated).to.be.false + sinon.assert.notCalled(removeServerSpy) + sinon.assert.notCalled(addRegistryServerSpy) + }) + + it('asks about the new version again after the kept configuration starts again', async () => { + const mgr = await buildMgr() + ;(mgr as any).currentRegistry = { + servers: [registryServer('1.2.4')], + lastFetched: new Date(), + url: 'https://registry.example.com/registry.json', + } + showMessageStub.rejects(new Error('no window')) + const running = (mgr as any).mcpServers.get('docs-server') + await (mgr as any).checkAndUpdateVersion('docs-server', 'docs-server', registryServer('1.2.4'), running) + + // The server starts its kept configuration again, for example after the user turns it off and on + ;(mgr as any).cacheRegistryVersion('docs-server', running) + + expect(running.__cachedVersion__).to.equal('1.2.3') + showMessageStub.reset() + showMessageStub.resolves({ title: 'Deny' }) + await (mgr as any).checkAndUpdateVersion('docs-server', 'docs-server', registryServer('1.2.4'), running) + sinon.assert.calledOnce(showMessageStub) + }) + + it('records the registry version of a started configuration that has none', async () => { + const mgr = await buildMgr() + ;(mgr as any).currentRegistry = { + servers: [registryServer('1.2.4')], + lastFetched: new Date(), + url: 'https://registry.example.com/registry.json', + } + const { __cachedVersion__, ...cfg } = runningCfg() + + ;(mgr as any).cacheRegistryVersion('docs-server', cfg) + + expect((cfg as MCPServerConfig).__cachedVersion__).to.equal('1.2.4') + }) + + it('reinstalls the server with one prompt after the user allows the new version', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Allow for this server' }) + // A later sync can load a registry with another version while the prompt is open + ;(mgr as any).currentRegistry = { + servers: [registryServer('1.2.5')], + lastFetched: new Date(), + url: 'https://registry.example.com/registry.json', + } + const newCfg: MCPServerConfig = { + ...new McpServerConfigConverter().convertRegistryServer(registryServer('1.2.4')), + __cachedVersion__: '1.2.4', + } + + let error: Error | undefined + try { + await (mgr as any).reinstallServer('docs-server', 'docs-server', registryServer('1.2.4')) + } catch (e: any) { + error = e + } + + // The new configuration passed the consent gate of its start without a second prompt + expect(error?.message).to.equal('PASSED_THE_GATE') + sinon.assert.calledOnce(showMessageStub) + sinon.assert.calledOnce(removeServerSpy) + // The server records the version that the prompt asked about + sinon.assert.calledOnceWithExactly(addRegistryServerSpy, 'docs-server', newCfg, globalAgent) + expect(removeServerSpy.calledBefore(addRegistryServerSpy)).to.be.true + // Only the new configuration is approved now + expect([...approvals]).to.deep.equal([ + `docs-server|${globalAgent}|${fingerprintServerConfig({ ...newCfg, __configPath__: globalAgent })}`, + ]) + }) + + it('reinstalls without a prompt when the user approved the new configuration before', async () => { + const mgr = await buildMgr() + const newCfg = new McpServerConfigConverter().convertRegistryServer(registryServer('1.2.4')) + approvals.add(`docs-server|${globalAgent}|${fingerprintServerConfig(newCfg)}`) + + let error: Error | undefined + try { + await (mgr as any).reinstallServer('docs-server', 'docs-server', registryServer('1.2.4')) + } catch (e: any) { + error = e + } + + expect(error?.message).to.equal('PASSED_THE_GATE') + sinon.assert.notCalled(showMessageStub) + sinon.assert.calledOnce(addRegistryServerSpy) + }) + + it('reports a reinstall after the user allows the new version', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Allow for this server' }) + addRegistryServerSpy.restore() + const addRegistryServer = sinon.stub(mgr, 'addRegistryServer').resolves() + const running = (mgr as any).mcpServers.get('docs-server') + + const updated = await (mgr as any).checkAndUpdateVersion( + 'docs-server', + 'docs-server', + registryServer('1.2.4'), + running + ) + + expect(updated).to.be.true + sinon.assert.calledOnce(addRegistryServer) + }) + + it('does not replace a server that changed while the prompt was open', async () => { + const mgr = await buildMgr() + const saved = { ...runningCfg(), env: { DOCS_REGION: 'eu-west-1' } } + showMessageStub.callsFake(async () => { + // The user saves the server in the edit view before answering the prompt + ;(mgr as any).mcpServers.set('docs-server', saved) + return { title: 'Allow for this server' } + }) + const running = (mgr as any).mcpServers.get('docs-server') + + const updated = await (mgr as any).checkAndUpdateVersion( + 'docs-server', + 'docs-server', + registryServer('1.2.4'), + running + ) + + expect(updated).to.be.false + sinon.assert.notCalled(removeServerSpy) + sinon.assert.notCalled(addRegistryServerSpy) + expect((mgr as any).mcpServers.get('docs-server')).to.equal(saved) + }) +}) + +describe('approval of a registry server from the install preview, with the real consent store', () => { + const fakeHome = '/home/testuser' + const globalAgentUri = require('vscode-uri').URI.file(mcpUtils.getGlobalAgentConfigPath(fakeHome)).toString() + // A name that sanitizeName changes, so the test also checks that both sides use the same name + const registryName = 'docs.server' + const remoteCfg = (): MCPServerConfig => ({ + url: 'https://mcp.example.com/docs', + headers: { 'X-Team': 'docs' }, + __cachedVersion__: '2.0.0', + }) + + afterEach(async () => { + sinon.restore() + try { + await McpManager.instance.close() + } catch {} + }) + + it('starts the approved configuration without asking, and asks again after the registry changes it', async () => { + const files = new Map() + const showMessageRequest = sinon.stub().resolves({ title: 'Deny' }) + const mgr: any = await McpManager.init([], { + ...features, + workspace: { + ...fakeWorkspace, + fs: { + ...fakeWorkspace.fs, + getUserHomeDir: () => fakeHome, + exists: async (p: string) => files.has(p), + readFile: async (p: string) => Buffer.from(files.get(p) ?? ''), + writeFile: async (p: string, data: string) => { + files.set(p, data) + }, + }, + }, + lsp: { window: { showMessageRequest, showDocument: sinon.stub().resolves({}) } }, + } as any) + await mgr.setWorkspaceTrust('trusted') + // Stops the start right after the consent gate + sinon.stub(mgr, 'cleanupExistingServer').rejects(new Error('PASSED_THE_GATE')) + + await mgr.recordRegistryServerApproval(registryName, remoteCfg(), globalAgentUri) + const started = { ...remoteCfg(), __configPath__: globalAgentUri, __registryServer__: true } + let error: Error | undefined + try { + await mgr.initOneServerInternal(mcpUtils.sanitizeName(registryName), started) + } catch (e: any) { + error = e + } + + expect(error?.message).to.equal('PASSED_THE_GATE') + sinon.assert.notCalled(showMessageRequest) + + const changed = { ...started, url: 'https://mcp.other.example.com/docs' } + await mgr.initOneServerInternal(mcpUtils.sanitizeName(registryName), changed) + sinon.assert.calledOnce(showMessageRequest) + }) + + it('checks a registry server that the loader reads, before discoverAllServers starts it', async () => { + // A home folder with a drive on Windows, as a real one has: the loader reads a path without a + // drive, such as \home\testuser\..., as the UNC path \\home\testuser\... + const home = require('path').resolve('/home/testuser') + const globalAgent = mcpUtils.getGlobalAgentConfigPath(home) + const files = new Map([ + [ + globalAgent, + JSON.stringify({ + name: 'default', + mcpServers: { 'docs-server': { type: 'registry' } }, + tools: ['@docs-server'], + allowedTools: [], + }), + ], + ]) + const showMessageRequest = sinon.stub().resolves({ title: 'Deny' }) + const mgr: any = await McpManager.init([globalAgent], { + ...features, + workspace: { + fs: { + getUserHomeDir: () => home, + exists: async (p: string) => files.has(p), + readFile: async (p: string) => Buffer.from(files.get(p) ?? ''), + writeFile: async (p: string, data: string) => { + files.set(p, data) + }, + mkdir: async () => {}, + readdir: async () => [], + }, + getAllWorkspaceFolders: () => [], + }, + lsp: { window: { showMessageRequest, showDocument: sinon.stub().resolves({}) } }, + } as any) + await mgr.setWorkspaceTrust('trusted') + const started: string[] = [] + sinon.stub(mgr, 'cleanupExistingServer').callsFake(async (name: unknown) => { + started.push(String(name)) + throw new Error('PASSED_THE_GATE') + }) + const registry = (url: string) => ({ + servers: [{ name: 'docs-server', version: '1.0.0', description: 'Docs', remotes: [{ type: 'sse', url }] }], + lastFetched: new Date(), + url: 'https://registry.example.com/registry.json', + }) + mgr.registryUrlProvided = true + mgr.currentRegistry = registry('https://mcp.example.com/v1') + // What the install preview records for the configuration that it showed + const { McpServerConfigConverter } = require('./mcpServerConfigConverter') + const shown = new McpServerConfigConverter().convertRegistryServer(mgr.currentRegistry.servers[0]) + await mgr.recordRegistryServerApproval('docs-server', shown, globalAgent) + + // The stub above stops the start right after the gate, and that error reaches discoverAllServers + await mgr.discoverAllServers().catch(() => undefined) + + expect(mgr.mcpServers.get('docs-server')?.__registryServer__).to.equal(true) + sinon.assert.notCalled(showMessageRequest) + expect(started).to.deep.equal(['docs-server']) + + // The registry changes the server: the next load asks before it starts the server + mgr.currentRegistry = registry('https://mcp.example.com/v2') + await mgr.discoverAllServers().catch(() => undefined) + + sinon.assert.calledOnce(showMessageRequest) + expect(showMessageRequest.firstCall.args[0].message).to.include('Amazon Q — MCP Server from the Registry') + expect(started).to.deep.equal(['docs-server']) + }) +}) + describe('workspace trust for stdio MCP servers', () => { const fakeHome = '/home/testuser' const globalMcp = mcpUtils.getGlobalMcpConfigPath(fakeHome) diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.ts index 66b5d4d0da..6210565d85 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.ts @@ -64,6 +64,7 @@ import { OAuthClient } from './mcpOauthClient' import { AgentPermissionManager } from './agentPermissionManager' import { McpRegistryService } from './mcpRegistryService' import { McpRegistryData } from './mcpTypes' +import { MCP_REGISTRY_CONSTANTS } from './mcpRegistryConstants' import { WorkspaceTrustState, isFolderApproved, @@ -94,6 +95,27 @@ function formatConsentPreview(value: string): string { : value } +/** The environment variables that set the package index of an npx or uvx server */ +const PACKAGE_INDEX_ENV_VARS = [MCP_REGISTRY_CONSTANTS.NPM.ENV_VAR, MCP_REGISTRY_CONSTANTS.PYPI.ENV_VAR] + +/** + * The user name and password of a URL in a text, with the scheme of the URL in group 1. The scheme has at most + * 64 characters. A URL with a backslash before its '@' is left as it is. + */ +const URL_CREDENTIALS = /\b([a-z][a-z\d+.-]{0,63}:\/\/)[^\s/\\?#]*@/gi + +/** A URL without its user name and password, or a placeholder when the text is not a URL */ +function urlWithoutCredentials(text: string): string { + try { + const url = new URL(text) + url.username = '' + url.password = '' + return url.toString() + } catch { + return '(not a URL)' + } +} + /** * Manages MCP servers and their tools */ @@ -643,6 +665,155 @@ export class McpManager { }) } + /** + * Whether a server needs the consent of the user before it starts, and which prompt it gets. Returns undefined + * when no consent is needed. + * + * Workspace-scoped configs live in a folder the user opened and may contain configuration that the user did not + * write. Global configs (~/.aws/amazonq/...) are user-authored and trusted implicitly. + * + * A registry server runs what the MCP registry lists. The install preview records the approval of the + * configuration that it showed (recordRegistryServerApproval). Any other configuration of a registry server + * needs approval before the server starts: after a version change in the registry, when the language server + * loads the configuration again, or after Save in the edit view. A registry server in the agent config of a + * workspace folder keeps the workspace prompt, because that file can add environment variables and headers. + */ + private consentScope( + cfg: MCPServerConfig + ): { configPath: string; isWorkspaceScoped: boolean; kind: 'workspace-scoped' | 'registry' } | undefined { + const configPath = cfg.__configPath__ + ? normalizePathFromUri(cfg.__configPath__, this.features.logging) + : undefined + if (!configPath) { + return undefined + } + const home = this.features.workspace.fs.getUserHomeDir() + const globalPaths = [ + getGlobalMcpConfigPath(home), + getGlobalAgentConfigPath(home), + getGlobalPersonaConfigPath(home), + ] + const isWorkspaceScoped = !globalPaths.includes(configPath) + if (!isWorkspaceScoped && cfg.__registryServer__ !== true) { + return undefined + } + return { configPath, isWorkspaceScoped, kind: isWorkspaceScoped ? 'workspace-scoped' : 'registry' } + } + + /** + * Asks the user to allow this configuration of a server. Returns 'approved' without a prompt when the consent + * store has an approval of the configuration, and 'denied' when the user denied it earlier in this session. + * Returns 'allowed' when the user allows it now; the caller records the approval. Returns 'denied' when the user + * denies it or closes the prompt, and then remembers the denial for the session. Returns 'failed' when the prompt + * cannot be shown. + */ + private async askForServerConsent( + serverName: string, + cfg: MCPServerConfig, + scope: { configPath: string; isWorkspaceScoped: boolean; kind: string } + ): Promise<'approved' | 'allowed' | 'denied' | 'failed'> { + const { configPath, isWorkspaceScoped } = scope + const denyKey = `${serverName}|${configPath}|${fingerprintServerConfig(cfg)}` + if (this.sessionDeniedConsent.has(denyKey)) { + return 'denied' + } + if (await hasApproval(this.features.workspace, this.features.logging, serverName, cfg, configPath)) { + return 'approved' + } + + // A URL in the command, such as the package index of a PyPI server, is shown without a user name or password + const cmdLine = formatConsentPreview( + [cfg.command ?? cfg.url ?? '(none)', ...(cfg.args ?? [])].join(' ').replace(URL_CREDENTIALS, '$1') + ) + // Surface the environment variables and headers the server will actually be + // launched with. Names only, never values: a config may legitimately hold + // tokens, and this string is shown in a dialog and written to logs. Values are + // covered by the fingerprint, so any value change re-prompts. + const env = effectiveEnv(cfg) + const envKeys = Object.keys(env) + const headerNames = Object.keys(effectiveHeaders(cfg)) + const envLine = + envKeys.length > 0 + ? `Environment variables: ${formatConsentPreview(envKeys.join(', '))}\n` + : `Environment variables: (none)\n` + const headerLine = headerNames.length > 0 ? `Headers: ${formatConsentPreview(headerNames.join(', '))}\n` : '' + // The exception is a package index, whose URL is shown without a user name or password. + const packageIndexes = PACKAGE_INDEX_ENV_VARS.map(name => env[name]).filter(value => !!value) + const packageIndexLine = + packageIndexes.length > 0 + ? `Package index: ${formatConsentPreview(packageIndexes.map(urlWithoutCredentials).join(', '))}\n` + : '' + const allowBtn = { title: 'Allow for this server' } + const denyBtn = { title: 'Deny' } + const reviewBtn = { title: 'View full configuration' } + const message = !isWorkspaceScoped + ? `Amazon Q — MCP Server from the Registry\n\n` + + `The MCP registry lists this server with a configuration that you have not allowed yet, ` + + `for example after the registry changed the server to a new version.\n` + + `Server: ${serverName}\n` + + `Command: ${cmdLine}\n` + + envLine + + packageIndexLine + + headerLine + + `\n` + + (cfg.command + ? `Running this server executes the above command on your machine, ` + + `with the environment variables listed above. ` + + `Variables such as NODE_OPTIONS can cause additional code to run. ` + : `Starting this server connects Amazon Q to the above URL, with the headers listed above. `) + + `Only allow if you expect this server and this configuration from your MCP registry.\n\n` + + `If you allow, you won't be asked again unless the registry changes the server configuration.` + : `Amazon Q — Untrusted MCP Server\n\n` + + `A workspace configuration file wants to start an MCP server.\n` + + `Server: ${serverName}\n` + + `Command: ${cmdLine}\n` + + envLine + + packageIndexLine + + headerLine + + `• Source: ${configPath}\n\n` + + `Running this server executes the above command on your machine, ` + + `with the environment variables listed above. ` + + `Use View full configuration to inspect the source before allowing. ` + + `Variables such as NODE_OPTIONS can cause additional code to run. ` + + `Only allow if you trust the authors of this workspace.\n\n` + + `Your choice will be remembered for this workspace. ` + + `If you allow, you won't be asked again unless the server configuration changes.` + + while (true) { + let choice: { title: string } | null | undefined + try { + choice = await this.features.lsp.window.showMessageRequest({ + type: MessageType.Warning, + message, + // The command of a registry server comes from the registry, not from its agent config file + actions: isWorkspaceScoped ? [reviewBtn, allowBtn, denyBtn] : [allowBtn, denyBtn], + }) + } catch (e: any) { + this.features.logging.warn(`MCP: consent prompt failed for '${serverName}': ${e?.message}`) + return 'failed' + } + if (choice?.title === reviewBtn.title) { + try { + await this.features.lsp.window.showDocument({ + uri: URI.file(configPath).toString(), + takeFocus: true, + }) + } catch (e: any) { + this.features.logging.warn(`MCP: failed to open configuration for '${serverName}': ${e?.message}`) + } + continue + } + if (choice?.title !== allowBtn.title) { + this.features.logging.info( + `MCP: user declined consent for ${scope.kind} server '${serverName}' (response: ${choice?.title ?? 'dismissed'})` + ) + this.sessionDeniedConsent.add(denyKey) + return 'denied' + } + return 'allowed' + } + } + private async initOneServerInternal( serverName: string, cfg: MCPServerConfig, @@ -664,103 +835,27 @@ export class McpManager { } this.releaseTrustHold(serverName) - // Consent gate for workspace-scoped MCP configs (P417451767). - // Workspace-scoped configs live in a folder the user opened and may be attacker-controlled. - // Global configs (~/.aws/amazonq/...) are user-authored and trusted implicitly. - const home = this.features.workspace.fs.getUserHomeDir() - const configPath = cfg.__configPath__ - ? normalizePathFromUri(cfg.__configPath__, this.features.logging) - : undefined - const globalMcp = getGlobalMcpConfigPath(home) - const globalAgent = getGlobalAgentConfigPath(home) - const globalPersona = getGlobalPersonaConfigPath(home) - const isWorkspaceScoped = - !!configPath && configPath !== globalMcp && configPath !== globalAgent && configPath !== globalPersona - if (isWorkspaceScoped && configPath) { - const denyKey = `${serverName}|${configPath}|${fingerprintServerConfig(cfg)}` - if (this.sessionDeniedConsent.has(denyKey)) { + // Consent gate for workspace-scoped MCP configs and for registry servers (see consentScope) + const consentScope = this.consentScope(cfg) + if (consentScope) { + const consent = await this.askForServerConsent(serverName, cfg, consentScope) + if (consent === 'failed') { + this.setState(serverName, McpServerStatus.FAILED, 0, 'consent prompt failed') + return + } + if (consent === 'denied') { this.setState(serverName, McpServerStatus.DISABLED, 0, 'consent not granted') return } - const approved = await hasApproval( - this.features.workspace, - this.features.logging, - serverName, - cfg, - configPath - ) - if (!approved) { - const cmdLine = formatConsentPreview( - [cfg.command ?? cfg.url ?? '(none)', ...(cfg.args ?? [])].join(' ') + if (consent === 'allowed') { + await recordApproval( + this.features.workspace, + this.features.logging, + serverName, + cfg, + consentScope.configPath ) - // Surface the environment variables and headers the server will actually be - // launched with. Names only, never values: a config may legitimately hold - // tokens, and this string is shown in a dialog and written to logs. Values are - // covered by the fingerprint, so any value change re-prompts. - const envKeys = Object.keys(effectiveEnv(cfg)) - const headerNames = Object.keys(effectiveHeaders(cfg)) - const envLine = - envKeys.length > 0 - ? `Environment variables: ${formatConsentPreview(envKeys.join(', '))}\n` - : `Environment variables: (none)\n` - const headerLine = - headerNames.length > 0 ? `Headers: ${formatConsentPreview(headerNames.join(', '))}\n` : '' - const allowBtn = { title: 'Allow for this server' } - const denyBtn = { title: 'Deny' } - const reviewBtn = { title: 'View full configuration' } - - while (true) { - let choice: { title: string } | null | undefined - try { - choice = await this.features.lsp.window.showMessageRequest({ - type: MessageType.Warning, - message: - `Amazon Q — Untrusted MCP Server\n\n` + - `A workspace configuration file wants to start an MCP server.\n` + - `Server: ${serverName}\n` + - `Command: ${cmdLine}\n` + - envLine + - headerLine + - `• Source: ${configPath}\n\n` + - `Running this server executes the above command on your machine, ` + - `with the environment variables listed above. ` + - `Use View full configuration to inspect the source before allowing. ` + - `Variables such as NODE_OPTIONS can cause additional code to run. ` + - `Only allow if you trust the authors of this workspace.\n\n` + - `Your choice will be remembered for this workspace. ` + - `If you allow, you won't be asked again unless the server configuration changes.`, - actions: [reviewBtn, allowBtn, denyBtn], - }) - } catch (e: any) { - this.features.logging.warn(`MCP: consent prompt failed for '${serverName}': ${e?.message}`) - this.setState(serverName, McpServerStatus.FAILED, 0, 'consent prompt failed') - return - } - if (choice?.title === reviewBtn.title) { - try { - await this.features.lsp.window.showDocument({ - uri: URI.file(configPath).toString(), - takeFocus: true, - }) - } catch (e: any) { - this.features.logging.warn( - `MCP: failed to open configuration for '${serverName}': ${e?.message}` - ) - } - continue - } - if (choice?.title !== allowBtn.title) { - this.features.logging.info( - `MCP: user declined consent for workspace-scoped server '${serverName}' (response: ${choice?.title ?? 'dismissed'})` - ) - this.sessionDeniedConsent.add(denyKey) - this.setState(serverName, McpServerStatus.DISABLED, 0, 'consent not granted') - return - } - await recordApproval(this.features.workspace, this.features.logging, serverName, cfg, configPath) - this.features.logging.info(`MCP: recorded consent for workspace-scoped server '${serverName}'`) - break - } + this.features.logging.info(`MCP: recorded consent for ${consentScope.kind} server '${serverName}'`) } } @@ -1026,16 +1121,7 @@ export class McpManager { } // Cache version for registry servers - if (this.currentRegistry) { - const unsanitizedName = this.serverNameMapping.get(serverName) || serverName - const registryServer = this.currentRegistry.servers.find(s => s.name === unsanitizedName) - if (registryServer) { - cfg.__cachedVersion__ = registryServer.version - this.features.logging.debug( - `MCP Registry: Cached version ${registryServer.version} for server '${unsanitizedName}'` - ) - } - } + this.cacheRegistryVersion(serverName, cfg) this.setState(serverName, McpServerStatus.ENABLED, resp.tools.length) this.emitToolsChanged(serverName) @@ -1229,6 +1315,24 @@ export class McpManager { } } + /** + * Records that the user approved this configuration of a registry server, as the install preview showed it, so + * that the server starts without the consent prompt. A different configuration needs approval again. + */ + public async recordRegistryServerApproval( + serverName: string, + cfg: MCPServerConfig, + configPath: string + ): Promise { + await recordApproval( + this.features.workspace, + this.features.logging, + sanitizeName(serverName), + cfg, + normalizePathFromUri(configPath, this.features.logging) + ) + } + /** * Add a registry server: persist config, register in memory, and initialize. */ @@ -1286,7 +1390,7 @@ export class McpManager { ) // Store additional headers/env separately and merge for runtime - const newCfg: MCPServerConfig = { ...cfg, __configPath__: configPath } + const newCfg: MCPServerConfig = { ...cfg, __configPath__: configPath, __registryServer__: true } if (additionalHeaders && Object.keys(additionalHeaders).length > 0) { newCfg.__additionalHeaders__ = additionalHeaders } @@ -1296,9 +1400,41 @@ export class McpManager { this.mcpServers.set(sanitizedName, newCfg) this.serverNameMapping.set(sanitizedName, serverName) + // The user asks for this server now (Install in the preview, Save in the edit view), so a denial earlier in + // the session does not keep it off without a question + this.forgetSessionDenials(sanitizedName, configPath) await this.initOneServer(sanitizedName, newCfg, AuthIntent.Interactive) } + /** Forgets the consent denials of this session for a server from one config file */ + private forgetSessionDenials(serverName: string, configPath: string): void { + const prefix = `${serverName}|${normalizePathFromUri(configPath, this.features.logging)}|` + for (const key of [...this.sessionDeniedConsent]) { + if (key.startsWith(prefix)) { + this.sessionDeniedConsent.delete(key) + } + } + } + + /** + * Records which registry version the configuration of a started server was built from. A configuration keeps the + * version that it has: after the user denies a new version in the registry sync, the server runs its approved + * configuration of the earlier version, and the next sync must still find the new version. + */ + private cacheRegistryVersion(serverName: string, cfg: MCPServerConfig): void { + if (!this.currentRegistry || cfg.__cachedVersion__) { + return + } + const unsanitizedName = this.serverNameMapping.get(serverName) || serverName + const registryServer = this.currentRegistry.servers.find(s => s.name === unsanitizedName) + if (registryServer) { + cfg.__cachedVersion__ = registryServer.version + this.features.logging.debug( + `MCP Registry: Cached version ${registryServer.version} for server '${unsanitizedName}'` + ) + } + } + /** * Add a new server: persist config, register in memory, and initialize. */ @@ -2597,14 +2733,13 @@ export class McpManager { const registryVersion = registryServer.version if (cachedVersion && cachedVersion !== registryVersion) { - const msg = `MCP Registry: Server '${unsanitizedName}' version changed from ${cachedVersion} to ${registryVersion} - reinstalling` + const msg = `MCP Registry: Server '${unsanitizedName}' version changed from ${cachedVersion} to ${registryVersion} - reinstalling after approval` this.features.logging.warn(msg) if (this.isPeriodicSync) { this.features.logging.warn(`WARNING: ${msg}`) } try { - await this.reinstallServer(sanitizedName, unsanitizedName, registryServer) - return true + return await this.reinstallServer(sanitizedName, unsanitizedName, registryServer) } catch (error) { const errorMsg = error instanceof Error ? error.message : String(error) this.features.logging.error( @@ -2617,22 +2752,70 @@ export class McpManager { } /** - * Reinstall server with new version + * Reinstall server with new version. The new configuration needs approval before the running server is + * removed, so that a denial keeps the server at the configuration that the user approved. + * @returns true when the server was reinstalled, false when it kept its configuration */ - private async reinstallServer(sanitizedName: string, unsanitizedName: string, registryServer: any): Promise { + private async reinstallServer( + sanitizedName: string, + unsanitizedName: string, + registryServer: any + ): Promise { + const running = this.mcpServers.get(sanitizedName) + // A reinstall starts the server, so it would turn on a server that the user turned off + if (this.isServerDisabled(sanitizedName)) { + this.features.logging.info( + `MCP Registry: Server '${unsanitizedName}' is disabled; not reinstalling it with version ${registryServer.version}` + ) + return false + } + const configPath = + running?.__configPath__ || getGlobalAgentConfigPath(this.features.workspace.fs.getUserHomeDir()) + + const converter = new (await import('./mcpServerConfigConverter')).McpServerConfigConverter() + // The version of the entry that the prompt asks about, not the one in a registry that a later sync loads + const newConfig: MCPServerConfig = { + ...converter.convertRegistryServer(registryServer), + __cachedVersion__: registryServer.version, + } + + // The configuration that addRegistryServer starts the server with + const candidate: MCPServerConfig = { ...newConfig, __configPath__: configPath, __registryServer__: true } + const scope = this.consentScope(candidate) + // The sync waits for the answer before it checks the next server + const consent = scope ? await this.askForServerConsent(sanitizedName, candidate, scope) : 'approved' + if (consent === 'denied' || consent === 'failed') { + this.features.logging.info( + `MCP Registry: Kept server '${unsanitizedName}' at its approved configuration; version ${registryServer.version} from the registry was not allowed` + ) + return false + } + // The user can save, remove, turn off or reinstall the server while the prompt is open. Replace only the + // server that the prompt asked about. + if (this.mcpServers.get(sanitizedName) !== running || this.isServerDisabled(sanitizedName)) { + this.features.logging.info( + `MCP Registry: Server '${unsanitizedName}' changed while the approval prompt was open; not reinstalling it` + ) + return false + } + this.features.logging.info( `MCP Registry: Reinstalling server '${unsanitizedName}' with version ${registryServer.version}` ) - - const configPath = - this.mcpServers.get(sanitizedName)?.__configPath__ || - getGlobalAgentConfigPath(this.features.workspace.fs.getUserHomeDir()) - await this.removeServer(sanitizedName) - const converter = new (await import('./mcpServerConfigConverter')).McpServerConfigConverter() - const newConfig = converter.convertRegistryServer(registryServer) - + // removeServer also removes the approvals of the server. Record the new configuration, which the user + // approved before or allowed now, so that the server starts without a second prompt. + if (scope) { + await recordApproval( + this.features.workspace, + this.features.logging, + sanitizedName, + candidate, + scope.configPath + ) + } await this.addRegistryServer(unsanitizedName, newConfig, configPath) + return true } } diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpTypes.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpTypes.ts index f021d07da8..0a223f0255 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpTypes.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpTypes.ts @@ -41,6 +41,7 @@ export interface MCPServerConfig { __additionalHeaders__?: Record // Additional headers from agent config (for registry servers) __additionalEnv__?: Record // Additional env vars from agent config (for registry servers) __registryError__?: string // Error message when registry server is not found in registry + __registryServer__?: boolean // The server comes from the MCP registry, so it starts only with an approved configuration } export interface RegistryServerConfig { diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpUtils.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpUtils.test.ts index e9da6af360..f165a89cc7 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpUtils.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpUtils.test.ts @@ -1165,6 +1165,9 @@ describe('loadAgentConfig with registry support', () => { expect(result.servers.has('manual-server')).to.be.false const server = result.servers.get('test-remote')! expect(server.url).to.equal('https://example.com/mcp') + // The agent config entry holds the converted fields, so the mark is what the consent gate checks + expect(server.__registryServer__).to.equal(true) + expect(result.agentConfig.mcpServers['test-remote']).to.not.have.property('type') }) it('should load manual servers when registry is not active', async () => { @@ -1193,6 +1196,7 @@ describe('loadAgentConfig with registry support', () => { expect(result.servers.has('manual-server')).to.be.true const server = result.servers.get('manual-server')! expect(server.command).to.equal('node') + expect(server.__registryServer__).to.equal(undefined) }) it('should warn when registry server not found in registry', async () => { diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpUtils.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpUtils.ts index 1447ace271..a1b00b8054 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpUtils.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpUtils.ts @@ -519,6 +519,9 @@ export async function loadAgentConfig( try { cfg = converter.convertRegistryServer(registryServer, entry.env) cfg.__configPath__ = fsPath + // The agent config entry below holds the converted fields, so the mark is the only record + // that the configuration comes from the registry + cfg.__registryServer__ = true // Apply timeout from registry server config if provided if (typeof entry.timeout === 'number') { From aafe9809c6c2b6c7985d911e1bffed43fe1617a5 Mon Sep 17 00:00:00 2001 From: Laxman Reddy Aileni Date: Wed, 18 Nov 2026 03:26:44 +0000 Subject: [PATCH 2/3] fix(amazonq): show hidden characters in the MCP consent prompt as escapes The consent prompt of an MCP server shows control, format, private use and unassigned characters, the braille blank and lone surrogates in the command line, the names and the package index as \u escapes, after it shortens them. The review of a registry server configuration also escapes private use and unassigned characters and the braille blank. The registry prompt says that Save and a reinstall ask again. Adds tests of the registry prompt after a version change and of an install whose approval cannot be recorded. --- .../tools/mcp/mcpConsentStore.test.ts | 26 ++++++++++++++ .../agenticChat/tools/mcp/mcpConsentStore.ts | 36 ++++++++++++++----- .../tools/mcp/mcpEventHandler.test.ts | 10 ++++++ .../agenticChat/tools/mcp/mcpManager.test.ts | 23 +++++++++++- .../agenticChat/tools/mcp/mcpManager.ts | 10 +++--- 5 files changed, 92 insertions(+), 13 deletions(-) diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.test.ts index 53ab179e69..c271b13d57 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.test.ts @@ -16,6 +16,7 @@ import { hasApproval, recordApproval, removeApproval, + showHiddenCharacters, } from './mcpConsentStore' import type { MCPServerConfig } from './mcpTypes' @@ -274,6 +275,31 @@ describe('mcpConsentStore', () => { expect(text).to.include('"データ"') expect(text).to.include('"✓"') }) + + it('writes the braille blank, private use and unassigned code points as escapes', () => { + const args = ['a\u2800b', 'a\uE000b', 'a\u0378b'] + + const text = formatServerConfigForReview({ command: 'npx', args }) + + expect(text).to.include('"a\\u2800b"') + expect(text).to.include('"a\\ue000b"') + expect(text).to.include('"a\\u0378b"') + expect(JSON.parse(text)).to.deep.equal({ command: 'npx', args }) + }) + }) + + describe('showHiddenCharacters', () => { + it('writes line breaks, bidirectional overrides and other hidden characters as escapes', () => { + const text = showHiddenCharacters('a\nb\r\tc\u202Ed\u200Be\u00A0f\u2800g\u2028h\uE000i\uD800j') + + expect(text).to.equal('a\\u000ab\\u000d\\u0009c\\u202ed\\u200be\\u00a0f\\u2800g\\u2028h\\ue000i\\ud800j') + }) + + it('keeps U+0020, <, > and & and visible non-ASCII characters', () => { + const text = 'npx -y @scope/pkg --url https://example.com/?a=1&b=<2> Größe データ ✓' + + expect(showHiddenCharacters(text)).to.equal(text) + }) }) describe('fingerprintWorkspace', () => { diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.ts index 5692b4bdba..0da00335f8 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.ts @@ -74,17 +74,42 @@ export function fingerprintServerConfig(cfg: MCPServerConfig): string { return 'sha256:' + createHash('sha256').update(JSON.stringify(canonical)).digest('hex') } +/** `text` with each UTF-16 code unit written as a \u escape */ +function unicodeEscapes(text: string): string { + return Array.from({ length: text.length }, (_, i) => `\\u${text.charCodeAt(i).toString(16).padStart(4, '0')}`).join( + '' + ) +} + /** * Characters that formatServerConfigForReview writes as \u escapes: * - control and format characters (such as bidirectional overrides and zero-width characters), line and paragraph * separators, and the other default ignorable characters - * - spaces other than U+0020 + * - spaces other than U+0020, and the braille blank U+2800, which also shows as a space + * - private use and unassigned code points, whose look depends on the font * - <, > and &, as JSON encoders that make text safe to put in HTML escape them * Line feeds and U+0020 are left alone: JSON.stringify uses them for the layout, it already escapes a line feed in a * string, and U+0020 in a string is shown as it is. The other characters can occur only in strings, where a \u escape * keeps the value. */ -const ESCAPED_CHARACTERS = /(?![\n ])[\p{Cc}\p{Cf}\p{Zs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}<>&]/gu +const ESCAPED_CHARACTERS = + /(?![\n ])[\p{Cc}\p{Cf}\p{Zs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}\p{Co}\p{Cn}\u2800<>&]/gu + +/** + * Characters that showHiddenCharacters writes as \u escapes: the ones in ESCAPED_CHARACTERS except <, > and &, and + * also line feeds and lone surrogates. U+0020 is left alone. + */ +const HIDDEN_CHARACTERS = + /(?! )[\p{Cc}\p{Cf}\p{Zs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}\p{Co}\p{Cn}\p{Cs}\u2800]/gu + +/** + * `text` with the characters that a person cannot see or tell apart written as \u escapes, for plain text that a + * person reads, such as a prompt. A line break or a bidirectional override in a value can then not change how the + * rest of the text reads. + */ +export function showHiddenCharacters(text: string): string { + return text.replace(HIDDEN_CHARACTERS, unicodeEscapes) +} /** * The fields of a server config that fingerprintServerConfig covers, as JSON in the format of mcp.json, for a person @@ -104,12 +129,7 @@ export function formatServerConfigForReview(cfg: MCPServerConfig): string { ...(Object.keys(env).length > 0 ? { env } : {}), } : { url: cfg.url ?? '', ...(Object.keys(headers).length > 0 ? { headers } : {}) } - return JSON.stringify(reviewed, undefined, 1).replace(ESCAPED_CHARACTERS, character => - Array.from( - { length: character.length }, - (_, i) => `\\u${character.charCodeAt(i).toString(16).padStart(4, '0')}` - ).join('') - ) + return JSON.stringify(reviewed, undefined, 1).replace(ESCAPED_CHARACTERS, unicodeEscapes) } /** Hash of the workspace path so approval is scoped to (workspace, config). diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpEventHandler.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpEventHandler.test.ts index 6b88e4cb88..3123263d3e 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpEventHandler.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpEventHandler.test.ts @@ -935,6 +935,16 @@ describe('McpEventHandler error handling', () => { expect(again.header.title).to.equal('Install MCP Server') }) + it('does not install the server when its approval cannot be recorded', async () => { + recordApproval.rejects(new Error('store write failed')) + await preview('docs-server 1.2.3') + + await confirm('docs-server') + + sinon.assert.calledOnce(recordApproval) + sinon.assert.notCalled(addRegistryServer) + }) + it('ignores form values that the chat client sends with the confirmation', async () => { await preview('docs-server 1.2.3') await eventHandler.onMcpServerClick({ diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.test.ts index e235f867ab..8d51253f8d 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.test.ts @@ -1889,7 +1889,8 @@ describe('Registry Synchronization', () => { args: ['-y', '@test/server@1.0.0'], disabled: false, __cachedVersion__: '1.0.0', - __configPath__: '/test/config.json', + // A registry server lives in the global agent config, so the reinstall asks with the registry prompt + __configPath__: mcpUtils.getGlobalAgentConfigPath(mockFeatures.workspace.fs.getUserHomeDir()), }) ;(mgr as any).serverNameMapping.set('test-server', 'test-server') ;(mgr as any).agentConfig = { @@ -1936,6 +1937,7 @@ describe('Registry Synchronization', () => { await mgr.updateRegistryUrl('https://example.com/registry.json', true) sinon.assert.calledOnce(showMessageRequest) + expect(showMessageRequest.firstCall.args[0].message).to.include('Amazon Q — MCP Server from the Registry') sinon.assert.calledOnce(recordApprovalStub) expect(removeServerStub.called).to.be.true expect(addRegistryServerStub.called).to.be.true @@ -2381,6 +2383,25 @@ describe('consent gate for MCP registry servers', () => { expect(recordApprovalStub.called).to.be.false }) + it('shows hidden characters of the command and the names in the prompt as escapes', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const cfg: MCPServerConfig = { + ...localCfg(), + args: ['-y', '@example/docs-server@1.2.4', 'a\u202Eb', 'first\nsecond'], + env: { 'DOCS\u200BREGION': 'hidden-env-value' }, + } + + await (mgr as any).initOneServerInternal('docs-server', cfg) + + const message: string = showMessageStub.firstCall.args[0].message + expect(message).to.include('Command: npx -y @example/docs-server@1.2.4 a\\u202eb first\\u000asecond\n') + expect(message).to.include('Environment variables: DOCS\\u200bREGION\n') + expect(message).to.not.include('\u202E') + expect(message).to.not.include('\u200B') + expect(message).to.not.include('first\nsecond') + }) + it('shows the URL and header names of a remote registry server', async () => { const mgr = await buildMgr() showMessageStub.resolves({ title: 'Deny' }) diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.ts index 6210565d85..ebd5f53b05 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.ts @@ -57,6 +57,7 @@ import { fingerprintServerConfig, effectiveEnv, effectiveHeaders, + showHiddenCharacters, } from './mcpConsentStore' import { sanitizeInput } from '../../../../shared/utils' import { ProfileStatusMonitor } from './profileStatusMonitor' @@ -90,9 +91,10 @@ const MCP_CONSENT_PREVIEW_MAX_LENGTH = 200 const MCP_CONSENT_TRUNCATION_CUE = ' { ... }' function formatConsentPreview(value: string): string { - return value.length > MCP_CONSENT_PREVIEW_MAX_LENGTH - ? `${value.slice(0, MCP_CONSENT_PREVIEW_MAX_LENGTH)}${MCP_CONSENT_TRUNCATION_CUE}` - : value + const truncated = value.length > MCP_CONSENT_PREVIEW_MAX_LENGTH + // A line break or a bidirectional override in a value must not change how the rest of the prompt reads + const shown = showHiddenCharacters(truncated ? value.slice(0, MCP_CONSENT_PREVIEW_MAX_LENGTH) : value) + return truncated ? `${shown}${MCP_CONSENT_TRUNCATION_CUE}` : shown } /** The environment variables that set the package index of an npx or uvx server */ @@ -762,7 +764,7 @@ export class McpManager { `Variables such as NODE_OPTIONS can cause additional code to run. ` : `Starting this server connects Amazon Q to the above URL, with the headers listed above. `) + `Only allow if you expect this server and this configuration from your MCP registry.\n\n` + - `If you allow, you won't be asked again unless the registry changes the server configuration.` + `If you allow, you won't be asked again for this configuration until you save or reinstall the server.` : `Amazon Q — Untrusted MCP Server\n\n` + `A workspace configuration file wants to start an MCP server.\n` + `Server: ${serverName}\n` + From 60284310c94aa4b0c83aff99e4a0152422df767c Mon Sep 17 00:00:00 2001 From: Laxman Reddy Aileni Date: Thu, 19 Nov 2026 19:56:38 +0000 Subject: [PATCH 3/3] fix(amazonq): harden mcp registry sync and server consent Harden MCP registry synchronization and server consent handling: - Gate the version re-check on the registry marker the loader keeps, so a new registry version is re-checked instead of skipped. - Show the full command and values in the registry consent prompt, which offers no separate view-configuration action. - Serialize approval-store reads and writes so concurrent server starts do not drop an approval. - Bound how long a background sync waits for a consent answer, and remember an unanswered prompt for the session so it is not reopened. - Match package-index environment variables case-insensitively, include the uv and pip variables, and show each URL in a multi-URL value without its user name or password. - Preserve the user environment, headers, request timeout, enabled tools and always-allow tools when a registry server is reinstalled at a new version. Adds unit tests for each behavior. --- .../tools/mcp/mcpConsentStore.test.ts | 13 + .../agenticChat/tools/mcp/mcpConsentStore.ts | 55 ++-- .../agenticChat/tools/mcp/mcpManager.test.ts | 255 +++++++++++++++++- .../agenticChat/tools/mcp/mcpManager.ts | 188 +++++++++++-- 4 files changed, 456 insertions(+), 55 deletions(-) diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.test.ts index c271b13d57..23da1e3aa5 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.test.ts @@ -393,6 +393,19 @@ describe('mcpConsentStore', () => { expect(stored.approvals).to.have.lengthOf(1) }) + // recordApproval reads the store, adds its entry and writes the store back. Several servers can + // finish starting at the same time, so these calls overlap. Without serialization one call reads the + // store before another has written its entry and then overwrites it, dropping that approval. Every + // approval recorded concurrently must survive. + it('keeps every approval recorded concurrently', async () => { + const names = Array.from({ length: 10 }, (_, i) => `srv-${i}`) + await Promise.all(names.map(name => recordApproval(workspace, logger, name, cfg, configPath))) + const stored = JSON.parse( + fs.readFileSync(path.join(tmpHome, '.aws', 'amazonq', 'mcp-approvals.json')).toString() + ) + expect(stored.approvals.map((a: any) => a.serverName).sort()).to.deep.equal([...names].sort()) + }) + it('evicts stale entry when config changes for same server and workspace', async () => { await recordApproval(workspace, logger, 'poc', cfg, configPath) const mutated: MCPServerConfig = { command: 'sh', args: ['-c', 'echo changed'] } diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.ts index 0da00335f8..e2ae22170e 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpConsentStore.ts @@ -7,6 +7,7 @@ import { createHash } from 'crypto' import * as path from 'path' import type { Workspace, Logging } from '@aws/language-server-runtimes/server-interface' import type { MCPServerConfig } from './mcpTypes' +import { Mutex } from 'async-mutex' const APPROVALS_FILE = 'mcp-approvals.json' // v2: the fingerprint now covers the fully-merged spawn environment and headers @@ -143,6 +144,10 @@ function getStorePath(workspace: Workspace): string { return path.join(workspace.fs.getUserHomeDir(), '.aws', 'amazonq', APPROVALS_FILE) } +// Serializes the read-modify-write of the approval store. Several servers can start at once, so without this a +// concurrent recordApproval could read the store before another wrote it and drop that approval on write. +const storeMutex = new Mutex() + async function readStore(workspace: Workspace, logging: Logging): Promise { const file = getStorePath(workspace) try { @@ -208,19 +213,21 @@ export async function recordApproval( cfg: MCPServerConfig, configPath: string ): Promise { - const store = await readStore(workspace, logging) - const fp = fingerprintServerConfig(cfg) - const wh = fingerprintWorkspace(configPath) - // Replace any prior approval for the same (server, workspace) — this evicts - // stale entries when the config changes (fingerprint differs). - store.approvals = store.approvals.filter(a => !(a.serverName === serverName && a.workspaceHash === wh)) - store.approvals.push({ - serverName, - fingerprint: fp, - workspaceHash: wh, - approvedAt: new Date().toISOString(), + return storeMutex.runExclusive(async () => { + const store = await readStore(workspace, logging) + const fp = fingerprintServerConfig(cfg) + const wh = fingerprintWorkspace(configPath) + // Replace any prior approval for the same (server, workspace) — this evicts + // stale entries when the config changes (fingerprint differs). + store.approvals = store.approvals.filter(a => !(a.serverName === serverName && a.workspaceHash === wh)) + store.approvals.push({ + serverName, + fingerprint: fp, + workspaceHash: wh, + approvedAt: new Date().toISOString(), + }) + await writeStore(workspace, logging, store) }) - await writeStore(workspace, logging, store) } export async function removeApproval( @@ -229,15 +236,17 @@ export async function removeApproval( serverName: string, configPath: string ): Promise { - const store = await readStore(workspace, logging) - const wh = fingerprintWorkspace(configPath) - const before = store.approvals.length - // Scope removal to the (serverName, workspace) that requested it, mirroring how - // recordApproval keys entries. Removing a server in one workspace must not - // revoke consent for an identically-named server in a different workspace. - store.approvals = store.approvals.filter(a => !(a.serverName === serverName && a.workspaceHash === wh)) - if (store.approvals.length < before) { - await writeStore(workspace, logging, store) - logging.info(`MCP consent store: removed approval for '${serverName}'`) - } + return storeMutex.runExclusive(async () => { + const store = await readStore(workspace, logging) + const wh = fingerprintWorkspace(configPath) + const before = store.approvals.length + // Scope removal to the (serverName, workspace) that requested it, mirroring how + // recordApproval keys entries. Removing a server in one workspace must not + // revoke consent for an identically-named server in a different workspace. + store.approvals = store.approvals.filter(a => !(a.serverName === serverName && a.workspaceHash === wh)) + if (store.approvals.length < before) { + await writeStore(workspace, logging, store) + logging.info(`MCP consent store: removed approval for '${serverName}'`) + } + }) } diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.test.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.test.ts index 8d51253f8d..2f0948e104 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.test.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.test.ts @@ -1799,11 +1799,12 @@ describe('Registry Synchronization', () => { command: 'npx', args: ['-y', '@test/server@1.0.0'], disabled: false, + __registryServer__: true, __configPath__: '/test/config.json', }) ;(mgr as any).serverNameMapping.set('test-server', 'test-server') ;(mgr as any).agentConfig = { - mcpServers: { 'test-server': { type: 'registry' } }, + mcpServers: { 'test-server': { command: 'npx', args: ['-y', '@test/server@1.0.0'] } }, tools: ['@test-server'], allowedTools: [], toolsSettings: {}, @@ -1873,6 +1874,9 @@ describe('Registry Synchronization', () => { const config = (mgr as any).mcpServers.get('manual-server') expect(config.disabled).to.be.false + // A broken gate would run the sync body on this manual server and, finding it absent from the empty + // registry, mark it FAILED. The skip must leave its state untouched. + expect(mgr.getServerState('manual-server')?.status).to.not.equal('FAILED') }) }) @@ -1889,12 +1893,13 @@ describe('Registry Synchronization', () => { args: ['-y', '@test/server@1.0.0'], disabled: false, __cachedVersion__: '1.0.0', + __registryServer__: true, // A registry server lives in the global agent config, so the reinstall asks with the registry prompt __configPath__: mcpUtils.getGlobalAgentConfigPath(mockFeatures.workspace.fs.getUserHomeDir()), }) ;(mgr as any).serverNameMapping.set('test-server', 'test-server') ;(mgr as any).agentConfig = { - mcpServers: { 'test-server': { type: 'registry' } }, + mcpServers: { 'test-server': { command: 'npx', args: ['-y', '@test/server@1.0.0'] } }, tools: [], allowedTools: [], toolsSettings: {}, @@ -2444,6 +2449,67 @@ describe('consent gate for MCP registry servers', () => { }) } + it('shows a package index set through a variable other than the npm and PyPI ones', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const cfg: MCPServerConfig = { + ...localCfg(), + env: { PIP_INDEX_URL: 'https://pip.example.com/simple' }, + } + + await (mgr as any).initOneServerInternal('docs-server', cfg) + + const message = showMessageStub.firstCall.args[0].message as string + expect(message).to.include('Package index: https://pip.example.com/simple\n') + }) + + it('shows a package index whose variable name is in another case', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + const cfg: MCPServerConfig = { + ...localCfg(), + env: { npm_config_registry: 'https://npm.example.com/' }, + } + + await (mgr as any).initOneServerInternal('docs-server', cfg) + + const message = showMessageStub.firstCall.args[0].message as string + expect(message).to.include('Package index: https://npm.example.com/\n') + }) + + it('shows every URL in a multi-URL package index without its user name and password', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + // PIP_EXTRA_INDEX_URL holds a whitespace-separated list of index URLs, each with credentials + const cfg: MCPServerConfig = { + ...localCfg(), + env: { + PIP_EXTRA_INDEX_URL: + 'https://a-user:a-pass@a.example.com/simple https://b-user:b-pass@b.example.com/simple', + }, + } + + await (mgr as any).initOneServerInternal('docs-server', cfg) + + const message = showMessageStub.firstCall.args[0].message as string + expect(message).to.include('Package index: https://a.example.com/simple https://b.example.com/simple\n') + expect(message).to.not.match(/a-user|a-pass|b-user|b-pass/) + }) + + it('shows the whole command of a registry server, which has no action to see the configuration in full', async () => { + const mgr = await buildMgr() + showMessageStub.resolves({ title: 'Deny' }) + // Longer than the 200-character preview limit that truncates a workspace prompt + const longArgument = 'a'.repeat(300) + const cfg: MCPServerConfig = { ...localCfg(), args: ['-y', longArgument] } + + await (mgr as any).initOneServerInternal('docs-server', cfg) + + const message = showMessageStub.firstCall.args[0].message as string + expect(message).to.include(`Command: npx -y ${longArgument}\n`) + expect(message).to.not.include('{ ... }') + }) + it('shows the URLs in the command without their user name and password', async () => { const mgr = await buildMgr() showMessageStub.resolves({ title: 'Deny' }) @@ -2902,8 +2968,19 @@ describe('registry sync of a new version of an installed registry server', () => expect(error?.message).to.equal('PASSED_THE_GATE') sinon.assert.calledOnce(showMessageStub) sinon.assert.calledOnce(removeServerSpy) - // The server records the version that the prompt asked about - sinon.assert.calledOnceWithExactly(addRegistryServerSpy, 'docs-server', newCfg, globalAgent) + // The server records the version that the prompt asked about. The trailing arguments carry the user's + // preserved environment, headers, "always allow" tools and enabled-tool entries; this server has only the + // whole-server entry and none of the rest. + sinon.assert.calledOnceWithExactly( + addRegistryServerSpy, + 'docs-server', + newCfg, + globalAgent, + undefined, + undefined, + [], + ['@docs-server'] + ) expect(removeServerSpy.calledBefore(addRegistryServerSpy)).to.be.true // Only the new configuration is approved now expect([...approvals]).to.deep.equal([ @@ -2968,6 +3045,176 @@ describe('registry sync of a new version of an installed registry server', () => sinon.assert.notCalled(addRegistryServerSpy) expect((mgr as any).mcpServers.get('docs-server')).to.equal(saved) }) + + it('keeps the approved configuration when a periodic sync prompt is not answered in time', async () => { + const mgr = await buildMgr() + // A background (periodic) sync must not stall on an unanswered prompt + ;(mgr as any).isPeriodicSync = true + const running = (mgr as any).mcpServers.get('docs-server') + // The user never answers the prompt + showMessageStub.returns(new Promise(() => {})) + + const clock = sinon.useFakeTimers() + try { + let settled = false + const reinstall = (mgr as any) + .reinstallServer('docs-server', 'docs-server', registryServer('1.2.4')) + .then((r: boolean) => { + settled = true + return r + }) + // Just before the one-minute timeout the sync is still waiting on the shown prompt + await clock.tickAsync(59_999) + sinon.assert.calledOnce(showMessageStub) + expect(settled).to.be.false + // Past the timeout, the unanswered prompt counts as a denial + await clock.tickAsync(2) + expect(await reinstall).to.be.false + expect(settled).to.be.true + } finally { + clock.restore() + } + + sinon.assert.notCalled(removeServerSpy) + sinon.assert.notCalled(addRegistryServerSpy) + expect((mgr as any).mcpServers.get('docs-server')).to.equal(running) + expect(approvals.size).to.equal(1) + }) + + it('does not time out an interactive (non-periodic) consent prompt', async () => { + const mgr = await buildMgr() + ;(mgr as any).isPeriodicSync = false + showMessageStub.returns(new Promise(() => {})) + + const clock = sinon.useFakeTimers() + try { + let settled = false + void (mgr as any).reinstallServer('docs-server', 'docs-server', registryServer('1.2.4')).then(() => { + settled = true + }) + await clock.tickAsync(120_000) + // The interactive path waits for a real answer; the timeout only applies to a background sync + sinon.assert.calledOnce(showMessageStub) + expect(settled).to.be.false + } finally { + clock.restore() + } + }) + + it('does not open a second prompt in the same session after a periodic sync prompt timed out', async () => { + const mgr = await buildMgr() + ;(mgr as any).isPeriodicSync = true + showMessageStub.returns(new Promise(() => {})) + + const clock = sinon.useFakeTimers() + try { + const first = (mgr as any).reinstallServer('docs-server', 'docs-server', registryServer('1.2.4')) + await clock.tickAsync(60_001) + expect(await first).to.be.false + sinon.assert.calledOnce(showMessageStub) + + // A later periodic sync of the same version must honour the "won't be asked again" promise + const second = (mgr as any).reinstallServer('docs-server', 'docs-server', registryServer('1.2.4')) + await clock.tickAsync(60_001) + expect(await second).to.be.false + sinon.assert.calledOnce(showMessageStub) + } finally { + clock.restore() + } + + sinon.assert.notCalled(removeServerSpy) + sinon.assert.notCalled(addRegistryServerSpy) + }) + + it('preserves the user environment, headers and allowed tools across a reinstall', async () => { + const mgr = await buildMgr() + const running = (mgr as any).mcpServers.get('docs-server') + running.__additionalEnv__ = { API_KEY: 'secret' } + running.__additionalHeaders__ = { Authorization: 'Bearer tok' } + // One tool this server may always run, plus an unrelated server's tool that must not be carried over + ;(mgr as any).agentConfig.allowedTools = ['@docs-server/search', '@other-server/tool'] + showMessageStub.resolves({ title: 'Allow for this server' }) + + let error: Error | undefined + try { + await (mgr as any).reinstallServer('docs-server', 'docs-server', registryServer('1.2.4')) + } catch (e: any) { + error = e + } + + expect(error?.message).to.equal('PASSED_THE_GATE') + // Exactly one prompt: carrying the env and headers onto candidate makes the recorded approval match what + // addRegistryServer starts, so its own consent gate does not prompt a second time. + sinon.assert.calledOnce(showMessageStub) + const newCfg: MCPServerConfig = { + ...new McpServerConfigConverter().convertRegistryServer(registryServer('1.2.4')), + __cachedVersion__: '1.2.4', + } + // The reinstall carries the user's own env and headers and only this server's "always allow" tool onto + // addRegistryServer, so the upgraded server keeps its credentials and approved tools. + sinon.assert.calledOnceWithExactly( + addRegistryServerSpy, + 'docs-server', + newCfg, + globalAgent, + { Authorization: 'Bearer tok' }, + { API_KEY: 'secret' }, + ['@docs-server/search'], + ['@docs-server'] + ) + }) + + it('passes the user environment to the converter so an OCI server keeps its container -e flags on reinstall', async () => { + const mgr = await buildMgr() + const running = (mgr as any).mcpServers.get('docs-server') + running.__additionalEnv__ = { API_KEY: 'secret' } + showMessageStub.resolves({ title: 'Allow for this server' }) + const ociServer = { + name: 'docs-server', + description: 'Searches the team docs', + version: '2.0.0', + packages: [{ registryType: 'oci', identifier: 'example/docs-server', transport: { type: 'stdio' } }], + } + + try { + await (mgr as any).reinstallServer('docs-server', 'docs-server', ociServer) + } catch {} + + // The container only receives env passed as -e flags, which the converter builds only when given the env + const passedCfg = addRegistryServerSpy.firstCall.args[1] as MCPServerConfig + expect(passedCfg.args).to.include('-e') + expect(passedCfg.args).to.include('API_KEY=secret') + }) + + it('keeps a request timeout the user set on the server when it reinstalls', async () => { + const mgr = await buildMgr() + const running = (mgr as any).mcpServers.get('docs-server') + running.timeout = 12345 + showMessageStub.resolves({ title: 'Allow for this server' }) + + try { + await (mgr as any).reinstallServer('docs-server', 'docs-server', registryServer('1.2.4')) + } catch {} + + const passedCfg = addRegistryServerSpy.firstCall.args[1] as MCPServerConfig + expect(passedCfg.timeout).to.equal(12345) + }) + + it('keeps the user tool enable state on reinstall and does not re-enable a disabled tool', async () => { + const mgr = await buildMgr() + // The user enabled only one tool; the whole-server entry is absent, so the other tools are denied + ;(mgr as any).agentConfig.tools = ['@docs-server/search'] + showMessageStub.resolves({ title: 'Allow for this server' }) + + try { + await (mgr as any).reinstallServer('docs-server', 'docs-server', registryServer('1.2.4')) + } catch {} + + const tools = (mgr as any).agentConfig.tools + expect(tools).to.include('@docs-server/search') + // A reinstall that reset the entry to the whole server would re-enable every tool + expect(tools).to.not.include('@docs-server') + }) }) describe('approval of a registry server from the install preview, with the real consent store', () => { diff --git a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.ts b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.ts index ebd5f53b05..2603978393 100644 --- a/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.ts +++ b/server/aws-lsp-codewhisperer/src/language-server/agenticChat/tools/mcp/mcpManager.ts @@ -23,7 +23,6 @@ import { AgentConfig, AgentResourceSource, isMCPServerConfig, - isRegistryServerConfig, } from './mcpTypes' import { isEmptyEnv, @@ -90,15 +89,34 @@ export enum AuthIntent { const MCP_CONSENT_PREVIEW_MAX_LENGTH = 200 const MCP_CONSENT_TRUNCATION_CUE = ' { ... }' -function formatConsentPreview(value: string): string { - const truncated = value.length > MCP_CONSENT_PREVIEW_MAX_LENGTH +// A registry consent prompt has no "View full configuration" action, so it shows its values in full (truncate +// false). A workspace prompt can be truncated because it offers that action. +function formatConsentPreview(value: string, truncate: boolean = true): string { + const truncated = truncate && value.length > MCP_CONSENT_PREVIEW_MAX_LENGTH // A line break or a bidirectional override in a value must not change how the rest of the prompt reads const shown = showHiddenCharacters(truncated ? value.slice(0, MCP_CONSENT_PREVIEW_MAX_LENGTH) : value) return truncated ? `${shown}${MCP_CONSENT_TRUNCATION_CUE}` : shown } -/** The environment variables that set the package index of an npx or uvx server */ -const PACKAGE_INDEX_ENV_VARS = [MCP_REGISTRY_CONSTANTS.NPM.ENV_VAR, MCP_REGISTRY_CONSTANTS.PYPI.ENV_VAR] +/** + * The environment variables that redirect where an npx or uvx server fetches its package, matched + * case-insensitively. Their values are URLs, so the prompt shows them without any user name or password; every + * other variable shows its name only, because a value can hold a token. + */ +const PACKAGE_INDEX_ENV_VARS = new Set( + [ + MCP_REGISTRY_CONSTANTS.NPM.ENV_VAR, + MCP_REGISTRY_CONSTANTS.PYPI.ENV_VAR, + 'UV_INDEX_URL', + 'UV_EXTRA_INDEX_URL', + 'PIP_INDEX_URL', + 'PIP_EXTRA_INDEX_URL', + ].map(name => name.toLowerCase()) +) + +// How long a background registry sync waits for an answer to a version-change prompt before it keeps the approved +// configuration and moves on, so an unanswered prompt cannot stall the rest of the sync. +const REGISTRY_SYNC_CONSENT_TIMEOUT_MS = 60000 /** * The user name and password of a URL in a text, with the scheme of the URL in group 1. The scheme has at most @@ -725,7 +743,8 @@ export class McpManager { // A URL in the command, such as the package index of a PyPI server, is shown without a user name or password const cmdLine = formatConsentPreview( - [cfg.command ?? cfg.url ?? '(none)', ...(cfg.args ?? [])].join(' ').replace(URL_CREDENTIALS, '$1') + [cfg.command ?? cfg.url ?? '(none)', ...(cfg.args ?? [])].join(' ').replace(URL_CREDENTIALS, '$1'), + isWorkspaceScoped ) // Surface the environment variables and headers the server will actually be // launched with. Names only, never values: a config may legitimately hold @@ -736,14 +755,24 @@ export class McpManager { const headerNames = Object.keys(effectiveHeaders(cfg)) const envLine = envKeys.length > 0 - ? `Environment variables: ${formatConsentPreview(envKeys.join(', '))}\n` + ? `Environment variables: ${formatConsentPreview(envKeys.join(', '), isWorkspaceScoped)}\n` : `Environment variables: (none)\n` - const headerLine = headerNames.length > 0 ? `Headers: ${formatConsentPreview(headerNames.join(', '))}\n` : '' - // The exception is a package index, whose URL is shown without a user name or password. - const packageIndexes = PACKAGE_INDEX_ENV_VARS.map(name => env[name]).filter(value => !!value) + const headerLine = + headerNames.length > 0 + ? `Headers: ${formatConsentPreview(headerNames.join(', '), isWorkspaceScoped)}\n` + : '' + // The exception is a package index, whose URL is shown without a user name or password. A variable such as + // PIP_EXTRA_INDEX_URL can hold a whitespace-separated list of URLs, so strip the credentials from every URL + // in the value, not only the first. + const packageIndexes = Object.entries(env) + .filter(([name]) => PACKAGE_INDEX_ENV_VARS.has(name.toLowerCase())) + .map(([, value]) => value) + .filter(value => !!value) + const indexValueWithoutCredentials = (value: string): string => + value.split(/\s+/).filter(Boolean).map(urlWithoutCredentials).join(' ') const packageIndexLine = packageIndexes.length > 0 - ? `Package index: ${formatConsentPreview(packageIndexes.map(urlWithoutCredentials).join(', '))}\n` + ? `Package index: ${formatConsentPreview(packageIndexes.map(indexValueWithoutCredentials).join(', '), isWorkspaceScoped)}\n` : '' const allowBtn = { title: 'Allow for this server' } const denyBtn = { title: 'Deny' } @@ -1343,7 +1372,9 @@ export class McpManager { cfg: MCPServerConfig, configPath: string, additionalHeaders?: Record, - additionalEnv?: Record + additionalEnv?: Record, + allowedTools: string[] = [], + serverTools?: string[] ): Promise { const sanitizedName = sanitizeName(serverName) if ( @@ -1377,8 +1408,19 @@ export class McpManager { this.agentConfig.mcpServers[serverName] = registryServerConfig const serverPrefix = `@${serverName}` - if (!this.agentConfig.tools.includes(serverPrefix)) { - this.agentConfig.tools.push(serverPrefix) + // A plain install enables the whole server; a registry reinstall passes the exact tool entries the user + // had, so a tool the user turned off stays off. + const toolsToRegister = serverTools ?? [serverPrefix] + for (const tool of toolsToRegister) { + if (!this.agentConfig.tools.includes(tool)) { + this.agentConfig.tools.push(tool) + } + } + // Re-apply any tools the caller preserved as "always allow" for this server (a plain install passes none). + for (const tool of allowedTools) { + if (!this.agentConfig.allowedTools.includes(tool)) { + this.agentConfig.allowedTools.push(tool) + } } await saveServerSpecificAgentConfig( @@ -1386,8 +1428,8 @@ export class McpManager { this.features.logging, serverName, registryServerConfig, - [serverPrefix], - [], + toolsToRegister, + allowedTools, configPath ) @@ -2646,8 +2688,11 @@ export class McpManager { // Only sync during periodic updates, not at startup if (isPeriodicSync) { this.isPeriodicSync = true - await this.syncWithRegistry() - this.isPeriodicSync = false + try { + await this.syncWithRegistry() + } finally { + this.isPeriodicSync = false + } } } } catch (error) { @@ -2678,10 +2723,10 @@ export class McpManager { for (const [sanitizedName, config] of configuredServers) { const unsanitizedName = this.serverNameMapping.get(sanitizedName) || sanitizedName - const agentConfig = this.agentConfig.mcpServers[unsanitizedName] - // Skip non-registry servers - if (!agentConfig || !isRegistryServerConfig(agentConfig)) { + // A registry server carries the __registryServer__ mark on its config. The agent-config entry does not + // keep a registry type after loadAgentConfig rewrites it to the converted fields, so gate on the mark. + if (config.__registryServer__ !== true) { continue } @@ -2693,7 +2738,13 @@ export class McpManager { // Close client and mark as failed, but keep in agent config const client = this.clients.get(sanitizedName) if (client) { - await client.close() + try { + await client.close() + } catch (e: any) { + this.features.logging.warn( + `MCP Registry: Failed to close client for '${unsanitizedName}': ${e?.message}` + ) + } this.clients.delete(sanitizedName) } this.mcpTools = this.mcpTools.filter(t => t.serverName !== sanitizedName) @@ -2774,19 +2825,79 @@ export class McpManager { const configPath = running?.__configPath__ || getGlobalAgentConfigPath(this.features.workspace.fs.getUserHomeDir()) + // A registry version bump replaces only the package version. The user's own additions to the server must + // survive the reinstall: the extra environment variables and headers they configured (an API key, for + // example) and the tools they marked "always allow". Capture them before removeServer discards them. + // Filter out empty entries, matching how addRegistryServer builds the started configuration, so the + // consent fingerprint of candidate equals what the server runs and a hand-edited empty value does not + // force a second, un-timed prompt inside the reinstall. + const nonEmptyRecord = (record?: Record): Record | undefined => { + const filtered = Object.fromEntries( + Object.entries(record ?? {}).filter(([key, value]) => key.trim() && value.trim()) + ) + return Object.keys(filtered).length > 0 ? filtered : undefined + } + const additionalEnv = nonEmptyRecord(running?.__additionalEnv__) + const additionalHeaders = nonEmptyRecord(running?.__additionalHeaders__) + const serverPrefix = `@${unsanitizedName}` + const converter = new (await import('./mcpServerConfigConverter')).McpServerConfigConverter() - // The version of the entry that the prompt asks about, not the one in a registry that a later sync loads + // The version of the entry that the prompt asks about, not the one in a registry that a later sync loads. + // Pass the user's env so an OCI (container) server keeps its -e flags, matching how the loader builds it. const newConfig: MCPServerConfig = { - ...converter.convertRegistryServer(registryServer), + ...converter.convertRegistryServer(registryServer, additionalEnv), __cachedVersion__: registryServer.version, } + // Keep a request timeout the user set on the server; the converter does not carry one. + if (typeof running?.timeout === 'number') { + newConfig.timeout = running.timeout + } - // The configuration that addRegistryServer starts the server with + // The configuration that addRegistryServer starts the server with. It carries the user's own environment + // and headers so the consent prompt and the recorded approval cover what will actually run. const candidate: MCPServerConfig = { ...newConfig, __configPath__: configPath, __registryServer__: true } + if (additionalEnv) { + candidate.__additionalEnv__ = additionalEnv + } + if (additionalHeaders) { + candidate.__additionalHeaders__ = additionalHeaders + } const scope = this.consentScope(candidate) - // The sync waits for the answer before it checks the next server - const consent = scope ? await this.askForServerConsent(sanitizedName, candidate, scope) : 'approved' + // The sync waits for the answer before it checks the next server, but only for a bounded time: an + // unanswered prompt then keeps the approved configuration so the sync moves on to the next server. + let consent: 'approved' | 'allowed' | 'denied' | 'failed' + if (!scope) { + consent = 'approved' + } else if (this.isPeriodicSync) { + let timer: ReturnType | undefined + const timeout = new Promise<'denied'>(resolve => { + timer = setTimeout(() => { + // Remember the unanswered prompt as a denial for this session, so a later sync keeps the + // approved configuration and does not open a second prompt for the same version. This honours + // the prompt's own promise that the user will not be asked again for this configuration. + this.sessionDeniedConsent.add( + `${sanitizedName}|${scope.configPath}|${fingerprintServerConfig(candidate)}` + ) + this.features.logging.info( + `MCP Registry: Consent prompt for '${unsanitizedName}' version ${registryServer.version} was not answered in time; keeping the approved configuration` + ) + resolve('denied') + }, REGISTRY_SYNC_CONSENT_TIMEOUT_MS) + }) + try { + consent = await Promise.race([this.askForServerConsent(sanitizedName, candidate, scope), timeout]) + } finally { + if (timer) { + clearTimeout(timer) + } + } + } else { + consent = await this.askForServerConsent(sanitizedName, candidate, scope) + } if (consent === 'denied' || consent === 'failed') { + // A timeout records the denial for the session (above), so an unanswered prompt is not reopened on the + // next sync. A user who answers the timed-out prompt late has no effect: the server stays on its + // approved version until the session restarts. This keeps the sync non-blocking and fails safe. this.features.logging.info( `MCP Registry: Kept server '${unsanitizedName}' at its approved configuration; version ${registryServer.version} from the registry was not allowed` ) @@ -2801,6 +2912,17 @@ export class McpManager { return false } + // Read the tool enable/disable state and the "always allow" tools now, after the prompt, so a permission + // the user changed while the prompt was open is preserved rather than reverted. The enable state lives in + // which @server and @server/tool entries are listed, so resetting them to the whole server would silently + // re-enable a tool the user had turned off. + const preservedServerTools = this.agentConfig.tools.filter( + tool => tool === serverPrefix || tool.startsWith(`${serverPrefix}/`) + ) + const preservedAllowedTools = this.agentConfig.allowedTools.filter( + tool => tool === serverPrefix || tool.startsWith(`${serverPrefix}/`) + ) + this.features.logging.info( `MCP Registry: Reinstalling server '${unsanitizedName}' with version ${registryServer.version}` ) @@ -2817,7 +2939,17 @@ export class McpManager { scope.configPath ) } - await this.addRegistryServer(unsanitizedName, newConfig, configPath) + // Restore the user's own environment, headers, enabled tools and "always allow" tools onto the reinstalled + // server, so a version bump does not drop the server's credentials or reset its tool permissions. + await this.addRegistryServer( + unsanitizedName, + newConfig, + configPath, + additionalHeaders, + additionalEnv, + preservedAllowedTools, + preservedServerTools + ) return true } }