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
4 changes: 2 additions & 2 deletions extensions/mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,11 +34,11 @@ Saving either settings file reconnects every server. OAuth is not supported yet:

Every agent that inherits tools gets `mcp`, and @ultimate lists it in `agents/ultimate.md`. Agents with an explicit `tools` list add it there.

Calls are `replay: 'unsafe'`: a call interrupted by a restart is reported as interrupted, never sent again. A call times out after 10 minutes without progress from the server. A call the server refuses with HTTP 429 (rate limited), or one the agent aborts, comes back as a tool error and keeps the connection.
Calls are `replay: 'unsafe'`: a call interrupted by a restart is reported as interrupted, never sent again. A call times out after 10 minutes without progress from the server. A call the server refuses with HTTP 429 (rate limited) is sent again up to twice, after the response's "Wait N seconds" or else 3 s; one that asks for more than 10 s, or is still refused, or one the agent aborts, comes back as a tool error and keeps the connection.

## Lifecycle

Servers connect when the server opens, each on its own: a failing one never blocks another or a turn. A failure or a dropped connection retries after 5 s, doubling up to 5 minutes. The servers close (stdio: the whole process group) when the extension reloads or Ultimate stops. A server's `tools/list_changed` notification refreshes its tool list.
Servers connect when the server opens, each on its own: a failing one never blocks another or a turn. A failure or a dropped connection retries after 5 s, doubling up to 5 minutes. The servers close (stdio: the whole process group) when the extension reloads or Ultimate stops. A server's `tools/list_changed` notification refreshes its tool list, and a listing waits for that refresh. A successful call to a tool named like `*enable_backend*` (Tool Gateway's, whose notification arrives after its result) lists the tools again before it returns, so the next listing has the backend's tools.

## UI

Expand Down
66 changes: 50 additions & 16 deletions extensions/mcp/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
import type { Tool } from '@earendil-works/pi-mcp'
import { implementAction } from '../../lib/actions.ts'
import { readSecret } from '../../lib/secrets.ts'
import { retryAfter, type Cancel } from '../../lib/timers.shared.ts'
import { pace, retryAfter, type Cancel } from '../../lib/timers.shared.ts'
import { readSettings, userSettingsPath } from '../../lib/settings.ts'
import type { ExtensionAction } from '../../server/actions.ts'
import type { ExtensionHost } from '../../server/extensions.ts'
Expand All @@ -29,8 +29,19 @@ export const pollActions = ['status']

const PROGRESS_RENEWED_CALL_TIMEOUT_MS = 10 * 60_000
const FIRST_RETRY = 5_000
const rateLimited = (error: unknown) => error instanceof McpHttpError && error.status === 429
const rateLimited = (error: unknown): error is McpHttpError =>
error instanceof McpHttpError && error.status === 429
const LAST_RETRY = 5 * 60_000
const RATE_LIMIT_RETRIES = 2
const RATE_LIMIT_BACKOFF = 3_000
const RATE_LIMIT_LONGEST_WAIT = 10_000
const enablesBackendWhoseToolsListLate = (tool: string) => /enable_backend/.test(tool)

function retryDelayWithinLongestWait(error: McpHttpError) {
const waitHint = /\bwait (\d+(?:\.\d+)?) seconds?\b/i.exec(error.body || error.message)
const ms = waitHint ? Number(waitHint[1]) * 1000 : RATE_LIMIT_BACKOFF
return ms <= RATE_LIMIT_LONGEST_WAIT ? ms : undefined
}

type Entry =
| { command: string; args: string[]; env: Record<string, string>; cwd?: string }
Expand All @@ -43,6 +54,7 @@ type Server = Omit<McpServerStatus, 'tools'> & {
attempts: number
cancelRetry?: Cancel
connectionQueueTail?: Promise<void>
relisting?: Promise<void>
resolvedSecretsForRedaction: string[]
}

