Skip to content
Open
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
29 changes: 29 additions & 0 deletions apps/server/src/mcp/AcpMcpStdioBridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -517,4 +517,33 @@ describe("AcpMcpStdioBridge", () => {
expect(signal?.aborted).toBe(true);
}),
);

it.effect("forwards t3-tool-exposure when toolExposure is configured on the stdio bridge", () =>
Effect.gen(function* () {
const seenHeaders: Array<string | null> = [];
const input = new NodeStream.PassThrough();
const written: Array<string> = [];
const bridge = runAcpMcpStdioBridge({
endpoint: "http://127.0.0.1:1/mcp",
authorization: "Bearer bridge-test",
toolExposure: "deferred-proxy",
input,
output: {
write: (chunk: string) => {
written.push(chunk);
},
},
fetchImplementation: async (_url, init) => {
seenHeaders.push(
new Request("http://127.0.0.1:1/mcp", init).headers.get("t3-tool-exposure"),
);
return Response.json({ jsonrpc: "2.0", id: 1, result: { tools: [] } });
},
});
input.end(`${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" })}\n`);
yield* bridge;
expect(seenHeaders).toEqual(["deferred-proxy"]);
expect(written).toHaveLength(1);
}),
);
});
12 changes: 12 additions & 0 deletions apps/server/src/mcp/AcpMcpStdioBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpResponsePayloads";

import {
MCP_TOOL_EXPOSURE_HEADER,
type McpToolExposureMode,
parseMcpToolExposureMode,
} from "@t3tools/provider-core/server/mcpSession";

/** ACP mandates stdio MCP support; HTTP/SSE support varies. */

