From 8686703d5fa325b7c1cf5860e1d4a8d0191a992c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 20 Jul 2026 16:49:49 +0200 Subject: [PATCH] fix(acp): bind MCP credentials to activated threads Passes the current target thread MCP configuration through ACP load, resume, and fork requests instead of reusing the credentials captured when the provider process opened. Addresses https://github.com/pingdotgg/t3code/pull/2829#discussion_r3507807130 Co-authored-by: codex --- .../Adapters/AcpAdapterV2.test.ts | 53 +++- .../orchestration-v2/Adapters/AcpAdapterV2.ts | 25 +- .../src/provider/acp/AcpSessionRuntime.ts | 247 +++++++++++++----- 3 files changed, 256 insertions(+), 69 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index ee9578dd93..ce8c25978e 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -1,6 +1,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { + EnvironmentId, MessageId, type ModelSelection, NodeId, @@ -29,6 +30,7 @@ import { ChildProcessSpawner } from "effect/unstable/process"; import type * as EffectAcpProtocol from "effect-acp/protocol"; import { ServerConfig } from "../../config.ts"; +import * as McpProviderSession from "../../mcp/McpProviderSession.ts"; import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts"; import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts"; import { @@ -106,6 +108,21 @@ function rawProtocolMethod(event: EffectAcpProtocol.AcpProtocolLogEvent): string return undefined; } +function rawProtocolRequest( + event: EffectAcpProtocol.AcpProtocolLogEvent, +): { readonly method?: unknown; readonly params?: unknown } | undefined { + if (event.stage !== "raw" || typeof event.payload !== "string") return undefined; + for (const line of event.payload.split("\n")) { + const trimmed = line.trim(); + if (trimmed.length === 0) continue; + const decoded = Option.getOrUndefined(decodeUnknownJson(trimmed)); + if (typeof decoded === "object" && decoded !== null && "method" in decoded) { + return decoded; + } + } + return undefined; +} + function makeTurnInput(input: { readonly threadId: ThreadId; readonly providerThread: OrchestrationV2ProviderThread; @@ -174,7 +191,8 @@ describe("AcpAdapterV2", () => { const mockAgentPath = yield* path.fromFileUrl( new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), ); - const makeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath }); + const protocolEvents = yield* Queue.bounded(256); + const makeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath, protocolEvents }); const instanceId = ProviderInstanceId.make("acp-test"); const adapter = makeAcpAdapterV2({ @@ -190,6 +208,17 @@ describe("AcpAdapterV2", () => { }); const sourceThreadId = ThreadId.make("thread-acp-native-fork-source"); const targetThreadId = ThreadId.make("thread-acp-native-fork-target"); + McpProviderSession.setMcpProviderSession({ + environmentId: EnvironmentId.make("environment-acp-native-fork"), + threadId: targetThreadId, + providerSessionId: "mcp-session-acp-native-fork", + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:43123/mcp", + authorizationHeader: "Bearer target-thread-token", + }); + yield* Effect.addFinalizer(() => + Effect.sync(() => McpProviderSession.clearMcpProviderSession(targetThreadId)), + ); const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ runtimeMode: "full-access", interactionMode: "default", @@ -215,11 +244,33 @@ describe("AcpAdapterV2", () => { sourceProviderThread, targetThreadId, }); + const forkRequest = Option.getOrThrow( + yield* Stream.fromQueue(protocolEvents).pipe( + Stream.filter( + (event) => + event.direction === "outgoing" && rawProtocolMethod(event) === "session/fork", + ), + Stream.map(rawProtocolRequest), + Stream.runHead, + ), + ); assert.equal(sourceProviderThread.nativeThreadRef?.nativeId, "mock-session-1"); assert.equal(forkedProviderThread.nativeThreadRef?.nativeId, "mock-session-1-fork"); assert.equal(forkedProviderThread.appThreadId, targetThreadId); assert.equal(forkedProviderThread.forkedFrom?.providerThreadId, sourceProviderThread.id); + assert.deepEqual(forkRequest.params, { + sessionId: "mock-session-1", + cwd: process.cwd(), + mcpServers: [ + { + type: "http", + name: "t3-code", + url: "http://127.0.0.1:43123/mcp", + headers: [{ name: "Authorization", value: "Bearer target-thread-token" }], + }, + ], + }); }).pipe(Effect.provide(testLayer), Effect.scoped), ); diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts index e5fc50d3b2..238ff85577 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts @@ -1896,12 +1896,16 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const supportsImagePrompts = started.initializeResult.agentCapabilities?.promptCapabilities?.image === true; - const activateSession = Effect.fnUntraced(function* (sessionId: string) { + const activateSession = Effect.fnUntraced(function* ( + sessionId: string, + threadId: ThreadId, + ) { + const activationOptions = { mcpServers: acpMcpServers(threadId) }; if (canLoadSession) { - return yield* runtime.loadSession(sessionId); + return yield* runtime.loadSession(sessionId, activationOptions); } if (canResumeSession) { - return yield* runtime.resumeSession(sessionId); + return yield* runtime.resumeSession(sessionId, activationOptions); } return yield* new ProviderAdapterProtocolError({ driver, @@ -2117,7 +2121,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV } const requestedSessionId = nativeThreadId(driver, turnInput.providerThread); if ((yield* Ref.get(activeSessionId)) !== requestedSessionId) { - const activated = yield* activateSession(requestedSessionId); + const activated = yield* activateSession(requestedSessionId, turnInput.threadId); yield* Ref.set(activeSessionId, activated.sessionId); yield* Ref.set(activeSessionSetup, activated); yield* configureSession(activated, turnInput.modelSelection, turnInput.runtimePolicy); @@ -2324,7 +2328,10 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV loadingRole: null, loadingIndex: 0, }); - const activated = yield* activateSession(sessionId); + const activated = yield* activateSession( + sessionId, + threadInput.providerThread.appThreadId, + ); yield* Ref.set(activeSessionId, activated.sessionId); yield* Ref.set(activeSessionSetup, activated); const nextSelection = threadInput.modelSelection ?? input.modelSelection; @@ -2447,7 +2454,9 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV loadingRole: null, loadingIndex: 0, }); - const activated = yield* runtime.loadSession(sessionId); + const activated = yield* runtime.loadSession(sessionId, { + mcpServers: acpMcpServers(snapshotInput.providerThread.appThreadId), + }); yield* Ref.set(activeSessionId, activated.sessionId); yield* Ref.set(activeSessionSetup, activated); yield* Ref.set(activeSelection, null); @@ -2506,7 +2515,9 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV }); } const sourceSessionId = nativeThreadId(driver, forkInput.sourceProviderThread); - const forked = yield* runtime.forkSession(sourceSessionId); + const forked = yield* runtime.forkSession(sourceSessionId, { + mcpServers: acpMcpServers(forkInput.targetThreadId), + }); yield* Ref.set(activeSessionId, forked.sessionId); yield* Ref.set(activeSessionSetup, forked); yield* Ref.set(activeSelection, null); diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 9e9d680986..611b93325b 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -112,61 +112,186 @@ export interface AcpSessionRuntimeStartResult { readonly modelConfigId: string | undefined; } -export interface AcpSessionRuntimeShape { - readonly handleRequestPermission: EffectAcpClient.AcpClientShape["handleRequestPermission"]; - readonly handleElicitation: EffectAcpClient.AcpClientShape["handleElicitation"]; - readonly handleReadTextFile: EffectAcpClient.AcpClientShape["handleReadTextFile"]; - readonly handleWriteTextFile: EffectAcpClient.AcpClientShape["handleWriteTextFile"]; - readonly handleCreateTerminal: EffectAcpClient.AcpClientShape["handleCreateTerminal"]; - readonly handleTerminalOutput: EffectAcpClient.AcpClientShape["handleTerminalOutput"]; - readonly handleTerminalWaitForExit: EffectAcpClient.AcpClientShape["handleTerminalWaitForExit"]; - readonly handleTerminalKill: EffectAcpClient.AcpClientShape["handleTerminalKill"]; - readonly handleTerminalRelease: EffectAcpClient.AcpClientShape["handleTerminalRelease"]; - readonly handleSessionUpdate: EffectAcpClient.AcpClientShape["handleSessionUpdate"]; - readonly handleElicitationComplete: EffectAcpClient.AcpClientShape["handleElicitationComplete"]; - readonly handleUnknownExtRequest: EffectAcpClient.AcpClientShape["handleUnknownExtRequest"]; - readonly handleUnknownExtNotification: EffectAcpClient.AcpClientShape["handleUnknownExtNotification"]; - readonly handleExtRequest: EffectAcpClient.AcpClientShape["handleExtRequest"]; - readonly handleExtNotification: EffectAcpClient.AcpClientShape["handleExtNotification"]; - readonly start: () => Effect.Effect; - readonly getEvents: () => Stream.Stream; - readonly getModeState: Effect.Effect; - readonly getConfigOptions: Effect.Effect>; - readonly loadSession: ( - sessionId: string, - ) => Effect.Effect; - readonly resumeSession: ( - sessionId: string, - ) => Effect.Effect; - readonly forkSession: ( - sessionId: string, - ) => Effect.Effect; - readonly listSessions: ( - cursor?: string, - ) => Effect.Effect; - readonly closeSession: ( - sessionId?: string, - ) => Effect.Effect; - readonly prompt: ( - payload: Omit, - ) => Effect.Effect; - readonly cancel: Effect.Effect; - readonly setMode: ( - modeId: string, - ) => Effect.Effect; - readonly setConfigOption: ( - configId: string, - value: string | boolean, - ) => Effect.Effect; - readonly setModel: (model: string) => Effect.Effect; - readonly request: ( - method: string, - payload: unknown, - ) => Effect.Effect; - readonly notify: ( - method: string, - payload: unknown, - ) => Effect.Effect; +export interface AcpSessionActivationOptions { + readonly mcpServers?: ReadonlyArray; +} + +export class AcpSessionRuntime extends Context.Service< + AcpSessionRuntime, + { + /** + * Registers a handler for `session/request_permission`. + * @see https://agentclientprotocol.com/protocol/schema#session/request_permission + */ + readonly handleRequestPermission: EffectAcpClient.AcpClient["Service"]["handleRequestPermission"]; + /** + * Registers a handler for `session/elicitation`. + * @see https://agentclientprotocol.com/protocol/schema#session/elicitation + */ + readonly handleElicitation: EffectAcpClient.AcpClient["Service"]["handleElicitation"]; + /** + * Registers a handler for `fs/read_text_file`. + * @see https://agentclientprotocol.com/protocol/schema#fs/read_text_file + */ + readonly handleReadTextFile: EffectAcpClient.AcpClient["Service"]["handleReadTextFile"]; + /** + * Registers a handler for `fs/write_text_file`. + * @see https://agentclientprotocol.com/protocol/schema#fs/write_text_file + */ + readonly handleWriteTextFile: EffectAcpClient.AcpClient["Service"]["handleWriteTextFile"]; + /** + * Registers a handler for `terminal/create`. + * @see https://agentclientprotocol.com/protocol/schema#terminal/create + */ + readonly handleCreateTerminal: EffectAcpClient.AcpClient["Service"]["handleCreateTerminal"]; + /** + * Registers a handler for `terminal/output`. + * @see https://agentclientprotocol.com/protocol/schema#terminal/output + */ + readonly handleTerminalOutput: EffectAcpClient.AcpClient["Service"]["handleTerminalOutput"]; + /** + * Registers a handler for `terminal/wait_for_exit`. + * @see https://agentclientprotocol.com/protocol/schema#terminal/wait_for_exit + */ + readonly handleTerminalWaitForExit: EffectAcpClient.AcpClient["Service"]["handleTerminalWaitForExit"]; + /** + * Registers a handler for `terminal/kill`. + * @see https://agentclientprotocol.com/protocol/schema#terminal/kill + */ + readonly handleTerminalKill: EffectAcpClient.AcpClient["Service"]["handleTerminalKill"]; + /** + * Registers a handler for `terminal/release`. + * @see https://agentclientprotocol.com/protocol/schema#terminal/release + */ + readonly handleTerminalRelease: EffectAcpClient.AcpClient["Service"]["handleTerminalRelease"]; + /** + * Registers a handler for `session/update`. + * @see https://agentclientprotocol.com/protocol/schema#session/update + */ + readonly handleSessionUpdate: EffectAcpClient.AcpClient["Service"]["handleSessionUpdate"]; + /** + * Registers a handler for `session/elicitation/complete`. + * @see https://agentclientprotocol.com/protocol/schema#session/elicitation/complete + */ + readonly handleElicitationComplete: EffectAcpClient.AcpClient["Service"]["handleElicitationComplete"]; + /** + * Registers a fallback extension request handler. + * @see https://agentclientprotocol.com/protocol/extensibility + */ + readonly handleUnknownExtRequest: EffectAcpClient.AcpClient["Service"]["handleUnknownExtRequest"]; + /** + * Registers a fallback extension notification handler. + * @see https://agentclientprotocol.com/protocol/extensibility + */ + readonly handleUnknownExtNotification: EffectAcpClient.AcpClient["Service"]["handleUnknownExtNotification"]; + /** + * Registers a typed extension request handler. + * @see https://agentclientprotocol.com/protocol/extensibility + */ + readonly handleExtRequest: EffectAcpClient.AcpClient["Service"]["handleExtRequest"]; + /** + * Registers a typed extension notification handler. + * @see https://agentclientprotocol.com/protocol/extensibility + */ + readonly handleExtNotification: EffectAcpClient.AcpClient["Service"]["handleExtNotification"]; + /** + * Initializes the ACP connection, authenticates, and loads, resumes, or creates the session. + * Concurrent calls share the same in-flight startup and a failed startup may be retried. + */ + readonly start: () => Effect.Effect; + /** Stream of parsed ACP session events emitted after startup. */ + readonly getEvents: () => Stream.Stream; + /** Waits until the current event consumer has processed every queued event. */ + readonly drainEvents: Effect.Effect; + /** Latest mode state observed from session setup and `session/update` notifications. */ + readonly getModeState: Effect.Effect; + /** Latest configuration options observed from session setup and configuration writes. */ + readonly getConfigOptions: Effect.Effect>; + readonly loadSession: ( + sessionId: string, + options?: AcpSessionActivationOptions, + ) => Effect.Effect; + readonly resumeSession: ( + sessionId: string, + options?: AcpSessionActivationOptions, + ) => Effect.Effect; + readonly forkSession: ( + sessionId: string, + options?: AcpSessionActivationOptions, + ) => Effect.Effect; + readonly listSessions: ( + cursor?: string, + ) => Effect.Effect; + readonly closeSession: ( + sessionId?: string, + ) => Effect.Effect; + /** + * Sends a prompt turn to the active session. + * @see https://agentclientprotocol.com/protocol/schema#session/prompt + */ + readonly prompt: ( + payload: Omit, + ) => Effect.Effect; + /** + * Sends a real ACP `session/cancel` notification for the active session. + * @see https://agentclientprotocol.com/protocol/schema#session/cancel + */ + readonly cancel: Effect.Effect; + /** + * Selects the active mode through the negotiated `mode` configuration option. + * This is a no-op when the requested mode is already active. + * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option + */ + readonly setMode: ( + modeId: string, + ) => Effect.Effect; + /** + * Updates a session configuration option and the runtime configuration snapshot. + * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option + */ + readonly setConfigOption: ( + configId: string, + value: string | boolean, + ) => Effect.Effect; + /** + * Selects the base model through the negotiated model configuration option. + * @see https://agentclientprotocol.com/protocol/schema#session/set_config_option + */ + readonly setModel: (model: string) => Effect.Effect; + /** + * Selects the active model through the unstable ACP `session/set_model` capability. + * @see https://agentclientprotocol.com/protocol/schema#session/set_model + */ + readonly setSessionModel: ( + modelId: string, + ) => Effect.Effect; + /** + * Sends a generic ACP extension request and records it through the request logger. + * @see https://agentclientprotocol.com/protocol/extensibility + */ + readonly request: ( + method: string, + payload: unknown, + ) => Effect.Effect; + /** + * Sends a generic ACP extension notification. + * @see https://agentclientprotocol.com/protocol/extensibility + */ + readonly notify: ( + method: string, + payload: unknown, + ) => Effect.Effect; + } +>()("t3/provider/acp/AcpSessionRuntime") { + static layer( + options: AcpSessionRuntimeOptions, + ): Layer.Layer< + AcpSessionRuntime, + EffectAcpErrors.AcpError, + ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto + > { + return Layer.effect(AcpSessionRuntime, make(options)); + } } interface AcpStartedState extends AcpSessionRuntimeStartResult {} @@ -653,13 +778,13 @@ export const make = ( getEvents: () => Stream.fromQueue(eventQueue), getModeState: Ref.get(modeStateRef), getConfigOptions: Ref.get(configOptionsRef), - loadSession: (sessionId) => + loadSession: (sessionId, activationOptions) => start.pipe( Effect.flatMap(() => { const requestPayload = { sessionId, cwd: options.cwd, - mcpServers: options.mcpServers ?? [], + mcpServers: activationOptions?.mcpServers ?? options.mcpServers ?? [], } satisfies EffectAcpSchema.LoadSessionRequest; return runLoggedRequest( "session/load", @@ -669,13 +794,13 @@ export const make = ( }), Effect.flatMap((response) => adoptSession(sessionId, response)), ), - resumeSession: (sessionId) => + resumeSession: (sessionId, activationOptions) => start.pipe( Effect.flatMap(() => { const requestPayload = { sessionId, cwd: options.cwd, - mcpServers: options.mcpServers ?? [], + mcpServers: activationOptions?.mcpServers ?? options.mcpServers ?? [], } satisfies EffectAcpSchema.ResumeSessionRequest; return runLoggedRequest( "session/resume", @@ -685,13 +810,13 @@ export const make = ( }), Effect.flatMap((response) => adoptSession(sessionId, response)), ), - forkSession: (sessionId) => + forkSession: (sessionId, activationOptions) => start.pipe( Effect.flatMap(() => { const requestPayload = { sessionId, cwd: options.cwd, - mcpServers: options.mcpServers ?? [], + mcpServers: activationOptions?.mcpServers ?? options.mcpServers ?? [], } satisfies EffectAcpSchema.ForkSessionRequest; return runLoggedRequest( "session/fork",