fix: send MCP servers to Claude Code over stdin, not on its command line (#1647)

## Summary

The adapter now sends a session's MCP servers to Claude Code over stdin,
not on its command line. A server's `env` and `headers` were readable
there by other users of the machine (`ps`). That includes the bearer
token of the local endpoint that serves an MCP-over-ACP server (#1645).

This uses the `mcpServersDelivery` option of SDK 0.3.326. It is stacked
on #1646, which updates the SDK and sets the option to `'argv'`. Merge
#1646 first.

## What changes

`mcpServersDelivery()` in `src/claude-cli.ts` picks the delivery, next
to `claudeCliPath()`, because it depends on which CLI is started:

- **The CLI that the adapter ships** (next to the executable, or the
SDK's platform package) gets the servers in the SDK's initialize
request: `'initialize'`. The SDK starts it with `--await-initialize` and
without `--mcp-config`.
- **A CLI that `CLAUDE_CODE_EXECUTABLE` names** gets them in the
`--mcp-config` flag as before: `'argv'`. Its version is not known, and
the SDK ends the session at startup when the CLI cannot read the servers
from the initialize request. For such a CLI nothing changes, and the
README says so.

Both cores set the value before the client's options, so a client's
`_meta.claudeCode.options.mcpServersDelivery` still wins. A session
without MCP servers starts as before: the SDK adds `--await-initialize`
only when it has servers to send.

## Why `CLAUDE_CODE_EXECUTABLE` keeps `'argv'` for now

Reading the servers from the initialize request needs Claude Code
2.1.326, which came out on 2026-11-16. The `stable` channel of Claude
Code is at 2.1.311. With `'initialize'` for every CLI, a session with an
MCP server would fail for each user whose `CLAUDE_CODE_EXECUTABLE` CLI
is older. Checked with 2.1.323 through the adapter: `session/new` fails
with `-32603` and "This Claude Code (version 2.1.323) is too old to read
MCP servers from the initialize request".

The plan is to drop the `'argv'` case once the `stable` channel is at
2.1.326 or newer, with an error that names `CLAUDE_CODE_EXECUTABLE`.

## Checked against the real CLI

Through the built adapter, with a stdio server that has a secret in its
`env` and an HTTP server with a secret `Authorization` header, and
without a prompt:

| | The adapter's CLI | `CLAUDE_CODE_EXECUTABLE` |
| --- | --- | --- |
| Launch flag | `--await-initialize` | `--mcp-config` |
| Secret on a command line (`ps`) | no | yes, as before |
| stdio server connects and gets its `env` | yes | yes |

This holds on v1 (a probe that is not part of this PR) and on v2. On v2
the MCP-over-ACP integration test now also checks that no command line
of the adapter's processes holds the endpoint's bearer token. With
`CLAUDE_CODE_EXECUTABLE` set, that check finds the token, so the test
skips it there.

With the SDK alone, under `'initialize'`:

- A resumed session (`--resume`) gets its servers: `mcp_servers_applied`
is true and the server connects.
- A startup failure still rejects with its reason: an invalid
`HTTPS_PROXY` gives `startupFailureReason: "proxy_invalid"` and the same
message as under `'argv'`.

## Notes for review

- **One difference that the SDK documents:** a Claude Code process that
the session's own process starts is not handed servers that came in the
initialize request. Subagents run in the session's process and are not
affected.
- **Unit runs take the `'argv'` case.** `vitest.config.ts` sets
`CLAUDE_CODE_EXECUTABLE` for them. So the session tests of v1 and v2
show that the value is passed and that the client's option wins.
`src/tests/claude-cli.test.ts` covers the rule, and the integration test
covers `'initialize'` end to end.

## Testing

- `npm run build`, `npm run check`, `npm run test:run` (4,285 tests
pass)
- Real CLI: the integration tests (`RUN_INTEGRATION_TESTS=true`, with
`CLAUDE_CODE_ENTRYPOINT` unset), 916 tests pass
- Real CLI: the probes above. One of them sends a prompt (one short
Haiku turn, to make a session to resume).

Of 6 full unit runs, 4 passed and 2 had one failure each. The one I
captured is "reads only the changed transcript for a subscription" in
`src/tests/v1/session-index.test.ts`, which passed in 12 runs alone. It
counts the transcripts that the session index reads after a file watcher
event (3 where it expects at most 1). This PR does not touch that code.
Not changed here. The other failure was not captured.
This commit is contained in:
Ben Brandt
2026-11-17 14:33:52 +01:00
committed by GitHub
parent 4a076397c6
commit c4dd80d739
8 changed files with 60 additions and 13 deletions

View File

@@ -46,6 +46,10 @@ Claude CLI (`claude`) it runs. Keep them in the same directory; a symlink to
instead, set `CLAUDE_CODE_EXECUTABLE`. On Alpine, install `libgcc` and
`libstdc++` first.
A CLI named with `CLAUDE_CODE_EXECUTABLE` gets a session's MCP servers on its
command line, where other users of the machine can read their `env` and
`headers`. The CLI that comes with the adapter gets them over stdin.
To build one for your machine (needs [Bun](https://bun.sh)) and check it:
```sh

View File

@@ -32,18 +32,26 @@ export async function claudeCliPath(): Promise<string> {
}
/**
* How a session's MCP servers reach the Claude CLI unless the client's options
* name a `mcpServersDelivery`: in the `--mcp-config` flag, as before SDK
* 0.3.326. A server's `env` and `headers` are then on the CLI's command line.
* `'initialize'` sends them over stdin instead, but with a CLI that cannot
* read them there (e.g. 2.1.323 through `CLAUDE_CODE_EXECUTABLE`) the session
* fails at startup.
* How a session's MCP servers reach the CLI of {@link claudeCliPath}, unless
* the client's options name a `mcpServersDelivery`.
*
* - `'initialize'` for the CLI that the adapter ships: over stdin, in the
* SDK's initialize request. A server's `env` and `headers`, such as the
* bearer token of an MCP-over-ACP endpoint (see `McpOverAcp`), stay off the
* CLI's command line, which other users of the machine can read. Only a
* launch that the client's options give `--sdk-url` still gets them there.
* - `'argv'` for a CLI that `CLAUDE_CODE_EXECUTABLE` names: in the
* `--mcp-config` flag, so on its command line, as before SDK 0.3.326. Its
* version is not known, and the SDK ends the session at startup when the CLI
* cannot read the servers from the initialize request (e.g. 2.1.323).
*
* The adapter always sets the option. It names the CLI to start
* (`pathToClaudeCodeExecutable`), and for such an app the SDK prints a
* `DeprecationWarning` when a session has MCP servers and the option is unset.
*/
export const MCP_SERVERS_DELIVERY: NonNullable<Options["mcpServersDelivery"]> = "argv";
export function mcpServersDelivery(): NonNullable<Options["mcpServersDelivery"]> {
return process.env.CLAUDE_CODE_EXECUTABLE ? "argv" : "initialize";
}
function bundledClaudeCliPath(directory: string): string {
const path = join(directory, CLI_FILE_NAME);

View File

@@ -55,3 +55,25 @@ describe("claudeCliPath", () => {
expect(await claudeCliPath()).toMatch(/@anthropic-ai\/claude-agent-sdk-[^/]+\/claude(\.exe)?$/);
});
});
describe("mcpServersDelivery", () => {
afterEach(() => vi.unstubAllEnvs());
it.each([
{
name: "is initialize for the CLI that it ships",
cli: "",
delivery: "initialize",
},
{
name: "is argv for a CLAUDE_CODE_EXECUTABLE CLI",
cli: "/opt/claude",
delivery: "argv",
},
])("$name", async ({ cli, delivery }) => {
vi.stubEnv("CLAUDE_CODE_EXECUTABLE", cli);
const { mcpServersDelivery } = await load();
expect(mcpServersDelivery()).toBe(delivery);
});
});

View File

@@ -616,7 +616,7 @@ describe("createSession options merging", () => {
});
it.each([
{ name: "sends MCP servers on the command line", delivery: undefined },
{ name: "sends MCP servers as the CLI takes them", delivery: undefined },
{ name: "lets a caller choose the MCP delivery", delivery: "initialize" as const },
])("$name", async ({ delivery }) => {
await agent.newSession({
@@ -625,6 +625,7 @@ describe("createSession options merging", () => {
...(delivery && { _meta: { claudeCode: { options: { mcpServersDelivery: delivery } } } }),
});
// Unit runs name a CLI with CLAUDE_CODE_EXECUTABLE (see `vitest.config.ts`).
expect(capturedOptions!.mcpServersDelivery).toBe(delivery ?? "argv");
});

View File

@@ -159,6 +159,17 @@ describe.skipIf(!process.env.RUN_INTEGRATION_TESTS)("v2 core with Claude Code",
// Claude Code asks for the server's MCP revision first, not with `initialize`.
await until(() => served.includes("tools/list"), 30_000);
expect(served[0]).toBe("server/discover");
// The server's bearer token went to Claude Code over stdin: it is on no
// command line of the adapter's processes (`ps`, so not on Windows). A
// CLAUDE_CODE_EXECUTABLE CLI gets it on its command line.
if (process.platform !== "win32" && !process.env.CLAUDE_CODE_EXECUTABLE) {
const commandLines = spawnSync("ps", ["-axww", "-o", "ppid=,command="], { encoding: "utf8" })
.stdout.split("\n")
.filter((line) => line.trim().startsWith(`${child.pid} `));
// Claude Code's session process is one of them.
expect(commandLines.some((line) => line.includes("stream-json"))).toBe(true);
expect(commandLines.filter((line) => line.includes("Bearer "))).toEqual([]);
}
}, 60_000);
it("reports requires_action while a permission request waits", async () => {

View File

@@ -879,7 +879,7 @@ describe("ACP v2 core", () => {
});
it.each([
{ name: "sends MCP servers on the command line", delivery: undefined },
{ name: "sends MCP servers as the CLI takes them", delivery: undefined },
{ name: "lets the client choose the MCP delivery", delivery: "initialize" },
])("$name", async ({ delivery }) => {
const client = v2Client();
@@ -895,6 +895,7 @@ describe("ACP v2 core", () => {
});
});
// Unit runs name a CLI with CLAUDE_CODE_EXECUTABLE (see `vitest.config.ts`).
expect(sdk.processes[0].options.mcpServersDelivery).toBe(delivery ?? "argv");
});

View File

@@ -187,7 +187,7 @@ import {
import { AuthStatusReporter, cliLogout } from "../auth-status-reporter.js";
import { terminalAuthMethods as authMethodsForTerminal } from "../auth-methods.js";
import { McpOverAcp, sdkMcpServers } from "../mcp-servers.js";
import { claudeCliPath, MCP_SERVERS_DELIVERY } from "../claude-cli.js";
import { claudeCliPath, mcpServersDelivery } from "../claude-cli.js";
import { ContentBlockParam } from "@anthropic-ai/sdk/resources";
import { randomUUID } from "node:crypto";
import type { Stats } from "node:fs";
@@ -10135,7 +10135,7 @@ export class ClaudeAcpAgent {
// `promptSuggestions: false` keeps it off.
promptSuggestions: true,
// Before `userProvidedOptions`, so a client's own `mcpServersDelivery` wins.
mcpServersDelivery: MCP_SERVERS_DELIVERY,
mcpServersDelivery: mcpServersDelivery(),
...userProvidedOptions,
// Claude Code uses the same checkpoint store for /rewind. Enable it only
// for clients that negotiated per-turn file-change reports; this avoids

View File

@@ -33,7 +33,7 @@ import packageJson from "../../package.json" with { type: "json" };
import { messageIdForGrouping } from "../sdk-to-acp.js";
import type { Logger } from "../logger.js";
import { customAgents } from "../session-config-options.js";
import { claudeCliPath, MCP_SERVERS_DELIVERY } from "../claude-cli.js";
import { claudeCliPath, mcpServersDelivery } from "../claude-cli.js";
import { clientSystemPrompt, sessionSystemPrompt } from "../client-system-prompt.js";
import type { ElicitationSupport } from "../elicitation.js";
import { forkSession } from "../fork-session.js";
@@ -1063,7 +1063,7 @@ class V2Agent implements AgentHandle, SessionConnection {
// Before the client's options: `promptSuggestions: false` turns it off.
...(this.air.client ? { promptSuggestions: true } : {}),
// Before the client's options: its own `mcpServersDelivery` wins.
mcpServersDelivery: MCP_SERVERS_DELIVERY,
mcpServersDelivery: mcpServersDelivery(),
...client,
// The checkpoints that AIR's file-change reports read (see
// `file-changes.ts`), only for a client that declared them, as on v1.