From 43e4516132976d89b8d22c4a12501276dccf9666 Mon Sep 17 00:00:00 2001 From: Eli Blau Date: Thu, 19 Nov 2026 16:10:12 -0500 Subject: [PATCH 1/6] fix(antigravity): defer optional T3 MCP tools via tool_call proxy --- apps/server/src/mcp/AcpMcpStdioBridge.test.ts | 29 +++ apps/server/src/mcp/AcpMcpStdioBridge.ts | 10 + apps/server/src/mcp/McpHttpServer.test.ts | 171 ++++++++++++++--- apps/server/src/mcp/McpHttpServer.ts | 178 +++++++++++++++++- apps/server/src/mcp/McpInvocationContext.ts | 3 + apps/server/src/mcp/McpToolExposure.ts | 71 ++++++- .../src/mcp/toolkits/toolSearch/handlers.ts | 12 +- .../src/mcp/toolkits/toolSearch/tools.ts | 8 +- .../Adapters/AcpRegistryAdapterV2.test.ts | 9 +- .../Adapters/AntigravityAdapterV2.test.ts | 82 +++++++- .../Adapters/AntigravityAdapterV2.ts | 2 + packages/provider-acp/src/server/adapter.ts | 28 ++- .../src/server/runtimeModel.test.ts | 56 ++++++ .../provider-acp/src/server/runtimeModel.ts | 46 ++++- .../provider-core/src/server/mcpSession.ts | 15 +- .../server/orchestrationInstructions.test.ts | 6 + .../src/server/orchestrationInstructions.ts | 11 +- 17 files changed, 669 insertions(+), 68 deletions(-) diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.test.ts b/apps/server/src/mcp/AcpMcpStdioBridge.test.ts index 89b320770ebfd..e4840b6737f92 100644 --- a/apps/server/src/mcp/AcpMcpStdioBridge.test.ts +++ b/apps/server/src/mcp/AcpMcpStdioBridge.test.ts @@ -445,4 +445,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 ffddcf7d5866b..e8609e024d931 100644 --- a/apps/server/src/mcp/AcpMcpStdioBridge.ts +++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts @@ -9,6 +9,8 @@ import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpResponsePayloads"; +import type { McpToolExposureMode } from "@t3tools/provider-core/server/mcpSession"; + /** ACP mandates stdio MCP support; HTTP/SSE support varies. */ export class AcpMcpBridgeError extends Schema.TaggedError()( @@ -40,6 +42,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 +239,9 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect. "content-type": "application/json", accept: "application/json, text/event-stream", authorization: options.authorization, + ...(options.toolExposure === undefined + ? {} + : { "t3-tool-exposure": options.toolExposure }), ...(sessionId === null ? {} : { "mcp-session-id": sessionId }), ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }), }, @@ -355,10 +361,14 @@ export async function runAcpMcpCliFastPath( return; } if (command === "acp-mcp-bridge") { + const rawExposure = process.env.T3_ACP_MCP_TOOL_EXPOSURE?.trim(); + const toolExposure: McpToolExposureMode | undefined = + rawExposure === "deferred" || rawExposure === "deferred-proxy" ? rawExposure : undefined; 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 e5d47410817f2..375fc50d2d13b 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -2037,26 +2037,38 @@ 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 OptionalToolkit = Toolkit.make( tool("delegate_task", "Delegates a task."), tool("preview_open", "Opens a browser preview."), tool("schedule_task", "Schedules a task."), + 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( @@ -2065,13 +2077,45 @@ it.effect("lists optional tools to a deferring client only after tool_search loa delegate_task: reads, preview_open: reads, schedule_task: 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(), process.cwd())), Layer.provide( Layer.mock(McpSessionRegistry.McpSessionRegistry)({ resolve: (token) => Effect.succeed(scopes.get(token)), @@ -2082,12 +2126,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, @@ -2096,7 +2140,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: { @@ -2109,17 +2153,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) => @@ -2128,25 +2173,103 @@ 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", + "preview_open", + "schedule_task", + ]); // 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"]); + + // 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 }); + 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", + "preview_open", + "schedule_task", + ]); }), ).pipe(Effect.provide(NodeHttpServer.layerTest)), ); diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 53d232aad842a..d4bbb3e1a25d4 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -51,7 +51,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"; @@ -336,7 +339,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) { @@ -1418,22 +1428,168 @@ 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): boolean => { + const enabledWhen = Context.getOrUndefined(annotations, McpSchema.EnabledWhen); + return enabledWhen === undefined || enabledWhen(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), + ); + 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* () { @@ -1443,18 +1599,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 97d2f8e5747ab..c99268c33724d 100644 --- a/apps/server/src/mcp/McpInvocationContext.ts +++ b/apps/server/src/mcp/McpInvocationContext.ts @@ -13,6 +13,7 @@ import { import * as Context from "effect/Context"; 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 = [ @@ -149,6 +150,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..9da6e6ee13443 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 MAX_PROXY_SCHEMA_BYTES; + } +}; + export const make = ( - tools: () => ReadonlyArray, + tools: () => ReadonlyArray, announceListChanged: () => Effect.Effect, ) => { const loaded = new Map>(); @@ -60,18 +90,39 @@ 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") { + let usedBytes = 0; + return found.map((tool): ListedTool => { + const withSchema: ListedTool = { + name: tool.name, + description: tool.description, + inputSchema: tool.inputSchema, + }; + const size = utf8Bytes(withSchema); + if (usedBytes === 0 || usedBytes + size <= MAX_PROXY_SCHEMA_BYTES) { + usedBytes += size; + return withSchema; + } + return { name: tool.name, description: tool.description }; + }); + } if (found.length > 0) { load( providerSessionId, @@ -79,9 +130,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 35c0ec29d1148..3d711b288494a 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1584,7 +1584,7 @@ describe("AcpRegistryAdapterV2", () => { ], }, ]; - const stdio = (authorization: string) => [ + const stdio = (authorization: string, exposure?: "deferred" | "deferred-proxy") => [ { name: "t3-code", command: selfInvocation.command, @@ -1593,6 +1593,9 @@ describe("AcpRegistryAdapterV2", () => { { name: "ELECTRON_RUN_AS_NODE", value: "1" }, { name: "T3_ACP_MCP_ENDPOINT", value: endpoint }, { name: "T3_ACP_MCP_AUTHORIZATION", value: authorization }, + ...(exposure === undefined + ? [] + : [{ name: "T3_ACP_MCP_TOOL_EXPOSURE", value: exposure }]), ], }, ]; @@ -1610,8 +1613,8 @@ describe("AcpRegistryAdapterV2", () => { { new: acp, load: acp }, ); assert.deepEqual(yield* sessionMcpServers({ agentId: "github-copilot-cli" }), { - new: stdio("Bearer opened-token"), - load: stdio("Bearer rotated-token"), + new: stdio("Bearer opened-token", "deferred"), + load: stdio("Bearer rotated-token", "deferred"), }); assert.deepEqual(yield* sessionMcpServers({ agentId: "gemini" }, { T3_ACP_MCP_HTTP: "1" }), { new: stdio("Bearer opened-token"), diff --git a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.test.ts index 21022a97f36d5..f67abd4305ad3 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, @@ -851,6 +852,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", @@ -866,11 +876,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: { @@ -997,10 +1022,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, }); @@ -1122,7 +1167,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", @@ -1134,6 +1179,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 e07e64185d276..2c3f7c15da192 100644 --- a/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AntigravityAdapterV2.ts @@ -220,6 +220,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: ({ diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 3e0864054c32f..dc8a1c64f978f 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -408,8 +408,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; @@ -992,15 +995,23 @@ interface AcpMcpContext { readonly authorization?: string; } +function mcpToolExposureMode( + deferMcpTools: boolean | "proxy" | undefined, +): McpProviderSession.McpToolExposureMode | undefined { + if (deferMcpTools === "proxy") return "deferred-proxy"; + return deferMcpTools === true ? "deferred" : undefined; +} + function acpMcpContext( session: McpProviderSession.McpProviderSessionConfig | undefined, self: SelfInvocation, mcpOverHttp: boolean | undefined, - deferMcpTools: boolean | undefined, + deferMcpTools: boolean | "proxy" | undefined, ): AcpMcpContext { if (session === undefined) { return { servers: [], acpServers: [], httpServers: [] }; } + const exposure = mcpToolExposureMode(deferMcpTools); // codex-acp 1.2.0 and pi-acp drop injected HTTP servers, so HTTP is opt-in per flavor. return { servers: [ @@ -1012,6 +1023,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 }, + ...(exposure === undefined + ? [] + : [{ name: "T3_ACP_MCP_TOOL_EXPOSURE", value: exposure }]), ], }, ], @@ -1025,9 +1039,9 @@ 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 }]), ], }, ] @@ -8860,10 +8874,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/runtimeModel.test.ts b/packages/provider-acp/src/server/runtimeModel.test.ts index 57c1acae82df9..225a037188298 100644 --- a/packages/provider-acp/src/server/runtimeModel.test.ts +++ b/packages/provider-acp/src/server/runtimeModel.test.ts @@ -1481,6 +1481,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( diff --git a/packages/provider-acp/src/server/runtimeModel.ts b/packages/provider-acp/src/server/runtimeModel.ts index 00e6861a80fae..b5ad38fd1cc14 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -1125,6 +1125,34 @@ 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) { + 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 +1165,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); } // Kiro names the server in `_meta.kiro.serverName` and the call in `rawInput.tool_id` // ("::"), with the tool's own input under `rawInput.arguments`. @@ -1160,6 +1188,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 ( @@ -1217,10 +1252,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 }; 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 c8dd21cc02634..b2f4538c6c201 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.test.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.test.ts @@ -81,5 +81,11 @@ 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, "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 4ce08d71119fe..391f9c27adb85 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 other T3 tool (`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":"..."}'\`.`; @@ -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, ] : []), From 9ca7adb68672f17f2cd2ec41800b9738e61b6e5e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 21:22:56 +0000 Subject: [PATCH 2/6] fix(antigravity): keep Copilot's stdio MCP bridge listing every tool Only deferred-proxy mode reaches the stdio bridge, so Copilot sessions on stdio keep their current tool listing, and the bridge reuses the shared exposure parser. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/mcp/AcpMcpStdioBridge.ts | 9 +++++---- .../Adapters/AcpRegistryAdapterV2.test.ts | 9 +++------ packages/provider-acp/src/server/adapter.ts | 7 ++++--- 3 files changed, 12 insertions(+), 13 deletions(-) diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.ts index e8609e024d931..55b976ccec560 100644 --- a/apps/server/src/mcp/AcpMcpStdioBridge.ts +++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts @@ -9,7 +9,10 @@ import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import { discardResponseBody, responsePayloads } from "@t3tools/shared/mcpResponsePayloads"; -import type { McpToolExposureMode } from "@t3tools/provider-core/server/mcpSession"; +import { + type McpToolExposureMode, + parseMcpToolExposureMode, +} from "@t3tools/provider-core/server/mcpSession"; /** ACP mandates stdio MCP support; HTTP/SSE support varies. */ @@ -361,9 +364,7 @@ export async function runAcpMcpCliFastPath( return; } if (command === "acp-mcp-bridge") { - const rawExposure = process.env.T3_ACP_MCP_TOOL_EXPOSURE?.trim(); - const toolExposure: McpToolExposureMode | undefined = - rawExposure === "deferred" || rawExposure === "deferred-proxy" ? rawExposure : undefined; + const toolExposure = parseMcpToolExposureMode(process.env.T3_ACP_MCP_TOOL_EXPOSURE); await Effect.runPromise( runAcpMcpStdioBridge({ endpoint, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 3d711b288494a..35c0ec29d1148 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1584,7 +1584,7 @@ describe("AcpRegistryAdapterV2", () => { ], }, ]; - const stdio = (authorization: string, exposure?: "deferred" | "deferred-proxy") => [ + const stdio = (authorization: string) => [ { name: "t3-code", command: selfInvocation.command, @@ -1593,9 +1593,6 @@ describe("AcpRegistryAdapterV2", () => { { name: "ELECTRON_RUN_AS_NODE", value: "1" }, { name: "T3_ACP_MCP_ENDPOINT", value: endpoint }, { name: "T3_ACP_MCP_AUTHORIZATION", value: authorization }, - ...(exposure === undefined - ? [] - : [{ name: "T3_ACP_MCP_TOOL_EXPOSURE", value: exposure }]), ], }, ]; @@ -1613,8 +1610,8 @@ describe("AcpRegistryAdapterV2", () => { { new: acp, load: acp }, ); assert.deepEqual(yield* sessionMcpServers({ agentId: "github-copilot-cli" }), { - new: stdio("Bearer opened-token", "deferred"), - load: stdio("Bearer rotated-token", "deferred"), + new: stdio("Bearer opened-token"), + load: stdio("Bearer rotated-token"), }); assert.deepEqual(yield* sessionMcpServers({ agentId: "gemini" }, { T3_ACP_MCP_HTTP: "1" }), { new: stdio("Bearer opened-token"), diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index dc8a1c64f978f..4be9f4f863231 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -1023,9 +1023,10 @@ 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 }, - ...(exposure === undefined - ? [] - : [{ name: "T3_ACP_MCP_TOOL_EXPOSURE", value: exposure }]), + // Copilot's stdio bridge keeps listing every tool; only proxy mode defers there. + ...(exposure === "deferred-proxy" + ? [{ name: "T3_ACP_MCP_TOOL_EXPOSURE", value: exposure }] + : []), ], }, ], From ddf1c11d6d9d5ad38069123805f66fb929247a7c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 21:27:47 +0000 Subject: [PATCH 3/6] fix(antigravity): send the proxy tool exposure over MCP-over-ACP too An agent that advertises ACP-native MCP takes that route before HTTP or stdio, and its bridge sent no t3-tool-exposure header, so a proxy session there would list every tool but tool_search and tool_call. Co-Authored-By: Claude Opus 5.5 --- packages/provider-acp/src/server/adapter.ts | 12 ++++++++---- .../provider-acp/src/server/mcpOverAcpBridge.test.ts | 2 ++ packages/provider-acp/src/server/mcpOverAcpBridge.ts | 8 ++++++++ 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 4be9f4f863231..757d78f4c86dd 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -993,6 +993,8 @@ 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( @@ -1012,6 +1014,7 @@ function acpMcpContext( 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: [ @@ -1023,10 +1026,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 }, - // Copilot's stdio bridge keeps listing every tool; only proxy mode defers there. - ...(exposure === "deferred-proxy" - ? [{ name: "T3_ACP_MCP_TOOL_EXPOSURE", value: exposure }] - : []), + ...(bridgeToolExposure === undefined + ? [] + : [{ name: "T3_ACP_MCP_TOOL_EXPOSURE", value: bridgeToolExposure }]), ], }, ], @@ -1049,6 +1051,7 @@ function acpMcpContext( : [], 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 @@ -7661,6 +7664,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); 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 }), From d0dc0032b92a5faeeee9982e4f74907a9a6f00a0 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 21:50:39 +0000 Subject: [PATCH 4/6] fix(antigravity): Local ACP agy commands defer T3 tools through tool_call A Local ACP command running agy acp uses the registry adapter, which detected agy but still listed every T3 tool schema. It now selects the same proxy exposure as the Antigravity provider. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/AcpRegistryAdapterV2.test.ts | 15 +++++++++++++++ .../provider-acp-registry/src/server/adapter.ts | 4 +++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index 35c0ec29d1148..677b4f86013b8 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1617,6 +1617,21 @@ describe("AcpRegistryAdapterV2", () => { new: stdio("Bearer opened-token"), load: stdio("Bearer rotated-token"), }); + // A local agy command defers optional tools through tool_call, as the Antigravity provider does. + const agyStdio = stdio("Bearer opened-token"); + assert.deepEqual( + (yield* sessionMcpServers({ source: "local", commandPath: "agy", commandArgs: ["acp"] })) + .new, + [ + { + ...agyStdio[0], + env: [ + ...agyStdio[0]!.env, + { name: "T3_ACP_MCP_TOOL_EXPOSURE", value: "deferred-proxy" }, + ], + }, + ], + ); // 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/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index ce5a2b94531c4..3123cff93aedc 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -255,7 +255,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(registryAgentId, cause), ...(registryAgentId === "factory-droid" ? { extractElicitationForm: extractDroidElicitationForm } From 9b8e79f44b7b31f7fd21f67ef3b91e137ffd1768 Mon Sep 17 00:00:00 2001 From: Eli Blau Date: Fri, 20 Nov 2026 11:43:48 -0500 Subject: [PATCH 5/6] fix(antigravity): harden deferred-proxy unwrapping, 8 KB budget, and CLI match --- apps/server/src/mcp/AcpMcpStdioBridge.ts | 3 +- apps/server/src/mcp/McpHttpServer.test.ts | 46 +++++++++++++++++++ apps/server/src/mcp/McpHttpServer.ts | 16 +++++-- apps/server/src/mcp/McpToolExposure.ts | 29 ++++++++---- .../Adapters/AcpRegistryAdapterV2.test.ts | 26 +++++++---- .../src/server/adapter.ts | 4 +- .../src/server/runtimeModel.test.ts | 24 ++++++++++ .../provider-acp/src/server/runtimeModel.ts | 16 +++++-- 8 files changed, 137 insertions(+), 27 deletions(-) diff --git a/apps/server/src/mcp/AcpMcpStdioBridge.ts b/apps/server/src/mcp/AcpMcpStdioBridge.ts index 55b976ccec560..a8652ef846c34 100644 --- a/apps/server/src/mcp/AcpMcpStdioBridge.ts +++ b/apps/server/src/mcp/AcpMcpStdioBridge.ts @@ -10,6 +10,7 @@ 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"; @@ -244,7 +245,7 @@ export function runAcpMcpStdioBridge(options: AcpMcpStdioBridgeOptions): Effect. authorization: options.authorization, ...(options.toolExposure === undefined ? {} - : { "t3-tool-exposure": options.toolExposure }), + : { [MCP_TOOL_EXPOSURE_HEADER]: options.toolExposure }), ...(sessionId === null ? {} : { "mcp-session-id": sessionId }), ...(protocolVersion === null ? {} : { "mcp-protocol-version": protocolVersion }), }, diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 375fc50d2d13b..53447f54bb7f1 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -2059,10 +2059,28 @@ it.effect("lists optional tools to a deferring client only after tool_search loa 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({ ok: true })); @@ -2077,6 +2095,8 @@ 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, }), ), @@ -2207,8 +2227,10 @@ it.effect("lists optional tools to a deferring client only after tool_search loa "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", {})).result?.structuredContent).toEqual({ @@ -2236,6 +2258,28 @@ it.effect("lists optional tools to a deferring client only after tool_search loa }); 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 @@ -2267,8 +2311,10 @@ it.effect("lists optional tools to a deferring client only after tool_search loa "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 1e66e5f0a7a08..e47424a2f11ae 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"; @@ -1445,9 +1446,18 @@ const enabledWhenFallbackClient = { clientInfo: { name: "t3-code", version: packageJson.version }, } as const; -const isToolRegistrationEnabled = (annotations: Context.Context): boolean => { +const isToolRegistrationEnabled = ( + annotations: Context.Context, + initializePayload?: (typeof McpSchema.Initialize.payloadSchema)["Type"], +): boolean => { const enabledWhen = Context.getOrUndefined(annotations, McpSchema.EnabledWhen); - return enabledWhen === undefined || enabledWhen(enabledWhenFallbackClient); + 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( @@ -1568,7 +1578,7 @@ const registerToolCall = Effect.fn("McpHttpServer.registerToolCall")(function* ( const entry = server.tools.find( (candidate) => candidate.tool.name === name && - isToolRegistrationEnabled(candidate.annotations), + isToolRegistrationEnabled(candidate.annotations, client.initializePayload), ); if (entry !== undefined) { return Effect.succeed( diff --git a/apps/server/src/mcp/McpToolExposure.ts b/apps/server/src/mcp/McpToolExposure.ts index 9da6e6ee13443..f133875a7f5f5 100644 --- a/apps/server/src/mcp/McpToolExposure.ts +++ b/apps/server/src/mcp/McpToolExposure.ts @@ -70,7 +70,7 @@ const utf8Bytes = (value: unknown): number => { try { return Buffer.byteLength(JSON.stringify(value) ?? "", "utf8"); } catch { - return MAX_PROXY_SCHEMA_BYTES; + return Number.POSITIVE_INFINITY; } }; @@ -108,20 +108,31 @@ export const make = ( .slice(0, MAX_RESULTS) .map((match) => match.tool); if (options?.mode === "deferred-proxy") { - let usedBytes = 0; - return found.map((tool): ListedTool => { + const results: Array = []; + for (const tool of found) { const withSchema: ListedTool = { name: tool.name, description: tool.description, inputSchema: tool.inputSchema, }; - const size = utf8Bytes(withSchema); - if (usedBytes === 0 || usedBytes + size <= MAX_PROXY_SCHEMA_BYTES) { - usedBytes += size; - return withSchema; + if (utf8Bytes({ tools: [...results, withSchema] }) <= MAX_PROXY_SCHEMA_BYTES) { + results.push(withSchema); + continue; } - return { name: tool.name, description: tool.description }; - }); + 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( diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index e84c9c8402d71..6ab6c102ad94f 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -1617,20 +1617,26 @@ describe("AcpRegistryAdapterV2", () => { new: stdio("Bearer opened-token"), load: stdio("Bearer rotated-token"), }); - // A local agy command defers optional tools through tool_call, as the Antigravity provider does. + // 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, - [ - { - ...agyStdio[0], - env: [ - ...agyStdio[0]!.env, - { name: "T3_ACP_MCP_TOOL_EXPOSURE", value: "deferred-proxy" }, - ], - }, - ], + 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. diff --git a/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 3d5fecc8b4bd5..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() ?? ""); diff --git a/packages/provider-acp/src/server/runtimeModel.test.ts b/packages/provider-acp/src/server/runtimeModel.test.ts index a57f5efe2b3eb..6334f0530658d 100644 --- a/packages/provider-acp/src/server/runtimeModel.test.ts +++ b/packages/provider-acp/src/server/runtimeModel.test.ts @@ -1806,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 687788f50b4fb..cb3e049502b17 100644 --- a/packages/provider-acp/src/server/runtimeModel.ts +++ b/packages/provider-acp/src/server/runtimeModel.ts @@ -1142,7 +1142,11 @@ function unwrapT3ToolCallProxy( ? rawInput.arguments : undefined; const delegated = typeof innerRaw?.name === "string" ? innerRaw.name.trim() : ""; - if (delegated.length === 0 || delegated === T3_MCP_TOOL_CALL_PROXY) { + if ( + delegated.length === 0 || + delegated === T3_MCP_TOOL_CALL_PROXY || + delegated === "tool_search" + ) { return identity; } const delegatedInput = isRecord(innerRaw?.arguments) ? innerRaw.arguments : {}; @@ -1173,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`. @@ -1280,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; From 4d91c1732ef33a99368831b6d54022665fab71bc Mon Sep 17 00:00:00 2001 From: Eli Blau Date: Sun, 22 Nov 2026 03:21:45 -0500 Subject: [PATCH 6/6] fix(antigravity): cover omitted core tools in proxy instructions and isolate proxy test dir --- apps/server/src/mcp/McpHttpServer.test.ts | 7 ++++++- .../src/server/orchestrationInstructions.test.ts | 1 + .../provider-core/src/server/orchestrationInstructions.ts | 2 +- 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/apps/server/src/mcp/McpHttpServer.test.ts b/apps/server/src/mcp/McpHttpServer.test.ts index 23cbdfd98c79e..060104975de5b 100644 --- a/apps/server/src/mcp/McpHttpServer.test.ts +++ b/apps/server/src/mcp/McpHttpServer.test.ts @@ -2096,7 +2096,7 @@ it.effect("lists optional tools to a deferring client only after tool_search loa }), ), Layer.provide(Layer.mock(ProjectService.ProjectService)({})), - Layer.provide(ServerConfig.layerTest(process.cwd(), process.cwd())), + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-proxy-test-" })), Layer.provide( Layer.mock(McpSessionRegistry.McpSessionRegistry)({ resolve: (token) => Effect.succeed(scopes.get(token)), @@ -2246,6 +2246,11 @@ it.effect("lists optional tools to a deferring client only after tool_search loa (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: {}, diff --git a/packages/provider-core/src/server/orchestrationInstructions.test.ts b/packages/provider-core/src/server/orchestrationInstructions.test.ts index aabcecf9b22eb..c0a2e5a4955c1 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.test.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.test.ts @@ -100,6 +100,7 @@ describe("T3 device instructions", () => { 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 02e004d268238..3099c545651fa 100644 --- a/packages/provider-core/src/server/orchestrationInstructions.ts +++ b/packages/provider-core/src/server/orchestrationInstructions.ts @@ -57,7 +57,7 @@ export const T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH = deviceToolInstr ); const T3_CODE_ACP_DEFERRED_PROXY_INSTRUCTIONS = - "Deferred T3 tools: only core orchestration tools, `tool_search`, and `tool_call` are declared directly. For any other T3 tool (`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."; + "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.