Open History to see the last commit
1/**
2 * Host-tool delegation for the CO-LOCATED ("combined") sandbox model.
3 *
4 * In the co-located model the harness loop AND its MCP tool-bridge run INSIDE
5 * the container (the in-container sandbox is just `local-process`, so the
6 * existing adapter + `nodeHttpBridgeProvisioner` serve the bridge on the
7 * container's own `localhost` with native stdin — nothing new there). The one
8 * thing that still must cross the container→orchestrator boundary is the
9 * **execution** of `chat()`-provided server tools: their `execute()` closures
10 * (DB / secrets / app state) live in the orchestrator, not the container.
11 *
12 * This module is that narrow seam:
13 * - {@link remoteToolStubs} (container side) rebuilds `chat()` tools from
14 * serialized {@link ToolDescriptor}s; each stub's `execute` delegates to a
15 * {@link RemoteToolExecutor} instead of running locally. The adapter bridges
16 * these stubs exactly like real tools.
17 * - {@link httpRemoteToolExecutor} (container side) is the default executor: it
18 * POSTs `{ name, args }` to the orchestrator's tool-exec endpoint.
19 * - {@link executeHostTool} (orchestrator side) runs the REAL tool and returns
20 * its raw result — the only host code the container can reach.
21 *
22 * So the public network surface shrinks from "the whole MCP protocol" (served
23 * from the orchestrator in the DO-drives-container model) to "one authenticated
24 * tool-exec call" — the MCP transport itself never leaves the container.
25 */
26import type { AnyTool } from '@tanstack/ai'
27import type { ToolDescriptor } from './tool-bridge'
28
29/** Per-call options forwarded to a {@link RemoteToolExecutor}. */
30export interface RemoteToolExecuteOptions {
31 /** Cancels the in-flight remote call when the in-container run aborts. */
32 signal?: AbortSignal
33}
34
35/** Runs a named host tool with the given args, returning its raw result. */
36export interface RemoteToolExecutor {
37 execute: (
38 name: string,
39 args: unknown,
40 options?: RemoteToolExecuteOptions,
41 ) => Promise<unknown>
42}
43
44/** Wire shape of a tool-exec request the container POSTs to the orchestrator. */
45export interface ToolExecRequest {
46 name: string
47 args: unknown
48}
49
50/** Narrow an unknown body into a {@link ToolExecRequest} (project rule: no `as`). */
51export function isToolExecRequest(value: unknown): value is ToolExecRequest {
52 return (
53 value !== null &&
54 typeof value === 'object' &&
55 'name' in value &&
56 typeof value.name === 'string'
57 )
58}
59
60/**
61 * Rebuild `chat()` tool objects (container side) from serialized descriptors.
62 * Each stub advertises the descriptor's JSON-schema and delegates `execute` to
63 * the executor; the harness adapter bridges them like any other tool. The
64 * harness's `abortSignal` is forwarded so a cancelled run cancels the in-flight
65 * remote call too.
66 */
67export function remoteToolStubs(
68 descriptors: Array<ToolDescriptor>,
69 executor: RemoteToolExecutor,
70): Array<AnyTool> {
71 return descriptors.map((descriptor) => ({
72 name: descriptor.name,
73 description: descriptor.description ?? '',
74 inputSchema: descriptor.inputSchema,
75 execute: (args: unknown, options?: { abortSignal?: AbortSignal }) =>
76 executor.execute(
77 descriptor.name,
78 args,
79 options?.abortSignal !== undefined
80 ? { signal: options.abortSignal }
81 : {},
82 ),
83 }))
84}
85
86/**
87 * Serialize `chat()` tools to wire descriptors to send into the container.
88 * `inputSchema` must already be a plain JSON-schema object (convert Standard
89 * Schemas before calling, the same way harness adapters advertise tools).
90 */
91export function toolDescriptors(tools: Array<AnyTool>): Array<ToolDescriptor> {
92 return tools.map((tool) => ({
93 name: tool.name,
94 description: tool.description,
95 inputSchema: isJsonSchemaObject(tool.inputSchema)
96 ? tool.inputSchema
97 : { type: 'object', properties: {} },
98 }))
99}
100
101function isJsonSchemaObject(
102 value: unknown,
103): value is { type: 'object'; [key: string]: unknown } {
104 return (
105 value !== null &&
106 typeof value === 'object' &&
107 'type' in value &&
108 (value as { type?: unknown }).type === 'object'
109 )
110}
111
112/** Wire shape of a tool-exec response from the orchestrator. */
113interface ToolExecResponse {
114 result: unknown
115}
116
117function isToolExecResponse(value: unknown): value is ToolExecResponse {
118 return value !== null && typeof value === 'object' && 'result' in value
119}
120
121/**
122 * The default {@link RemoteToolExecutor}: POST `{ name, args }` (bearer-gated)
123 * to the orchestrator's tool-exec endpoint and return its `result`. A non-2xx
124 * or malformed response throws (surfaced to the agent as a failed tool call by
125 * the bridge) — never silently swallowed.
126 */
127export function httpRemoteToolExecutor(
128 url: string,
129 token: string,
130): RemoteToolExecutor {
131 return {
132 async execute(name, args, options) {
133 const res = await fetch(url, {
134 method: 'POST',
135 headers: {
136 'content-type': 'application/json',
137 authorization: `Bearer ${token}`,
138 },
139 body: JSON.stringify({ name, args }),
140 ...(options?.signal !== undefined ? { signal: options.signal } : {}),
141 })
142 if (!res.ok) {
143 const text = await res.text()
144 throw new Error(
145 `remote tool "${name}" failed: ${res.status} ${text.slice(0, 200)}`,
146 )
147 }
148 const body: unknown = await res.json()
149 if (!isToolExecResponse(body)) {
150 throw new Error(
151 `remote tool "${name}": malformed orchestrator response`,
152 )
153 }
154 return body.result
155 },
156 }
157}
158
159/**
160 * Run a host tool by name with the given args, returning its raw result
161 * (orchestrator side of {@link httpRemoteToolExecutor}). Throws for an unknown
162 * tool or one with no `execute` — the orchestrator surfaces that as a 4xx/5xx.
163 */
164export function executeHostTool(
165 tools: Array<AnyTool>,
166 name: string,
167 args: unknown,
168 options: { context?: unknown; signal?: AbortSignal } = {},
169): Promise<unknown> {
170 const tool = tools.find((candidate) => candidate.name === name)
171 if (!tool?.execute) {
172 return Promise.reject(new Error(`Unknown tool: ${name}`))
173 }
174 return Promise.resolve(
175 tool.execute(args ?? {}, {
176 context: options.context,
177 abortSignal: options.signal,
178 }),
179 )
180}