Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions packages/acp-bridge/src/bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11826,6 +11826,110 @@ describe('createAcpSessionBridge', () => {
});
});

describe('session-scoped runtime MCP servers', () => {
it('routes add and remove to the selected live session only', async () => {
const calls: Array<{
method: string;
params: Record<string, unknown>;
}> = [];
const factory: ChannelFactory = async () => {
const { clientStream, agentStream } = createInMemoryChannel();
const agent = new FakeAgent({
extMethodImpl: (method, params) => {
calls.push({ method, params });
if (method === SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeAdd) {
return Promise.resolve({
name: params['name'],
transport: 'sdk',
replaced: false,
shadowedSettings: false,
toolCount: 1,
originatorClientId: params['originatorClientId'],
});
}
if (method === SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeRemove) {
return Promise.resolve({
name: params['name'],
removed: true,
wasShadowingSettings: false,
originatorClientId: params['originatorClientId'],
});
}
return Promise.resolve({});
},
});
new AgentSideConnection(() => agent as Agent, agentStream);
return {
stream: clientStream,
exited: new Promise<
| { exitCode: number | null; signalCode: NodeJS.Signals | null }
| undefined
>(() => {}),
kill: async () => {},
killSync: () => {},
};
};
const bridge = makeBridge({
sessionScope: 'thread',
channelFactory: factory,
});
await bridge.spawnOrAttach({ workspaceCwd: WS_A });
const target = await bridge.spawnOrAttach({ workspaceCwd: WS_A });

await bridge.addSessionRuntimeMcpServer(
target.sessionId,
'channel-loop',
{ type: 'sdk' },
'daemon-channel',
);
await bridge.removeSessionRuntimeMcpServer(
target.sessionId,
'channel-loop',
'daemon-channel',
);

expect(calls.slice(-2)).toEqual([
{
method: SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeAdd,
params: {
sessionId: target.sessionId,
name: 'channel-loop',
config: { type: 'sdk' },
originatorClientId: 'daemon-channel',
},
},
{
method: SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeRemove,
params: {
sessionId: target.sessionId,
name: 'channel-loop',
originatorClientId: 'daemon-channel',
},
},
]);
await bridge.shutdown();
});

it('rejects an unknown session without falling back to a live channel', async () => {
const extMethodImpl = vi.fn().mockResolvedValue({});
const bridge = makeBridge({
channelFactory: async () => makeChannel({ extMethodImpl }).channel,
});
await bridge.spawnOrAttach({ workspaceCwd: WS_A });

await expect(
bridge.addSessionRuntimeMcpServer('missing-session', 'channel-loop', {
type: 'sdk',
}),
).rejects.toBeInstanceOf(SessionNotFoundError);
expect(extMethodImpl).not.toHaveBeenCalledWith(
SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeAdd,
expect.anything(),
);
await bridge.shutdown();
});
});

