diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.test.ts b/apps/server/src/mcp/AcpMcpStdioBridge.test.ts index f1403e1971f73..4b79ea550c917 100644 --- a/apps/server/src/mcp/AcpMcpStdioBridge.test.ts +++ b/apps/server/src/mcp/AcpMcpStdioBridge.test.ts @@ -490,4 +490,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 = []; + const input = new NodeStream.PassThrough(); + const written: Array = []; + 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); + }), + ); }); diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.ts index 11bd819f4b88b..d3a1d32dd9413 100644 --- a/apps/server/src/mcp/AcpMcpStdioBridge.ts +++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts @@ -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. */ export class AcpMcpBridgeError extends Schema.TaggedError()( @@ -40,6 +46,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; @@ -236,6 +243,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 }), }, @@ -363,10 +373,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, }), diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 3842d1a4b3bf2..060104975de5b 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -1998,26 +1998,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( @@ -2026,13 +2056,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)), @@ -2043,12 +2107,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, @@ -2057,7 +2121,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: { @@ -2070,17 +2134,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) => @@ -2089,25 +2154,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)), ); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 4c9d9dca1081a..f83d6a3402a8b 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -6,6 +6,7 @@ import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -52,7 +53,10 @@ import { advertisedJsonSchema } from "./advertisedJsonSchema.ts"; import * as McpInvocationContext from "./McpInvocationContext.ts"; import * as McpToolAccess from "./McpToolAccess.ts"; import * as McpToolExposure from "./McpToolExposure.ts"; -import { MCP_TOOL_EXPOSURE_HEADER } from "@t3tools/provider-core/server/mcpSession"; +import { + MCP_TOOL_EXPOSURE_HEADER, + parseMcpToolExposureMode, +} from "@t3tools/provider-core/server/mcpSession"; import * as OrchestratorMcpService from "./OrchestratorMcpService.ts"; import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts"; import * as PreviewControlsHandlers from "./toolkits/previewControls/handlers.ts"; @@ -337,7 +341,14 @@ const makeMcpAuthMiddleware = Effect.gen(function* () { limited.thread === undefined ? undefined : yield* Cache.get(forgeOfThread, limited.thread.threadId); - return { ...limited, linkedEnvironments, origin, ...(forge === undefined ? {} : { forge }) }; + const toolExposure = parseMcpToolExposureMode(request.headers[MCP_TOOL_EXPOSURE_HEADER]); + return { + ...limited, + linkedEnvironments, + origin, + ...(forge === undefined ? {} : { forge }), + ...(toolExposure === undefined ? {} : { toolExposure }), + }; }); // Untraced: a span here would wrap the tool call; the HTTP server span already covers it. return Effect.fnUntraced(function* (httpEffect) { @@ -1397,22 +1408,177 @@ export const layerTools = Layer.mergeAll( layerMessageToolkit, ); +const enabledWhenFallbackClient = { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "t3-code", version: packageJson.version }, +} as const; + +const isToolRegistrationEnabled = ( + annotations: Context.Context, + initializePayload?: (typeof McpSchema.Initialize.payloadSchema)["Type"], +): boolean => { + const enabledWhen = Context.getOrUndefined(annotations, McpSchema.EnabledWhen); + if (enabledWhen === undefined) return true; + if (initializePayload !== undefined) return enabledWhen(initializePayload); + const fiber = Fiber.getCurrent(); + const client = fiber + ? Context.getOrUndefined(fiber.context, McpSchema.McpServerClient) + : undefined; + return enabledWhen(client?.initializePayload ?? enabledWhenFallbackClient); +}; + const layerToolExposure = Layer.effect( McpToolExposure.McpToolExposure, Effect.gen(function* () { const server = yield* McpServer.McpServer; return McpToolExposure.make( () => - server.tools.map(({ tool }) => ({ name: tool.name, description: tool.description ?? "" })), + server.tools.map(({ tool, annotations }) => ({ + name: tool.name, + description: tool.description ?? "", + inputSchema: tool.inputSchema, + isEnabled: () => isToolRegistrationEnabled(annotations), + })), () => server.notifications["notifications/tools/list_changed"]({}), ); }), ); +const isMcpInvalidParams = Schema.is(McpSchema.InvalidParams); +const isMcpInternalError = Schema.is(McpSchema.InternalError); + +/** + * Runs a deferred T3 MCP tool by name for ACP harnesses that freeze their tool list + * per turn. Registered directly on `McpServer` so image results pass through intact. + */ +const registerToolCall = Effect.fn("McpHttpServer.registerToolCall")(function* () { + const server = yield* McpServer.McpServer; + const annotations = Context.make( + McpSchema.EnabledWhen, + McpInvocationContext.hiddenFromOutsideClients, + ); + yield* server.addTool({ + tool: new McpSchema.Tool({ + name: McpToolExposure.TOOL_CALL, + description: + "Invoke any T3 Code MCP tool by exact name (find schemas with tool_search first).", + inputSchema: { + type: "object", + properties: { + name: { type: "string", description: "Exact T3 MCP tool name." }, + arguments: { type: "object", description: "Arguments object for that tool." }, + }, + required: ["name"], + }, + annotations: { + readOnlyHint: false, + openWorldHint: false, + }, + }), + annotations, + handle: (payload) => + Effect.withFiber((fiber) => { + const invocation = Context.getOrUndefined( + fiber.context, + McpInvocationContext.McpInvocationContext, + ); + if (invocation?.thread === undefined) { + return Effect.fail( + new McpSchema.InvalidParams({ + message: "tool_call requires an active T3 thread session.", + }), + ); + } + const record = + typeof payload === "object" && payload !== null && !Array.isArray(payload) + ? (payload as Record) + : undefined; + const name = typeof record?.name === "string" ? record.name.trim() : ""; + if (name.length === 0) { + return Effect.fail(new McpSchema.InvalidParams({ message: "name is required." })); + } + if (name === McpToolExposure.TOOL_CALL || name === McpToolExposure.TOOL_SEARCH) { + return Effect.fail( + new McpSchema.InvalidParams({ message: `Cannot invoke '${name}' via tool_call.` }), + ); + } + const rawArgs = record?.arguments; + if ( + rawArgs !== undefined && + (typeof rawArgs !== "object" || rawArgs === null || Array.isArray(rawArgs)) + ) { + return Effect.fail( + new McpSchema.InvalidParams({ message: "arguments must be a JSON object." }), + ); + } + const requestContext = Context.getOrUndefined(fiber.context, McpSchema.McpRequestContext); + const client = + Context.getOrUndefined(fiber.context, McpSchema.McpServerClient) ?? + McpSchema.McpServerClient.of({ + clientId: 0, + clientCapabilities: requestContext?.clientCapabilities ?? {}, + clientInfo: requestContext?.clientInfo ?? enabledWhenFallbackClient.clientInfo, + protocolVersion: enabledWhenFallbackClient.protocolVersion, + initializePayload: { + protocolVersion: enabledWhenFallbackClient.protocolVersion, + capabilities: requestContext?.clientCapabilities ?? {}, + clientInfo: requestContext?.clientInfo ?? enabledWhenFallbackClient.clientInfo, + }, + getClient: Effect.die("Stateless MCP requests do not expose a client RPC handle."), + }); + return server + .callTool({ + name, + arguments: (rawArgs as Record | undefined) ?? {}, + }) + .pipe( + Effect.provideService(McpSchema.McpServerClient, client), + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), + Effect.catch( + ( + error, + ): Effect.Effect< + McpSchema.CallToolResult, + McpSchema.InternalError | McpSchema.InvalidParams + > => { + if (isMcpInvalidParams(error)) { + const entry = server.tools.find( + (candidate) => + candidate.tool.name === name && + isToolRegistrationEnabled(candidate.annotations, client.initializePayload), + ); + if (entry !== undefined) { + return Effect.succeed( + new McpSchema.CallToolResult({ + isError: true, + content: [ + { + type: "text", + text: `${error.message}\nExpected inputSchema: ${encodeJsonText(entry.tool.inputSchema)}`, + }, + ], + }), + ); + } + return Effect.fail(error); + } + return Effect.fail( + isMcpInternalError(error) + ? error + : new McpSchema.InternalError({ message: error.message }), + ); + }, + ), + ); + }), + }); +}); + /** - * A provider session that sends `MCP_TOOL_EXPOSURE_HEADER: deferred` lists only - * the direct tools and what its `tool_search` calls loaded. Calls are never - * gated, and every other client lists everything but `tool_search`. + * A provider session sending `MCP_TOOL_EXPOSURE_HEADER` (`deferred` or `deferred-proxy`) + * lists only its core set (plus any tools dynamically loaded in `deferred` mode). + * Calls are never gated, and every other client lists everything except `tool_search`/`tool_call`. */ const layerDeferredListing = McpServer.visibility( Effect.gen(function* () { @@ -1422,18 +1588,20 @@ const layerDeferredListing = McpServer.visibility( if (method !== "tools/list") return true; const scope = yield* Effect.serviceOption(McpInvocationContext.McpInvocationContext); const providerSessionId = Option.getOrUndefined(scope)?.thread?.providerSessionId; - if (headers[MCP_TOOL_EXPOSURE_HEADER] !== "deferred" || providerSessionId === undefined) { - return target !== McpToolExposure.TOOL_SEARCH; + const mode = parseMcpToolExposureMode(headers[MCP_TOOL_EXPOSURE_HEADER]); + if (mode === undefined || providerSessionId === undefined) { + return target !== McpToolExposure.TOOL_SEARCH && target !== McpToolExposure.TOOL_CALL; } - return exposure.isListed(providerSessionId, target); + return exposure.isListed(providerSessionId, target, mode); }); }), { global: true }, ); -/** Outside layerTools: the clients its budget measures never list `tool_search`. */ +/** Outside layerTools: the clients its budget measures never list `tool_search` or `tool_call`. */ export const layerToolSearch = Layer.mergeAll( toolkitRegistration(ToolSearchToolkit, ToolSearchHandlers.layer), + Layer.effectDiscard(registerToolCall()), layerDeferredListing, ).pipe(Layer.provide(layerToolExposure)); diff --git a/apps/server/src/mcp/McpInvocationContext.ts b/apps/server/src/mcp/McpInvocationContext.ts index 893c17f23311b..bd3bc23749415 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -14,6 +14,7 @@ import * as Context from "effect/Context"; import type * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; +import type { McpToolExposureMode } from "@t3tools/provider-core/server/mcpSession"; import { formatThreadLink, hostedThreadLink } from "@t3tools/shared/threadLinks"; const ALL_MCP_CAPABILITIES = [ @@ -159,6 +160,8 @@ export interface McpInvocationScope { readonly origin?: string | undefined; /** False when the calling thread's project is on no forge T3 reads; `/mcp` reads it per request. */ readonly forge?: boolean; + /** Set from `t3-tool-exposure` when an ACP client defers optional T3 MCP tools. */ + readonly toolExposure?: McpToolExposureMode | undefined; } /** diff --git a/apps/server/src/mcp/McpToolExposure.ts b/apps/server/src/mcp/McpToolExposure.ts index cb1ff850717d1..f133875a7f5f5 100644 --- a/apps/server/src/mcp/McpToolExposure.ts +++ b/apps/server/src/mcp/McpToolExposure.ts @@ -1,7 +1,9 @@ +import type { McpToolExposureMode } from "@t3tools/provider-core/server/mcpSession"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; export const TOOL_SEARCH = "tool_search"; +export const TOOL_CALL = "tool_call"; /** What a deferring client lists before it searches. Pi's extension declares the same three. */ const DIRECT_TOOLS: ReadonlySet = new Set([ @@ -11,28 +13,48 @@ const DIRECT_TOOLS: ReadonlySet = new Set([ TOOL_SEARCH, ]); +const PROXY_DIRECT_TOOLS: ReadonlySet = new Set([...DIRECT_TOOLS, TOOL_CALL]); + const MAX_RESULTS = 10; +// Antigravity caps inline MCP tool results around 10 KB; stay comfortably under it so JSON schemas never truncate. +const MAX_PROXY_SCHEMA_BYTES = 8_000; // Sessions that ended are never reported here, so keep only the newest. const MAX_SESSIONS = 256; export interface ListedTool { readonly name: string; readonly description: string; + readonly inputSchema?: unknown; +} + +export interface SearchableTool { + readonly name: string; + readonly description: string; + readonly inputSchema: unknown; + readonly isEnabled?: () => boolean; } export class McpToolExposure extends Context.Service< McpToolExposure, { - /** Finds tools for the query and lists them to the session from now on. */ + /** Finds tools for the query and, in dynamic mode, lists them to the session from now on. */ readonly search: ( providerSessionId: string, query: string, + options?: { readonly mode?: McpToolExposureMode | undefined }, ) => Effect.Effect>; - readonly isListed: (providerSessionId: string, tool: string) => boolean; + readonly isListed: ( + providerSessionId: string, + tool: string, + mode?: McpToolExposureMode, + ) => boolean; } >()("t3/mcp/McpToolExposure") {} -const score = (tool: ListedTool, terms: ReadonlyArray) => { +const score = ( + tool: Pick, + terms: ReadonlyArray, +) => { const name = tool.name.toLowerCase(); const description = tool.description.toLowerCase(); let total = 0; @@ -44,8 +66,16 @@ const score = (tool: ListedTool, terms: ReadonlyArray) => { return total; }; +const utf8Bytes = (value: unknown): number => { + try { + return Buffer.byteLength(JSON.stringify(value) ?? "", "utf8"); + } catch { + return Number.POSITIVE_INFINITY; + } +}; + export const make = ( - tools: () => ReadonlyArray, + tools: () => ReadonlyArray, announceListChanged: () => Effect.Effect, ) => { const loaded = new Map>(); @@ -60,18 +90,50 @@ export const make = ( } }; return McpToolExposure.of({ - search: Effect.fn("McpToolExposure.search")(function* (providerSessionId, query) { + search: Effect.fn("McpToolExposure.search")(function* (providerSessionId, query, options) { const terms = query .toLowerCase() .split(/[^a-z0-9_]+/u) .filter(Boolean); const found = tools() - .filter((tool) => tool.name !== TOOL_SEARCH) + .filter( + (tool) => + tool.name !== TOOL_SEARCH && + tool.name !== TOOL_CALL && + (tool.isEnabled === undefined || tool.isEnabled()), + ) .map((tool) => ({ tool, score: score(tool, terms) })) .filter((match) => match.score > 0) .sort((a, b) => b.score - a.score) .slice(0, MAX_RESULTS) .map((match) => match.tool); + if (options?.mode === "deferred-proxy") { + const results: Array = []; + for (const tool of found) { + const withSchema: ListedTool = { + name: tool.name, + description: tool.description, + inputSchema: tool.inputSchema, + }; + if (utf8Bytes({ tools: [...results, withSchema] }) <= MAX_PROXY_SCHEMA_BYTES) { + results.push(withSchema); + continue; + } + const compact: ListedTool = { name: tool.name, description: tool.description }; + if (utf8Bytes({ tools: [...results, compact] }) <= MAX_PROXY_SCHEMA_BYTES) { + results.push(compact); + continue; + } + if (results.length === 0) { + results.push({ + name: tool.name, + description: `${tool.description.slice(0, 200)} (Truncated: exceeds response budget.)`, + }); + } + break; + } + return results; + } if (found.length > 0) { load( providerSessionId, @@ -79,9 +141,11 @@ export const make = ( ); yield* announceListChanged(); } - return found; + return found.map(({ name, description }) => ({ name, description })); }), - isListed: (providerSessionId, tool) => - DIRECT_TOOLS.has(tool) || loaded.get(providerSessionId)?.has(tool) === true, + isListed: (providerSessionId, tool, mode = "deferred") => + mode === "deferred-proxy" + ? PROXY_DIRECT_TOOLS.has(tool) + : DIRECT_TOOLS.has(tool) || loaded.get(providerSessionId)?.has(tool) === true, }); }; diff --git a/apps/server/src/mcp/toolkits/toolSearch/handlers.ts b/apps/server/src/mcp/toolkits/toolSearch/handlers.ts index 649069fbc1adb..30721c77c5111 100644 --- a/apps/server/src/mcp/toolkits/toolSearch/handlers.ts +++ b/apps/server/src/mcp/toolkits/toolSearch/handlers.ts @@ -8,11 +8,17 @@ import { ToolSearchToolkit } from "./tools.ts"; export const layer = McpToolAccess.toLayer(ToolSearchToolkit, { tool_search: McpToolAccess.readsAsCaller(({ query }) => Effect.gen(function* () { - const { thread } = yield* McpInvocationContext.McpInvocationContext.pipe( - Effect.flatMap((scope) => McpInvocationContext.requireThreadScope(scope, "tool_search")), + const scope = yield* McpInvocationContext.McpInvocationContext.pipe( + Effect.flatMap((current) => + McpInvocationContext.requireThreadScope(current, "tool_search"), + ), ); const exposure = yield* McpToolExposure.McpToolExposure; - return { tools: yield* exposure.search(thread.providerSessionId, query) }; + return { + tools: yield* exposure.search(scope.thread.providerSessionId, query, { + mode: scope.toolExposure, + }), + }; }), ), }); diff --git a/apps/server/src/mcp/toolkits/toolSearch/tools.ts b/apps/server/src/mcp/toolkits/toolSearch/tools.ts index 74741ccca557d..33b6e92825090 100644 --- a/apps/server/src/mcp/toolkits/toolSearch/tools.ts +++ b/apps/server/src/mcp/toolkits/toolSearch/tools.ts @@ -10,7 +10,13 @@ const ToolSearchTool = Tool.make(McpToolExposure.TOOL_SEARCH, { "Load T3 Code tools you do not have yet, then call them by name. Search by name or purpose: threads (t3_thread_*), projects (t3_project_*), worktrees, preview_* browser, device_*, html_preview/html_render, schedule_task, pull requests and guides, attachments, request_secret, environment links. Exact names work too.", parameters: Schema.Struct({ query: Schema.String.check(Schema.isMaxLength(500)) }), success: Schema.Struct({ - tools: Schema.Array(Schema.Struct({ name: Schema.String, description: Schema.String })), + tools: Schema.Array( + Schema.Struct({ + name: Schema.String, + description: Schema.String, + inputSchema: Schema.optional(Schema.Unknown), + }), + ), }), failure: OrchestratorMcpFailure, failureMode: "return", diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 55b313a9d3adc..6ab6c102ad94f 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1617,6 +1617,27 @@ describe("AcpRegistryAdapterV2", () => { new: stdio("Bearer opened-token"), load: stdio("Bearer rotated-token"), }); + // Local agy / antigravity commands defer optional tools through tool_call, as the Antigravity provider does. + const agyStdio = stdio("Bearer opened-token"); + const expectedAgyStdio = [ + { + ...agyStdio[0], + env: [...agyStdio[0]!.env, { name: "T3_ACP_MCP_TOOL_EXPOSURE", value: "deferred-proxy" }], + }, + ]; + assert.deepEqual( + (yield* sessionMcpServers({ source: "local", commandPath: "agy", commandArgs: ["acp"] })) + .new, + expectedAgyStdio, + ); + assert.deepEqual( + (yield* sessionMcpServers({ + source: "local", + commandPath: "antigravity", + commandArgs: ["acp"], + })).new, + expectedAgyStdio, + ); // Command Code cannot start the stdio bridge on Windows: it spawns MCP commands through // cmd.exe, which splits the unquoted T3 executable path at the space. const commandCode = { diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index fca472c6c433e..302687c62deca 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts @@ -3,6 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import { ChatFileAttachment, + EnvironmentId, MessageId, NodeId, ProjectId, @@ -704,6 +705,15 @@ describe("AntigravityAdapterV2 html_render pages", () => { let sessionUpdate: Parameters[0] | undefined; const instanceId = ProviderInstanceId.make("antigravity-html-render-test"); const threadId = ThreadId.make("thread-antigravity-html-render"); + yield* mcpSessions.set({ + environmentId: EnvironmentId.make("env-antigravity-html-render"), + threadId, + providerSessionId: ProviderSessionId.make("provider-session-antigravity-html-render"), + providerInstanceId: instanceId, + endpoint: "http://127.0.0.1:3773/mcp", + authorizationHeader: "Bearer antigravity-html-render-token", + browserToolsAvailable: true, + }); const page = (name: string) => ({ attachmentId: `${threadId}-${name}-html`, title: "Revenue", @@ -719,11 +729,26 @@ describe("AntigravityAdapterV2 html_render pages", () => { title: "Telemetry", height: 411, }; + const proxied = { + html: "

