@cloudflare/codemode 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp.js CHANGED
@@ -1,24 +1,24 @@
1
1
  import { a as sanitizeToolName, s as normalizeCode, t as generateTypesFromJsonSchema } from "./json-schema-types-D_m9tVnI.js";
2
+ import { n as truncateResult } from "./truncate-Dd-VZZYQ.js";
2
3
  import { z } from "zod";
3
4
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
5
  import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/cfworker";
5
6
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
6
7
  import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
7
8
  //#region src/mcp.ts
8
- const CHARS_PER_TOKEN = 4;
9
- const MAX_TOKENS = 6e3;
10
- const MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;
11
- const TRUNCATION_MARKER = "--- TRUNCATED ---";
12
- const TRUNCATION_FOOTER_PREFIX = `\n\n${TRUNCATION_MARKER}\nResponse was ~`;
13
- const MAX_SANDBOX_TRUNCATED_CHARS = 24512;
14
- function truncateResponse(content) {
15
- const text = typeof content === "string" ? content : JSON.stringify(content, null, 2) ?? "undefined";
16
- if (text.length <= MAX_CHARS) return text;
17
- return `${text.slice(0, MAX_CHARS)}\n\n${TRUNCATION_MARKER}\nResponse was ~${Math.ceil(text.length / CHARS_PER_TOKEN).toLocaleString()} tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.`;
18
- }
19
- function sandboxResponseText(content) {
20
- if (typeof content === "string" && content.length <= MAX_SANDBOX_TRUNCATED_CHARS && content.slice(MAX_CHARS).startsWith(TRUNCATION_FOOTER_PREFIX)) return content;
21
- return truncateResponse(content);
9
+ /** Character budget for a tool response (~6,000 tokens). */
10
+ const MAX_RESPONSE_CHARS = 24e3;
11
+ /**
12
+ * Model-facing text for a sandbox or executor result. Strings are clipped to
13
+ * the budget; structured values are truncated structurally (largest values
14
+ * first) so the text stays valid JSON. The budget applies to the emitted text:
15
+ * pretty-printed when that still fits, compact otherwise.
16
+ */
17
+ function responseText(content) {
18
+ const shaped = truncateResult(content, { maxChars: MAX_RESPONSE_CHARS });
19
+ if (typeof shaped === "string") return shaped;
20
+ const pretty = JSON.stringify(shaped, null, 2) ?? "undefined";
21
+ return pretty.length <= MAX_RESPONSE_CHARS ? pretty : JSON.stringify(shaped) ?? "undefined";
22
22
  }
23
23
  function formatError(error) {
24
24
  return error instanceof Error ? error.message : String(error);
@@ -122,7 +122,7 @@ async function codeMcpServer(options) {
122
122
  };
123
123
  return { content: [{
124
124
  type: "text",
125
- text: truncateResponse(result.result)
125
+ text: responseText(result.result)
126
126
  }] };
127
127
  } catch (error) {
128
128
  return {
@@ -247,17 +247,10 @@ const __resolveRefs = (obj, root, seen = new Set()) => {
247
247
  return result;
248
248
  };
249
249
  let __resolvedSpec;
250
- const __truncateResponse = (content) => {
251
- const text = typeof content === "string" ? content : (JSON.stringify(content, null, 2) ?? "undefined");
252
- if (text.length <= ${MAX_CHARS}) return text;
253
- const truncated = text.slice(0, ${MAX_CHARS});
254
- const estimatedTokens = Math.ceil(text.length / ${CHARS_PER_TOKEN});
255
- return truncated + "\\n\\n${TRUNCATION_MARKER}\\nResponse was ~" + estimatedTokens.toLocaleString() + " tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.";
256
- };
257
250
  const codemode = {
258
251
  spec: async () => (__resolvedSpec ??= __resolveRefs(__rawSpec, __rawSpec))${requestFn ? `,\n ${requestFn}` : ""}
259
252
  };
260
- return __truncateResponse(await (${normalized})());
253
+ return await (${normalized})();
261
254
  }`;
262
255
  }
263
256
  /**
@@ -316,7 +309,7 @@ async () => {
316
309
  };
317
310
  return { content: [{
318
311
  type: "text",
319
- text: sandboxResponseText(result.result)
312
+ text: responseText(result.result)
320
313
  }] };
321
314
  } catch (error) {
322
315
  return {
@@ -357,7 +350,7 @@ async () => {
357
350
  };
358
351
  return { content: [{
359
352
  type: "text",
360
- text: sandboxResponseText(result.result)
353
+ text: responseText(result.result)
361
354
  }] };
362
355
  } catch (error) {
363
356
  return {
package/dist/mcp.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/sdk/validation/cfworker\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n ServerNotification,\n ServerRequest\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor } from \"./executor\";\n\nimport type { JSONSchema7 } from \"json-schema\";\n\n// -- Shared utilities --\n\nconst CHARS_PER_TOKEN = 4;\nconst MAX_TOKENS = 6000;\nconst MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;\nconst TRUNCATION_MARKER = \"--- TRUNCATED ---\";\nconst TRUNCATION_FOOTER_PREFIX = `\\n\\n${TRUNCATION_MARKER}\\nResponse was ~`;\nconst MAX_SANDBOX_TRUNCATED_CHARS = MAX_CHARS + 512;\n\nfunction truncateResponse(content: unknown): string {\n const text =\n typeof content === \"string\"\n ? content\n : (JSON.stringify(content, null, 2) ?? \"undefined\");\n\n if (text.length <= MAX_CHARS) {\n return text;\n }\n\n const truncated = text.slice(0, MAX_CHARS);\n const estimatedTokens = Math.ceil(text.length / CHARS_PER_TOKEN);\n\n return `${truncated}\\n\\n${TRUNCATION_MARKER}\\nResponse was ~${estimatedTokens.toLocaleString()} tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.`;\n}\n\nfunction sandboxResponseText(content: unknown): string {\n if (\n typeof content === \"string\" &&\n content.length <= MAX_SANDBOX_TRUNCATED_CHARS &&\n content.slice(MAX_CHARS).startsWith(TRUNCATION_FOOTER_PREFIX)\n ) {\n return content;\n }\n return truncateResponse(content);\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype CallToolResult = Awaited<ReturnType<Client[\"callTool\"]>>;\n\n/**\n * Unwrap an MCP CallToolResult so sandbox code sees plain values,\n * consistent with how createCodeTool exposes tool results.\n *\n * Priority:\n * 1. Compat `toolResult` → return directly\n * 2. `isError` → throw so sandbox gets a proper exception\n * 3. `structuredContent` → authoritative typed value when present\n * 4. All-text content → JSON.parse or raw string\n * 5. Mixed content (text + images/audio/resources) → return as-is,\n * since binary content has no clean plain-value representation\n */\nfunction unwrapMcpResult(result: CallToolResult): unknown {\n if (\"toolResult\" in result) {\n return result.toolResult;\n }\n\n if (result.isError) {\n const msg =\n result.content\n .filter((c) => c.type === \"text\")\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\") || \"Tool call failed\";\n throw new Error(msg);\n }\n\n if (result.structuredContent != null) {\n return result.structuredContent;\n }\n\n const allText =\n result.content.length > 0 && result.content.every((c) => c.type === \"text\");\n if (allText) {\n const text = result.content\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\");\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n\n return result;\n}\n\n// -- codeMcpServer --\n\nconst CODE_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\n{{example}}`;\n\n/**\n * Wrap an existing MCP server with a single codemode `code` tool.\n *\n * Connects to the upstream server via in-memory transport, discovers its\n * tools, and returns a new MCP server with a `code` tool that exposes\n * all upstream tools as typed methods.\n */\nexport interface CodeMcpServerOptions {\n server: McpServer;\n executor: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for the\n * auto-generated type definitions and `{{example}}` for the example snippet.\n * Falls back to a generic default when omitted.\n */\n description?: string;\n}\n\nexport async function codeMcpServer(\n options: CodeMcpServerOptions\n): Promise<McpServer> {\n const { server, executor, description } = options;\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n\n await server.connect(serverTransport);\n\n const client = new Client({ name: \"codemode-proxy\", version: \"1.0.0\" });\n await client.connect(clientTransport);\n\n const { tools } = await client.listTools();\n\n // Build type hints\n const toolDescriptors: JsonSchemaToolDescriptors = {};\n for (const tool of tools) {\n toolDescriptors[tool.name] = {\n description: tool.description,\n inputSchema: tool.inputSchema as JSONSchema7\n };\n }\n const types = generateTypesFromJsonSchema(toolDescriptors);\n\n // Build executor fns — each upstream tool is a direct method.\n // Unwrap MCP content wrappers so sandbox code sees plain values,\n // consistent with how createCodeTool returns results.\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const tool of tools) {\n const toolName = tool.name;\n fns[toolName] = async (args: unknown) => {\n const result = await client.callTool({\n name: toolName,\n arguments: args as Record<string, unknown>\n });\n return unwrapMcpResult(result);\n };\n }\n\n // Build example from first upstream tool with placeholder args\n const firstTool = tools[0];\n let example = \"\";\n if (firstTool) {\n const schema = firstTool.inputSchema as {\n properties?: Record<string, { type?: string; description?: string }>;\n required?: string[];\n };\n const props = schema.properties ?? {};\n const parts: string[] = [];\n for (const [key, prop] of Object.entries(props)) {\n if (prop.type === \"number\" || prop.type === \"integer\") {\n parts.push(`${key}: 0`);\n } else if (prop.type === \"boolean\") {\n parts.push(`${key}: true`);\n } else {\n parts.push(`${key}: \"...\"`);\n }\n }\n const args = parts.length > 0 ? `{ ${parts.join(\", \")} }` : \"{}\";\n example = `Example: async () => { const r = await codemode.${sanitizeToolName(firstTool.name)}(${args}); return r; }`;\n }\n\n const codeDescription = (description ?? CODE_DESCRIPTION)\n .replace(\"{{types}}\", types)\n .replace(\"{{example}}\", example);\n\n const codemodeServer = new McpServer({\n name: \"codemode\",\n version: \"1.0.0\"\n });\n\n codemodeServer.registerTool(\n \"code\",\n {\n description: codeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(code, [\n { name: \"codemode\", fns }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: truncateResponse(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return codemodeServer;\n}\n\n// -- openApiMcpServer --\n\nexport interface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\n/**\n * MCP context for the outer `execute` tool call.\n *\n * This remains in trusted host code and is never exposed to the sandbox.\n * Use it only while the outer tool call is active.\n */\nexport type OpenApiMcpRequestContext = RequestHandlerExtra<\n ServerRequest,\n ServerNotification\n>;\n\nexport interface OpenApiMcpServerOptions {\n spec: Record<string, unknown>;\n executor: Executor;\n /**\n * Handle an API request from sandbox code on the trusted host.\n *\n * The context belongs to the outer MCP `execute` tool call. It can be used\n * to associate elicitation, sampling, roots, and notifications with that\n * call's response stream.\n *\n * This callback runs while the sandbox is still suspended on its\n * `codemode.request()` call, so the executor timeout covers the whole wait.\n * The default executor timeout (60s) matches the elicitation timeout, so the\n * default config already lets an elicitation finish. If you lower the\n * executor timeout below the elicitation timeout, the sandbox aborts the\n * call before the user can respond.\n */\n request: (\n options: RequestOptions,\n context: OpenApiMcpRequestContext\n ) => Promise<unknown>;\n name?: string;\n version?: string;\n description?: string;\n}\n\nconst SPEC_TYPES = `\n// OpenAPI 3.x spec with $refs resolved inline.\n// The spec object follows the standard OpenAPI 3.x structure.\n\ninterface OperationObject {\n summary?: string;\n description?: string;\n operationId?: string;\n tags?: string[];\n parameters?: Array<{\n name: string;\n in: \"query\" | \"header\" | \"path\" | \"cookie\";\n required?: boolean;\n schema?: unknown;\n description?: string;\n }>;\n requestBody?: {\n required?: boolean;\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n };\n responses?: Record<string, {\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n }>;\n security?: Array<Record<string, string[]>>;\n deprecated?: boolean;\n}\n\ninterface PathItem {\n summary?: string;\n description?: string;\n get?: OperationObject;\n post?: OperationObject;\n put?: OperationObject;\n patch?: OperationObject;\n delete?: OperationObject;\n head?: OperationObject;\n options?: OperationObject;\n trace?: OperationObject;\n parameters?: OperationObject[\"parameters\"];\n}\n\ninterface OpenApiSpec {\n openapi: string;\n info: { title: string; version: string; description?: string };\n paths: Record<string, PathItem>;\n servers?: Array<{ url: string; description?: string }>;\n components?: Record<string, unknown>;\n tags?: Array<{ name: string; description?: string }>;\n}\n`;\n\nconst SEARCH_TYPES = `${SPEC_TYPES}\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n};\n`;\n\nconst REQUEST_TYPES = `\ninterface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\n${SPEC_TYPES}\n\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n request(options: RequestOptions): Promise<unknown>;\n};\n`;\n\nfunction createOpenApiSandboxCode(\n code: string,\n spec: Record<string, unknown>,\n includeRequest: boolean\n): string {\n const normalized = normalizeCode(code);\n const specJson = JSON.stringify(spec).replace(/</g, \"\\\\u003c\");\n const requestFn = includeRequest\n ? `request: async (options) => await __openapiHost.request(options)`\n : \"\";\n\n return `async () => {\nconst __rawSpec = ${specJson};\nconst __refCache = new Map();\nconst __cloneResolvedRef = (value) => structuredClone(value);\nconst __resolveRefs = (obj, root, seen = new Set()) => {\n if (obj === null || obj === undefined) return obj;\n if (typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map((item) => __resolveRefs(item, root, seen));\n\n if (Object.prototype.hasOwnProperty.call(obj, \"$ref\") && typeof obj.$ref === \"string\") {\n const ref = obj.$ref;\n if (seen.has(ref)) return { $circular: ref };\n if (!ref.startsWith(\"#/\")) return obj;\n if (__refCache.has(ref)) return __cloneResolvedRef(__refCache.get(ref));\n seen.add(ref);\n\n const parts = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n let resolved = root;\n for (const part of parts) resolved = resolved?.[part];\n const result = __resolveRefs(resolved, root, seen);\n seen.delete(ref);\n __refCache.set(ref, result);\n return __cloneResolvedRef(result);\n }\n\n const result = {};\n for (const [key, value] of Object.entries(obj)) result[key] = __resolveRefs(value, root, seen);\n return result;\n};\nlet __resolvedSpec;\nconst __truncateResponse = (content) => {\n const text = typeof content === \"string\" ? content : (JSON.stringify(content, null, 2) ?? \"undefined\");\n if (text.length <= ${MAX_CHARS}) return text;\n const truncated = text.slice(0, ${MAX_CHARS});\n const estimatedTokens = Math.ceil(text.length / ${CHARS_PER_TOKEN});\n return truncated + \"\\\\n\\\\n${TRUNCATION_MARKER}\\\\nResponse was ~\" + estimatedTokens.toLocaleString() + \" tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.\";\n};\nconst codemode = {\n spec: async () => (__resolvedSpec ??= __resolveRefs(__rawSpec, __rawSpec))${requestFn ? `,\\n ${requestFn}` : \"\"}\n};\nreturn __truncateResponse(await (${normalized})());\n}`;\n}\n\n/**\n * Create an MCP server with search + execute tools from an OpenAPI spec.\n *\n * The search tool lets the LLM query the spec to find endpoints.\n * The execute tool lets the LLM call the API via a user-provided\n * request function that runs on the host (auth never enters the sandbox).\n */\nexport function openApiMcpServer(options: OpenApiMcpServerOptions): McpServer {\n const {\n executor,\n request: requestFn,\n name = \"openapi\",\n version = \"1.0.0\",\n description\n } = options;\n\n const spec = options.spec;\n\n const server = new McpServer(\n { name, version },\n { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() }\n );\n\n // --- search tool ---\n server.registerTool(\n \"search\",\n {\n description: `Search the OpenAPI spec. codemode.spec() returns $refs resolved inline.\n\nTypes:\n${SEARCH_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExamples:\n\n// List all paths\nasync () => {\n const spec = await codemode.spec();\n return Object.keys(spec.paths);\n}\n\n// Find endpoints by tag\nasync () => {\n const spec = await codemode.spec();\n const results = [];\n for (const [path, methods] of Object.entries(spec.paths)) {\n for (const [method, op] of Object.entries(methods)) {\n if (op.tags?.some(t => t.toLowerCase() === 'your_tag')) {\n results.push({ method: method.toUpperCase(), path, summary: op.summary });\n }\n }\n }\n return results;\n}`,\n inputSchema: {\n code: z\n .string()\n .describe(\"JavaScript async arrow function to search the spec\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, false),\n []\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: sandboxResponseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n // --- execute tool ---\n const executeDescription = `Execute API calls using JavaScript code. First use 'search' to find the right endpoints.\n\nAvailable in your code:\n${REQUEST_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExample:\nasync () => {\n return await codemode.request({ method: \"GET\", path: \"/your/endpoint\" });\n}${description ? `\\n\\n${description}` : \"\"}`;\n\n server.registerTool(\n \"execute\",\n {\n description: executeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }, context) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, true),\n [\n {\n name: \"__openapiHost\",\n fns: {\n request: (args: unknown) =>\n requestFn(args as RequestOptions, context)\n }\n }\n ]\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: sandboxResponseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return server;\n}\n"],"mappings":";;;;;;;AAsBA,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,YAAY,aAAa;AAC/B,MAAM,oBAAoB;AAC1B,MAAM,2BAA2B,OAAO,kBAAkB;AAC1D,MAAM,8BAA8B;AAEpC,SAAS,iBAAiB,SAA0B;CAClD,MAAM,OACJ,OAAO,YAAY,WACf,UACC,KAAK,UAAU,SAAS,MAAM,CAAC,KAAK;CAE3C,IAAI,KAAK,UAAU,WACjB,OAAO;CAMT,OAAO,GAHW,KAAK,MAAM,GAAG,SAGd,EAAE,MAAM,kBAAkB,kBAFpB,KAAK,KAAK,KAAK,SAAS,eAE4B,CAAC,CAAC,eAAe,EAAE,kBAAkB,WAAW,eAAe,EAAE;AAC/I;AAEA,SAAS,oBAAoB,SAA0B;CACrD,IACE,OAAO,YAAY,YACnB,QAAQ,UAAU,+BAClB,QAAQ,MAAM,SAAS,CAAC,CAAC,WAAW,wBAAwB,GAE5D,OAAO;CAET,OAAO,iBAAiB,OAAO;AACjC;AAEA,SAAS,YAAY,OAAwB;CAC3C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;;;;;;;;;;;;AAgBA,SAAS,gBAAgB,QAAiC;CACxD,IAAI,gBAAgB,QAClB,OAAO,OAAO;C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OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,YAAY,KAAK;IAAI,CAChE;IACA,SAAS;GACX;EACF;CACF,CACF;CAGA,MAAM,qBAAqB;;;EAG3B,cAAc;;;;;;;GAOb,cAAc,OAAO,gBAAgB;CAEtC,OAAO,aACL,WACA;EACE,aAAa;EACb,aAAa,EACX,MAAM,EAAE,OAAO,CAAC,CAAC,SAAS,4CAA4C,EACxE;CACF,GACA,OAAO,EAAE,QAAQ,YAAY;EAC3B,IAAI;GACF,MAAM,SAAS,MAAM,SAAS,QAC5B,yBAAyB,MAAM,MAAM,IAAI,GACzC,CACE;IACE,MAAM;IACN,KAAK,EACH,UAAU,SACR,UAAU,MAAwB,OAAO,EAC7C;GACF,CACF,CACF;GACA,IAAI,OAAO,OACT,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;IAAQ,CAC1D;IACA,SAAS;GACX;GAEF,OAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAiB,MAAM,oBAAoB,OAAO,MAAM;GAAE,CACpE,EACF;EACF,SAAS,OAAO;GACd,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,YAAY,KAAK;IAAI,CAChE;IACA,SAAS;GACX;EACF;CACF,CACF;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/sdk/validation/cfworker\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport type { RequestHandlerExtra } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport type {\n ServerNotification,\n ServerRequest\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport { z } from \"zod\";\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor } from \"./executor\";\nimport { truncateResult } from \"./truncate\";\n\nimport type { JSONSchema7 } from \"json-schema\";\n\n// -- Shared utilities --\n\n/** Character budget for a tool response (~6,000 tokens). */\nconst MAX_RESPONSE_CHARS = 24_000;\n\n/**\n * Model-facing text for a sandbox or executor result. Strings are clipped to\n * the budget; structured values are truncated structurally (largest values\n * first) so the text stays valid JSON. The budget applies to the emitted text:\n * pretty-printed when that still fits, compact otherwise.\n */\nfunction responseText(content: unknown): string {\n const shaped = truncateResult(content, { maxChars: MAX_RESPONSE_CHARS });\n if (typeof shaped === \"string\") return shaped;\n const pretty = JSON.stringify(shaped, null, 2) ?? \"undefined\";\n return pretty.length <= MAX_RESPONSE_CHARS\n ? pretty\n : (JSON.stringify(shaped) ?? \"undefined\");\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\ntype CallToolResult = Awaited<ReturnType<Client[\"callTool\"]>>;\n\n/**\n * Unwrap an MCP CallToolResult so sandbox code sees plain values,\n * consistent with how createCodeTool exposes tool results.\n *\n * Priority:\n * 1. Compat `toolResult` → return directly\n * 2. `isError` → throw so sandbox gets a proper exception\n * 3. `structuredContent` → authoritative typed value when present\n * 4. All-text content → JSON.parse or raw string\n * 5. Mixed content (text + images/audio/resources) → return as-is,\n * since binary content has no clean plain-value representation\n */\nfunction unwrapMcpResult(result: CallToolResult): unknown {\n if (\"toolResult\" in result) {\n return result.toolResult;\n }\n\n if (result.isError) {\n const msg =\n result.content\n .filter((c) => c.type === \"text\")\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\") || \"Tool call failed\";\n throw new Error(msg);\n }\n\n if (result.structuredContent != null) {\n return result.structuredContent;\n }\n\n const allText =\n result.content.length > 0 && result.content.every((c) => c.type === \"text\");\n if (allText) {\n const text = result.content\n .map((c) => (\"text\" in c ? c.text : \"\"))\n .join(\"\\n\");\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n }\n\n return result;\n}\n\n// -- codeMcpServer --\n\nconst CODE_DESCRIPTION = `Execute code to achieve a goal.\n\nAvailable:\n{{types}}\n\nWrite an async arrow function in JavaScript that returns the result.\nDo NOT use TypeScript syntax — no type annotations, interfaces, or generics.\nDo NOT define named functions then call them — just write the arrow function body directly.\n\n{{example}}`;\n\n/**\n * Wrap an existing MCP server with a single codemode `code` tool.\n *\n * Connects to the upstream server via in-memory transport, discovers its\n * tools, and returns a new MCP server with a `code` tool that exposes\n * all upstream tools as typed methods.\n */\nexport interface CodeMcpServerOptions {\n server: McpServer;\n executor: Executor;\n /**\n * Custom tool description. Use `{{types}}` as a placeholder for the\n * auto-generated type definitions and `{{example}}` for the example snippet.\n * Falls back to a generic default when omitted.\n */\n description?: string;\n}\n\nexport async function codeMcpServer(\n options: CodeMcpServerOptions\n): Promise<McpServer> {\n const { server, executor, description } = options;\n const [clientTransport, serverTransport] =\n InMemoryTransport.createLinkedPair();\n\n await server.connect(serverTransport);\n\n const client = new Client({ name: \"codemode-proxy\", version: \"1.0.0\" });\n await client.connect(clientTransport);\n\n const { tools } = await client.listTools();\n\n // Build type hints\n const toolDescriptors: JsonSchemaToolDescriptors = {};\n for (const tool of tools) {\n toolDescriptors[tool.name] = {\n description: tool.description,\n inputSchema: tool.inputSchema as JSONSchema7\n };\n }\n const types = generateTypesFromJsonSchema(toolDescriptors);\n\n // Build executor fns — each upstream tool is a direct method.\n // Unwrap MCP content wrappers so sandbox code sees plain values,\n // consistent with how createCodeTool returns results.\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n for (const tool of tools) {\n const toolName = tool.name;\n fns[toolName] = async (args: unknown) => {\n const result = await client.callTool({\n name: toolName,\n arguments: args as Record<string, unknown>\n });\n return unwrapMcpResult(result);\n };\n }\n\n // Build example from first upstream tool with placeholder args\n const firstTool = tools[0];\n let example = \"\";\n if (firstTool) {\n const schema = firstTool.inputSchema as {\n properties?: Record<string, { type?: string; description?: string }>;\n required?: string[];\n };\n const props = schema.properties ?? {};\n const parts: string[] = [];\n for (const [key, prop] of Object.entries(props)) {\n if (prop.type === \"number\" || prop.type === \"integer\") {\n parts.push(`${key}: 0`);\n } else if (prop.type === \"boolean\") {\n parts.push(`${key}: true`);\n } else {\n parts.push(`${key}: \"...\"`);\n }\n }\n const args = parts.length > 0 ? `{ ${parts.join(\", \")} }` : \"{}\";\n example = `Example: async () => { const r = await codemode.${sanitizeToolName(firstTool.name)}(${args}); return r; }`;\n }\n\n const codeDescription = (description ?? CODE_DESCRIPTION)\n .replace(\"{{types}}\", types)\n .replace(\"{{example}}\", example);\n\n const codemodeServer = new McpServer({\n name: \"codemode\",\n version: \"1.0.0\"\n });\n\n codemodeServer.registerTool(\n \"code\",\n {\n description: codeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(code, [\n { name: \"codemode\", fns }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: responseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return codemodeServer;\n}\n\n// -- openApiMcpServer --\n\nexport interface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\n/**\n * MCP context for the outer `execute` tool call.\n *\n * This remains in trusted host code and is never exposed to the sandbox.\n * Use it only while the outer tool call is active.\n */\nexport type OpenApiMcpRequestContext = RequestHandlerExtra<\n ServerRequest,\n ServerNotification\n>;\n\nexport interface OpenApiMcpServerOptions {\n spec: Record<string, unknown>;\n executor: Executor;\n /**\n * Handle an API request from sandbox code on the trusted host.\n *\n * The context belongs to the outer MCP `execute` tool call. It can be used\n * to associate elicitation, sampling, roots, and notifications with that\n * call's response stream.\n *\n * This callback runs while the sandbox is still suspended on its\n * `codemode.request()` call, so the executor timeout covers the whole wait.\n * The default executor timeout (60s) matches the elicitation timeout, so the\n * default config already lets an elicitation finish. If you lower the\n * executor timeout below the elicitation timeout, the sandbox aborts the\n * call before the user can respond.\n */\n request: (\n options: RequestOptions,\n context: OpenApiMcpRequestContext\n ) => Promise<unknown>;\n name?: string;\n version?: string;\n description?: string;\n}\n\nconst SPEC_TYPES = `\n// OpenAPI 3.x spec with $refs resolved inline.\n// The spec object follows the standard OpenAPI 3.x structure.\n\ninterface OperationObject {\n summary?: string;\n description?: string;\n operationId?: string;\n tags?: string[];\n parameters?: Array<{\n name: string;\n in: \"query\" | \"header\" | \"path\" | \"cookie\";\n required?: boolean;\n schema?: unknown;\n description?: string;\n }>;\n requestBody?: {\n required?: boolean;\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n };\n responses?: Record<string, {\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n }>;\n security?: Array<Record<string, string[]>>;\n deprecated?: boolean;\n}\n\ninterface PathItem {\n summary?: string;\n description?: string;\n get?: OperationObject;\n post?: OperationObject;\n put?: OperationObject;\n patch?: OperationObject;\n delete?: OperationObject;\n head?: OperationObject;\n options?: OperationObject;\n trace?: OperationObject;\n parameters?: OperationObject[\"parameters\"];\n}\n\ninterface OpenApiSpec {\n openapi: string;\n info: { title: string; version: string; description?: string };\n paths: Record<string, PathItem>;\n servers?: Array<{ url: string; description?: string }>;\n components?: Record<string, unknown>;\n tags?: Array<{ name: string; description?: string }>;\n}\n`;\n\nconst SEARCH_TYPES = `${SPEC_TYPES}\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n};\n`;\n\nconst REQUEST_TYPES = `\ninterface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\n${SPEC_TYPES}\n\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n request(options: RequestOptions): Promise<unknown>;\n};\n`;\n\nfunction createOpenApiSandboxCode(\n code: string,\n spec: Record<string, unknown>,\n includeRequest: boolean\n): string {\n const normalized = normalizeCode(code);\n const specJson = JSON.stringify(spec).replace(/</g, \"\\\\u003c\");\n const requestFn = includeRequest\n ? `request: async (options) => await __openapiHost.request(options)`\n : \"\";\n\n return `async () => {\nconst __rawSpec = ${specJson};\nconst __refCache = new Map();\nconst __cloneResolvedRef = (value) => structuredClone(value);\nconst __resolveRefs = (obj, root, seen = new Set()) => {\n if (obj === null || obj === undefined) return obj;\n if (typeof obj !== \"object\") return obj;\n if (Array.isArray(obj)) return obj.map((item) => __resolveRefs(item, root, seen));\n\n if (Object.prototype.hasOwnProperty.call(obj, \"$ref\") && typeof obj.$ref === \"string\") {\n const ref = obj.$ref;\n if (seen.has(ref)) return { $circular: ref };\n if (!ref.startsWith(\"#/\")) return obj;\n if (__refCache.has(ref)) return __cloneResolvedRef(__refCache.get(ref));\n seen.add(ref);\n\n const parts = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n let resolved = root;\n for (const part of parts) resolved = resolved?.[part];\n const result = __resolveRefs(resolved, root, seen);\n seen.delete(ref);\n __refCache.set(ref, result);\n return __cloneResolvedRef(result);\n }\n\n const result = {};\n for (const [key, value] of Object.entries(obj)) result[key] = __resolveRefs(value, root, seen);\n return result;\n};\nlet __resolvedSpec;\nconst codemode = {\n spec: async () => (__resolvedSpec ??= __resolveRefs(__rawSpec, __rawSpec))${requestFn ? `,\\n ${requestFn}` : \"\"}\n};\nreturn await (${normalized})();\n}`;\n}\n\n/**\n * Create an MCP server with search + execute tools from an OpenAPI spec.\n *\n * The search tool lets the LLM query the spec to find endpoints.\n * The execute tool lets the LLM call the API via a user-provided\n * request function that runs on the host (auth never enters the sandbox).\n */\nexport function openApiMcpServer(options: OpenApiMcpServerOptions): McpServer {\n const {\n executor,\n request: requestFn,\n name = \"openapi\",\n version = \"1.0.0\",\n description\n } = options;\n\n const spec = options.spec;\n\n const server = new McpServer(\n { name, version },\n { jsonSchemaValidator: new CfWorkerJsonSchemaValidator() }\n );\n\n // --- search tool ---\n server.registerTool(\n \"search\",\n {\n description: `Search the OpenAPI spec. codemode.spec() returns $refs resolved inline.\n\nTypes:\n${SEARCH_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExamples:\n\n// List all paths\nasync () => {\n const spec = await codemode.spec();\n return Object.keys(spec.paths);\n}\n\n// Find endpoints by tag\nasync () => {\n const spec = await codemode.spec();\n const results = [];\n for (const [path, methods] of Object.entries(spec.paths)) {\n for (const [method, op] of Object.entries(methods)) {\n if (op.tags?.some(t => t.toLowerCase() === 'your_tag')) {\n results.push({ method: method.toUpperCase(), path, summary: op.summary });\n }\n }\n }\n return results;\n}`,\n inputSchema: {\n code: z\n .string()\n .describe(\"JavaScript async arrow function to search the spec\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, false),\n []\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: responseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n // --- execute tool ---\n const executeDescription = `Execute API calls using JavaScript code. First use 'search' to find the right endpoints.\n\nAvailable in your code:\n${REQUEST_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExample:\nasync () => {\n return await codemode.request({ method: \"GET\", path: \"/your/endpoint\" });\n}${description ? `\\n\\n${description}` : \"\"}`;\n\n server.registerTool(\n \"execute\",\n {\n description: executeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }, context) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, true),\n [\n {\n name: \"__openapiHost\",\n fns: {\n request: (args: unknown) =>\n requestFn(args as RequestOptions, context)\n }\n }\n ]\n );\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: responseText(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return server;\n}\n"],"mappings":";;;;;;;;;AAwBA,MAAM,qBAAqB;;;;;;;AAQ3B,SAAS,aAAa,SAA0B;CAC9C,MAAM,SAAS,eAAe,SAAS,EAAE,UAAU,mBAAmB,CAAC;CACvE,IAAI,OAAO,WAAW,UAAU,OAAO;CACvC,MAAM,SAAS,KAAK,UAAU,QAAQ,MAAM,CAAC,KAAK;CAClD,OAAO,OAAO,UAAU,qBACpB,SACC,KAAK,UAAU,MAAM,KAAK;AACjC;AAEA,SAAS,YAAY,OAAwB;CAC3C,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC9D;;;;;;;;;;;;;AAgBA,SAAS,gBAAgB,QAAiC;CACxD,IAAI,gBAAgB,QAClB,OAAO,OAAO;CAGhB,IAAI,OAAO,SAAS;EAClB,MAAM,MACJ,OAAO,QACJ,QAAQ,MAAM,EAAE,SAAS,MAAM,CAAC,CAChC,KAAK,MAAO,UAAU,IAAI,EAAE,OAAO,EAAG,CAAC,CACvC,KAAK,IAAI,KAAK;EACnB,MAAM,IAAI,MAAM,GAAG;CACrB;CAEA,IAAI,OAAO,qBAAqB,MAC9B,OAAO,OAAO;CAKhB,IADE,OAAO,QAAQ,SAAS,KAAK,OAAO,QAAQ,OAAO,MAAM,EAAE,SAAS,MAAM,GAC/D;EACX,MAAM,OAAO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AAwB,OAAO,EAC7C;GACF,CACF,CACF;GACA,IAAI,OAAO,OACT,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;IAAQ,CAC1D;IACA,SAAS;GACX;GAEF,OAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAiB,MAAM,aAAa,OAAO,MAAM;GAAE,CAC7D,EACF;EACF,SAAS,OAAO;GACd,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,YAAY,KAAK;IAAI,CAChE;IACA,SAAS;GACX;EACF;CACF,CACF;CAEA,OAAO;AACT"}
@@ -0,0 +1,191 @@
1
+ //#region src/truncate.ts
2
+ /**
3
+ * Result truncation utilities.
4
+ *
5
+ * Tool and sandbox results can be large enough to blow a model's context
6
+ * window. These cap the serialized size of a value while leaving small,
7
+ * structured results intact so the model can still reason over them. They are
8
+ * the default building blocks for a `transformResult` hook (see
9
+ * `createCodemodeRuntime`).
10
+ *
11
+ * Structured values are truncated structurally: the output is always valid
12
+ * JSON of the same shape, with the largest values cut first. A truncated
13
+ * string ends with a marker, a truncated array ends with a marker element
14
+ * counting the dropped items, and an object that had to lose entries carries a
15
+ * marker entry naming the omitted keys. Every marker contains
16
+ * `--- TRUNCATED ---` so callers and models can find them.
17
+ */
18
+ /** ~4 characters per token is a reasonable cross-model estimate. */
19
+ const CHARS_PER_TOKEN = 4;
20
+ const DEFAULT_MAX_TOKENS = 6e3;
21
+ const TRUNCATION_MARKER = "--- TRUNCATED ---";
22
+ /**
23
+ * The least a string or container is worth keeping at (see `floorSize`). A
24
+ * value that would get fewer serialized characters than this is dropped in
25
+ * favour of its siblings rather than reduced to a bare marker.
26
+ */
27
+ const MIN_SLOT = 128;
28
+ function budget(options) {
29
+ const maxTokens = options?.maxTokens ?? DEFAULT_MAX_TOKENS;
30
+ return {
31
+ maxChars: options?.maxChars ?? maxTokens * CHARS_PER_TOKEN,
32
+ maxTokens
33
+ };
34
+ }
35
+ /**
36
+ * Truncate a text response to a character budget, appending a marker that notes
37
+ * the original size so the model knows the output was clipped. Returns the
38
+ * input unchanged when it is within budget.
39
+ */
40
+ function truncateResponse(text, options) {
41
+ const { maxChars, maxTokens } = budget(options);
42
+ if (text.length <= maxChars) return text;
43
+ const estimatedTokens = Math.ceil(text.length / CHARS_PER_TOKEN);
44
+ return text.slice(0, maxChars) + `\n\n${TRUNCATION_MARKER}\nResponse was ~${estimatedTokens.toLocaleString()} tokens (limit: ${maxTokens.toLocaleString()}). Narrow the request to reduce response size.`;
45
+ }
46
+ /**
47
+ * Truncate a structured result. Strings are truncated directly. Other values
48
+ * pass through unchanged (same reference) when their JSON serialization is
49
+ * within budget. When oversized, the value is shrunk structurally — largest
50
+ * values first, deepest last — so the model gets a bounded value that is still
51
+ * valid JSON of the original shape, with markers where content was cut.
52
+ *
53
+ * Values that can't be serialized (cycles, bigint, `undefined`) are returned
54
+ * unchanged.
55
+ */
56
+ function truncateResult(value, options) {
57
+ if (typeof value === "string") return truncateResponse(value, options);
58
+ let serialized;
59
+ try {
60
+ serialized = JSON.stringify(value);
61
+ } catch {
62
+ return value;
63
+ }
64
+ if (serialized === void 0) return value;
65
+ const { maxChars } = budget(options);
66
+ if (serialized.length <= maxChars) return value;
67
+ const shrunk = shrink(JSON.parse(serialized), maxChars);
68
+ return size(shrunk) <= maxChars ? shrunk : truncateResponse(serialized, options);
69
+ }
70
+ /** Serialized size in characters (compact JSON). */
71
+ function size(value) {
72
+ return JSON.stringify(value).length;
73
+ }
74
+ /** Only strings and containers can give up characters; scalars are atomic. */
75
+ function shrinkable(value) {
76
+ return typeof value === "string" || typeof value === "object" && !!value;
77
+ }
78
+ /**
79
+ * The least budget a value is kept at; a scalar must fit whole. The floor
80
+ * never exceeds half the container's own budget, so tiny budgets still keep
81
+ * something rather than nothing.
82
+ */
83
+ function floorSize(value, maxChars) {
84
+ const full = size(value);
85
+ return shrinkable(value) ? Math.min(full, MIN_SLOT, Math.max(2, Math.floor(maxChars / 2))) : full;
86
+ }
87
+ function shrink(value, maxChars) {
88
+ if (size(value) <= maxChars) return value;
89
+ if (typeof value === "string") return shrinkString(value, maxChars);
90
+ if (Array.isArray(value)) return shrinkArray(value, maxChars);
91
+ if (typeof value === "object" && value !== null) return shrinkObject(value, maxChars);
92
+ return value;
93
+ }
94
+ function shrinkString(value, maxChars) {
95
+ const suffix = ` ${TRUNCATION_MARKER} ${value.length.toLocaleString()} chars`;
96
+ let keep = Math.max(0, maxChars - suffix.length - 2);
97
+ let out = value.slice(0, keep) + suffix;
98
+ while (keep > 0 && size(out) > maxChars) {
99
+ keep = Math.max(0, keep - (size(out) - maxChars));
100
+ out = value.slice(0, keep) + suffix;
101
+ }
102
+ return size(out) <= maxChars ? out : TRUNCATION_MARKER.slice(0, Math.max(0, maxChars - 2));
103
+ }
104
+ /**
105
+ * Share `available` characters across values by water-filling: values are
106
+ * admitted smallest first, each taking the lesser of its full size and an
107
+ * equal share of what is left. Requires `available >= Σ floorSize(values)`;
108
+ * then every value receives at least its floor.
109
+ */
110
+ function allocate(values, available) {
111
+ const sizes = values.map(size);
112
+ const order = sizes.map((_, i) => i).sort((a, b) => sizes[a] - sizes[b]);
113
+ const allocation = new Array(values.length);
114
+ let remaining = available;
115
+ let count = values.length;
116
+ for (const i of order) {
117
+ const alloc = Math.min(sizes[i], Math.floor(remaining / count));
118
+ allocation[i] = alloc;
119
+ remaining -= alloc;
120
+ count--;
121
+ }
122
+ return allocation;
123
+ }
124
+ function shrinkArray(items, maxChars) {
125
+ const marker = (dropped) => `${TRUNCATION_MARKER} ${dropped.toLocaleString()} more items`;
126
+ const floors = items.map((item) => floorSize(item, maxChars));
127
+ const skeleton = (count) => 2 + Math.max(0, count - 1);
128
+ let keep = items.length;
129
+ if (floors.reduce((n, f) => n + f, 0) + skeleton(keep) > maxChars) {
130
+ const tail = size(marker(items.length)) + 1;
131
+ let used = skeleton(0) + tail;
132
+ keep = 0;
133
+ while (keep < items.length && used + floors[keep] + 1 <= maxChars) {
134
+ used += floors[keep] + 1;
135
+ keep++;
136
+ }
137
+ }
138
+ const kept = items.slice(0, keep);
139
+ const dropped = items.length - keep;
140
+ const tail = dropped > 0 ? size(marker(dropped)) + (keep > 0 ? 1 : 0) : 0;
141
+ const allocation = allocate(kept, maxChars - skeleton(keep) - tail);
142
+ const out = kept.map((item, i) => shrink(item, allocation[i]));
143
+ if (dropped > 0 && size([...out, marker(dropped)]) <= maxChars) out.push(marker(dropped));
144
+ return out;
145
+ }
146
+ function shrinkObject(value, maxChars) {
147
+ const entries = Object.entries(value);
148
+ let markerKey = TRUNCATION_MARKER;
149
+ while (markerKey in value) markerKey += " ";
150
+ const keyCost = (key) => size(key) + 1;
151
+ const floors = entries.map(([k, v]) => keyCost(k) + floorSize(v, maxChars));
152
+ const floorOf = (chars) => Math.min(chars, MIN_SLOT, Math.max(2, Math.floor(maxChars / 2)));
153
+ const byValueSize = entries.map((_, i) => i).sort((a, b) => size(entries[b][1]) - size(entries[a][1]));
154
+ const dropped = /* @__PURE__ */ new Set();
155
+ let present = entries.length;
156
+ let floorsSum = floors.reduce((n, f) => n + f, 0);
157
+ let namesLength = 0;
158
+ const noteLength = () => `${dropped.size.toLocaleString()} keys omitted: `.length + namesLength + 2 * (dropped.size - 1);
159
+ const cost = () => {
160
+ const marker = dropped.size > 0 ? keyCost(markerKey) + floorOf(noteLength() + 2) : 0;
161
+ const count = present + (dropped.size > 0 ? 1 : 0);
162
+ return 2 + Math.max(0, count - 1) + floorsSum + marker;
163
+ };
164
+ for (const i of byValueSize) {
165
+ if (cost() <= maxChars) break;
166
+ dropped.add(i);
167
+ present--;
168
+ floorsSum -= floors[i];
169
+ namesLength += size(entries[i][0]) - 2;
170
+ }
171
+ const kept = entries.filter((_, i) => !dropped.has(i));
172
+ const omitted = [...dropped].sort((a, b) => a - b).map((i) => entries[i][0]);
173
+ const note = `${omitted.length.toLocaleString()} keys omitted: ${omitted.join(", ")}`;
174
+ if (cost() > maxChars) {
175
+ const room = maxChars - 2 - keyCost(markerKey);
176
+ return room >= 2 ? { [markerKey]: shrink(note, room) } : {};
177
+ }
178
+ const all = [...kept];
179
+ if (omitted.length > 0) all.push([markerKey, note]);
180
+ const fixed = 2 + Math.max(0, all.length - 1) + all.reduce((n, [k]) => n + keyCost(k), 0);
181
+ const allocation = allocate(all.map(([, v]) => v), maxChars - fixed);
182
+ const out = {};
183
+ all.forEach(([k, v], i) => {
184
+ out[k] = shrink(v, allocation[i]);
185
+ });
186
+ return out;
187
+ }
188
+ //#endregion
189
+ export { truncateResult as n, truncateResponse as t };
190
+
191
+ //# sourceMappingURL=truncate-Dd-VZZYQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"truncate-Dd-VZZYQ.js","names":[],"sources":["../src/truncate.ts"],"sourcesContent":["/**\n * Result truncation utilities.\n *\n * Tool and sandbox results can be large enough to blow a model's context\n * window. These cap the serialized size of a value while leaving small,\n * structured results intact so the model can still reason over them. They are\n * the default building blocks for a `transformResult` hook (see\n * `createCodemodeRuntime`).\n *\n * Structured values are truncated structurally: the output is always valid\n * JSON of the same shape, with the largest values cut first. A truncated\n * string ends with a marker, a truncated array ends with a marker element\n * counting the dropped items, and an object that had to lose entries carries a\n * marker entry naming the omitted keys. Every marker contains\n * `--- TRUNCATED ---` so callers and models can find them.\n */\n\n/** ~4 characters per token is a reasonable cross-model estimate. */\nconst CHARS_PER_TOKEN = 4;\nconst DEFAULT_MAX_TOKENS = 6000;\nconst TRUNCATION_MARKER = \"--- TRUNCATED ---\";\n/**\n * The least a string or container is worth keeping at (see `floorSize`). A\n * value that would get fewer serialized characters than this is dropped in\n * favour of its siblings rather than reduced to a bare marker.\n */\nconst MIN_SLOT = 128;\n\nexport type TruncateOptions = {\n /**\n * Maximum characters in the (serialized) output before truncation kicks in.\n * Defaults to `maxTokens * 4`.\n */\n maxChars?: number;\n /** Token budget used to derive the default `maxChars`. Defaults to 6000. */\n maxTokens?: number;\n};\n\nfunction budget(options?: TruncateOptions): {\n maxChars: number;\n maxTokens: number;\n} {\n const maxTokens = options?.maxTokens ?? DEFAULT_MAX_TOKENS;\n const maxChars = options?.maxChars ?? maxTokens * CHARS_PER_TOKEN;\n return { maxChars, maxTokens };\n}\n\n/**\n * Truncate a text response to a character budget, appending a marker that notes\n * the original size so the model knows the output was clipped. Returns the\n * input unchanged when it is within budget.\n */\nexport function truncateResponse(\n text: string,\n options?: TruncateOptions\n): string {\n const { maxChars, maxTokens } = budget(options);\n if (text.length <= maxChars) return text;\n\n const estimatedTokens = Math.ceil(text.length / CHARS_PER_TOKEN);\n return (\n text.slice(0, maxChars) +\n `\\n\\n${TRUNCATION_MARKER}\\nResponse was ~${estimatedTokens.toLocaleString()} tokens ` +\n `(limit: ${maxTokens.toLocaleString()}). Narrow the request to reduce response size.`\n );\n}\n\n/**\n * Truncate a structured result. Strings are truncated directly. Other values\n * pass through unchanged (same reference) when their JSON serialization is\n * within budget. When oversized, the value is shrunk structurally — largest\n * values first, deepest last — so the model gets a bounded value that is still\n * valid JSON of the original shape, with markers where content was cut.\n *\n * Values that can't be serialized (cycles, bigint, `undefined`) are returned\n * unchanged.\n */\nexport function truncateResult(\n value: unknown,\n options?: TruncateOptions\n): unknown {\n if (typeof value === \"string\") return truncateResponse(value, options);\n\n let serialized: string | undefined;\n try {\n serialized = JSON.stringify(value);\n } catch {\n return value;\n }\n if (serialized === undefined) return value;\n\n const { maxChars } = budget(options);\n if (serialized.length <= maxChars) return value;\n\n // Re-parse so `toJSON`, class instances and `undefined` members are seen in\n // their serialized form — the shape the model would receive anyway.\n const shrunk = shrink(JSON.parse(serialized) as Json, maxChars);\n // `shrink` honours its budget for anything a container can hold; only a\n // scalar (a number too long for the budget) can still miss it.\n return size(shrunk) <= maxChars\n ? shrunk\n : truncateResponse(serialized, options);\n}\n\n// ---------------------------------------------------------------------------\n// Structural shrinking\n// ---------------------------------------------------------------------------\n//\n// Every `shrink*` below returns a value whose compact serialization fits the\n// budget it was given, provided the budget can hold an empty container (2\n// chars). Containers share their budget by water-filling: each child is owed\n// at least its floor (`floorSize`), small children keep their full size, and\n// the largest children absorb the cut. A container only drops children when\n// even their floors cannot fit — arrays drop from the tail (order carries\n// meaning), objects drop their largest values first (keys are all meaningful).\n\ntype Json = string | number | boolean | null | Json[] | { [key: string]: Json };\n\n/** Serialized size in characters (compact JSON). */\nfunction size(value: Json): number {\n return JSON.stringify(value).length;\n}\n\n/** Only strings and containers can give up characters; scalars are atomic. */\nfunction shrinkable(value: Json): boolean {\n return typeof value === \"string\" || (typeof value === \"object\" && !!value);\n}\n\n/**\n * The least budget a value is kept at; a scalar must fit whole. The floor\n * never exceeds half the container's own budget, so tiny budgets still keep\n * something rather than nothing.\n */\nfunction floorSize(value: Json, maxChars: number): number {\n const full = size(value);\n return shrinkable(value)\n ? Math.min(full, MIN_SLOT, Math.max(2, Math.floor(maxChars / 2)))\n : full;\n}\n\nfunction shrink(value: Json, maxChars: number): Json {\n if (size(value) <= maxChars) return value;\n if (typeof value === \"string\") return shrinkString(value, maxChars);\n if (Array.isArray(value)) return shrinkArray(value, maxChars);\n if (typeof value === \"object\" && value !== null) {\n return shrinkObject(value, maxChars);\n }\n return value;\n}\n\nfunction shrinkString(value: string, maxChars: number): string {\n const suffix = ` ${TRUNCATION_MARKER} ${value.length.toLocaleString()} chars`;\n let keep = Math.max(0, maxChars - suffix.length - 2);\n let out = value.slice(0, keep) + suffix;\n // Escapes inflate the serialized form; back off until it fits.\n while (keep > 0 && size(out) > maxChars) {\n keep = Math.max(0, keep - (size(out) - maxChars));\n out = value.slice(0, keep) + suffix;\n }\n // No room for a prefix and the size note: keep as much of the marker as fits.\n return size(out) <= maxChars\n ? out\n : TRUNCATION_MARKER.slice(0, Math.max(0, maxChars - 2));\n}\n\n/**\n * Share `available` characters across values by water-filling: values are\n * admitted smallest first, each taking the lesser of its full size and an\n * equal share of what is left. Requires `available >= Σ floorSize(values)`;\n * then every value receives at least its floor.\n */\nfunction allocate(values: Json[], available: number): number[] {\n const sizes = values.map(size);\n const order = sizes.map((_, i) => i).sort((a, b) => sizes[a] - sizes[b]);\n const allocation = new Array<number>(values.length);\n let remaining = available;\n let count = values.length;\n for (const i of order) {\n const alloc = Math.min(sizes[i], Math.floor(remaining / count));\n allocation[i] = alloc;\n remaining -= alloc;\n count--;\n }\n return allocation;\n}\n\nfunction shrinkArray(items: Json[], maxChars: number): Json[] {\n const marker = (dropped: number) =>\n `${TRUNCATION_MARKER} ${dropped.toLocaleString()} more items`;\n const floors = items.map((item) => floorSize(item, maxChars));\n const skeleton = (count: number) => 2 + Math.max(0, count - 1);\n\n // Keep everything when every floor fits.\n let keep = items.length;\n if (floors.reduce((n, f) => n + f, 0) + skeleton(keep) > maxChars) {\n // Otherwise keep the longest prefix whose floors fit beside a tail marker\n // (sized for the largest possible count, so the real one always fits).\n const tail = size(marker(items.length)) + 1;\n let used = skeleton(0) + tail;\n keep = 0;\n while (keep < items.length && used + floors[keep] + 1 <= maxChars) {\n used += floors[keep] + 1;\n keep++;\n }\n }\n\n const kept = items.slice(0, keep);\n const dropped = items.length - keep;\n const tail = dropped > 0 ? size(marker(dropped)) + (keep > 0 ? 1 : 0) : 0;\n const allocation = allocate(kept, maxChars - skeleton(keep) - tail);\n const out = kept.map((item, i) => shrink(item, allocation[i]));\n if (dropped > 0 && size([...out, marker(dropped)]) <= maxChars) {\n out.push(marker(dropped));\n }\n return out;\n}\n\nfunction shrinkObject(\n value: { [key: string]: Json },\n maxChars: number\n): { [key: string]: Json } {\n const entries = Object.entries(value);\n // The marker entry must not shadow a real key.\n let markerKey = TRUNCATION_MARKER;\n while (markerKey in value) markerKey += \" \";\n const keyCost = (key: string) => size(key) + 1;\n const floors = entries.map(([k, v]) => keyCost(k) + floorSize(v, maxChars));\n const floorOf = (chars: number) =>\n Math.min(chars, MIN_SLOT, Math.max(2, Math.floor(maxChars / 2)));\n\n // Drop the largest values first, only until the remaining floors fit. Costs\n // are tracked incrementally so a wide object stays linear in its key count;\n // the marker note's cost is derived arithmetically from the omitted names.\n const byValueSize = entries\n .map((_, i) => i)\n .sort((a, b) => size(entries[b][1]) - size(entries[a][1]));\n const dropped = new Set<number>();\n let present = entries.length;\n let floorsSum = floors.reduce((n, f) => n + f, 0);\n let namesLength = 0;\n const noteLength = () =>\n `${dropped.size.toLocaleString()} keys omitted: `.length +\n namesLength +\n 2 * (dropped.size - 1);\n const cost = () => {\n const marker =\n dropped.size > 0 ? keyCost(markerKey) + floorOf(noteLength() + 2) : 0;\n const count = present + (dropped.size > 0 ? 1 : 0);\n return 2 + Math.max(0, count - 1) + floorsSum + marker;\n };\n for (const i of byValueSize) {\n if (cost() <= maxChars) break;\n dropped.add(i);\n present--;\n floorsSum -= floors[i];\n namesLength += size(entries[i][0]) - 2;\n }\n\n const kept = entries.filter((_, i) => !dropped.has(i));\n const omitted = [...dropped].sort((a, b) => a - b).map((i) => entries[i][0]);\n const note = `${omitted.length.toLocaleString()} keys omitted: ${omitted.join(\", \")}`;\n if (cost() > maxChars) {\n // Not even the marker fits at its floor: keep as much of it as there is\n // room for, or nothing.\n const room = maxChars - 2 - keyCost(markerKey);\n return room >= 2 ? { [markerKey]: shrink(note, room) } : {};\n }\n const all: [string, Json][] = [...kept];\n if (omitted.length > 0) all.push([markerKey, note]);\n const fixed =\n 2 + Math.max(0, all.length - 1) + all.reduce((n, [k]) => n + keyCost(k), 0);\n // The note is shrunk like any other value, so it can never overshoot.\n const allocation = allocate(\n all.map(([, v]) => v),\n maxChars - fixed\n );\n const out: { [key: string]: Json } = {};\n all.forEach(([k, v], i) => {\n out[k] = shrink(v, allocation[i]);\n });\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;;;;;;AAM1B,MAAM,WAAW;AAYjB,SAAS,OAAO,SAGd;CACA,MAAM,YAAY,SAAS,aAAa;CAExC,OAAO;EAAE,UADQ,SAAS,YAAY,YAAY;EAC/B;CAAU;AAC/B;;;;;;AAOA,SAAgB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,IAAI,QAAQ,CAAC,GAAG,CAAC;CAE5E,MAAM,aAAa,SACjB,IAAI,KAAK,GAAG,OAAO,CAAC,GACpB,WAAW,KACb;CACA,MAAM,MAA+B,CAAC;CACtC,IAAI,SAAS,CAAC,GAAG,IAAI,MAAM;EACzB,IAAI,KAAK,OAAO,GAAG,WAAW,EAAE;CAClC,CAAC;CACD,OAAO;AACT"}
package/docs/index.md CHANGED
@@ -137,6 +137,8 @@ export class Chat extends AIChatAgent<Env> {
137
137
 
138
138
  That's the whole developer surface: a connector class, `createCodemodeRuntime`, and the runtime handle. The handle is the control plane — `tool()` for the model, `pending()`/`approve()`/`reject()`/`rollback()` for approvals, `executions()` for the audit trail, and `saveSnippet()`/`snippets()`/`deleteSnippet()` for curating what the model gets to reuse.
139
139
 
140
+ `runtime.tool()` declares its input as `{ code: string }`. Its schema implements the Standard Schema protocol, so compatible tool consumers such as TanStack AI can infer that input type.
141
+
140
142
  ## Use it (what the model writes)
141
143
 
142
144
  The sandbox SDK is four methods — discover, learn, do-once, reuse — plus one global per connector:
package/docs/runtime.md CHANGED
@@ -232,7 +232,9 @@ const runtime = createCodemodeRuntime({
232
232
  });
233
233
  ```
234
234
 
235
- `truncateResult(value, options?)` returns the value unchanged when its serialized size is within budget, and a truncated string (with a marker noting the original size) when it isn't. `truncateResponse(text, options?)` is the string-only variant. Both take `{ maxChars?, maxTokens? }` (default ~6000 tokens).
235
+ `truncateResult(value, options?)` returns the value unchanged when its serialized size is within budget. When it isn't, the value is shrunk structurally — largest values first — so the model still receives valid JSON of the original shape: a clipped string ends with `--- TRUNCATED --- <n> chars`, a clipped array ends with a `--- TRUNCATED --- <n> more items` element, and an object that had to lose entries gains a `"--- TRUNCATED ---"` entry naming the omitted keys. `truncateResponse(text, options?)` is the string-only variant. Both take `{ maxChars?, maxTokens? }` (default ~6000 tokens).
236
+
237
+ The tool's `toModelOutput` sends the model everything but `calls`, with `logs` bounded the same way: the durable call log (every connector call's args and result) stays on the persisted tool part for UIs and audit, and is never part of the model's context.
236
238
 
237
239
  `transformResult` shapes only the final returned value — individual connector results inside the run are unaffected, so the model's own code still sees full data to reason over.
238
240
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cloudflare/codemode",
3
- "version": "0.5.1",
3
+ "version": "0.5.3",
4
4
  "description": "Code Mode: use LLMs to generate executable code that performs tool calls",
5
5
  "repository": {
6
6
  "directory": "packages/codemode",
@@ -15,12 +15,11 @@
15
15
  "acorn": "^8.17.0"
16
16
  },
17
17
  "devDependencies": {
18
- "@modelcontextprotocol/sdk": "1.29.0",
18
+ "@modelcontextprotocol/sdk": "1.30.0",
19
19
  "@playwright/test": "^1.61.1",
20
20
  "@tanstack/ai": "0.38.0",
21
21
  "ai": "^7.0.0",
22
- "vitest": "4.1.9",
23
- "zod": "^4.4.3"
22
+ "zod": "^4.5.4"
24
23
  },
25
24
  "peerDependencies": {
26
25
  "@modelcontextprotocol/sdk": "^1.25.0",