const JsonRpcError = Schema.Struct({ code: Schema.Number, message: Schema.String });
Expand Down Expand Up @@ -49,6 +55,7 @@ const MCP_PROTOCOL_VERSION = "2025-06-18";
export interface AcpMcpStdioBridgeOptions {
readonly endpoint: string;
readonly authorization: string;
readonly toolExposure?: McpToolExposureMode | undefined;
readonly input: NodeJS.ReadableStream;
readonly output: { write(chunk: string): unknown };
readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise<Response>;
Expand Down Expand Up @@ -247,6 +254,9 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect.
"content-type": "application/json",
accept: "application/json, text/event-stream",
authorization: options.authorization,
...(options.toolExposure === undefined
? {}
: { [MCP_TOOL_EXPOSURE_HEADER]: options.toolExposure }),
...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }),
},
Expand Down Expand Up @@ -374,10 +384,12 @@ export async function runAcpMcpCliFastPath(
return;
}
if (command === "acp-mcp-bridge") {
const toolExposure = parseMcpToolExposureMode(process.env.T3_ACP_MCP_TOOL_EXPOSURE);
await Effect.runPromise(
runAcpMcpStdioBridge({
endpoint,
authorization,
...(toolExposure === undefined ? {} : { toolExposure }),
input: process.stdin,
output: process.stdout,
}),
Expand Down
222 changes: 198 additions & 24 deletions apps/server/src/mcp/McpHttpServer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2131,26 +2131,56 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
providerInstanceId: ProviderInstanceId.make("copilot"),
},
client: undefined,
capabilities: new Set(["orchestration"]),
capabilities: new Set(["orchestration", "device"]),
issuedAt: 1,
});
const scopes = new Map([
["deferringToken", scopeFor("deferringToken")],
["proxyToken", scopeFor("proxyToken")],
["otherToken", scopeFor("otherToken")],
]);
const tool = (name: string, description: string) =>
Tool.make(name, {
description,
success: Schema.Struct({}),
parameters: Schema.Struct({ url: Schema.optional(Schema.String) }),
success: Schema.Struct({ ok: Schema.Boolean }),
failure: OrchestratorMcpFailure,
failureMode: "return",
});
const disabledTool = Tool.make("disabled_secret", {
description: "Hidden browser tool.",
success: Schema.Struct({ ok: Schema.Boolean }),
failure: OrchestratorMcpFailure,
failureMode: "return",
}).annotate(McpSchema.EnabledWhen, () => false);
const oversizedTool = Tool.make("oversized_budget_tool", {
description: "Budget boundary test tool with a giant schema.",
parameters: Schema.Struct({
payload: Schema.String.annotate({ description: "x".repeat(8_500) }),
}),
success: Schema.Struct({ ok: Schema.Boolean }),
failure: OrchestratorMcpFailure,
failureMode: "return",
});
const smallBudgetTool = Tool.make("small_budget_tool", {
description: "Budget boundary test tool with a small schema.",
parameters: Schema.Struct({ flag: Schema.optional(Schema.Boolean) }),
success: Schema.Struct({ ok: Schema.Boolean }),
failure: OrchestratorMcpFailure,
failureMode: "return",
});
const OptionalToolkit = Toolkit.make(
tool("delegate_task", "Delegates a task."),
tool("preview_open", "Opens a browser preview."),
tool("schedule_task", "Schedules a task."),
oversizedTool,
smallBudgetTool,
disabledTool,
);
const reads = McpToolAccess.reads(() => Effect.succeed({}));
const reads = McpToolAccess.reads(() => Effect.succeed({ ok: true }));
const pngBytes = new Uint8Array([
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1,
]);
const serverLayer = McpHttpServer.layerMcpTransport(
Layer.mergeAll(
McpHttpServer.toolkitRegistration(
Expand All @@ -2159,13 +2189,47 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
delegate_task: reads,
preview_open: reads,
schedule_task: reads,
oversized_budget_tool: reads,
small_budget_tool: reads,
disabled_secret: reads,
}),
),
McpHttpServer.layerDeviceToolkit,
McpHttpServer.layerToolSearch,
),
).pipe(
Layer.provide(ServerSettings.layerTest()),
Layer.provide(McpToolAccessTestkit.liveThreadsLayer),
Layer.provide(
Layer.mock(DeviceService.DeviceService)({
locateSession: () => Effect.succeedNone,
sessionsForThread: (tid) =>
Effect.succeed([
{
threadId: tid,
hostId: "local",
deviceId: DeviceId.make("phone"),
platform: "ios",
openedAt: "2026-10-23T00:00:00Z",
},
]),
screenshot: () =>
Effect.succeed({
device: {
hostId: "local",
id: DeviceId.make("phone"),
platform: "ios" as const,
name: "iPhone",
version: "18.0",
booted: true,
physical: false,
},
png: pngBytes,
}),
}),
),
Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-proxy-test-" })),
Layer.provide(
Layer.mock(McpSessionRegistry.McpSessionRegistry)({
resolve: (token) => Effect.succeed(scopes.get(token)),
Expand All @@ -2176,12 +2240,12 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
Layer.build,
);
const httpClient = yield* HttpClient.HttpClient;
const session = (token: string, deferred: boolean) =>
const session = (token: string, exposure?: "deferred" | "deferred-proxy") =>
Effect.gen(function* () {
const headers = {
accept: "application/json, text/event-stream",
authorization: `Bearer ${token}`,
...(deferred ? { "t3-tool-exposure": "deferred" } : {}),
...(exposure === undefined ? {} : { "t3-tool-exposure": exposure }),
};
const initialize = yield* httpClient.post("/mcp", {
headers,
Expand All @@ -2190,7 +2254,7 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
"application/json",
),
});
const rpc = (method: string, params: object) =>
const rpcRaw = (method: string, params: object) =>
httpClient
.post("/mcp", {
headers: {
Expand All @@ -2203,17 +2267,18 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
"application/json",
),
})
.pipe(
Effect.flatMap((response) => response.text),
// tool_search answers over SSE, after its list_changed notification.
Effect.map((text): unknown =>
text
.split("\n")
.filter((line) => line.startsWith("data: ") || line.startsWith("{"))
.map((line) => JSON.parse(line.replace(/^data: /u, "")) as { id?: number })
.find((message) => message.id === 2),
),
);
.pipe(Effect.flatMap((response) => response.text));
const rpc = (method: string, params: object) =>
rpcRaw(method, params).pipe(
// tool_search answers over SSE, after its list_changed notification.
Effect.map((text): unknown =>
text
.split("\n")
.filter((line) => line.startsWith("data: ") || line.startsWith("{"))
.map((line) => JSON.parse(line.replace(/^data: /u, "")) as { id?: number })
.find((message) => message.id === 2),
),
);
return {
listed: rpc("tools/list", {}).pipe(
Effect.map((body) =>
Expand All @@ -2222,25 +2287,134 @@ it.effect("lists optional tools to a deferring client only after tool_search loa
.sort(),
),
),
callRaw: (name: string, args: object) =>
rpcRaw("tools/call", { name, arguments: args }),
call: (name: string, args: object) =>
rpc("tools/call", { name, arguments: args }).pipe(
Effect.map((body) => (body as { result: { structuredContent?: unknown } }).result),
Effect.map(
(body) =>
body as {
readonly result?: {
readonly isError?: boolean;
readonly structuredContent?: unknown;
readonly content?: ReadonlyArray<{
readonly type: string;
readonly text?: string;
readonly mimeType?: string;
}>;
};
readonly error?: { readonly message: string };
},
),
),
};
});

const deferring = yield* session("deferringToken", true);
const other = yield* session("otherToken", false);
const deferring = yield* session("deferringToken", "deferred");
const proxying = yield* session("proxyToken", "deferred-proxy");
const other = yield* session("otherToken");
expect(yield* deferring.listed).toEqual(["delegate_task", "tool_search"]);
expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]);
expect(yield* proxying.listed).toEqual(["delegate_task", "tool_call", "tool_search"]);
expect(yield* other.listed).toEqual([
"delegate_task",
"device_close",
"device_list",
"device_open",
"device_screenshot",
"oversized_budget_tool",
"preview_open",
"schedule_task",
"small_budget_tool",
]);
// Unlisted tools stay callable.
expect((yield* deferring.call("schedule_task", {})).structuredContent).toEqual({});
expect((yield* deferring.call("schedule_task", {})).result?.structuredContent).toEqual({
ok: true,
});

// Dynamic deferred mode (Copilot): omits inputSchema and adds matches to tools/list.
expect(
(yield* deferring.call("tool_search", { query: "browser" })).structuredContent,
(yield* deferring.call("tool_search", { query: "browser" })).result?.structuredContent,
).toEqual({ tools: [{ name: "preview_open", description: "Opens a browser preview." }] });
expect(yield* deferring.listed).toEqual(["delegate_task", "preview_open", "tool_search"]);
expect(yield* other.listed).toEqual(["delegate_task", "preview_open", "schedule_task"]);

// Proxy deferred mode (Antigravity): returns inputSchema, skips disabled tools and list_changed, keeps fixed list.
const proxySearchRaw = yield* proxying.callRaw("tool_search", { query: "browser" });
expect(proxySearchRaw).not.toContain("notifications/tools/list_changed");
const proxySearch = yield* proxying.call("tool_search", { query: "browser" });
expect(proxySearch.result?.structuredContent).toEqual({
tools: [
{
name: "preview_open",
description: "Opens a browser preview.",
inputSchema: expect.objectContaining({ type: "object" }),
},
],
});
expect(yield* proxying.listed).toEqual(["delegate_task", "tool_call", "tool_search"]);

// An oversized schema falls back to name + description so the whole response stays <= 8 KB, while small matches keep schemas.
const budgetSearch = yield* proxying.call("tool_search", { query: "budget" });
const budgetPayload = budgetSearch.result?.structuredContent as {
readonly tools: ReadonlyArray<{
readonly name: string;
readonly description: string;
readonly inputSchema?: unknown;
}>;
};
expect(Buffer.byteLength(JSON.stringify(budgetPayload), "utf8")).toBeLessThanOrEqual(8_000);
expect(budgetPayload.tools).toEqual([
{
name: "oversized_budget_tool",
description: "Budget boundary test tool with a giant schema.",
},
{
name: "small_budget_tool",
description: "Budget boundary test tool with a small schema.",
inputSchema: expect.objectContaining({ type: "object" }),
},
]);

// tool_call invokes optional tools, preserves image content, blocks disabled/meta tools, and returns schema on bad args.
expect(
(yield* proxying.call("tool_call", { name: "schedule_task", arguments: {} })).result
?.structuredContent,
).toEqual({ ok: true });
// Core tools such as delegate_task also work through tool_call if the agent evicts them.
expect(
(yield* proxying.call("tool_call", { name: "delegate_task", arguments: {} })).result
?.structuredContent,
).toEqual({ ok: true });
const imageCall = yield* proxying.call("tool_call", {
name: "device_screenshot",
arguments: {},
});
expect(imageCall.result?.content).toEqual(
expect.arrayContaining([expect.objectContaining({ type: "image", mimeType: "image/png" })]),
);
const blockedMeta = yield* proxying.call("tool_call", { name: "tool_call", arguments: {} });
expect(blockedMeta.error?.message).toContain("Cannot invoke 'tool_call'");
const blockedDisabled = yield* proxying.call("tool_call", {
name: "disabled_secret",
arguments: {},
});
expect(blockedDisabled.error?.message).toContain("Tool 'disabled_secret' not found");
const badArgs = yield* proxying.call("tool_call", {
name: "preview_open",
arguments: { url: 123 },
});
expect(badArgs.result?.isError).toBe(true);
expect(badArgs.result?.content?.[0]?.text).toContain("Expected inputSchema:");
expect(yield* other.listed).toEqual([
"delegate_task",
"device_close",
"device_list",
"device_open",
"device_screenshot",
"oversized_budget_tool",
"preview_open",
"schedule_task",
"small_budget_tool",
]);
}),
).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
Loading
Loading