Proxied chart

", + title: "Proxied", + height: 300, + }; + let capturedMcpServers: + | { + readonly stdio: ReadonlyArray; + readonly http: ReadonlyArray; + } + | undefined; const adapter = yield* makeAntigravityAdapterV2({ instanceId, selfInvocation: yield* resolveSelfInvocation(), - makeRuntime: (input) => - makeAntigravityAcpRuntime({ + makeRuntime: (input) => { + capturedMcpServers = { + stdio: input.mcpServers ?? [], + http: input.httpMcpServers ?? [], + }; + return makeAntigravityAcpRuntime({ ...input, childProcessSpawner, spawn: { @@ -850,10 +875,30 @@ describe("AntigravityAdapterV2 html_render pages", () => { toolCallId: "agy-1.5.8", status: "completed", }); + // Deferred-proxy calls wrap html_render inside `tool_call`. + yield* send({ + sessionUpdate: "tool_call", + toolCallId: "tool-call-proxy", + title: "Run mcp_t3-code_tool_call", + kind: "other", + status: "in_progress", + rawInput: { + name: "html_render", + arguments: proxied, + toolSummary: "Render proxied", + }, + }); + yield* mcpSessions.recordHtmlRender(threadId, proxied, page("tool-call-proxy")); + yield* send({ + sessionUpdate: "tool_call_update", + toolCallId: "tool-call-proxy", + status: "completed", + }); return { stopReason: "end_turn" as const }; }), })), - ), + ); + }, withProcess: (_stop, task) => task, defaultModel: Effect.undefined, }); @@ -975,7 +1020,7 @@ describe("AntigravityAdapterV2 html_render pages", () => { ), [page("report"), page("report"), page("replacement"), page("replacement")], ); - for (const name of ["failed-retry", "error-retry", "agy-1.5.8"]) { + for (const name of ["failed-retry", "error-retry", "agy-1.5.8", "tool-call-proxy"]) { assert.deepEqual(tool(name), { status: "completed", toolName: "t3-code.html_render", @@ -987,6 +1032,35 @@ describe("AntigravityAdapterV2 html_render pages", () => { assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, failed), undefined); assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, errored), undefined); assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, telemetry), undefined); + assert.strictEqual(yield* mcpSessions.takeHtmlRender(threadId, proxied), undefined); + assert.isDefined(capturedMcpServers); + const stdioServer = capturedMcpServers!.stdio[0]; + const httpServer = capturedMcpServers!.http[0]; + const stdioEnv = + stdioServer !== undefined && !("type" in stdioServer) ? (stdioServer.env ?? []) : []; + const httpHeaders = + httpServer !== undefined && + "type" in httpServer && + httpServer.type === "http" && + Array.isArray(httpServer.headers) + ? httpServer.headers + : []; + assert.isTrue( + stdioEnv.some( + (entry) => entry.name === "T3_ACP_MCP_TOOL_EXPOSURE" && entry.value === "deferred-proxy", + ), + ); + assert.isTrue( + httpHeaders.some( + (entry) => + typeof entry === "object" && + entry !== null && + "name" in entry && + entry.name === "t3-tool-exposure" && + "value" in entry && + entry.value === "deferred-proxy", + ), + ); }).pipe(Effect.provide(layerSession)), ); }); diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts index 3f629c813b615..4e798e865c078 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -222,6 +222,8 @@ export function makeAntigravityAcpAdapterFlavor( supportsNativeGoals: options.supportsNativeGoals ?? Effect.succeed(false), // Agents that advertise HTTP MCP skip the stdio bridge process; others keep stdio. mcpOverHttp: true, + // Antigravity freezes its toolbox per turn, so optional T3 tools run through `tool_call`. + deferMcpTools: "proxy", sessionCarriesPullRequestLinking: antigravityAppendsSystemPrompt, makeRuntime, buildAttachmentPrompt: ({ text, attachments, resolveAttachmentPath, promptCapabilities }) => diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 8eb5dbb30b8cc..ece9b3a445db8 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -199,7 +199,9 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu const isDevin = registryAgentId === "devin"; const isAntigravityCli = options.settings.source === "local" && - /^agy(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""); + /^(?:agy|antigravity)(?:\.(?:exe|cmd|bat))?$/i.test( + options.settings.commandPath.split(/[\\/]/).pop() ?? "", + ); const isOmp = options.settings.source === "local" && /^omp(\.exe|\.cmd)?$/i.test(options.settings.commandPath.split(/[\\/]/).pop() ?? ""); @@ -273,7 +275,9 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu : AcpProviderCapabilitiesV2, customModels: readCustomModelEntries(options.settings.customModels).map((entry) => entry.slug), compactViaAdvertisedCommand: true, - ...(isAntigravityCli ? { wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true } : {}), + ...(isAntigravityCli + ? { wakeOnDetachedRequest: true, replyEndsWithUsageUpdate: true, deferMcpTools: "proxy" } + : {}), promptFailure: (cause) => acpRegistryPromptFailure(isVibe ? "mistral-vibe" : registryAgentId, cause), ...(isDroid diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index a712d40629e60..12af4856f5830 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -415,8 +415,11 @@ export interface AcpAdapterV2Flavor { EffectAcpSchema.InitializeRequest["clientCapabilities"] >["_meta"]; readonly mcpOverHttp?: boolean; - /** The agent has no tool search of its own, so T3 lists optional tools on demand. */ - readonly deferMcpTools?: boolean; + /** + * The agent has no tool search of its own, so T3 lists optional tools on demand. + * `"proxy"` keeps a fixed core set plus `tool_search` and `tool_call` for agents that freeze tools per turn. + */ + readonly deferMcpTools?: boolean | "proxy"; readonly normalizeSessionUpdate?: ( notification: EffectAcpSchema.SessionNotification, ) => EffectAcpSchema.SessionNotification; @@ -1004,6 +1007,15 @@ interface AcpMcpContext { readonly processEnvironment?: NodeJS.ProcessEnv; readonly endpoint?: string; readonly authorization?: string; + /** Only proxy mode reaches the stdio and MCP-over-ACP bridges; Copilot lists every tool there. */ + readonly bridgeToolExposure?: McpProviderSession.McpToolExposureMode; +} + +function mcpToolExposureMode( + deferMcpTools: boolean | "proxy" | undefined, +): McpProviderSession.McpToolExposureMode | undefined { + if (deferMcpTools === "proxy") return "deferred-proxy"; + return deferMcpTools === true ? "deferred" : undefined; } // A GUI-subsystem executable (packaged Windows desktop) does not hold the console, so PowerShell @@ -1043,12 +1055,14 @@ function acpMcpContext( session: McpProviderSession.McpProviderSessionConfig | undefined, self: SelfInvocation, mcpOverHttp: boolean | undefined, - deferMcpTools: boolean | undefined, + deferMcpTools: boolean | "proxy" | undefined, callLauncher: string | undefined, ): AcpMcpContext { if (session === undefined) { return { servers: [], acpServers: [], httpServers: [] }; } + const exposure = mcpToolExposureMode(deferMcpTools); + const bridgeToolExposure = exposure === "deferred-proxy" ? exposure : undefined; // codex-acp 1.2.0 and pi-acp drop injected HTTP servers, so HTTP is opt-in per flavor. return { servers: [ @@ -1060,6 +1074,9 @@ function acpMcpContext( { name: "ELECTRON_RUN_AS_NODE", value: "1" }, { name: "T3_ACP_MCP_ENDPOINT", value: session.endpoint }, { name: "T3_ACP_MCP_AUTHORIZATION", value: session.authorizationHeader }, + ...(bridgeToolExposure === undefined + ? [] + : [{ name: "T3_ACP_MCP_TOOL_EXPOSURE", value: bridgeToolExposure }]), ], }, ], @@ -1073,15 +1090,16 @@ function acpMcpContext( url: session.endpoint, headers: [ { name: "Authorization", value: session.authorizationHeader }, - ...(deferMcpTools === true - ? [{ name: McpProviderSession.MCP_TOOL_EXPOSURE_HEADER, value: "deferred" }] - : []), + ...(exposure === undefined + ? [] + : [{ name: McpProviderSession.MCP_TOOL_EXPOSURE_HEADER, value: exposure }]), ], }, ] : [], endpoint: session.endpoint, authorization: session.authorizationHeader, + ...(bridgeToolExposure === undefined ? {} : { bridgeToolExposure }), processEnvironment: { // The thread id every process the agent starts inherits, so a tool run // from its shell can find its T3 thread. Claude and Codex sessions set @@ -7722,6 +7740,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const mcpBridge = yield* makeAcpMcpOverAcpBridge({ endpoint: mcpContext.endpoint, authorization: mcpContext.authorization, + toolExposure: mcpContext.bridgeToolExposure, allocateConnectionId: random.uuidV4(), }); yield* Scope.addFinalizer(scope, mcpBridge.dispose); @@ -8944,10 +8963,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( sessionId: string, ) { const mcpSession = yield* mcpSessions.read(turnInput.threadId); + const toolExposure = mcpToolExposureMode(flavor.deferMcpTools); const instructionState = { interactionMode: turnInput.runtimePolicy.interactionMode, hasT3Mcp: mcpSession !== undefined, hasDeviceTools: mcpSession?.capabilities?.has("device") === true, + ...(toolExposure === undefined ? {} : { toolExposure }), } satisfies T3AcpInstructionState; const userText = flavor.rewriteUserText === undefined diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts index 04d9fe4b55632..f383693eec91e 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.test.ts @@ -24,6 +24,7 @@ describe("AcpMcpOverAcpBridge", () => { const bridge = yield* makeAcpMcpOverAcpBridge({ endpoint: "http://127.0.0.1:1/mcp", authorization: "Bearer bridge-test", + toolExposure: "deferred-proxy", allocateConnectionId: Effect.succeed("connection-1"), fetchImplementation: async (_url, init) => { const method = init?.method ?? "GET"; @@ -99,6 +100,7 @@ describe("AcpMcpOverAcpBridge", () => { expect(requests[0]?.headers.get("authorization")).toBe("Bearer bridge-test"); expect(requests[1]?.headers.get("mcp-session-id")).toBe("session-42"); expect(requests[1]?.headers.get("mcp-protocol-version")).toBe("2025-06-18"); + expect(requests[1]?.headers.get("t3-tool-exposure")).toBe("deferred-proxy"); expect(requests.at(-1)?.method).toBe("DELETE"); expect(requests.at(-1)?.headers.get("mcp-session-id")).toBe("session-42"); }), diff --git a/packages/provider-acp/src/server/mcpOverAcpBridge.ts b/packages/provider-acp/src/server/mcpOverAcpBridge.ts index 779076a622b5b..60cb3bed40ecd 100644 --- a/packages/provider-acp/src/server/mcpOverAcpBridge.ts +++ b/packages/provider-acp/src/server/mcpOverAcpBridge.ts @@ -7,6 +7,10 @@ import * as Stream from "effect/Stream"; import type * as AcpSchema from "effect-acp/compat"; import { responsePayloads } from "@t3tools/shared/mcpResponsePayloads"; +import { + MCP_TOOL_EXPOSURE_HEADER, + type McpToolExposureMode, +} from "@t3tools/provider-core/server/mcpSession"; const MAX_CONNECTIONS = 16; const MAX_MESSAGE_BYTES = 8 * 1024 * 1024; @@ -67,6 +71,7 @@ function errorMessage(error: unknown): string { export interface AcpMcpOverAcpBridgeOptions { readonly endpoint: string; readonly authorization: string; + readonly toolExposure?: McpToolExposureMode | undefined; readonly allocateConnectionId: Effect.Effect; readonly fetchImplementation?: (url: string, init?: RequestInit) => Promise; } @@ -134,6 +139,9 @@ export const makeAcpMcpOverAcpBridge = Effect.fn("AcpMcpOverAcpBridge.make")(fun "content-type": "application/json", accept: "application/json, text/event-stream", authorization: options.authorization, + ...(options.toolExposure === undefined + ? {} + : { [MCP_TOOL_EXPOSURE_HEADER]: options.toolExposure }), ...(connection.sessionId === null ? {} : { "mcp-session-id": connection.sessionId }), diff --git a/packages/provider-acp/src/server/runtimeModel.test.ts b/packages/provider-acp/src/server/runtimeModel.test.ts index ee4a9ca2aa57a..6334f0530658d 100644 --- a/packages/provider-acp/src/server/runtimeModel.test.ts +++ b/packages/provider-acp/src/server/runtimeModel.test.ts @@ -1503,6 +1503,62 @@ describe("extractMcpToolCallIdentity", () => { } }); + it("unwraps T3 tool_call proxy invocations to the target tool and arguments", () => { + const htmlArgs = { title: "Chart", html: "

