Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions chat-client/src/client/mcpMynahUi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -681,4 +681,72 @@ describe('McpMynahUi', () => {
assert.strictEqual(detailedList.list[0].children[0].icon, 'mocked-icon')
})
})

describe('registry server install', () => {
const openRegistryView = (params: Record<string, unknown>) => {
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)
})
})
})
16 changes: 14 additions & 2 deletions chat-client/src/client/mcpMynahUi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
},
Expand All @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -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', () => {
Expand All @@ -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) <b>x</b> **y**'),
'`[docs](https://example.com) <b>x</b> **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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ import {
effectiveHeaders,
fingerprintServerConfig,
fingerprintWorkspace,
formatServerConfigForReview,
hasApproval,
recordApproval,
removeApproval,
showHiddenCharacters,
} from './mcpConsentStore'
import type { MCPServerConfig } from './mcpTypes'

Expand Down Expand Up @@ -143,6 +145,163 @@ 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 = ['<span>', '--verbose', '</span>', 'a&quot;, "b', '<b ', 'c&#x3A;d', '&lt;i&gt;']
const cfg: MCPServerConfig = { command: 'npx', args: values, env: { 'A<B': 'x&y' } }

const text = formatServerConfigForReview(cfg)

expect(text).to.not.match(/[<>&]/)
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<B': 'x&y' } })
})

it('writes <, > and & in a URL and headers as escapes', () => {
const cfg: MCPServerConfig = { url: 'https://mcp.example.com/?a=1&b=<2>', headers: { 'X-A&B': '<c>' } }

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('"✓"')
})

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', () => {
it('is keyed on the directory of the config, not the filename', () => {
const a = fingerprintWorkspace('/foo/bar/.amazonq/mcp.json')
Expand Down Expand Up @@ -234,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'] }
Expand Down
Loading
Loading