Expand Down Expand Up @@ -181,6 +193,16 @@ function listing(server: Server, match: string | undefined) {
...tools.map((tool) => tool.name),
].join('\n')
}
function relist(server: Server, client: McpClient) {
const next = client.listTools().then(
(tools) => {
if (server.client === client) server.tools = tools
},
(error: unknown) => console.warn(`MCP ${server.name}: tools/list: ${redact(server, error)}`),
)
server.relisting = next
return next
}
const schemaOf = (tool: Tool) => `${tool.name} input: ${JSON.stringify(tool.inputSchema)}`
const renewTimeoutOnProgress = () => {}
const failure = (text: string) => ({ output: [{ type: 'text' as const, text }], isError: true })
Expand Down Expand Up @@ -258,14 +280,7 @@ export default async function mcp(host: ExtensionHost) {
client.onNotification('notifications/tools/list_changed', () => {
rebuiltOnOpen(
'open reconnects MCP servers and lists their tools again',
client
.listTools()
.then((tools) => {
if (server.client === client) server.tools = tools
})
.catch((error: unknown) =>
console.warn(`MCP ${server.name}: tools/list: ${redact(server, error)}`),
),
relist(server, client),
)
})
const tools = await client.listTools()
Expand Down Expand Up @@ -388,14 +403,33 @@ export default async function mcp(host: ExtensionHost) {
return failure(
`MCP server ${name} is ${server.state}: ${server.error ?? 'not connected'}`,
)
if (!tool) return { output: [{ type: 'text', text: listing(server, match) }] }
if (!tool) {
await server.relisting
return { output: [{ type: 'text', text: listing(server, match) }] }
}
const client = server.client
const call = async () => {
for (let retries = 0; ; retries++) {
try {
return await client.callTool(tool, args ?? {}, {
signal: context.abortSignal,
timeoutMs: PROGRESS_RENEWED_CALL_TIMEOUT_MS,
onProgress: renewTimeoutOnProgress,
})
} catch (error) {
const wait =
rateLimited(error) && retries < RATE_LIMIT_RETRIES
? retryDelayWithinLongestWait(error)
: undefined
if (wait === undefined) throw error
await pace(wait, context.abortSignal)
}
}
}
try {
const result = await client.callTool(tool, args ?? {}, {
signal: context.abortSignal,
timeoutMs: PROGRESS_RENEWED_CALL_TIMEOUT_MS,
onProgress: renewTimeoutOnProgress,
})
const result = await call()
if (result.isError !== true && enablesBackendWhoseToolsListLate(tool))
await relist(server, client)
return { output: toLlmContent(result), isError: result.isError === true }
} catch (error) {
const brokenConnectionNoResend = !(
Expand Down
46 changes: 41 additions & 5 deletions extensions/mcp/test/mcp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,16 @@ const echoTools = [
},
]

const vaultTool = { name: 'vault_get', inputSchema: { type: 'object' } }

/** A Streamable HTTP MCP server with `tools` (by default `echo` and `shout`), answering only requests that carry the
* token. A call with `{text: 'busy'}` is refused with a 429, as a rate-limited gateway does; `shout` without `text` gets
* invalid params. */
* token. A call with `{text: 'busy'}` is refused with a 429 and a "Wait 0 seconds" hint, as a rate-limited Tool Gateway
* does, and `{text: 'busy 2'}` only twice; `refused` counts them. `shout` without `text` gets invalid params.
* `enable_backend` adds `vault_get` to the tools without telling the client, as Tool Gateway's notice comes late. */
let initializes = 0
const refused = new Map<string, number>()
async function serve(token: string, tools: object[] = echoTools) {
let listed = tools
const server = createServer((request, response) => {
if (request.method !== 'POST') {
response.writeHead(405).end()
Expand All @@ -55,16 +60,28 @@ async function serve(token: string, tools: object[] = echoTools) {
response.writeHead(202).end()
return
}
if (args.text === 'busy') {
const busy = /^busy(?: (\d+))?$/.exec(args.text ?? '')
if (busy && (refused.get(args.text) ?? 0) < Number(busy[1] ?? Infinity)) {
refused.set(args.text, (refused.get(args.text) ?? 0) + 1)
response.writeHead(429, { 'content-type': 'application/json' }).end(
JSON.stringify({
jsonrpc: '2.0',
id: message.id,
result: { content: [{ type: 'text', text: 'ratelimited' }], isError: true },
result: {
content: [
{ type: 'text', text: 'ratelimited' },
{
type: 'text',
text: 'Slack refused this call with a rate limit. Wait 0 seconds.',
},
],
isError: true,
},
}),
)
return
}
if (params.name === 'enable_backend') listed = [...listed, vaultTool]
if (params.name === 'shout' && args.text === undefined) {
response.writeHead(200, { 'content-type': 'application/json' }).end(
JSON.stringify({
Expand All @@ -81,7 +98,7 @@ async function serve(token: string, tools: object[] = echoTools) {
capabilities: { tools: {} },
serverInfo: { name: 'echo', version: '1.0.0' },
},
'tools/list': { tools },
'tools/list': { tools: listed },
'tools/call': {
content: [{ type: 'text', text: `echo: ${args.text ?? ''}` }],
isError: args.text === undefined,
Expand Down Expand Up @@ -150,13 +167,32 @@ it('connects configured servers, lists and calls their tools, and isolates a fai
expect(JSON.stringify(shout)).toContain('text is required')
expect(JSON.stringify(shout)).toContain('\\"required\\":[\\"text\\"]')
const connections = initializes
expect(await run({ server: 'echo', tool: 'echo', args: { text: 'busy 2' } })).toEqual({
output: [{ type: 'text', text: 'echo: busy 2' }],
isError: false,
})
expect(refused.get('busy 2')).toBe(2)
expect(await run({ server: 'echo', tool: 'echo', args: { text: 'busy' } })).toMatchObject({
isError: true,
output: [{ text: expect.stringContaining('Wait 0 seconds') }],
})
expect(refused.get('busy')).toBe(3)
expect(await run({ server: 'echo', tool: 'echo', args: { text: 'hi' } })).toMatchObject({
isError: false,
})
expect(initializes).toBe(connections)

expect(await run({ server: 'echo', match: 'vault' })).toMatchObject({
output: [{ text: expect.stringContaining('0 tools') }],
})
expect(
await run({ server: 'echo', tool: 'enable_backend', args: { text: 'vault' } }),
).toMatchObject({
isError: false,
})
expect(await run({ server: 'echo', match: 'vault' })).toMatchObject({
output: [{ text: expect.stringContaining('vault_get: ') }],
})
expect(await run({ server: 'locked', tool: 'echo' })).toMatchObject({
isError: true,
output: [{ text: expect.stringContaining('MCP server locked is failed') }],
Expand Down