@cloudflare/codemode 0.3.4 → 0.3.6
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/README.md +21 -2
- package/dist/ai.d.ts +4 -4
- package/dist/ai.js +9 -17
- package/dist/ai.js.map +1 -1
- package/dist/browser.d.ts +142 -0
- package/dist/browser.js +509 -0
- package/dist/browser.js.map +1 -0
- package/dist/{executor-wZjYdqEX.d.ts → executor-BWtTiHBV.d.ts} +37 -36
- package/dist/index.d.ts +13 -37
- package/dist/index.js +120 -13
- package/dist/index.js.map +1 -1
- package/dist/json-schema-types-1OL3uao0.d.ts +38 -0
- package/dist/{json-schema-types-DoQ0VISs.js → json-schema-types-CVt4X9cw.js} +43 -2
- package/dist/json-schema-types-CVt4X9cw.js.map +1 -0
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +72 -39
- package/dist/mcp.js.map +1 -1
- package/dist/{resolve-DULSpsq2.d.ts → resolve-9VUW-grI.d.ts} +4 -4
- package/dist/resolve-BU1FGVYs.js +44 -0
- package/dist/resolve-BU1FGVYs.js.map +1 -0
- package/dist/run-code-5x8S5YWt.js +17 -0
- package/dist/run-code-5x8S5YWt.js.map +1 -0
- package/dist/{shared-Hnh_Idta.d.ts → shared-CcZcDoiO.d.ts} +5 -6
- package/dist/{shared-ra3HW2ti.js → shared-xjl2irqK.js} +1 -1
- package/dist/{shared-ra3HW2ti.js.map → shared-xjl2irqK.js.map} +1 -1
- package/dist/tanstack-ai.d.ts +3 -3
- package/dist/tanstack-ai.js +10 -18
- package/dist/tanstack-ai.js.map +1 -1
- package/package.json +14 -8
- package/dist/json-schema-types-DoQ0VISs.js.map +0 -1
- package/dist/resolve-DIQRkRqQ.js +0 -85
- package/dist/resolve-DIQRkRqQ.js.map +0 -1
package/dist/mcp.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as sanitizeToolName, t as generateTypesFromJsonSchema } from "./json-schema-types-
|
|
1
|
+
import { a as sanitizeToolName, s as normalizeCode, t as generateTypesFromJsonSchema } from "./json-schema-types-CVt4X9cw.js";
|
|
2
2
|
import { z } from "zod";
|
|
3
3
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
4
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
@@ -7,10 +7,17 @@ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
|
7
7
|
const CHARS_PER_TOKEN = 4;
|
|
8
8
|
const MAX_TOKENS = 6e3;
|
|
9
9
|
const MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;
|
|
10
|
+
const TRUNCATION_MARKER = "--- TRUNCATED ---";
|
|
11
|
+
const TRUNCATION_FOOTER_PREFIX = `\n\n${TRUNCATION_MARKER}\nResponse was ~`;
|
|
12
|
+
const MAX_SANDBOX_TRUNCATED_CHARS = MAX_CHARS + 512;
|
|
10
13
|
function truncateResponse(content) {
|
|
11
14
|
const text = typeof content === "string" ? content : JSON.stringify(content, null, 2) ?? "undefined";
|
|
12
15
|
if (text.length <= MAX_CHARS) return text;
|
|
13
|
-
return `${text.slice(0, MAX_CHARS)}\n\n
|
|
16
|
+
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.`;
|
|
17
|
+
}
|
|
18
|
+
function sandboxResponseText(content) {
|
|
19
|
+
if (typeof content === "string" && content.length <= MAX_SANDBOX_TRUNCATED_CHARS && content.slice(MAX_CHARS).startsWith(TRUNCATION_FOOTER_PREFIX)) return content;
|
|
20
|
+
return truncateResponse(content);
|
|
14
21
|
}
|
|
15
22
|
function formatError(error) {
|
|
16
23
|
return error instanceof Error ? error.message : String(error);
|
|
@@ -128,31 +135,6 @@ async function codeMcpServer(options) {
|
|
|
128
135
|
});
|
|
129
136
|
return codemodeServer;
|
|
130
137
|
}
|
|
131
|
-
/**
|
|
132
|
-
* Resolve internal $ref pointers in a JSON object against the root document.
|
|
133
|
-
* Only handles `#/` internal refs. External file refs are left as-is.
|
|
134
|
-
*/
|
|
135
|
-
function resolveRefs(obj, root, seen = /* @__PURE__ */ new Set()) {
|
|
136
|
-
if (obj === null || obj === void 0) return obj;
|
|
137
|
-
if (typeof obj !== "object") return obj;
|
|
138
|
-
if (Array.isArray(obj)) return obj.map((item) => resolveRefs(item, root, seen));
|
|
139
|
-
const record = obj;
|
|
140
|
-
if ("$ref" in record && typeof record.$ref === "string") {
|
|
141
|
-
const ref = record.$ref;
|
|
142
|
-
if (seen.has(ref)) return { $circular: ref };
|
|
143
|
-
if (!ref.startsWith("#/")) return record;
|
|
144
|
-
seen.add(ref);
|
|
145
|
-
const parts = ref.slice(2).split("/").map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
146
|
-
let resolved = root;
|
|
147
|
-
for (const part of parts) resolved = resolved?.[part];
|
|
148
|
-
const result = resolveRefs(resolved, root, seen);
|
|
149
|
-
seen.delete(ref);
|
|
150
|
-
return result;
|
|
151
|
-
}
|
|
152
|
-
const result = {};
|
|
153
|
-
for (const [key, value] of Object.entries(record)) result[key] = resolveRefs(value, root, seen);
|
|
154
|
-
return result;
|
|
155
|
-
}
|
|
156
138
|
const SPEC_TYPES = `
|
|
157
139
|
// OpenAPI 3.x spec with $refs resolved inline.
|
|
158
140
|
// The spec object follows the standard OpenAPI 3.x structure.
|
|
@@ -204,7 +186,8 @@ interface OpenApiSpec {
|
|
|
204
186
|
components?: Record<string, unknown>;
|
|
205
187
|
tags?: Array<{ name: string; description?: string }>;
|
|
206
188
|
}
|
|
207
|
-
|
|
189
|
+
`;
|
|
190
|
+
const SEARCH_TYPES = `${SPEC_TYPES}
|
|
208
191
|
declare const codemode: {
|
|
209
192
|
spec(): Promise<OpenApiSpec>;
|
|
210
193
|
};
|
|
@@ -219,10 +202,63 @@ interface RequestOptions {
|
|
|
219
202
|
rawBody?: boolean;
|
|
220
203
|
}
|
|
221
204
|
|
|
205
|
+
${SPEC_TYPES}
|
|
206
|
+
|
|
222
207
|
declare const codemode: {
|
|
208
|
+
spec(): Promise<OpenApiSpec>;
|
|
223
209
|
request(options: RequestOptions): Promise<unknown>;
|
|
224
210
|
};
|
|
225
211
|
`;
|
|
212
|
+
function createOpenApiSandboxCode(code, spec, includeRequest) {
|
|
213
|
+
const normalized = normalizeCode(code);
|
|
214
|
+
const specJson = JSON.stringify(spec).replace(/</g, "\\u003c");
|
|
215
|
+
const requestFn = includeRequest ? `request: async (options) => await __openapiHost.request(options)` : "";
|
|
216
|
+
return `async () => {
|
|
217
|
+
const __rawSpec = ${specJson};
|
|
218
|
+
const __refCache = new Map();
|
|
219
|
+
const __cloneResolvedRef = (value) => structuredClone(value);
|
|
220
|
+
const __resolveRefs = (obj, root, seen = new Set()) => {
|
|
221
|
+
if (obj === null || obj === undefined) return obj;
|
|
222
|
+
if (typeof obj !== "object") return obj;
|
|
223
|
+
if (Array.isArray(obj)) return obj.map((item) => __resolveRefs(item, root, seen));
|
|
224
|
+
|
|
225
|
+
if (Object.prototype.hasOwnProperty.call(obj, "$ref") && typeof obj.$ref === "string") {
|
|
226
|
+
const ref = obj.$ref;
|
|
227
|
+
if (seen.has(ref)) return { $circular: ref };
|
|
228
|
+
if (!ref.startsWith("#/")) return obj;
|
|
229
|
+
if (__refCache.has(ref)) return __cloneResolvedRef(__refCache.get(ref));
|
|
230
|
+
seen.add(ref);
|
|
231
|
+
|
|
232
|
+
const parts = ref
|
|
233
|
+
.slice(2)
|
|
234
|
+
.split("/")
|
|
235
|
+
.map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
236
|
+
let resolved = root;
|
|
237
|
+
for (const part of parts) resolved = resolved?.[part];
|
|
238
|
+
const result = __resolveRefs(resolved, root, seen);
|
|
239
|
+
seen.delete(ref);
|
|
240
|
+
__refCache.set(ref, result);
|
|
241
|
+
return __cloneResolvedRef(result);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const result = {};
|
|
245
|
+
for (const [key, value] of Object.entries(obj)) result[key] = __resolveRefs(value, root, seen);
|
|
246
|
+
return result;
|
|
247
|
+
};
|
|
248
|
+
let __resolvedSpec;
|
|
249
|
+
const __truncateResponse = (content) => {
|
|
250
|
+
const text = typeof content === "string" ? content : (JSON.stringify(content, null, 2) ?? "undefined");
|
|
251
|
+
if (text.length <= ${MAX_CHARS}) return text;
|
|
252
|
+
const truncated = text.slice(0, ${MAX_CHARS});
|
|
253
|
+
const estimatedTokens = Math.ceil(text.length / ${CHARS_PER_TOKEN});
|
|
254
|
+
return truncated + "\\n\\n${TRUNCATION_MARKER}\\nResponse was ~" + estimatedTokens.toLocaleString() + " tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.";
|
|
255
|
+
};
|
|
256
|
+
const codemode = {
|
|
257
|
+
spec: async () => (__resolvedSpec ??= __resolveRefs(__rawSpec, __rawSpec))${requestFn ? `,\n ${requestFn}` : ""}
|
|
258
|
+
};
|
|
259
|
+
return __truncateResponse(await (${normalized})());
|
|
260
|
+
}`;
|
|
261
|
+
}
|
|
226
262
|
/**
|
|
227
263
|
* Create an MCP server with search + execute tools from an OpenAPI spec.
|
|
228
264
|
*
|
|
@@ -232,16 +268,16 @@ declare const codemode: {
|
|
|
232
268
|
*/
|
|
233
269
|
function openApiMcpServer(options) {
|
|
234
270
|
const { executor, request: requestFn, name = "openapi", version = "1.0.0", description } = options;
|
|
235
|
-
const
|
|
271
|
+
const spec = options.spec;
|
|
236
272
|
const server = new McpServer({
|
|
237
273
|
name,
|
|
238
274
|
version
|
|
239
275
|
});
|
|
240
276
|
server.registerTool("search", {
|
|
241
|
-
description: `Search the OpenAPI spec.
|
|
277
|
+
description: `Search the OpenAPI spec. codemode.spec() returns $refs resolved inline.
|
|
242
278
|
|
|
243
279
|
Types:
|
|
244
|
-
${
|
|
280
|
+
${SEARCH_TYPES}
|
|
245
281
|
|
|
246
282
|
Your code must be an async arrow function that returns the result.
|
|
247
283
|
|
|
@@ -269,10 +305,7 @@ async () => {
|
|
|
269
305
|
inputSchema: { code: z.string().describe("JavaScript async arrow function to search the spec") }
|
|
270
306
|
}, async ({ code }) => {
|
|
271
307
|
try {
|
|
272
|
-
const result = await executor.execute(code, [
|
|
273
|
-
name: "codemode",
|
|
274
|
-
fns: { spec: async () => resolved }
|
|
275
|
-
}]);
|
|
308
|
+
const result = await executor.execute(createOpenApiSandboxCode(code, spec, false), []);
|
|
276
309
|
if (result.error) return {
|
|
277
310
|
content: [{
|
|
278
311
|
type: "text",
|
|
@@ -282,7 +315,7 @@ async () => {
|
|
|
282
315
|
};
|
|
283
316
|
return { content: [{
|
|
284
317
|
type: "text",
|
|
285
|
-
text:
|
|
318
|
+
text: sandboxResponseText(result.result)
|
|
286
319
|
}] };
|
|
287
320
|
} catch (error) {
|
|
288
321
|
return {
|
|
@@ -310,8 +343,8 @@ async () => {
|
|
|
310
343
|
inputSchema: { code: z.string().describe("JavaScript async arrow function to execute") }
|
|
311
344
|
}, async ({ code }) => {
|
|
312
345
|
try {
|
|
313
|
-
const result = await executor.execute(code, [{
|
|
314
|
-
name: "
|
|
346
|
+
const result = await executor.execute(createOpenApiSandboxCode(code, spec, true), [{
|
|
347
|
+
name: "__openapiHost",
|
|
315
348
|
fns: { request: (args) => requestFn(args) }
|
|
316
349
|
}]);
|
|
317
350
|
if (result.error) return {
|
|
@@ -323,7 +356,7 @@ async () => {
|
|
|
323
356
|
};
|
|
324
357
|
return { content: [{
|
|
325
358
|
type: "text",
|
|
326
|
-
text:
|
|
359
|
+
text: sandboxResponseText(result.result)
|
|
327
360
|
}] };
|
|
328
361
|
} catch (error) {
|
|
329
362
|
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 { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { z } from \"zod\";\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\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;\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--- TRUNCATED ---\\nResponse was ~${estimatedTokens.toLocaleString()} tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.`;\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\nexport interface OpenApiMcpServerOptions {\n spec: Record<string, unknown>;\n executor: Executor;\n request: (options: RequestOptions) => Promise<unknown>;\n name?: string;\n version?: string;\n description?: string;\n}\n\n/**\n * Resolve internal $ref pointers in a JSON object against the root document.\n * Only handles `#/` internal refs. External file refs are left as-is.\n */\nfunction resolveRefs(\n obj: unknown,\n root: Record<string, unknown>,\n seen = new Set<string>()\n): unknown {\n if (obj === null || obj === undefined) return obj;\n if (typeof obj !== \"object\") return obj;\n if (Array.isArray(obj))\n return obj.map((item) => resolveRefs(item, root, seen));\n\n const record = obj as Record<string, unknown>;\n\n if (\"$ref\" in record && typeof record.$ref === \"string\") {\n const ref = record.$ref;\n if (seen.has(ref)) return { $circular: ref };\n if (!ref.startsWith(\"#/\")) return record;\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: unknown = root;\n for (const part of parts) {\n resolved = (resolved as Record<string, unknown>)?.[part];\n }\n const result = resolveRefs(resolved, root, seen);\n seen.delete(ref);\n return result;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = resolveRefs(value, root, seen);\n }\n return result;\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\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\ndeclare const codemode: {\n request(options: RequestOptions): Promise<unknown>;\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 resolved = resolveRefs(options.spec, options.spec);\n\n const server = new McpServer({ name, version });\n\n // --- search tool ---\n server.registerTool(\n \"search\",\n {\n description: `Search the OpenAPI spec. All $refs are pre-resolved inline.\n\nTypes:\n${SPEC_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(code, [\n { name: \"codemode\", fns: { spec: async () => resolved } }\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 // --- 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 }) => {\n try {\n const result = await executor.execute(code, [\n {\n name: \"codemode\",\n fns: {\n request: (args: unknown) => requestFn(args as RequestOptions)\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: 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 server;\n}\n"],"mappings":";;;;;;AAeA,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,YAAY,aAAa;AAE/B,SAAS,iBAAiB,SAA0B;CAClD,MAAM,OACJ,OAAO,YAAY,WACf,UACC,KAAK,UAAU,SAAS,MAAM,EAAE,IAAI;AAE3C,KAAI,KAAK,UAAU,UACjB,QAAO;AAMT,QAAO,GAHW,KAAK,MAAM,GAAG,UAAU,CAGtB,uCAFI,KAAK,KAAK,KAAK,SAAS,gBAAgB,CAEW,gBAAgB,CAAC,kBAAkB,WAAW,gBAAgB,CAAC;;AAG5I,SAAS,YAAY,OAAwB;AAC3C,QAAO,iBA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V;;GAGN;AAED,QAAO"}
|
|
1
|
+
{"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.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\nexport interface OpenApiMcpServerOptions {\n spec: Record<string, unknown>;\n executor: Executor;\n request: (options: RequestOptions) => 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({ name, version });\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 }) => {\n try {\n const result = await executor.execute(\n createOpenApiSandboxCode(code, spec, true),\n [\n {\n name: \"__openapiHost\",\n fns: {\n request: (args: unknown) => requestFn(args as RequestOptions)\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":";;;;;;AAgBA,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,YAAY,aAAa;AAC/B,MAAM,oBAAoB;AAC1B,MAAM,2BAA2B,OAAO,kBAAkB;AAC1D,MAAM,8BAA8B,YAAY;AAEhD,SAAS,iBAAiB,SAA0B;CAClD,MAAM,OACJ,OAAO,YAAY,WACf,UACC,KAAK,UAAU,SAAS,MAAM,EAAE,IAAI;CAE3C,IAAI,KAAK,UAAU,WACjB,OAAO;CAMT,OAAO,GAHW,KAAK,MAAM,GAAG,UAGb,CAAC,MAAM,kBAAkB,kBAFpB,KAAK,KAAK,KAAK,S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AAM,MAAM,EAC3C,EAAE,CACH;GACD,IAAI,OAAO,OACT,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;KAAS,CAC1D;IACD,SAAS;IACV;GAEH,OAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAiB,MAAM,oBAAoB,OAAO,OAAO;IAAE,CACpE,EACF;WACM,OAAO;GACd,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,YAAY,MAAM;KAAI,CAChE;IACD,SAAS;IACV;;GAGN;CAGD,MAAM,qBAAqB;;;EAG3B,cAAc;;;;;;;GAOb,cAAc,OAAO,gBAAgB;CAEtC,OAAO,aACL,WACA;EACE,aAAa;EACb,aAAa,EACX,MAAM,EAAE,QAAQ,CAAC,SAAS,6CAA6C,EACxE;EACF,EACD,OAAO,EAAE,WAAW;EAClB,IAAI;GACF,MAAM,SAAS,MAAM,SAAS,QAC5B,yBAAyB,MAAM,MAAM,KAAK,EAC1C,CACE;IACE,MAAM;IACN,KAAK,EACH,UAAU,SAAkB,UAAU,KAAuB,EAC9D;IACF,CACF,CACF;GACD,IAAI,OAAO,OACT,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;KAAS,CAC1D;IACD,SAAS;IACV;GAEH,OAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAiB,MAAM,oBAAoB,OAAO,OAAO;IAAE,CACpE,EACF;WACM,OAAO;GACd,OAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,YAAY,MAAM;KAAI,CAChE;IACD,SAAS;IACV;;GAGN;CAED,OAAO"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
} from "./executor-
|
|
2
|
+
c as ResolvedProvider,
|
|
3
|
+
i as ToolProvider
|
|
4
|
+
} from "./executor-BWtTiHBV.js";
|
|
5
5
|
|
|
6
6
|
//#region src/resolve.d.ts
|
|
7
7
|
/**
|
|
@@ -14,4 +14,4 @@ import {
|
|
|
14
14
|
declare function resolveProvider(provider: ToolProvider): ResolvedProvider;
|
|
15
15
|
//#endregion
|
|
16
16
|
export { resolveProvider as t };
|
|
17
|
-
//# sourceMappingURL=resolve-
|
|
17
|
+
//# sourceMappingURL=resolve-9VUW-grI.d.ts.map
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
//#region src/resolve.ts
|
|
2
|
+
function hasNeedsApproval(t) {
|
|
3
|
+
return t.needsApproval === true || typeof t.needsApproval === "function";
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Filter out tools with needsApproval and return a clean copy.
|
|
7
|
+
*/
|
|
8
|
+
function filterTools(tools) {
|
|
9
|
+
const filtered = {};
|
|
10
|
+
for (const [name, t] of Object.entries(tools)) if (!hasNeedsApproval(t)) filtered[name] = t;
|
|
11
|
+
return filtered;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Extract execute functions from tools, keyed by name.
|
|
15
|
+
* This is the base version — no schema validation.
|
|
16
|
+
* The AI SDK entry point overrides this with `asSchema`-based validation.
|
|
17
|
+
*/
|
|
18
|
+
function extractFns(tools) {
|
|
19
|
+
const fns = {};
|
|
20
|
+
for (const [name, t] of Object.entries(tools)) {
|
|
21
|
+
const execute = "execute" in t ? t.execute : void 0;
|
|
22
|
+
if (execute) fns[name] = execute;
|
|
23
|
+
}
|
|
24
|
+
return fns;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Resolve a ToolProvider into a ResolvedProvider ready for execution.
|
|
28
|
+
* Filters out tools with `needsApproval`.
|
|
29
|
+
*
|
|
30
|
+
* This version does NOT perform schema validation on inputs.
|
|
31
|
+
* Import from `@cloudflare/codemode/ai` for the schema-validating version.
|
|
32
|
+
*/
|
|
33
|
+
function resolveProvider(provider) {
|
|
34
|
+
const resolved = {
|
|
35
|
+
name: provider.name ?? "codemode",
|
|
36
|
+
fns: extractFns(filterTools(provider.tools))
|
|
37
|
+
};
|
|
38
|
+
if (provider.positionalArgs) resolved.positionalArgs = true;
|
|
39
|
+
return resolved;
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { filterTools as n, resolveProvider as r, extractFns as t };
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=resolve-BU1FGVYs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-BU1FGVYs.js","names":[],"sources":["../src/resolve.ts"],"sourcesContent":["/**\n * Framework-agnostic tool resolution.\n *\n * Extracts execute functions from tool records and resolves ToolProviders\n * into ResolvedProviders — no dependency on the AI SDK or Zod.\n *\n * The AI SDK entry point (`./ai`) layers on schema validation via `asSchema`.\n */\n\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\n\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return t.needsApproval === true || typeof t.needsApproval === \"function\";\n}\n\n/**\n * Filter out tools with needsApproval and return a clean copy.\n */\nexport function filterTools(tools: ToolProviderTools): ToolProviderTools {\n const filtered: Record<string, unknown> = {};\n for (const [name, t] of Object.entries(tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n filtered[name] = t;\n }\n }\n return filtered as ToolProviderTools;\n}\n\n/**\n * Extract execute functions from tools, keyed by name.\n * This is the base version — no schema validation.\n * The AI SDK entry point overrides this with `asSchema`-based validation.\n */\nexport function extractFns(\n tools: ToolProviderTools\n): Record<string, (...args: unknown[]) => Promise<unknown>> {\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n fns[name] = execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval`.\n *\n * This version does NOT perform schema validation on inputs.\n * Import from `@cloudflare/codemode/ai` for the schema-validating version.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n return resolved;\n}\n"],"mappings":";AAeA,SAAS,iBAAiB,GAAqC;CAC7D,OAAO,EAAE,kBAAkB,QAAQ,OAAO,EAAE,kBAAkB;;;;;AAMhE,SAAgB,YAAY,OAA6C;CACvE,MAAM,WAAoC,EAAE;CAC5C,KAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,MAAM,EAC3C,IAAI,CAAC,iBAAiB,EAA6B,EACjD,SAAS,QAAQ;CAGrB,OAAO;;;;;;;AAQT,SAAgB,WACd,OAC0D;CAC1D,MAAM,MAAgE,EAAE;CAExE,KAAK,MAAM,CAAC,MAAM,MAAM,OAAO,QAAQ,MAAM,EAAE;EAC7C,MAAM,UACJ,aAAa,IACR,EAAE,UACH,KAAA;EACN,IAAI,SACF,IAAI,QAAQ;;CAIhB,OAAO;;;;;;;;;AAUT,SAAgB,gBAAgB,UAA0C;CAGxE,MAAM,WAA6B;EAAE,MAFxB,SAAS,QAAQ;EAEa,KAAK,WAD/B,YAAY,SAAS,MAC6B,CAAC;EAAE;CACtE,IAAI,SAAS,gBAAgB,SAAS,iBAAiB;CACvD,OAAO"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { s as normalizeCode } from "./json-schema-types-CVt4X9cw.js";
|
|
2
|
+
//#region src/run-code.ts
|
|
3
|
+
async function runCode({ code, executor, providers }) {
|
|
4
|
+
const executeResult = await executor.execute(normalizeCode(code), providers);
|
|
5
|
+
if (executeResult.error) {
|
|
6
|
+
const logCtx = executeResult.logs?.length ? `\n\nConsole output:\n${executeResult.logs.join("\n")}` : "";
|
|
7
|
+
throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
|
|
8
|
+
}
|
|
9
|
+
return executeResult.logs?.length ? {
|
|
10
|
+
result: executeResult.result,
|
|
11
|
+
logs: executeResult.logs
|
|
12
|
+
} : { result: executeResult.result };
|
|
13
|
+
}
|
|
14
|
+
//#endregion
|
|
15
|
+
export { runCode as t };
|
|
16
|
+
|
|
17
|
+
//# sourceMappingURL=run-code-5x8S5YWt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run-code-5x8S5YWt.js","names":[],"sources":["../src/run-code.ts"],"sourcesContent":["import type { CodeOutput } from \"./shared\";\nimport type { Executor, ResolvedProvider } from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\n\nexport async function runCode({\n code,\n executor,\n providers\n}: {\n code: string;\n executor: Executor;\n providers: ResolvedProvider[];\n}): Promise<CodeOutput> {\n const executeResult = await executor.execute(normalizeCode(code), providers);\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);\n }\n\n return executeResult.logs?.length\n ? { result: executeResult.result, logs: executeResult.logs }\n : { result: executeResult.result };\n}\n"],"mappings":";;AAIA,eAAsB,QAAQ,EAC5B,MACA,UACA,aAKsB;CACtB,MAAM,gBAAgB,MAAM,SAAS,QAAQ,cAAc,KAAK,EAAE,UAAU;CAE5E,IAAI,cAAc,OAAO;EACvB,MAAM,SAAS,cAAc,MAAM,SAC/B,wBAAwB,cAAc,KAAK,KAAK,KAAK,KACrD;EACJ,MAAM,IAAI,MAAM,0BAA0B,cAAc,QAAQ,SAAS;;CAG3E,OAAO,cAAc,MAAM,SACvB;EAAE,QAAQ,cAAc;EAAQ,MAAM,cAAc;EAAM,GAC1D,EAAE,QAAQ,cAAc,QAAQ"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
i as
|
|
4
|
-
s as
|
|
5
|
-
} from "./executor-
|
|
2
|
+
a as ToolProviderTools,
|
|
3
|
+
i as ToolProvider,
|
|
4
|
+
s as Executor
|
|
5
|
+
} from "./executor-BWtTiHBV.js";
|
|
6
6
|
|
|
7
7
|
//#region src/shared.d.ts
|
|
8
8
|
declare const DEFAULT_DESCRIPTION =
|
|
@@ -19,7 +19,6 @@ type CodeInput = {
|
|
|
19
19
|
code: string;
|
|
20
20
|
};
|
|
21
21
|
type CodeOutput = {
|
|
22
|
-
code: string;
|
|
23
22
|
result: unknown;
|
|
24
23
|
logs?: string[];
|
|
25
24
|
};
|
|
@@ -38,4 +37,4 @@ export {
|
|
|
38
37
|
CreateCodeToolOptions as r,
|
|
39
38
|
CodeInput as t
|
|
40
39
|
};
|
|
41
|
-
//# sourceMappingURL=shared-
|
|
40
|
+
//# sourceMappingURL=shared-CcZcDoiO.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared-
|
|
1
|
+
{"version":3,"file":"shared-xjl2irqK.js","names":[],"sources":["../src/shared.ts"],"sourcesContent":["/**\n * Shared constants and types used by both the AI SDK (`./ai`) and\n * TanStack AI (`./tanstack-ai`) entry points.\n *\n * No dependency on `ai`, `@tanstack/ai`, or `zod`.\n */\n\nimport type { Executor, ToolProvider, ToolProviderTools } from \"./executor\";\n\nexport const DEFAULT_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\nExample: async () => { const r = await codemode.searchWeb({ query: \"test\" }); return r; }`;\n\nexport interface CreateCodeToolOptions {\n tools: ToolProviderTools | ToolProvider[];\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nexport type CodeInput = { code: string };\nexport type CodeOutput = { result: unknown; logs?: string[] };\n\n/**\n * Check if the tools option is an array of ToolProviders.\n * A plain ToolSet/ToolDescriptors is a Record (not an array).\n */\nfunction isToolProviderArray(\n tools: ToolProviderTools | ToolProvider[]\n): tools is ToolProvider[] {\n return Array.isArray(tools);\n}\n\n/**\n * Normalize the tools option into a list of ToolProviders.\n * Raw ToolSet/ToolDescriptors are wrapped as a single default provider.\n */\nexport function normalizeProviders(\n tools: ToolProviderTools | ToolProvider[]\n): ToolProvider[] {\n if (isToolProviderArray(tools)) {\n return tools;\n }\n return [{ tools }];\n}\n"],"mappings":";AASA,MAAa,sBAAsB;;;;;;;;;;;;;;AA2BnC,SAAS,oBACP,OACyB;CACzB,OAAO,MAAM,QAAQ,MAAM;;;;;;AAO7B,SAAgB,mBACd,OACgB;CAChB,IAAI,oBAAoB,MAAM,EAC5B,OAAO;CAET,OAAO,CAAC,EAAE,OAAO,CAAC"}
|
package/dist/tanstack-ai.d.ts
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as ToolProvider } from "./executor-BWtTiHBV.js";
|
|
2
2
|
import {
|
|
3
3
|
a as normalizeProviders,
|
|
4
4
|
i as DEFAULT_DESCRIPTION,
|
|
5
5
|
n as CodeOutput,
|
|
6
6
|
r as CreateCodeToolOptions,
|
|
7
7
|
t as CodeInput
|
|
8
|
-
} from "./shared-
|
|
9
|
-
import { t as resolveProvider } from "./resolve-
|
|
8
|
+
} from "./shared-CcZcDoiO.js";
|
|
9
|
+
import { t as resolveProvider } from "./resolve-9VUW-grI.js";
|
|
10
10
|
import { ServerTool, Tool } from "@tanstack/ai";
|
|
11
11
|
|
|
12
12
|
//#region src/tanstack-ai.d.ts
|
package/dist/tanstack-ai.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { a as sanitizeToolName, i as escapeJsDoc, n as jsonSchemaToType, o as toPascalCase } from "./json-schema-types-CVt4X9cw.js";
|
|
2
|
+
import { n as filterTools, r as resolveProvider, t as extractFns } from "./resolve-BU1FGVYs.js";
|
|
3
|
+
import { t as runCode } from "./run-code-5x8S5YWt.js";
|
|
4
|
+
import { n as normalizeProviders, t as DEFAULT_DESCRIPTION } from "./shared-xjl2irqK.js";
|
|
4
5
|
import { z } from "zod";
|
|
5
6
|
import { convertSchemaToJsonSchema, toolDefinition } from "@tanstack/ai";
|
|
6
7
|
//#region src/tanstack-ai.ts
|
|
@@ -106,7 +107,7 @@ ${availableTools}
|
|
|
106
107
|
* ```
|
|
107
108
|
*/
|
|
108
109
|
function tanstackTools(tools, name) {
|
|
109
|
-
const filtered = tools.filter((t) =>
|
|
110
|
+
const filtered = tools.filter((t) => t.needsApproval !== true && typeof t.needsApproval !== "function");
|
|
110
111
|
const toolRecord = {};
|
|
111
112
|
for (const tool of filtered) if (tool.execute) toolRecord[tool.name] = {
|
|
112
113
|
description: tool.description,
|
|
@@ -173,20 +174,11 @@ function createCodeTool(options) {
|
|
|
173
174
|
name: "codemode_execute",
|
|
174
175
|
description: (options.description ?? DEFAULT_DESCRIPTION).replace("{{types}}", typeBlock),
|
|
175
176
|
inputSchema: codeSchema
|
|
176
|
-
}).server(async ({ code }) => {
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);
|
|
182
|
-
}
|
|
183
|
-
const output = {
|
|
184
|
-
code,
|
|
185
|
-
result: executeResult.result
|
|
186
|
-
};
|
|
187
|
-
if (executeResult.logs) output.logs = executeResult.logs;
|
|
188
|
-
return output;
|
|
189
|
-
});
|
|
177
|
+
}).server(async ({ code }) => runCode({
|
|
178
|
+
code,
|
|
179
|
+
executor,
|
|
180
|
+
providers: resolvedProviders
|
|
181
|
+
}));
|
|
190
182
|
}
|
|
191
183
|
/**
|
|
192
184
|
* Generate types from a ToolProviderTools record.
|
package/dist/tanstack-ai.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tanstack-ai.js","names":[],"sources":["../src/tanstack-ai.ts"],"sourcesContent":["/**\n * TanStack AI integration for codemode.\n *\n * Provides the same capabilities as `@cloudflare/codemode/ai` but returns\n * TanStack AI-compatible tools for use with `chat()` from `@tanstack/ai`.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n * import { chat } from \"@tanstack/ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myServerTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n */\n\nimport { toolDefinition, convertSchemaToJsonSchema } from \"@tanstack/ai\";\nimport type {\n Tool as TanStackTool,\n ServerTool,\n JSONSchema as TanStackJSONSchema\n} from \"@tanstack/ai\";\nimport { z } from \"zod\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider,\n SimpleToolRecord\n} from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\nimport { filterTools, extractFns } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n type CodeOutput,\n normalizeProviders\n} from \"./shared\";\nimport { jsonSchemaToType } from \"./json-schema-types\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\n\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\nexport { resolveProvider } from \"./resolve\";\n\nconst codeSchema = z.object({\n code: z\n .string()\n .meta({ description: \"JavaScript async arrow function to execute\" })\n});\n\n/**\n * Convert a TanStack AI schema (StandardJSONSchema or plain JSONSchema) to\n * a JSON Schema 7 object usable by the core type generator.\n */\nfunction toJsonSchema7(schema: unknown): JSONSchema7 | null {\n const converted = convertSchemaToJsonSchema(schema as TanStackJSONSchema);\n if (!converted) return null;\n return converted as unknown as JSONSchema7;\n}\n\n/**\n * Generate TypeScript type definitions from an array of TanStack AI tools.\n *\n * Uses the tools' schemas (Zod, ArkType, JSON Schema, etc.) to produce type\n * declarations that the LLM sees in the code-tool description.\n */\nexport function generateTypes(\n tools: TanStackTool[],\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const tool of tools) {\n const safeName = sanitizeToolName(tool.name);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputJsonSchema = tool.inputSchema\n ? toJsonSchema7(tool.inputSchema)\n : null;\n const outputJsonSchema = tool.outputSchema\n ? toJsonSchema7(tool.outputSchema)\n : null;\n\n const inputType = inputJsonSchema\n ? jsonSchemaToType(inputJsonSchema, `${typeName}Input`)\n : `type ${typeName}Input = unknown`;\n\n const outputType = outputJsonSchema\n ? jsonSchemaToType(outputJsonSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n if (!inputJsonSchema?.properties) return [];\n return Object.entries(inputJsonSchema.properties)\n .filter(\n ([, propSchema]) =>\n propSchema &&\n typeof propSchema === \"object\" &&\n (propSchema as JSONSchema7).description\n )\n .map(\n ([fieldName, propSchema]) =>\n `@param input.${fieldName} - ${(propSchema as JSONSchema7).description}`\n );\n } catch {\n return [];\n }\n })();\n\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(tool.name));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(tool.name)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n\n/**\n * Wrap TanStack AI tools into a ToolProvider for use with `createCodeTool`.\n *\n * Converts the array-based TanStack tool format into the record-based\n * ToolProvider that the codemode executor expects.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [\n * tanstackTools(myServerTools),\n * tanstackTools(otherTools, \"other\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function tanstackTools(\n tools: TanStackTool[],\n name?: string\n): ToolProvider {\n const filtered = tools.filter(\n (t) => !(\"needsApproval\" in t && t.needsApproval != null)\n );\n\n const toolRecord: SimpleToolRecord = {};\n for (const tool of filtered) {\n if (tool.execute) {\n toolRecord[tool.name] = {\n description: tool.description,\n execute: async (args: unknown) => tool.execute!(args)\n };\n }\n }\n\n const ns = name ?? \"codemode\";\n const types = generateTypes(filtered, ns);\n\n return { name: ns === \"codemode\" ? undefined : ns, tools: toolRecord, types };\n}\n\n/**\n * Create a codemode tool that allows LLMs to write and execute code\n * with access to your tools in a sandboxed environment.\n *\n * Returns a TanStack AI `ServerTool` compatible with `chat()` from `@tanstack/ai`.\n *\n * @example Basic usage\n * ```ts\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n *\n * @example Multiple namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * tanstackTools(githubTools, \"github\"),\n * tanstackTools(dbTools, \"db\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function createCodeTool(options: CreateCodeToolOptions): ServerTool {\n const providers = normalizeProviders(options.tools);\n\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const providerName = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n\n const types =\n provider.types ?? generateTypesFromRecord(filtered, providerName);\n typeBlocks.push(types);\n\n const resolved: ResolvedProvider = {\n name: providerName,\n fns: extractFns(filtered)\n };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n const def = toolDefinition({\n name: \"codemode_execute\" as const,\n description,\n inputSchema: codeSchema\n });\n\n return def.server(async ({ code }) => {\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(\n normalizedCode,\n resolvedProviders\n );\n\n if (executeResult.error) {\n const logCtx = executeResult.logs?.length\n ? `\\n\\nConsole output:\\n${executeResult.logs.join(\"\\n\")}`\n : \"\";\n throw new Error(`Code execution failed: ${executeResult.error}${logCtx}`);\n }\n\n const output: CodeOutput = { code, result: executeResult.result };\n if (executeResult.logs) output.logs = executeResult.logs;\n return output;\n });\n}\n\n/**\n * Generate types from a ToolProviderTools record.\n * Falls back to the JSON Schema generator for SimpleToolRecord.\n */\nfunction generateTypesFromRecord(\n tools: ToolProviderTools,\n namespace: string\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n const description =\n \"description\" in tool\n ? (tool as Record<string, unknown>).description\n : undefined;\n\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n const descStr =\n typeof description === \"string\" && description.trim()\n ? escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \"))\n : escapeJsDoc(toolName);\n\n availableTools += `\\n\\t/**\\n\\t * ${descStr}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqDA,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EACH,QAAQ,CACR,KAAK,EAAE,aAAa,8CAA8C,CAAC,EACvE,CAAC;;;;;AAMF,SAAS,cAAc,QAAqC;CAC1D,MAAM,YAAY,0BAA0B,OAA6B;AACzE,KAAI,CAAC,UAAW,QAAO;AACvB,QAAO;;;;;;;;AAST,SAAgB,cACd,OACA,YAAY,YACJ;CACR,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;AAErB,MAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,WAAW,iBAAiB,KAAK,KAAK;EAC5C,MAAM,WAAW,aAAa,SAAS;AAEvC,MAAI;GACF,MAAM,kBAAkB,KAAK,cACzB,cAAc,KAAK,YAAY,GAC/B;GACJ,MAAM,mBAAmB,KAAK,eAC1B,cAAc,KAAK,aAAa,GAChC;GAEJ,MAAM,YAAY,kBACd,iBAAiB,iBAAiB,GAAG,SAAS,OAAO,GACrD,QAAQ,SAAS;GAErB,MAAM,aAAa,mBACf,iBAAiB,kBAAkB,GAAG,SAAS,QAAQ,GACvD,QAAQ,SAAS;AAErB,qBAAkB,KAAK,UAAU,MAAM;AACvC,qBAAkB,KAAK,WAAW,MAAM;GAExC,MAAM,oBAAoB;AACxB,QAAI;AACF,SAAI,CAAC,iBAAiB,WAAY,QAAO,EAAE;AAC3C,YAAO,OAAO,QAAQ,gBAAgB,WAAW,CAC9C,QACE,GAAG,gBACF,cACA,OAAO,eAAe,YACrB,WAA2B,YAC/B,CACA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,cAClC,KAAA;AAEN,oBAAkB,UAAU,SAAS;AACrC,oBAAkB,UAAU,SAAS;EAErC,MAAM,UACJ,OAAO,gBAAgB,YAAY,YAAY,MAAM,GACjD,YAAY,YAAY,MAAM,CAAC,QAAQ,UAAU,IAAI,CAAC,GACtD,YAAY,SAAS;AAE3B,oBAAkB,iBAAiB,QAAQ;AAC3C,oBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;AACpF,oBAAkB;;AAGpB,kBAAiB,mBAAmB,UAAU,KAAK,eAAe;AAElE,QAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
|
|
1
|
+
{"version":3,"file":"tanstack-ai.js","names":[],"sources":["../src/tanstack-ai.ts"],"sourcesContent":["/**\n * TanStack AI integration for codemode.\n *\n * Provides the same capabilities as `@cloudflare/codemode/ai` but returns\n * TanStack AI-compatible tools for use with `chat()` from `@tanstack/ai`.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n * import { chat } from \"@tanstack/ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myServerTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n */\n\nimport { toolDefinition, convertSchemaToJsonSchema } from \"@tanstack/ai\";\nimport type {\n Tool as TanStackTool,\n ServerTool,\n JSONSchema as TanStackJSONSchema\n} from \"@tanstack/ai\";\nimport { z } from \"zod\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider,\n SimpleToolRecord\n} from \"./executor\";\nimport { runCode } from \"./run-code\";\nimport { filterTools, extractFns } from \"./resolve\";\nimport {\n DEFAULT_DESCRIPTION,\n type CreateCodeToolOptions,\n normalizeProviders\n} from \"./shared\";\nimport { jsonSchemaToType } from \"./json-schema-types\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\n\nexport type { CreateCodeToolOptions, CodeInput, CodeOutput } from \"./shared\";\nexport { DEFAULT_DESCRIPTION, normalizeProviders } from \"./shared\";\nexport { resolveProvider } from \"./resolve\";\n\nconst codeSchema = z.object({\n code: z\n .string()\n .meta({ description: \"JavaScript async arrow function to execute\" })\n});\n\n/**\n * Convert a TanStack AI schema (StandardJSONSchema or plain JSONSchema) to\n * a JSON Schema 7 object usable by the core type generator.\n */\nfunction toJsonSchema7(schema: unknown): JSONSchema7 | null {\n const converted = convertSchemaToJsonSchema(schema as TanStackJSONSchema);\n if (!converted) return null;\n return converted as unknown as JSONSchema7;\n}\n\n/**\n * Generate TypeScript type definitions from an array of TanStack AI tools.\n *\n * Uses the tools' schemas (Zod, ArkType, JSON Schema, etc.) to produce type\n * declarations that the LLM sees in the code-tool description.\n */\nexport function generateTypes(\n tools: TanStackTool[],\n namespace = \"codemode\"\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const tool of tools) {\n const safeName = sanitizeToolName(tool.name);\n const typeName = toPascalCase(safeName);\n\n try {\n const inputJsonSchema = tool.inputSchema\n ? toJsonSchema7(tool.inputSchema)\n : null;\n const outputJsonSchema = tool.outputSchema\n ? toJsonSchema7(tool.outputSchema)\n : null;\n\n const inputType = inputJsonSchema\n ? jsonSchemaToType(inputJsonSchema, `${typeName}Input`)\n : `type ${typeName}Input = unknown`;\n\n const outputType = outputJsonSchema\n ? jsonSchemaToType(outputJsonSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramDescs = (() => {\n try {\n if (!inputJsonSchema?.properties) return [];\n return Object.entries(inputJsonSchema.properties)\n .filter(\n ([, propSchema]) =>\n propSchema &&\n typeof propSchema === \"object\" &&\n (propSchema as JSONSchema7).description\n )\n .map(\n ([fieldName, propSchema]) =>\n `@param input.${fieldName} - ${(propSchema as JSONSchema7).description}`\n );\n } catch {\n return [];\n }\n })();\n\n const jsdocLines: string[] = [];\n if (tool.description?.trim()) {\n jsdocLines.push(\n escapeJsDoc(tool.description.trim().replace(/\\r?\\n/g, \" \"))\n );\n } else {\n jsdocLines.push(escapeJsDoc(tool.name));\n }\n for (const pd of paramDescs) {\n jsdocLines.push(escapeJsDoc(pd.replace(/\\r?\\n/g, \" \")));\n }\n\n const jsdocBody = jsdocLines.map((l) => `\\t * ${l}`).join(\"\\n\");\n availableTools += `\\n\\t/**\\n${jsdocBody}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n } catch {\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n availableTools += `\\n\\t/**\\n\\t * ${escapeJsDoc(tool.name)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n\n/**\n * Wrap TanStack AI tools into a ToolProvider for use with `createCodeTool`.\n *\n * Converts the array-based TanStack tool format into the record-based\n * ToolProvider that the codemode executor expects.\n *\n * @example\n * ```ts\n * import { createCodeTool, tanstackTools } from \"@cloudflare/codemode/tanstack-ai\";\n *\n * const codeTool = createCodeTool({\n * tools: [\n * tanstackTools(myServerTools),\n * tanstackTools(otherTools, \"other\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function tanstackTools(\n tools: TanStackTool[],\n name?: string\n): ToolProvider {\n const filtered = tools.filter(\n (t) => t.needsApproval !== true && typeof t.needsApproval !== \"function\"\n );\n\n const toolRecord: SimpleToolRecord = {};\n for (const tool of filtered) {\n if (tool.execute) {\n toolRecord[tool.name] = {\n description: tool.description,\n execute: async (args: unknown) => tool.execute!(args)\n };\n }\n }\n\n const ns = name ?? \"codemode\";\n const types = generateTypes(filtered, ns);\n\n return { name: ns === \"codemode\" ? undefined : ns, tools: toolRecord, types };\n}\n\n/**\n * Create a codemode tool that allows LLMs to write and execute code\n * with access to your tools in a sandboxed environment.\n *\n * Returns a TanStack AI `ServerTool` compatible with `chat()` from `@tanstack/ai`.\n *\n * @example Basic usage\n * ```ts\n * const codeTool = createCodeTool({\n * tools: [tanstackTools(myTools)],\n * executor,\n * });\n *\n * const stream = chat({\n * adapter: openaiText(\"gpt-4o\"),\n * tools: [codeTool],\n * messages,\n * });\n * ```\n *\n * @example Multiple namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * tanstackTools(githubTools, \"github\"),\n * tanstackTools(dbTools, \"db\"),\n * ],\n * executor,\n * });\n * ```\n */\nexport function createCodeTool(options: CreateCodeToolOptions): ServerTool {\n const providers = normalizeProviders(options.tools);\n\n const typeBlocks: string[] = [];\n const resolvedProviders: ResolvedProvider[] = [];\n\n for (const provider of providers) {\n const providerName = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n\n const types =\n provider.types ?? generateTypesFromRecord(filtered, providerName);\n typeBlocks.push(types);\n\n const resolved: ResolvedProvider = {\n name: providerName,\n fns: extractFns(filtered)\n };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n resolvedProviders.push(resolved);\n }\n\n const typeBlock = typeBlocks.filter(Boolean).join(\"\\n\\n\");\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n typeBlock\n );\n\n const def = toolDefinition({\n name: \"codemode_execute\" as const,\n description,\n inputSchema: codeSchema\n });\n\n return def.server(async ({ code }) =>\n runCode({ code, executor, providers: resolvedProviders })\n );\n}\n\n/**\n * Generate types from a ToolProviderTools record.\n * Falls back to the JSON Schema generator for SimpleToolRecord.\n */\nfunction generateTypesFromRecord(\n tools: ToolProviderTools,\n namespace: string\n): string {\n let availableTools = \"\";\n let availableTypes = \"\";\n\n for (const [toolName, tool] of Object.entries(tools)) {\n const safeName = sanitizeToolName(toolName);\n const typeName = toPascalCase(safeName);\n const description =\n \"description\" in tool\n ? (tool as Record<string, unknown>).description\n : undefined;\n\n availableTypes += `\\ntype ${typeName}Input = unknown`;\n availableTypes += `\\ntype ${typeName}Output = unknown`;\n\n const descStr =\n typeof description === \"string\" && description.trim()\n ? escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \"))\n : escapeJsDoc(toolName);\n\n availableTools += `\\n\\t/**\\n\\t * ${descStr}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n\n availableTools = `\\ndeclare const ${namespace}: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,MAAM,aAAa,EAAE,OAAO,EAC1B,MAAM,EACH,QAAQ,CACR,KAAK,EAAE,aAAa,8CAA8C,CAAC,EACvE,CAAC;;;;;AAMF,SAAS,cAAc,QAAqC;CAC1D,MAAM,YAAY,0BAA0B,OAA6B;CACzE,IAAI,CAAC,WAAW,OAAO;CACvB,OAAO;;;;;;;;AAST,SAAgB,cACd,OACA,YAAY,YACJ;CACR,IAAI,iBAAiB;CACrB,IAAI,iBAAiB;CAErB,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,WAAW,iBAAiB,KAAK,KAAK;EAC5C,MAAM,WAAW,aAAa,SAAS;EAEvC,IAAI;GACF,MAAM,kBAAkB,KAAK,cACzB,cAAc,KAAK,YAAY,GAC/B;GACJ,MAAM,mBAAmB,KAAK,eAC1B,cAAc,KAAK,aAAa,GAChC;GAEJ,MAAM,YAAY,kBACd,iBAAiB,iBAAiB,GAAG,SAAS,OAAO,GACrD,QAAQ,SAAS;GAErB,MAAM,aAAa,mBACf,iBAAiB,kBAAkB,GAAG,SAAS,QAAQ,GACvD,QAAQ,SAAS;GAErB,kBAAkB,KAAK,UAAU,MAAM;GACvC,kBAAkB,KAA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BAAgB,YAAY,YAAY,MAAM,GACjD,YAAY,YAAY,MAAM,CAAC,QAAQ,UAAU,IAAI,CAAC,GACtD,YAAY,SAAS;EAE3B,kBAAkB,iBAAiB,QAAQ;EAC3C,kBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;EACpF,kBAAkB;;CAGpB,iBAAiB,mBAAmB,UAAU,KAAK,eAAe;CAElE,OAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cloudflare/codemode",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.6",
|
|
4
4
|
"description": "Code Mode: use LLMs to generate executable code that performs tool calls",
|
|
5
5
|
"repository": {
|
|
6
6
|
"directory": "packages/codemode",
|
|
@@ -16,11 +16,11 @@
|
|
|
16
16
|
},
|
|
17
17
|
"devDependencies": {
|
|
18
18
|
"@modelcontextprotocol/sdk": "1.29.0",
|
|
19
|
-
"@playwright/test": "^1.
|
|
20
|
-
"@tanstack/ai": "^0.
|
|
21
|
-
"ai": "^6.0.
|
|
22
|
-
"vitest": "4.1.
|
|
23
|
-
"zod": "^4.3
|
|
19
|
+
"@playwright/test": "^1.60.0",
|
|
20
|
+
"@tanstack/ai": "^0.16.0",
|
|
21
|
+
"ai": "^6.0.180",
|
|
22
|
+
"vitest": "4.1.6",
|
|
23
|
+
"zod": "^4.4.3"
|
|
24
24
|
},
|
|
25
25
|
"peerDependencies": {
|
|
26
26
|
"@modelcontextprotocol/sdk": "^1.25.0",
|
|
@@ -63,13 +63,19 @@
|
|
|
63
63
|
"types": "./dist/tanstack-ai.d.ts",
|
|
64
64
|
"import": "./dist/tanstack-ai.js",
|
|
65
65
|
"require": "./dist/tanstack-ai.js"
|
|
66
|
+
},
|
|
67
|
+
"./browser": {
|
|
68
|
+
"types": "./dist/browser.d.ts",
|
|
69
|
+
"import": "./dist/browser.js",
|
|
70
|
+
"require": "./dist/browser.js"
|
|
66
71
|
}
|
|
67
72
|
},
|
|
68
73
|
"scripts": {
|
|
69
74
|
"build": "tsx ./scripts/build.ts",
|
|
70
|
-
"test": "vitest run",
|
|
75
|
+
"test": "vitest run && vitest run --config vitest.browser.config.ts",
|
|
71
76
|
"test:e2e": "npx playwright test --config e2e/playwright.config.ts",
|
|
72
|
-
"test:watch": "vitest"
|
|
77
|
+
"test:watch": "vitest",
|
|
78
|
+
"test:browser": "vitest run --config vitest.browser.config.ts"
|
|
73
79
|
},
|
|
74
80
|
"keywords": [
|
|
75
81
|
"cloudflare",
|