@cloudflare/codemode 0.2.0 → 0.2.1
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 +2 -2
- package/dist/ai.d.ts +1 -1
- package/dist/ai.js +2 -1
- package/dist/ai.js.map +1 -1
- package/dist/{executor-BjlGw-Dd.d.ts → executor-6RSFUhUk.d.ts} +9 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +14 -4
- package/dist/index.js.map +1 -1
- package/dist/{normalize-xNh5CsfI.js → json-schema-types-DoQ0VISs.js} +2 -43
- package/dist/json-schema-types-DoQ0VISs.js.map +1 -0
- package/dist/mcp.d.ts +51 -0
- package/dist/mcp.js +305 -0
- package/dist/mcp.js.map +1 -0
- package/dist/normalize-DnrE6oKV.js +44 -0
- package/dist/normalize-DnrE6oKV.js.map +1 -0
- package/package.json +11 -1
- package/dist/normalize-xNh5CsfI.js.map +0 -1
package/README.md
CHANGED
|
@@ -231,7 +231,7 @@ const codemode = createCodeTool({
|
|
|
231
231
|
|
|
232
232
|
### `sanitizeToolName(name)`
|
|
233
233
|
|
|
234
|
-
Converts tool names into valid JavaScript identifiers. Handles hyphens, dots, digits, reserved words.
|
|
234
|
+
Converts tool names into valid JavaScript identifiers. Handles hyphens, dots, digits, reserved words. Called automatically by `DynamicWorkerExecutor` on `fns` keys — you only need this for custom use cases.
|
|
235
235
|
|
|
236
236
|
```ts
|
|
237
237
|
import { sanitizeToolName } from "@cloudflare/codemode";
|
|
@@ -243,7 +243,7 @@ sanitizeToolName("delete"); // "delete_"
|
|
|
243
243
|
|
|
244
244
|
### `normalizeCode(code)`
|
|
245
245
|
|
|
246
|
-
Normalizes LLM-generated code into a valid async arrow function. Strips markdown code fences, handles various function formats.
|
|
246
|
+
Normalizes LLM-generated code into a valid async arrow function. Strips markdown code fences, handles various function formats. Called automatically by `DynamicWorkerExecutor` — you only need this for custom use cases.
|
|
247
247
|
|
|
248
248
|
````ts
|
|
249
249
|
import { normalizeCode } from "@cloudflare/codemode";
|
package/dist/ai.d.ts
CHANGED
package/dist/ai.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as normalizeCode } from "./normalize-DnrE6oKV.js";
|
|
2
|
+
import { a as sanitizeToolName, i as escapeJsDoc, o as toPascalCase, r as jsonSchemaToTypeString } from "./json-schema-types-DoQ0VISs.js";
|
|
2
3
|
import { asSchema, tool } from "ai";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
//#region src/tool-types.ts
|
package/dist/ai.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ai.js","names":[],"sources":["../src/tool-types.ts","../src/tool.ts"],"sourcesContent":["import { asSchema } from \"ai\";\nimport type { ZodType } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\nimport {\n jsonSchemaToTypeString,\n type ConversionContext\n} from \"./json-schema-types\";\n\nexport interface ToolDescriptor {\n description?: string;\n inputSchema: ZodType;\n outputSchema?: ZodType;\n execute?: (args: unknown) => Promise<unknown>;\n}\n\nexport type ToolDescriptors = Record<string, ToolDescriptor>;\n\n/**\n * Check if a value is a Zod schema (has _zod property).\n */\nfunction isZodSchema(value: unknown): value is ZodType {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"_zod\" in value &&\n (value as { _zod?: unknown })._zod !== undefined\n );\n}\n\n/**\n * Check if a value conforms to the Standard Schema protocol (~standard).\n * This catches Zod v3 schemas (which expose ~standard but not _zod).\n */\nfunction isStandardSchema(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"~standard\" in value &&\n (value as Record<string, unknown>)[\"~standard\"] !== undefined\n );\n}\n\n/**\n * Check if a value is an AI SDK jsonSchema wrapper.\n * The jsonSchema wrapper has a [Symbol] with jsonSchema property.\n */\nfunction isJsonSchemaWrapper(\n value: unknown\n): value is { jsonSchema: JSONSchema7 } {\n if (value === null || typeof value !== \"object\") return false;\n\n if (\"jsonSchema\" in value) {\n return true;\n }\n\n const symbols = Object.getOwnPropertySymbols(value);\n for (const sym of symbols) {\n const symValue = (value as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Extract JSON schema from an AI SDK jsonSchema wrapper.\n */\nfunction extractJsonSchema(wrapper: unknown): JSONSchema7 | null {\n if (wrapper === null || typeof wrapper !== \"object\") return null;\n\n if (\"jsonSchema\" in wrapper) {\n return (wrapper as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n\n const symbols = Object.getOwnPropertySymbols(wrapper);\n for (const sym of symbols) {\n const symValue = (wrapper as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return (symValue as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n }\n\n return null;\n}\n\n/**\n * Extract field descriptions from a schema.\n * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).\n */\nfunction extractDescriptions(schema: unknown): Record<string, string> {\n const descriptions: Record<string, string> = {};\n\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape && typeof shape === \"object\") {\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n let s = fieldSchema as { description?: string; unwrap?: () => unknown };\n while (!s.description && typeof s.unwrap === \"function\") {\n s = s.unwrap() as typeof s;\n }\n if (s.description) {\n descriptions[fieldName] = s.description;\n }\n }\n return descriptions;\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema?.properties) {\n for (const [fieldName, propSchema] of Object.entries(\n jsonSchema.properties\n )) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n }\n\n return descriptions;\n}\n\n/**\n * Extract field descriptions from a schema and format as @param lines.\n */\nfunction extractParamDescriptions(schema: unknown): string[] {\n const descriptions = extractDescriptions(schema);\n return Object.entries(descriptions).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n}\n\n/**\n * Safely convert a schema to TypeScript type string.\n * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.\n */\nfunction safeSchemaToTs(schema: unknown, typeName: string): string {\n try {\n if (isZodSchema(schema) || isStandardSchema(schema)) {\n const wrapped = asSchema(schema as ZodType);\n const jsonSchema = wrapped.jsonSchema as JSONSchema7;\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n return `type ${typeName} = unknown`;\n } catch {\n return `type ${typeName} = unknown`;\n }\n}\n\n/**\n * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.\n * These types can be included in tool descriptions to help LLMs write correct code.\n *\n * Requires the `ai` peer dependency. For a version that works with plain JSON Schema\n * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.\n */\nexport function generateTypes(tools: ToolDescriptors | ToolSet): 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\n try {\n const inputSchema =\n \"inputSchema\" in tool ? tool.inputSchema : tool.parameters;\n const outputSchema =\n \"outputSchema\" in tool ? tool.outputSchema : undefined;\n const description = tool.description;\n\n const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);\n\n const outputType = outputSchema\n ? safeSchemaToTs(outputSchema, `${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 return inputSchema ? extractParamDescriptions(inputSchema) : [];\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (description?.trim()) {\n jsdocLines.push(escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \")));\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\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(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n","import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport { generateTypes, type ToolDescriptors } from \"./tool-types\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor } from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\n\nconst 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: ToolDescriptors | ToolSet;\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\ntype CodeInput = z.infer<typeof codeSchema>;\ntype CodeOutput = { code: string; result: unknown; logs?: string[] };\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 an AI SDK compatible tool.\n */\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return \"needsApproval\" in t && t.needsApproval != null;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const tools: ToolDescriptors | ToolSet = {};\n for (const [name, t] of Object.entries(options.tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n (tools as Record<string, unknown>)[name] = t;\n }\n }\n\n const types = generateTypes(tools);\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n types\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) => {\n // Extract execute functions from tools, keyed by name.\n // Wrap each with its schema so arguments from the sandbox\n // are validated before reaching the tool function.\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 const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : \"parameters\" in t\n ? (t as Record<string, unknown>).parameters\n : undefined;\n\n // Use AI SDK's asSchema() to normalize any schema type\n // (Zod v3/v4, Standard Schema, JSON Schema) into a unified\n // Schema with an optional .validate() method.\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[sanitizeToolName(name)] = schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : execute;\n }\n }\n\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(normalizedCode, fns);\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(\n `Code execution failed: ${executeResult.error}${logCtx}`\n );\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"],"mappings":";;;;;;;AAsBA,SAAS,YAAY,OAAkC;AACrD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS,KAAA;;;;;;AAQ3C,SAAS,iBAAiB,OAAyB;AACjD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,eAAe,SACd,MAAkC,iBAAiB,KAAA;;;;;;AAQxD,SAAS,oBACP,OACsC;AACtC,KAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AAExD,KAAI,gBAAgB,MAClB,QAAO;CAGT,MAAM,UAAU,OAAO,sBAAsB,MAAM;AACnD,MAAK,MAAM,OAAO,SAAS;EACzB,MAAM,WAAY,MAAkC;AACpD,MAAI,YAAY,OAAO,aAAa,YAAY,gBAAgB,SAC9D,QAAO;;AAIX,QAAO;;;;;AAMT,SAAS,kBAAkB,SAAsC;AAC/D,KAAI,YAAY,QAAQ,OAAO,YAAY,SAAU,QAAO;AAE5D,KAAI,gBAAgB,QAClB,QAAQ,QAAwC;CAGlD,MAAM,UAAU,OAAO,sBAAsB,QAAQ;AACrD,MAAK,MAAM,OAAO,SAAS;EACzB,MAAM,WAAY,QAAoC;AACtD,MAAI,YAAY,OAAO,aAAa,YAAY,gBAAgB,SAC9D,QAAQ,SAAyC;;AAIrD,QAAO;;;;;;AAOT,SAAS,oBAAoB,QAAyC;CACpE,MAAM,eAAuC,EAAE;CAE/C,MAA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,QAAQ,SACjD;;GAGH,MAAM,SAAqB;IAAE;IAAM,QAAQ,cAAc;IAAQ;AACjE,OAAI,cAAc,KAAM,QAAO,OAAO,cAAc;AACpD,UAAO;;EAEV,CAAC"}
|
|
1
|
+
{"version":3,"file":"ai.js","names":[],"sources":["../src/tool-types.ts","../src/tool.ts"],"sourcesContent":["import { asSchema } from \"ai\";\nimport type { ZodType } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { sanitizeToolName, toPascalCase, escapeJsDoc } from \"./utils\";\nimport {\n jsonSchemaToTypeString,\n type ConversionContext\n} from \"./json-schema-types\";\n\nexport interface ToolDescriptor {\n description?: string;\n inputSchema: ZodType;\n outputSchema?: ZodType;\n execute?: (args: unknown) => Promise<unknown>;\n}\n\nexport type ToolDescriptors = Record<string, ToolDescriptor>;\n\n/**\n * Check if a value is a Zod schema (has _zod property).\n */\nfunction isZodSchema(value: unknown): value is ZodType {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"_zod\" in value &&\n (value as { _zod?: unknown })._zod !== undefined\n );\n}\n\n/**\n * Check if a value conforms to the Standard Schema protocol (~standard).\n * This catches Zod v3 schemas (which expose ~standard but not _zod).\n */\nfunction isStandardSchema(value: unknown): boolean {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"~standard\" in value &&\n (value as Record<string, unknown>)[\"~standard\"] !== undefined\n );\n}\n\n/**\n * Check if a value is an AI SDK jsonSchema wrapper.\n * The jsonSchema wrapper has a [Symbol] with jsonSchema property.\n */\nfunction isJsonSchemaWrapper(\n value: unknown\n): value is { jsonSchema: JSONSchema7 } {\n if (value === null || typeof value !== \"object\") return false;\n\n if (\"jsonSchema\" in value) {\n return true;\n }\n\n const symbols = Object.getOwnPropertySymbols(value);\n for (const sym of symbols) {\n const symValue = (value as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Extract JSON schema from an AI SDK jsonSchema wrapper.\n */\nfunction extractJsonSchema(wrapper: unknown): JSONSchema7 | null {\n if (wrapper === null || typeof wrapper !== \"object\") return null;\n\n if (\"jsonSchema\" in wrapper) {\n return (wrapper as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n\n const symbols = Object.getOwnPropertySymbols(wrapper);\n for (const sym of symbols) {\n const symValue = (wrapper as Record<symbol, unknown>)[sym];\n if (symValue && typeof symValue === \"object\" && \"jsonSchema\" in symValue) {\n return (symValue as { jsonSchema: JSONSchema7 }).jsonSchema;\n }\n }\n\n return null;\n}\n\n/**\n * Extract field descriptions from a schema.\n * Works with Zod schemas (via .shape) and jsonSchema wrappers (via .properties).\n */\nfunction extractDescriptions(schema: unknown): Record<string, string> {\n const descriptions: Record<string, string> = {};\n\n const shape = (schema as { shape?: Record<string, ZodType> }).shape;\n if (shape && typeof shape === \"object\") {\n for (const [fieldName, fieldSchema] of Object.entries(shape)) {\n let s = fieldSchema as { description?: string; unwrap?: () => unknown };\n while (!s.description && typeof s.unwrap === \"function\") {\n s = s.unwrap() as typeof s;\n }\n if (s.description) {\n descriptions[fieldName] = s.description;\n }\n }\n return descriptions;\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema?.properties) {\n for (const [fieldName, propSchema] of Object.entries(\n jsonSchema.properties\n )) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n }\n\n return descriptions;\n}\n\n/**\n * Extract field descriptions from a schema and format as @param lines.\n */\nfunction extractParamDescriptions(schema: unknown): string[] {\n const descriptions = extractDescriptions(schema);\n return Object.entries(descriptions).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n}\n\n/**\n * Safely convert a schema to TypeScript type string.\n * Handles Zod schemas (v3/v4) and AI SDK jsonSchema wrappers.\n */\nfunction safeSchemaToTs(schema: unknown, typeName: string): string {\n try {\n if (isZodSchema(schema) || isStandardSchema(schema)) {\n const wrapped = asSchema(schema as ZodType);\n const jsonSchema = wrapped.jsonSchema as JSONSchema7;\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n if (isJsonSchemaWrapper(schema)) {\n const jsonSchema = extractJsonSchema(schema);\n if (jsonSchema) {\n const ctx: ConversionContext = {\n root: jsonSchema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(jsonSchema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n }\n }\n\n return `type ${typeName} = unknown`;\n } catch {\n return `type ${typeName} = unknown`;\n }\n}\n\n/**\n * Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.\n * These types can be included in tool descriptions to help LLMs write correct code.\n *\n * Requires the `ai` peer dependency. For a version that works with plain JSON Schema\n * objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.\n */\nexport function generateTypes(tools: ToolDescriptors | ToolSet): 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\n try {\n const inputSchema =\n \"inputSchema\" in tool ? tool.inputSchema : tool.parameters;\n const outputSchema =\n \"outputSchema\" in tool ? tool.outputSchema : undefined;\n const description = tool.description;\n\n const inputType = safeSchemaToTs(inputSchema, `${typeName}Input`);\n\n const outputType = outputSchema\n ? safeSchemaToTs(outputSchema, `${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 return inputSchema ? extractParamDescriptions(inputSchema) : [];\n } catch {\n return [];\n }\n })();\n const jsdocLines: string[] = [];\n if (description?.trim()) {\n jsdocLines.push(escapeJsDoc(description.trim().replace(/\\r?\\n/g, \" \")));\n } else {\n jsdocLines.push(escapeJsDoc(toolName));\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(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n","import { tool, type Tool, asSchema } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolSet } from \"ai\";\nimport { generateTypes, type ToolDescriptors } from \"./tool-types\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor } from \"./executor\";\nimport { normalizeCode } from \"./normalize\";\n\nconst 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: ToolDescriptors | ToolSet;\n executor: Executor;\n /**\n * Custom tool description. Use {{types}} as a placeholder for the generated type definitions.\n */\n description?: string;\n}\n\nconst codeSchema = z.object({\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n});\n\ntype CodeInput = z.infer<typeof codeSchema>;\ntype CodeOutput = { code: string; result: unknown; logs?: string[] };\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 an AI SDK compatible tool.\n */\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return \"needsApproval\" in t && t.needsApproval != null;\n}\n\nexport function createCodeTool(\n options: CreateCodeToolOptions\n): Tool<CodeInput, CodeOutput> {\n const tools: ToolDescriptors | ToolSet = {};\n for (const [name, t] of Object.entries(options.tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n (tools as Record<string, unknown>)[name] = t;\n }\n }\n\n const types = generateTypes(tools);\n const executor = options.executor;\n\n const description = (options.description ?? DEFAULT_DESCRIPTION).replace(\n \"{{types}}\",\n types\n );\n\n return tool({\n description,\n inputSchema: codeSchema,\n execute: async ({ code }) => {\n // Extract execute functions from tools, keyed by name.\n // Wrap each with its schema so arguments from the sandbox\n // are validated before reaching the tool function.\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 const rawSchema =\n \"inputSchema\" in t\n ? t.inputSchema\n : \"parameters\" in t\n ? (t as Record<string, unknown>).parameters\n : undefined;\n\n // Use AI SDK's asSchema() to normalize any schema type\n // (Zod v3/v4, Standard Schema, JSON Schema) into a unified\n // Schema with an optional .validate() method.\n const schema = rawSchema != null ? asSchema(rawSchema) : undefined;\n\n fns[sanitizeToolName(name)] = schema?.validate\n ? async (args: unknown) => {\n const result = await schema.validate!(args);\n if (!result.success) throw result.error;\n return execute(result.value);\n }\n : execute;\n }\n }\n\n const normalizedCode = normalizeCode(code);\n\n const executeResult = await executor.execute(normalizedCode, fns);\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(\n `Code execution failed: ${executeResult.error}${logCtx}`\n );\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"],"mappings":";;;;;;;;AAsBA,SAAS,YAAY,OAAkC;AACrD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAA6B,SAAS,KAAA;;;;;;AAQ3C,SAAS,iBAAiB,OAAyB;AACjD,QACE,UAAU,QACV,OAAO,UAAU,YACjB,eAAe,SACd,MAAkC,iBAAiB,KAAA;;;;;;AAQxD,SAAS,oBACP,OACsC;AACtC,KAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;AAExD,KAAI,gBAAgB,MAClB,QAAO;CAGT,MAAM,UAAU,OAAO,sBAAsB,MAAM;AACnD,MAAK,MAAM,OAAO,SAAS;EACzB,MAAM,WAAY,MAAkC;AACpD,MAAI,YAAY,OAAO,aAAa,YAAY,gBAAgB,SAC9D,QAAO;;AAIX,QAAO;;;;;AAMT,SAAS,kBAAkB,SAAsC;AAC/D,KAAI,YAAY,QAAQ,OAAO,YAAY,SAAU,QAAO;AAE5D,KAAI,gBAAgB,QAClB,QAAQ,QAAwC;CAGlD,MAAM,UAAU,OAAO,sBAAsB,QAAQ;AACrD,MAAK,MAAM,OAAO,SAAS;EACzB,MAAM,WAAY,QAAoC;AACtD,MAAI,YAAY,OAAO,aAAa,YAAY,gBAAgB,SAC9D,QAAQ,SAAyC;;AAIrD,QAAO;;;;;;AAOT,SAAS,oBAAoB,QAAyC;CACpE,MAAM,eAAuC,EAAE;CAE/C,MAAM,QAAS,OAA+C;AAC9D,KAAI,SAAS,OAAO,UAAU,UAAU;AACtC,OAAK,MAAM,CAAC,WAAW,gBAAgB,OAAO,QAAQ,MAAM,EAAE;GAC5D,IAAI,IAAI;AACR,UAAO,CAAC,EAAE,eAAe,OAAO,EAAE,WAAW,WAC3C,KAAI,EAAE,QAAQ;AAEhB,OAAI,EAAE,YACJ,cAAa,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/
|
|
43
43
|
globalOutbound?: Fetcher | null;
|
|
44
|
+
/**
|
|
45
|
+
* Additional modules to make available in the sandbox.
|
|
46
|
+
* Keys are module specifiers (e.g. `"mylib.js"`), values are module source code.
|
|
47
|
+
* Sandbox code can import from these via `import { ... } from "mylib.js"`.
|
|
48
|
+
*
|
|
49
|
+
* Note: the key `"executor.js"` is reserved and will be ignored if provided.
|
|
50
|
+
*/
|
|
51
|
+
modules?: Record<string, string>;
|
|
44
52
|
}
|
|
45
53
|
/**
|
|
46
54
|
* Executes code in an isolated Cloudflare Worker via WorkerLoader.
|
|
@@ -67,4 +75,4 @@ export {
|
|
|
67
75
|
ExecuteResult as r,
|
|
68
76
|
DynamicWorkerExecutor as t
|
|
69
77
|
};
|
|
70
|
-
//# sourceMappingURL=executor-
|
|
78
|
+
//# sourceMappingURL=executor-6RSFUhUk.d.ts.map
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t as normalizeCode } from "./normalize-DnrE6oKV.js";
|
|
2
|
+
import { a as sanitizeToolName, n as jsonSchemaToType, t as generateTypesFromJsonSchema } from "./json-schema-types-DoQ0VISs.js";
|
|
2
3
|
import { RpcTarget } from "cloudflare:workers";
|
|
3
4
|
//#region src/executor.ts
|
|
4
5
|
/**
|
|
@@ -42,13 +43,19 @@ var DynamicWorkerExecutor = class {
|
|
|
42
43
|
#loader;
|
|
43
44
|
#timeout;
|
|
44
45
|
#globalOutbound;
|
|
46
|
+
#modules;
|
|
45
47
|
constructor(options) {
|
|
46
48
|
this.#loader = options.loader;
|
|
47
49
|
this.#timeout = options.timeout ?? 3e4;
|
|
48
50
|
this.#globalOutbound = options.globalOutbound ?? null;
|
|
51
|
+
const { "executor.js": _, ...safeModules } = options.modules ?? {};
|
|
52
|
+
this.#modules = safeModules;
|
|
49
53
|
}
|
|
50
54
|
async execute(code, fns) {
|
|
55
|
+
const normalized = normalizeCode(code);
|
|
51
56
|
const timeoutMs = this.#timeout;
|
|
57
|
+
const sanitizedFns = {};
|
|
58
|
+
for (const [name, fn] of Object.entries(fns)) sanitizedFns[sanitizeToolName(name)] = fn;
|
|
52
59
|
const modulePrefix = [
|
|
53
60
|
"import { WorkerEntrypoint } from \"cloudflare:workers\";",
|
|
54
61
|
"",
|
|
@@ -82,13 +89,16 @@ var DynamicWorkerExecutor = class {
|
|
|
82
89
|
" }",
|
|
83
90
|
"}"
|
|
84
91
|
].join("\n");
|
|
85
|
-
const executorModule = modulePrefix +
|
|
86
|
-
const dispatcher = new ToolDispatcher(
|
|
92
|
+
const executorModule = modulePrefix + normalized + moduleSuffix;
|
|
93
|
+
const dispatcher = new ToolDispatcher(sanitizedFns);
|
|
87
94
|
const response = await this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({
|
|
88
95
|
compatibilityDate: "2025-06-01",
|
|
89
96
|
compatibilityFlags: ["nodejs_compat"],
|
|
90
97
|
mainModule: "executor.js",
|
|
91
|
-
modules: {
|
|
98
|
+
modules: {
|
|
99
|
+
...this.#modules,
|
|
100
|
+
"executor.js": executorModule
|
|
101
|
+
},
|
|
92
102
|
globalOutbound: this.#globalOutbound
|
|
93
103
|
})).getEntrypoint().evaluate(dispatcher);
|
|
94
104
|
if (response.error) return {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["#fns","#loader","#timeout","#globalOutbound"],"sources":["../src/executor.ts"],"sourcesContent":["/**\n * Executor interface and DynamicWorkerExecutor implementation.\n *\n * The Executor interface is the core abstraction — implement it to run\n * LLM-generated code in any sandbox (Workers, QuickJS, Node VM, etc.).\n */\n\nimport { RpcTarget } from \"cloudflare:workers\";\n\nexport interface ExecuteResult {\n result: unknown;\n error?: string;\n logs?: string[];\n}\n\n/**\n * An executor runs LLM-generated code in a sandbox, making the provided\n * tool functions callable as `codemode.*` inside the sandbox.\n *\n * Implementations should never throw — errors are returned in `ExecuteResult.error`.\n */\nexport interface Executor {\n execute(\n code: string,\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult>;\n}\n\n// -- ToolDispatcher (RPC target for tool calls from sandboxed Workers) --\n\n/**\n * An RpcTarget that dispatches tool calls from the sandboxed Worker\n * back to the host. Passed via Workers RPC to the dynamic Worker's\n * evaluate() method — no globalOutbound or Fetcher bindings needed.\n */\nexport class ToolDispatcher extends RpcTarget {\n #fns: Record<string, (...args: unknown[]) => Promise<unknown>>;\n\n constructor(fns: Record<string, (...args: unknown[]) => Promise<unknown>>) {\n super();\n this.#fns = fns;\n }\n\n async call(name: string, argsJson: string): Promise<string> {\n const fn = this.#fns[name];\n if (!fn) {\n return JSON.stringify({ error: `Tool \"${name}\" not found` });\n }\n try {\n const args = argsJson ? JSON.parse(argsJson) : {};\n const result = await fn(args);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n}\n\n// -- DynamicWorkerExecutor (Cloudflare Workers) --\n\nexport interface DynamicWorkerExecutorOptions {\n loader: WorkerLoader;\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n */\n timeout?: number;\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access (full internet).\n * - A `Fetcher`: all outbound requests route through this handler.\n */\n globalOutbound?: Fetcher | null;\n}\n\n/**\n * Executes code in an isolated Cloudflare Worker via WorkerLoader.\n * Tool calls are dispatched via Workers RPC — the host passes a\n * ToolDispatcher (RpcTarget) to the Worker's evaluate() method.\n *\n * External fetch() and connect() are blocked by default via\n * `globalOutbound: null` (runtime-enforced). Pass a Fetcher to\n * `globalOutbound` to allow controlled outbound access.\n */\nexport class DynamicWorkerExecutor implements Executor {\n #loader: WorkerLoader;\n #timeout: number;\n #globalOutbound: Fetcher | null;\n\n constructor(options: DynamicWorkerExecutorOptions) {\n this.#loader = options.loader;\n this.#timeout = options.timeout ?? 30000;\n this.#globalOutbound = options.globalOutbound ?? null;\n }\n\n async execute(\n code: string,\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n const timeoutMs = this.#timeout;\n\n const modulePrefix = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(dispatcher) {\",\n \" const __logs = [];\",\n ' console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };',\n ' console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };',\n ' console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };',\n \" const codemode = new Proxy({}, {\",\n \" get: (_, toolName) => async (args) => {\",\n \" const resJson = await dispatcher.call(String(toolName), JSON.stringify(args ?? {}));\",\n \" const data = JSON.parse(resJson);\",\n \" if (data.error) throw new Error(data.error);\",\n \" return data.result;\",\n \" }\",\n \" });\",\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ].join(\"\\n\");\n\n const moduleSuffix = [\n \")(),\",\n ' new Promise((_, reject) => setTimeout(() => reject(new Error(\"Execution timed out\")), ' +\n timeoutMs +\n \"))\",\n \" ]);\",\n \" return { result, logs: __logs };\",\n \" } catch (err) {\",\n \" return { result: undefined, error: err.message, logs: __logs };\",\n \" }\",\n \" }\",\n \"}\"\n ].join(\"\\n\");\n\n const executorModule = modulePrefix +
|
|
1
|
+
{"version":3,"file":"index.js","names":["#fns","#loader","#timeout","#globalOutbound","#modules"],"sources":["../src/executor.ts"],"sourcesContent":["/**\n * Executor interface and DynamicWorkerExecutor implementation.\n *\n * The Executor interface is the core abstraction — implement it to run\n * LLM-generated code in any sandbox (Workers, QuickJS, Node VM, etc.).\n */\n\nimport { RpcTarget } from \"cloudflare:workers\";\nimport { normalizeCode } from \"./normalize\";\nimport { sanitizeToolName } from \"./utils\";\n\nexport interface ExecuteResult {\n result: unknown;\n error?: string;\n logs?: string[];\n}\n\n/**\n * An executor runs LLM-generated code in a sandbox, making the provided\n * tool functions callable as `codemode.*` inside the sandbox.\n *\n * Implementations should never throw — errors are returned in `ExecuteResult.error`.\n */\nexport interface Executor {\n execute(\n code: string,\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult>;\n}\n\n// -- ToolDispatcher (RPC target for tool calls from sandboxed Workers) --\n\n/**\n * An RpcTarget that dispatches tool calls from the sandboxed Worker\n * back to the host. Passed via Workers RPC to the dynamic Worker's\n * evaluate() method — no globalOutbound or Fetcher bindings needed.\n */\nexport class ToolDispatcher extends RpcTarget {\n #fns: Record<string, (...args: unknown[]) => Promise<unknown>>;\n\n constructor(fns: Record<string, (...args: unknown[]) => Promise<unknown>>) {\n super();\n this.#fns = fns;\n }\n\n async call(name: string, argsJson: string): Promise<string> {\n const fn = this.#fns[name];\n if (!fn) {\n return JSON.stringify({ error: `Tool \"${name}\" not found` });\n }\n try {\n const args = argsJson ? JSON.parse(argsJson) : {};\n const result = await fn(args);\n return JSON.stringify({ result });\n } catch (err) {\n return JSON.stringify({\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n}\n\n// -- DynamicWorkerExecutor (Cloudflare Workers) --\n\nexport interface DynamicWorkerExecutorOptions {\n loader: WorkerLoader;\n /**\n * Timeout in milliseconds for code execution. Defaults to 30000 (30s).\n */\n timeout?: number;\n /**\n * Controls outbound network access from sandboxed code.\n * - `null` (default): fetch() and connect() throw — sandbox is fully isolated.\n * - `undefined`: inherits parent Worker's network access (full internet).\n * - A `Fetcher`: all outbound requests route through this handler.\n */\n globalOutbound?: Fetcher | null;\n /**\n * Additional modules to make available in the sandbox.\n * Keys are module specifiers (e.g. `\"mylib.js\"`), values are module source code.\n * Sandbox code can import from these via `import { ... } from \"mylib.js\"`.\n *\n * Note: the key `\"executor.js\"` is reserved and will be ignored if provided.\n */\n modules?: Record<string, string>;\n}\n\n/**\n * Executes code in an isolated Cloudflare Worker via WorkerLoader.\n * Tool calls are dispatched via Workers RPC — the host passes a\n * ToolDispatcher (RpcTarget) to the Worker's evaluate() method.\n *\n * External fetch() and connect() are blocked by default via\n * `globalOutbound: null` (runtime-enforced). Pass a Fetcher to\n * `globalOutbound` to allow controlled outbound access.\n */\nexport class DynamicWorkerExecutor implements Executor {\n #loader: WorkerLoader;\n #timeout: number;\n #globalOutbound: Fetcher | null;\n #modules: Record<string, string>;\n\n constructor(options: DynamicWorkerExecutorOptions) {\n this.#loader = options.loader;\n this.#timeout = options.timeout ?? 30000;\n this.#globalOutbound = options.globalOutbound ?? null;\n const { \"executor.js\": _, ...safeModules } = options.modules ?? {};\n this.#modules = safeModules;\n }\n\n async execute(\n code: string,\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n const normalized = normalizeCode(code);\n const timeoutMs = this.#timeout;\n\n // Sanitize fn keys so raw tool names (e.g. \"github.list-issues\") become\n // valid JS identifiers (e.g. \"github_list_issues\") on the codemode proxy.\n const sanitizedFns: Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n > = {};\n for (const [name, fn] of Object.entries(fns)) {\n sanitizedFns[sanitizeToolName(name)] = fn;\n }\n\n const modulePrefix = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(dispatcher) {\",\n \" const __logs = [];\",\n ' console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };',\n ' console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };',\n ' console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };',\n \" const codemode = new Proxy({}, {\",\n \" get: (_, toolName) => async (args) => {\",\n \" const resJson = await dispatcher.call(String(toolName), JSON.stringify(args ?? {}));\",\n \" const data = JSON.parse(resJson);\",\n \" if (data.error) throw new Error(data.error);\",\n \" return data.result;\",\n \" }\",\n \" });\",\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ].join(\"\\n\");\n\n const moduleSuffix = [\n \")(),\",\n ' new Promise((_, reject) => setTimeout(() => reject(new Error(\"Execution timed out\")), ' +\n timeoutMs +\n \"))\",\n \" ]);\",\n \" return { result, logs: __logs };\",\n \" } catch (err) {\",\n \" return { result: undefined, error: err.message, logs: __logs };\",\n \" }\",\n \" }\",\n \"}\"\n ].join(\"\\n\");\n\n const executorModule = modulePrefix + normalized + moduleSuffix;\n\n const dispatcher = new ToolDispatcher(sanitizedFns);\n\n const worker = this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({\n compatibilityDate: \"2025-06-01\",\n compatibilityFlags: [\"nodejs_compat\"],\n mainModule: \"executor.js\",\n modules: {\n ...this.#modules,\n \"executor.js\": executorModule\n },\n globalOutbound: this.#globalOutbound\n }));\n\n const entrypoint = worker.getEntrypoint() as unknown as {\n evaluate(dispatcher: ToolDispatcher): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatcher);\n\n if (response.error) {\n return { result: undefined, error: response.error, logs: response.logs };\n }\n\n return { result: response.result, logs: response.logs };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqCA,IAAa,iBAAb,cAAoC,UAAU;CAC5C;CAEA,YAAY,KAA+D;AACzE,SAAO;AACP,QAAA,MAAY;;CAGd,MAAM,KAAK,MAAc,UAAmC;EAC1D,MAAM,KAAK,MAAA,IAAU;AACrB,MAAI,CAAC,GACH,QAAO,KAAK,UAAU,EAAE,OAAO,SAAS,KAAK,cAAc,CAAC;AAE9D,MAAI;GAEF,MAAM,SAAS,MAAM,GADR,WAAW,KAAK,MAAM,SAAS,GAAG,EAAE,CACpB;AAC7B,UAAO,KAAK,UAAU,EAAE,QAAQ,CAAC;WAC1B,KAAK;AACZ,UAAO,KAAK,UAAU,EACpB,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,IAAI,EACxD,CAAC;;;;;;;;;;;;;AAuCR,IAAa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
|
|
4
3
|
"abstract",
|
|
@@ -328,46 +327,6 @@ ${availableTools}
|
|
|
328
327
|
`.trim();
|
|
329
328
|
}
|
|
330
329
|
//#endregion
|
|
331
|
-
|
|
332
|
-
/**
|
|
333
|
-
* Strip markdown code fences that LLMs commonly wrap code in.
|
|
334
|
-
* Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.
|
|
335
|
-
*/
|
|
336
|
-
function stripCodeFences(code) {
|
|
337
|
-
const match = code.match(/^```(?:js|javascript|typescript|ts|tsx|jsx)?\s*\n([\s\S]*?)```\s*$/);
|
|
338
|
-
return match ? match[1] : code;
|
|
339
|
-
}
|
|
340
|
-
function normalizeCode(code) {
|
|
341
|
-
const trimmed = stripCodeFences(code.trim());
|
|
342
|
-
if (!trimmed.trim()) return "async () => {}";
|
|
343
|
-
const source = trimmed.trim();
|
|
344
|
-
try {
|
|
345
|
-
const ast = acorn.parse(source, {
|
|
346
|
-
ecmaVersion: "latest",
|
|
347
|
-
sourceType: "module"
|
|
348
|
-
});
|
|
349
|
-
if (ast.body.length === 1 && ast.body[0].type === "ExpressionStatement") {
|
|
350
|
-
if (ast.body[0].expression.type === "ArrowFunctionExpression") return source;
|
|
351
|
-
}
|
|
352
|
-
if (ast.body.length === 1 && ast.body[0].type === "ExportDefaultDeclaration") {
|
|
353
|
-
const decl = ast.body[0].declaration;
|
|
354
|
-
const inner = source.slice(decl.start, decl.end);
|
|
355
|
-
if (decl.type === "FunctionDeclaration" && !decl.id) return `async () => {\nreturn (${inner})();\n}`;
|
|
356
|
-
if (decl.type === "ClassDeclaration" && !decl.id) return `async () => {\nreturn (${inner});\n}`;
|
|
357
|
-
return normalizeCode(inner);
|
|
358
|
-
}
|
|
359
|
-
if (ast.body.length === 1 && ast.body[0].type === "FunctionDeclaration") return `async () => {\n${source}\nreturn ${ast.body[0].id?.name ?? "fn"}();\n}`;
|
|
360
|
-
const last = ast.body[ast.body.length - 1];
|
|
361
|
-
if (last?.type === "ExpressionStatement") {
|
|
362
|
-
const exprStmt = last;
|
|
363
|
-
return `async () => {\n${source.slice(0, last.start)}return (${source.slice(exprStmt.expression.start, exprStmt.expression.end)})\n}`;
|
|
364
|
-
}
|
|
365
|
-
return `async () => {\n${source}\n}`;
|
|
366
|
-
} catch {
|
|
367
|
-
return `async () => {\n${source}\n}`;
|
|
368
|
-
}
|
|
369
|
-
}
|
|
370
|
-
//#endregion
|
|
371
|
-
export { escapeJsDoc as a, jsonSchemaToTypeString as i, generateTypesFromJsonSchema as n, sanitizeToolName as o, jsonSchemaToType as r, toPascalCase as s, normalizeCode as t };
|
|
330
|
+
export { sanitizeToolName as a, escapeJsDoc as i, jsonSchemaToType as n, toPascalCase as o, jsonSchemaToTypeString as r, generateTypesFromJsonSchema as t };
|
|
372
331
|
|
|
373
|
-
//# sourceMappingURL=
|
|
332
|
+
//# sourceMappingURL=json-schema-types-DoQ0VISs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"json-schema-types-DoQ0VISs.js","names":[],"sources":["../src/utils.ts","../src/json-schema-types.ts"],"sourcesContent":["const JS_RESERVED = new Set([\n \"abstract\",\n \"arguments\",\n \"await\",\n \"boolean\",\n \"break\",\n \"byte\",\n \"case\",\n \"catch\",\n \"char\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"double\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"final\",\n \"finally\",\n \"float\",\n \"for\",\n \"function\",\n \"goto\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"int\",\n \"interface\",\n \"let\",\n \"long\",\n \"native\",\n \"new\",\n \"null\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"return\",\n \"short\",\n \"static\",\n \"super\",\n \"switch\",\n \"synchronized\",\n \"this\",\n \"throw\",\n \"throws\",\n \"transient\",\n \"true\",\n \"try\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"volatile\",\n \"while\",\n \"with\",\n \"yield\"\n]);\n\n/**\n * Sanitize a tool name into a valid JavaScript identifier.\n * Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,\n * prefixes digit-leading names with `_`, and appends `_` to JS reserved words.\n */\nexport function sanitizeToolName(name: string): string {\n if (!name) return \"_\";\n\n // Replace common separators with underscores\n let sanitized = name.replace(/[-.\\s]/g, \"_\");\n\n // Strip any remaining non-identifier characters\n sanitized = sanitized.replace(/[^a-zA-Z0-9_$]/g, \"\");\n\n if (!sanitized) return \"_\";\n\n // Prefix with _ if starts with a digit\n if (/^[0-9]/.test(sanitized)) {\n sanitized = \"_\" + sanitized;\n }\n\n // Append _ to reserved words\n if (JS_RESERVED.has(sanitized)) {\n sanitized = sanitized + \"_\";\n }\n\n return sanitized;\n}\n\nexport function toPascalCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\n/**\n * Escape a character as a unicode escape sequence if it is a control character.\n */\nfunction escapeControlChar(ch: string): string {\n const code = ch.charCodeAt(0);\n if (code <= 0x1f || code === 0x7f) {\n return \"\\\\u\" + code.toString(16).padStart(4, \"0\");\n }\n return ch;\n}\n\n/**\n * Quote a property name if needed.\n * Escapes backslashes, quotes, and control characters.\n */\nexport function quoteProp(name: string): string {\n if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {\n let escaped = \"\";\n for (const ch of name) {\n if (ch === \"\\\\\") escaped += \"\\\\\\\\\";\n else if (ch === '\"') escaped += '\\\\\"';\n else if (ch === \"\\n\") escaped += \"\\\\n\";\n else if (ch === \"\\r\") escaped += \"\\\\r\";\n else if (ch === \"\\t\") escaped += \"\\\\t\";\n else if (ch === \"\\u2028\") escaped += \"\\\\u2028\";\n else if (ch === \"\\u2029\") escaped += \"\\\\u2029\";\n else escaped += escapeControlChar(ch);\n }\n return `\"${escaped}\"`;\n }\n return name;\n}\n\n/**\n * Escape a string for use inside a double-quoted TypeScript string literal.\n */\nexport function escapeStringLiteral(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch === \"\\\\\") out += \"\\\\\\\\\";\n else if (ch === '\"') out += '\\\\\"';\n else if (ch === \"\\n\") out += \"\\\\n\";\n else if (ch === \"\\r\") out += \"\\\\r\";\n else if (ch === \"\\t\") out += \"\\\\t\";\n else if (ch === \"\\u2028\") out += \"\\\\u2028\";\n else if (ch === \"\\u2029\") out += \"\\\\u2029\";\n else out += escapeControlChar(ch);\n }\n return out;\n}\n\n/**\n * Escape a string for use inside a JSDoc comment.\n * Prevents premature comment closure from star-slash sequences.\n */\nexport function escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"*\\\\/\");\n}\n","import type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport {\n sanitizeToolName,\n toPascalCase,\n escapeJsDoc,\n escapeStringLiteral,\n quoteProp\n} from \"./utils\";\n\nexport interface ConversionContext {\n root: JSONSchema7;\n depth: number;\n seen: Set<unknown>;\n maxDepth: number;\n}\n\n/**\n * Resolve an internal JSON Pointer $ref (e.g. #/definitions/Foo) against the root schema.\n * Returns null for external URLs or unresolvable paths.\n */\nfunction resolveRef(\n ref: string,\n root: JSONSchema7\n): JSONSchema7Definition | null {\n // \"#\" is a valid self-reference to the root schema\n if (ref === \"#\") return root;\n\n if (!ref.startsWith(\"#/\")) return null;\n\n const segments = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n\n let current: unknown = root;\n for (const seg of segments) {\n if (current === null || typeof current !== \"object\") return null;\n current = (current as Record<string, unknown>)[seg];\n if (current === undefined) return null;\n }\n\n // Allow both object schemas and boolean schemas (true = any, false = never)\n if (typeof current === \"boolean\") return current;\n if (current === null || typeof current !== \"object\") return null;\n return current as JSONSchema7;\n}\n\n/**\n * Apply OpenAPI 3.0 `nullable: true` to a type result.\n */\nfunction applyNullable(result: string, schema: unknown): string {\n if (\n result !== \"unknown\" &&\n result !== \"never\" &&\n (schema as Record<string, unknown>)?.nullable === true\n ) {\n return `${result} | null`;\n }\n return result;\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type string.\n * This is a direct conversion without going through Zod.\n */\nexport function jsonSchemaToTypeString(\n schema: JSONSchema7Definition,\n indent: string,\n ctx: ConversionContext\n): string {\n // Handle boolean schemas\n if (typeof schema === \"boolean\") {\n return schema ? \"unknown\" : \"never\";\n }\n\n // Depth guard\n if (ctx.depth >= ctx.maxDepth) return \"unknown\";\n\n // Circular reference guard\n if (ctx.seen.has(schema)) return \"unknown\";\n\n ctx.seen.add(schema);\n const nextCtx: ConversionContext = {\n ...ctx,\n depth: ctx.depth + 1\n };\n\n try {\n // Handle $ref\n if (schema.$ref) {\n const resolved = resolveRef(schema.$ref, ctx.root);\n if (!resolved) return \"unknown\";\n return applyNullable(\n jsonSchemaToTypeString(resolved, indent, nextCtx),\n schema\n );\n }\n\n // Handle anyOf/oneOf (union types)\n if (schema.anyOf) {\n const types = schema.anyOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n if (schema.oneOf) {\n const types = schema.oneOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n\n // Handle allOf (intersection types)\n if (schema.allOf) {\n const types = schema.allOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" & \"), schema);\n }\n\n // Handle enum\n if (schema.enum) {\n if (schema.enum.length === 0) return \"never\";\n const result = schema.enum\n .map((v) => {\n if (v === null) return \"null\";\n if (typeof v === \"string\") return '\"' + escapeStringLiteral(v) + '\"';\n if (typeof v === \"object\") return JSON.stringify(v) ?? \"unknown\";\n return String(v);\n })\n .join(\" | \");\n return applyNullable(result, schema);\n }\n\n // Handle const\n if (schema.const !== undefined) {\n const result =\n schema.const === null\n ? \"null\"\n : typeof schema.const === \"string\"\n ? '\"' + escapeStringLiteral(schema.const) + '\"'\n : typeof schema.const === \"object\"\n ? (JSON.stringify(schema.const) ?? \"unknown\")\n : String(schema.const);\n return applyNullable(result, schema);\n }\n\n // Handle type\n const type = schema.type;\n\n if (type === \"string\") return applyNullable(\"string\", schema);\n if (type === \"number\" || type === \"integer\")\n return applyNullable(\"number\", schema);\n if (type === \"boolean\") return applyNullable(\"boolean\", schema);\n if (type === \"null\") return \"null\";\n\n if (type === \"array\") {\n // Tuple support: prefixItems (JSON Schema 2020-12)\n const prefixItems = (schema as Record<string, unknown>)\n .prefixItems as JSONSchema7Definition[];\n if (Array.isArray(prefixItems)) {\n const types = prefixItems.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n // Tuple support: items as array (draft-07)\n if (Array.isArray(schema.items)) {\n const types = schema.items.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n if (schema.items) {\n const itemType = jsonSchemaToTypeString(schema.items, indent, nextCtx);\n return applyNullable(`${itemType}[]`, schema);\n }\n return applyNullable(\"unknown[]\", schema);\n }\n\n if (type === \"object\" || schema.properties) {\n const props = schema.properties || {};\n const required = new Set(schema.required || []);\n const lines: string[] = [];\n\n for (const [propName, propSchema] of Object.entries(props)) {\n if (typeof propSchema === \"boolean\") {\n const boolType = propSchema ? \"unknown\" : \"never\";\n const optionalMark = required.has(propName) ? \"\" : \"?\";\n lines.push(\n `${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`\n );\n continue;\n }\n\n const isRequired = required.has(propName);\n const propType = jsonSchemaToTypeString(\n propSchema,\n indent + \" \",\n nextCtx\n );\n const desc = propSchema.description;\n const format = propSchema.format;\n\n if (desc || format) {\n const descText = desc\n ? escapeJsDoc(desc.replace(/\\r?\\n/g, \" \"))\n : undefined;\n const formatTag = format\n ? `@format ${escapeJsDoc(format)}`\n : undefined;\n\n if (descText && formatTag) {\n lines.push(`${indent} /**`);\n lines.push(`${indent} * ${descText}`);\n lines.push(`${indent} * ${formatTag}`);\n lines.push(`${indent} */`);\n } else {\n lines.push(`${indent} /** ${descText ?? formatTag} */`);\n }\n }\n\n const quotedName = quoteProp(propName);\n const optionalMark = isRequired ? \"\" : \"?\";\n lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);\n }\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n const valueType =\n schema.additionalProperties === true\n ? \"unknown\"\n : jsonSchemaToTypeString(\n schema.additionalProperties,\n indent + \" \",\n nextCtx\n );\n lines.push(`${indent} [key: string]: ${valueType};`);\n }\n\n if (lines.length === 0) {\n if (schema.additionalProperties === false) {\n return applyNullable(\"{}\", schema);\n }\n return applyNullable(\"Record<string, unknown>\", schema);\n }\n\n const result = `{\\n${lines.join(\"\\n\")}\\n${indent}}`;\n return applyNullable(result, schema);\n }\n\n // Handle array of types (e.g., [\"string\", \"null\"])\n if (Array.isArray(type)) {\n const types = type.map((t) => {\n if (t === \"string\") return \"string\";\n if (t === \"number\" || t === \"integer\") return \"number\";\n if (t === \"boolean\") return \"boolean\";\n if (t === \"null\") return \"null\";\n if (t === \"array\") return \"unknown[]\";\n if (t === \"object\") return \"Record<string, unknown>\";\n return \"unknown\";\n });\n return applyNullable(types.join(\" | \"), schema);\n }\n\n return \"unknown\";\n } finally {\n ctx.seen.delete(schema);\n }\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type declaration.\n */\nexport function jsonSchemaToType(\n schema: JSONSchema7,\n typeName: string\n): string {\n const ctx: ConversionContext = {\n root: schema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(schema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n}\n\n/**\n * Extract field descriptions from a JSON Schema's properties.\n */\nfunction extractJsonSchemaDescriptions(\n schema: JSONSchema7\n): Record<string, string> {\n const descriptions: Record<string, string> = {};\n if (schema.properties) {\n for (const [fieldName, propSchema] of Object.entries(schema.properties)) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n return descriptions;\n}\n\n/**\n * A tool descriptor using plain JSON Schema (no Zod or AI SDK dependency).\n */\nexport interface JsonSchemaToolDescriptor {\n description?: string;\n inputSchema: JSONSchema7;\n outputSchema?: JSONSchema7;\n}\n\nexport type JsonSchemaToolDescriptors = Record<\n string,\n JsonSchemaToolDescriptor\n>;\n\n/**\n * Generate TypeScript type definitions from tool descriptors with JSON Schema.\n * This function has NO dependency on the AI SDK or Zod — it works purely with\n * JSON Schema objects.\n *\n * Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool\n * definitions, etc.) and don't need the AI SDK.\n */\nexport function generateTypesFromJsonSchema(\n tools: JsonSchemaToolDescriptors\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\n try {\n const inputType = jsonSchemaToType(tool.inputSchema, `${typeName}Input`);\n\n const outputType = tool.outputSchema\n ? jsonSchemaToType(tool.outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramLines = (() => {\n try {\n const paramDescs = extractJsonSchemaDescriptions(tool.inputSchema);\n return Object.entries(paramDescs).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n } catch {\n return [];\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(toolName));\n }\n for (const pd of paramLines) {\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(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n"],"mappings":";AAAA,MAAM,cAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;AAOF,SAAgB,iBAAiB,MAAsB;AACrD,KAAI,CAAC,KAAM,QAAO;CAGlB,IAAI,YAAY,KAAK,QAAQ,WAAW,IAAI;AAG5C,aAAY,UAAU,QAAQ,mBAAmB,GAAG;AAEpD,KAAI,CAAC,UAAW,QAAO;AAGvB,KAAI,SAAS,KAAK,UAAU,CAC1B,aAAY,MAAM;AAIpB,KAAI,YAAY,IAAI,UAAU,CAC5B,aAAY,YAAY;AAG1B,QAAO;;AAGT,SAAgB,aAAa,KAAa;AACxC,QAAO,IACJ,QAAQ,cAAc,GAAG,WAAW,OAAO,aAAa,CAAC,CACzD,QAAQ,WAAW,WAAW,OA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vC,qBAAkB,KAAK,WAAW,MAAM;GAExC,MAAM,oBAAoB;AACxB,QAAI;KACF,MAAM,aAAa,8BAA8B,KAAK,YAAY;AAClE,YAAO,OAAO,QAAQ,WAAW,CAAC,KAC/B,CAAC,WAAW,UAAU,gBAAgB,UAAU,KAAK,OACvD;YACK;AACN,YAAO,EAAE;;OAET;GACJ,MAAM,aAAuB,EAAE;AAC/B,OAAI,KAAK,aAAa,MAAM,CAC1B,YAAW,KACT,YAAY,KAAK,YAAY,MAAM,CAAC,QAAQ,UAAU,IAAI,CAAC,CAC5D;OAED,YAAW,KAAK,YAAY,SAAS,CAAC;AAExC,QAAK,MAAM,MAAM,WACf,YAAW,KAAK,YAAY,GAAG,QAAQ,UAAU,IAAI,CAAC,CAAC;GAGzD,MAAM,YAAY,WAAW,KAAK,MAAM,QAAQ,IAAI,CAAC,KAAK,KAAK;AAC/D,qBAAkB,YAAY,UAAU;AACxC,qBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;AACpF,qBAAkB;UACZ;AACN,qBAAkB,UAAU,SAAS;AACrC,qBAAkB,UAAU,SAAS;AAErC,qBAAkB,iBAAiB,YAAY,SAAS,CAAC;AACzD,qBAAkB,OAAO,SAAS,YAAY,SAAS,oBAAoB,SAAS;AACpF,qBAAkB;;;AAItB,kBAAiB,8BAA8B,eAAe;AAE9D,QAAO;EACP,eAAe;EACf,eAAe;IACb,MAAM"}
|
package/dist/mcp.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { i as Executor } from "./executor-6RSFUhUk.js";
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
|
|
4
|
+
//#region src/mcp.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Wrap an existing MCP server with a single codemode `code` tool.
|
|
7
|
+
*
|
|
8
|
+
* Connects to the upstream server via in-memory transport, discovers its
|
|
9
|
+
* tools, and returns a new MCP server with a `code` tool that exposes
|
|
10
|
+
* all upstream tools as typed methods.
|
|
11
|
+
*/
|
|
12
|
+
interface CodeMcpServerOptions {
|
|
13
|
+
server: McpServer;
|
|
14
|
+
executor: Executor;
|
|
15
|
+
}
|
|
16
|
+
declare function codeMcpServer(
|
|
17
|
+
options: CodeMcpServerOptions
|
|
18
|
+
): Promise<McpServer>;
|
|
19
|
+
interface RequestOptions {
|
|
20
|
+
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
21
|
+
path: string;
|
|
22
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
23
|
+
body?: unknown;
|
|
24
|
+
contentType?: string;
|
|
25
|
+
rawBody?: boolean;
|
|
26
|
+
}
|
|
27
|
+
interface OpenApiMcpServerOptions {
|
|
28
|
+
spec: Record<string, unknown>;
|
|
29
|
+
executor: Executor;
|
|
30
|
+
request: (options: RequestOptions) => Promise<unknown>;
|
|
31
|
+
name?: string;
|
|
32
|
+
version?: string;
|
|
33
|
+
description?: string;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Create an MCP server with search + execute tools from an OpenAPI spec.
|
|
37
|
+
*
|
|
38
|
+
* The search tool lets the LLM query the spec to find endpoints.
|
|
39
|
+
* The execute tool lets the LLM call the API via a user-provided
|
|
40
|
+
* request function that runs on the host (auth never enters the sandbox).
|
|
41
|
+
*/
|
|
42
|
+
declare function openApiMcpServer(options: OpenApiMcpServerOptions): McpServer;
|
|
43
|
+
//#endregion
|
|
44
|
+
export {
|
|
45
|
+
CodeMcpServerOptions,
|
|
46
|
+
OpenApiMcpServerOptions,
|
|
47
|
+
RequestOptions,
|
|
48
|
+
codeMcpServer,
|
|
49
|
+
openApiMcpServer
|
|
50
|
+
};
|
|
51
|
+
//# sourceMappingURL=mcp.d.ts.map
|
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { a as sanitizeToolName, t as generateTypesFromJsonSchema } from "./json-schema-types-DoQ0VISs.js";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
4
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
5
|
+
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
|
6
|
+
//#region src/mcp.ts
|
|
7
|
+
const CHARS_PER_TOKEN = 4;
|
|
8
|
+
const MAX_TOKENS = 6e3;
|
|
9
|
+
const MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;
|
|
10
|
+
function truncateResponse(content) {
|
|
11
|
+
const text = typeof content === "string" ? content : JSON.stringify(content, null, 2) ?? "undefined";
|
|
12
|
+
if (text.length <= MAX_CHARS) return text;
|
|
13
|
+
return `${text.slice(0, MAX_CHARS)}\n\n--- TRUNCATED ---\nResponse was ~${Math.ceil(text.length / CHARS_PER_TOKEN).toLocaleString()} tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.`;
|
|
14
|
+
}
|
|
15
|
+
function formatError(error) {
|
|
16
|
+
return error instanceof Error ? error.message : String(error);
|
|
17
|
+
}
|
|
18
|
+
const CODE_DESCRIPTION = `Execute code to achieve a goal.
|
|
19
|
+
|
|
20
|
+
Available:
|
|
21
|
+
{{types}}
|
|
22
|
+
|
|
23
|
+
Write an async arrow function in JavaScript that returns the result.
|
|
24
|
+
Do NOT use TypeScript syntax — no type annotations, interfaces, or generics.
|
|
25
|
+
Do NOT define named functions then call them — just write the arrow function body directly.
|
|
26
|
+
|
|
27
|
+
{{example}}`;
|
|
28
|
+
async function codeMcpServer(options) {
|
|
29
|
+
const { server, executor } = options;
|
|
30
|
+
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
|
31
|
+
await server.connect(serverTransport);
|
|
32
|
+
const client = new Client({
|
|
33
|
+
name: "codemode-proxy",
|
|
34
|
+
version: "1.0.0"
|
|
35
|
+
});
|
|
36
|
+
await client.connect(clientTransport);
|
|
37
|
+
const { tools } = await client.listTools();
|
|
38
|
+
const toolDescriptors = {};
|
|
39
|
+
for (const tool of tools) toolDescriptors[tool.name] = {
|
|
40
|
+
description: tool.description,
|
|
41
|
+
inputSchema: tool.inputSchema
|
|
42
|
+
};
|
|
43
|
+
const types = generateTypesFromJsonSchema(toolDescriptors);
|
|
44
|
+
const fns = {};
|
|
45
|
+
for (const tool of tools) {
|
|
46
|
+
const toolName = tool.name;
|
|
47
|
+
fns[toolName] = async (args) => {
|
|
48
|
+
return await client.callTool({
|
|
49
|
+
name: toolName,
|
|
50
|
+
arguments: args
|
|
51
|
+
});
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
const firstTool = tools[0];
|
|
55
|
+
let example = "";
|
|
56
|
+
if (firstTool) {
|
|
57
|
+
const props = firstTool.inputSchema.properties ?? {};
|
|
58
|
+
const parts = [];
|
|
59
|
+
for (const [key, prop] of Object.entries(props)) if (prop.type === "number" || prop.type === "integer") parts.push(`${key}: 0`);
|
|
60
|
+
else if (prop.type === "boolean") parts.push(`${key}: true`);
|
|
61
|
+
else parts.push(`${key}: "..."`);
|
|
62
|
+
const args = parts.length > 0 ? `{ ${parts.join(", ")} }` : "{}";
|
|
63
|
+
example = `Example: async () => { const r = await codemode.${sanitizeToolName(firstTool.name)}(${args}); return r; }`;
|
|
64
|
+
}
|
|
65
|
+
const description = CODE_DESCRIPTION.replace("{{types}}", types).replace("{{example}}", example);
|
|
66
|
+
const codemodeServer = new McpServer({
|
|
67
|
+
name: "codemode",
|
|
68
|
+
version: "1.0.0"
|
|
69
|
+
});
|
|
70
|
+
codemodeServer.registerTool("code", {
|
|
71
|
+
description,
|
|
72
|
+
inputSchema: { code: z.string().describe("JavaScript async arrow function to execute") }
|
|
73
|
+
}, async ({ code }) => {
|
|
74
|
+
try {
|
|
75
|
+
const result = await executor.execute(code, fns);
|
|
76
|
+
if (result.error) return {
|
|
77
|
+
content: [{
|
|
78
|
+
type: "text",
|
|
79
|
+
text: `Error: ${result.error}`
|
|
80
|
+
}],
|
|
81
|
+
isError: true
|
|
82
|
+
};
|
|
83
|
+
return { content: [{
|
|
84
|
+
type: "text",
|
|
85
|
+
text: truncateResponse(result.result)
|
|
86
|
+
}] };
|
|
87
|
+
} catch (error) {
|
|
88
|
+
return {
|
|
89
|
+
content: [{
|
|
90
|
+
type: "text",
|
|
91
|
+
text: `Error: ${formatError(error)}`
|
|
92
|
+
}],
|
|
93
|
+
isError: true
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
return codemodeServer;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Resolve internal $ref pointers in a JSON object against the root document.
|
|
101
|
+
* Only handles `#/` internal refs. External file refs are left as-is.
|
|
102
|
+
*/
|
|
103
|
+
function resolveRefs(obj, root, seen = /* @__PURE__ */ new Set()) {
|
|
104
|
+
if (obj === null || obj === void 0) return obj;
|
|
105
|
+
if (typeof obj !== "object") return obj;
|
|
106
|
+
if (Array.isArray(obj)) return obj.map((item) => resolveRefs(item, root, seen));
|
|
107
|
+
const record = obj;
|
|
108
|
+
if ("$ref" in record && typeof record.$ref === "string") {
|
|
109
|
+
const ref = record.$ref;
|
|
110
|
+
if (seen.has(ref)) return { $circular: ref };
|
|
111
|
+
if (!ref.startsWith("#/")) return record;
|
|
112
|
+
seen.add(ref);
|
|
113
|
+
const parts = ref.slice(2).split("/").map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
|
|
114
|
+
let resolved = root;
|
|
115
|
+
for (const part of parts) resolved = resolved?.[part];
|
|
116
|
+
const result = resolveRefs(resolved, root, seen);
|
|
117
|
+
seen.delete(ref);
|
|
118
|
+
return result;
|
|
119
|
+
}
|
|
120
|
+
const result = {};
|
|
121
|
+
for (const [key, value] of Object.entries(record)) result[key] = resolveRefs(value, root, seen);
|
|
122
|
+
return result;
|
|
123
|
+
}
|
|
124
|
+
const SPEC_TYPES = `
|
|
125
|
+
// OpenAPI 3.x spec with $refs resolved inline.
|
|
126
|
+
// The spec object follows the standard OpenAPI 3.x structure.
|
|
127
|
+
|
|
128
|
+
interface OperationObject {
|
|
129
|
+
summary?: string;
|
|
130
|
+
description?: string;
|
|
131
|
+
operationId?: string;
|
|
132
|
+
tags?: string[];
|
|
133
|
+
parameters?: Array<{
|
|
134
|
+
name: string;
|
|
135
|
+
in: "query" | "header" | "path" | "cookie";
|
|
136
|
+
required?: boolean;
|
|
137
|
+
schema?: unknown;
|
|
138
|
+
description?: string;
|
|
139
|
+
}>;
|
|
140
|
+
requestBody?: {
|
|
141
|
+
required?: boolean;
|
|
142
|
+
description?: string;
|
|
143
|
+
content?: Record<string, { schema?: unknown }>;
|
|
144
|
+
};
|
|
145
|
+
responses?: Record<string, {
|
|
146
|
+
description?: string;
|
|
147
|
+
content?: Record<string, { schema?: unknown }>;
|
|
148
|
+
}>;
|
|
149
|
+
security?: Array<Record<string, string[]>>;
|
|
150
|
+
deprecated?: boolean;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
interface PathItem {
|
|
154
|
+
summary?: string;
|
|
155
|
+
description?: string;
|
|
156
|
+
get?: OperationObject;
|
|
157
|
+
post?: OperationObject;
|
|
158
|
+
put?: OperationObject;
|
|
159
|
+
patch?: OperationObject;
|
|
160
|
+
delete?: OperationObject;
|
|
161
|
+
head?: OperationObject;
|
|
162
|
+
options?: OperationObject;
|
|
163
|
+
trace?: OperationObject;
|
|
164
|
+
parameters?: OperationObject["parameters"];
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
interface OpenApiSpec {
|
|
168
|
+
openapi: string;
|
|
169
|
+
info: { title: string; version: string; description?: string };
|
|
170
|
+
paths: Record<string, PathItem>;
|
|
171
|
+
servers?: Array<{ url: string; description?: string }>;
|
|
172
|
+
components?: Record<string, unknown>;
|
|
173
|
+
tags?: Array<{ name: string; description?: string }>;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
declare const codemode: {
|
|
177
|
+
spec(): Promise<OpenApiSpec>;
|
|
178
|
+
};
|
|
179
|
+
`;
|
|
180
|
+
const REQUEST_TYPES = `
|
|
181
|
+
interface RequestOptions {
|
|
182
|
+
method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
183
|
+
path: string;
|
|
184
|
+
query?: Record<string, string | number | boolean | undefined>;
|
|
185
|
+
body?: unknown;
|
|
186
|
+
contentType?: string;
|
|
187
|
+
rawBody?: boolean;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
declare const codemode: {
|
|
191
|
+
request(options: RequestOptions): Promise<unknown>;
|
|
192
|
+
};
|
|
193
|
+
`;
|
|
194
|
+
/**
|
|
195
|
+
* Create an MCP server with search + execute tools from an OpenAPI spec.
|
|
196
|
+
*
|
|
197
|
+
* The search tool lets the LLM query the spec to find endpoints.
|
|
198
|
+
* The execute tool lets the LLM call the API via a user-provided
|
|
199
|
+
* request function that runs on the host (auth never enters the sandbox).
|
|
200
|
+
*/
|
|
201
|
+
function openApiMcpServer(options) {
|
|
202
|
+
const { executor, request: requestFn, name = "openapi", version = "1.0.0", description } = options;
|
|
203
|
+
const resolved = resolveRefs(options.spec, options.spec);
|
|
204
|
+
const server = new McpServer({
|
|
205
|
+
name,
|
|
206
|
+
version
|
|
207
|
+
});
|
|
208
|
+
server.registerTool("search", {
|
|
209
|
+
description: `Search the OpenAPI spec. All $refs are pre-resolved inline.
|
|
210
|
+
|
|
211
|
+
Types:
|
|
212
|
+
${SPEC_TYPES}
|
|
213
|
+
|
|
214
|
+
Your code must be an async arrow function that returns the result.
|
|
215
|
+
|
|
216
|
+
Examples:
|
|
217
|
+
|
|
218
|
+
// List all paths
|
|
219
|
+
async () => {
|
|
220
|
+
const spec = await codemode.spec();
|
|
221
|
+
return Object.keys(spec.paths);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Find endpoints by tag
|
|
225
|
+
async () => {
|
|
226
|
+
const spec = await codemode.spec();
|
|
227
|
+
const results = [];
|
|
228
|
+
for (const [path, methods] of Object.entries(spec.paths)) {
|
|
229
|
+
for (const [method, op] of Object.entries(methods)) {
|
|
230
|
+
if (op.tags?.some(t => t.toLowerCase() === 'your_tag')) {
|
|
231
|
+
results.push({ method: method.toUpperCase(), path, summary: op.summary });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return results;
|
|
236
|
+
}`,
|
|
237
|
+
inputSchema: { code: z.string().describe("JavaScript async arrow function to search the spec") }
|
|
238
|
+
}, async ({ code }) => {
|
|
239
|
+
try {
|
|
240
|
+
const result = await executor.execute(code, { spec: async () => resolved });
|
|
241
|
+
if (result.error) return {
|
|
242
|
+
content: [{
|
|
243
|
+
type: "text",
|
|
244
|
+
text: `Error: ${result.error}`
|
|
245
|
+
}],
|
|
246
|
+
isError: true
|
|
247
|
+
};
|
|
248
|
+
return { content: [{
|
|
249
|
+
type: "text",
|
|
250
|
+
text: truncateResponse(result.result)
|
|
251
|
+
}] };
|
|
252
|
+
} catch (error) {
|
|
253
|
+
return {
|
|
254
|
+
content: [{
|
|
255
|
+
type: "text",
|
|
256
|
+
text: `Error: ${formatError(error)}`
|
|
257
|
+
}],
|
|
258
|
+
isError: true
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
});
|
|
262
|
+
const executeDescription = `Execute API calls using JavaScript code. First use 'search' to find the right endpoints.
|
|
263
|
+
|
|
264
|
+
Available in your code:
|
|
265
|
+
${REQUEST_TYPES}
|
|
266
|
+
|
|
267
|
+
Your code must be an async arrow function that returns the result.
|
|
268
|
+
|
|
269
|
+
Example:
|
|
270
|
+
async () => {
|
|
271
|
+
return await codemode.request({ method: "GET", path: "/your/endpoint" });
|
|
272
|
+
}${description ? `\n\n${description}` : ""}`;
|
|
273
|
+
server.registerTool("execute", {
|
|
274
|
+
description: executeDescription,
|
|
275
|
+
inputSchema: { code: z.string().describe("JavaScript async arrow function to execute") }
|
|
276
|
+
}, async ({ code }) => {
|
|
277
|
+
try {
|
|
278
|
+
const result = await executor.execute(code, { request: (args) => requestFn(args) });
|
|
279
|
+
if (result.error) return {
|
|
280
|
+
content: [{
|
|
281
|
+
type: "text",
|
|
282
|
+
text: `Error: ${result.error}`
|
|
283
|
+
}],
|
|
284
|
+
isError: true
|
|
285
|
+
};
|
|
286
|
+
return { content: [{
|
|
287
|
+
type: "text",
|
|
288
|
+
text: truncateResponse(result.result)
|
|
289
|
+
}] };
|
|
290
|
+
} catch (error) {
|
|
291
|
+
return {
|
|
292
|
+
content: [{
|
|
293
|
+
type: "text",
|
|
294
|
+
text: `Error: ${formatError(error)}`
|
|
295
|
+
}],
|
|
296
|
+
isError: true
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
return server;
|
|
301
|
+
}
|
|
302
|
+
//#endregion
|
|
303
|
+
export { codeMcpServer, openApiMcpServer };
|
|
304
|
+
|
|
305
|
+
//# sourceMappingURL=mcp.js.map
|
package/dist/mcp.js.map
ADDED
|
@@ -0,0 +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\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\nexport async function codeMcpServer(\n options: CodeMcpServerOptions\n): Promise<McpServer> {\n const { server, executor } = 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 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 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 description = CODE_DESCRIPTION.replace(\"{{types}}\", types).replace(\n \"{{example}}\",\n example\n );\n\n const codemodeServer = new McpServer({\n name: \"codemode\",\n version: \"1.0.0\"\n });\n\n codemodeServer.registerTool(\n \"code\",\n {\n description,\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, fns);\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 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 request: (args: unknown) => requestFn(args as RequestOptions)\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,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;;AAK/D,MAAM,mBAAmB;;;;;;;;;;AAuBzB,eAAsB,cACpB,SACoB;CACpB,MAAM,EAAE,QAAQ,aAAa;CAC7B,MAAM,CAAC,iBAAiB,mBACtB,kBAAkB,kBAAkB;AAEtC,OAAM,OAAO,QAAQ,gBAAgB;CAErC,MAAM,SAAS,IAAI,OAAO;EAAE,MAAM;EAAkB,SAAS;EAAS,CAAC;AACvE,OAAM,OAAO,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S;IACV;AAEH,UAAO,EACL,SAAS,CACP;IAAE,MAAM;IAAiB,MAAM,iBAAiB,OAAO,OAAO;IAAE,CACjE,EACF;WACM,OAAO;AACd,UAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,YAAY,MAAM;KAAI,CAChE;IACD,SAAS;IACV;;GAGN;AAED,QAAO"}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import * as acorn from "acorn";
|
|
2
|
+
//#region src/normalize.ts
|
|
3
|
+
/**
|
|
4
|
+
* Strip markdown code fences that LLMs commonly wrap code in.
|
|
5
|
+
* Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.
|
|
6
|
+
*/
|
|
7
|
+
function stripCodeFences(code) {
|
|
8
|
+
const match = code.match(/^```(?:js|javascript|typescript|ts|tsx|jsx)?\s*\n([\s\S]*?)```\s*$/);
|
|
9
|
+
return match ? match[1] : code;
|
|
10
|
+
}
|
|
11
|
+
function normalizeCode(code) {
|
|
12
|
+
const trimmed = stripCodeFences(code.trim());
|
|
13
|
+
if (!trimmed.trim()) return "async () => {}";
|
|
14
|
+
const source = trimmed.trim();
|
|
15
|
+
try {
|
|
16
|
+
const ast = acorn.parse(source, {
|
|
17
|
+
ecmaVersion: "latest",
|
|
18
|
+
sourceType: "module"
|
|
19
|
+
});
|
|
20
|
+
if (ast.body.length === 1 && ast.body[0].type === "ExpressionStatement") {
|
|
21
|
+
if (ast.body[0].expression.type === "ArrowFunctionExpression") return source;
|
|
22
|
+
}
|
|
23
|
+
if (ast.body.length === 1 && ast.body[0].type === "ExportDefaultDeclaration") {
|
|
24
|
+
const decl = ast.body[0].declaration;
|
|
25
|
+
const inner = source.slice(decl.start, decl.end);
|
|
26
|
+
if (decl.type === "FunctionDeclaration" && !decl.id) return `async () => {\nreturn (${inner})();\n}`;
|
|
27
|
+
if (decl.type === "ClassDeclaration" && !decl.id) return `async () => {\nreturn (${inner});\n}`;
|
|
28
|
+
return normalizeCode(inner);
|
|
29
|
+
}
|
|
30
|
+
if (ast.body.length === 1 && ast.body[0].type === "FunctionDeclaration") return `async () => {\n${source}\nreturn ${ast.body[0].id?.name ?? "fn"}();\n}`;
|
|
31
|
+
const last = ast.body[ast.body.length - 1];
|
|
32
|
+
if (last?.type === "ExpressionStatement") {
|
|
33
|
+
const exprStmt = last;
|
|
34
|
+
return `async () => {\n${source.slice(0, last.start)}return (${source.slice(exprStmt.expression.start, exprStmt.expression.end)})\n}`;
|
|
35
|
+
}
|
|
36
|
+
return `async () => {\n${source}\n}`;
|
|
37
|
+
} catch {
|
|
38
|
+
return `async () => {\n${source}\n}`;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
//#endregion
|
|
42
|
+
export { normalizeCode as t };
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=normalize-DnrE6oKV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"normalize-DnrE6oKV.js","names":[],"sources":["../src/normalize.ts"],"sourcesContent":["import * as acorn from \"acorn\";\n\n/**\n * Strip markdown code fences that LLMs commonly wrap code in.\n * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.\n */\nfunction stripCodeFences(code: string): string {\n const fenced =\n /^```(?:js|javascript|typescript|ts|tsx|jsx)?\\s*\\n([\\s\\S]*?)```\\s*$/;\n const match = code.match(fenced);\n return match ? match[1] : code;\n}\n\nexport function normalizeCode(code: string): string {\n const trimmed = stripCodeFences(code.trim());\n if (!trimmed.trim()) return \"async () => {}\";\n\n const source = trimmed.trim();\n\n try {\n const ast = acorn.parse(source, {\n ecmaVersion: \"latest\",\n sourceType: \"module\"\n });\n\n // Already an arrow function — pass through\n if (ast.body.length === 1 && ast.body[0].type === \"ExpressionStatement\") {\n const expr = (ast.body[0] as acorn.ExpressionStatement).expression;\n if (expr.type === \"ArrowFunctionExpression\") return source;\n }\n\n // export default <expression> → unwrap to just the expression\n if (\n ast.body.length === 1 &&\n ast.body[0].type === \"ExportDefaultDeclaration\"\n ) {\n const decl = (ast.body[0] as acorn.ExportDefaultDeclaration).declaration;\n const inner = source.slice(decl.start, decl.end);\n\n // Anonymous function/class declarations aren't valid as standalone\n // statements — wrap them as expressions directly.\n if (\n decl.type === \"FunctionDeclaration\" &&\n !(decl as acorn.FunctionDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner})();\\n}`;\n }\n if (\n decl.type === \"ClassDeclaration\" &&\n !(decl as acorn.ClassDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner});\\n}`;\n }\n\n return normalizeCode(inner);\n }\n\n // Single named function declaration → wrap and call it\n if (ast.body.length === 1 && ast.body[0].type === \"FunctionDeclaration\") {\n const fn = ast.body[0] as acorn.FunctionDeclaration;\n const name = fn.id?.name ?? \"fn\";\n return `async () => {\\n${source}\\nreturn ${name}();\\n}`;\n }\n\n // Last statement is expression → splice in return\n const last = ast.body[ast.body.length - 1];\n if (last?.type === \"ExpressionStatement\") {\n const exprStmt = last as acorn.ExpressionStatement;\n const before = source.slice(0, last.start);\n const exprText = source.slice(\n exprStmt.expression.start,\n exprStmt.expression.end\n );\n return `async () => {\\n${before}return (${exprText})\\n}`;\n }\n\n return `async () => {\\n${source}\\n}`;\n } catch {\n return `async () => {\\n${source}\\n}`;\n }\n}\n"],"mappings":";;;;;;AAMA,SAAS,gBAAgB,MAAsB;CAG7C,MAAM,QAAQ,KAAK,MADjB,qEAC8B;AAChC,QAAO,QAAQ,MAAM,KAAK;;AAG5B,SAAgB,cAAc,MAAsB;CAClD,MAAM,UAAU,gBAAgB,KAAK,MAAM,CAAC;AAC5C,KAAI,CAAC,QAAQ,MAAM,CAAE,QAAO;CAE5B,MAAM,SAAS,QAAQ,MAAM;AAE7B,KAAI;EACF,MAAM,MAAM,MAAM,MAAM,QAAQ;GAC9B,aAAa;GACb,YAAY;GACb,CAAC;AAGF,MAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS;OAClC,IAAI,KAAK,GAAiC,WAC/C,SAAS,0BAA2B,QAAO;;AAItD,MACE,IAAI,KAAK,WAAW,KACpB,IAAI,KAAK,GAAG,SAAS,4BACrB;GACA,MAAM,OAAQ,IAAI,KAAK,GAAsC;GAC7D,MAAM,QAAQ,OAAO,MAAM,KAAK,OAAO,KAAK,IAAI;AAIhD,OACE,KAAK,SAAS,yBACd,CAAE,KAAmC,GAErC,QAAO,0BAA0B,MAAM;AAEzC,OACE,KAAK,SAAS,sBACd,CAAE,KAAgC,GAElC,QAAO,0BAA0B,MAAM;AAGzC,UAAO,cAAc,MAAM;;AAI7B,MAAI,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,GAAG,SAAS,sBAGhD,QAAO,kBAAkB,OAAO,WAFrB,IAAI,KAAK,GACJ,IAAI,QAAQ,KACoB;EAIlD,MAAM,OAAO,IAAI,KAAK,IAAI,KAAK,SAAS;AACxC,MAAI,MAAM,SAAS,uBAAuB;GACxC,MAAM,WAAW;AAMjB,UAAO,kBALQ,OAAO,MAAM,GAAG,KAAK,MAAM,CAKV,UAJf,OAAO,MACtB,SAAS,WAAW,OACpB,SAAS,WAAW,IACrB,CACkD;;AAGrD,SAAO,kBAAkB,OAAO;SAC1B;AACN,SAAO,kBAAkB,OAAO"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cloudflare/codemode",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Code Mode: use LLMs to generate executable code that performs tool calls",
|
|
5
5
|
"repository": {
|
|
6
6
|
"directory": "packages/codemode",
|
|
@@ -15,16 +15,21 @@
|
|
|
15
15
|
"acorn": "^8.16.0"
|
|
16
16
|
},
|
|
17
17
|
"devDependencies": {
|
|
18
|
+
"@modelcontextprotocol/sdk": "1.26.0",
|
|
18
19
|
"@playwright/test": "^1.58.2",
|
|
19
20
|
"ai": "^6.0.116",
|
|
20
21
|
"vitest": "3.2.4",
|
|
21
22
|
"zod": "^4.3.6"
|
|
22
23
|
},
|
|
23
24
|
"peerDependencies": {
|
|
25
|
+
"@modelcontextprotocol/sdk": "^1.25.0",
|
|
24
26
|
"ai": "^6.0.0",
|
|
25
27
|
"zod": "^3.25.0 || ^4.0.0"
|
|
26
28
|
},
|
|
27
29
|
"peerDependenciesMeta": {
|
|
30
|
+
"@modelcontextprotocol/sdk": {
|
|
31
|
+
"optional": true
|
|
32
|
+
},
|
|
28
33
|
"ai": {
|
|
29
34
|
"optional": true
|
|
30
35
|
},
|
|
@@ -43,6 +48,11 @@
|
|
|
43
48
|
"types": "./dist/ai.d.ts",
|
|
44
49
|
"import": "./dist/ai.js",
|
|
45
50
|
"require": "./dist/ai.js"
|
|
51
|
+
},
|
|
52
|
+
"./mcp": {
|
|
53
|
+
"types": "./dist/mcp.d.ts",
|
|
54
|
+
"import": "./dist/mcp.js",
|
|
55
|
+
"require": "./dist/mcp.js"
|
|
46
56
|
}
|
|
47
57
|
},
|
|
48
58
|
"scripts": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"normalize-xNh5CsfI.js","names":[],"sources":["../src/utils.ts","../src/json-schema-types.ts","../src/normalize.ts"],"sourcesContent":["const JS_RESERVED = new Set([\n \"abstract\",\n \"arguments\",\n \"await\",\n \"boolean\",\n \"break\",\n \"byte\",\n \"case\",\n \"catch\",\n \"char\",\n \"class\",\n \"const\",\n \"continue\",\n \"debugger\",\n \"default\",\n \"delete\",\n \"do\",\n \"double\",\n \"else\",\n \"enum\",\n \"eval\",\n \"export\",\n \"extends\",\n \"false\",\n \"final\",\n \"finally\",\n \"float\",\n \"for\",\n \"function\",\n \"goto\",\n \"if\",\n \"implements\",\n \"import\",\n \"in\",\n \"instanceof\",\n \"int\",\n \"interface\",\n \"let\",\n \"long\",\n \"native\",\n \"new\",\n \"null\",\n \"package\",\n \"private\",\n \"protected\",\n \"public\",\n \"return\",\n \"short\",\n \"static\",\n \"super\",\n \"switch\",\n \"synchronized\",\n \"this\",\n \"throw\",\n \"throws\",\n \"transient\",\n \"true\",\n \"try\",\n \"typeof\",\n \"undefined\",\n \"var\",\n \"void\",\n \"volatile\",\n \"while\",\n \"with\",\n \"yield\"\n]);\n\n/**\n * Sanitize a tool name into a valid JavaScript identifier.\n * Replaces hyphens, dots, and spaces with `_`, strips other invalid chars,\n * prefixes digit-leading names with `_`, and appends `_` to JS reserved words.\n */\nexport function sanitizeToolName(name: string): string {\n if (!name) return \"_\";\n\n // Replace common separators with underscores\n let sanitized = name.replace(/[-.\\s]/g, \"_\");\n\n // Strip any remaining non-identifier characters\n sanitized = sanitized.replace(/[^a-zA-Z0-9_$]/g, \"\");\n\n if (!sanitized) return \"_\";\n\n // Prefix with _ if starts with a digit\n if (/^[0-9]/.test(sanitized)) {\n sanitized = \"_\" + sanitized;\n }\n\n // Append _ to reserved words\n if (JS_RESERVED.has(sanitized)) {\n sanitized = sanitized + \"_\";\n }\n\n return sanitized;\n}\n\nexport function toPascalCase(str: string) {\n return str\n .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n .replace(/^[a-z]/, (letter) => letter.toUpperCase());\n}\n\n/**\n * Escape a character as a unicode escape sequence if it is a control character.\n */\nfunction escapeControlChar(ch: string): string {\n const code = ch.charCodeAt(0);\n if (code <= 0x1f || code === 0x7f) {\n return \"\\\\u\" + code.toString(16).padStart(4, \"0\");\n }\n return ch;\n}\n\n/**\n * Quote a property name if needed.\n * Escapes backslashes, quotes, and control characters.\n */\nexport function quoteProp(name: string): string {\n if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name)) {\n let escaped = \"\";\n for (const ch of name) {\n if (ch === \"\\\\\") escaped += \"\\\\\\\\\";\n else if (ch === '\"') escaped += '\\\\\"';\n else if (ch === \"\\n\") escaped += \"\\\\n\";\n else if (ch === \"\\r\") escaped += \"\\\\r\";\n else if (ch === \"\\t\") escaped += \"\\\\t\";\n else if (ch === \"\\u2028\") escaped += \"\\\\u2028\";\n else if (ch === \"\\u2029\") escaped += \"\\\\u2029\";\n else escaped += escapeControlChar(ch);\n }\n return `\"${escaped}\"`;\n }\n return name;\n}\n\n/**\n * Escape a string for use inside a double-quoted TypeScript string literal.\n */\nexport function escapeStringLiteral(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch === \"\\\\\") out += \"\\\\\\\\\";\n else if (ch === '\"') out += '\\\\\"';\n else if (ch === \"\\n\") out += \"\\\\n\";\n else if (ch === \"\\r\") out += \"\\\\r\";\n else if (ch === \"\\t\") out += \"\\\\t\";\n else if (ch === \"\\u2028\") out += \"\\\\u2028\";\n else if (ch === \"\\u2029\") out += \"\\\\u2029\";\n else out += escapeControlChar(ch);\n }\n return out;\n}\n\n/**\n * Escape a string for use inside a JSDoc comment.\n * Prevents premature comment closure from star-slash sequences.\n */\nexport function escapeJsDoc(text: string): string {\n return text.replace(/\\*\\//g, \"*\\\\/\");\n}\n","import type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport {\n sanitizeToolName,\n toPascalCase,\n escapeJsDoc,\n escapeStringLiteral,\n quoteProp\n} from \"./utils\";\n\nexport interface ConversionContext {\n root: JSONSchema7;\n depth: number;\n seen: Set<unknown>;\n maxDepth: number;\n}\n\n/**\n * Resolve an internal JSON Pointer $ref (e.g. #/definitions/Foo) against the root schema.\n * Returns null for external URLs or unresolvable paths.\n */\nfunction resolveRef(\n ref: string,\n root: JSONSchema7\n): JSONSchema7Definition | null {\n // \"#\" is a valid self-reference to the root schema\n if (ref === \"#\") return root;\n\n if (!ref.startsWith(\"#/\")) return null;\n\n const segments = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n\n let current: unknown = root;\n for (const seg of segments) {\n if (current === null || typeof current !== \"object\") return null;\n current = (current as Record<string, unknown>)[seg];\n if (current === undefined) return null;\n }\n\n // Allow both object schemas and boolean schemas (true = any, false = never)\n if (typeof current === \"boolean\") return current;\n if (current === null || typeof current !== \"object\") return null;\n return current as JSONSchema7;\n}\n\n/**\n * Apply OpenAPI 3.0 `nullable: true` to a type result.\n */\nfunction applyNullable(result: string, schema: unknown): string {\n if (\n result !== \"unknown\" &&\n result !== \"never\" &&\n (schema as Record<string, unknown>)?.nullable === true\n ) {\n return `${result} | null`;\n }\n return result;\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type string.\n * This is a direct conversion without going through Zod.\n */\nexport function jsonSchemaToTypeString(\n schema: JSONSchema7Definition,\n indent: string,\n ctx: ConversionContext\n): string {\n // Handle boolean schemas\n if (typeof schema === \"boolean\") {\n return schema ? \"unknown\" : \"never\";\n }\n\n // Depth guard\n if (ctx.depth >= ctx.maxDepth) return \"unknown\";\n\n // Circular reference guard\n if (ctx.seen.has(schema)) return \"unknown\";\n\n ctx.seen.add(schema);\n const nextCtx: ConversionContext = {\n ...ctx,\n depth: ctx.depth + 1\n };\n\n try {\n // Handle $ref\n if (schema.$ref) {\n const resolved = resolveRef(schema.$ref, ctx.root);\n if (!resolved) return \"unknown\";\n return applyNullable(\n jsonSchemaToTypeString(resolved, indent, nextCtx),\n schema\n );\n }\n\n // Handle anyOf/oneOf (union types)\n if (schema.anyOf) {\n const types = schema.anyOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n if (schema.oneOf) {\n const types = schema.oneOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" | \"), schema);\n }\n\n // Handle allOf (intersection types)\n if (schema.allOf) {\n const types = schema.allOf.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(types.join(\" & \"), schema);\n }\n\n // Handle enum\n if (schema.enum) {\n if (schema.enum.length === 0) return \"never\";\n const result = schema.enum\n .map((v) => {\n if (v === null) return \"null\";\n if (typeof v === \"string\") return '\"' + escapeStringLiteral(v) + '\"';\n if (typeof v === \"object\") return JSON.stringify(v) ?? \"unknown\";\n return String(v);\n })\n .join(\" | \");\n return applyNullable(result, schema);\n }\n\n // Handle const\n if (schema.const !== undefined) {\n const result =\n schema.const === null\n ? \"null\"\n : typeof schema.const === \"string\"\n ? '\"' + escapeStringLiteral(schema.const) + '\"'\n : typeof schema.const === \"object\"\n ? (JSON.stringify(schema.const) ?? \"unknown\")\n : String(schema.const);\n return applyNullable(result, schema);\n }\n\n // Handle type\n const type = schema.type;\n\n if (type === \"string\") return applyNullable(\"string\", schema);\n if (type === \"number\" || type === \"integer\")\n return applyNullable(\"number\", schema);\n if (type === \"boolean\") return applyNullable(\"boolean\", schema);\n if (type === \"null\") return \"null\";\n\n if (type === \"array\") {\n // Tuple support: prefixItems (JSON Schema 2020-12)\n const prefixItems = (schema as Record<string, unknown>)\n .prefixItems as JSONSchema7Definition[];\n if (Array.isArray(prefixItems)) {\n const types = prefixItems.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n // Tuple support: items as array (draft-07)\n if (Array.isArray(schema.items)) {\n const types = schema.items.map((s) =>\n jsonSchemaToTypeString(s, indent, nextCtx)\n );\n return applyNullable(`[${types.join(\", \")}]`, schema);\n }\n\n if (schema.items) {\n const itemType = jsonSchemaToTypeString(schema.items, indent, nextCtx);\n return applyNullable(`${itemType}[]`, schema);\n }\n return applyNullable(\"unknown[]\", schema);\n }\n\n if (type === \"object\" || schema.properties) {\n const props = schema.properties || {};\n const required = new Set(schema.required || []);\n const lines: string[] = [];\n\n for (const [propName, propSchema] of Object.entries(props)) {\n if (typeof propSchema === \"boolean\") {\n const boolType = propSchema ? \"unknown\" : \"never\";\n const optionalMark = required.has(propName) ? \"\" : \"?\";\n lines.push(\n `${indent} ${quoteProp(propName)}${optionalMark}: ${boolType};`\n );\n continue;\n }\n\n const isRequired = required.has(propName);\n const propType = jsonSchemaToTypeString(\n propSchema,\n indent + \" \",\n nextCtx\n );\n const desc = propSchema.description;\n const format = propSchema.format;\n\n if (desc || format) {\n const descText = desc\n ? escapeJsDoc(desc.replace(/\\r?\\n/g, \" \"))\n : undefined;\n const formatTag = format\n ? `@format ${escapeJsDoc(format)}`\n : undefined;\n\n if (descText && formatTag) {\n lines.push(`${indent} /**`);\n lines.push(`${indent} * ${descText}`);\n lines.push(`${indent} * ${formatTag}`);\n lines.push(`${indent} */`);\n } else {\n lines.push(`${indent} /** ${descText ?? formatTag} */`);\n }\n }\n\n const quotedName = quoteProp(propName);\n const optionalMark = isRequired ? \"\" : \"?\";\n lines.push(`${indent} ${quotedName}${optionalMark}: ${propType};`);\n }\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n const valueType =\n schema.additionalProperties === true\n ? \"unknown\"\n : jsonSchemaToTypeString(\n schema.additionalProperties,\n indent + \" \",\n nextCtx\n );\n lines.push(`${indent} [key: string]: ${valueType};`);\n }\n\n if (lines.length === 0) {\n if (schema.additionalProperties === false) {\n return applyNullable(\"{}\", schema);\n }\n return applyNullable(\"Record<string, unknown>\", schema);\n }\n\n const result = `{\\n${lines.join(\"\\n\")}\\n${indent}}`;\n return applyNullable(result, schema);\n }\n\n // Handle array of types (e.g., [\"string\", \"null\"])\n if (Array.isArray(type)) {\n const types = type.map((t) => {\n if (t === \"string\") return \"string\";\n if (t === \"number\" || t === \"integer\") return \"number\";\n if (t === \"boolean\") return \"boolean\";\n if (t === \"null\") return \"null\";\n if (t === \"array\") return \"unknown[]\";\n if (t === \"object\") return \"Record<string, unknown>\";\n return \"unknown\";\n });\n return applyNullable(types.join(\" | \"), schema);\n }\n\n return \"unknown\";\n } finally {\n ctx.seen.delete(schema);\n }\n}\n\n/**\n * Convert a JSON Schema to a TypeScript type declaration.\n */\nexport function jsonSchemaToType(\n schema: JSONSchema7,\n typeName: string\n): string {\n const ctx: ConversionContext = {\n root: schema,\n depth: 0,\n seen: new Set(),\n maxDepth: 20\n };\n const typeBody = jsonSchemaToTypeString(schema, \"\", ctx);\n return `type ${typeName} = ${typeBody}`;\n}\n\n/**\n * Extract field descriptions from a JSON Schema's properties.\n */\nfunction extractJsonSchemaDescriptions(\n schema: JSONSchema7\n): Record<string, string> {\n const descriptions: Record<string, string> = {};\n if (schema.properties) {\n for (const [fieldName, propSchema] of Object.entries(schema.properties)) {\n if (\n propSchema &&\n typeof propSchema === \"object\" &&\n propSchema.description\n ) {\n descriptions[fieldName] = propSchema.description;\n }\n }\n }\n return descriptions;\n}\n\n/**\n * A tool descriptor using plain JSON Schema (no Zod or AI SDK dependency).\n */\nexport interface JsonSchemaToolDescriptor {\n description?: string;\n inputSchema: JSONSchema7;\n outputSchema?: JSONSchema7;\n}\n\nexport type JsonSchemaToolDescriptors = Record<\n string,\n JsonSchemaToolDescriptor\n>;\n\n/**\n * Generate TypeScript type definitions from tool descriptors with JSON Schema.\n * This function has NO dependency on the AI SDK or Zod — it works purely with\n * JSON Schema objects.\n *\n * Use this when you have raw JSON Schema (e.g. from OpenAPI specs, MCP tool\n * definitions, etc.) and don't need the AI SDK.\n */\nexport function generateTypesFromJsonSchema(\n tools: JsonSchemaToolDescriptors\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\n try {\n const inputType = jsonSchemaToType(tool.inputSchema, `${typeName}Input`);\n\n const outputType = tool.outputSchema\n ? jsonSchemaToType(tool.outputSchema, `${typeName}Output`)\n : `type ${typeName}Output = unknown`;\n\n availableTypes += `\\n${inputType.trim()}`;\n availableTypes += `\\n${outputType.trim()}`;\n\n const paramLines = (() => {\n try {\n const paramDescs = extractJsonSchemaDescriptions(tool.inputSchema);\n return Object.entries(paramDescs).map(\n ([fieldName, desc]) => `@param input.${fieldName} - ${desc}`\n );\n } catch {\n return [];\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(toolName));\n }\n for (const pd of paramLines) {\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(toolName)}\\n\\t */`;\n availableTools += `\\n\\t${safeName}: (input: ${typeName}Input) => Promise<${typeName}Output>;`;\n availableTools += \"\\n\";\n }\n }\n\n availableTools = `\\ndeclare const codemode: {${availableTools}}`;\n\n return `\n${availableTypes}\n${availableTools}\n `.trim();\n}\n","import * as acorn from \"acorn\";\n\n/**\n * Strip markdown code fences that LLMs commonly wrap code in.\n * Handles ```js, ```javascript, ```typescript, ```ts, or bare ```.\n */\nfunction stripCodeFences(code: string): string {\n const fenced =\n /^```(?:js|javascript|typescript|ts|tsx|jsx)?\\s*\\n([\\s\\S]*?)```\\s*$/;\n const match = code.match(fenced);\n return match ? match[1] : code;\n}\n\nexport function normalizeCode(code: string): string {\n const trimmed = stripCodeFences(code.trim());\n if (!trimmed.trim()) return \"async () => {}\";\n\n const source = trimmed.trim();\n\n try {\n const ast = acorn.parse(source, {\n ecmaVersion: \"latest\",\n sourceType: \"module\"\n });\n\n // Already an arrow function — pass through\n if (ast.body.length === 1 && ast.body[0].type === \"ExpressionStatement\") {\n const expr = (ast.body[0] as acorn.ExpressionStatement).expression;\n if (expr.type === \"ArrowFunctionExpression\") return source;\n }\n\n // export default <expression> → unwrap to just the expression\n if (\n ast.body.length === 1 &&\n ast.body[0].type === \"ExportDefaultDeclaration\"\n ) {\n const decl = (ast.body[0] as acorn.ExportDefaultDeclaration).declaration;\n const inner = source.slice(decl.start, decl.end);\n\n // Anonymous function/class declarations aren't valid as standalone\n // statements — wrap them as expressions directly.\n if (\n decl.type === \"FunctionDeclaration\" &&\n !(decl as acorn.FunctionDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner})();\\n}`;\n }\n if (\n decl.type === \"ClassDeclaration\" &&\n !(decl as acorn.ClassDeclaration).id\n ) {\n return `async () => {\\nreturn (${inner});\\n}`;\n }\n\n return normalizeCode(inner);\n }\n\n // Single named function declaration → wrap and call it\n if (ast.body.length === 1 && ast.body[0].type === \"FunctionDeclaration\") {\n const fn = ast.body[0] as acorn.FunctionDeclaration;\n const name = fn.id?.name ?? \"fn\";\n return `async () => {\\n${source}\\nreturn ${name}();\\n}`;\n }\n\n // Last statement is expression → splice in return\n const last = ast.body[ast.body.length - 1];\n if (last?.type === \"ExpressionStatement\") {\n const exprStmt = last as acorn.ExpressionStatement;\n const before = source.slice(0, last.start);\n const exprText = source.slice(\n exprStmt.expression.start,\n exprStmt.expression.end\n );\n return `async () => {\\n${before}return (${exprText})\\n}`;\n }\n\n return `async () => {\\n${source}\\n}`;\n } catch {\n return `async () => {\\n${source}\\n}`;\n }\n}\n"],"mappings":";;AAAA,MAAM,cAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;AAOF,SAAgB,iBAAiB,MAAsB;AACrD,KAAI,CAAC,KAAM,QAAO;CAGlB,IAAI,YAAY,KAAK,QAAQ,WAAW,IAAI;AAG5C,aAAY,UAAU,QAAQ,mBAAmB,GAAG;AAEpD,KAAI,CAAC,UAAW,QAAO;AAGvB,KAAI,SAA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