hi

", height: 320 }; + expect( + extractMcpToolCallIdentity( + toolCallFromUpdate({ + sessionUpdate: "tool_call", + toolCallId: "proxy-1", + kind: "other", + title: "Run mcp_t3-code_tool_call", + status: "pending", + rawInput: { name: "html_render", arguments: htmlArgs }, + }), + ), + ).toEqual({ + server: "t3-code", + tool: "html_render", + input: htmlArgs, + }); + + expect( + extractMcpToolCallIdentity( + toolCallFromUpdate({ + sessionUpdate: "tool_call", + toolCallId: "proxy-2", + kind: "other", + title: "Running tool_call", + status: "pending", + rawInput: { + server: "t3-code", + tool: "tool_call", + arguments: { name: "t3_thread_read", arguments: { threadId: "thread-1" } }, + }, + _meta: { is_mcp_tool_call: true }, + }), + ), + ).toEqual({ + server: "t3-code", + tool: "t3_thread_read", + input: { threadId: "thread-1" }, + }); + + // A bare non-T3 `tool_call` title must not be misclassified as a T3 proxy call. + expect( + extractMcpToolCallIdentity( + toolCallFromUpdate({ + sessionUpdate: "tool_call", + toolCallId: "proxy-3", + kind: "other", + title: "tool_call", + status: "pending", + rawInput: { name: "html_render", arguments: htmlArgs }, + }), + ), + ).toBeUndefined(); + }); + it("recovers T3 identity from Hermes editor-renamed MCP tool titles", () => { const identityFor = (title: string) => extractMcpToolCallIdentity( @@ -1750,6 +1806,30 @@ describe("extractMcpToolCallIdentity", () => { expect(extractMcpToolCallIdentity(toolCall)).toBeUndefined(); }); + + it("unwraps T3 tool_call when Antigravity routes it through call_mcp_tool", () => { + const toolCall = toolCallFromUpdate({ + sessionUpdate: "tool_call", + toolCallId: "call-mcp-proxy-1", + kind: "execute", + title: "MCP Tool tool_call", + status: "completed", + rawInput: { + ServerName: "t3-code", + ToolName: "tool_call", + Arguments: { + name: "html_render", + arguments: { title: "Chart", html: "

