Skip to content

Commit 854d619

Browse files
committed
feat: use client roots as ACP agent working directory
- Add setRootsProvider to ISamplingShim for per-session roots/list callbacks - Resolve cwd from client roots in sampling shim with 5s timeout fallback - Wire roots provider in both HTTP and stdio transport modes - Fix server-to-client requests being silently dropped by routing listRoots through POST response stream via relatedRequestId - Add unit tests for roots-based cwd resolution and timeout behavior
1 parent bf54d96 commit 854d619

6 files changed

Lines changed: 283 additions & 7 deletions

File tree

‎apps/gateway/src/index.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,13 @@ async function startHttpMode(
288288
logger,
289289
);
290290

291+
// Register roots provider so the sampling shim can resolve client roots as cwd
292+
if (capabilities.roots && samplingShim) {
293+
samplingShim.setRootsProvider(sessionId, () =>
294+
gatewayServer.forwardListRootsRequest(),
295+
);
296+
}
297+
291298
// Now initialize upstream MCP clients with the (possibly augmented) capabilities
292299
// This tells upstream servers what requests they can send through the proxy
293300
const initResult = await initializeClientsForSession(
@@ -507,6 +514,13 @@ async function startStdioMode(
507514
logger,
508515
);
509516

517+
// Register roots provider so the sampling shim can resolve client roots as cwd
518+
if (capabilities.roots && samplingShim) {
519+
samplingShim.setRootsProvider(SESSION_ID, () =>
520+
gatewayServer.forwardListRootsRequest(),
521+
);
522+
}
523+
510524
// Initialize upstream MCP clients with (possibly augmented) capabilities
511525
const initResult = await initializeClientsForSession(
512526
SESSION_ID,

‎apps/gateway/src/mcp/gateway-server.ts‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,14 @@ export class MCPGatewayServer {
7474
private serverId = "my-cool-proxy";
7575
private onDownstreamInitialized?: OnDownstreamInitializedCallback;
7676

77+
/**
78+
* Tracks the downstream request ID during tool execution.
79+
* Used to route server-to-client requests (like roots/list) through the
80+
* active POST response stream instead of the standalone GET SSE stream,
81+
* which may be disconnected depending on the client implementation.
82+
*/
83+
private activeDownstreamRequestId?: string | number;
84+
7785
constructor(
7886
@$inject(TYPES.ToolRegistry) private toolRegistry: IToolRegistry,
7987
@$inject(TYPES.MCPClientManager) private clientPool: IMCPClientManager,
@@ -166,8 +174,18 @@ export class MCPGatewayServer {
166174
},
167175
async (
168176
args: Record<string, unknown>,
169-
context: { sessionId?: string },
170-
) => tool.execute(args, context),
177+
// The SDK passes the full RequestHandlerExtra here, which includes
178+
// requestId — we capture it so forwardListRootsRequest can route
179+
// through the POST response stream rather than the standalone GET SSE.
180+
context: { sessionId?: string; requestId?: string | number },
181+
) => {
182+
this.activeDownstreamRequestId = context.requestId;
183+
try {
184+
return await tool.execute(args, context);
185+
} finally {
186+
this.activeDownstreamRequestId = undefined;
187+
}
188+
},
171189
);
172190

173191
this.logger.info(`Registered tool: ${tool.name}`);
@@ -331,7 +349,14 @@ export class MCPGatewayServer {
331349
this.logger.debug(`Forwarding roots/list request to downstream`);
332350

333351
try {
334-
const result = await this.server.server.listRoots();
352+
// Pass relatedRequestId so the transport routes through the active POST
353+
// response stream. Without this, the request goes to the standalone GET
354+
// SSE stream which may be disconnected (e.g. Claude Code doesn't maintain one).
355+
const options =
356+
this.activeDownstreamRequestId !== undefined
357+
? { relatedRequestId: this.activeDownstreamRequestId }
358+
: undefined;
359+
const result = await this.server.server.listRoots(undefined, options);
335360
this.logger.debug(
336361
`Roots/list request completed: ${result.roots.length} root(s)`,
337362
);

‎apps/gateway/src/services/sampling-shim.test.ts‎

Lines changed: 166 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,13 @@ vi.mock("@my-cool-proxy/acp-client", () => ({
1111
ACPClient: vi.fn(),
1212
}));
1313

14-
// Mock the mappers and tempdir utilities
14+
// Mock the mappers, tempdir utilities, and root utils
1515
vi.mock("../utils/index.js", () => ({
1616
mapMcpToAcpPrompt: vi.fn(),
1717
mapAcpToMcpResult: vi.fn(),
1818
createSessionTempDir: vi.fn((sessionId: string) => `/tmp/test-${sessionId}`),
1919
cleanupSessionTempDir: vi.fn(),
20+
findValidLocalRoot: vi.fn(),
2021
}));
2122

2223
const createMockLogger = (): ILogger => ({
@@ -211,6 +212,170 @@ describe("SamplingShim", () => {
211212
});
212213
});
213214

215+
describe("roots-based cwd resolution", () => {
216+
const params: CreateMessageRequest["params"] = {
217+
messages: [{ role: "user", content: { type: "text", text: "Hello" } }],
218+
maxTokens: 100,
219+
};
220+
221+
it("should use client root as cwd when roots provider returns a valid local root", async () => {
222+
vi.mocked(mappers.findValidLocalRoot).mockReturnValue(
223+
"/Users/test/my-project",
224+
);
225+
226+
const shim = new SamplingShim(
227+
agentConfig,
228+
createMockLogger(),
229+
createMockCapabilityStore() as never,
230+
);
231+
await shim.initialize("session-1");
232+
233+
shim.setRootsProvider("session-1", async () => ({
234+
roots: [{ uri: "file:///Users/test/my-project" }],
235+
}));
236+
237+
await shim.handleSamplingRequest("session-1", params);
238+
239+
expect(mappers.findValidLocalRoot).toHaveBeenCalledWith([
240+
{ uri: "file:///Users/test/my-project" },
241+
]);
242+
expect(mockAcpClient.createSession).toHaveBeenCalledWith(
243+
"/Users/test/my-project",
244+
[],
245+
undefined,
246+
);
247+
});
248+
249+
it("should fall back to tempdir when roots provider returns no valid local paths", async () => {
250+
vi.mocked(mappers.findValidLocalRoot).mockReturnValue(undefined);
251+
252+
const shim = new SamplingShim(
253+
agentConfig,
254+
createMockLogger(),
255+
createMockCapabilityStore() as never,
256+
);
257+
await shim.initialize("session-1");
258+
259+
shim.setRootsProvider("session-1", async () => ({
260+
roots: [{ uri: "https://example.com/repo" }],
261+
}));
262+
263+
await shim.handleSamplingRequest("session-1", params);
264+
265+
expect(mockAcpClient.createSession).toHaveBeenCalledWith(
266+
"/tmp/test-session-1",
267+
[],
268+
undefined,
269+
);
270+
});
271+
272+
it("should fall back to tempdir when roots provider times out", async () => {
273+
vi.useFakeTimers();
274+
275+
const shim = new SamplingShim(
276+
agentConfig,
277+
createMockLogger(),
278+
createMockCapabilityStore() as never,
279+
);
280+
await shim.initialize("session-1");
281+
282+
shim.setRootsProvider(
283+
"session-1",
284+
() => new Promise(() => {}), // never resolves
285+
);
286+
287+
const requestPromise = shim.handleSamplingRequest("session-1", params);
288+
289+
// Advance past the 5s timeout
290+
await vi.advanceTimersByTimeAsync(6_000);
291+
292+
const result = await requestPromise;
293+
294+
expect(result).toEqual({
295+
role: "assistant",
296+
content: { type: "text", text: "agent response" },
297+
model: "acp-agent",
298+
stopReason: "endTurn",
299+
});
300+
expect(mockAcpClient.createSession).toHaveBeenCalledWith(
301+
"/tmp/test-session-1",
302+
[],
303+
undefined,
304+
);
305+
306+
vi.useRealTimers();
307+
});
308+
309+
it("should fall back to tempdir when roots provider throws an error", async () => {
310+
const shim = new SamplingShim(
311+
agentConfig,
312+
createMockLogger(),
313+
createMockCapabilityStore() as never,
314+
);
315+
await shim.initialize("session-1");
316+
317+
shim.setRootsProvider("session-1", async () => {
318+
throw new Error("Client disconnected");
319+
});
320+
321+
await shim.handleSamplingRequest("session-1", params);
322+
323+
expect(mockAcpClient.createSession).toHaveBeenCalledWith(
324+
"/tmp/test-session-1",
325+
[],
326+
undefined,
327+
);
328+
});
329+
330+
it("should use tempdir when no roots provider is set", async () => {
331+
const shim = new SamplingShim(
332+
agentConfig,
333+
createMockLogger(),
334+
createMockCapabilityStore() as never,
335+
);
336+
await shim.initialize("session-1");
337+
338+
await shim.handleSamplingRequest("session-1", params);
339+
340+
expect(mockAcpClient.createSession).toHaveBeenCalledWith(
341+
"/tmp/test-session-1",
342+
[],
343+
undefined,
344+
);
345+
});
346+
347+
it("should clean up roots provider on close", async () => {
348+
vi.mocked(mappers.findValidLocalRoot).mockReturnValue(
349+
"/Users/test/my-project",
350+
);
351+
352+
const shim = new SamplingShim(
353+
agentConfig,
354+
createMockLogger(),
355+
createMockCapabilityStore() as never,
356+
);
357+
await shim.initialize("session-1");
358+
359+
shim.setRootsProvider("session-1", async () => ({
360+
roots: [{ uri: "file:///Users/test/my-project" }],
361+
}));
362+
363+
await shim.close("session-1");
364+
365+
// Re-initialize and verify roots provider is gone (falls back to tempdir)
366+
vi.mocked(mappers.findValidLocalRoot).mockClear();
367+
await shim.initialize("session-1");
368+
await shim.handleSamplingRequest("session-1", params);
369+
370+
expect(mappers.findValidLocalRoot).not.toHaveBeenCalled();
371+
expect(mockAcpClient.createSession).toHaveBeenCalledWith(
372+
"/tmp/test-session-1",
373+
[],
374+
undefined,
375+
);
376+
});
377+
});
378+
214379
describe("close", () => {
215380
it("should close the ACPClient for the session", async () => {
216381
const shim = new SamplingShim(

‎apps/gateway/src/services/sampling-shim.ts‎

Lines changed: 63 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,12 @@ import type {
2020
ACPFilesystemConfig,
2121
ACPAllowOwnToolsConfig,
2222
} from "../types/interfaces.js";
23-
import { mapMcpToAcpPrompt, mapAcpToMcpResult } from "../utils/index.js";
23+
import type { ListRootsResult } from "@modelcontextprotocol/sdk/types.js";
24+
import {
25+
mapMcpToAcpPrompt,
26+
mapAcpToMcpResult,
27+
findValidLocalRoot,
28+
} from "../utils/index.js";
2429
import { $inject } from "../container/decorators.js";
2530
import { TYPES } from "../types/index.js";
2631
import { ToolCallbackServer } from "./tool-callback-server.js";
@@ -43,6 +48,7 @@ const require = createRequire(import.meta.url);
4348
@injectable()
4449
export class SamplingShim implements ISamplingShim {
4550
private clients = new Map<string, ACPClient>();
51+
private rootsProviders = new Map<string, () => Promise<ListRootsResult>>();
4652

4753
constructor(
4854
private readonly agentConfig: ACPAgentConfig,
@@ -94,10 +100,61 @@ export class SamplingShim implements ISamplingShim {
94100
this.logger.info(`Sampling shim initialized for session ${sessionId}`);
95101
}
96102

103+
setRootsProvider(
104+
sessionId: string,
105+
provider: () => Promise<ListRootsResult>,
106+
): void {
107+
this.rootsProviders.set(sessionId, provider);
108+
}
109+
110+
/** Timeout for roots/list requests (ms). Keeps sampling fast when the client is slow. */
111+
private static readonly ROOTS_TIMEOUT_MS = 5_000;
112+
113+
/**
114+
* Resolve the working directory for a sampling request.
115+
* Tries roots/list first (if provider available), falls back to capability store.
116+
* A timeout ensures a slow/unresponsive downstream client doesn't block sampling.
117+
*/
118+
private async resolveWorkingDirectory(
119+
sessionId: string,
120+
): Promise<string | undefined> {
121+
const provider = this.rootsProviders.get(sessionId);
122+
if (provider) {
123+
try {
124+
const rootsResult = await Promise.race([
125+
provider(),
126+
new Promise<never>((_, reject) =>
127+
setTimeout(
128+
() => reject(new Error("roots/list timed out")),
129+
SamplingShim.ROOTS_TIMEOUT_MS,
130+
),
131+
),
132+
]);
133+
const localRoot = findValidLocalRoot(rootsResult.roots);
134+
if (localRoot) {
135+
this.logger.info(
136+
`Session ${sessionId}: Using client root as cwd: ${localRoot}`,
137+
);
138+
return localRoot;
139+
}
140+
this.logger.debug(
141+
`Session ${sessionId}: No valid local root found, falling back to tempdir`,
142+
);
143+
} catch (error) {
144+
this.logger.warn(
145+
{ error: error instanceof Error ? error.message : String(error) },
146+
`Session ${sessionId}: Failed to fetch roots, falling back to tempdir`,
147+
);
148+
}
149+
}
150+
151+
return this.capabilityStore.getWorkingDirectory(sessionId);
152+
}
153+
97154
/**
98155
* Handle a sampling request by forwarding it through the ACP agent.
99156
* Creates a new ACP session for each request (short-lived, isolated).
100-
* Uses the working directory stored in CapabilityStore (client root or tempdir).
157+
* Uses the working directory from client roots (preferred) or tempdir (fallback).
101158
*
102159
* SPEC-COMPLIANT SAMPLING-WITH-TOOLS:
103160
* When tools are provided, the agent may attempt to call them. Instead of
@@ -113,7 +170,7 @@ export class SamplingShim implements ISamplingShim {
113170
params: CreateMessageRequest["params"],
114171
): Promise<CreateMessageResult | CreateMessageResultWithTools> {
115172
const client = this.clients.get(sessionId);
116-
const cwd = this.capabilityStore.getWorkingDirectory(sessionId);
173+
const cwd = await this.resolveWorkingDirectory(sessionId);
117174

118175
if (!client) {
119176
throw new Error(`Sampling shim not initialized for session ${sessionId}`);
@@ -234,6 +291,8 @@ export class SamplingShim implements ISamplingShim {
234291
async close(sessionId: string): Promise<void> {
235292
const client = this.clients.get(sessionId);
236293

294+
this.rootsProviders.delete(sessionId);
295+
237296
if (client) {
238297
this.logger.debug(`Closing sampling shim for session ${sessionId}`);
239298
await client.close();
@@ -264,5 +323,6 @@ export class SamplingShim implements ISamplingShim {
264323

265324
await Promise.all(closePromises);
266325
this.clients.clear();
326+
this.rootsProviders.clear();
267327
}
268328
}

‎apps/gateway/src/types/interfaces.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,17 @@ export interface ISamplingShim {
217217
| import("@modelcontextprotocol/sdk/types.js").CreateMessageResultWithTools
218218
>;
219219

220+
/**
221+
* Register a callback that retrieves roots from the downstream client.
222+
* Called per-session so the shim can resolve a project root as cwd.
223+
*/
224+
setRootsProvider(
225+
sessionId: string,
226+
provider: () => Promise<
227+
import("@modelcontextprotocol/sdk/types.js").ListRootsResult
228+
>,
229+
): void;
230+
220231
/**
221232
* Close the ACP agent for a specific session.
222233
*/

0 commit comments

Comments
 (0)