@cloudflare/codemode 0.4.1 → 0.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -11
- package/dist/ai.d.ts +2 -2
- package/dist/ai.js +3 -3
- package/dist/{base-CHRR_a5j.js → base-BqhlNCSH.js} +2 -2
- package/dist/{base-CHRR_a5j.js.map → base-BqhlNCSH.js.map} +1 -1
- package/dist/browser.d.ts +2 -2
- package/dist/browser.js +4 -4
- package/dist/browser.js.map +1 -1
- package/dist/{executor-BIs2dr7X.d.ts → executor-DkMGH_7-.d.ts} +2 -2
- package/dist/index.d.ts +54 -12
- package/dist/index.js +79 -27
- package/dist/index.js.map +1 -1
- package/dist/{json-schema-types-BGjW4KPy.js → json-schema-types-D_m9tVnI.js} +2 -2
- package/dist/{json-schema-types-BGjW4KPy.js.map → json-schema-types-D_m9tVnI.js.map} +1 -1
- package/dist/mcp.d.ts +35 -2
- package/dist/mcp.js +3 -3
- package/dist/mcp.js.map +1 -1
- package/dist/{resolve-CBr_VoPl.d.ts → resolve-tqDt6Djo.d.ts} +2 -2
- package/dist/{run-code-aKHcTgf9.js → run-code-Q3Jh6Dcu.js} +2 -2
- package/dist/{run-code-aKHcTgf9.js.map → run-code-Q3Jh6Dcu.js.map} +1 -1
- package/dist/{shared-Ce-zCEBP.d.ts → shared-BOF2IKt-.d.ts} +2 -2
- package/dist/tanstack-ai.d.ts +3 -3
- package/dist/tanstack-ai.js +2 -2
- package/dist/vite.js +19 -91
- package/dist/vite.js.map +1 -1
- package/docs/approvals.md +169 -0
- package/docs/connectors.md +343 -0
- package/docs/index.md +192 -0
- package/docs/runtime.md +263 -0
- package/docs/snippets.md +96 -0
- package/docs/vite-plugin.md +60 -0
- package/package.json +22 -4
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
# Approvals
|
|
2
|
+
|
|
3
|
+
A tool with `requiresApproval: true` pauses the run when the model's code calls it (the run aborts), the action is recorded as pending, and the user is asked to approve. On approval the execution **continues via replay** — see [Runtime](./runtime.md) for the mechanism.
|
|
4
|
+
|
|
5
|
+
## Marking tools
|
|
6
|
+
|
|
7
|
+
On a custom connector, set it on the tool itself:
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
protected tools() {
|
|
11
|
+
return {
|
|
12
|
+
create_issue: {
|
|
13
|
+
description: "Create a GitHub issue.",
|
|
14
|
+
requiresApproval: true,
|
|
15
|
+
execute: (args) => this.client.createIssue(args)
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
On a derived connector (MCP, OpenAPI), decorate via the `tool(name, t)` hook:
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
class GithubConnector extends McpConnector<Env> {
|
|
25
|
+
protected tool(name: string, t: ConnectorTool): ConnectorTool {
|
|
26
|
+
if (name === "create_issue" || name === "merge_pull_request") {
|
|
27
|
+
return { ...t, requiresApproval: true };
|
|
28
|
+
}
|
|
29
|
+
return t;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
`requiresApproval: true` is the entire surface. Mark only what needs a human — everything else executes immediately and is still recorded in the durable log for replay and audit.
|
|
35
|
+
|
|
36
|
+
## Flow
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
Model calls codemode({ code }) where code calls github.create_issue(...)
|
|
40
|
+
→ runtime logs calls; create_issue requires approval → run pauses
|
|
41
|
+
→ tool returns { status: "paused", executionId, pending: [...] }
|
|
42
|
+
|
|
43
|
+
Agent shows the pending action to the user.
|
|
44
|
+
User approves.
|
|
45
|
+
|
|
46
|
+
Agent calls runtime.approve({ executionId })
|
|
47
|
+
→ runtime replays the log, runs create_issue for real, continues
|
|
48
|
+
→ returns { status: "completed", result } (or pauses again at the next action)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
The model writes code as if the call returns normally. It doesn't see a provisional result — the run simply pauses and resumes transparently across the approval.
|
|
52
|
+
|
|
53
|
+
## Tool output
|
|
54
|
+
|
|
55
|
+
Execution outcomes are returned, not thrown — a sandbox error or a replay divergence comes back as `{ status: "error" }` (and is recorded on the execution), so the agent loop is never broken by an exception:
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
type ProxyToolOutput =
|
|
59
|
+
| {
|
|
60
|
+
status: "completed";
|
|
61
|
+
executionId: string;
|
|
62
|
+
result: unknown;
|
|
63
|
+
logs?: string[];
|
|
64
|
+
calls?: ToolLogEntry[];
|
|
65
|
+
}
|
|
66
|
+
| {
|
|
67
|
+
status: "paused";
|
|
68
|
+
executionId: string;
|
|
69
|
+
pending: PendingAction[];
|
|
70
|
+
calls?: ToolLogEntry[];
|
|
71
|
+
}
|
|
72
|
+
| {
|
|
73
|
+
status: "error";
|
|
74
|
+
executionId: string;
|
|
75
|
+
error: string;
|
|
76
|
+
logs?: string[];
|
|
77
|
+
calls?: ToolLogEntry[];
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
type PendingAction = {
|
|
81
|
+
executionId: string;
|
|
82
|
+
seq: number;
|
|
83
|
+
connector: string;
|
|
84
|
+
method: string;
|
|
85
|
+
args: unknown;
|
|
86
|
+
};
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
Every outcome also carries `calls` — the execution's [tool-call log](./runtime.md#the-tool-call-log) as it stands at the end of the pass: each connector call and `codemode.step`, with args, recorded result, approval requirement, and state. Render it to show the user what a run actually did (and what is still pending) without a separate `executions()` round trip.
|
|
90
|
+
|
|
91
|
+
## Resolving approvals
|
|
92
|
+
|
|
93
|
+
The agent drives resolution through the runtime handle:
|
|
94
|
+
|
|
95
|
+
```ts
|
|
96
|
+
const runtime = createCodemodeRuntime({ ctx: this.ctx, connectors, executor });
|
|
97
|
+
|
|
98
|
+
// List actions awaiting approval, for approval UIs. With no executionId this
|
|
99
|
+
// aggregates across every paused run, so concurrent approvals all show up.
|
|
100
|
+
await runtime.pending();
|
|
101
|
+
|
|
102
|
+
// Approve the pending action(s) and continue
|
|
103
|
+
await runtime.approve({ executionId });
|
|
104
|
+
|
|
105
|
+
// Reject — ends the execution. Does NOT undo actions already applied earlier
|
|
106
|
+
// in the same run; call rollback() for that. Returns false if the action was
|
|
107
|
+
// no longer pending (approved/rejected elsewhere) — check it before telling
|
|
108
|
+
// the user the run was rejected, because the action may have executed.
|
|
109
|
+
const terminated = await runtime.reject({ seq, executionId });
|
|
110
|
+
|
|
111
|
+
// Roll back applied actions in reverse order
|
|
112
|
+
await runtime.rollback({ executionId });
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Every lifecycle call targets an explicit `executionId` (there is no implicit "current run" — that would be racy when multiple runs are in flight). Get the id from `pending()`, from `executions()`, or from the tool's own output, which carries `executionId` on every outcome.
|
|
116
|
+
|
|
117
|
+
`approve()` is a **safe no-op on a run that is no longer paused.** Approval UIs are racy: the run may have completed, been rejected, or been rolled back — in another tab, by another operator, or by a concurrent turn — between the moment the queue was rendered and the moment someone clicks. In that case `approve()` does not revive the run (which would re-offer a rejected action or re-apply rolled-back effects); it returns `{ status: "error", executionId, error: "...is not paused..." }` and changes nothing. Treat that outcome as "this run already moved on, refresh the queue," not as an execution failure. Only a `paused` run can be resumed.
|
|
118
|
+
|
|
119
|
+
Wire these to callable agent methods so the client UI can approve/reject:
|
|
120
|
+
|
|
121
|
+
```ts
|
|
122
|
+
export class Chat extends AIChatAgent<Env> {
|
|
123
|
+
@callable()
|
|
124
|
+
async listPending() {
|
|
125
|
+
return this.codemodeRuntime().pending();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
@callable()
|
|
129
|
+
async approve(executionId: string) {
|
|
130
|
+
return this.codemodeRuntime().approve({ executionId });
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Rollback
|
|
136
|
+
|
|
137
|
+
Rollback reverts **all** applied actions that have a `revert` — not only approval-gated ones — in reverse order. Define `revert` on the tool (or override `revertAction`); it returns whether a revert actually ran, and the runtime marks only those entries as reverted:
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
protected tools() {
|
|
141
|
+
return {
|
|
142
|
+
create_issue: {
|
|
143
|
+
description: "Create a GitHub issue.",
|
|
144
|
+
requiresApproval: true,
|
|
145
|
+
execute: (args) => this.client.createIssue(args),
|
|
146
|
+
revert: (_args, result) => {
|
|
147
|
+
const { number } = result as { number: number };
|
|
148
|
+
return this.client.closeIssue(number);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
Tools without a `revert` are skipped, as are reads. Rollback is independent of approval: a non-approval write with a `revert` is still undone.
|
|
156
|
+
|
|
157
|
+
## Comparison with Gatekeeper
|
|
158
|
+
|
|
159
|
+
| Concept | Gatekeeper | Codemode |
|
|
160
|
+
| -------------------- | ---------------------------------- | ------------------------------------------------- |
|
|
161
|
+
| Read classification | `authorizeObservation()` | unannotated (default) |
|
|
162
|
+
| Write classification | `submitAction()` | `{ requiresApproval: true }` |
|
|
163
|
+
| Pending state | Simulated in the session | Logged; run aborts |
|
|
164
|
+
| Continue | Session simulates ahead | Abort-and-replay |
|
|
165
|
+
| Apply | `applyAction(action)` | `runtime.approve({ executionId })` replays + runs |
|
|
166
|
+
| Reject | `rejectAction(action)` | `runtime.reject({ seq, executionId })` |
|
|
167
|
+
| Revert | `revertAction(action, revertInfo)` | `revertAction(method, args, result)` |
|
|
168
|
+
|
|
169
|
+
The key difference: Gatekeeper _simulates_ pending actions so code keeps running. Codemode _aborts and replays_ — simpler and fully durable, at the cost of re-running the code (cheap, since prior calls are served from the log).
|
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
# Connectors
|
|
2
|
+
|
|
3
|
+
Connectors are class-based integrations that bridge external services into the codemode sandbox.
|
|
4
|
+
|
|
5
|
+
**Why this exists:** there should be one way to add a capability. Whether the source is an MCP server, an OpenAPI spec, an AI SDK toolset, or your own service, the answer is the same — wrap it in a connector class, put it in a runtime, and the model sees it as a typed global (`github.list_pull_requests(...)`). The model-facing protocol never changes; only the class you subclass does.
|
|
6
|
+
|
|
7
|
+
Connectors define and execute tools. The [Runtime](./runtime.md) facet routes every call through a durable log — the connector owns definition and execution, while the runtime owns state, approvals, and rollback.
|
|
8
|
+
|
|
9
|
+
A connector answers three questions: what global name does the model use (`name`), what guidance does the model get (`instructions`), and what tools exist (`tools`). Each tool carries its own docs, schema, approval requirement, execution, and optional revert — **everything about a tool lives in one place**.
|
|
10
|
+
|
|
11
|
+
## Base class
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
import { CodemodeConnector } from "@cloudflare/codemode";
|
|
15
|
+
|
|
16
|
+
export class MyConnector extends CodemodeConnector<Env> {
|
|
17
|
+
name() {
|
|
18
|
+
return "myService";
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
protected instructions() {
|
|
22
|
+
return "Use for interacting with My Service.";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
protected tools() {
|
|
26
|
+
return {
|
|
27
|
+
listItems: {
|
|
28
|
+
description: "List all items.",
|
|
29
|
+
inputSchema: {
|
|
30
|
+
type: "object",
|
|
31
|
+
properties: { limit: { type: "number" } }
|
|
32
|
+
},
|
|
33
|
+
execute: (args) => this.env.MY_SERVICE.list(args)
|
|
34
|
+
},
|
|
35
|
+
createItem: {
|
|
36
|
+
description: "Create an item.",
|
|
37
|
+
inputSchema: {
|
|
38
|
+
type: "object",
|
|
39
|
+
properties: { title: { type: "string" } },
|
|
40
|
+
required: ["title"]
|
|
41
|
+
},
|
|
42
|
+
requiresApproval: true,
|
|
43
|
+
execute: (args) => this.env.MY_SERVICE.create(args),
|
|
44
|
+
revert: (_args, result) => this.env.MY_SERVICE.delete(result.id)
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Authoring surface
|
|
52
|
+
|
|
53
|
+
| Method | Required | Purpose |
|
|
54
|
+
| ---------------- | -------- | -------------------------------------------------------------------------------- |
|
|
55
|
+
| `name()` | Yes | Unique namespace in the sandbox (`github`, `stripe`, etc.) |
|
|
56
|
+
| `instructions()` | No | Guidance shown to the model |
|
|
57
|
+
| `tools()` | Yes | One record, one entry per tool (derived connectors generate it for you) |
|
|
58
|
+
| `tool(name, t)` | No | Decoration hook — adjust tools you didn't author inline (approval, revert, docs) |
|
|
59
|
+
|
|
60
|
+
### Each tool
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
type ToolExecuteContext = { executionId: string };
|
|
64
|
+
|
|
65
|
+
type ConnectorTool = {
|
|
66
|
+
description?: string;
|
|
67
|
+
inputSchema?: JSONSchema7; // defaults to an open object
|
|
68
|
+
outputSchema?: JSONSchema7;
|
|
69
|
+
requiresApproval?: boolean; // omit to execute immediately
|
|
70
|
+
execute: (
|
|
71
|
+
args: unknown,
|
|
72
|
+
ctx?: ToolExecuteContext
|
|
73
|
+
) => Promise<unknown> | unknown;
|
|
74
|
+
revert?: (
|
|
75
|
+
args: unknown,
|
|
76
|
+
result: unknown,
|
|
77
|
+
ctx?: ToolExecuteContext
|
|
78
|
+
) => Promise<void> | void;
|
|
79
|
+
};
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
`execute`/`revert` receive an optional `ctx` carrying the `executionId` of the run they belong to. The id is stable across a run's pause/resume passes, so it's the key to use for any resource scoped to the whole execution (see [Per-execution resources](#per-execution-resources)).
|
|
83
|
+
|
|
84
|
+
`requiresApproval: true` pauses the run for [approval](./approvals.md). `revert` enables [rollback](./runtime.md#rollback). Everything else executes immediately and is recorded in the durable log.
|
|
85
|
+
|
|
86
|
+
AI SDK tools are shape-compatible — an existing `ToolSet` can be returned from `tools()` directly:
|
|
87
|
+
|
|
88
|
+
```ts
|
|
89
|
+
export class LinearConnector extends CodemodeConnector<Env> {
|
|
90
|
+
name() {
|
|
91
|
+
return "linear";
|
|
92
|
+
}
|
|
93
|
+
protected tools() {
|
|
94
|
+
return linearTools; // an AI SDK ToolSet
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### RPC surface (derived — you don't implement this)
|
|
100
|
+
|
|
101
|
+
The proxy tool talks to connectors over Workers RPC. The base class derives this wire surface from the tools record:
|
|
102
|
+
|
|
103
|
+
- `describe()` — name, instructions, descriptors, annotations
|
|
104
|
+
- `getTypeScriptTypes()` — TypeScript declarations for describe
|
|
105
|
+
- `executeTool(method, args, ctx?)` — dispatch to the tool's `execute`
|
|
106
|
+
- `revertAction(method, args, result, ctx?)` — dispatch to the tool's `revert`
|
|
107
|
+
|
|
108
|
+
## Per-execution resources
|
|
109
|
+
|
|
110
|
+
Some connectors own a resource that must live for the lifetime of one run — a browser/CDP session, a database transaction, a temp workspace. Two pieces of the contract make this work:
|
|
111
|
+
|
|
112
|
+
1. **`execute(args, ctx)`** receives the `executionId`. Use it to lazily acquire (or reconnect to) the resource on first use, keyed by that id. Because the id is stable across pause/resume, the resource is addressable even after a run pauses for approval and resumes in a later Worker invocation. `ctx` is typed optional (so AI SDK toolsets stay shape-compatible), so read it as `ctx?.executionId` — the runtime always provides it on a real call.
|
|
113
|
+
2. **`disposeExecution(executionId, status)`** is called when the run reaches a **terminal** state, so you can tear the resource down.
|
|
114
|
+
|
|
115
|
+
```ts
|
|
116
|
+
export class BrowserConnector extends CodemodeConnector<Env> {
|
|
117
|
+
name() {
|
|
118
|
+
return "browser";
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
protected tools() {
|
|
122
|
+
return {
|
|
123
|
+
navigate: {
|
|
124
|
+
description: "Open a URL in the run's browser session.",
|
|
125
|
+
execute: async ({ url }, ctx) => {
|
|
126
|
+
const session = await this.sessionFor(ctx?.executionId);
|
|
127
|
+
return session.goto(url);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Fires on completed / error / rejected / rolled_back — never on pause.
|
|
134
|
+
override async disposeExecution(
|
|
135
|
+
executionId: string,
|
|
136
|
+
_status: ExecutionEndStatus
|
|
137
|
+
) {
|
|
138
|
+
await this.closeSessionFor(executionId);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
`disposeExecution` is deliberately **not** called when a run pauses for approval — a paused run may resume, so a resource scoped to the whole run must survive the pause. It fires for **every** connector in the runtime on each terminal transition, not just the ones a run used, so a connector that opened nothing should find nothing to close. `status` is one of:
|
|
144
|
+
|
|
145
|
+
| `ExecutionEndStatus` | When |
|
|
146
|
+
| -------------------- | ----------------------------------------- |
|
|
147
|
+
| `completed` | the run finished and returned a result |
|
|
148
|
+
| `error` | the run threw or hit a replay divergence |
|
|
149
|
+
| `rejected` | a pending action was rejected by the user |
|
|
150
|
+
| `rolled_back` | the run's applied effects were reverted |
|
|
151
|
+
|
|
152
|
+
Implementation rules (the default is a no-op, so connectors with no per-run state skip it):
|
|
153
|
+
|
|
154
|
+
- **Idempotent.** It fires on each terminal transition, so it can run more than once for one execution — a `completed` run that is later rolled back disposes twice. The second call should no-op.
|
|
155
|
+
- **No instance memory.** It may run on a different connector instance than the one that opened the resource (the host can reconstruct connectors per request, and the opening pass may have hibernated). Read what you need from durable storage keyed by `executionId`.
|
|
156
|
+
- **Never throws.** Teardown failures must not turn a finished run into a failure; the runtime ignores rejections from this hook.
|
|
157
|
+
|
|
158
|
+
> To abandon a paused run and release its resources, [`reject`](./approvals.md) the pending action — that's a terminal transition and fires `disposeExecution`. Stale paused runs nobody answers can be reclaimed in bulk with [`runtime.expirePaused`](./runtime.md#retention). (`rollback` only fires `disposeExecution` when it actually reverts an effect; a paused, read-only run isn't terminated by rollback.)
|
|
159
|
+
|
|
160
|
+
### Per-pass resources
|
|
161
|
+
|
|
162
|
+
`onPassEnd(executionId, status)` fires at the end of **every** execution pass — including a pass that ends in a pause, where `disposeExecution` deliberately does not fire. Use it to release per-pass resources: an open socket, a lease, an in-memory cache entry. `status` is an `ExecutionEndStatus` or `"paused"`. On a terminal pass, `onPassEnd` fires first, then `disposeExecution`.
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
// Keep the browser session (per-execution) across a pause, but close the
|
|
166
|
+
// CDP socket (per-pass) — the resume pass reconnects.
|
|
167
|
+
override async onPassEnd(executionId: string, _status: PassEndStatus) {
|
|
168
|
+
await this.closeSocketFor(executionId);
|
|
169
|
+
}
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
The same implementation rules as `disposeExecution` apply: idempotent, no instance memory, never throws.
|
|
173
|
+
|
|
174
|
+
> **AI SDK toolsets:** when `tools()` returns an AI SDK `ToolSet`, codemode passes `{ executionId }` as the tool's second `execute` argument — the slot the AI SDK uses for its own call options. Inside codemode those options aren't otherwise populated, but a tool authored against the AI SDK's `toolCallId`/`messages` won't receive them here.
|
|
175
|
+
|
|
176
|
+
## Replay policy
|
|
177
|
+
|
|
178
|
+
By default every call's result is recorded in the durable log and replayed on resume. A tool whose results are large and cheap to recompute can opt out with `replay: "reexecute"`:
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
protected tools(): ConnectorTools {
|
|
182
|
+
return {
|
|
183
|
+
read_file: {
|
|
184
|
+
description: "Read a file from the workspace.",
|
|
185
|
+
replay: "reexecute", // ephemeral: re-runs on replay, result never stored
|
|
186
|
+
execute: ({ path }) => this.fs.read(path)
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
The call is still logged (for sequencing and divergence detection), but its result stays out of the durable log and a replay **re-executes** it. Only use this for idempotent reads — the call runs again on every resume pass, and the value may legitimately differ across passes (which the code must tolerate). `replay: "reexecute"` cannot be combined with `requiresApproval`: an approved side effect must be logged, never re-executed.
|
|
193
|
+
|
|
194
|
+
## McpConnector
|
|
195
|
+
|
|
196
|
+
Wraps an MCP server. Each MCP tool becomes one entry in the tools record, executing through `connection.client.callTool()`. Tool names are sanitized into valid JS identifiers.
|
|
197
|
+
|
|
198
|
+
Implement `createConnection()`; decorate derived tools with the `tool(name, t)` hook:
|
|
199
|
+
|
|
200
|
+
```ts
|
|
201
|
+
import {
|
|
202
|
+
McpConnector,
|
|
203
|
+
type McpConnectionLike,
|
|
204
|
+
type ConnectorTool
|
|
205
|
+
} from "@cloudflare/codemode";
|
|
206
|
+
|
|
207
|
+
export class GithubConnector extends McpConnector<Env> {
|
|
208
|
+
constructor(
|
|
209
|
+
ctx: ExecutionContext,
|
|
210
|
+
env: Env,
|
|
211
|
+
private conn: McpConnectionLike
|
|
212
|
+
) {
|
|
213
|
+
super(ctx, env);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
name() {
|
|
217
|
+
return "github";
|
|
218
|
+
}
|
|
219
|
+
protected instructions() {
|
|
220
|
+
return "Use for GitHub operations.";
|
|
221
|
+
}
|
|
222
|
+
protected createConnection() {
|
|
223
|
+
return this.conn;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
protected tool(name: string, t: ConnectorTool): ConnectorTool {
|
|
227
|
+
if (name === "create_issue") {
|
|
228
|
+
return {
|
|
229
|
+
...t,
|
|
230
|
+
requiresApproval: true,
|
|
231
|
+
revert: (_args, result) => this.closeIssue(result)
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
return t;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
| Method | Purpose |
|
|
240
|
+
| -------------------- | -------------------------------------------------------------------- |
|
|
241
|
+
| `createConnection()` | Required. Return an MCP connection. |
|
|
242
|
+
| `toolName(tool)` | Override to customize how MCP tool names map to sandbox identifiers. |
|
|
243
|
+
|
|
244
|
+
Sandbox sees one method per MCP tool:
|
|
245
|
+
|
|
246
|
+
```ts
|
|
247
|
+
github.list_pull_requests({ owner, repo, state });
|
|
248
|
+
github.search_issues({ query });
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
## OpenApiConnector
|
|
252
|
+
|
|
253
|
+
Wraps an OpenAPI spec. The base reads the spec **once, host-side** and derives one typed tool **per operation**, so the model calls operations directly — `stripe.CreatePaymentIntent({ amount, currency })` — discoverable through `codemode.search`/`describe` with real input types. Deriving on the host costs zero prompt tokens. Override two methods:
|
|
254
|
+
|
|
255
|
+
- `spec()` returns the OpenAPI document (used to derive operations).
|
|
256
|
+
- `request()` performs an authenticated request.
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
import {
|
|
260
|
+
OpenApiConnector,
|
|
261
|
+
type OpenApiRequestOptions
|
|
262
|
+
} from "@cloudflare/codemode";
|
|
263
|
+
|
|
264
|
+
export class StripeConnector extends OpenApiConnector<Env> {
|
|
265
|
+
name() {
|
|
266
|
+
return "stripe";
|
|
267
|
+
}
|
|
268
|
+
protected instructions() {
|
|
269
|
+
return "Use for Stripe payments. Call the per-operation tools directly.";
|
|
270
|
+
}
|
|
271
|
+
protected spec() {
|
|
272
|
+
return stripeOpenApiSpec;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
protected request(options: OpenApiRequestOptions) {
|
|
276
|
+
return fetch(`https://api.stripe.com${options.path}`, {
|
|
277
|
+
method: options.method ?? "GET",
|
|
278
|
+
headers: { Authorization: `Bearer ${this.env.STRIPE_KEY}` },
|
|
279
|
+
body: options.body ? JSON.stringify(options.body) : undefined
|
|
280
|
+
}).then((r) => r.json());
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
| Method | Purpose |
|
|
286
|
+
| ------------------ | ----------------------------------------------------------------------------------------------- |
|
|
287
|
+
| `spec()` | Required. Return the OpenAPI spec document. May be async. Operations are derived from it. |
|
|
288
|
+
| `request(options)` | Required. Perform an authenticated request. Receives `{ path, method, params, body, headers }`. |
|
|
289
|
+
| `exposeSpec()` | Optional. Return `true` to also expose the raw `spec` document as a tool. Off by default. |
|
|
290
|
+
|
|
291
|
+
Each derived tool takes a single object: top-level keys are the operation's path/query/header parameters, plus a `body` key when the operation has a JSON request body. The base substitutes path params and hands `request()` a clean `{ path, method, params, body, headers }`. Local `$ref`s in the spec are inlined so the generated input types are usable. A low-level `request` tool is also exposed as an escape hatch for operations a derived tool can't reach.
|
|
292
|
+
|
|
293
|
+
Sandbox sees:
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
// Path params are substituted; the body is a typed object.
|
|
297
|
+
const intent = await stripe.CreatePaymentIntent({
|
|
298
|
+
amount: 2000,
|
|
299
|
+
currency: "usd"
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
// Escape hatch, if needed:
|
|
303
|
+
const raw = await stripe.request({
|
|
304
|
+
path: "/v1/charges",
|
|
305
|
+
method: "GET"
|
|
306
|
+
});
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
## Constructor convention
|
|
310
|
+
|
|
311
|
+
Constructors are for **dependencies** — connections, tokens, clients. Service identity and behavior come from overridable methods, not constructor config.
|
|
312
|
+
|
|
313
|
+
```ts
|
|
314
|
+
// Good — constructor receives dependency
|
|
315
|
+
export class GithubConnector extends McpConnector<Env> {
|
|
316
|
+
constructor(
|
|
317
|
+
ctx: ExecutionContext,
|
|
318
|
+
env: Env,
|
|
319
|
+
private conn: McpConnectionLike
|
|
320
|
+
) {
|
|
321
|
+
super(ctx, env);
|
|
322
|
+
}
|
|
323
|
+
name() {
|
|
324
|
+
return "github";
|
|
325
|
+
}
|
|
326
|
+
protected createConnection() {
|
|
327
|
+
return this.conn;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// Also good — reads from env
|
|
332
|
+
export class StripeConnector extends OpenApiConnector<Env> {
|
|
333
|
+
name() {
|
|
334
|
+
return "stripe";
|
|
335
|
+
}
|
|
336
|
+
protected spec() {
|
|
337
|
+
return stripeSpec;
|
|
338
|
+
}
|
|
339
|
+
protected async request(options: OpenApiRequestOptions) {
|
|
340
|
+
// Uses this.env.STRIPE_KEY
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
```
|