TypeScript
fix(server): send Claude MCP servers over the control channel (#17898)
Julius Marmingef82796a16abb
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.tsindex 83d5b11aef6..95a6b453c45 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts@@ -1,10 +1,15 @@+// @effect-diagnostics nodeBuiltinImport:off - the fake Claude CLI hands the SDK Node streams.+import * as NodeEvents from "node:events";import * as NodeOS from "node:os";+import * as NodeStream from "node:stream";import type {Query as ClaudeQuery,SDKMessage,SDKResultMessage,SDKUserMessage,+ SpawnedProcess,+ SpawnOptions,} from "@anthropic-ai/claude-agent-sdk";import type { AskUserQuestionInput } from "@anthropic-ai/claude-agent-sdk/sdk-tools";import * as NodeServices from "@effect/platform-node/NodeServices";@@ -63,7 +68,7 @@ import { WorktreeToolkit } from "../../mcp/toolkits/worktree/tools.ts";import { ThreadToolkit } from "../../mcp/toolkits/thread/tools.ts";import { OrchestratorToolkit } from "../../mcp/toolkits/orchestrator/tools.ts";import { ClaudeExecutableFileCheck } from "../../provider/Drivers/ClaudeExecutable.ts";-import type * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";+import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";import type * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";import { makeProviderFailure } from "@t3tools/provider-core/server/failure";@@ -499,14 +504,11 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {type: "http",url: "http://127.0.0.1:43123/mcp",headers: {- Authorization: "${T3_CODE_MCP_AUTHORIZATION}",+ Authorization: "Bearer secret-claude-token",},timeout: ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_TIMEOUT_MS,},} as const;- const T3_MCP_ENVIRONMENT = {- T3_CODE_MCP_AUTHORIZATION: "Bearer secret-claude-token",- } as const;const mcpSessionFor = (threadId: ThreadId,@@ -551,7 +553,6 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {assert.deepEqual(overrides, {allowedTools: [ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD],mcpServers: T3_MCP_SERVERS,- mcpEnvironment: T3_MCP_ENVIRONMENT,});});@@ -567,7 +568,6 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {assert.deepEqual(overrides, {allowedTools: ["Read", "mcp__t3-code__*"],mcpServers: T3_MCP_SERVERS,- mcpEnvironment: T3_MCP_ENVIRONMENT,});});@@ -586,7 +586,6 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {...ClaudeAdapterV2.CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS,],mcpServers: T3_MCP_SERVERS,- mcpEnvironment: T3_MCP_ENVIRONMENT,});assert.isFalse(overrides.allowedTools?.includes(ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_WILDCARD));});@@ -706,12 +705,11 @@ describe("ClaudeAdapterV2 native protocol logging", () => {type: "http",url: "http://127.0.0.1:43123/mcp",headers: {- Authorization: "${T3_CODE_MCP_AUTHORIZATION}",+ Authorization: "Bearer secret-claude-token",},timeout: ClaudeAdapterV2.CLAUDE_T3_MCP_TOOL_TIMEOUT_MS,},},- mcpEnvironment: { T3_CODE_MCP_AUTHORIZATION: "Bearer secret-claude-token" },});const options = ClaudeAdapterV2.makeClaudeQueryOptions({@@ -724,12 +722,8 @@ describe("ClaudeAdapterV2 native protocol logging", () => {cwd: "/workspace",allowedTools: overrides.allowedTools ?? [],mcpServers: overrides.mcpServers ?? {},- environment: { ...overrides.mcpEnvironment },+ environment: {},});- // mcpServers becomes a CLI argument, readable by every local user; the- // credential may only travel in the child's environment.- assert.notInclude(JSON.stringify(options.mcpServers), "secret-claude-token");- assert.equal(options.env?.T3_CODE_MCP_AUTHORIZATION, "Bearer secret-claude-token");assert.isObject(options.systemPrompt);const systemPrompt = options.systemPrompt as {readonly type: string;@@ -1850,6 +1844,120 @@ describe("ClaudeAdapterV2 native fork", () => {);});+// Stands in for the Claude CLI behind the SDK's spawn hook: records how it was+// started and answers stdin control requests, except mcp_set_servers if asked.+function makeFakeClaudeCli(answerSetServers = true) {+ const spawns: Array<SpawnOptions> = [];+ const controlRequests: Array<object> = [];+ const stdins: Array<NodeStream.PassThrough> = [];+ const spawn = (options: SpawnOptions): SpawnedProcess => {+ spawns.push(options);+ const stdin = new NodeStream.PassThrough();+ const stdout = new NodeStream.PassThrough();+ stdins.push(stdin);+ const child = Object.assign(new NodeEvents.EventEmitter(), {+ stdin,+ stdout,+ killed: false,+ exitCode: null as number | null,+ kill: () => {+ stdout.end();+ child.emit("exit", null, "SIGTERM");+ return true;+ },+ });+ let pending = "";+ stdin.on("data", (chunk: Buffer) => {+ pending += chunk.toString("utf8");+ for (let end = pending.indexOf("\n"); end >= 0; end = pending.indexOf("\n")) {+ const frame = JSON.parse(pending.slice(0, end));+ pending = pending.slice(end + 1);+ if (frame.type !== "control_request") continue;+ controlRequests.push(frame.request);+ const setServers = frame.request.subtype === "mcp_set_servers";+ if (setServers && !answerSetServers) continue;+ const response = {+ subtype: "success",+ request_id: frame.request_id,+ response: setServers ? { added: [], removed: [], errors: {} } : {},+ };+ stdout.write(`${JSON.stringify({ type: "control_response", response })}\n`);+ }+ });+ stdin.on("end", () => {+ stdout.end();+ child.emit("exit", 0, null);+ });+ return child;+ };+ // The SDK closes the CLI by ending its stdin.+ const closed = () => stdins.length > 0 && stdins.every((stdin) => stdin.writableEnded);+ return { spawn, spawns, controlRequests, closed };+}++describe("ClaudeAdapterV2 MCP credential channel", () => {+ const t3McpServer = {+ type: "http" as const,+ url: "http://127.0.0.1:43123/mcp",+ headers: { Authorization: "Bearer dummy-mcp-credential" },+ };+ const openWith = (cli: ReturnType<typeof makeFakeClaudeCli>) =>+ Effect.gen(function* () {+ const runner = yield* ClaudeAdapterV2.ClaudeAgentSdkQueryRunner;+ return yield* runner.open({+ threadId: ThreadId.make("thread-claude-mcp-channel"),+ providerSessionId: ProviderSessionId.make("provider-session-claude-mcp-channel"),+ options: {+ ...ClaudeAdapterV2.makeClaudeQueryOptions({+ modelSelection: CLAUDE_TEST_MODEL_SELECTION,+ nativeThreadId: "native-thread-claude-mcp-channel",+ resume: false,+ cwd: null,+ environment: { PATH: "/usr/bin" },+ mcpServers: { "t3-code": t3McpServer },+ }),+ pathToClaudeCodeExecutable: "/opt/claude/cli.js",+ spawnClaudeCodeProcess: cli.spawn,+ },+ });+ }).pipe(+ Effect.provide(ClaudeAdapterV2.layerQueryRunner),+ Effect.provideService(+ ProviderEventLoggers.ProviderEventLoggers,+ ProviderEventLoggers.NoOpProviderEventLoggers,+ ),+ Effect.provide(NodeServices.layer),+ );++ it.effect("sends MCP servers over stdin, not argv or the environment", () =>+ Effect.gen(function* () {+ const cli = makeFakeClaudeCli();+ const session = yield* openWith(cli);+ yield* session.close;++ assert.deepInclude(cli.controlRequests, {+ subtype: "mcp_set_servers",+ servers: { "t3-code": t3McpServer },+ });+ const spawned = JSON.stringify(cli.spawns);+ assert.notInclude(spawned, "--mcp-config");+ assert.notInclude(spawned, "dummy-mcp-credential");+ }),+ );++ it.effect("closes the CLI when it never answers the MCP registration", () =>+ Effect.gen(function* () {+ const cli = makeFakeClaudeCli(false);+ const opening = yield* openWith(cli).pipe(Effect.result, Effect.forkChild);+ yield* TestClock.adjust("90 seconds");+ const opened = yield* Fiber.join(opening);++ assert.equal(opened._tag, "Failure");+ assert.isTrue(cli.closed());+ }),+ );+});+describe("ClaudeAdapterV2 native session identity", () => {const openTurnWithOrdinal = (providerTurnOrdinal: number, nativeThreadHasTurns?: boolean) =>Effect.scoped(diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex 6251e698b2a..aadf28a618f 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -185,6 +185,9 @@ export const CLAUDE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CLAUDE_PROVconst DEFAULT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({});// Entry extensions the Claude SDK runs through node instead of executing.const CLAUDE_SCRIPT_EXTENSIONS = [".js", ".mjs", ".tsx", ".ts", ".jsx"];+// The SDK puts no deadline on control requests. The CLI answers+// mcp_set_servers once each server connected or hit its own 30 s timeout.+const CLAUDE_MCP_REGISTRATION_TIMEOUT = "90 seconds";export const ClaudeProviderCapabilitiesV2 = {sessions: {@@ -636,11 +639,16 @@ export const layerQueryRunner: Layer.Layer<),Stream.toAsyncIterable,);+ // The SDK would pass `mcpServers` as an inline `--mcp-config` argument,+ // which every local user can read. They go over the CLI's stdin control+ // channel instead, so header credentials stay out of its argv and out+ // of the environment every command the agent runs inherits.+ const { mcpServers, ...queryOptions } = input.options;// The SDK spawns a native binary as `path ...executableArgs ...sdkArgs`,// which lets the agent scope wrapper go in front of the CLI while the// SDK keeps its own stderr capture and exit reporting. The SDK runs a// script entry through node instead, so those launch unwrapped.- const binaryPath = input.options.pathToClaudeCodeExecutable;+ const binaryPath = queryOptions.pathToClaudeCodeExecutable;const launch =binaryPath === undefined ||CLAUDE_SCRIPT_EXTENSIONS.some((ext) => binaryPath.endsWith(ext))@@ -650,32 +658,74 @@ export const layerQueryRunner: Layer.Layer<args: [],name: "claude",threadId: input.threadId,- env: input.options.env,+ env: queryOptions.env,});const options =launch === undefined || launch.args.length === 0- ? input.options+ ? queryOptions: {- ...input.options,+ ...queryOptions,pathToClaudeCodeExecutable: launch.command,- executableArgs: [...launch.args, ...(input.options.executableArgs ?? [])],+ executableArgs: [...launch.args, ...(queryOptions.executableArgs ?? [])],};- const queryRuntime = yield* Effect.try({- try: () =>- query({- prompt,- options,- }),- catch: (cause) => queryRunnerError(cause, "query"),- });- yield* logProtocolEvent({- direction: "outgoing",- stage: "decoded",- payload: {- type: "query.open",- options: loggedClaudeQueryOptions(input.options),- },- });+ // The CLI is running once query() returns, so it is closed if anything+ // before the session is handed out fails or is interrupted.+ const queryRuntime = yield* Effect.uninterruptibleMask((restore) =>+ Effect.try({+ try: () => query({ prompt, options }),+ catch: (cause) => queryRunnerError(cause, "query"),+ }).pipe(+ Effect.tap((queryRuntime) =>+ restore(+ Effect.gen(function* () {+ if (mcpServers !== undefined) {+ // A rejected request or a server that failed to connect+ // leaves the turn without those tools, as `--mcp-config`+ // did. Error texts and the CLI's mcp_status response can+ // echo the headers, so only server names are logged.+ const failed = yield* Effect.tryPromise(() =>+ queryRuntime.setMcpServers(mcpServers),+ ).pipe(+ Effect.map((result) => Object.keys(result.errors)),+ Effect.orElseSucceed(() => Object.keys(mcpServers)),+ Effect.timeoutOrElse({+ duration: CLAUDE_MCP_REGISTRATION_TIMEOUT,+ orElse: () =>+ Effect.fail(+ queryRunnerError(+ "Claude Code did not answer the MCP server registration.",+ "setMcpServers",+ ),+ ),+ }),+ );+ if (failed.length > 0) {+ yield* Effect.logWarning("orchestration-v2.claude-mcp-servers-unavailable", {+ threadId: input.threadId,+ servers: failed,+ });+ }+ }+ yield* logProtocolEvent({+ direction: "outgoing",+ stage: "decoded",+ payload: {+ type: "query.open",+ options: loggedClaudeQueryOptions(input.options),+ },+ });+ }),+ ).pipe(+ Effect.onError(() =>+ Queue.shutdown(promptQueue).pipe(+ Effect.andThen(closeClaudeQuery(queryRuntime)),+ Effect.ignore,+ ),+ ),+ ),+ ),+ ),+ );return {messages: Stream.fromAsyncIterable(claudeQueryMessages(queryRuntime), (cause) =>@@ -1005,11 +1055,8 @@ export const CLAUDE_T3_MCP_TOOL_TIMEOUT_MS = 65 * 60 * 1_000;// read-only orchestrator tools so a read-only session cannot silently spawn// threads or scheduled tasks.//-// The SDK passes `mcpServers` to the CLI as an inline `--mcp-config` argument,-// and process arguments are readable by every local user. The credential-// therefore travels in the child's environment, which only its owner can read,-// and the CLI expands the `${VAR}` reference when it connects.-const CLAUDE_T3_MCP_AUTHORIZATION_ENV = "T3_CODE_MCP_AUTHORIZATION";+// The header carries the credential itself: the query runner sends+// `mcpServers` over the CLI's stdin, never its argv or environment.export function claudeMcpQueryOverrides(input: {readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined;@@ -1018,7 +1065,6 @@ export function claudeMcpQueryOverrides(input: {}): {readonly allowedTools?: ReadonlyArray<string>;readonly mcpServers?: ClaudeQueryOptions["mcpServers"];- readonly mcpEnvironment?: Readonly<Record<string, string>>;} {const session = input.mcpSession;if (session === undefined) {@@ -1034,12 +1080,11 @@ export function claudeMcpQueryOverrides(input: {type: "http",url: session.endpoint,headers: {- Authorization: `\${${CLAUDE_T3_MCP_AUTHORIZATION_ENV}}`,+ Authorization: session.authorizationHeader,},timeout: CLAUDE_T3_MCP_TOOL_TIMEOUT_MS,},},- mcpEnvironment: { [CLAUDE_T3_MCP_AUTHORIZATION_ENV]: session.authorizationHeader },};}@@ -1670,7 +1715,6 @@ export function claudeEffectiveQueryPolicyKey(mcpOverrides: {readonly allowedTools?: ReadonlyArray<string>;readonly mcpServers?: ClaudeQueryOptions["mcpServers"];- readonly mcpEnvironment?: Readonly<Record<string, string>>;},): string {return JSON.stringify({@@ -1681,7 +1725,6 @@ export function claudeEffectiveQueryPolicyKey(: { allowedTools: mcpOverrides.allowedTools }),}),mcpServers: mcpOverrides.mcpServers,- mcpEnvironment: mcpOverrides.mcpEnvironment,});}@@ -7488,7 +7531,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (cwd: turnInput.runtimePolicy.cwd,attachmentsDir,settings: adapterOptions.settings,- environment: { ...adapterOptions.environment, ...mcpOverrides.mcpEnvironment },+ environment: adapterOptions.environment,tools: queryPolicy.tools ?? CLAUDE_CODE_PRESET_TOOLS,...(mcpOverrides.allowedTools === undefined? {}