describe('removeRuntimeMcpServer (T2.8 #4514)', () => {
/**
* Build a channel factory whose ACP `extMethod` handler returns a
Expand Down
23 changes: 23 additions & 0 deletions packages/acp-bridge/src/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ import type {
BridgeSessionTranscriptPageRequest,
BridgeGenerationStreamEvent,
BridgeWorkspaceGenerationStreamEvent,
RuntimeMcpServerAddResult,
RuntimeMcpServerRemoveResult,
} from './bridgeTypes.js';
import type {
BridgeFreshSessionAdmissionContext,
Expand Down Expand Up @@ -8169,6 +8171,27 @@ export function createAcpSessionBridge(opts: BridgeOptions): AcpSessionBridge {
return response;
},

async addSessionRuntimeMcpServer(
sessionId,
name,
config,
originatorClientId,
) {
return requestSessionStatus<RuntimeMcpServerAddResult>(
sessionId,
SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeAdd,
{ name, config, originatorClientId },
);
},

async removeSessionRuntimeMcpServer(sessionId, name, originatorClientId) {
return requestSessionStatus<RuntimeMcpServerRemoveResult>(
sessionId,
SERVE_CONTROL_EXT_METHODS.sessionMcpRuntimeRemove,
{ name, originatorClientId },
);
},

async killSession(sessionId, opts) {
const entry = byId.get(sessionId);
if (!entry) return false;
Expand Down
84 changes: 84 additions & 0 deletions packages/acp-bridge/src/bridgeClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2834,6 +2834,90 @@ describe('BridgeClient — reverse tool channel (qwen/control/client_mcp/message
expect((result as { payload?: unknown }).payload).toBeDefined();
});

it('forwards the originating session id to the client MCP sender', async () => {
const contexts: unknown[] = [];
const sender: ClientMcpMessageSender = () => async (_payload, context) => {
contexts.push(context);
return { jsonrpc: '2.0', id: 1, result: {} };
};
const client = new BridgeClient(
(() => undefined) as never,
(() => undefined) as never,
{ request: thrower } as never,
0,
Infinity,
undefined,
undefined,
undefined,
sender,
);

await client.extMethod('qwen/control/client_mcp/message', {
server: 'channel-loop',
sessionId: 'session-channel-1',
payload: { jsonrpc: '2.0', id: 1, method: 'tools/list' },
});

expect(contexts).toEqual([{ sessionId: 'session-channel-1' }]);
});

it('rejects a malformed optional session id', async () => {
const sender: ClientMcpMessageSender = () => async () => ({
jsonrpc: '2.0',
id: 1,
result: {},
});
const client = new BridgeClient(
(() => undefined) as never,
(() => undefined) as never,
{ request: thrower } as never,
0,
Infinity,
undefined,
undefined,
undefined,
sender,
);

await expect(
client.extMethod('qwen/control/client_mcp/message', {
server: 'channel-loop',
sessionId: '',
payload: { jsonrpc: '2.0', id: 1, method: 'tools/list' },
}),
).rejects.toMatchObject({ code: -32602 });
});

it('rejects a session id owned by another ACP channel', async () => {
const send = vi.fn().mockResolvedValue({
jsonrpc: '2.0',
id: 1,
result: {},
});
const sender: ClientMcpMessageSender = () => send;
const client = new BridgeClient(
(() => undefined) as never,
(() => undefined) as never,
{ request: thrower } as never,
0,
Infinity,
undefined,
undefined,
undefined,
sender,
() => false,
);

await expect(
client.extMethod('qwen/control/client_mcp/message', {
server: 'channel-loop',
sessionId: 'foreign-session',
payload: { jsonrpc: '2.0', id: 1, method: 'tools/list' },
}),
).rejects.toMatchObject({ code: -32602 });
expect(send).not.toHaveBeenCalled();
});

it('rejects (invalidParams) when the named server is not connected', async () => {
const registrar = new ClientMcpRegistrar({ sendFrame: () => {} });
// No registerServer call — the lookup returns undefined.
Expand Down
21 changes: 20 additions & 1 deletion packages/acp-bridge/src/bridgeClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1300,7 +1300,26 @@ export class BridgeClient implements Client {
`client-hosted MCP server '${server}' is not currently connected`,
);
}
const response = await send(payload);
const sessionId = params['sessionId'];
if (
sessionId !== undefined &&
(typeof sessionId !== 'string' || sessionId.length === 0)
) {
throw RequestError.invalidParams(
undefined,
'`sessionId` must be a non-empty string when provided',
);
}
if (typeof sessionId === 'string' && !this.ownsSession(sessionId)) {
throw RequestError.invalidParams(
undefined,
`Session not owned by this channel: ${sessionId}`,
);
}
const response = await send(
payload,
typeof sessionId === 'string' ? { sessionId } : undefined,
);
return { payload: response as Record<string, unknown> };
}

Expand Down
8 changes: 7 additions & 1 deletion packages/acp-bridge/src/bridgeOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -464,9 +464,15 @@ export interface BridgeOptions {
* package free of an MCP-SDK dependency; the serve layer passes a
* `JSONRPCMessage`.
*/
export interface ClientMcpMessageContext {
sessionId?: string;
}

export type ClientMcpMessageSender = (
serverName: string,
) => ((payload: unknown) => Promise<unknown>) | undefined;
) =>
| ((payload: unknown, context?: ClientMcpMessageContext) => Promise<unknown>)
| undefined;

/** Ceiling on a sub-session prompt arriving over `extMethod`. The child is a
* separate process, so this is a trust boundary — mirrors the scheduled-task
Expand Down
69 changes: 45 additions & 24 deletions packages/acp-bridge/src/bridgeTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -774,6 +774,30 @@ export type BridgeWorkspaceGenerationNotificationEvent = Exclude<
{ type: 'done' }
>;

export type RuntimeMcpServerAddResult =
| {
name: string;
transport: string;
replaced: boolean;
shadowedSettings: boolean;
toolCount: number;
originatorClientId: string;
}
| {
name: string;
skipped: true;
reason: 'budget_warning_only' | 'runtime_name_conflict';
};

export type RuntimeMcpServerRemoveResult =
| {
name: string;
removed: true;
wasShadowingSettings: boolean;
originatorClientId: string;
}
| { name: string; skipped: true; reason: 'not_present' };

export interface AcpSessionBridge {
/** Read-only daemon diagnostics for status endpoints. */
getDaemonStatusSnapshot(): BridgeDaemonStatusSnapshot;
Expand Down Expand Up @@ -1392,21 +1416,7 @@ export interface AcpSessionBridge {
name: string,
config: Record<string, unknown>,
originatorClientId?: string,
): Promise<
| {
name: string;
transport: string;
replaced: boolean;
shadowedSettings: boolean;
toolCount: number;
originatorClientId: string;
}
| {
name: string;
skipped: true;
reason: 'budget_warning_only' | 'runtime_name_conflict';
}
>;
): Promise<RuntimeMcpServerAddResult>;

