mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-11-19 15:51:32 +00:00
fix: send a session's settings to Claude Code over stdin (#1669)
## Summary The adapter now sends a session's `settings` to Claude Code over stdin, in the SDK's initialize request, as it has done for MCP servers since #1647. They went in the `--settings` flag before. Builds on #1668, which updated the SDK to 0.3.328. ## What changes `cliDelivery()` in `src/claude-cli.ts` replaces `mcpServersDelivery()`. It returns the SDK options `mcpServersDelivery` and `settingsDelivery` together, because one rule decides both: - **The CLI that the adapter ships** gets MCP servers and settings over stdin: `'initialize'`. Claude Code is then started with `--await-initialize --initialize-fields=settings` and without `--settings`. - **A CLI that `CLAUDE_CODE_EXECUTABLE` names** gets both in flags as before: `'argv'`. Its version is not known, and an older one fails the session at startup. Checked with 2.1.323: "unknown option '--initialize-fields=settings'". - **Settings stay in the flag when the client's `extraArgs` hold `settings` or `sdk-url`.** With `settings` there, Claude Code refuses to start with both ("--initialize-fields=settings cannot be used with --settings"), and in the flag the `settings` option replaces that argument, as before. A session with `sdk-url` cannot read the initialize request at launch, which is why the SDK sends its MCP servers in the flag too. Both cores set the two options before the client's options, so a client's own `mcpServersDelivery` or `settingsDelivery` wins. The settings in question are the ones the adapter passes as the SDK's `settings` option: a client's `_meta.claudeCode.options.settings`, the model configuration of the environment, and the route of a provider or gateway. A `settings` value that is a file path stays in the flag: the SDK only sends an object over stdin. ## `settingsDelivery` is not in the SDK's types SDK 0.3.328 reads `settingsDelivery`, but `sdk.d.ts` does not declare it and the changelog does not name it. The SDK version is pinned, and no cast is needed: the options are spread into the query's options. Nothing fails to compile if a later SDK drops the option. For that case the v2 integration tests have a new test against the real CLI: it starts a session with settings, and checks that Claude Code was started with `--initialize-fields=settings` and that no command line holds the settings' value. ## Delivery tests in `npm run test:integration` Each core has a test that expects `'argv'` for the MCP servers and one for the settings ("sends MCP servers as the CLI takes them", "sends settings as the CLI takes them"). They now set `CLAUDE_CODE_EXECUTABLE` themselves. Before, they relied on the value that `vitest.config.ts` sets for unit runs only. In `npm run test:integration` the variable is unset, the adapter's own CLI gets `'initialize'`, and the tests failed. On `main`, the MCP servers test fails in that run on both cores since #1647. This PR fixes it. ## Checked against the real CLI Through the built adapter, on v1 and on v2, without API usage: | Session | Started with | Result | | --- | --- | --- | | A client's `settings` | `--await-initialize --initialize-fields=settings` | the session starts | | The same, with the client's `settingsDelivery: 'argv'` | `--settings` | the session starts | | A provider with a header (`providers/set`, a local stand-in gateway) | `--await-initialize --initialize-fields=settings` | the session's model request reaches the gateway, with the provider's header | With the SDK alone: - The settings land in the same layer as before (`flagSettings` in `getSettings()`), and they survive `applyFlagSettings()` calls for effort and Fast mode. - Without a `settings` option, nothing changes in the launch flags. ## Testing - `npm run build`, `npm run check`, `npm run test:run` (4,375 tests pass) - Real CLI: the whole suite, as `npm run test:integration` runs it (with `CLAUDE_CODE_ENTRYPOINT` unset): 4,406 tests pass and 9 are skipped (the live capability audits, the baseline recording, and one test that skips itself). With `CLAUDE_CODE_EXECUTABLE` set, the new integration test is skipped. - Real CLI: the probes above
This commit is contained in:
@@ -31,26 +31,44 @@ export async function claudeCliPath(): Promise<string> {
|
||||
return installedClaudeCliPath();
|
||||
}
|
||||
|
||||
/** How an option reaches the Claude CLI: in a flag, or over stdin in the SDK's initialize request. */
|
||||
type Delivery = NonNullable<Options["mcpServersDelivery"]>;
|
||||
|
||||
/**
|
||||
* How a session's MCP servers reach the CLI of {@link claudeCliPath}, unless
|
||||
* the client's options name a `mcpServersDelivery`.
|
||||
* The SDK options that say how a session's MCP servers and its `settings`
|
||||
* reach the CLI of {@link claudeCliPath}. A client's own options replace them.
|
||||
*
|
||||
* - `'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.
|
||||
* SDK's initialize request.
|
||||
* - `'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).
|
||||
* `--mcp-config` and `--settings` flags, as before SDK 0.3.326. Its version
|
||||
* is not known, and a CLI that cannot take them over stdin fails the session
|
||||
* at startup (2.1.323: "too old to read MCP servers from the initialize
|
||||
* request", "unknown option '--initialize-fields=settings'").
|
||||
* - `settings` stay `'argv'` when the client's `extraArgs` hold `settings`:
|
||||
* Claude Code refuses to start with both ("--initialize-fields=settings
|
||||
* cannot be used with --settings"), and in the flag the `settings` option
|
||||
* replaces that argument. They also stay `'argv'` with `sdk-url` in the
|
||||
* `extraArgs`: such a session cannot read the request at launch, and the SDK
|
||||
* sends its MCP servers in the flag for the same reason.
|
||||
*
|
||||
* The adapter always sets the option. It names the CLI to start
|
||||
* The SDK reads `settingsDelivery` (0.3.328) but does not declare it in
|
||||
* `sdk.d.ts`, so nothing fails to compile if a later SDK drops it. The v2
|
||||
* integration tests check the delivery against the real CLI.
|
||||
*
|
||||
* `mcpServersDelivery` is always set. The adapter 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 function mcpServersDelivery(): NonNullable<Options["mcpServersDelivery"]> {
|
||||
return process.env.CLAUDE_CODE_EXECUTABLE ? "argv" : "initialize";
|
||||
export function cliDelivery(clientExtraArgs: Options["extraArgs"]): {
|
||||
mcpServersDelivery: Delivery;
|
||||
settingsDelivery: Delivery;
|
||||
} {
|
||||
const delivery = process.env.CLAUDE_CODE_EXECUTABLE ? "argv" : "initialize";
|
||||
const settingsInFlag = Object.keys(clientExtraArgs ?? {}).some(
|
||||
(name) => name === "settings" || name === "sdk-url" || name.startsWith("sdk-url="),
|
||||
);
|
||||
return { mcpServersDelivery: delivery, settingsDelivery: settingsInFlag ? "argv" : delivery };
|
||||
}
|
||||
|
||||
function bundledClaudeCliPath(directory: string): string {
|
||||
|
||||
@@ -56,24 +56,49 @@ describe("claudeCliPath", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("mcpServersDelivery", () => {
|
||||
describe("cliDelivery", () => {
|
||||
afterEach(() => vi.unstubAllEnvs());
|
||||
|
||||
it.each([
|
||||
it.each<{
|
||||
name: string;
|
||||
cli: string;
|
||||
extraArgs?: Record<string, string>;
|
||||
mcpServers: string;
|
||||
settings: string;
|
||||
}>([
|
||||
{
|
||||
name: "is initialize for the CLI that it ships",
|
||||
name: "is stdin for the CLI that it ships",
|
||||
cli: "",
|
||||
delivery: "initialize",
|
||||
mcpServers: "initialize",
|
||||
settings: "initialize",
|
||||
},
|
||||
{
|
||||
name: "is argv for a CLAUDE_CODE_EXECUTABLE CLI",
|
||||
name: "is a flag for a CLAUDE_CODE_EXECUTABLE",
|
||||
cli: "/opt/claude",
|
||||
delivery: "argv",
|
||||
mcpServers: "argv",
|
||||
settings: "argv",
|
||||
},
|
||||
])("$name", async ({ cli, delivery }) => {
|
||||
{
|
||||
name: "keeps settings a flag beside a client's",
|
||||
cli: "",
|
||||
extraArgs: { settings: "{}" },
|
||||
mcpServers: "initialize",
|
||||
settings: "argv",
|
||||
},
|
||||
{
|
||||
name: "keeps settings a flag with sdk-url",
|
||||
cli: "",
|
||||
extraArgs: { "sdk-url": "wss://example.com/session" },
|
||||
mcpServers: "initialize",
|
||||
settings: "argv",
|
||||
},
|
||||
])("$name", async ({ cli, extraArgs, mcpServers, settings }) => {
|
||||
vi.stubEnv("CLAUDE_CODE_EXECUTABLE", cli);
|
||||
const { mcpServersDelivery } = await load();
|
||||
const { cliDelivery } = await load();
|
||||
|
||||
expect(mcpServersDelivery()).toBe(delivery);
|
||||
expect(cliDelivery(extraArgs)).toEqual({
|
||||
mcpServersDelivery: mcpServers,
|
||||
settingsDelivery: settings,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import { describe, it, expect, beforeEach, afterEach, onTestFinished, vi } from "vitest";
|
||||
import {
|
||||
CreateElicitationRequest,
|
||||
RequestError,
|
||||
@@ -630,17 +630,33 @@ describe("createSession options merging", () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ 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 }) => {
|
||||
{ name: "sends MCP servers as the CLI takes them", option: "mcpServersDelivery" },
|
||||
{
|
||||
name: "lets a caller choose the MCP delivery",
|
||||
option: "mcpServersDelivery",
|
||||
own: "initialize",
|
||||
},
|
||||
{ name: "sends settings as the CLI takes them", option: "settingsDelivery" },
|
||||
{
|
||||
name: "lets a caller choose settings delivery",
|
||||
option: "settingsDelivery",
|
||||
own: "initialize",
|
||||
},
|
||||
])("$name", async ({ option, own }) => {
|
||||
// A CLI that CLAUDE_CODE_EXECUTABLE names gets both in flags.
|
||||
// `vitest.config.ts` sets the variable for unit runs only.
|
||||
vi.stubEnv("CLAUDE_CODE_EXECUTABLE", "/usr/bin/false");
|
||||
onTestFinished(() => {
|
||||
vi.unstubAllEnvs();
|
||||
});
|
||||
|
||||
await agent.newSession({
|
||||
cwd: process.cwd(),
|
||||
mcpServers: [],
|
||||
...(delivery && { _meta: { claudeCode: { options: { mcpServersDelivery: delivery } } } }),
|
||||
...(own && { _meta: { claudeCode: { options: { [option]: own } } } }),
|
||||
});
|
||||
|
||||
// Unit runs name a CLI with CLAUDE_CODE_EXECUTABLE (see `vitest.config.ts`).
|
||||
expect(capturedOptions!.mcpServersDelivery).toBe(delivery ?? "argv");
|
||||
expect((capturedOptions as Record<string, unknown>)[option]).toBe(own ?? "argv");
|
||||
});
|
||||
|
||||
it("defaults tools to claude_code preset when not provided", async () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
@@ -70,6 +71,19 @@ describe.skipIf(!process.env.RUN_INTEGRATION_TESTS)("v2 core with Claude Code",
|
||||
|
||||
afterAll(() => child?.kill());
|
||||
|
||||
/**
|
||||
* Whether the adapter sends MCP servers and settings to Claude Code over
|
||||
* stdin (see `cliDelivery`), and `ps` can show that: not for a
|
||||
* CLAUDE_CODE_EXECUTABLE CLI, and not on Windows.
|
||||
*/
|
||||
const takesOptionsOverStdin = process.platform !== "win32" && !process.env.CLAUDE_CODE_EXECUTABLE;
|
||||
|
||||
/** The command lines of the processes that the adapter started. */
|
||||
const adapterCommandLines = () =>
|
||||
spawnSync("ps", ["-axww", "-o", "ppid=,command="], { encoding: "utf8" })
|
||||
.stdout.split("\n")
|
||||
.filter((line) => line.trim().startsWith(`${child.pid} `));
|
||||
|
||||
/** The states of the root session's `state_update`s, in order. */
|
||||
const states = (sessionId: string) =>
|
||||
updates.flatMap(({ sessionId: id, update }) =>
|
||||
@@ -218,19 +232,34 @@ 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} `));
|
||||
// The server's bearer token went to Claude Code over stdin.
|
||||
if (takesOptionsOverStdin) {
|
||||
const commandLines = adapterCommandLines();
|
||||
// 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);
|
||||
|
||||
// No prompt: it costs no API usage.
|
||||
it.skipIf(!takesOptionsOverStdin)(
|
||||
"sends a session's settings to Claude Code over stdin",
|
||||
async () => {
|
||||
const marker = `v2-integration-${randomUUID()}`;
|
||||
await agent.request(v2.methods.agent.session.new, {
|
||||
cwd,
|
||||
_meta: {
|
||||
claudeCode: { options: { settings: { env: { V2_INTEGRATION_MARKER: marker } } } },
|
||||
},
|
||||
});
|
||||
const commandLines = adapterCommandLines();
|
||||
// Claude Code's session process, told to read the settings from the initialize request.
|
||||
expect(commandLines.some((line) => line.includes("--initialize-fields=settings"))).toBe(true);
|
||||
expect(commandLines.filter((line) => line.includes(marker))).toEqual([]);
|
||||
},
|
||||
60_000,
|
||||
);
|
||||
|
||||
it("reports requires_action while a permission request waits", async () => {
|
||||
const sessionId = await newSession("default");
|
||||
await prompt(
|
||||
|
||||
@@ -1024,9 +1024,23 @@ describe("ACP v2 core", () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ name: "sends MCP servers as the CLI takes them", delivery: undefined },
|
||||
{ name: "lets the client choose the MCP delivery", delivery: "initialize" },
|
||||
])("$name", async ({ delivery }) => {
|
||||
{ name: "sends MCP servers as the CLI takes them", option: "mcpServersDelivery" },
|
||||
{
|
||||
name: "lets the client choose the MCP delivery",
|
||||
option: "mcpServersDelivery",
|
||||
own: "initialize",
|
||||
},
|
||||
{ name: "sends settings as the CLI takes them", option: "settingsDelivery" },
|
||||
{
|
||||
name: "lets the client choose settings delivery",
|
||||
option: "settingsDelivery",
|
||||
own: "initialize",
|
||||
},
|
||||
])("$name", async ({ option, own }) => {
|
||||
// A CLI that CLAUDE_CODE_EXECUTABLE names gets both in flags.
|
||||
// `vitest.config.ts` sets the variable for unit runs only.
|
||||
vi.stubEnv("CLAUDE_CODE_EXECUTABLE", "/usr/bin/false");
|
||||
|
||||
const client = v2Client();
|
||||
await client.connect(async (agent) => {
|
||||
await agent.request(v2.methods.agent.initialize, {
|
||||
@@ -1036,12 +1050,11 @@ describe("ACP v2 core", () => {
|
||||
});
|
||||
await agent.request(v2.methods.agent.session.new, {
|
||||
cwd,
|
||||
...(delivery && { _meta: { claudeCode: { options: { mcpServersDelivery: delivery } } } }),
|
||||
...(own && { _meta: { claudeCode: { options: { [option]: own } } } }),
|
||||
});
|
||||
});
|
||||
|
||||
// Unit runs name a CLI with CLAUDE_CODE_EXECUTABLE (see `vitest.config.ts`).
|
||||
expect(sdk.processes[0].options.mcpServersDelivery).toBe(delivery ?? "argv");
|
||||
expect((sdk.processes[0].options as Record<string, unknown>)[option]).toBe(own ?? "argv");
|
||||
});
|
||||
|
||||
it("answers a prompt when Claude Code starts it, and reports the work until the turn's result", async () => {
|
||||
|
||||
@@ -192,7 +192,7 @@ import {
|
||||
import { AuthStatusReporter, cliLogout } from "../auth-status-reporter.js";
|
||||
import { terminalAuthMethods as authMethodsForTerminal } from "../auth-methods.js";
|
||||
import { McpOverAcp, sdkMcpServers, type UnservedMcpServer } from "../mcp-servers.js";
|
||||
import { claudeCliPath, mcpServersDelivery } from "../claude-cli.js";
|
||||
import { claudeCliPath, cliDelivery } from "../claude-cli.js";
|
||||
import { ContentBlockParam } from "@anthropic-ai/sdk/resources";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Stats } from "node:fs";
|
||||
@@ -10226,8 +10226,9 @@ export class ClaudeAcpAgent {
|
||||
// Before `userProvidedOptions`, so a client that passes
|
||||
// `promptSuggestions: false` keeps it off.
|
||||
...promptSuggestionOptions(suggestionForms),
|
||||
// Before `userProvidedOptions`, so a client's own `mcpServersDelivery` wins.
|
||||
mcpServersDelivery: mcpServersDelivery(),
|
||||
// Before `userProvidedOptions`, so a client's own `mcpServersDelivery`
|
||||
// and `settingsDelivery` win.
|
||||
...cliDelivery(userProvidedOptions?.extraArgs),
|
||||
...userProvidedOptions,
|
||||
// Claude Code uses the same checkpoint store for /rewind. Enable it only
|
||||
// for clients that negotiated per-turn file-change reports; this avoids
|
||||
|
||||
@@ -35,7 +35,7 @@ import { messageIdForGrouping } from "../sdk-to-acp.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { customAgents } from "../session-config-options.js";
|
||||
import { restrictedChild } from "../acp-subagents.js";
|
||||
import { claudeCliPath, mcpServersDelivery } from "../claude-cli.js";
|
||||
import { claudeCliPath, cliDelivery } from "../claude-cli.js";
|
||||
import { clientSystemPrompt, sessionSystemPrompt } from "../client-system-prompt.js";
|
||||
import type { ElicitationSupport } from "../elicitation.js";
|
||||
import { forkSession } from "../fork-session.js";
|
||||
@@ -1102,8 +1102,9 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
// other client's session spends a request on it.
|
||||
// Before the client's options: `promptSuggestions: false` turns it off.
|
||||
...promptSuggestionOptions(this.promptSuggestions),
|
||||
// Before the client's options: its own `mcpServersDelivery` wins.
|
||||
mcpServersDelivery: mcpServersDelivery(),
|
||||
// Before the client's options: its own `mcpServersDelivery` and
|
||||
// `settingsDelivery` win.
|
||||
...cliDelivery(client?.extraArgs),
|
||||
...client,
|
||||
// The checkpoints that AIR's file-change reports read (see
|
||||
// `file-changes.ts`), only for a client that declared them, as on v1.
|
||||
|
||||
Reference in New Issue
Block a user