fix: sign in to MCP servers of Claude Code's settings on /mcp reconnect (#1728)

## Problem

[IJAI-4341](https://youtrack.jetbrains.com/issue/IJAI-4341): in an ACP
client (Air's Chat mode), an MCP server from Claude Code's settings or
the project's `.mcp.json` that needs OAuth stays `needs-auth`. `/mcp
reconnect <server>` answers "Couldn't reconnect: Server status:
needs-auth" and offers no sign-in. The only way around it was to sign in
from the Claude Code terminal UI.

## Causes

1. **v1:** after `/mcp reconnect`, OAuth started only for servers in the
session's ACP `mcpServers`.
2. **v2:** a reconnect never started OAuth. The `/mcp` text replacement
also never ran with the real CLI. In SDK mode, Claude Code sends a
`<synthetic>` assistant message before the result. v2 showed that
message, so the replacement, which runs only when no agent text has been
sent yet, was skipped. The v2 test double sent only the result.
3. **Shared:** startup OAuth for ACP servers read the status once, right
after `session/new`. On a warm start every server is still `pending`, so
none was signed in. An OAuth request that arrived while a run was in
progress was dropped without notice.

## Changes

- **`src/v1/acp-agent.ts`, `src/v2/session.ts`:** a reconnect starts
OAuth for each server it tried. The OAuth run skips those that aren't
`needs-auth`. A cancelled turn starts none.
- **`src/v2/session.ts`:** during an adapter `/mcp` turn, v2 drops the
`<synthetic>` copy, so the result's text is replaced as on v1.
- **`src/mcp-oauth.ts`:** a server that reads `pending` is checked again
once a second, up to the existing 10-minute limit. Servers requested
while a run is in progress join that run.
- **Docs:** `scratch/` is gitignored and described in `AGENTS.md` as the
place for one-off reproductions.

At session start, servers from settings or `.mcp.json` still don't
prompt for sign-in, as before (see `reportMcpServerStartupFailures`).
The user signs in with `/mcp reconnect <server>`.

## Testing

- **Unit tests:**
- The v1 double now refuses to reconnect a `needs-auth` server, as the
real CLI does.
- The v2 `/mcp` test now uses the real message sequence: `<synthetic>`
assistant message, then the result.
- New tests cover: a reconnect of a server that isn't from ACP (v1 and
v2), a cancelled v2 reconnect, a `pending` server at startup, and a
reconnect during an open sign-in.
- **Real CLI:** an OAuth-protected test MCP server and a raw ACP client
that advertises URL elicitation. Tested on v1 and v2, with the server in
`.mcp.json` and in `session/new`. Before the fix, the `.mcp.json` case
reproduces the issue. After it, the server signs in via `/mcp reconnect`
and connects. A warm start now signs in to ACP servers.
- `npm run check`, `npm run build`, `npm run test:run`.

## Known gap

If a Claude Code build sends `/mcp` output as `local_command_output`, v2
still shows Claude Code's text. v1 handles that shape and the bundled
CLI doesn't send it.
This commit is contained in:
Andrey Bragin
2026-11-30 23:33:22 +01:00
committed by GitHub
parent 1762ccff2e
commit bc752f88e1
9 changed files with 279 additions and 113 deletions

1
.gitignore vendored
View File

@@ -5,3 +5,4 @@ dist
CLAUDE.local.md
.idea/
dist-bin
/scratch/

View File

@@ -101,6 +101,10 @@ opening a PR.
including fields like `origin` it echoes back and fields it omits. A double
simpler than the real message hides bugs. If unsure, check against the real
CLI (`npm run test:integration`).
- For a one-off reproduction against the real CLI (a throwaway MCP server, a
raw ACP client driving `dist/index.js`), use `scratch/` at the repo root. Git
ignores it, so nothing there is committed; turn what it proves into a test in
`src/tests/`.
- Cover both ACP v1 and v2 when a change affects what a client receives
(updates, responses, replay). A change to internal logic only does not need
its tests duplicated per version.

View File

@@ -1,7 +1,8 @@
/**
* OAuth for the MCP servers that Claude Code reports as `needs-auth`, as an
* ACP URL elicitation. Protocol-neutral: the v1 core and the v2 core
* both start it once a session's setup response is sent.
* ACP URL elicitation. Protocol-neutral: the v1 core and the v2 core start it
* for the session's ACP servers once a session's setup response is sent, and
* for the servers that a `/mcp reconnect` tried once its output is sent.
*/
import { randomUUID } from "node:crypto";
import type {
@@ -62,11 +63,13 @@ export type McpOAuthSession = {
readonly closed: AbortSignal;
};
const mcpAuthentications = new WeakMap<object, Promise<void>>();
/** The servers that the session's OAuth run has yet to check, by session key. */
const mcpAuthentications = new WeakMap<object, Set<string>>();
/** Start OAuth in the background for the servers in `requestedServers` that
* Claude reports as needing authentication. It does nothing while another
* OAuth run of the session is in progress. */
* Claude reports as needing authentication. While an OAuth run of the
* session is in progress, the servers join it: it checks them after the
* sign-in that it waits for now. */
export function startMcpServerAuthentication(
client: McpOAuthClient,
session: McpOAuthSession,
@@ -74,43 +77,72 @@ export function startMcpServerAuthentication(
): void {
if (!client.urlElicitation || requestedServers.size === 0) return;
const query = session.currentQuery();
if (!query || mcpAuthentications.has(session.key)) return;
if (!query) return;
const running = mcpAuthentications.get(session.key);
if (running) {
for (const name of requestedServers) running.add(name);
return;
}
const authentication = authenticateMcpServers(client, session, query, requestedServers)
.catch((error) => {
if (!session.closed.aborted) {
client.logger.error(`Failed to inspect MCP servers for OAuth: ${error}`);
}
})
.finally(() => {
if (mcpAuthentications.get(session.key) === authentication) {
mcpAuthentications.delete(session.key);
}
});
mcpAuthentications.set(session.key, authentication);
const wanted = new Set(requestedServers);
mcpAuthentications.set(session.key, wanted);
authenticateMcpServers(client, session, query, wanted).catch((error) => {
if (!session.closed.aborted) {
client.logger.error(`Failed to inspect MCP servers for OAuth: ${error}`);
}
});
}
/** Signs in to the servers of `wanted` that need it, until `wanted` is empty.
* A server that reads `pending` stays in `wanted`: Claude Code connects the
* servers in the background, so right after a warm `session/new` a server
* that needs OAuth still reads `pending`. The run stops waiting for it
* {@link MCP_OAUTH_TIMEOUT_MS} after the run started, or when the session
* closes or its query is replaced. The run leaves `mcpAuthentications` in the same synchronous step
* that finds `wanted` empty, so a server added later starts a new run. */
async function authenticateMcpServers(
client: McpOAuthClient,
session: McpOAuthSession,
query: Query,
requestedServers: Set<string>,
wanted: Set<string>,
): Promise<void> {
if (!supportsMcpOAuth(query)) {
client.logger.error("The Claude Agent SDK does not expose MCP OAuth authentication.");
return;
}
const statuses = await query.mcpServerStatus();
for (const status of statuses) {
if (status.status !== "needs-auth" || !requestedServers.has(status.name)) continue;
try {
await authenticateMcpServer(client, session, query, status.name);
} catch (error) {
if (session.currentQuery() && !session.closed.aborted) {
client.logger.error(`Failed to authenticate MCP server ${status.name}: ${error}`);
}
try {
if (!supportsMcpOAuth(query)) {
client.logger.error("The Claude Agent SDK does not expose MCP OAuth authentication.");
return;
}
const deadline = Date.now() + MCP_OAUTH_TIMEOUT_MS;
while (wanted.size > 0) {
if (session.currentQuery() !== query) return;
// A server that joins during the read is checked by the next one.
const checked = [...wanted];
const statuses = new Map(
(await query.mcpServerStatus()).map((status) => [status.name, status.status]),
);
const settled = checked.filter((name) => statuses.get(name) !== "pending");
for (const name of settled) wanted.delete(name);
for (const name of settled) {
if (statuses.get(name) !== "needs-auth") continue;
if (session.currentQuery() !== query) return;
try {
await authenticateMcpServer(client, session, query, name);
} catch (error) {
if (session.currentQuery() && !session.closed.aborted) {
client.logger.error(`Failed to authenticate MCP server ${name}: ${error}`);
}
}
}
// Wait only when every server left read `pending`; read again at once
// for one that joined meanwhile.
const onlyPending = [...wanted].every(
(name) => checked.includes(name) && !settled.includes(name),
);
if (wanted.size === 0 || !onlyPending) continue;
if (Date.now() >= deadline) return;
if (!(await waitUnlessAborted(MCP_OAUTH_STATUS_POLL_MS, session.closed))) return;
}
} finally {
if (mcpAuthentications.get(session.key) === wanted) mcpAuthentications.delete(session.key);
}
}

View File

@@ -2098,56 +2098,69 @@ describe("createSession options merging", () => {
expect(typeof capturedOptions!.onElicitation).toBe("function");
});
it("starts MCP OAuth as an ACP URL elicitation and completes it after reconnect", async () => {
let statusCall = 0;
mcpServerStatusResult = async () =>
statusCall++ === 0
? [{ name: "linear", status: "needs-auth" }]
: [{ name: "linear", status: "connected" }];
const authenticate = vi.fn(async () => ({
authUrl: "https://example.com/oauth/authorize",
requiresUserAction: true,
callbackExpected: true,
}));
mcpAuthenticateImpl = authenticate;
const createElicitation = vi.fn(async (_request: CreateElicitationRequest) => ({
action: "accept" as const,
}));
const completeElicitation = vi.fn(async () => {});
Object.assign((agent as unknown as { client: object }).client, {
createElicitation,
completeElicitation,
});
it.each([
["needs authentication", ["needs-auth"]],
// Claude Code still connects it when a warm `session/new` returns.
["is still connecting", ["pending", "needs-auth"]],
])(
"starts MCP OAuth as an ACP URL elicitation for a server that %s and completes it after reconnect",
async (_, before) => {
let statusCall = 0;
mcpServerStatusResult = async () => [
{ name: "linear", status: before[statusCall++] ?? "connected" },
];
const authenticate = vi.fn(async () => ({
authUrl: "https://example.com/oauth/authorize",
requiresUserAction: true,
callbackExpected: true,
}));
mcpAuthenticateImpl = authenticate;
const createElicitation = vi.fn(async (_request: CreateElicitationRequest) => ({
action: "accept" as const,
}));
const completeElicitation = vi.fn(async () => {});
Object.assign((agent as unknown as { client: object }).client, {
createElicitation,
completeElicitation,
});
await agent.initialize({
protocolVersion: 1,
clientCapabilities: { elicitation: { url: {} } },
});
const { sessionId } = await agent.newSession({
cwd: process.cwd(),
mcpServers: [
{ name: "linear", type: "http", url: "https://mcp.linear.app/mcp", headers: [] },
],
});
await agent.initialize({
protocolVersion: 1,
clientCapabilities: { elicitation: { url: {} } },
});
const { sessionId } = await agent.newSession({
cwd: process.cwd(),
mcpServers: [
{ name: "linear", type: "http", url: "https://mcp.linear.app/mcp", headers: [] },
],
});
// A `pending` read waits one status poll (1 s) before it reads again.
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
onTestFinished(() => {
vi.useRealTimers();
});
await vi.waitFor(() => expect(statusCall).toBeGreaterThan(0));
await vi.advanceTimersByTimeAsync(1_000);
await vi.waitFor(() => expect(completeElicitation).toHaveBeenCalledOnce());
await vi.waitFor(() => expect(completeElicitation).toHaveBeenCalledOnce());
expect(authenticate).toHaveBeenCalledWith("linear");
expect(createElicitation).toHaveBeenCalledOnce();
const request = createElicitation.mock.calls[0]![0];
expect(request.mode).toBe("url");
if (request.mode !== "url") throw new Error("Expected a URL elicitation");
expect(request).toMatchObject({
mode: "url",
sessionId,
message: "Authenticate with MCP server linear",
url: "https://example.com/oauth/authorize",
elicitationId: expect.stringMatching(/^mcp-oauth-/),
});
expect(completeElicitation).toHaveBeenCalledWith({
elicitationId: request.elicitationId,
});
});
expect(authenticate).toHaveBeenCalledWith("linear");
expect(createElicitation).toHaveBeenCalledOnce();
const request = createElicitation.mock.calls[0]![0];
expect(request.mode).toBe("url");
if (request.mode !== "url") throw new Error("Expected a URL elicitation");
expect(request).toMatchObject({
mode: "url",
sessionId,
message: "Authenticate with MCP server linear",
url: "https://example.com/oauth/authorize",
elicitationId: expect.stringMatching(/^mcp-oauth-/),
});
expect(completeElicitation).toHaveBeenCalledWith({
elicitationId: request.elicitationId,
});
},
);
it("still merges user-provided disallowedTools when AskUserQuestion is enabled", async () => {
await agent.initialize({

View File

@@ -159,7 +159,9 @@ function setup(
reconnectMcpServer: vi.fn(async (name: string) => {
events.push(`reconnect ${name}`);
const status = find(name);
if (status.status !== "needs-auth") status.status = "connected";
// As Claude Code: a server that needs OAuth does not reconnect.
if (status.status === "needs-auth") throw new Error("Server status: needs-auth");
status.status = "connected";
}),
toggleMcpServer: vi.fn(async (name: string, enabled: boolean) => {
events.push(`${enabled ? "enable" : "disable"} ${name}`);
@@ -517,7 +519,7 @@ describe("/mcp", () => {
expect(sdkQuery.reconnectMcpServer.mock.calls).toEqual([["linear"], ["db"], ["docs"]]);
expect(text()).toBe(
[
"- Reconnected `linear`\n- Reconnected `db`\n- Reconnected `docs`",
"- Couldn't reconnect `linear`: Server status: needs-auth\n- Reconnected `db`\n- Reconnected `docs`",
listAfter({ db: "connected", docs: "connected" }),
].join("\n\n"),
);
@@ -731,20 +733,51 @@ describe("/mcp and MCP OAuth", () => {
return { ...harness, mcpAuthenticate };
}
it("starts the MCP OAuth flow after an explicit reconnect of an ACP server", async () => {
const { mcpAuthenticate, text, prompt } = await oauthSetup({ acpServers: ["linear"] });
it("starts the MCP OAuth flow after an explicit reconnect of a server that needs it", async () => {
// From Claude Code's settings or the project's `.mcp.json`: no ACP server.
const { mcpAuthenticate, text, prompt } = await oauthSetup();
await prompt("/mcp reconnect linear");
await vi.waitFor(() => expect(mcpAuthenticate).toHaveBeenCalledOnce());
expect(mcpAuthenticate).toHaveBeenCalledWith("linear");
expect(text()).toBe(`- Reconnected \`linear\`\n\n${formatMcpStatus(SERVERS)}`);
expect(text()).toBe(
`- Couldn't reconnect \`linear\`: Server status: needs-auth\n\n${formatMcpStatus(SERVERS)}`,
);
});
it("starts the MCP OAuth flow only for the ACP servers of a reconnect of all", async () => {
it("checks the servers of a reconnect that arrives while another sign-in is open", async () => {
const statuses: McpServerStatus[] = [
{ name: "first", status: "needs-auth" },
{ name: "second", status: "needs-auth" },
];
let finishFirst!: () => void;
const mcpAuthenticate = vi.fn(async (server: string) => {
if (server === "first") await new Promise<void>((resolve) => (finishFirst = resolve));
return { requiresUserAction: false, callbackExpected: false };
});
const { prompt } = await oauthSetup({
query: {
mcpServerStatus: vi.fn(async () => statuses),
reconnectMcpServer: vi.fn(),
mcpAuthenticate,
},
});
await prompt("/mcp reconnect first");
await vi.waitFor(() => expect(mcpAuthenticate).toHaveBeenCalledOnce());
await prompt("/mcp reconnect second");
finishFirst();
await vi.waitFor(() => expect(mcpAuthenticate).toHaveBeenCalledTimes(2));
expect(mcpAuthenticate.mock.calls).toEqual([["first"], ["second"]]);
});
it("starts the MCP OAuth flow for each server of a reconnect of all that needs it", async () => {
const statuses: McpServerStatus[] = [
{ name: "acp", status: "needs-auth" },
{ name: "user", status: "needs-auth" },
{ name: "failing", status: "failed" },
];
const { mcpAuthenticate, prompt } = await oauthSetup({
acpServers: ["acp"],
@@ -753,8 +786,8 @@ describe("/mcp and MCP OAuth", () => {
await prompt("/mcp reconnect all");
await vi.waitFor(() => expect(mcpAuthenticate).toHaveBeenCalledOnce());
expect(mcpAuthenticate).toHaveBeenCalledWith("acp");
await vi.waitFor(() => expect(mcpAuthenticate).toHaveBeenCalledTimes(2));
expect(mcpAuthenticate.mock.calls).toEqual([["acp"], ["user"]]);
});
it("does not start the MCP OAuth flow for a plain /mcp", async () => {
@@ -767,15 +800,6 @@ describe("/mcp and MCP OAuth", () => {
expect(mcpAuthenticate).not.toHaveBeenCalled();
});
it("does not start the MCP OAuth flow for a server that is not from the ACP request", async () => {
const { mcpAuthenticate, prompt } = await oauthSetup();
await prompt("/mcp reconnect linear");
await new Promise((resolve) => setTimeout(resolve, 0));
expect(mcpAuthenticate).not.toHaveBeenCalled();
});
it("does not start the MCP OAuth flow when the turn was cancelled", async () => {
let releaseResult!: () => void;
const resultHeld = new Promise<void>((resolve) => (releaseResult = resolve));
@@ -786,7 +810,7 @@ describe("/mcp and MCP OAuth", () => {
});
const response = prompt("/mcp reconnect linear");
await vi.waitFor(() => expect(text()).toContain("Reconnected `linear`"));
await vi.waitFor(() => expect(text()).toContain("Couldn't reconnect `linear`"));
await agent.cancel({ sessionId: "test-session" });
releaseResult();

View File

@@ -90,6 +90,8 @@ const sdk = vi.hoisted(() => ({
enableRemoteControl: undefined as ((...args: unknown[]) => Promise<unknown>) | undefined,
/** Whether Claude Code asks at `initialize` for Remote Control to start with the query. */
remoteControlAtStartup: false,
/** When set, `reconnectMcpServer` waits for it. */
reconnectGate: undefined as Promise<void> | undefined,
}));
vi.mock("@anthropic-ai/claude-agent-sdk", async () => {
@@ -180,6 +182,12 @@ vi.mock("@anthropic-ai/claude-agent-sdk", async () => {
applyFlagSettings: fake.applyFlagSettings,
rewindFiles: fake.rewindFiles,
mcpServerStatus: async () => sdk.mcpServers,
// As Claude Code: a server that needs OAuth does not reconnect.
reconnectMcpServer: async (name: string) => {
await sdk.reconnectGate;
const server = sdk.mcpServers.find((candidate) => candidate.name === name);
if (server?.status === "needs-auth") throw new Error("Server status: needs-auth");
},
...(sdk.enableRemoteControl ? { enableRemoteControl: sdk.enableRemoteControl } : {}),
setMcpServers: fake.setMcpServers,
// A server that needs OAuth: Claude Code returns its authorization URL.
@@ -252,6 +260,7 @@ beforeEach(async () => {
sdk.startGate = undefined;
sdk.enableRemoteControl = undefined;
sdk.remoteControlAtStartup = false;
sdk.reconnectGate = undefined;
vi.mocked(forkSession).mockClear();
});
@@ -419,6 +428,12 @@ function assistant(id: string, content: unknown[]) {
};
}
/** Claude Code's answer to a local command such as `/mcp`, before its result with the same text. */
function syntheticAssistant(text: string) {
const message = assistant(`local-${randomUUID()}`, [{ type: "text", text }]);
return { ...message, message: { ...message.message, model: "<synthetic>" } };
}
function result(overrides: Record<string, unknown> = {}) {
return {
type: "result",
@@ -1934,7 +1949,9 @@ describe("ACP v2 core", () => {
const prompt = await claude.prompt(0);
claude.send(lifecycle(prompt, "started"));
await answer;
claude.send(result({ result: "1 MCP server connected. Run /mcp in the terminal." }));
const text = "1 MCP server connected. Run /mcp in the terminal.";
claude.send(syntheticAssistant(text));
claude.send(result({ result: text }));
claude.send(sessionState("idle"));
await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"]));
});
@@ -1950,6 +1967,69 @@ describe("ACP v2 core", () => {
expect(output.join()).not.toContain("in the terminal");
});
it("starts OAuth after the idle of a /mcp reconnect of a server that is not from the ACP request", async () => {
// A server of Claude Code's settings or of the project's `.mcp.json`.
sdk.mcpServers = [{ name: "linear", status: "needs-auth" }];
let statesAtElicitation: unknown[] | undefined;
const client = v2Client({
answerElicitation: () => {
statesAtElicitation = client.states();
return { action: "cancel" };
},
});
await client.connect(async (agent) => {
const { response, claude } = await openSession(agent, { elicitation: { url: {} } });
const answer = agent.request(v2.methods.agent.session.prompt, {
sessionId: response.sessionId,
prompt: [{ type: "text", text: "/mcp reconnect linear" }],
});
const prompt = await claude.prompt(0);
claude.send(lifecycle(prompt, "started"));
await answer;
const text = "Reconnect, enable, and disable aren't available in this session.";
claude.send(syntheticAssistant(text));
claude.send(result({ result: text }));
claude.send(sessionState("idle"));
await vi.waitFor(() => expect(client.elicitations).toHaveLength(1));
});
expect(client.elicitations[0]).toMatchObject({
mode: "url",
message: "Authenticate with MCP server linear",
url: "https://mcp.example.com/authorize",
});
expect(statesAtElicitation).toEqual(["running", "idle"]);
});
it("starts no OAuth for a /mcp reconnect whose turn was cancelled", async () => {
sdk.mcpServers = [{ name: "linear", status: "needs-auth" }];
let releaseReconnect!: () => void;
sdk.reconnectGate = new Promise((resolve) => (releaseReconnect = resolve));
const client = v2Client();
await client.connect(async (agent) => {
const { response, claude } = await openSession(agent, { elicitation: { url: {} } });
const sessionId = response.sessionId;
const answer = agent.request(v2.methods.agent.session.prompt, {
sessionId,
prompt: [{ type: "text", text: "/mcp reconnect linear" }],
});
const prompt = await claude.prompt(0);
claude.send(lifecycle(prompt, "started"));
await answer;
const text = "Reconnect, enable, and disable aren't available in this session.";
claude.send(syntheticAssistant(text));
claude.send(result({ result: text }));
await agent.notify(v2.methods.agent.session.cancel, { sessionId });
await vi.waitFor(() => expect(claude.interrupt).toHaveBeenCalled());
claude.send(sessionState("idle"));
await vi.waitFor(() => expect(client.states()).toEqual(["running", "idle"]));
releaseReconnect();
await new Promise((resolve) => setTimeout(resolve, 10));
});
expect(client.elicitations).toEqual([]);
});
it("fails the pending prompts and ends the work when Claude Code exits", async () => {
const client = v2Client();
const error = await client.connect(async (agent) => {

View File

@@ -2603,16 +2603,16 @@ export class ClaudeAcpAgent {
reconnected = outcome.reconnected;
return outcome.markdown;
},
// A reconnect starts OAuth for the ACP servers that it tried, as the
// session start does. A plain `/mcp` and a cancelled turn start none.
// A reconnect starts OAuth for each server that it tried and that needs
// it, also for one from Claude Code's settings or the project's
// `.mcp.json`: the client has no terminal to sign in from. A plain
// `/mcp` and a cancelled turn start none.
afterDelivery: () => {
const session = this.sessions[params.sessionId];
if (!session || session.cancelled) return;
const acpServers = new Set(
(session.creationParams?.mcpServers ?? []).map((server) => server.name),
);
const servers = new Set(reconnected.filter((server) => acpServers.has(server)));
if (servers.size > 0) startMcpServerAuthentication(this, params.sessionId, servers);
if (reconnected.length > 0) {
startMcpServerAuthentication(this, params.sessionId, new Set(reconnected));
}
},
};
}

View File

@@ -11,7 +11,8 @@
*
* `/mcp` is served as on v1 (`runMcpCommand`): Claude Code runs the command,
* and the adapter's server list replaces Claude Code's text in the turn's
* output.
* output. Once that text is sent, a reconnect starts OAuth for the servers
* that it tried and that need it.
*/
import type { ContentBlock } from "@agentclientprotocol/sdk/unstable";
import type * as v2 from "@agentclientprotocol/sdk/experimental/v2/unstable";
@@ -67,7 +68,8 @@ export class SessionCommands {
/**
* The text that replaces Claude Code's `output` of `command`, or `output`
* when the adapter cannot build it (a status read failed, or `signal`
* aborted).
* aborted). `reconnected` names the MCP servers that a reconnect tried, and is
* empty when `text` is `output`.
*/
async replace(
query: Parameters<typeof runMcpCommand>[0],
@@ -75,9 +77,9 @@ export class SessionCommands {
output: string,
signal: AbortSignal,
logError: (message: string) => void,
): Promise<string> {
const { markdown } = await runMcpCommand(query, command, output, signal, logError);
return markdown ?? output;
): Promise<{ text: string; reconnected: string[] }> {
const { markdown, reconnected } = await runMcpCommand(query, command, output, signal, logError);
return markdown === null ? { text: output, reconnected: [] } : { text: markdown, reconnected };
}
private render(commands: SlashCommand[]): v2.AvailableCommand[] {

View File

@@ -1174,6 +1174,10 @@ export class V2Session implements RequestTarget {
// Claude Code's sign-in message and its message for a failed API
// request are not shown as Claude's text (see `TurnReport`).
if (this.turnReport.assistant(message)) return;
// Claude Code answers `/mcp` with a `<synthetic>` assistant message
// and then a result with the same text. The adapter's text replaces
// the result's (see `result`), so this copy is not shown.
if (this.turnLocalCommand && message.message.model === "<synthetic>") return;
this.outputStarts();
this.wentOnPastApiError();
this.reports.assistant(message);
@@ -1447,9 +1451,15 @@ export class V2Session implements RequestTarget {
.replace(this.query, local.command, message.result, local.abort.signal, (error) =>
this.connection.logger.error(`Session ${this.sessionId}: ${error}`),
)
.then((text) => {
.then(async ({ text, reconnected }) => {
this.output.agentMessage(text, message.uuid);
return this.endTurn();
await this.endTurn();
// As on v1: a reconnect starts OAuth for each server that it
// tried and that needs it, wherever the server is configured. A
// cancelled turn starts none.
if (reconnected.length > 0 && !local.abort.signal.aborted) {
this.elicitations.authenticateMcpServers(reconnected);
}
});
}
this.output.agentMessage(message.result, message.uuid);