返回源码地图

packages/coding-agent/src/extensions/mcp/index.ts

v1.3.0 · 71023aec1546 · 09:reachesTools等待server与session signal;非全管理UI审计

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1/**
2 * Built-in MCP integration.
3 *
4 * Connects the servers from `mcp.json` and the servers extensions register with
5 * `pi.registerMcpServer()` when a session starts, and servers registered later right away. A server
6 * in `mcp.json` takes precedence over a registered server of the same name. Connections run in the
7 * background: the first prompt waits only for servers with `direct` tools, and codemode scripts,
8 * `tool_search`, and the resource tools wait for the servers they need when they run. Tools are
9 * registered as `mcp__<server>__<tool>`. By default (`"exposure": "codemode"`) the tools are only
10 * callable from codemode scripts, which keeps MCP tools out of the model's tool declarations and
11 * the codemode description: scripts find the tools with `searchTools()` and the server instructions
12 * with `describeNamespace()`. The codemode tool is activated for that unless `autoEnableCodemode` is
13 * false. `"deferred"` declares the tools to the model once the `tool_search` tool loads them, and
14 * activates `tool_search` instead of codemode.
15 * `"exposure": "direct"` declares them to the model right away, and `"hidden"` makes them
16 * unreachable. `toolExposure` overrides the exposure of single tools. Servers with resources are
17 * reached through Codex's `list_mcp_resources`, `list_mcp_resource_templates`, and
18 * `read_mcp_resource` tools (resources.ts).
19 *
20 * Every call runs through pi's tool pipeline, so `tool_call`/`tool_result` hooks and permission
21 * extensions apply to MCP tools the same way they do to built-in tools.
22 *
23 * Problems found at startup (config errors, failed connections, servers that need a sign-in) are
24 * reported once. `/mcp` opens a manager to sign in, reconnect, enable or disable servers, and change
25 * their exposure; the last two are saved to the `mcp.json` that defines the server, or apply to the
26 * current session for registered servers.
27 */
28
29import { join, resolve } from "node:path";
30import type { SelectItem } from "@earendil-works/pi-tui";
31import type { TSchema } from "typebox";
32import { getAgentDir } from "../../config.ts";
33import type {
34 ExtensionAPI,
35 ExtensionCommandContext,
36 ExtensionContext,
37 ExtensionFactory,
38 ToolDefinition,
39} from "../../core/extensions/types.ts";
40import { mcpNamespace } from "../../core/mcp-servers.ts";
41import type { ModelRegistry } from "../../core/model-registry.ts";
42import { openBrowser } from "../../utils/open-browser.ts";
43import { CODEMODE_TOOL_NAME } from "../codemode/tool.ts";
44import { TOOL_SEARCH_TOOL_NAME } from "../tool-search/tool.ts";
45import {
46 getMcpToolExposure,
47 type LoadedMcpConfig,
48 loadMcpConfig,
49 type McpExposure,
50 type McpServerConfigPatch,
51 type McpServerEntry,
52 updateMcpServerConfig,
53} from "./config.ts";
54import type { McpOAuthCredentialStore, McpSignInPrompt } from "./oauth.ts";
55import {
56 createMcpResourceToolDefinitions,
57 LIST_MCP_RESOURCE_TEMPLATES_TOOL,
58 LIST_MCP_RESOURCES_TOOL,
59 READ_MCP_RESOURCE_TOOL,
60} from "./resources.ts";
61import { loadMcpRuntime } from "./runtime.lazy.ts";
62import type * as McpRuntime from "./runtime.ts";
63import type { McpServerConnection, McpServerLog, McpTransportFactory } from "./runtime.ts";
64import { createMcpToolDefinition, createMcpToolName, createMcpToolRenderers, type McpToolDetails } from "./tools.ts";
65import { type McpMenu, type McpUi, showMcpManager } from "./ui.ts";
66
67export type { McpTransportFactory } from "./runtime.ts";
68
69export interface McpExtensionOptions {
70 /** Defaults to reading `mcp.json` from the agent directory and the trusted project. */
71 loadConfig?: (ctx: ExtensionContext) => LoadedMcpConfig;
72 /** Defaults to stdio and streamable HTTP transports built from the server config. */
73 createTransport?: McpTransportFactory;
74 /** Defaults to `mcp-auth.json` in the agent directory. */
75 credentials?: McpOAuthCredentialStore;
76 /** File server log messages are appended to. Defaults to `mcp.log` in the agent directory. */
77 logPath?: string;
78 /** Opens the OAuth authorization URL. Defaults to the platform browser. */
79 openUrl?: (url: string) => void;
80 /**
81 * Saves `/mcp` changes to the server's config file: its project `override` when set, else its
82 * `source`. Defaults to editing that `mcp.json`.
83 */
84 updateConfig?: (entry: McpServerEntry, patch: McpServerConfigPatch) => void;
85 /**
86 * How long the first prompt waits for servers with `direct` tools that are still connecting at
87 * startup, in milliseconds. Their tools become available when they connect. Other servers are
88 * waited for when a script or search needs them. Default: 10000.
89 */
90 startupWaitMs?: number;
91}
92
93const DEFAULT_STARTUP_WAIT_MS = 10_000;
94
95const RESOURCE_TOOL_NAMES: ReadonlySet<string> = new Set([
96 LIST_MCP_RESOURCES_TOOL,
97 LIST_MCP_RESOURCE_TEMPLATES_TOOL,
98 READ_MCP_RESOURCE_TOOL,
99]);
100
101/** A configured server. Disabled servers have no connection. */
102interface McpServer {
103 entry: McpServerEntry;
104 connection?: McpServerConnection;
105 /** For servers extensions registered: the config as registered, to detect re-registrations. */
106 registeredConfig?: string;
107 /** Result of the last `/mcp` action that failed, shown in the manager. */
108 message?: string;
109 /** Identifies the current connection attempt; disabling or replacing it invalidates earlier work. */
110 attempt?: symbol;
111 /** Settles when the connection started for the server connected or failed. */
112 ready?: Promise<void>;
113 /** Cleanup of a detached connection; a replacement waits for it before opening a transport. */
114 closing?: Promise<void>;
115}
116
117const EXPOSURE_DESCRIPTIONS: Record<Exclude<McpExposure, "hidden">, string> = {
118 codemode: "called from codemode scripts, which find them with searchTools()",
119 deferred: "not declared until tool_search loads them, then called directly; no codemode needed",
120 direct: "declared to the model like built-in tools",
121};
122
123function errorMessage(error: unknown): string {
124 return error instanceof Error ? error.message : String(error);
125}
126
127function firstLine(text: string): string {
128 return text.split("\n", 1)[0] ?? "";
129}
130
131function isEnabled(server: Pick<McpServer, "entry">): boolean {
132 return server.entry.config.enabled !== false;
133}
134
135function exposureOf(entry: McpServerEntry): McpExposure {
136 return entry.config.exposure ?? "codemode";
137}
138
139/** Exposures the server's tools can have, known from its config before it connects. */
140function configuredExposures(entry: McpServerEntry): Set<McpExposure> {
141 return new Set([exposureOf(entry), ...Object.values(entry.config.toolExposure ?? {})]);
142}
143
144/** Whether some of the server's tools are declared to the model, so the first prompt waits for them. */
145function hasDirectTools(entry: McpServerEntry): boolean {
146 return configuredExposures(entry).has("direct");
147}
148
149/** Whether some of the server's tools are reached through codemode or tool_search. */
150function hasIndirectTools(entry: McpServerEntry): boolean {
151 const exposures = configuredExposures(entry);
152 return exposures.has("codemode") || exposures.has("deferred");
153}
154
155/** Name of the system prompt section that lists the servers whose tools are not declared. */
156export const MCP_SERVERS_SECTION = "mcp_servers";
157/** Characters of a server description in the section, as Codex allows for deferred namespaces. */
158const MAX_SERVER_DESCRIPTION_CHARS = 250;
159/**
160 * Characters of the whole section. Descriptions shrink to fit; when the server lines alone do not
161 * fit, the last servers are left out and counted in a closing line.
162 */
163export const MAX_SERVERS_SECTION_CHARS = 4096;
164
165/** The section's first line. It explains only the ways of reaching tools that the listed servers use. */
166function serversSectionIntro(reaches: ReadonlySet<string>): string {
167 let intro = "MCP servers whose tools are not declared to you.";
168 if (reaches.has("codemode")) intro += " Call the tools of `codemode` servers from codemode scripts.";
169 if (reaches.has("tool_search")) intro += " Load the tools of `tool_search` servers with `tool_search`.";
170 return intro;
171}
172
173function truncate(text: string, max: number): string {
174 if (text.length <= max) return text;
175 return max <= 1 ? "" : `${text.slice(0, max - 1).trimEnd()}…`;
176}
177
178/** What the `mcp_servers` section needs of a server. */
179export interface McpServerListing {
180 entry: McpServerEntry;
181 connection?: { instructions?: string };
182}
183
184/** First line of the configured description, or of the server instructions once connected. */
185function serverSummary(server: McpServerListing): string {
186 const text = server.entry.config.description?.trim() || server.connection?.instructions || "";
187 return (text.split("\n", 1)[0] ?? "").trim();
188}
189
190/**
191 * The `mcp_servers` section: every enabled server with codemode or deferred tools, with how its
192 * tools are reached and a one-line summary. The model learns of the servers from it, since neither
193 * codemode nor tool_search lists them. Undefined when there are no such servers.
194 */
195export function renderServersSection(servers: readonly McpServerListing[]): string | undefined {
196 const listed = servers
197 .filter((server) => isEnabled(server) && hasIndirectTools(server.entry))
198 .sort((a, b) => a.entry.name.localeCompare(b.entry.name));
199 if (listed.length === 0) return undefined;
200 const reaches = listed.map((server) =>
201 configuredExposures(server.entry).has("codemode") ? "codemode" : "tool_search",
202 );
203 const intro = serversSectionIntro(new Set(reaches));
204 const heads = listed.map((server, index) => `- ${mcpNamespace(server.entry.name)} (${reaches[index]})`);
205 const omitted = (count: number) =>
206 count > 0 ? [`- … ${count} more server${count === 1 ? "" : "s"}; find their tools with searchTools()`] : [];
207 // Characters of the intro, the first `kept` server lines without descriptions, and the omission line.
208 const size = (kept: number) => [intro, ...heads.slice(0, kept), ...omitted(listed.length - kept)].join("\n").length;
209 let kept = listed.length;
210 while (kept > 0 && size(kept) > MAX_SERVERS_SECTION_CHARS) kept--;
211 // Each description also takes a ": " separator.
212 const perServer =
213 kept === 0
214 ? 0
215 : Math.min(MAX_SERVER_DESCRIPTION_CHARS, Math.floor((MAX_SERVERS_SECTION_CHARS - size(kept)) / kept) - 2);
216 const lines = listed.slice(0, kept).map((server, index) => {
217 const summary = perServer > 0 ? truncate(serverSummary(server), perServer) : "";
218 return summary ? `${heads[index]}: ${summary}` : heads[index];
219 });
220 return [intro, ...lines, ...omitted(listed.length - kept)].join("\n");
221}
222
223/**
224 * Whether a call that reaches `reach` (see `ToolDefinition.reachesTools`) needs the server: it
225 * reaches every tool, or one of its words contains the server's namespace.
226 */
227function reachesServer(reach: "all" | readonly string[], server: string): boolean {
228 if (reach === "all") return true;
229 const namespace = mcpNamespace(server);
230 return reach.some((word) => word.includes(namespace));
231}
232
233/** Short state for lists and the startup report. `withError` appends the first line of a failure. */
234function describeState(server: McpServer, withError = true): string {
235 if (!isEnabled(server)) return "disabled";
236 const connection = server.connection;
237 if (!connection) return "starting";
238 switch (connection.state) {
239 case "needs-auth":
240 return "needs sign-in";
241 case "failed":
242 return withError ? `failed: ${firstLine(connection.error ?? "unknown error")}` : "failed";
243 case "connected": {
244 const { tools, hasResources } = connection;
245 return `connected · ${tools.length} tool${tools.length === 1 ? "" : "s"}${hasResources ? " · resources" : ""}`;
246 }
247 case "connecting":
248 return "connecting…";
249 default:
250 return connection.state;
251 }
252}
253
254/** Servers that need the user first. */
255function attentionRank(server: McpServer): number {
256 if (!isEnabled(server)) return 5;
257 switch (server.connection?.state) {
258 case "needs-auth":
259 return 0;
260 case "failed":
261 return 1;
262 case "disconnected":
263 return 2;
264 case "connected":
265 return 4;
266 default:
267 return 3;
268 }
269}
270
271function describeTransport(entry: McpServerEntry): string {
272 const { config } = entry;
273 if ("url" in config) return config.url;
274 return [config.command, ...(config.args ?? [])].join(" ");
275}
276
277const MCP_USAGE = "Usage: /mcp, /mcp login [server], /mcp logout [server], /mcp reconnect [server]";
278
279export function createMcpExtension(options: McpExtensionOptions = {}): ExtensionFactory {
280 return (pi: ExtensionAPI) => {
281 let servers: McpServer[] = [];
282 /** Servers from `mcp.json`, which take precedence over registered servers of the same name. */
283 let configuredEntries: McpServerEntry[] = [];
284 let configErrors: string[] = [];
285 /** The trusted project's `mcp.json`, where `/mcp` saves project overrides of global servers. */
286 let projectConfig: string | undefined;
287 /** Registered servers that `mcp.json` overrides, shown in `/mcp`. */
288 let overridden: string[] = [];
289 let autoEnableCodemode = true;
290 /** Whether the "codemode tools unreachable" warning was shown since the session started. */
291 let warnedUnreachable = false;
292 let pending: Promise<unknown> | undefined;
293 /** Whether a prompt already waited for the startup connections since the session started. */
294 let waitedForStartup = false;
295 const startupWaitMs = options.startupWaitMs ?? DEFAULT_STARTUP_WAIT_MS;
296 /** Working directory of the session, for stdio servers. */
297 let sessionCwd = process.cwd();
298 let credentials = options.credentials;
299 /** The session's model registry, which resolves `auth.provider` tokens. */
300 let modelRegistry: ModelRegistry | undefined;
301 let serverLog: McpServerLog | undefined;
302 const openUrl = options.openUrl ?? openBrowser;
303 const updateConfig =
304 options.updateConfig ??
305 ((entry, patch) =>
306 updateMcpServerConfig(entry.override ?? entry.source, entry.name, patch, {
307 override: entry.override !== undefined,
308 }));
309
310 /**
311 * Lifetime of the current session: aborted on session_shutdown, and before the first session_start
312 * (registrations before that are read on session_start). Work captures `session.signal` when it
313 * starts and drops late results once it aborted, for example a runtime load that resolves after
314 * shutdown. Work that outlives the command that started it also stops on the signal and is
315 * registered with `track`, so shutdown can wait for its cleanup.
316 */
317 let session = new AbortController();
318 session.abort();
319 /** Work registered with `track`: manager actions opening or closing connections, and sign-ins. */
320 const backgroundActions = new Set<Promise<void>>();
321 const track = <T>(work: Promise<T>): Promise<T> => {
322 const task = work.then(
323 () => undefined,
324 () => undefined,
325 );
326 backgroundActions.add(task);
327 void task.finally(() => backgroundActions.delete(task));
328 return work;
329 };
330 const listeners = new Set<() => void>();
331 const emitChange = () => {
332 for (const listener of listeners) listener();
333 };
334 const subscribe = (listener: () => void) => {
335 listeners.add(listener);
336 return () => {
337 listeners.delete(listener);
338 };
339 };
340
341 const connections = () => servers.flatMap((server) => (server.connection ? [server.connection] : []));
342 const findServer = (name: string) => servers.find((server) => server.entry.name === name);
343
344 /** Servers extensions registered, except names `mcp.json` defines, which take precedence. */
345 const registeredServers = (): { servers: McpServer[]; overridden: string[] } => {
346 const registered: McpServer[] = [];
347 const overriddenNames: string[] = [];
348 for (const { name, config, extensionPath } of pi.getMcpServers()) {
349 const configured = configuredEntries.find((entry) => mcpNamespace(entry.name) === mcpNamespace(name));
350 if (configured) {
351 overriddenNames.push(
352 `"${name}" registered by ${extensionPath} is overridden by "${configured.name}" in ${configured.source}`,
353 );
354 continue;
355 }
356 registered.push({
357 entry: { name, config, source: extensionPath, scope: "extension" },
358 registeredConfig: JSON.stringify(config),
359 });
360 }
361 return { servers: registered, overridden: overriddenNames };
362 };
363
364 const getCredentials = (runtime: typeof McpRuntime): McpOAuthCredentialStore => {
365 credentials ??= new runtime.McpOAuthCredentialStore();
366 return credentials;
367 };
368
369 const getServerLog = (runtime: typeof McpRuntime): McpServerLog => {
370 serverLog ??= new runtime.McpServerLog(options.logPath ?? join(getAgentDir(), "mcp.log"));
371 return serverLog;
372 };
373
374 /** pi tool name to the `<server>\0<tool>` it was assigned to, so names stay unique and stable. */
375 const toolOwners = new Map<string, string>();
376 /** Tool names currently offered by each server. */
377 const serverTools = new Map<string, Set<string>>();
378 /** Last definition registered under each tool name, to re-register withdrawn tools as hidden. */
379 const definitions = new Map<string, ToolDefinition<TSchema, McpToolDetails>>();
380
381 // A resumed session renders calls to MCP tools before their server connected, if it ever does.
382 pi.registerToolRenderer((toolName, next) => {
383 const match = /^mcp__(.+?)__(.+)$/.exec(toolName);
384 return next() ?? (match ? createMcpToolRenderers(`${match[1]}/${match[2]}`) : undefined);
385 });
386
387 const registerTools = (connection: McpServerConnection) => {
388 const server = connection.entry.name;
389 const entry = findServer(server)?.entry ?? connection.entry;
390 const description = entry.config.description?.trim();
391 const namespace = {
392 name: mcpNamespace(server),
393 // `describeNamespace("docs")` finds `mcp__docs`.
394 aliases: [server],
395 ...(description ? { description } : {}),
396 ...(connection.instructions ? { instructions: connection.instructions } : {}),
397 };
398 const previous = serverTools.get(server) ?? new Set<string>();
399 const current = new Set<string>();
400 // Like Codex, all tools whose names sanitize to the same name get the hash suffix, so which
401 // one would keep the plain name does not depend on the order of the list.
402 const plain = [...new Set(connection.tools.map((tool) => tool.name))].map((tool) =>
403 createMcpToolName(server, tool),
404 );
405 const assignName = (tool: string, owner: string) => {
406 const name = createMcpToolName(server, tool, (candidate) => {
407 const existing = toolOwners.get(candidate);
408 return (
409 (existing !== undefined && existing !== owner) ||
410 current.has(candidate) ||
411 plain.indexOf(candidate) !== plain.lastIndexOf(candidate)
412 );
413 });
414 toolOwners.set(name, owner);
415 current.add(name);
416 return name;
417 };
418 for (const tool of connection.tools) {
419 const definition = createMcpToolDefinition({
420 server,
421 tool,
422 name: assignName(tool.name, `${server}\0${tool.name}`),
423 exposure: getMcpToolExposure(entry.config, tool.name),
424 namespace,
425 timeoutMs: connection.timeoutMs,
426 getClient: async () => {
427 // A prepared call can outlive this definition's connection while the readiness
428 // hook waits for a disable/re-enable. Resolve the replacement at execution time.
429 const current = findServer(server);
430 if (!current || !isEnabled(current)) throw new Error(`MCP server "${server}" is disabled.`);
431 const client = current.connection;
432 if (!client) throw new Error(`MCP server "${server}" is still starting.`);
433 if (
434 getMcpToolExposure(current.entry.config, tool.name) === "hidden" ||
435 (client.state === "connected" && !client.tools.some((offered) => offered.name === tool.name))
436 ) {
437 throw new Error(`MCP tool "${server}/${tool.name}" is no longer available.`);
438 }
439 return client;
440 },
441 readableResources: () => resourceServers().some((current) => current.name === server),
442 });
443 definitions.set(definition.name, definition);
444 pi.registerTool(definition);
445 }
446 serverTools.set(server, current);
447 // Tools cannot be unregistered, so tools the server dropped are re-registered as hidden. When
448 // the server offers them again they are registered with their configured exposure above.
449 for (const name of previous) {
450 const definition = definitions.get(name);
451 if (!current.has(name) && definition) pi.registerTool({ ...definition, exposure: "hidden" });
452 }
453 syncResourceTools();
454 };
455
456 /** Make a disabled server's tools unreachable. */
457 const hideTools = (server: string) => {
458 for (const name of serverTools.get(server) ?? []) {
459 const definition = definitions.get(name);
460 if (definition) pi.registerTool({ ...definition, exposure: "hidden" });
461 }
462 serverTools.set(server, new Set());
463 syncResourceTools();
464 };
465
466 /** Enabled servers with resources whose exposure is not `hidden`, which the resource tools reach. */
467 const serversWithResources = (): McpServer[] =>
468 servers.filter(
469 (server) => server.connection?.hasResources && isEnabled(server) && exposureOf(server.entry) !== "hidden",
470 );
471 const resourceServers = (): McpServerConnection[] =>
472 serversWithResources().flatMap((server) => (server.connection ? [server.connection] : []));
473
474 /** Exposure the resource tools were last registered with; undefined until a server has resources. */
475 let resourceToolsExposure: McpExposure | undefined;
476 /**
477 * Register the resource tools with the widest exposure of the servers they reach: `direct` when
478 * one of them is direct, and so on. They are hidden when no server has resources.
479 */
480 const syncResourceTools = () => {
481 const exposures = new Set(serversWithResources().map((server) => exposureOf(server.entry)));
482 const exposure = (["direct", "codemode", "deferred"] as const).find((candidate) => exposures.has(candidate));
483 const next = exposure ?? "hidden";
484 if (next === resourceToolsExposure || (resourceToolsExposure === undefined && next === "hidden")) return;
485 const wasDirect = resourceToolsExposure === "direct";
486 resourceToolsExposure = next;
487 const resourceDefinitions = createMcpResourceToolDefinitions({ exposure: next, servers: resourceServers });
488 for (const definition of resourceDefinitions) pi.registerTool(definition);
489 if (wasDirect) {
490 const names = new Set(resourceDefinitions.map((definition) => definition.name));
491 pi.setActiveTools(pi.getActiveTools().filter((name) => !names.has(name)));
492 }
493 };
494
495 /**
496 * Tools that are not declared to the model are reached through the codemode tool (scripts call
497 * them) or the tool_search tool (it declares them). Either reaches every such tool. Activate the
498 * one the tools' exposure asks for: codemode for `codemode` unless `autoEnableCodemode` is false,
499 * tool_search for `deferred`.
500 */
501 const ensureDiscoveryActive = (ctx: ExtensionContext) => {
502 // From the config, so the tool is active before the servers connect. Resource tools share
503 // their server's exposure.
504 const exposures = new Set<McpExposure>();
505 for (const server of servers) {
506 if (isEnabled(server)) for (const exposure of configuredExposures(server.entry)) exposures.add(exposure);
507 }
508 const needsCodemode = exposures.has("codemode");
509 const needsToolSearch = exposures.has("deferred");
510 if (!needsCodemode && !needsToolSearch) return;
511 // Only a tool of these names that declares `reachesTools` can reach MCP tools; another
512 // extension's tool of the same name without it is never activated.
513 const tools = pi.getAllTools();
514 const hasReachingTool = (name: string) => tools.some((tool) => tool.name === name && tool.reachesTools);
515 const hasCodemode = hasReachingTool(CODEMODE_TOOL_NAME);
516 const hasToolSearch = hasReachingTool(TOOL_SEARCH_TOOL_NAME);
517 const active = pi.getActiveTools();
518 const activate: string[] = [];
519 if (needsCodemode && hasCodemode && autoEnableCodemode && !active.includes(CODEMODE_TOOL_NAME)) {
520 activate.push(CODEMODE_TOOL_NAME);
521 }
522 if (needsToolSearch && hasToolSearch && !active.includes(TOOL_SEARCH_TOOL_NAME)) {
523 activate.push(TOOL_SEARCH_TOOL_NAME);
524 }
525 if (activate.length > 0) pi.setActiveTools([...active, ...activate]);
526 const reachable = [...active, ...activate];
527 if (hasCodemode && reachable.includes(CODEMODE_TOOL_NAME)) return;
528 if (hasToolSearch && reachable.includes(TOOL_SEARCH_TOOL_NAME)) return;
529 if (warnedUnreachable) return;
530 warnedUnreachable = true;
531 const reason = needsCodemode && hasCodemode && !autoEnableCodemode ? " (autoEnableCodemode is false)" : "";
532 ctx.ui.notify(
533 `MCP tools are only reachable from the codemode or tool_search tool, but neither is active${reason}; they cannot be called.`,
534 "warning",
535 );
536 };
537
538 /**
539 * Stored tokens of servers waiting for a sign-in, as they were when the sign-in was needed.
540 * `pi mcp login` in another process (for example run by the agent) changes them.
541 */
542 const tokensAtSignIn = new Map<McpServerConnection, string>();
543 const storedTokens = (connection: McpServerConnection): string => {
544 const url = connection.oauthUrl;
545 return url && credentials ? JSON.stringify(credentials.tokens(connection.name, url) ?? null) : "null";
546 };
547 const onConnectionChange = (connection: McpServerConnection) => {
548 if (connection.state !== "needs-auth") tokensAtSignIn.delete(connection);
549 else if (!tokensAtSignIn.has(connection)) tokensAtSignIn.set(connection, storedTokens(connection));
550 emitChange();
551 };
552 /** Reconnect servers that need a sign-in when their credentials were stored since. */
553 const reconnectSignedIn = async (ctx: ExtensionContext) => {
554 const signedIn = [...tokensAtSignIn].filter(([connection, tokens]) => storedTokens(connection) !== tokens);
555 if (signedIn.length === 0) return;
556 for (const [connection] of signedIn) tokensAtSignIn.delete(connection);
557 await Promise.allSettled(signedIn.map(([connection]) => connection.reconnect()));
558 ensureDiscoveryActive(ctx);
559 };
560
561 /** Create the server's connection, loading the MCP runtime on first use. */
562 const createConnection = async (
563 server: McpServer,
564 isCurrent: () => boolean,
565 ): Promise<McpServerConnection | undefined> => {
566 const runtime = await loadMcpRuntime();
567 if (!isCurrent()) return undefined;
568 const connection = new runtime.McpServerConnection({
569 entry: server.entry,
570 cwd: sessionCwd,
571 createTransport: options.createTransport ?? runtime.createDefaultTransport,
572 credentials: getCredentials(runtime),
573 providerToken: async (provider) => modelRegistry?.getApiKeyForProvider(provider),
574 log: getServerLog(runtime),
575 onTools: (connection) => {
576 if (isCurrent()) registerTools(connection);
577 },
578 onChange: (connection) => {
579 if (isCurrent()) onConnectionChange(connection);
580 else tokensAtSignIn.delete(connection);
581 },
582 });
583 server.connection = connection;
584 emitChange();
585 return connection;
586 };
587
588 /**
589 * Connect the server in the background. `server.ready` settles when it connected or failed;
590 * failures show in its state. It starts after `after`, unless disabled, replaced, or shut down
591 * meanwhile. The returned promise rejects when the MCP runtime cannot be loaded.
592 */
593 const startConnection = (server: McpServer, after?: Promise<unknown>): Promise<void> => {
594 const { signal } = session;
595 const attempt = Symbol();
596 server.attempt = attempt;
597 const isCurrent = () =>
598 !signal.aborted && server.attempt === attempt && isEnabled(server) && servers.includes(server);
599 const ready = (async () => {
600 await after;
601 if (!isCurrent()) return;
602 const connection = await createConnection(server, isCurrent);
603 if (!connection || !isCurrent()) return;
604 await connection.getClient().catch(() => undefined);
605 })();
606 server.ready = ready.catch(() => undefined);
607 return ready;
608 };
609
610 /** Wait for the latest connection attempts, including ones queued while waiting, or an abort. */
611 const waitForServers = async (waiting: readonly McpServer[], signal: AbortSignal | undefined) => {
612 for (;;) {
613 const ready = waiting.flatMap((server) =>
614 isEnabled(server) && servers.includes(server) && server.ready ? [{ server, ready: server.ready }] : [],
615 );
616 if (ready.length === 0 || signal?.aborted) return;
617 let onAbort: (() => void) | undefined;
618 await Promise.race([
619 Promise.all(ready.map((attempt) => attempt.ready)),
620 new Promise<void>((resolve) => {
621 onAbort = () => resolve();
622 signal?.addEventListener("abort", onAbort, { once: true });
623 }),
624 ]);
625 if (onAbort) signal?.removeEventListener("abort", onAbort);
626 if (
627 signal?.aborted ||
628 ready.every(
629 (attempt) =>
630 !isEnabled(attempt.server) ||
631 !servers.includes(attempt.server) ||
632 attempt.ready === attempt.server.ready,
633 )
634 )
635 return;
636 }
637 };
638
639 /**
640 * One message for everything that needs the user after startup, or only for `only`, servers
641 * that connected later.
642 */
643 const reportProblems = (ctx: ExtensionContext, only?: readonly McpServer[]) => {
644 const lines = only ? [] : configErrors.map((error) => `config: ${error}`);
645 for (const server of only ?? servers) {
646 const state = server.connection?.state;
647 if (state === "needs-auth" || state === "failed")
648 lines.push(`${server.entry.name}: ${describeState(server)}`);
649 }
650 if (lines.length === 0) return;
651 ctx.ui.notify(
652 `MCP servers need attention:\n${lines.map((line) => ` ${line}`).join("\n")}\nRun /mcp to fix.`,
653 "warning",
654 );
655 };
656
657 /**
658 * Save a config change; returns an error message when the file could not be updated. Changes to
659 * registered servers only apply to the current session. `inProject` adds a project override.
660 */
661 const saveConfig = (server: McpServer, patch: McpServerConfigPatch, inProject = false): string | undefined => {
662 const override = inProject ? projectConfig : server.entry.override;
663 const entry = override ? { ...server.entry, override } : server.entry;
664 if (entry.scope !== "extension") {
665 try {
666 updateConfig(entry, patch);
667 } catch (error) {
668 return `Could not update ${entry.override ?? entry.source}: ${errorMessage(error)}`;
669 }
670 }
671 server.entry = { ...entry, config: { ...entry.config, ...patch } };
672 return undefined;
673 };
674
675 /** Sign in, then reconnect. Returns an error message on failure. `cancel` or the session's end stops the sign-in. */
676 const signIn = async (
677 server: McpServer,
678 prompt: McpSignInPrompt,
679 cancel?: AbortSignal,
680 ): Promise<string | undefined> => {
681 const connection = server.connection;
682 const url = connection?.oauthUrl;
683 if (!connection || !url) return `MCP server "${server.entry.name}" does not use OAuth.`;
684 const runtime = await loadMcpRuntime();
685 const signal = cancel ? AbortSignal.any([session.signal, cancel]) : session.signal;
686 try {
687 await track(
688 runtime.signInMcpServer({
689 serverUrl: url,
690 store: getCredentials(runtime).forServer(server.entry.name, url),
691 settings: connection.oauthSettings(),
692 challenge: connection.challenge,
693 prompt,
694 signal,
695 }),
696 );
697 } catch (error) {
698 if (error instanceof runtime.McpSignInCancelledError) return "Sign-in cancelled.";
699 return `Sign-in failed: ${errorMessage(error)}`;
700 }
701 // The challenge that asked for this sign-in (for example for more scope) is answered.
702 connection.challenge = undefined;
703 try {
704 await connection.reconnect();
705 } catch (error) {
706 return `Signed in, but ${errorMessage(error)}`;
707 }
708 return undefined;
709 };
710
711 const signOut = async (server: McpServer): Promise<boolean> => {
712 const connection = server.connection;
713 const url = connection?.oauthUrl;
714 if (!connection || !url) return false;
715 const removed = getCredentials(await loadMcpRuntime()).remove(server.entry.name, url);
716 await connection.signOut();
717 return removed;
718 };
719
720 const reconnect = async (server: McpServer): Promise<string | undefined> => {
721 const connection = server.connection;
722 if (!connection) return `MCP server "${server.entry.name}" is disabled.`;
723 const previous = server.ready;
724 const ready = (async () => {
725 await previous;
726 await connection.reconnect();
727 })();
728 server.ready = ready.catch(() => undefined);
729 try {
730 await ready;
731 return undefined;
732 } catch (error) {
733 return errorMessage(error);
734 }
735 };
736
737 /** Returns an error message when the config could not be saved; connection errors show in the state. */
738 const setEnabled = async (
739 server: McpServer,
740 enabled: boolean,
741 inProject = false,
742 ): Promise<string | undefined> => {
743 const failed = saveConfig(server, { enabled }, inProject);
744 if (failed) return failed;
745 if (!enabled) {
746 const connection = server.connection;
747 server.attempt = undefined;
748 server.connection = undefined;
749 if (connection) {
750 // A reconnect may already have detached its old client while awaiting transport
751 // shutdown. Closing the connection alone does not wait for that reconnect.
752 server.closing = Promise.all([connection.close(), server.ready]).then(() => undefined);
753 }
754 const closing = server.closing;
755 hideTools(server.entry.name);
756 emitChange();
757 try {
758 await closing;
759 } finally {
760 if (server.closing === closing) server.closing = undefined;
761 }
762 return undefined;
763 }
764 await startConnection(server, server.closing);
765 return undefined;
766 };
767
768 const setExposure = (server: McpServer, exposure: McpExposure): string | undefined => {
769 const failed = saveConfig(server, { exposure });
770 if (failed) return failed;
771 if (server.connection?.state === "connected") registerTools(server.connection);
772 syncResourceTools();
773 // Tools no longer exposed directly leave the declared set; direct tools are activated on registration.
774 const indirect = new Set(
775 pi
776 .getAllTools()
777 .filter((tool) => tool.exposure !== "direct")
778 .map((tool) => tool.name),
779 );
780 const tools = serverTools.get(server.entry.name) ?? new Set<string>();
781 pi.setActiveTools(pi.getActiveTools().filter((name) => !tools.has(name) || !indirect.has(name)));
782 emitChange();
783 return undefined;
784 };
785
786 // ---------------------------------------------------------------------------------------
787 // Manager (`/mcp` in the TUI)
788 // ---------------------------------------------------------------------------------------
789
790 const notices = () => [
791 ...configErrors.map((error) => `config: ${error}`),
792 ...overridden.map((line) => `overridden: ${line}`),
793 ];
794
795 const serversMenu = (): McpMenu => ({
796 title: "MCP servers",
797 error: notices().join("\n") || undefined,
798 items: [...servers]
799 .sort((a, b) => attentionRank(a) - attentionRank(b) || a.entry.name.localeCompare(b.entry.name))
800 .map((server) => ({
801 value: server.entry.name,
802 label: server.entry.name,
803 description: `${describeState(server)} · ${exposureOf(server.entry)} · ${server.entry.override ? "global, project override" : (server.entry.scope ?? server.entry.source)}`,
804 })),
805 empty: `No MCP servers configured. Add them to ${resolve(getAgentDir(), "mcp.json")} or .pi/mcp.json.`,
806 confirmLabel: "manage",
807 cancelLabel: "close",
808 });
809
810 const serverMenu = (name: string): McpMenu => {
811 const server = findServer(name);
812 if (!server) {
813 return {
814 title: name,
815 items: [],
816 empty: "This server is no longer configured.",
817 confirmLabel: "",
818 cancelLabel: "back",
819 };
820 }
821 const { entry, connection } = server;
822 const saved =
823 entry.scope === "extension"
824 ? "for this session"
825 : entry.override
826 ? "saved to the project mcp.json"
827 : entry.scope
828 ? `saved to the ${entry.scope} mcp.json`
829 : "saved to mcp.json";
830 // Global servers without an override can be turned on or off for the trusted project alone.
831 const inProject = entry.scope === "global" && !entry.override && projectConfig !== undefined;
832 const inProjectSaved = "saved to the project mcp.json";
833 const items: SelectItem[] = [];
834 if (!isEnabled(server)) {
835 items.push({ value: "enable", label: "Enable", description: saved });
836 if (inProject) {
837 items.push({ value: "enable-project", label: "Enable in this project", description: inProjectSaved });
838 }
839 } else {
840 const state = connection?.state;
841 if (state === "needs-auth")
842 items.push({ value: "signin", label: "Sign in", description: "opens the browser" });
843 if (state === "connected" && connection) {
844 items.push({ value: "tools", label: "Tools", description: `${connection.tools.length} offered` });
845 }
846 if (state === "failed" || state === "disconnected" || state === "connected" || state === "needs-auth") {
847 items.push({ value: "reconnect", label: "Reconnect" });
848 }
849 if (state === "connected" && connection?.oauthUrl) {
850 items.push({ value: "signout", label: "Sign out", description: "deletes the stored credentials" });
851 }
852 items.push({ value: "exposure", label: "Exposure", description: exposureOf(entry) });
853 items.push({ value: "disable", label: "Disable", description: saved });
854 if (inProject) {
855 items.push({ value: "disable-project", label: "Disable in this project", description: inProjectSaved });
856 }
857 }
858 const details = [
859 describeTransport(entry),
860 `${entry.scope ?? "config"}: ${entry.source}`,
861 ...(entry.override ? [`project override: ${entry.override}`] : []),
862 `State: ${describeState(server, false)}`,
863 ];
864 const error = [server.message, connection?.state === "connected" ? undefined : connection?.error]
865 .filter((line): line is string => line !== undefined)
866 .join("\n");
867 return {
868 title: `MCP server ${name}`,
869 details: details.join("\n"),
870 error: error || undefined,
871 items,
872 selected: items[0]?.value,
873 confirmLabel: "select",
874 cancelLabel: "back",
875 };
876 };
877
878 const showTools = async (ui: McpUi, server: McpServer) => {
879 const exposure = exposureOf(server.entry);
880 const overridden = Object.keys(server.entry.config.toolExposure ?? {}).length > 0;
881 await ui.menu(() => ({
882 title: `Tools of ${server.entry.name}`,
883 details: `Exposure ${exposure}: ${exposure === "hidden" ? "unreachable" : EXPOSURE_DESCRIPTIONS[exposure]}${overridden ? "\nSome tools override it with toolExposure." : ""}`,
884 items: (server.connection?.tools ?? []).map((tool) => {
885 const toolExposure = getMcpToolExposure(server.entry.config, tool.name);
886 const description = firstLine(tool.description ?? "");
887 return {
888 value: tool.name,
889 label: tool.name,
890 description: toolExposure === exposure ? description : `[${toolExposure}] ${description}`,
891 };
892 }),
893 empty: "The server offers no tools.",
894 confirmLabel: "back",
895 cancelLabel: "back",
896 }));
897 };
898
899 const chooseExposure = async (ui: McpUi, server: McpServer): Promise<string | undefined> => {
900 const current = exposureOf(server.entry);
901 const choice = await ui.menu(() => ({
902 title: `Exposure of ${server.entry.name}`,
903 details:
904 server.entry.scope === "extension"
905 ? `Applies to this session; the server is registered by ${server.entry.source}.`
906 : `Saved to ${server.entry.override ?? server.entry.source}.`,
907 items: (Object.keys(EXPOSURE_DESCRIPTIONS) as (keyof typeof EXPOSURE_DESCRIPTIONS)[]).map((exposure) => ({
908 value: exposure,
909 label: `${exposure === current ? "✓ " : " "}${exposure}`,
910 description: EXPOSURE_DESCRIPTIONS[exposure],
911 })),
912 selected: current,
913 confirmLabel: "save",
914 cancelLabel: "back",
915 }));
916 if (!choice || choice === current) return undefined;
917 return setExposure(server, choice as McpExposure);
918 };
919
920 /** Sign in with the manager view's sign-in screen, which shows the URL with a copy key and cancels with Esc. */
921 const signInWithUi = (ui: McpUi, server: McpServer): Promise<string | undefined> => {
922 const title = `Sign in to ${server.entry.name}`;
923 const cancel = new AbortController();
924 const status = (message: string) => ui.status(title, message, () => cancel.abort());
925 let authorizationUrl = "";
926 status("Contacting the authorization server…");
927 return signIn(
928 server,
929 {
930 showAuthorizationUrl: (url) => {
931 authorizationUrl = url.href;
932 openUrl(url.href);
933 },
934 promptForRedirectUrl: async (signal) => {
935 const value = await ui.redirectUrl(title, authorizationUrl, signal);
936 status("Connecting…");
937 return value;
938 },
939 },
940 cancel.signal,
941 );
942 };
943
944 /** Keep the subscribed menu usable while a connection opens or closes. */
945 const runInBackground = (
946 ctx: ExtensionContext,
947 server: McpServer,
948 operation: () => Promise<string | undefined>,
949 ) => {
950 const ready = operation();
951 const attempt = server.attempt;
952 const { signal } = session;
953 const finish = (message: string | undefined) => {
954 if (signal.aborted || server.attempt !== attempt || !servers.includes(server)) return;
955 server.message = message;
956 ensureDiscoveryActive(ctx);
957 emitChange();
958 };
959 void track(ready.then(finish, (error: unknown) => finish(errorMessage(error))));
960 };
961
962 const runAction = async (ui: McpUi, ctx: ExtensionContext, server: McpServer, action: string) => {
963 const { signal } = session;
964 let message: string | undefined;
965 switch (action) {
966 case "signin":
967 message = await signInWithUi(ui, server);
968 break;
969 case "reconnect":
970 // Connection state and error already report failures, including required sign-ins.
971 runInBackground(ctx, server, async () => {
972 await reconnect(server);
973 return undefined;
974 });
975 break;
976 case "signout":
977 await signOut(server);
978 break;
979 case "tools":
980 await showTools(ui, server);
981 break;
982 case "exposure":
983 message = await chooseExposure(ui, server);
984 break;
985 case "enable":
986 case "disable":
987 case "enable-project":
988 case "disable-project": {
989 const enable = action.startsWith("enable");
990 runInBackground(ctx, server, () => setEnabled(server, enable, action.endsWith("-project")));
991 break;
992 }
993 }
994 // The session ended meanwhile (for example during a sign-in), which made ctx stale.
995 if (signal.aborted) return;
996 server.message = message;
997 ensureDiscoveryActive(ctx);
998 emitChange();
999 };
1000 const manage = async (ui: McpUi, ctx: ExtensionContext) => {
1001 for (;;) {
1002 const name = await ui.menu(serversMenu, subscribe);
1003 if (!name) return;
1004 for (;;) {
1005 const action = await ui.menu(() => serverMenu(name), subscribe);
1006 const server = findServer(name);
1007 if (!action || !server) break;
1008 await runAction(ui, ctx, server, action);
1009 }
1010 }
1011 };
1012
1013 // ---------------------------------------------------------------------------------------
1014 // Subcommands and plain status (no TUI)
1015 // ---------------------------------------------------------------------------------------
1016
1017 const formatStatus = (): string => {
1018 if (servers.length === 0 && configErrors.length === 0 && overridden.length === 0) {
1019 return `No MCP servers configured. Add them to ${resolve(getAgentDir(), "mcp.json")} or .pi/mcp.json.`;
1020 }
1021 const lines = servers.map((server) => {
1022 const { name } = server.entry;
1023 const exposure = exposureOf(server.entry);
1024 const connection = server.connection;
1025 if (connection?.state === "needs-auth")
1026 return `${name}: needs sign-in, run /mcp login ${name} (${exposure})`;
1027 const tools = connection?.state === "connected" ? `, ${connection.tools.length} tools` : "";
1028 const state = !isEnabled(server)
1029 ? "disabled"
1030 : connection?.state === "disconnected"
1031 ? "disconnected, reconnects on next call"
1032 : (connection?.state ?? "starting");
1033 const error =
1034 connection?.error && connection.state !== "connected"
1035 ? `\n ${connection.error.split("\n").join("\n ")}`
1036 : "";
1037 return `${name}: ${state}${tools} (${exposure})${error}`;
1038 });
1039 for (const error of configErrors) lines.push(`config error: ${error}`);
1040 for (const line of overridden) lines.push(`overridden: ${line}`);
1041 return lines.join("\n");
1042 };
1043
1044 /** Resolve the server for a subcommand, asking when the name is omitted and ambiguous. */
1045 const pickServer = async (
1046 name: string | undefined,
1047 ctx: ExtensionCommandContext,
1048 options: { eligible: (server: McpServer) => boolean; preferred: (server: McpServer) => boolean; none: string },
1049 ): Promise<McpServer | undefined> => {
1050 if (name) {
1051 const server = findServer(name);
1052 if (!server) ctx.ui.notify(`No MCP server named "${name}".`, "error");
1053 else if (!options.eligible(server)) ctx.ui.notify(options.none, "error");
1054 return server && options.eligible(server) ? server : undefined;
1055 }
1056 const candidates = servers.filter(options.eligible);
1057 if (candidates.length === 0) {
1058 ctx.ui.notify(options.none, "info");
1059 return undefined;
1060 }
1061 const preferred = candidates.filter(options.preferred);
1062 if (candidates.length === 1) return candidates[0];
1063 if (preferred.length === 1) return preferred[0];
1064 const choice = await ctx.ui.select(
1065 "MCP server",
1066 candidates.map((server) => server.entry.name),
1067 );
1068 return candidates.find((server) => server.entry.name === choice);
1069 };
1070
1071 const usesOAuth = (server: McpServer) => server.connection?.oauthUrl !== undefined;
1072 const oauthPick = {
1073 eligible: usesOAuth,
1074 preferred: (server: McpServer) => server.connection?.state === "needs-auth",
1075 none: "No enabled MCP server uses OAuth. Only HTTP servers without an Authorization header do.",
1076 };
1077
1078 const loginCommand = async (server: McpServer, ctx: ExtensionCommandContext) => {
1079 const { name } = server.entry;
1080 if (!ctx.hasUI) {
1081 ctx.ui.notify(`Signing in to MCP server "${name}" requires interactive mode.`, "error");
1082 return;
1083 }
1084 const { signal } = session;
1085 let failure: string | undefined;
1086 if (ctx.mode === "tui") {
1087 await showMcpManager(ctx, async (ui) => {
1088 failure = await signInWithUi(ui, server);
1089 });
1090 } else {
1091 failure = await signIn(server, {
1092 showAuthorizationUrl: (url) => {
1093 ctx.ui.notify(`Sign in to MCP server "${name}" in your browser:\n${url.href}`, "info");
1094 openUrl(url.href);
1095 },
1096 promptForRedirectUrl: (signal) =>
1097 ctx.ui.input(
1098 `Waiting for sign-in to "${name}". If the browser cannot reach this machine, paste the URL it was redirected to.`,
1099 "http://127.0.0.1:.../callback?code=...",
1100 { signal },
1101 ),
1102 });
1103 }
1104 // The session ended meanwhile, which cancelled the sign-in and made ctx stale.
1105 if (signal.aborted) return;
1106 if (failure) {
1107 ctx.ui.notify(failure, failure === "Sign-in cancelled." ? "info" : "error");
1108 return;
1109 }
1110 ensureDiscoveryActive(ctx);
1111 ctx.ui.notify(`Signed in to MCP server "${name}" (${server.connection?.tools.length ?? 0} tools).`, "info");
1112 };
1113
1114 pi.on("session_start", (_event, ctx) => {
1115 const loaded = (options.loadConfig ?? defaultLoadConfig)(ctx);
1116 configErrors = loaded.errors;
1117 projectConfig = loaded.projectConfig;
1118 autoEnableCodemode = loaded.autoEnableCodemode ?? true;
1119 warnedUnreachable = false;
1120 waitedForStartup = false;
1121 sessionCwd = ctx.cwd;
1122 modelRegistry = ctx.modelRegistry;
1123 session = new AbortController();
1124 const { signal } = session;
1125 configuredEntries = loaded.servers;
1126 const registered = registeredServers();
1127 overridden = registered.overridden;
1128 servers = [...loaded.servers.map((entry) => ({ entry })), ...registered.servers];
1129 emitChange();
1130 // Codemode or tool_search is activated from the config: the first prompt does not wait for
1131 // servers whose tools are not declared to the model, and scripts or searches wait for them.
1132 ensureDiscoveryActive(ctx);
1133 const enabled = servers.filter(isEnabled);
1134 if (enabled.length === 0) {
1135 reportProblems(ctx);
1136 return;
1137 }
1138 // The MCP client loads only now, so sessions without servers never pay for it. Waiting one
1139 // event loop turn lets the first render happen before loading and connecting.
1140 const runtime = new Promise((resolve) => setImmediate(resolve)).then(() => loadMcpRuntime());
1141 pending = Promise.all(enabled.map((server) => startConnection(server, runtime)))
1142 .then(() => {
1143 if (!signal.aborted) reportProblems(ctx);
1144 })
1145 .catch((error: unknown) => {
1146 // The session may have been disposed meanwhile, which makes ctx stale.
1147 try {
1148 ctx.ui.notify(`MCP failed to load: ${errorMessage(error)}`, "error");
1149 } catch {}
1150 });
1151 });
1152
1153 // The first prompt waits for servers whose tools are declared to the model, so they are declared
1154 // in its first request, but not indefinitely: a slow or hanging server must not hold up the
1155 // prompt. Other servers are waited for when a script or search needs them (below).
1156 const waitForDirectServers = async (ctx: ExtensionContext) => {
1157 if (waitedForStartup) return;
1158 waitedForStartup = true;
1159 const ready = servers.flatMap((server) =>
1160 isEnabled(server) && hasDirectTools(server.entry) && server.ready ? [server.ready] : [],
1161 );
1162 if (ready.length === 0) return;
1163 let timer: NodeJS.Timeout | undefined;
1164 const finished = await Promise.race([
1165 Promise.all(ready).then(() => true),
1166 new Promise<boolean>((resolve) => {
1167 timer = setTimeout(() => resolve(false), startupWaitMs);
1168 }),
1169 ]);
1170 clearTimeout(timer);
1171 if (!finished) {
1172 ctx.ui.notify("MCP servers are still connecting; their tools become available once connected.", "info");
1173 }
1174 };
1175
1176 // Every prompt lists the servers in the `mcp_servers` section as they are when it starts. Pi
1177 // appends the section to the conversation when it changed, for example after a server connected.
1178 pi.on("before_agent_start", async (event, ctx) => {
1179 await waitForDirectServers(ctx);
1180 const { sections } = event.systemPromptOptions;
1181 const section = renderServersSection(servers);
1182 if (section) sections[MCP_SERVERS_SECTION] = section;
1183 else delete sections[MCP_SERVERS_SECTION];
1184 });
1185
1186 // A tool that reaches other tools (`reachesTools`) waits for the servers it may reach, so their
1187 // tools are registered before it runs: a codemode script for the servers it names, or for every
1188 // server when it searches or enumerates tools, and tool_search for every server. The resource
1189 // tools reach every server, so they wait for all of them. Direct MCP calls wait only for their
1190 // own server, including a reconnect still closing its old transport.
1191 pi.on("tool_call", async (event, ctx) => {
1192 const tool = pi.getAllTools().find((candidate) => candidate.name === event.toolName);
1193 if (!tool) return;
1194 // Readiness can be pending while the display state is still connected: reconnect first
1195 // closes the old transport, then opens a new one. Settled promises return immediately.
1196 const readyServers = servers.filter((server) => isEnabled(server) && server.ready);
1197 if (readyServers.length === 0) return;
1198 let waiting: McpServer[] = [];
1199 const reach = tool.reachesTools?.(event.input);
1200 if (reach !== undefined) {
1201 waiting = readyServers.filter((server) => reachesServer(reach, server.entry.name));
1202 } else if (RESOURCE_TOOL_NAMES.has(tool.name)) {
1203 waiting = readyServers;
1204 } else {
1205 const owner = toolOwners.get(event.toolName)?.split("\0", 1)[0];
1206 waiting = readyServers.filter((server) => server.entry.name === owner);
1207 }
1208 await waitForServers(waiting, ctx.signal);
1209 });
1210
1211 // Pick up sign-ins done outside the session, such as `pi mcp login` run by the agent.
1212 pi.on("turn_start", async (_event, ctx) => {
1213 if (tokensAtSignIn.size > 0) await reconnectSignedIn(ctx);
1214 });
1215
1216 // Servers registered or unregistered during the session connect or disconnect right away.
1217 pi.on("mcp_servers_change", async (_event, ctx) => {
1218 const { signal } = session;
1219 if (signal.aborted) return;
1220 const registered = registeredServers();
1221 overridden = registered.overridden;
1222 const next = new Map(registered.servers.map((server) => [server.entry.name, server]));
1223 // Unregistered servers and re-registered ones with a new config are dropped; the latter come back below.
1224 const removed = servers.filter(
1225 (server) =>
1226 server.entry.scope === "extension" &&
1227 next.get(server.entry.name)?.registeredConfig !== server.registeredConfig,
1228 );
1229 servers = servers.filter((server) => !removed.includes(server));
1230 for (const server of removed) hideTools(server.entry.name);
1231 const added = registered.servers.filter((server) => !findServer(server.entry.name));
1232 servers.push(...added);
1233 emitChange();
1234 ensureDiscoveryActive(ctx);
1235 await Promise.all(removed.map((server) => server.connection?.close()));
1236 const connecting = added.filter(isEnabled);
1237 if (signal.aborted || connecting.length === 0) return;
1238 try {
1239 await Promise.all(connecting.map((server) => startConnection(server)));
1240 if (signal.aborted) {
1241 await Promise.all(connecting.map((server) => server.connection?.close()));
1242 return;
1243 }
1244 } catch (error) {
1245 ctx.ui.notify(`MCP failed to load: ${errorMessage(error)}`, "error");
1246 return;
1247 }
1248 if (signal.aborted) return;
1249 reportProblems(ctx, connecting);
1250 });
1251
1252 pi.on("session_shutdown", async () => {
1253 session.abort();
1254 const closing = connections();
1255 servers = [];
1256 emitChange();
1257 await Promise.all([...backgroundActions, ...closing.map((connection) => connection.close())]);
1258 });
1259
1260 pi.registerCommand("mcp", {
1261 description: "Manage MCP servers: sign in, reconnect, enable or disable, and change exposure",
1262 getArgumentCompletions: (prefix) => {
1263 const [action, server, ...rest] = prefix.trimStart().split(/\s+/);
1264 if (rest.length > 0) return null;
1265 if (server === undefined) {
1266 return ["login", "logout", "reconnect"]
1267 .filter((item) => item.startsWith(action ?? ""))
1268 .map((item) => ({ value: `${item} `, label: item }));
1269 }
1270 if (action !== "login" && action !== "logout" && action !== "reconnect") return null;
1271 const items = servers
1272 .filter((candidate) =>
1273 action === "reconnect" ? candidate.connection !== undefined : usesOAuth(candidate),
1274 )
1275 .filter((candidate) => candidate.entry.name.startsWith(server))
1276 .map((candidate) => ({
1277 value: `${action} ${candidate.entry.name}`,
1278 label: candidate.entry.name,
1279 description: describeState(candidate),
1280 }));
1281 return items.length > 0 ? items : null;
1282 },
1283 handler: async (args, ctx) => {
1284 const [action, name, ...extra] = args.trim().split(/\s+/).filter(Boolean);
1285 if (action === undefined) {
1286 if (ctx.mode === "tui") await showMcpManager(ctx, (ui) => manage(ui, ctx));
1287 else {
1288 await pending;
1289 ctx.ui.notify(formatStatus(), "info");
1290 }
1291 return;
1292 }
1293 if (extra.length > 0) {
1294 ctx.ui.notify(MCP_USAGE, "warning");
1295 return;
1296 }
1297 await pending;
1298 switch (action) {
1299 case "login": {
1300 const server = await pickServer(name, ctx, oauthPick);
1301 if (server) await loginCommand(server, ctx);
1302 return;
1303 }
1304 case "logout": {
1305 const server = await pickServer(name, ctx, oauthPick);
1306 if (!server) return;
1307 const removed = await signOut(server);
1308 ctx.ui.notify(
1309 removed
1310 ? `Signed out of MCP server "${server.entry.name}".`
1311 : `No stored credentials for MCP server "${server.entry.name}".`,
1312 "info",
1313 );
1314 return;
1315 }
1316 case "reconnect": {
1317 const server = await pickServer(name, ctx, {
1318 eligible: (candidate) => candidate.connection !== undefined,
1319 preferred: (candidate) =>
1320 candidate.connection?.state === "failed" || candidate.connection?.state === "disconnected",
1321 none: "No enabled MCP server to reconnect.",
1322 });
1323 if (!server) return;
1324 const failure = await reconnect(server);
1325 if (failure) ctx.ui.notify(failure, "error");
1326 else {
1327 ensureDiscoveryActive(ctx);
1328 ctx.ui.notify(
1329 `Reconnected to MCP server "${server.entry.name}" (${describeState(server)}).`,
1330 "info",
1331 );
1332 }
1333 return;
1334 }
1335 default:
1336 ctx.ui.notify(MCP_USAGE, "warning");
1337 }
1338 },
1339 });
1340 };
1341}
1342
1343function defaultLoadConfig(ctx: ExtensionContext): LoadedMcpConfig {
1344 return loadMcpConfig({ agentDir: getAgentDir(), cwd: ctx.cwd, projectTrusted: ctx.isProjectTrusted() });
1345}
1346
1347export default createMcpExtension();