From 5f7670739d154cfc8c68f7ef2f539d04e9c160ce Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:25:29 -0600 Subject: [PATCH] fix(runner): compact Antigravity MCP tool schemas so lifecycle tools stay within agy budget (#23620) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The Paperclip Runner exposes Paperclip's semantic tools (`paperclip_finish`, `paperclip_block`, `set_task_monitor`, `report_progress`, `call_api`, etc.) to Google Antigravity (`agy` 1.5.19) over a loopback HTTP MCP bridge (`startRunnerToolBridge`) > - `agy` 1.5.19 packs MCP `functionDeclarations` smallest-first under a ~40 KB total schema budget and silently drops tools that exceed it instead of making them lazy-loaded > - Because the full Paperclip semantic action catalog plus reserved lifecycle tools exceeds 61 KB of JSON Schema, `agy` 1.5.19 evicted the largest tools first — starting with `paperclip_finish` (5.6 KB) and `paperclip_block` (5.0 KB), and on larger catalogs also `call_api`, `report_progress`, and `set_task_monitor` — causing ordinary Antigravity runs to finish work without being able to finalize and fail with `native_finalization_missing` > - This pull request adds `compactToolInputSchema()` and a `compactToolSchemas` option on `startRunnerToolBridge` (enabled for Antigravity in `AcpxRuntimeHost`) to strip verbose schema-level metadata from `tools/list` while keeping full original Ajv validation on every `tools/call` > - The benefit is that total schema size drops by more than half (~61 KB to ~28 KB), so all Paperclip MCP lifecycle tools stay declared in `agy` 1.5.19 with full server-side validation intact ## Linked Issues or Issue Description Refs #23168, #23536 **What happened?** Ordinary Google Antigravity runs on `agy` 1.5.19 started cleanly and executed shell/read tools (`get_task_context`, `get_identity`, `run_command`), but could not call `paperclip_finish`, `paperclip_block`, `set_task_monitor`, `report_progress`, or `call_api` because `agy` 1.5.19 silently evicted the largest MCP tool schemas from `functionDeclarations` once the server's total schema size exceeded its ~40 KB budget. Runs then ended with `native_finalization_missing: session returned no semantic result`. **Expected behavior** All Paperclip MCP lifecycle tools (`paperclip_finish`, `paperclip_block`, `set_task_monitor`, `report_progress`, `call_api`, `create_task`, etc.) remain declared in `agy` 1.5.19 `functionDeclarations` even when the full semantic action catalog and assigned tools are served, while `tools/call` continues enforcing every original JSON Schema constraint. **Steps to reproduce** 1. Start `startRunnerToolBridge` with `PAPERCLIP_SEMANTIC_ACTION_CATALOG` (`schemaPatternDialect: "re2"` without `compactToolSchemas`). 2. Connect `agy` 1.5.19 `acp` to the bridge via `session/new` `mcpServers` and inspect the outgoing `functionDeclarations` on `session/prompt`. 3. Observe `agy` 1.5.19 keeps only 60 of 66 tools and silently drops the 6 largest (`paperclip_finish`, `paperclip_block`, `handoff_case`, `create_task`, `create_case`, `create_responsibility`). **Paperclip version or commit** `master` (after #23168 / #23536) **Deployment mode** Self-hosted server ## What Changed - Add `compactToolInputSchema()` in `packages/paperclip-runner/src/drivers/re2-schema-patterns.ts` to strip schema-level metadata (`description`, `title`, `$schema`, `$id`, `examples`, `default`, `minLength`, `maxLength`, `minItems`, `maxItems`, `minimum`, `maximum`, and `additionalProperties: false`) while preserving all property keys inside `properties` / `patternProperties` / `$defs` / `definitions` (including properties named `description` or `title`), types, enums, and `required` lists. - Add `compactToolSchemas?: boolean` to `RunnerToolBridgeOptions` in `packages/paperclip-runner/src/drivers/runner-tool-bridge.ts`, applied only to `tools/list` output after compiling the full original Ajv validators. - Enable `compactToolSchemas: true` for `options.agent === "antigravity"` in `packages/paperclip-runner/src/drivers/acpx/runtime-host.ts`. - Add red-green regression tests in `packages/paperclip-runner/src/drivers/re2-schema-patterns.test.ts` and `packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.test.ts`. ## Verification - **Red (before fix)**: New regression test in `re2-schema-patterns.test.ts` failed with `expected 61366 to be less than 35000`; real `agy` 1.5.19 binary probe dropped `paperclip_finish`, `paperclip_block`, `handoff_case`, `create_task`, `create_case`, and `create_responsibility` (60/66 kept). - **Green (after fix)**: - `pnpm --dir packages/paperclip-runner exec vitest run src/drivers/re2-schema-patterns.test.ts src/drivers/runner-tool-bridge.test.ts src/drivers/acpx/antigravity-acp-runtime.test.ts` — **3 files, 58 tests passed** - `pnpm --dir packages/paperclip-runner exec tsc -p tsconfig.json --noEmit && pnpm --dir packages/paperclip-runner exec tsc -p tsconfig.test.json --noEmit` — **passed** - Real `agy` 1.5.19 binary probe with 80 tools (`PAPERCLIP_SEMANTIC_ACTION_CATALOG` + 14 extra tools + `paperclip_finish` + `paperclip_block`): **80/80 tools kept** in `functionDeclarations` (including `paperclip_finish`, `paperclip_block`, `set_task_monitor`, `report_progress`, `call_api`, `create_task`). ## Risks - Low risk. Scoped strictly to `options.agent === "antigravity"` (`compactToolSchemas: true`), and every `tools/call` invocation is still validated against the original uncompacted Ajv schema with plain-language error messages (`toolInputError`). ## Model Used - Google Gemini 4 Neon (Medium) via Antigravity agent with tool use and local code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- .../acpx/antigravity-acp-runtime.test.ts | 38 ++++++- .../src/drivers/acpx/runtime-host.ts | 6 +- .../src/drivers/re2-schema-patterns.test.ts | 100 ++++++++++++++++++ .../src/drivers/re2-schema-patterns.ts | 64 ++++++++++- .../src/drivers/runner-tool-bridge.ts | 20 +++- 5 files changed, 219 insertions(+), 9 deletions(-) diff --git a/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.test.ts b/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.test.ts index d5c4e08c505..c6712f53ed5 100644 --- a/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.test.ts +++ b/packages/paperclip-runner/src/drivers/acpx/antigravity-acp-runtime.test.ts @@ -534,6 +534,7 @@ describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", () const { mkdir } = await import("node:fs/promises"); await mkdir(runtimeDirectory, { recursive: true }); const baseCommand = openOptions().command; + let capturedBridge: { url: string; bearerToken?: string } | null = null; const dependencies = { verifyInstallation: async () => ({ commandDigest: QUALIFIED_ACPX_PROFILES.antigravity.commandDigest, @@ -541,8 +542,11 @@ describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", () agentRuntimePackageJsonPath: null, openCommand: async () => baseCommand, }), - openRuntime: (opts: AcpxRuntimePortOpenOptions) => - openAntigravityAcpRuntime(opts, { awaitProviderOwnership: async () => undefined }), + openRuntime: (opts: AcpxRuntimePortOpenOptions) => { + const paperclipServer = opts.mcpServers.find(server => "url" in server && server.name === "paperclip"); + if (paperclipServer && "url" in paperclipServer) capturedBridge = { url: paperclipServer.url, bearerToken: paperclipServer.bearerToken }; + return openAntigravityAcpRuntime(opts, { awaitProviderOwnership: async () => undefined }); + }, reportRetainedCleanupFailure: () => undefined, }; const hostOptions = { @@ -553,6 +557,21 @@ describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", () model: "gemini-4-argon-medium", permissionMode: "approve-all" as const, environment: { GEMINI_API_KEY: "test-antigravity-key" }, + semanticTools: { + tools: [{ + name: "sample_tool", + description: "Sample tool.", + inputSchema: { + type: "object", + description: "Verbose schema description.", + properties: { + title: { type: "string", description: "Verbose property description.", minLength: 1 }, + }, + additionalProperties: false, + }, + }], + handler: async () => ({ ok: true }), + }, }; const first = await AcpxRuntimeHost.open(hostOptions, dependencies); @@ -562,6 +581,21 @@ describe("openAntigravityAcpRuntime (unified agy acp 1.5.19 ordinary turns)", () expect(first.identity().backendSessionId).toBe("sess-ordinary-1"); expectedIdentity = acpxProviderSessionIdentity(first.identity(), first.binding()); expect(expectedIdentity.mode).toBeUndefined(); + expect(capturedBridge).not.toBeNull(); + const listResponse = await fetch(capturedBridge!.url, { + method: "POST", + headers: { + Authorization: `Bearer ${capturedBridge!.bearerToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/list" }), + }); + const listed = ((await listResponse.json()) as { result: { tools: Array<{ name: string; inputSchema: Record }> } }).result.tools; + const sample = listed.find(tool => tool.name === "paperclip_sample_tool" || tool.name === "sample_tool"); + expect(sample?.inputSchema).toEqual({ type: "object", properties: { title: { type: "string" } } }); + const finish = listed.find(tool => tool.name === "paperclip_finish"); + expect(finish).toBeDefined(); + expect(JSON.stringify(finish!.inputSchema).length).toBeLessThan(3_500); } finally { await first.close({ reason: "first turn done" }); } diff --git a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts index 2679e31f998..53e31565071 100644 --- a/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts +++ b/packages/paperclip-runner/src/drivers/acpx/runtime-host.ts @@ -743,8 +743,10 @@ export class AcpxRuntimeHost { ...(swarmRoute && options.semanticTools!.tools ? { tools: antigravitySwarmTools(options.semanticTools!.tools) } : {}), preserveToolNames: options.assignedMcpTransport === "prp", preloadClaudeTaskTools: options.agent === "claude", - // The Antigravity CLI checks tool schemas with RE2 and refuses its whole toolbox otherwise. - ...(options.agent === "antigravity" ? { schemaPatternDialect: "re2" as const } : {}), + // The Antigravity CLI checks tool schemas with RE2 and packs MCP tool + // declarations smallest-first under a ~40 KB budget, dropping large + // schemas like `paperclip_finish` / `paperclip_block` unless compacted. + ...(options.agent === "antigravity" ? { schemaPatternDialect: "re2" as const, compactToolSchemas: true } : {}), }), resource: "tool_bridge", releaseLate: (lateToolBridge) => lateToolBridge.close(), diff --git a/packages/paperclip-runner/src/drivers/re2-schema-patterns.test.ts b/packages/paperclip-runner/src/drivers/re2-schema-patterns.test.ts index 0dfbc22e3b1..bc52664cb61 100644 --- a/packages/paperclip-runner/src/drivers/re2-schema-patterns.test.ts +++ b/packages/paperclip-runner/src/drivers/re2-schema-patterns.test.ts @@ -114,3 +114,103 @@ it("tells the model in plain words which rule a value broke when the CLI never s // The rule the served schema no longer carried, as the schema's own words. expect(text).toContain("key: Stable document identifier, not a filename or path"); }); + +it("compacts tools/list schemas below agy's MCP budget while preserving property names, enum/const literals, and full call validation", async () => { + const { PAPERCLIP_SEMANTIC_ACTION_CATALOG } = await import("../catalog/semantic-action-catalog.js"); + const tools = PAPERCLIP_SEMANTIC_ACTION_CATALOG.map(action => ({ + name: action.operationId, + description: action.description, + inputSchema: action.inputSchema as Record, + })); + const bridge = await startRunnerToolBridge({ + preserveToolNames: true, + schemaPatternDialect: "re2", + compactToolSchemas: true, + tools, + handler: async () => ({ ok: true }), + }); + bridges.push(bridge); + const listed = (await rpc(bridge, { id: 1, method: "tools/list" })).result.tools!; + + // Exact set of admitted tool names must be served (nothing silently dropped). + const expectedNames = new Set([ + ...PAPERCLIP_SEMANTIC_ACTION_CATALOG.map(action => action.operationId), + "paperclip_finish", + "paperclip_block", + ]); + expect(new Set(listed.map(tool => tool.name))).toEqual(expectedNames); + + // Measure both inputSchema bytes and full tool declaration bytes (name + description + inputSchema). + const totalSchemaBytes = listed.reduce((sum, tool) => sum + JSON.stringify(tool.inputSchema).length, 0); + const totalDeclarationBytes = listed.reduce((sum, tool) => sum + JSON.stringify(tool).length, 0); + expect(totalSchemaBytes).toBeLessThan(35_000); + expect(totalDeclarationBytes).toBeLessThan(60_000); + + // Property names that match JSON Schema metadata keywords must never be stripped. + const createTask = listed.find(tool => tool.name === "create_task"); + const createTaskProps = (createTask?.inputSchema as { properties?: Record })?.properties; + expect(createTaskProps).toHaveProperty("title"); + expect(createTaskProps).toHaveProperty("description"); + + // paperclip_finish and paperclip_block must be present and compacted. + const finish = listed.find(tool => tool.name === "paperclip_finish"); + const block = listed.find(tool => tool.name === "paperclip_block"); + expect(finish).toBeDefined(); + expect(block).toBeDefined(); + expect(JSON.stringify(finish!.inputSchema).length).toBeLessThan(3_500); + expect(JSON.stringify(block!.inputSchema).length).toBeLessThan(3_500); + + // Original full Ajv validation still enforces stripped keywords (additionalProperties: false and minimum: 1). + const rejectedExtraProp = await rpc(bridge, { + id: 2, + method: "tools/call", + params: { name: "get_task_context", arguments: { unexpectedField: true } }, + }); + expect(rejectedExtraProp.result.isError).toBe(true); + + const rejectedRange = await rpc(bridge, { + id: 3, + method: "tools/call", + params: { name: "get_task_history", arguments: { limit: 0 } }, + }); + expect(rejectedRange.result.isError).toBe(true); +}); + +it("preserves literal objects inside enum and const verbatim while still transforming properties named enum or const", async () => { + const literalEnum = [{ title: "Deploy", description: "Run deploy", minimum: 1, additionalProperties: false }]; + const literalConst = { title: "Exact", description: "Exact value", pattern: "\\u212a" }; + const bridge = await startRunnerToolBridge({ + preserveToolNames: true, + schemaPatternDialect: "re2", + compactToolSchemas: true, + tools: [{ + name: "choose_action", + description: "Pick an action.", + inputSchema: { + type: "object", + properties: { + choice: { enum: literalEnum, description: "Stripped schema description" }, + fixed: { const: literalConst, title: "Stripped schema title" }, + enum: { type: "string", pattern: "^\\u212a$", description: "Property literally named enum" }, + const: { type: "string", pattern: "^\\u212a$", title: "Property literally named const" }, + }, + required: ["choice", "fixed"], + additionalProperties: false, + }, + }], + handler: async () => ({ ok: true }), + }); + bridges.push(bridge); + const listed = (await rpc(bridge, { id: 1, method: "tools/list" })).result.tools!; + const choose = listed.find(tool => tool.name === "choose_action"); + expect(choose?.inputSchema).toEqual({ + type: "object", + properties: { + choice: { enum: literalEnum }, + fixed: { const: literalConst }, + enum: { type: "string", pattern: String.raw`^\x{212a}$` }, + const: { type: "string", pattern: String.raw`^\x{212a}$` }, + }, + required: ["choice", "fixed"], + }); +}); diff --git a/packages/paperclip-runner/src/drivers/re2-schema-patterns.ts b/packages/paperclip-runner/src/drivers/re2-schema-patterns.ts index 23e2c2a971a..8d1d4bedf69 100644 --- a/packages/paperclip-runner/src/drivers/re2-schema-patterns.ts +++ b/packages/paperclip-runner/src/drivers/re2-schema-patterns.ts @@ -77,13 +77,23 @@ function escapesToRe2(pattern: string): string | null { return output; } +const LITERAL_DATA_SCHEMA_KEYWORDS = new Set(["enum", "const"]); + +const SCHEMA_MAP_KEYWORDS = new Set([ + "properties", + "$defs", + "definitions", +]); + /** A copy of `schema` whose `pattern` values and `patternProperties` keys are RE2-portable. */ export function re2PortableSchema(schema: Json): Json { if (Array.isArray(schema)) return schema.map(re2PortableSchema); if (schema === null || typeof schema !== "object") return schema; const result: Record = {}; for (const [key, value] of Object.entries(schema as Record)) { - if (key === "pattern" && typeof value === "string") { + if (LITERAL_DATA_SCHEMA_KEYWORDS.has(key)) { + result[key] = structuredClone(value); + } else if (key === "pattern" && typeof value === "string") { const portable = re2PortablePattern(value); if (portable !== null) result[key] = portable; } else if (key === "patternProperties" && value !== null && typeof value === "object" && !Array.isArray(value)) { @@ -93,9 +103,61 @@ export function re2PortableSchema(schema: Json): Json { if (portable !== null) properties[portable] = re2PortableSchema(subschema); } result[key] = properties; + } else if (SCHEMA_MAP_KEYWORDS.has(key) && value !== null && typeof value === "object" && !Array.isArray(value)) { + const entries: Record = {}; + for (const [entryKey, subschema] of Object.entries(value as Record)) { + entries[entryKey] = re2PortableSchema(subschema); + } + result[key] = entries; } else { result[key] = re2PortableSchema(value); } } return result; } + +const COMPACT_DROPPED_SCHEMA_KEYWORDS = new Set([ + "description", + "title", + "$schema", + "$id", + "examples", + "default", + "minLength", + "maxLength", + "minItems", + "maxItems", + "minimum", + "maximum", +]); + +/** + * Compact a JSON Schema for MCP clients with a tight total tool-declaration + * byte budget (e.g., Antigravity CLI, which packs MCP tools smallest-first and + * drops large schemas like `paperclip_finish` when the server exceeds ~40 KB). + * Drops metadata/range keywords from schema nodes while preserving all property + * names (including keys named `description` or `title`), literal `enum`/`const` + * values, types, and `required` lists. Calls are still validated against the + * original full schema. + */ +export function compactToolInputSchema(schema: Json): Json { + if (Array.isArray(schema)) return schema.map(compactToolInputSchema); + if (schema === null || typeof schema !== "object") return schema; + const result: Record = {}; + for (const [key, value] of Object.entries(schema as Record)) { + if (COMPACT_DROPPED_SCHEMA_KEYWORDS.has(key)) continue; + if (key === "additionalProperties" && value === false) continue; + if (LITERAL_DATA_SCHEMA_KEYWORDS.has(key)) { + result[key] = structuredClone(value); + } else if ((key === "patternProperties" || SCHEMA_MAP_KEYWORDS.has(key)) && value !== null && typeof value === "object" && !Array.isArray(value)) { + const entries: Record = {}; + for (const [propName, propSchema] of Object.entries(value as Record)) { + entries[propName] = compactToolInputSchema(propSchema); + } + result[key] = entries; + } else { + result[key] = compactToolInputSchema(value); + } + } + return result; +} diff --git a/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts b/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts index addeee4f408..114554212dc 100644 --- a/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts +++ b/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts @@ -1,5 +1,5 @@ import { createHash, randomBytes, timingSafeEqual } from "node:crypto"; -import { re2PortableSchema } from "./re2-schema-patterns.js"; +import { compactToolInputSchema, re2PortableSchema } from "./re2-schema-patterns.js"; import { appendSemanticToolReceipt, semanticCanonicalJson as canonicalJson, semanticInputSha256, type SemanticToolReceipt } from "./semantic-tool-receipt.js"; import { createServer, @@ -71,6 +71,11 @@ export interface RunnerToolBridgeOptions { /** Regex dialect of the client reading tools/list. "re2" serves RE2-portable * patterns (Antigravity CLI); calls are still validated with the originals. */ schemaPatternDialect?: "ecma" | "re2"; + /** Strip verbose schema metadata from tools/list so MCP clients with a tight + * tool-declaration byte budget (Antigravity CLI) keep every Paperclip tool + * including `paperclip_finish` and `paperclip_block`. Calls are still + * validated against the original full schemas. */ + compactToolSchemas?: boolean; } export interface RunnerToolBridge { @@ -171,9 +176,16 @@ export async function startRunnerToolBridge( } } const admittedTools = [...visibleTools, ...privateTools]; - const servedTools = options.schemaPatternDialect === "re2" - ? visibleTools.map(tool => ({ ...tool, inputSchema: re2PortableSchema(tool.inputSchema) as Record })) - : visibleTools; + const servedTools = visibleTools.map(tool => { + let inputSchema = tool.inputSchema; + if (options.schemaPatternDialect === "re2") { + inputSchema = re2PortableSchema(inputSchema) as Record; + } + if (options.compactToolSchemas === true) { + inputSchema = compactToolInputSchema(inputSchema) as Record; + } + return inputSchema === tool.inputSchema ? tool : { ...tool, inputSchema }; + }); const calls = new Map(); const controllers = new Map(); const context = {