@cloudflare/codemode 0.2.1 → 0.3.0
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 +172 -36
- package/dist/ai.d.ts +32 -38
- package/dist/ai.js +63 -37
- package/dist/ai.js.map +1 -1
- package/dist/executor-wZjYdqEX.d.ts +186 -0
- package/dist/index.d.ts +8 -2
- package/dist/index.js +63 -24
- package/dist/index.js.map +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/mcp.js +12 -3
- package/dist/mcp.js.map +1 -1
- package/dist/{normalize-DnrE6oKV.js → resolve-DIQRkRqQ.js} +43 -2
- package/dist/resolve-DIQRkRqQ.js.map +1 -0
- package/dist/resolve-DULSpsq2.d.ts +17 -0
- package/dist/shared-Hnh_Idta.d.ts +41 -0
- package/dist/shared-ra3HW2ti.js +30 -0
- package/dist/shared-ra3HW2ti.js.map +1 -0
- package/dist/tanstack-ai.d.ts +84 -0
- package/dist/tanstack-ai.js +216 -0
- package/dist/tanstack-ai.js.map +1 -0
- package/package.json +14 -4
- package/dist/executor-6RSFUhUk.d.ts +0 -78
- package/dist/normalize-DnrE6oKV.js.map +0 -1
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { RpcTarget } from "cloudflare:workers";
|
|
2
|
+
import { ToolSet } from "ai";
|
|
3
|
+
import { ZodType } from "zod";
|
|
4
|
+
|
|
5
|
+
//#region src/tool-types.d.ts
|
|
6
|
+
interface ToolDescriptor {
|
|
7
|
+
description?: string;
|
|
8
|
+
inputSchema: ZodType;
|
|
9
|
+
outputSchema?: ZodType;
|
|
10
|
+
execute?: (args: unknown) => Promise<unknown>;
|
|
11
|
+
}
|
|
12
|
+
type ToolDescriptors = Record<string, ToolDescriptor>;
|
|
13
|
+
/**
|
|
14
|
+
* Generate TypeScript type definitions from tool descriptors or an AI SDK ToolSet.
|
|
15
|
+
* These types can be included in tool descriptions to help LLMs write correct code.
|
|
16
|
+
*
|
|
17
|
+
* Requires the `ai` peer dependency. For a version that works with plain JSON Schema
|
|
18
|
+
* objects (no AI SDK), use `generateTypesFromJsonSchema` from the main entry point.
|
|
19
|
+
*/
|
|
20
|
+
declare function generateTypes(
|
|
21
|
+
tools: ToolDescriptors | ToolSet,
|
|
22
|
+
namespace?: string
|
|
23
|
+
): string;
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region src/executor.d.ts
|
|
26
|
+
interface ExecuteResult {
|
|
27
|
+
result: unknown;
|
|
28
|
+
error?: string;
|
|
29
|
+
logs?: string[];
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* A minimal tool record — just a description and an execute function.
|
|
33
|
+
* Use this for providers that supply their own `types` and don't need
|
|
34
|
+
* schema-based type generation (e.g. stateTools).
|
|
35
|
+
*/
|
|
36
|
+
type SimpleToolRecord = Record<
|
|
37
|
+
string,
|
|
38
|
+
{
|
|
39
|
+
description?: string;
|
|
40
|
+
execute: (args: unknown) => Promise<unknown>;
|
|
41
|
+
}
|
|
42
|
+
>;
|
|
43
|
+
/**
|
|
44
|
+
* All tool record types accepted by a ToolProvider.
|
|
45
|
+
*/
|
|
46
|
+
type ToolProviderTools = ToolDescriptors | ToolSet | SimpleToolRecord;
|
|
47
|
+
/**
|
|
48
|
+
* A ToolProvider contributes tools to the codemode sandbox under a namespace.
|
|
49
|
+
*
|
|
50
|
+
* Each provider's tools are accessible as `name.toolName()` in sandbox code.
|
|
51
|
+
* If `name` is omitted, tools are exposed under the default `codemode.*` namespace.
|
|
52
|
+
*
|
|
53
|
+
* @example Multiple providers with different namespaces
|
|
54
|
+
* ```ts
|
|
55
|
+
* createCodeTool({
|
|
56
|
+
* tools: [
|
|
57
|
+
* { name: "github", tools: githubTools },
|
|
58
|
+
* { name: "shell", tools: shellTools },
|
|
59
|
+
* { tools: aiTools }, // default "codemode" namespace
|
|
60
|
+
* ],
|
|
61
|
+
* executor,
|
|
62
|
+
* });
|
|
63
|
+
* // sandbox: github.listIssues(), shell.exec(), codemode.search()
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
interface ToolProvider {
|
|
67
|
+
/** Namespace prefix in the sandbox (e.g. "state", "mcp"). Defaults to "codemode". */
|
|
68
|
+
name?: string;
|
|
69
|
+
/** Tools exposed as `namespace.toolName()` in the sandbox. */
|
|
70
|
+
tools: ToolProviderTools;
|
|
71
|
+
/** Type declarations for the LLM. Auto-generated from `tools` if omitted. */
|
|
72
|
+
types?: string;
|
|
73
|
+
/**
|
|
74
|
+
* When true, tools accept positional args instead of a single object arg.
|
|
75
|
+
* The sandbox proxy uses `(...args)` and the dispatcher spreads the args array.
|
|
76
|
+
*
|
|
77
|
+
* Default tools use single-object args: `codemode.search({ query: "test" })`
|
|
78
|
+
* Positional tools use normal args: `state.readFile("/path")`
|
|
79
|
+
*/
|
|
80
|
+
positionalArgs?: boolean;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Internal resolved form of a ToolProvider, ready for execution.
|
|
84
|
+
* The tool functions have been extracted and keyed by sanitized name.
|
|
85
|
+
*/
|
|
86
|
+
interface ResolvedProvider {
|
|
87
|
+
name: string;
|
|
88
|
+
fns: Record<string, (...args: unknown[]) => Promise<unknown>>;
|
|
89
|
+
positionalArgs?: boolean;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* An executor runs LLM-generated code in a sandbox, making the provided
|
|
93
|
+
* tool functions callable under their namespace inside the sandbox.
|
|
94
|
+
*
|
|
95
|
+
* Implementations should never throw — errors are returned in `ExecuteResult.error`.
|
|
96
|
+
*
|
|
97
|
+
* @param code - The code to execute in the sandbox.
|
|
98
|
+
* @param providersOrFns - An array of `ResolvedProvider` (preferred), or a
|
|
99
|
+
* plain `Record<string, fn>` for backwards compatibility (deprecated — will
|
|
100
|
+
* be removed in the next major version).
|
|
101
|
+
*/
|
|
102
|
+
interface Executor {
|
|
103
|
+
execute(
|
|
104
|
+
code: string,
|
|
105
|
+
providersOrFns:
|
|
106
|
+
| ResolvedProvider[]
|
|
107
|
+
| Record<string, (...args: unknown[]) => Promise<unknown>>
|
|
108
|
+
): Promise<ExecuteResult>;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* An RpcTarget that dispatches tool calls from the sandboxed Worker
|
|
112
|
+
* back to the host. Passed via Workers RPC to the dynamic Worker's
|
|
113
|
+
* evaluate() method — no globalOutbound or Fetcher bindings needed.
|
|
114
|
+
*/
|
|
115
|
+
declare class ToolDispatcher extends RpcTarget {
|
|
116
|
+
#private;
|
|
117
|
+
constructor(
|
|
118
|
+
fns: Record<string, (...args: unknown[]) => Promise<unknown>>,
|
|
119
|
+
positionalArgs?: boolean
|
|
120
|
+
);
|
|
121
|
+
call(name: string, argsJson: string): Promise<string>;
|
|
122
|
+
}
|
|
123
|
+
interface DynamicWorkerExecutorOptions {
|
|
124
|
+
loader: WorkerLoader;
|
|
125
|
+
/**
|
|
126
|
+
* Timeout in milliseconds for code execution. Defaults to 30000 (30s).
|
|
127
|
+
*/
|
|
128
|
+
timeout?: number;
|
|
129
|
+
/**
|
|
130
|
+
* Controls outbound network access from sandboxed code.
|
|
131
|
+
* - `null` (default): fetch() and connect() throw — sandbox is fully isolated.
|
|
132
|
+
* - `undefined`: inherits parent Worker's network access (full internet).
|
|
133
|
+
* - A `Fetcher`: all outbound requests route through this handler.
|
|
134
|
+
*/
|
|
135
|
+
globalOutbound?: Fetcher | null;
|
|
136
|
+
/**
|
|
137
|
+
* Additional modules to make available in the sandbox.
|
|
138
|
+
* Keys are module specifiers (e.g. `"mylib.js"`), values are module source code.
|
|
139
|
+
*
|
|
140
|
+
* Note: the key `"executor.js"` is reserved and will be ignored if provided.
|
|
141
|
+
*/
|
|
142
|
+
modules?: Record<string, string>;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Executes code in an isolated Cloudflare Worker via WorkerLoader.
|
|
146
|
+
* Tool calls are dispatched via Workers RPC — the host passes
|
|
147
|
+
* ToolDispatchers (one per namespace) to the Worker's evaluate() method.
|
|
148
|
+
*
|
|
149
|
+
* External fetch() and connect() are blocked by default via
|
|
150
|
+
* `globalOutbound: null` (runtime-enforced). Pass a Fetcher to
|
|
151
|
+
* `globalOutbound` to allow controlled outbound access.
|
|
152
|
+
*
|
|
153
|
+
* @example
|
|
154
|
+
* ```ts
|
|
155
|
+
* const result = await executor.execute(code, [
|
|
156
|
+
* { name: "codemode", fns: { search: searchFn } },
|
|
157
|
+
* { name: "state", fns: { readFile: readFileFn } },
|
|
158
|
+
* ]);
|
|
159
|
+
* // sandbox has both codemode.search() and state.readFile()
|
|
160
|
+
* ```
|
|
161
|
+
*/
|
|
162
|
+
declare class DynamicWorkerExecutor implements Executor {
|
|
163
|
+
#private;
|
|
164
|
+
constructor(options: DynamicWorkerExecutorOptions);
|
|
165
|
+
execute(
|
|
166
|
+
code: string,
|
|
167
|
+
providersOrFns:
|
|
168
|
+
| ResolvedProvider[]
|
|
169
|
+
| Record<string, (...args: unknown[]) => Promise<unknown>>
|
|
170
|
+
): Promise<ExecuteResult>;
|
|
171
|
+
}
|
|
172
|
+
//#endregion
|
|
173
|
+
export {
|
|
174
|
+
ResolvedProvider as a,
|
|
175
|
+
ToolProviderTools as c,
|
|
176
|
+
generateTypes as d,
|
|
177
|
+
Executor as i,
|
|
178
|
+
ToolDescriptor as l,
|
|
179
|
+
DynamicWorkerExecutorOptions as n,
|
|
180
|
+
ToolDispatcher as o,
|
|
181
|
+
ExecuteResult as r,
|
|
182
|
+
ToolProvider as s,
|
|
183
|
+
DynamicWorkerExecutor as t,
|
|
184
|
+
ToolDescriptors as u
|
|
185
|
+
};
|
|
186
|
+
//# sourceMappingURL=executor-wZjYdqEX.d.ts.map
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,13 @@
|
|
|
1
1
|
import {
|
|
2
|
-
a as
|
|
2
|
+
a as ResolvedProvider,
|
|
3
3
|
i as Executor,
|
|
4
4
|
n as DynamicWorkerExecutorOptions,
|
|
5
|
+
o as ToolDispatcher,
|
|
5
6
|
r as ExecuteResult,
|
|
7
|
+
s as ToolProvider,
|
|
6
8
|
t as DynamicWorkerExecutor
|
|
7
|
-
} from "./executor-
|
|
9
|
+
} from "./executor-wZjYdqEX.js";
|
|
10
|
+
import { t as resolveProvider } from "./resolve-DULSpsq2.js";
|
|
8
11
|
import { JSONSchema7 } from "json-schema";
|
|
9
12
|
|
|
10
13
|
//#region src/utils.d.ts
|
|
@@ -54,10 +57,13 @@ export {
|
|
|
54
57
|
type Executor,
|
|
55
58
|
type JsonSchemaToolDescriptor,
|
|
56
59
|
type JsonSchemaToolDescriptors,
|
|
60
|
+
type ResolvedProvider,
|
|
57
61
|
ToolDispatcher,
|
|
62
|
+
type ToolProvider,
|
|
58
63
|
generateTypesFromJsonSchema,
|
|
59
64
|
jsonSchemaToType,
|
|
60
65
|
normalizeCode,
|
|
66
|
+
resolveProvider,
|
|
61
67
|
sanitizeToolName
|
|
62
68
|
};
|
|
63
69
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { i as normalizeCode, r as resolveProvider } from "./resolve-DIQRkRqQ.js";
|
|
2
2
|
import { a as sanitizeToolName, n as jsonSchemaToType, t as generateTypesFromJsonSchema } from "./json-schema-types-DoQ0VISs.js";
|
|
3
3
|
import { RpcTarget } from "cloudflare:workers";
|
|
4
4
|
//#region src/executor.ts
|
|
@@ -15,14 +15,21 @@ import { RpcTarget } from "cloudflare:workers";
|
|
|
15
15
|
*/
|
|
16
16
|
var ToolDispatcher = class extends RpcTarget {
|
|
17
17
|
#fns;
|
|
18
|
-
|
|
18
|
+
#positionalArgs;
|
|
19
|
+
constructor(fns, positionalArgs = false) {
|
|
19
20
|
super();
|
|
20
21
|
this.#fns = fns;
|
|
22
|
+
this.#positionalArgs = positionalArgs;
|
|
21
23
|
}
|
|
22
24
|
async call(name, argsJson) {
|
|
23
25
|
const fn = this.#fns[name];
|
|
24
26
|
if (!fn) return JSON.stringify({ error: `Tool "${name}" not found` });
|
|
25
27
|
try {
|
|
28
|
+
if (this.#positionalArgs) {
|
|
29
|
+
const args = argsJson ? JSON.parse(argsJson) : [];
|
|
30
|
+
const result = await fn(...Array.isArray(args) ? args : [args]);
|
|
31
|
+
return JSON.stringify({ result });
|
|
32
|
+
}
|
|
26
33
|
const result = await fn(argsJson ? JSON.parse(argsJson) : {});
|
|
27
34
|
return JSON.stringify({ result });
|
|
28
35
|
} catch (err) {
|
|
@@ -32,12 +39,21 @@ var ToolDispatcher = class extends RpcTarget {
|
|
|
32
39
|
};
|
|
33
40
|
/**
|
|
34
41
|
* Executes code in an isolated Cloudflare Worker via WorkerLoader.
|
|
35
|
-
* Tool calls are dispatched via Workers RPC — the host passes
|
|
36
|
-
*
|
|
42
|
+
* Tool calls are dispatched via Workers RPC — the host passes
|
|
43
|
+
* ToolDispatchers (one per namespace) to the Worker's evaluate() method.
|
|
37
44
|
*
|
|
38
45
|
* External fetch() and connect() are blocked by default via
|
|
39
46
|
* `globalOutbound: null` (runtime-enforced). Pass a Fetcher to
|
|
40
47
|
* `globalOutbound` to allow controlled outbound access.
|
|
48
|
+
*
|
|
49
|
+
* @example
|
|
50
|
+
* ```ts
|
|
51
|
+
* const result = await executor.execute(code, [
|
|
52
|
+
* { name: "codemode", fns: { search: searchFn } },
|
|
53
|
+
* { name: "state", fns: { readFile: readFileFn } },
|
|
54
|
+
* ]);
|
|
55
|
+
* // sandbox has both codemode.search() and state.readFile()
|
|
56
|
+
* ```
|
|
41
57
|
*/
|
|
42
58
|
var DynamicWorkerExecutor = class {
|
|
43
59
|
#loader;
|
|
@@ -51,34 +67,53 @@ var DynamicWorkerExecutor = class {
|
|
|
51
67
|
const { "executor.js": _, ...safeModules } = options.modules ?? {};
|
|
52
68
|
this.#modules = safeModules;
|
|
53
69
|
}
|
|
54
|
-
async execute(code,
|
|
70
|
+
async execute(code, providersOrFns) {
|
|
71
|
+
let providers;
|
|
72
|
+
if (!Array.isArray(providersOrFns)) {
|
|
73
|
+
console.warn("[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. Use ResolvedProvider[] instead. This will be removed in the next major version.");
|
|
74
|
+
providers = [{
|
|
75
|
+
name: "codemode",
|
|
76
|
+
fns: providersOrFns
|
|
77
|
+
}];
|
|
78
|
+
} else providers = providersOrFns;
|
|
55
79
|
const normalized = normalizeCode(code);
|
|
56
80
|
const timeoutMs = this.#timeout;
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
const
|
|
81
|
+
const RESERVED_NAMES = new Set(["__dispatchers", "__logs"]);
|
|
82
|
+
const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
83
|
+
const seenNames = /* @__PURE__ */ new Set();
|
|
84
|
+
for (const provider of providers) {
|
|
85
|
+
if (RESERVED_NAMES.has(provider.name)) return {
|
|
86
|
+
result: void 0,
|
|
87
|
+
error: `Provider name "${provider.name}" is reserved`
|
|
88
|
+
};
|
|
89
|
+
if (!VALID_IDENT.test(provider.name)) return {
|
|
90
|
+
result: void 0,
|
|
91
|
+
error: `Provider name "${provider.name}" is not a valid JavaScript identifier`
|
|
92
|
+
};
|
|
93
|
+
if (seenNames.has(provider.name)) return {
|
|
94
|
+
result: void 0,
|
|
95
|
+
error: `Duplicate provider name "${provider.name}"`
|
|
96
|
+
};
|
|
97
|
+
seenNames.add(provider.name);
|
|
98
|
+
}
|
|
99
|
+
const executorModule = [
|
|
60
100
|
"import { WorkerEntrypoint } from \"cloudflare:workers\";",
|
|
61
101
|
"",
|
|
62
102
|
"export default class CodeExecutor extends WorkerEntrypoint {",
|
|
63
|
-
" async evaluate(
|
|
103
|
+
" async evaluate(__dispatchers = {}) {",
|
|
64
104
|
" const __logs = [];",
|
|
65
105
|
" console.log = (...a) => { __logs.push(a.map(String).join(\" \")); };",
|
|
66
106
|
" console.warn = (...a) => { __logs.push(\"[warn] \" + a.map(String).join(\" \")); };",
|
|
67
107
|
" console.error = (...a) => { __logs.push(\"[error] \" + a.map(String).join(\" \")); };",
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
" if (data.error) throw new Error(data.error);",
|
|
73
|
-
" return data.result;",
|
|
74
|
-
" }",
|
|
75
|
-
" });",
|
|
108
|
+
...providers.map((p) => {
|
|
109
|
+
if (p.positionalArgs) return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (...args) => {\n const resJson = await __dispatchers.${p.name}.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 });`;
|
|
110
|
+
return ` const ${p.name} = new Proxy({}, {\n get: (_, toolName) => async (args) => {\n const resJson = await __dispatchers.${p.name}.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 });`;
|
|
111
|
+
}),
|
|
76
112
|
"",
|
|
77
113
|
" try {",
|
|
78
114
|
" const result = await Promise.race([",
|
|
79
115
|
" ("
|
|
80
|
-
].
|
|
81
|
-
const moduleSuffix = [
|
|
116
|
+
].concat([normalized]).concat([
|
|
82
117
|
")(),",
|
|
83
118
|
" new Promise((_, reject) => setTimeout(() => reject(new Error(\"Execution timed out\")), " + timeoutMs + "))",
|
|
84
119
|
" ]);",
|
|
@@ -88,9 +123,13 @@ var DynamicWorkerExecutor = class {
|
|
|
88
123
|
" }",
|
|
89
124
|
" }",
|
|
90
125
|
"}"
|
|
91
|
-
].join("\n");
|
|
92
|
-
const
|
|
93
|
-
const
|
|
126
|
+
]).join("\n");
|
|
127
|
+
const dispatchers = {};
|
|
128
|
+
for (const provider of providers) {
|
|
129
|
+
const sanitizedFns = {};
|
|
130
|
+
for (const [name, fn] of Object.entries(provider.fns)) sanitizedFns[sanitizeToolName(name)] = fn;
|
|
131
|
+
dispatchers[provider.name] = new ToolDispatcher(sanitizedFns, provider.positionalArgs);
|
|
132
|
+
}
|
|
94
133
|
const response = await this.#loader.get(`codemode-${crypto.randomUUID()}`, () => ({
|
|
95
134
|
compatibilityDate: "2025-06-01",
|
|
96
135
|
compatibilityFlags: ["nodejs_compat"],
|
|
@@ -100,7 +139,7 @@ var DynamicWorkerExecutor = class {
|
|
|
100
139
|
"executor.js": executorModule
|
|
101
140
|
},
|
|
102
141
|
globalOutbound: this.#globalOutbound
|
|
103
|
-
})).getEntrypoint().evaluate(
|
|
142
|
+
})).getEntrypoint().evaluate(dispatchers);
|
|
104
143
|
if (response.error) return {
|
|
105
144
|
result: void 0,
|
|
106
145
|
error: response.error,
|
|
@@ -113,6 +152,6 @@ var DynamicWorkerExecutor = class {
|
|
|
113
152
|
}
|
|
114
153
|
};
|
|
115
154
|
//#endregion
|
|
116
|
-
export { DynamicWorkerExecutor, ToolDispatcher, generateTypesFromJsonSchema, jsonSchemaToType, normalizeCode, sanitizeToolName };
|
|
155
|
+
export { DynamicWorkerExecutor, ToolDispatcher, generateTypesFromJsonSchema, jsonSchemaToType, normalizeCode, resolveProvider, sanitizeToolName };
|
|
117
156
|
|
|
118
157
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
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,wBAAb,MAAuD;CACrD;CACA;CACA;CACA;CAEA,YAAY,SAAuC;AACjD,QAAA,SAAe,QAAQ;AACvB,QAAA,UAAgB,QAAQ,WAAW;AACnC,QAAA,iBAAuB,QAAQ,kBAAkB;EACjD,MAAM,EAAE,eAAe,GAAG,GAAG,gBAAgB,QAAQ,WAAW,EAAE;AAClE,QAAA,UAAgB;;CAGlB,MAAM,QACJ,MACA,KACwB;EACxB,MAAM,aAAa,cAAc,KAAK;EACtC,MAAM,YAAY,MAAA;EAIlB,MAAM,eAGF,EAAE;AACN,OAAK,MAAM,CAAC,MAAM,OAAO,OAAO,QAAQ,IAAI,CAC1C,cAAa,iBAAiB,KAAK,IAAI;EAGzC,MAAM,eAAe;GACnB;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CAAC,KAAK,KAAK;EAEZ,MAAM,eAAe;GACnB;GACA,qGACE,YACA;GACF;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CAAC,KAAK,KAAK;EAEZ,MAAM,iBAAiB,eAAe,aAAa;EAEnD,MAAM,aAAa,IAAI,eAAe,aAAa;EAoBnD,MAAM,WAAW,MAlBF,MAAA,OAAa,IAAI,YAAY,OAAO,YAAY,WAAW;GACxE,mBAAmB;GACnB,oBAAoB,CAAC,gBAAgB;GACrC,YAAY;GACZ,SAAS;IACP,GAAG,MAAA;IACH,eAAe;IAChB;GACD,gBAAgB,MAAA;GACjB,EAAE,CAEuB,eAAe,CAOP,SAAS,WAAW;AAEtD,MAAI,SAAS,MACX,QAAO;GAAE,QAAQ,KAAA;GAAW,OAAO,SAAS;GAAO,MAAM,SAAS;GAAM;AAG1E,SAAO;GAAE,QAAQ,SAAS;GAAQ,MAAM,SAAS;GAAM"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["#fns","#positionalArgs","#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\";\nimport type { ToolDescriptors } from \"./tool-types\";\nimport type { ToolSet } from \"ai\";\n\nexport interface ExecuteResult {\n result: unknown;\n error?: string;\n logs?: string[];\n}\n\n// ── ToolProvider ──────────────────────────────────────────────────────\n\n/**\n * A minimal tool record — just a description and an execute function.\n * Use this for providers that supply their own `types` and don't need\n * schema-based type generation (e.g. stateTools).\n */\nexport type SimpleToolRecord = Record<\n string,\n { description?: string; execute: (args: unknown) => Promise<unknown> }\n>;\n\n/**\n * All tool record types accepted by a ToolProvider.\n */\nexport type ToolProviderTools = ToolDescriptors | ToolSet | SimpleToolRecord;\n\n/**\n * A ToolProvider contributes tools to the codemode sandbox under a namespace.\n *\n * Each provider's tools are accessible as `name.toolName()` in sandbox code.\n * If `name` is omitted, tools are exposed under the default `codemode.*` namespace.\n *\n * @example Multiple providers with different namespaces\n * ```ts\n * createCodeTool({\n * tools: [\n * { name: \"github\", tools: githubTools },\n * { name: \"shell\", tools: shellTools },\n * { tools: aiTools }, // default \"codemode\" namespace\n * ],\n * executor,\n * });\n * // sandbox: github.listIssues(), shell.exec(), codemode.search()\n * ```\n */\nexport interface ToolProvider {\n /** Namespace prefix in the sandbox (e.g. \"state\", \"mcp\"). Defaults to \"codemode\". */\n name?: string;\n\n /** Tools exposed as `namespace.toolName()` in the sandbox. */\n tools: ToolProviderTools;\n\n /** Type declarations for the LLM. Auto-generated from `tools` if omitted. */\n types?: string;\n\n /**\n * When true, tools accept positional args instead of a single object arg.\n * The sandbox proxy uses `(...args)` and the dispatcher spreads the args array.\n *\n * Default tools use single-object args: `codemode.search({ query: \"test\" })`\n * Positional tools use normal args: `state.readFile(\"/path\")`\n */\n positionalArgs?: boolean;\n}\n\n// ── ResolvedProvider ──────────────────────────────────────────────────\n\n/**\n * Internal resolved form of a ToolProvider, ready for execution.\n * The tool functions have been extracted and keyed by sanitized name.\n */\nexport interface ResolvedProvider {\n name: string;\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>;\n positionalArgs?: boolean;\n}\n\n// ── Executor ──────────────────────────────────────────────────────────\n\n/**\n * An executor runs LLM-generated code in a sandbox, making the provided\n * tool functions callable under their namespace inside the sandbox.\n *\n * Implementations should never throw — errors are returned in `ExecuteResult.error`.\n *\n * @param code - The code to execute in the sandbox.\n * @param providersOrFns - An array of `ResolvedProvider` (preferred), or a\n * plain `Record<string, fn>` for backwards compatibility (deprecated — will\n * be removed in the next major version).\n */\nexport interface Executor {\n execute(\n code: string,\n providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult>;\n}\n\n// ── ToolDispatcher ────────────────────────────────────────────────────\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 #positionalArgs: boolean;\n\n constructor(\n fns: Record<string, (...args: unknown[]) => Promise<unknown>>,\n positionalArgs = false\n ) {\n super();\n this.#fns = fns;\n this.#positionalArgs = positionalArgs;\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 if (this.#positionalArgs) {\n const args = argsJson ? JSON.parse(argsJson) : [];\n const result = await fn(...(Array.isArray(args) ? args : [args]));\n return JSON.stringify({ result });\n }\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 ─────────────────────────────────────────────\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 *\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\n * ToolDispatchers (one per namespace) 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 *\n * @example\n * ```ts\n * const result = await executor.execute(code, [\n * { name: \"codemode\", fns: { search: searchFn } },\n * { name: \"state\", fns: { readFile: readFileFn } },\n * ]);\n * // sandbox has both codemode.search() and state.readFile()\n * ```\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 providersOrFns:\n | ResolvedProvider[]\n | Record<string, (...args: unknown[]) => Promise<unknown>>\n ): Promise<ExecuteResult> {\n // Backwards compat: detect old `execute(code, fns)` signature.\n let providers: ResolvedProvider[];\n if (!Array.isArray(providersOrFns)) {\n console.warn(\n \"[@cloudflare/codemode] Passing raw fns to executor.execute() is deprecated. \" +\n \"Use ResolvedProvider[] instead. This will be removed in the next major version.\"\n );\n providers = [{ name: \"codemode\", fns: providersOrFns }];\n } else {\n providers = providersOrFns;\n }\n\n const normalized = normalizeCode(code);\n const timeoutMs = this.#timeout;\n\n // Validate provider names.\n const RESERVED_NAMES = new Set([\"__dispatchers\", \"__logs\"]);\n const VALID_IDENT = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;\n const seenNames = new Set<string>();\n for (const provider of providers) {\n if (RESERVED_NAMES.has(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is reserved`\n };\n }\n if (!VALID_IDENT.test(provider.name)) {\n return {\n result: undefined,\n error: `Provider name \"${provider.name}\" is not a valid JavaScript identifier`\n };\n }\n if (seenNames.has(provider.name)) {\n return {\n result: undefined,\n error: `Duplicate provider name \"${provider.name}\"`\n };\n }\n seenNames.add(provider.name);\n }\n\n // Generate a Proxy global for each provider namespace.\n const proxyInits = providers.map((p) => {\n if (p.positionalArgs) {\n return (\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (...args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), JSON.stringify(args));\\n` +\n ` const data = JSON.parse(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n }\n return (\n ` const ${p.name} = new Proxy({}, {\\n` +\n ` get: (_, toolName) => async (args) => {\\n` +\n ` const resJson = await __dispatchers.${p.name}.call(String(toolName), JSON.stringify(args ?? {}));\\n` +\n ` const data = JSON.parse(resJson);\\n` +\n ` if (data.error) throw new Error(data.error);\\n` +\n ` return data.result;\\n` +\n ` }\\n` +\n ` });`\n );\n });\n\n const executorModule = [\n 'import { WorkerEntrypoint } from \"cloudflare:workers\";',\n \"\",\n \"export default class CodeExecutor extends WorkerEntrypoint {\",\n \" async evaluate(__dispatchers = {}) {\",\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 ...proxyInits,\n \"\",\n \" try {\",\n \" const result = await Promise.race([\",\n \" (\"\n ]\n .concat([normalized])\n .concat([\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 ])\n .join(\"\\n\");\n\n // Build dispatcher map: { codemode: ToolDispatcher, state: ToolDispatcher, ... }\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 proxy.\n const dispatchers: Record<string, ToolDispatcher> = {};\n for (const provider of providers) {\n const sanitizedFns: Record<\n string,\n (...args: unknown[]) => Promise<unknown>\n > = {};\n for (const [name, fn] of Object.entries(provider.fns)) {\n sanitizedFns[sanitizeToolName(name)] = fn;\n }\n dispatchers[provider.name] = new ToolDispatcher(\n sanitizedFns,\n provider.positionalArgs\n );\n }\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(dispatchers: Record<string, ToolDispatcher>): Promise<{\n result: unknown;\n error?: string;\n logs?: string[];\n }>;\n };\n const response = await entrypoint.evaluate(dispatchers);\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":";;;;;;;;;;;;;;;AAoHA,IAAa,iBAAb,cAAoC,UAAU;CAC5C;CACA;CAEA,YACE,KACA,iBAAiB,OACjB;AACA,SAAO;AACP,QAAA,MAAY;AACZ,QAAA,iBAAuB;;CAGzB,MAAM,KAAK,MAAc,UAAmC;EAC1D,MAAM,KAAK,MAAA,IAAU;AACrB,MAAI,CAAC,GACH,QAAO,KAAK,UAAU,EAAE,OAA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
package/dist/mcp.js
CHANGED
|
@@ -72,7 +72,10 @@ async function codeMcpServer(options) {
|
|
|
72
72
|
inputSchema: { code: z.string().describe("JavaScript async arrow function to execute") }
|
|
73
73
|
}, async ({ code }) => {
|
|
74
74
|
try {
|
|
75
|
-
const result = await executor.execute(code,
|
|
75
|
+
const result = await executor.execute(code, [{
|
|
76
|
+
name: "codemode",
|
|
77
|
+
fns
|
|
78
|
+
}]);
|
|
76
79
|
if (result.error) return {
|
|
77
80
|
content: [{
|
|
78
81
|
type: "text",
|
|
@@ -237,7 +240,10 @@ async () => {
|
|
|
237
240
|
inputSchema: { code: z.string().describe("JavaScript async arrow function to search the spec") }
|
|
238
241
|
}, async ({ code }) => {
|
|
239
242
|
try {
|
|
240
|
-
const result = await executor.execute(code, {
|
|
243
|
+
const result = await executor.execute(code, [{
|
|
244
|
+
name: "codemode",
|
|
245
|
+
fns: { spec: async () => resolved }
|
|
246
|
+
}]);
|
|
241
247
|
if (result.error) return {
|
|
242
248
|
content: [{
|
|
243
249
|
type: "text",
|
|
@@ -275,7 +281,10 @@ async () => {
|
|
|
275
281
|
inputSchema: { code: z.string().describe("JavaScript async arrow function to execute") }
|
|
276
282
|
}, async ({ code }) => {
|
|
277
283
|
try {
|
|
278
|
-
const result = await executor.execute(code, {
|
|
284
|
+
const result = await executor.execute(code, [{
|
|
285
|
+
name: "codemode",
|
|
286
|
+
fns: { request: (args) => requestFn(args) }
|
|
287
|
+
}]);
|
|
279
288
|
if (result.error) return {
|
|
280
289
|
content: [{
|
|
281
290
|
type: "text",
|
package/dist/mcp.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.js","names":[],"sources":["../src/mcp.ts"],"sourcesContent":["import { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { InMemoryTransport } from \"@modelcontextprotocol/sdk/inMemory.js\";\nimport { z } from \"zod\";\nimport {\n generateTypesFromJsonSchema,\n type JsonSchemaToolDescriptors\n} from \"./json-schema-types\";\nimport { sanitizeToolName } from \"./utils\";\nimport type { Executor } from \"./executor\";\n\nimport type { JSONSchema7 } from \"json-schema\";\n\n// -- Shared utilities --\n\nconst CHARS_PER_TOKEN = 4;\nconst MAX_TOKENS = 6000;\nconst MAX_CHARS = MAX_TOKENS * CHARS_PER_TOKEN;\n\nfunction truncateResponse(content: unknown): string {\n const text =\n typeof content === \"string\"\n ? content\n : (JSON.stringify(content, null, 2) ?? \"undefined\");\n\n if (text.length <= MAX_CHARS) {\n return text;\n }\n\n const truncated = text.slice(0, MAX_CHARS);\n const estimatedTokens = Math.ceil(text.length / CHARS_PER_TOKEN);\n\n return `${truncated}\\n\\n--- TRUNCATED ---\\nResponse was ~${estimatedTokens.toLocaleString()} tokens (limit: ${MAX_TOKENS.toLocaleString()}). Use more specific queries to reduce response size.`;\n}\n\nfunction formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\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,MAA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,MAAM,UAAU,YAAY,MAAM;KAAI,CAChE;IACD,SAAS;IACV;;GAGN;CAGD,MAAM,qBAAqB;;;EAG3B,cAAc;;;;;;;GAOb,cAAc,OAAO,gBAAgB;AAEtC,QAAO,aACL,WACA;EACE,aAAa;EACb,aAAa,EACX,MAAM,EAAE,QAAQ,CAAC,SAAS,6CAA6C,EACxE;EACF,EACD,OAAO,EAAE,WAAW;AAClB,MAAI;GACF,MAAM,SAAS,MAAM,SAAS,QAAQ,MAAM,EAC1C,UAAU,SAAkB,UAAU,KAAuB,EAC9D,CAAC;AACF,OAAI,OAAO,MACT,QAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;KAAS,CAC1D;IACD,SAAS;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"}
|
|
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, [\n { name: \"codemode\", fns }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: truncateResponse(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return codemodeServer;\n}\n\n// -- openApiMcpServer --\n\nexport interface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\nexport interface OpenApiMcpServerOptions {\n spec: Record<string, unknown>;\n executor: Executor;\n request: (options: RequestOptions) => Promise<unknown>;\n name?: string;\n version?: string;\n description?: string;\n}\n\n/**\n * Resolve internal $ref pointers in a JSON object against the root document.\n * Only handles `#/` internal refs. External file refs are left as-is.\n */\nfunction resolveRefs(\n obj: unknown,\n root: Record<string, unknown>,\n seen = new Set<string>()\n): unknown {\n if (obj === null || obj === undefined) return obj;\n if (typeof obj !== \"object\") return obj;\n if (Array.isArray(obj))\n return obj.map((item) => resolveRefs(item, root, seen));\n\n const record = obj as Record<string, unknown>;\n\n if (\"$ref\" in record && typeof record.$ref === \"string\") {\n const ref = record.$ref;\n if (seen.has(ref)) return { $circular: ref };\n if (!ref.startsWith(\"#/\")) return record;\n seen.add(ref);\n\n const parts = ref\n .slice(2)\n .split(\"/\")\n .map((s) => s.replace(/~1/g, \"/\").replace(/~0/g, \"~\"));\n let resolved: unknown = root;\n for (const part of parts) {\n resolved = (resolved as Record<string, unknown>)?.[part];\n }\n const result = resolveRefs(resolved, root, seen);\n seen.delete(ref);\n return result;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record)) {\n result[key] = resolveRefs(value, root, seen);\n }\n return result;\n}\n\nconst SPEC_TYPES = `\n// OpenAPI 3.x spec with $refs resolved inline.\n// The spec object follows the standard OpenAPI 3.x structure.\n\ninterface OperationObject {\n summary?: string;\n description?: string;\n operationId?: string;\n tags?: string[];\n parameters?: Array<{\n name: string;\n in: \"query\" | \"header\" | \"path\" | \"cookie\";\n required?: boolean;\n schema?: unknown;\n description?: string;\n }>;\n requestBody?: {\n required?: boolean;\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n };\n responses?: Record<string, {\n description?: string;\n content?: Record<string, { schema?: unknown }>;\n }>;\n security?: Array<Record<string, string[]>>;\n deprecated?: boolean;\n}\n\ninterface PathItem {\n summary?: string;\n description?: string;\n get?: OperationObject;\n post?: OperationObject;\n put?: OperationObject;\n patch?: OperationObject;\n delete?: OperationObject;\n head?: OperationObject;\n options?: OperationObject;\n trace?: OperationObject;\n parameters?: OperationObject[\"parameters\"];\n}\n\ninterface OpenApiSpec {\n openapi: string;\n info: { title: string; version: string; description?: string };\n paths: Record<string, PathItem>;\n servers?: Array<{ url: string; description?: string }>;\n components?: Record<string, unknown>;\n tags?: Array<{ name: string; description?: string }>;\n}\n\ndeclare const codemode: {\n spec(): Promise<OpenApiSpec>;\n};\n`;\n\nconst REQUEST_TYPES = `\ninterface RequestOptions {\n method: \"GET\" | \"POST\" | \"PUT\" | \"PATCH\" | \"DELETE\";\n path: string;\n query?: Record<string, string | number | boolean | undefined>;\n body?: unknown;\n contentType?: string;\n rawBody?: boolean;\n}\n\ndeclare const codemode: {\n request(options: RequestOptions): Promise<unknown>;\n};\n`;\n\n/**\n * Create an MCP server with search + execute tools from an OpenAPI spec.\n *\n * The search tool lets the LLM query the spec to find endpoints.\n * The execute tool lets the LLM call the API via a user-provided\n * request function that runs on the host (auth never enters the sandbox).\n */\nexport function openApiMcpServer(options: OpenApiMcpServerOptions): McpServer {\n const {\n executor,\n request: requestFn,\n name = \"openapi\",\n version = \"1.0.0\",\n description\n } = options;\n\n const resolved = resolveRefs(options.spec, options.spec);\n\n const server = new McpServer({ name, version });\n\n // --- search tool ---\n server.registerTool(\n \"search\",\n {\n description: `Search the OpenAPI spec. All $refs are pre-resolved inline.\n\nTypes:\n${SPEC_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExamples:\n\n// List all paths\nasync () => {\n const spec = await codemode.spec();\n return Object.keys(spec.paths);\n}\n\n// Find endpoints by tag\nasync () => {\n const spec = await codemode.spec();\n const results = [];\n for (const [path, methods] of Object.entries(spec.paths)) {\n for (const [method, op] of Object.entries(methods)) {\n if (op.tags?.some(t => t.toLowerCase() === 'your_tag')) {\n results.push({ method: method.toUpperCase(), path, summary: op.summary });\n }\n }\n }\n return results;\n}`,\n inputSchema: {\n code: z\n .string()\n .describe(\"JavaScript async arrow function to search the spec\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(code, [\n { name: \"codemode\", fns: { spec: async () => resolved } }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: truncateResponse(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n // --- execute tool ---\n const executeDescription = `Execute API calls using JavaScript code. First use 'search' to find the right endpoints.\n\nAvailable in your code:\n${REQUEST_TYPES}\n\nYour code must be an async arrow function that returns the result.\n\nExample:\nasync () => {\n return await codemode.request({ method: \"GET\", path: \"/your/endpoint\" });\n}${description ? `\\n\\n${description}` : \"\"}`;\n\n server.registerTool(\n \"execute\",\n {\n description: executeDescription,\n inputSchema: {\n code: z.string().describe(\"JavaScript async arrow function to execute\")\n }\n },\n async ({ code }) => {\n try {\n const result = await executor.execute(code, [\n {\n name: \"codemode\",\n fns: {\n request: (args: unknown) => requestFn(args as RequestOptions)\n }\n }\n ]);\n if (result.error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${result.error}` }\n ],\n isError: true\n };\n }\n return {\n content: [\n { type: \"text\" as const, text: truncateResponse(result.result) }\n ]\n };\n } catch (error) {\n return {\n content: [\n { type: \"text\" as const, text: `Error: ${formatError(error)}` }\n ],\n isError: true\n };\n }\n }\n );\n\n return server;\n}\n"],"mappings":";;;;;;AAeA,MAAM,kBAAkB;AACxB,MAAM,aAAa;AACnB,MAAM,YAAY,aAAa;AAE/B,SAAS,iBAAiB,SAA0B;CAClD,MAAM,OACJ,OAAO,YAAY,WACf,UACC,KAAK,UAAU,SAAS,MAAM,EAAE,IAAI;AAE3C,KAAI,KAAK,UAAU,UACjB,QAAO;AAMT,QAAO,GAHW,KAAK,MAAM,GAAG,UAAU,CAGtB,uCAFI,KAAK,KAAK,KAAK,SAAS,gBAAgB,CAEW,gBAAgB,CAAC,kBAAkB,WAAW,gBAAgB,CAAC;;AAG5I,SAAS,YAAY,OAAwB;AAC3C,QAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;;AAK/D,MAAM,mBAAmB;;;;;;;;;;AAuBzB,eAAsB,cACpB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ACb,aAAa,EACX,MAAM,EAAE,QAAQ,CAAC,SAAS,6CAA6C,EACxE;EACF,EACD,OAAO,EAAE,WAAW;AAClB,MAAI;GACF,MAAM,SAAS,MAAM,SAAS,QAAQ,MAAM,CAC1C;IACE,MAAM;IACN,KAAK,EACH,UAAU,SAAkB,UAAU,KAAuB,EAC9D;IACF,CACF,CAAC;AACF,OAAI,OAAO,MACT,QAAO;IACL,SAAS,CACP;KAAE,MAAM;KAAiB,MAAM,UAAU,OAAO;KAAS,CAC1D;IACD,SAAS;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"}
|
|
@@ -39,6 +39,47 @@ function normalizeCode(code) {
|
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
41
|
//#endregion
|
|
42
|
-
|
|
42
|
+
//#region src/resolve.ts
|
|
43
|
+
function hasNeedsApproval(t) {
|
|
44
|
+
return "needsApproval" in t && t.needsApproval != null;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Filter out tools with needsApproval and return a clean copy.
|
|
48
|
+
*/
|
|
49
|
+
function filterTools(tools) {
|
|
50
|
+
const filtered = {};
|
|
51
|
+
for (const [name, t] of Object.entries(tools)) if (!hasNeedsApproval(t)) filtered[name] = t;
|
|
52
|
+
return filtered;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Extract execute functions from tools, keyed by name.
|
|
56
|
+
* This is the base version — no schema validation.
|
|
57
|
+
* The AI SDK entry point overrides this with `asSchema`-based validation.
|
|
58
|
+
*/
|
|
59
|
+
function extractFns(tools) {
|
|
60
|
+
const fns = {};
|
|
61
|
+
for (const [name, t] of Object.entries(tools)) {
|
|
62
|
+
const execute = "execute" in t ? t.execute : void 0;
|
|
63
|
+
if (execute) fns[name] = execute;
|
|
64
|
+
}
|
|
65
|
+
return fns;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Resolve a ToolProvider into a ResolvedProvider ready for execution.
|
|
69
|
+
* Filters out tools with `needsApproval`.
|
|
70
|
+
*
|
|
71
|
+
* This version does NOT perform schema validation on inputs.
|
|
72
|
+
* Import from `@cloudflare/codemode/ai` for the schema-validating version.
|
|
73
|
+
*/
|
|
74
|
+
function resolveProvider(provider) {
|
|
75
|
+
const resolved = {
|
|
76
|
+
name: provider.name ?? "codemode",
|
|
77
|
+
fns: extractFns(filterTools(provider.tools))
|
|
78
|
+
};
|
|
79
|
+
if (provider.positionalArgs) resolved.positionalArgs = true;
|
|
80
|
+
return resolved;
|
|
81
|
+
}
|
|
82
|
+
//#endregion
|
|
83
|
+
export { normalizeCode as i, filterTools as n, resolveProvider as r, extractFns as t };
|
|
43
84
|
|
|
44
|
-
//# sourceMappingURL=
|
|
85
|
+
//# sourceMappingURL=resolve-DIQRkRqQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resolve-DIQRkRqQ.js","names":[],"sources":["../src/normalize.ts","../src/resolve.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","/**\n * Framework-agnostic tool resolution.\n *\n * Extracts execute functions from tool records and resolves ToolProviders\n * into ResolvedProviders — no dependency on the AI SDK or Zod.\n *\n * The AI SDK entry point (`./ai`) layers on schema validation via `asSchema`.\n */\n\nimport type {\n ToolProvider,\n ToolProviderTools,\n ResolvedProvider\n} from \"./executor\";\n\nfunction hasNeedsApproval(t: Record<string, unknown>): boolean {\n return \"needsApproval\" in t && t.needsApproval != null;\n}\n\n/**\n * Filter out tools with needsApproval and return a clean copy.\n */\nexport function filterTools(tools: ToolProviderTools): ToolProviderTools {\n const filtered: Record<string, unknown> = {};\n for (const [name, t] of Object.entries(tools)) {\n if (!hasNeedsApproval(t as Record<string, unknown>)) {\n filtered[name] = t;\n }\n }\n return filtered as ToolProviderTools;\n}\n\n/**\n * Extract execute functions from tools, keyed by name.\n * This is the base version — no schema validation.\n * The AI SDK entry point overrides this with `asSchema`-based validation.\n */\nexport function extractFns(\n tools: ToolProviderTools\n): Record<string, (...args: unknown[]) => Promise<unknown>> {\n const fns: Record<string, (...args: unknown[]) => Promise<unknown>> = {};\n\n for (const [name, t] of Object.entries(tools)) {\n const execute =\n \"execute\" in t\n ? (t.execute as (args: unknown) => Promise<unknown>)\n : undefined;\n if (execute) {\n fns[name] = execute;\n }\n }\n\n return fns;\n}\n\n/**\n * Resolve a ToolProvider into a ResolvedProvider ready for execution.\n * Filters out tools with `needsApproval`.\n *\n * This version does NOT perform schema validation on inputs.\n * Import from `@cloudflare/codemode/ai` for the schema-validating version.\n */\nexport function resolveProvider(provider: ToolProvider): ResolvedProvider {\n const name = provider.name ?? \"codemode\";\n const filtered = filterTools(provider.tools);\n const resolved: ResolvedProvider = { name, fns: extractFns(filtered) };\n if (provider.positionalArgs) resolved.positionalArgs = true;\n return resolved;\n}\n"],"mappings":";;;;;;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,W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AO;;;;;;;;;AAUT,SAAgB,gBAAgB,UAA0C;CAGxE,MAAM,WAA6B;EAAE,MAFxB,SAAS,QAAQ;EAEa,KAAK,WAD/B,YAAY,SAAS,MAAM,CACwB;EAAE;AACtE,KAAI,SAAS,eAAgB,UAAS,iBAAiB;AACvD,QAAO"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import {
|
|
2
|
+
a as ResolvedProvider,
|
|
3
|
+
s as ToolProvider
|
|
4
|
+
} from "./executor-wZjYdqEX.js";
|
|
5
|
+
|
|
6
|
+
//#region src/resolve.d.ts
|
|
7
|
+
/**
|
|
8
|
+
* Resolve a ToolProvider into a ResolvedProvider ready for execution.
|
|
9
|
+
* Filters out tools with `needsApproval`.
|
|
10
|
+
*
|
|
11
|
+
* This version does NOT perform schema validation on inputs.
|
|
12
|
+
* Import from `@cloudflare/codemode/ai` for the schema-validating version.
|
|
13
|
+
*/
|
|
14
|
+
declare function resolveProvider(provider: ToolProvider): ResolvedProvider;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { resolveProvider as t };
|
|
17
|
+
//# sourceMappingURL=resolve-DULSpsq2.d.ts.map
|