fix: start a session without an MCP-over-ACP server whose local endpoint cannot open (#1653)

## Summary

An MCP server that the client declares with `"type": "acp"` can no
longer fail session setup. The session starts without the server and the
user gets the usual "failed to start" warning.

This comes out of #1651. It does not make the server of that issue
connect (see "Not fixed here").

## What was failing

The adapter serves an `acp` server to Claude Code through a listener on
`127.0.0.1` (`McpOverAcp`, #1645). When that listener could not open,
for example `listen EPERM` where the process may not open a socket,
`session/new` failed with `-32603`:

> Could not open the local endpoint that serves MCP server tools to
Claude Code: listen EPERM: operation not permitted 127.0.0.1. Start the
session without the server, or try again.

A session starts without any other MCP server that does not connect (a
stdio command that is missing, an HTTP server that is down). The `acp`
case was the only one that ended setup.

## What changes

- **`sdkMcpServers`** (`src/mcp-servers.ts`) returns `{ configs,
unserved }`. An `acp` server that gets no endpoint is in `unserved` with
the error, and the other servers keep their configs.
- **Both cores report it** through the existing notice of a client
server that did not start (`mcpServerStartupNotice`), once per server,
on the first turn. On v1 that is `reportMcpServerStartupFailures`, on v2
`SessionReports.mcpStartupFailures`. A resume of the active session on
v2 (`setMcpServers`) reports it the same way.
- **The notice has the error.** Claude Code was never given the server,
so `/mcp` does not list it and "Run /mcp for the error" would lead
nowhere:

> **MCP server "tools" failed to start:** Its tools are unavailable in
this session. The adapter could not open the local endpoint that serves
it to Claude Code (listen EPERM: operation not permitted 127.0.0.1). A
new session tries again.

- The adapter also logs the server and the error at setup.

A later session, or a restart of the session's query, tries to open the
listener again.

## Not fixed here

In #1651 the server is listed as failed because Claude Code sends
`initialize` first and the endpoint accepts MCP 2026-07-28 requests
only. That is unchanged.

Setup did not fail in that case before this PR either. Checked through
the built adapter with Claude Code 2.1.326, without a model turn:

| Case | `session/new` | The server |
| --- | --- | --- |
| Claude Code as it starts by default | succeeds | connects
(`server/discover`, then `tools/list`) |
| `MCP_PROTOCOL_NEGOTIATION=legacy` (Claude Code sends `initialize`) |
succeeds | failed, with the warning |
| The client rejects `server/discover` | succeeds | failed, with the
warning |
| The client never answers `mcp/message` | succeeds | not connected |
| The listener cannot open, before this PR | fails with `-32603` | |
| The listener cannot open, with this PR | succeeds | left out, with the
warning above |

For the last two rows the adapter ran with a preload that makes
`http.Server.prototype.listen` fail.

## Testing

- `npm run check`, `npm run build`, `npm run test:run` (4,314 tests
pass)
- New tests: `sdkMcpServers` with an endpoint that rejects,
`session/new` on v1, the notice on v1, and on v2 both `session/new` and
a resume of the active session
- The live cases in the table above

Refs #1651
This commit is contained in:
Ben Brandt
2026-11-18 14:08:22 +01:00
committed by GitHub
parent 3205f0bf02
commit 96dd2bb10d
10 changed files with 266 additions and 69 deletions

View File

@@ -1,6 +1,5 @@
import {
McpOverAcpCaller,
RequestError,
type HasConnectionContext,
type McpServer,
type McpServerAcp,
@@ -15,16 +14,33 @@ import type { McpHttpServerConfig, McpServerConfig } from "@anthropic-ai/claude-
export type McpOverAcpConfig = (server: McpServerAcp) => Promise<McpHttpServerConfig>;
/**
* The SDK configs of a session's ACP MCP servers, by name. HTTP and SSE
* servers keep their URL and headers; a server without `type` is stdio; an
* `acp` server gets the config that `overAcp` makes. A server of any other
* transport is left out: the session's `initialize` advertises none.
* A client MCP server that Claude Code is not given, so it lists no entry for
* it. This is the entry it would list: `failed`, with the error.
*/
export type UnservedMcpServer = { name: string; status: "failed"; error: string };
/** A session's ACP MCP servers, as {@link sdkMcpServers} sorts them. */
export type SdkMcpServers = {
/** The SDK configs of the servers that Claude Code gets, by name. */
configs: Record<string, McpServerConfig>;
/** The `acp` servers that `overAcp` made no config for. */
unserved: UnservedMcpServer[];
};
/**
* The SDK configs of a session's ACP MCP servers. HTTP and SSE servers keep
* their URL and headers; a server without `type` is stdio; an `acp` server
* gets the config that `overAcp` makes. When `overAcp` rejects, the server is
* in `unserved` with the error and the session starts without it, as it
* starts without a server that Claude Code cannot connect to. A server of any
* other transport is left out: the session's `initialize` advertises none.
*/
export async function sdkMcpServers(
servers: readonly McpServer[] | null | undefined,
overAcp: McpOverAcpConfig,
): Promise<Record<string, McpServerConfig>> {
): Promise<SdkMcpServers> {
const configs: Record<string, McpServerConfig> = {};
const unserved: UnservedMcpServer[] = [];
for (const server of servers ?? []) {
if ("type" in server && (server.type === "http" || server.type === "sse")) {
configs[server.name] = {
@@ -35,7 +51,15 @@ export async function sdkMcpServers(
: undefined,
};
} else if ("type" in server && server.type === "acp") {
configs[server.name] = await overAcp(server);
try {
configs[server.name] = await overAcp(server);
} catch (error) {
unserved.push({
name: server.name,
status: "failed",
error: error instanceof Error ? error.message : String(error),
});
}
} else if (!("type" in server)) {
configs[server.name] = {
type: "stdio",
@@ -45,7 +69,7 @@ export async function sdkMcpServers(
};
}
}
return configs;
return { configs, unserved };
}
/**
@@ -78,8 +102,9 @@ export class McpOverAcp {
* The SDK config of `server` for the sessions of the connection behind
* `client`. A server gets the same config every time for as long as the
* connection lives, so a session that restarts or resumes with the same
* servers sees no change. Fails with an internal error (-32603) when the
* listener cannot open, or the connection is closed.
* servers sees no change. Rejects when the listener cannot open (e.g.
* `listen EPERM` where the process may not open a socket), or the
* connection is closed. The next call tries to open the listener again.
*/
async sdkConfig(
client: HasConnectionContext,
@@ -89,11 +114,11 @@ export class McpOverAcp {
try {
http = await this.bridge.toHttp(client, { ...server, type: "acp" });
} catch (error) {
throw RequestError.internalError(
{ name: server.name },
`Could not open the local endpoint that serves MCP server ${server.name} to Claude Code: ${
throw new Error(
`The adapter could not open the local endpoint that serves it to Claude Code (${
error instanceof Error ? error.message : String(error)
}. Start the session without the server, or try again.`,
}). A new session tries again.`,
{ cause: error },
);
}
return {

View File

@@ -132,18 +132,23 @@ export function informationalNotice(message: { level: string; content: string })
};
}
/** The notice of a client MCP server that the `system/init` lists as not
* started: `failed`, or `needs-auth` when the client cannot run the OAuth
* flow (`oauthAvailable`). Undefined for any other status. */
/** The notice of a client MCP server that did not start: `failed`, or
* `needs-auth` when the client cannot run the OAuth flow (`oauthAvailable`).
* Undefined for any other status. A server of the `system/init` list has no
* `error`: `/mcp` shows it. An `UnservedMcpServer` is on no list of Claude
* Code, so the notice has its `error`. */
export function mcpServerStartupNotice(
server: { name: string; status: string },
server: { name: string; status: string; error?: string },
oauthAvailable: boolean,
): SessionNotice | undefined {
if (server.status === "failed") {
return {
severity: "warning",
title: `MCP server "${server.name}" failed to start`,
description: "Its tools are unavailable in this session. Run /mcp for the error.",
description:
server.error === undefined
? "Its tools are unavailable in this session. Run /mcp for the error."
: `Its tools are unavailable in this session. ${server.error}`,
};
}
if (server.status === "needs-auth" && !oauthAvailable) {

View File

@@ -26,17 +26,36 @@ describe("sdkMcpServers", () => {
});
expect(configs).toEqual({
files: { type: "stdio", command: "/bin/files", args: ["--stdio"], env: { A: "1" } },
linear: {
type: "http",
url: "https://mcp.linear.app/mcp",
headers: { Authorization: "Bearer token" },
configs: {
files: { type: "stdio", command: "/bin/files", args: ["--stdio"], env: { A: "1" } },
linear: {
type: "http",
url: "https://mcp.linear.app/mcp",
headers: { Authorization: "Bearer token" },
},
events: { type: "sse", url: "https://example.com/sse", headers: {} },
tools: overAcp,
},
events: { type: "sse", url: "https://example.com/sse", headers: {} },
tools: overAcp,
unserved: [],
});
expect(acpServers).toEqual([{ type: "acp", name: "tools", serverId: "tools:1" }]);
});
it("leaves out an acp server that gets no config, and keeps the others", async () => {
const servers = [
{ type: "acp", name: "tools", serverId: "tools:1" },
{ name: "files", command: "/bin/files", args: [], env: [] },
] as acp.McpServer[];
const served = await sdkMcpServers(servers, async () => {
throw new Error("listen EPERM");
});
expect(served).toEqual({
configs: { files: { type: "stdio", command: "/bin/files", args: [], env: {} } },
unserved: [{ name: "tools", status: "failed", error: "listen EPERM" }],
});
});
});
describe("McpOverAcp", () => {
@@ -117,10 +136,10 @@ describe("McpOverAcp", () => {
agent.close();
await agent.closed;
await expect(claudeCodeMcpRequest(config, "tools/list")).rejects.toThrow();
await expect(mcp.sdkConfig(agent.client, tools)).rejects.toMatchObject({
code: -32603,
message: expect.stringContaining("MCP server tools"),
});
await expect(mcp.sdkConfig(agent.client, tools)).rejects.toThrow(
"The adapter could not open the local endpoint that serves it to Claude Code " +
"(ACP connection is closed). A new session tries again.",
);
});
it.each([

View File

@@ -46,6 +46,7 @@ import {
stripLocalCommandMetadata,
} from "../../message-filters.js";
import type { AcpClient } from "../../acp-client.js";
import type { UnservedMcpServer } from "../../mcp-servers.js";
import type { SDKMessageFilter } from "../../new-session-meta.js";
import { SessionTitles } from "../../session-titles.js";
import { SessionBackgroundWork } from "../../v1/background-work.js";
@@ -14130,7 +14131,10 @@ describe("model refusal fallback handling", () => {
});
describe("MCP server startup failures", () => {
function setup(mcpServersStatus: { name: string; status: string; source?: string }[]) {
function setup(
mcpServersStatus: { name: string; status: string; source?: string }[],
unservedMcpServers?: UnservedMcpServer[],
) {
const sessionUpdate = vi.fn(async () => {});
const agent = new ClaudeAcpAgent({ sessionUpdate } as unknown as AcpClient, {
log: () => {},
@@ -14188,6 +14192,7 @@ describe("MCP server startup failures", () => {
{ name: "client-api", type: "http", url: "https://example.com/mcp", headers: [] },
],
},
unservedMcpServers,
});
const updates = () =>
sessionUpdate.mock.calls.map((c: any[]) => (c[0] as { update: any }).update);
@@ -14217,6 +14222,29 @@ describe("MCP server startup failures", () => {
]);
});
it("sends one notice, with the error, for a server the query started without", async () => {
// Claude Code was not given the server, so its init does not list it.
const { agent, updates } = setup(
[{ name: "client-api", status: "connected", source: "dynamic" }],
[{ name: "client-acp", status: "failed", error: "listen EPERM" }],
);
await agent.initialize({
protocolVersion: 1,
clientCapabilities: { session: { notices: {} } },
});
await agent.prompt({ sessionId: "test-session", prompt: [{ type: "text", text: "hi" }] });
expect(updates().filter((u) => u.sessionUpdate === "notice")).toEqual([
{
sessionUpdate: "notice",
severity: "warning",
title: 'MCP server "client-acp" failed to start',
description: "Its tools are unavailable in this session. listen EPERM",
},
]);
});
it("reports a needs-auth server only when the client can't run OAuth", async () => {
const withoutUrlElicitation = setup([{ name: "client-api", status: "needs-auth" }]);
await withoutUrlElicitation.agent.initialize({

View File

@@ -1271,6 +1271,32 @@ describe("createSession options merging", () => {
expect(capturedOptions!.mcpServers).toHaveProperty("acp-server");
});
it("starts the session without an acp server that gets no endpoint", async () => {
agent = new ClaudeAcpAgent(
{
...createMockClient(),
mcpServerOverAcp: async () => {
throw new Error("listen EPERM");
},
},
{ log: () => {}, error: () => {} },
);
const { sessionId } = await agent.newSession({
cwd: process.cwd(),
mcpServers: [
{ type: "acp", name: "tools", serverId: "tools:1" },
{ name: "files", command: "node", args: ["files.js"], env: [] },
],
});
expect(Object.keys(capturedOptions!.mcpServers ?? {})).toEqual(["files"]);
// What the first turn reports (see "MCP server startup failures").
expect(agent.sessions[sessionId].unservedMcpServers).toEqual([
{ name: "tools", status: "failed", error: "listen EPERM" },
]);
});
describe("thinking config from MAX_THINKING_TOKENS", () => {
let originalMaxThinking: string | undefined;

View File

@@ -12,7 +12,7 @@ import { randomUUID } from "node:crypto";
import { mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
import * as os from "node:os";
import * as path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
import * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
import {
forkSession,
@@ -22,6 +22,7 @@ import {
type Settings,
type SDKUserMessage,
} from "@anthropic-ai/claude-agent-sdk";
import { McpOverAcp } from "../../mcp-servers.js";
import { acpProtocolRouter } from "../../serve.js";
import { SettingsManager } from "../../settings.js";
import type { AgentHandle } from "../../v2/agent.js";
@@ -1339,6 +1340,57 @@ describe("ACP v2 core", () => {
]);
});
it.each([{ request: "session/new" }, { request: "a resume of the active session" }] as const)(
"goes on without an acp MCP server that gets no endpoint at $request, and reports it",
async ({ request }) => {
const endpoint = vi
.spyOn(McpOverAcp.prototype, "sdkConfig")
.mockRejectedValue(new Error("listen EPERM"));
onTestFinished(() => endpoint.mockRestore());
const mcpServers: v2.McpServer[] = [
{ type: "acp", name: "tools", serverId: "tools:1" },
{ type: "stdio", name: "files", command: "/usr/local/bin/mcp-files" },
];
const client = v2Client();
await client.connect(async (agent) => {
await agent.request(v2.methods.agent.initialize, {
protocolVersion: v2.PROTOCOL_VERSION,
info: { name: "v2-test-client", version: "1.0.0" },
capabilities: {},
});
if (request === "session/new") {
await agent.request(v2.methods.agent.session.new, { cwd, mcpServers });
} else {
const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd });
await agent.request(v2.methods.agent.session.resume, { sessionId, cwd, mcpServers });
}
const claude = sdk.processes.at(-1)!;
if (request === "session/new") {
expect(Object.keys(claude.options.mcpServers ?? {})).toEqual(["files"]);
}
// Claude Code lists the servers it was given.
claude.send({
type: "system",
subtype: "init",
uuid: randomUUID(),
mcp_servers: [{ name: "files", status: "connected" }],
});
claude.send(result());
// The resume sent the session's idle state first.
await vi.waitFor(() => expect(client.states().slice(-2)).toEqual(["running", "idle"]));
});
expect(client.sessionUpdates.filter((update) => update.sessionUpdate === "notice")).toEqual([
{
sessionUpdate: "notice",
severity: "warning",
title: 'MCP server "tools" failed to start',
description: "Its tools are unavailable in this session. listen EPERM",
},
]);
},
);
it("replaces Claude Code's text of /mcp with the server list, before the turn's idle", async () => {
const client = v2Client();
sdk.mcpServers = [{ name: "linear", status: "connected" }];

View File

@@ -186,7 +186,7 @@ import {
} from "../auth-status.js";
import { AuthStatusReporter, cliLogout } from "../auth-status-reporter.js";
import { terminalAuthMethods as authMethodsForTerminal } from "../auth-methods.js";
import { McpOverAcp, sdkMcpServers } from "../mcp-servers.js";
import { McpOverAcp, sdkMcpServers, type UnservedMcpServer } from "../mcp-servers.js";
import { claudeCliPath, mcpServersDelivery } from "../claude-cli.js";
import { ContentBlockParam } from "@anthropic-ai/sdk/resources";
import { randomUUID } from "node:crypto";
@@ -991,6 +991,10 @@ export type Session = {
* needing authentication. `system`/init re-emits on every turn with the
* same statuses, and each server is reported once per session. */
reportedMcpServers?: Set<string>;
/** The client's `acp` MCP servers that the session's query started without
* (see `sdkMcpServers`). They are reported like a server that `system`/init
* lists as `failed`. */
unservedMcpServers?: UnservedMcpServer[];
/** The long-lived consumer task. Lazily started on the first `prompt()` and
* kept alive for the session so between-turn/background messages are still
* drained and forwarded. */
@@ -2739,12 +2743,13 @@ export class ClaudeAcpAgent {
}
/** Tells the user about client-provided MCP servers that `system`/init
* reports as `failed` or `needs-auth`, once per server per session. Servers
* from the user's Claude Code settings are left to `/mcp`: they are the same
* in every session, so a broken one would be reported in every session. A
* `needs-auth` server is reported only when the OAuth flow can't run (no
* URL elicitation on the client, or no `mcpAuthenticate` on the query);
* otherwise `startMcpAuthentication` asks the user to sign in. */
* reports as `failed` or `needs-auth`, and about the ones the query started
* without (`session.unservedMcpServers`), once per server per session.
* Servers from the user's Claude Code settings are left to `/mcp`: they are
* the same in every session, so a broken one would be reported in every
* session. A `needs-auth` server is reported only when the OAuth flow can't
* run (no URL elicitation on the client, or no `mcpAuthenticate` on the
* query); otherwise `startMcpAuthentication` asks the user to sign in. */
private async reportMcpServerStartupFailures(
session: Session,
servers: SDKSystemMessage["mcp_servers"] | undefined,
@@ -2752,16 +2757,18 @@ export class ClaudeAcpAgent {
sendUpdate: (notification: AcpSessionNotification) => Promise<void>,
sessionId: string,
): Promise<void> {
if (!servers?.length) return;
const clientServers = new Set(
(session.creationParams?.mcpServers ?? []).map((server) => server.name),
);
const notStarted = [
...(session.unservedMcpServers ?? []),
...(servers ?? []).filter((server) => clientServers.has(server.name)),
];
if (!notStarted.length) return;
const oauthAvailable =
!!this.clientCapabilities?.elicitation?.url && supportsMcpOAuth(session.query);
for (const server of servers) {
if (!clientServers.has(server.name) || session.reportedMcpServers?.has(server.name)) {
continue;
}
for (const server of notStarted) {
if (session.reportedMcpServers?.has(server.name)) continue;
const notice = mcpServerStartupNotice(server, oauthAvailable);
if (!notice) continue;
(session.reportedMcpServers ??= new Set()).add(server.name);
@@ -9991,10 +9998,15 @@ export class ClaudeAcpAgent {
timing.phase("resume-transcript");
}
// Before the settings watchers open: a failure here leaves nothing to dispose.
const mcpServers = await sdkMcpServers(params.mcpServers, (server) =>
this.client.mcpServerOverAcp(server),
const { configs: mcpServers, unserved: unservedMcpServers } = await sdkMcpServers(
params.mcpServers,
(server) => this.client.mcpServerOverAcp(server),
);
for (const server of unservedMcpServers) {
this.logger.error(
`Session ${sessionId} starts without MCP server ${server.name}: ${server.error}`,
);
}
const input = new Pushable<SDKUserMessage>();
@@ -10597,6 +10609,7 @@ export class ClaudeAcpAgent {
cwd: params.cwd,
sessionFingerprint: computeSessionFingerprint(params),
creationParams: params,
unservedMcpServers,
settingsManager,
effortSettingsOverride: configuredSettingsObject,
titles: new SessionTitles(this, sessionId),

View File

@@ -508,10 +508,11 @@ class V2Agent implements AgentHandle, SessionConnection {
// session's.
const request = await validatedSetup(params);
assertCwdOf(session, request.cwd, "resume it");
await session.setMcpServers({
...clientOptions(params._meta)?.mcpServers,
...(await this.sdkMcpServers(request.mcpServers)),
});
const served = await this.sdkMcpServers(sessionId, request.mcpServers);
await session.setMcpServers(
{ ...clientOptions(params._meta)?.mcpServers, ...served.configs },
served.unserved,
);
if (!sameDirectories(request.additionalDirectories ?? [], session.additionalDirectories)) {
// The SDK cannot change them on a running query: it restarts with
// them at its next turn boundary (see `restarts.ts`).
@@ -951,6 +952,7 @@ class V2Agent implements AgentHandle, SessionConnection {
configuredSettings: opened.configured,
env: opened.env,
mcpServers: opened.request.mcpServers.map((server) => server.name),
unservedMcpServers: opened.unservedMcpServers,
mcpOAuth: this.elicitation.url && supportsMcpOAuth(q),
query: q,
model: { id: models.models.currentModelId, info: models.allowlistedModelInfo },
@@ -967,10 +969,18 @@ class V2Agent implements AgentHandle, SessionConnection {
/**
* The SDK configs of a setup request's MCP servers. An `acp` server is
* served to Claude Code over this connection (see `mcp-servers.ts`).
* served to Claude Code over this connection (see `mcp-servers.ts`). One
* that gets no endpoint is in `unserved`, and the session goes on without
* it.
*/
private sdkMcpServers(servers: readonly McpServer[]) {
return sdkMcpServers(servers, (server) => this.mcp.sdkConfig(this.ctx, server));
private async sdkMcpServers(sessionId: string, servers: readonly McpServer[]) {
const served = await sdkMcpServers(servers, (server) => this.mcp.sdkConfig(this.ctx, server));
for (const server of served.unserved) {
this.logger.error(
`Session ${sessionId} runs without MCP server ${server.name}: ${server.error}`,
);
}
return served;
}
/**
@@ -993,8 +1003,8 @@ class V2Agent implements AgentHandle, SessionConnection {
) {
const request = await validatedSetup(params);
const client = clientOptions(params._meta);
// Before the settings watchers open: a failure here leaves nothing to dispose.
const mcpServers = { ...client?.mcpServers, ...(await this.sdkMcpServers(request.mcpServers)) };
const served = await this.sdkMcpServers(sessionId, request.mcpServers);
const mcpServers = { ...client?.mcpServers, ...served.configs };
// After a provider change that is still listing its models.
await this.auth.routeSettled();
// The resumed transcript's last model and mode.
@@ -1228,6 +1238,7 @@ class V2Agent implements AgentHandle, SessionConnection {
env: options.env ?? {},
request,
mcpServers,
unservedMcpServers: served.unserved,
routeGeneration,
};
}

View File

@@ -36,6 +36,7 @@ import {
readContextWindow,
} from "../context-window.js";
import { IdleCompaction } from "../idle-compaction.js";
import type { UnservedMcpServer } from "../mcp-servers.js";
import { PromptSuggestions } from "../prompt-suggestions.js";
import {
informationalNotice,
@@ -88,6 +89,8 @@ export interface ReportsSetup {
env: Record<string, string | undefined>;
/** The names of the client's MCP servers. */
mcpServers: readonly string[];
/** The ones of them that the query started without (see `sdkMcpServers`). */
unservedMcpServers: readonly UnservedMcpServer[];
/**
* Whether the session asks the user to sign in to an MCP server that needs
* it (see `SessionElicitations.authenticateMcpServers`): the client renders
@@ -112,6 +115,7 @@ export class SessionReports {
private settings: ReportsSetup["settings"] | undefined;
private configuredSettings: Settings | undefined;
private clientMcpServers = new Set<string>();
private unservedMcpServers: readonly UnservedMcpServer[] = [];
private mcpOAuth = false;
private readonly reportedMcpServers = new Set<string>();
/** The tool uses whose `informational` progress went out as a notice. */
@@ -168,6 +172,7 @@ export class SessionReports {
/** Called once, before the query's first message. */
configure(setup: ReportsSetup): void {
this.clientMcpServers = new Set(setup.mcpServers);
this.unservedMcpServers = setup.unservedMcpServers;
this.mcpOAuth = setup.mcpOAuth;
this.settings = setup.settings;
this.configuredSettings = setup.configuredSettings;
@@ -198,9 +203,13 @@ export class SessionReports {
this.suggestions = previous.suggestions;
}
/** The session's MCP servers changed, as a resume of the active session asks. */
mcpServersChanged(names: readonly string[]): void {
/**
* The session's MCP servers are now the ones of `names`, and `unserved`
* the ones it goes on without, as a resume of the active session asks.
*/
mcpServersChanged(names: readonly string[], unserved: readonly UnservedMcpServer[]): void {
this.clientMcpServers = new Set(names);
this.unservedMcpServers = unserved;
}
// --- Turns ---------------------------------------------------------------
@@ -579,12 +588,18 @@ export class SessionReports {
);
}
/** A notice for each client MCP server that did not start, once per server. */
/**
* A notice for each client MCP server that did not start, once per server:
* the ones that `servers`, the list of `system/init`, has as not started,
* and the ones the query started without.
*/
private mcpStartupFailures(servers: Array<{ name: string; status: string }> | undefined): void {
for (const server of servers ?? []) {
if (!this.clientMcpServers.has(server.name) || this.reportedMcpServers.has(server.name)) {
continue;
}
const notStarted = [
...this.unservedMcpServers,
...(servers ?? []).filter((server) => this.clientMcpServers.has(server.name)),
];
for (const server of notStarted) {
if (this.reportedMcpServers.has(server.name)) continue;
const notice = mcpServerStartupNotice(server, this.mcpOAuth);
if (!notice) continue;
this.reportedMcpServers.add(server.name);

View File

@@ -63,6 +63,7 @@ import { V2Background, stateUpdate as currentStateUpdate } from "./background.js
import type { V2UpdateTranslator } from "./update-translator.js";
import { isLocalCommandOutput } from "../message-filters.js";
import { MODEL_CONFIG_ID } from "../session-model.js";
import type { UnservedMcpServer } from "../mcp-servers.js";
import { modelRefusalFallback, noticeUpdate } from "../session-notices.js";
import { planModeUpdate } from "../exit-plan.js";
import { resetPlanUpdates } from "../plans.js";
@@ -389,14 +390,16 @@ export class V2Session implements RequestTarget {
/**
* Replaces the session's MCP servers, as a resume of the active session
* asks. The same servers stay as they are, connected.
* asks. The same servers stay as they are, connected. `unserved` are the
* request's servers that are not in `servers` (see `sdkMcpServers`).
*/
async setMcpServers(servers: McpServers): Promise<void> {
async setMcpServers(servers: McpServers, unserved: readonly UnservedMcpServer[]): Promise<void> {
const key = JSON.stringify(servers);
if (key === this.mcpServers) return;
await this.query?.setMcpServers(servers);
this.reports.mcpServersChanged(Object.keys(servers));
this.mcpServers = key;
if (key !== this.mcpServers) {
await this.query?.setMcpServers(servers);
this.mcpServers = key;
}
this.reports.mcpServersChanged(Object.keys(servers), unserved);
}
// --- Requests ---------------------------------------------------------