hi

", height: 240 }, + }, + }, + }); + + expect(extractMcpToolCallIdentity(toolCall)).toEqual({ + server: "t3-code", + tool: "html_render", + input: { title: "Chart", html: "

hi

", height: 240 }, + }); + }); }); describe("embeddedTerminalIdsFromSessionUpdate", () => { diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts index e01ca47772f9e..cb3e049502b17 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -1125,6 +1125,38 @@ const T3_MCP_BARE_TITLE_CALL = /^(?[A-Za-z0-9_]+)(?::\s*\{|$)/; // Antigravity titles calls "Running " or, from agy 1.5.8, "Run mcp__"; prompts end in "?". const ANTIGRAVITY_TOOL_TITLE = /^Run(?:ning)? (?[^\s?]+)\??$/; +const T3_MCP_TOOL_CALL_PROXY = "tool_call"; + +function unwrapT3ToolCallProxy( + identity: AcpMcpToolCallIdentity, + rawInput: Record | undefined, +): AcpMcpToolCallIdentity { + if (!/^t3[-_ ]?code$/i.test(identity.server) || identity.tool !== T3_MCP_TOOL_CALL_PROXY) { + return identity; + } + // Native MCP wrappers pass `{ name, arguments }` directly; `is_mcp_tool_call` nests them under `arguments`. + const innerRaw = + typeof rawInput?.name === "string" + ? rawInput + : isRecord(rawInput?.arguments) + ? rawInput.arguments + : undefined; + const delegated = typeof innerRaw?.name === "string" ? innerRaw.name.trim() : ""; + if ( + delegated.length === 0 || + delegated === T3_MCP_TOOL_CALL_PROXY || + delegated === "tool_search" + ) { + return identity; + } + const delegatedInput = isRecord(innerRaw?.arguments) ? innerRaw.arguments : {}; + return { + server: "t3-code", + tool: delegated, + input: delegatedInput, + }; +} + /** ACP lacks typed MCP calls; recognize provider metadata and terminal fallback commands. */ export function extractMcpToolCallIdentity( toolCall: AcpToolCallState, @@ -1137,7 +1169,7 @@ export function extractMcpToolCallIdentity( const server = typeof rawInput?.server === "string" ? rawInput.server.trim() : ""; const tool = typeof rawInput?.tool === "string" ? rawInput.tool.trim() : ""; if (meta?.is_mcp_tool_call === true && server.length > 0 && tool.length > 0) { - return { server, tool }; + return unwrapT3ToolCallProxy({ server, tool }, rawInput); } // Antigravity reaches MCP tools its context budget left out through call_mcp_tool, an execute // call titled "MCP Tool " whose rawInput names the server, tool, and arguments. @@ -1145,7 +1177,10 @@ export function extractMcpToolCallIdentity( const proxiedTool = typeof rawInput?.ToolName === "string" ? rawInput.ToolName.trim() : ""; if (proxiedServer.length > 0 && proxiedTool.length > 0) { const input = isRecord(rawInput?.Arguments) ? rawInput.Arguments : undefined; - return { server: proxiedServer, tool: proxiedTool, ...(input === undefined ? {} : { input }) }; + return unwrapT3ToolCallProxy( + { server: proxiedServer, tool: proxiedTool, ...(input === undefined ? {} : { input }) }, + input, + ); } // Kiro names the server in `_meta.kiro.serverName` and the call in `rawInput.tool_id` // ("::"), with the tool's own input under `rawInput.arguments`. @@ -1168,6 +1203,13 @@ export function extractMcpToolCallIdentity( const metaServerId = typeof meta?.serverId === "string" ? meta.serverId.trim() : ""; const metaToolName = typeof meta?.toolName === "string" ? meta.toolName.trim() : ""; if (/^t3[-_ ]?code$/i.test(metaServerId) && metaToolName.length > 0) { + if ( + metaToolName === T3_MCP_TOOL_CALL_PROXY || + metaToolName.endsWith(`_${T3_MCP_TOOL_CALL_PROXY}`) || + metaToolName.endsWith(`.${T3_MCP_TOOL_CALL_PROXY}`) + ) { + return unwrapT3ToolCallProxy({ server: "t3-code", tool: T3_MCP_TOOL_CALL_PROXY }, rawInput); + } for (const knownTool of T3_MCP_TOOL_NAMES) { const boundary = metaToolName.length - knownTool.length - 1; if ( @@ -1225,10 +1267,11 @@ export function extractMcpToolCallIdentity( if (qualified?.[1] && qualified[2] && !/^t3[-_ ]?code$/i.test(qualified[1])) return { server: qualified[1], tool: qualified[2] }; const name = ANTIGRAVITY_TOOL_TITLE.exec(trimmed)?.groups?.name ?? trimmed; - const match = - T3_MCP_TITLE_CALL.exec(name) ?? - T3_MCP_TITLE_SUFFIX_CALL.exec(name) ?? - T3_MCP_BARE_TITLE_CALL.exec(name); + const qualifiedMatch = T3_MCP_TITLE_CALL.exec(name) ?? T3_MCP_TITLE_SUFFIX_CALL.exec(name); + if (qualifiedMatch?.groups?.tool === T3_MCP_TOOL_CALL_PROXY) { + return unwrapT3ToolCallProxy({ server: "t3-code", tool: T3_MCP_TOOL_CALL_PROXY }, rawInput); + } + const match = qualifiedMatch ?? T3_MCP_BARE_TITLE_CALL.exec(name); const candidateTool = match?.groups?.tool; if (candidateTool !== undefined && T3_MCP_TOOL_NAMES.has(candidateTool)) { return { server: "t3-code", tool: candidateTool }; @@ -1244,7 +1287,10 @@ export function extractMcpToolCallIdentity( const match = ACP_MCP_FALLBACK_CALL.exec(command); if (match?.[1] !== undefined) { const input = acpMcpFallbackInput(match[2]); - return { server: "t3-code", tool: match[1], ...(input === undefined ? {} : { input }) }; + return unwrapT3ToolCallProxy( + { server: "t3-code", tool: match[1], ...(input === undefined ? {} : { input }) }, + input, + ); } } return undefined; diff --git a/packages/provider-core/src/server/mcpSession.ts b/packages/provider-core/src/server/mcpSession.ts index 20d17df610fd7..6d169653270b8 100644 --- a/packages/provider-core/src/server/mcpSession.ts +++ b/packages/provider-core/src/server/mcpSession.ts @@ -2,11 +2,22 @@ import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contr import type * as Effect from "effect/Effect"; /** - * Sent by MCP clients that cannot defer tools themselves. The T3 MCP server then - * lists only a core set plus `tool_search`, which lists the rest on demand. + * Sent by MCP clients that cannot defer tools themselves. `"deferred"` lists a core set plus + * `tool_search` (for clients that reload on `notifications/tools/list_changed`); `"deferred-proxy"` + * keeps a fixed core set plus `tool_search` (with schemas) and `tool_call` (for clients that + * freeze their toolbox per turn). */ export const MCP_TOOL_EXPOSURE_HEADER = "t3-tool-exposure"; +export type McpToolExposureMode = "deferred" | "deferred-proxy"; + +export function parseMcpToolExposureMode( + value: string | undefined, +): McpToolExposureMode | undefined { + const trimmed = value?.trim(); + return trimmed === "deferred" || trimmed === "deferred-proxy" ? trimmed : undefined; +} + export interface McpProviderSessionConfig { readonly environmentId: EnvironmentId; readonly threadId: ThreadId; diff --git a/packages/provider-core/src/server/orchestrationInstructions.test.ts b/packages/provider-core/src/server/orchestrationInstructions.test.ts index ca3c3432d5b2b..c0a2e5a4955c1 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.test.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.test.ts @@ -96,5 +96,12 @@ describe("T3 device instructions", () => { "Again.", ); assert.notInclude(t3AcpPromptWithInstructions({ prompt: "Hi.", state }), "## T3 Code devices"); + const withProxy = t3AcpPromptWithInstructions({ + prompt: "Render a chart.", + state: { ...state, toolExposure: "deferred-proxy" }, + }); + assert.include(withProxy, "including `delegate_task`"); + assert.include(withProxy, "tool_call({ name, arguments })"); + assert.notInclude(t3AcpPromptWithInstructions({ prompt: "Hi.", state }), "tool_call("); }); }); diff --git a/packages/provider-core/src/server/orchestrationInstructions.ts b/packages/provider-core/src/server/orchestrationInstructions.ts index 3f97035bdacbd..3099c545651fa 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -1,4 +1,5 @@ import type { ProviderInteractionMode } from "@t3tools/contracts"; +import type { McpToolExposureMode } from "./mcpSession.ts"; // Codex truncates entries over 4,000 bytes; keep each section self-contained and below that limit. export const T3_CODE_ORCHESTRATION_SECTIONS: ReadonlyArray = [ @@ -55,6 +56,9 @@ export const T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH = deviceToolInstr ` Load them with ToolSearch \`select:${T3_CODE_DEVICE_TOOLS.map((tool) => `mcp__t3-code__${tool}`).join(",")}\`.`, ); +const T3_CODE_ACP_DEFERRED_PROXY_INSTRUCTIONS = + "Deferred T3 tools: only core orchestration tools, `tool_search`, and `tool_call` are declared directly. For any T3 tool not declared directly (including `delegate_task` if omitted, or optional tools like `preview_*`, `device_*`, `html_preview`, `html_render`, `t3_thread_*`, `t3_project_*`, `t3_worktree_*`, pull requests, `schedule_task`, `request_secret`, etc.), call `tool_search` to get its schema and `tool_call({ name, arguments })` to run it."; + // ACP only: some ACP agents accept the injected MCP server but never expose // its tools, so they need the terminal transport other harnesses never use. const T3_CODE_ACP_MCP_FALLBACK_INSTRUCTIONS = `ACP fallback: if the T3 tools are absent and \`T3_ACP_MCP_NODE\` is present, call them through the terminal: \`ELECTRON_RUN_AS_NODE=1 "$T3_ACP_MCP_NODE" \${T3_ACP_MCP_ENTRYPOINT:+"$T3_ACP_MCP_ENTRYPOINT"} acp-mcp-call orchestrator_capabilities '{}'\` (\`T3_ACP_MCP_ENTRYPOINT\` is unset for a standalone executable). Delegate with \`acp-mcp-call delegate_task '{"task":"...","target":{"providerInstanceId":"...","model":"..."},"mode":"async","clientRequestId":"..."}'\`. On Windows, run \`T3_ACP_MCP_CALL\` instead and pipe the JSON to stdin, as in PowerShell \`'{}' | & $env:T3_ACP_MCP_CALL orchestrator_capabilities -\`, writing non-ASCII characters as \`\\uXXXX\` escapes.`; @@ -71,6 +75,7 @@ export interface T3AcpInstructionState { readonly interactionMode: ProviderInteractionMode; readonly hasT3Mcp: boolean; readonly hasDeviceTools: boolean; + readonly toolExposure?: McpToolExposureMode | undefined; } /** ACP lacks system/developer fields; inject context on first prompt and tool/mode changes. */ @@ -84,7 +89,8 @@ export function t3AcpPromptWithInstructions(input: { if ( input.previousState?.interactionMode === input.state.interactionMode && input.previousState.hasT3Mcp === input.state.hasT3Mcp && - input.previousState.hasDeviceTools === input.state.hasDeviceTools + input.previousState.hasDeviceTools === input.state.hasDeviceTools && + input.previousState.toolExposure === input.state.toolExposure ) { return input.prompt; } @@ -97,6 +103,9 @@ export function t3AcpPromptWithInstructions(input: { T3_CODE_BROWSER_TOOL_INSTRUCTIONS.trim(), ...(input.state.hasDeviceTools ? [T3_CODE_DEVICE_TOOL_INSTRUCTIONS] : []), T3_CODE_ORCHESTRATION_INSTRUCTIONS.trim(), + ...(input.state.toolExposure === "deferred-proxy" + ? [T3_CODE_ACP_DEFERRED_PROXY_INSTRUCTIONS] + : []), T3_CODE_ACP_MCP_FALLBACK_INSTRUCTIONS, ] : []),