/**
* Remove a runtime MCP server through the ACP child's
Expand All @@ -1419,15 +1429,26 @@ export interface AcpSessionBridge {
removeRuntimeMcpServer(
name: string,
originatorClientId?: string,
): Promise<
| {
name: string;
removed: true;
wasShadowingSettings: boolean;
originatorClientId: string;
}
| { name: string; skipped: true; reason: 'not_present' }
>;
): Promise<RuntimeMcpServerRemoveResult>;

/**
* Add a runtime MCP server to one live session only. This does not mutate
* workspace bootstrap state, affect sibling sessions, or emit a workspace
* event.
*/
addSessionRuntimeMcpServer(
sessionId: string,
name: string,
config: Record<string, unknown>,
originatorClientId?: string,
): Promise<RuntimeMcpServerAddResult>;

/** Remove a runtime MCP server from one live session only. */
removeSessionRuntimeMcpServer(
sessionId: string,
name: string,
originatorClientId?: string,
): Promise<RuntimeMcpServerRemoveResult>;

manageMcpServer(
serverName: string,
Expand Down
2 changes: 2 additions & 0 deletions packages/acp-bridge/src/status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,8 @@ export const SERVE_CONTROL_EXT_METHODS = {
* `{ sessionId }`; result: `{ active: ActiveGoalView | null }`.
*/
sessionGoalGet: 'qwen/control/session/goal/get',
sessionMcpRuntimeAdd: 'qwen/control/session/mcp/runtime-add',
sessionMcpRuntimeRemove: 'qwen/control/session/mcp/runtime-remove',
workspaceMcpRuntimeAdd: 'qwen/control/workspace/mcp/runtime-add',
workspaceMcpRuntimeRemove: 'qwen/control/workspace/mcp/runtime-remove',
workspaceReload: 'qwen/control/workspace/reload',
Expand Down
Loading
Loading