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 bc52664cb61..04ada54dcfd 100644 --- a/packages/paperclip-runner/src/drivers/re2-schema-patterns.test.ts +++ b/packages/paperclip-runner/src/drivers/re2-schema-patterns.test.ts @@ -1,6 +1,6 @@ import { afterEach, expect, it } from "vitest"; import { taskDocumentKeySchema } from "../protocol-actions/task-document-key-schema.js"; -import { re2Incompatibility, re2PortableSchema } from "./re2-schema-patterns.js"; +import { compactToolDescription, re2Incompatibility, re2PortableSchema } from "./re2-schema-patterns.js"; import { startRunnerToolBridge, type RunnerToolBridge } from "./runner-tool-bridge.js"; const bridges: RunnerToolBridge[] = []; @@ -140,11 +140,14 @@ it("compacts tools/list schemas below agy's MCP budget while preserving property ]); 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); + // Measure both inputSchema UTF-8 bytes and full tool declaration UTF-8 bytes (name + description + inputSchema). + const totalSchemaBytes = listed.reduce((sum, tool) => sum + Buffer.byteLength(JSON.stringify(tool.inputSchema), "utf8"), 0); + const totalDeclarationBytes = listed.reduce((sum, tool) => sum + Buffer.byteLength(JSON.stringify(tool), "utf8"), 0); + expect(totalSchemaBytes).toBeLessThan(25_000); + expect(totalDeclarationBytes).toBeLessThan(35_000); + for (const tool of listed as Array<{ name: string; description?: string }>) { + expect(Buffer.byteLength(tool.description ?? "", "utf8")).toBeLessThanOrEqual(120); + } // Property names that match JSON Schema metadata keywords must never be stripped. const createTask = listed.find(tool => tool.name === "create_task"); @@ -152,15 +155,21 @@ it("compacts tools/list schemas below agy's MCP budget while preserving property 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"); + // Nullable fields like set_task_monitor.monitor must keep null allowed so clearing works. + const setTaskMonitor = listed.find(tool => tool.name === "set_task_monitor"); + expect(JSON.stringify(setTaskMonitor?.inputSchema)).toContain('"null"'); + + // paperclip_finish and paperclip_block must be present, compacted, and have complete sentences. + const finish = listed.find(tool => tool.name === "paperclip_finish") as { description?: string; inputSchema: unknown } | undefined; + const block = listed.find(tool => tool.name === "paperclip_block") as { description?: string; inputSchema: unknown } | undefined; expect(finish).toBeDefined(); expect(block).toBeDefined(); - expect(JSON.stringify(finish!.inputSchema).length).toBeLessThan(3_500); - expect(JSON.stringify(block!.inputSchema).length).toBeLessThan(3_500); + expect(finish!.description).toBe("Report completed work, work requiring review, or an explicit wait."); + expect(block!.description?.endsWith(".")).toBe(true); + expect(Buffer.byteLength(JSON.stringify(finish), "utf8")).toBeLessThan(3_000); + expect(Buffer.byteLength(JSON.stringify(block), "utf8")).toBeLessThan(3_000); - // Original full Ajv validation still enforces stripped keywords (additionalProperties: false and minimum: 1). + // Original full Ajv validation still enforces stripped keywords (additionalProperties: false, minimum: 1, and pattern). const rejectedExtraProp = await rpc(bridge, { id: 2, method: "tools/call", @@ -174,43 +183,70 @@ it("compacts tools/list schemas below agy's MCP budget while preserving property params: { name: "get_task_history", arguments: { limit: 0 } }, }); expect(rejectedRange.result.isError).toBe(true); + + const rejectedPattern = await rpc(bridge, { + id: 4, + method: "tools/call", + params: { name: "read_document", arguments: { key: "notes.md" } }, + }); + expect(rejectedPattern.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 schema = { + 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: { anyOf: [{ type: "string", format: "uuid", pattern: "^\\u212a$" }, { type: "null" }], title: "Property literally named const" }, + nullableType: { type: ["string", "null"] }, + }, + required: ["choice", "fixed"], + additionalProperties: false, + }; + + // re2PortableSchema rewrites patterns inside properties named enum/const while leaving literal enum/const untouched. + const re2Only = re2PortableSchema(schema) as { + properties: Record>; + }; + expect(re2Only.properties.choice.enum).toEqual(literalEnum); + expect(re2Only.properties.fixed.const).toEqual(literalConst); + expect(re2Only.properties.enum.pattern).toBe(String.raw`^\x{212a}$`); + expect((re2Only.properties.const.anyOf as Array<{ pattern?: string }>)[0]?.pattern).toBe(String.raw`^\x{212a}$`); + + // compactToolSchemas strips metadata/format/pattern and collapses nullable unions while preserving literals. 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, - }, + description: "Pick an action. This second sentence is intentionally very long so that description compaction trims it back to the first sentence.", + inputSchema: schema, }], handler: async () => ({ ok: true }), }); bridges.push(bridge); - const listed = (await rpc(bridge, { id: 1, method: "tools/list" })).result.tools!; + const listed = (await rpc(bridge, { id: 1, method: "tools/list" })).result.tools! as Array<{ + name: string; + description?: string; + inputSchema: Record; + }>; const choose = listed.find(tool => tool.name === "choose_action"); + expect(choose?.description).toBe("Pick an 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}$` }, + enum: { type: "string" }, + const: { anyOf: [{ type: "string" }, { type: "null" }] }, + nullableType: { type: ["string", "null"] }, }, required: ["choice", "fixed"], }); + expect(compactToolDescription("word ".repeat(30), 40)).toBe("word word word word word word word..."); }); diff --git a/packages/paperclip-runner/src/drivers/re2-schema-patterns.ts b/packages/paperclip-runner/src/drivers/re2-schema-patterns.ts index 8d1d4bedf69..5701adb0068 100644 --- a/packages/paperclip-runner/src/drivers/re2-schema-patterns.ts +++ b/packages/paperclip-runner/src/drivers/re2-schema-patterns.ts @@ -123,6 +123,8 @@ const COMPACT_DROPPED_SCHEMA_KEYWORDS = new Set([ "$id", "examples", "default", + "format", + "pattern", "minLength", "maxLength", "minItems", @@ -131,20 +133,52 @@ const COMPACT_DROPPED_SCHEMA_KEYWORDS = new Set([ "maximum", ]); +const DEFAULT_COMPACT_DESCRIPTION_MAX_LENGTH = 120; + +/** + * Compact a tool's top-level MCP description for clients with a tight total + * tool-declaration budget (e.g., Antigravity CLI, which counts full + * `functionDeclarations` including descriptions and silently drops large tools + * like `paperclip_finish` / `paperclip_block` when the server overflows). + */ +export function compactToolDescription( + description: string | undefined, + maxLength = DEFAULT_COMPACT_DESCRIPTION_MAX_LENGTH, +): string | undefined { + if (description === undefined) return undefined; + const normalized = description.trim().replace(/\s+/g, " "); + if (normalized.length <= maxLength) return normalized; + const sentenceEnd = normalized.indexOf(". "); + const firstSentence = sentenceEnd > 0 ? normalized.slice(0, sentenceEnd + 1) : normalized; + if (firstSentence.length <= maxLength) { + return firstSentence; + } + const withoutParentheticals = firstSentence.replace(/\s*\([^)]*\)/g, "").replace(/\s+([.,;:])/g, "$1").trim(); + if (withoutParentheticals.length > 0 && withoutParentheticals.length <= maxLength) { + return withoutParentheticals; + } + if (maxLength <= 3) return normalized.slice(0, Math.max(0, maxLength)); + const slice = normalized.slice(0, maxLength - 3); + const lastSpace = slice.lastIndexOf(" "); + const trimmed = (lastSpace > Math.floor(maxLength / 2) ? slice.slice(0, lastSpace) : slice).trimEnd(); + return `${trimmed}...`; +} + /** * 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. + * drops large tools like `paperclip_finish` when the server overflows). + * Drops metadata/format/pattern/range keywords from schema nodes while + * preserving all property names (including keys named `description` or + * `title`), nullable types, literal `enum`/`const` values, 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 record = schema as Record; const result: Record = {}; - for (const [key, value] of Object.entries(schema as Record)) { + for (const [key, value] of Object.entries(record)) { if (COMPACT_DROPPED_SCHEMA_KEYWORDS.has(key)) continue; if (key === "additionalProperties" && value === false) continue; if (LITERAL_DATA_SCHEMA_KEYWORDS.has(key)) { diff --git a/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts b/packages/paperclip-runner/src/drivers/runner-tool-bridge.ts index 114554212dc..d996cfdb77c 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 { compactToolInputSchema, re2PortableSchema } from "./re2-schema-patterns.js"; +import { compactToolDescription, compactToolInputSchema, re2PortableSchema } from "./re2-schema-patterns.js"; import { appendSemanticToolReceipt, semanticCanonicalJson as canonicalJson, semanticInputSha256, type SemanticToolReceipt } from "./semantic-tool-receipt.js"; import { createServer, @@ -178,13 +178,17 @@ export async function startRunnerToolBridge( const admittedTools = [...visibleTools, ...privateTools]; const servedTools = visibleTools.map(tool => { let inputSchema = tool.inputSchema; + let description = tool.description; if (options.schemaPatternDialect === "re2") { inputSchema = re2PortableSchema(inputSchema) as Record; } if (options.compactToolSchemas === true) { inputSchema = compactToolInputSchema(inputSchema) as Record; + description = compactToolDescription(description); } - return inputSchema === tool.inputSchema ? tool : { ...tool, inputSchema }; + return inputSchema === tool.inputSchema && description === tool.description + ? tool + : { ...tool, ...(description === undefined ? {} : { description }), inputSchema }; }); const calls = new Map(); const controllers = new Map();