@catamorphic/ai-sdk 0.0.0-stage → 0.1.0-alpha.30
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/LICENSE.txt +202 -0
- package/NOTICE.txt +32 -0
- package/README.md +73 -2
- package/dist/adapter.d.ts +86 -0
- package/dist/adapter.d.ts.map +1 -0
- package/dist/errors.d.ts +18 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2166 -0
- package/dist/index.js.map +15 -0
- package/dist/shell.d.ts +88 -0
- package/dist/shell.d.ts.map +1 -0
- package/dist/telemetry.d.ts +22 -0
- package/dist/telemetry.d.ts.map +1 -0
- package/dist/testing/index.d.ts +123 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +211 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/thread.d.ts +71 -0
- package/dist/thread.d.ts.map +1 -0
- package/dist/tools.d.ts +148 -0
- package/dist/tools.d.ts.map +1 -0
- package/package.json +67 -4
- package/src/adapter.ts +1378 -0
- package/src/errors.ts +83 -0
- package/src/index.ts +23 -0
- package/src/shell.ts +470 -0
- package/src/telemetry.ts +295 -0
- package/src/testing/index.ts +349 -0
- package/src/thread.ts +209 -0
- package/src/tools.ts +740 -0
package/src/tools.ts
ADDED
|
@@ -0,0 +1,740 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import type {
|
|
4
|
+
HostToolDescriptor,
|
|
5
|
+
HostToolResult,
|
|
6
|
+
} from "@catamorphic/agent-protocol/runner";
|
|
7
|
+
import {
|
|
8
|
+
type ConnectedMcpServer,
|
|
9
|
+
flattenToolResult,
|
|
10
|
+
type McpToolInfo,
|
|
11
|
+
} from "@catamorphic/mcp";
|
|
12
|
+
import {
|
|
13
|
+
agentQuestionInputSchema,
|
|
14
|
+
agentToolResult,
|
|
15
|
+
extraToolResult,
|
|
16
|
+
type SandboxProvider,
|
|
17
|
+
} from "@catamorphic/sandbox";
|
|
18
|
+
import { dynamicTool, jsonSchema, type Tool, tool } from "ai";
|
|
19
|
+
import { z } from "zod";
|
|
20
|
+
import { type ShellProvider, type ShellState, shellTools } from "./shell.js";
|
|
21
|
+
|
|
22
|
+
const MAX_TOOL_OUTPUT_LENGTH = 100_000;
|
|
23
|
+
const EXA_MCP_URL = "https://mcp.exa.ai/mcp";
|
|
24
|
+
const WEBFETCH_MAX_BYTES = 5 * 1024 * 1024;
|
|
25
|
+
const WEBFETCH_TIMEOUT_MS = 30_000;
|
|
26
|
+
|
|
27
|
+
/** The sandbox surface the built-in file and shell tools run on. */
|
|
28
|
+
export type AiSdkSandboxProvider = ShellProvider &
|
|
29
|
+
Pick<SandboxProvider, "uploadFiles" | "downloadFile">;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* What a model tool name stands for, so its calls become the right
|
|
33
|
+
* transcript items: shell commands, file changes, or tool calls.
|
|
34
|
+
*/
|
|
35
|
+
export type ToolMeta =
|
|
36
|
+
| { kind: "command" }
|
|
37
|
+
| { kind: "file"; change: "modified" | null }
|
|
38
|
+
| { kind: "title" }
|
|
39
|
+
| { kind: "ask" }
|
|
40
|
+
| { kind: "tool"; server: string | null; source: "builtin" }
|
|
41
|
+
| { kind: "tool"; server: string; source: "host" | "mcp" };
|
|
42
|
+
|
|
43
|
+
export interface ToolSetWithMeta {
|
|
44
|
+
tools: Record<string, Tool>;
|
|
45
|
+
meta: Map<string, ToolMeta>;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface WorkspaceToolContext {
|
|
49
|
+
provider: AiSdkSandboxProvider;
|
|
50
|
+
sandboxId: string;
|
|
51
|
+
workingDirectory: string;
|
|
52
|
+
/** Read-only directories beside the working directory. */
|
|
53
|
+
readableRoots: readonly string[];
|
|
54
|
+
/** Where the next shell command starts and this chat's background commands. */
|
|
55
|
+
shell: ShellState;
|
|
56
|
+
/** The Environment's budget for one foreground command (ADR 0174). */
|
|
57
|
+
budgetSeconds?: number;
|
|
58
|
+
/**
|
|
59
|
+
* The session's environment files, which every command loads (ADRs
|
|
60
|
+
* 0206, 0212).
|
|
61
|
+
*/
|
|
62
|
+
envFiles?: readonly string[];
|
|
63
|
+
/** Fires when the agent should stop waiting (ADR 0264). */
|
|
64
|
+
stopWaiting(): AbortSignal;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const ASK_USER_DESCRIPTION = `Ask the user one or more questions. When the tool allows blocking=false, use it to continue independent work while awaiting answers. ALWAYS use this tool instead of writing questions as plain text whenever you are asking the user something and their answer shapes what you do next. Use it when (1) you are blocked on a decision that is genuinely the user's to make, one you cannot resolve from the request, the project, or sensible defaults, e.g. choosing between data sources, schedules, external services, or destructive vs. safe variants of an operation; or (2) the user asks you to interview them, gather their preferences, or otherwise requests that you ask them questions. A request like "ask me some questions" should go through this tool, batching up to 4 questions per call and calling it again for follow-ups. For routine implementation choices, pick a sensible default and state it instead of asking. Each option needs a concise label and a description explaining its effects, implications, or trade-offs; for open-ended questions offer plausible example answers as options. The user can always answer with free text instead of picking one. If you recommend an option, make it the first one and append " (Recommended)" to its label. Do not use it to ask "should I proceed?" or to confirm work you already described.`;
|
|
68
|
+
|
|
69
|
+
const SET_TITLE_DESCRIPTION =
|
|
70
|
+
"Set the title of this conversation as shown in the user's chat list and tabs. Call it once near the start of a new conversation with a concise, specific title (2-5 words, sentence case, no trailing punctuation) describing what the conversation is about. Call it again whenever the current title no longer describes the conversation: the topic moved on, the scope changed, or the original title turned out to be wrong. Don't re-title for minor detours. Examples: 'Daily sales report workflow', 'Drafting onboarding doc', 'Fixing checkout bug', 'Getting to know you'.";
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The tools every attempt has: the conversation title, questions, and web
|
|
74
|
+
* access. `ask` runs one question batch and returns what the model reads.
|
|
75
|
+
*/
|
|
76
|
+
export function conversationTools(input: {
|
|
77
|
+
ask: (args: {
|
|
78
|
+
questions: z.output<typeof agentQuestionInputSchema>["questions"];
|
|
79
|
+
blocking: boolean;
|
|
80
|
+
toolCallId: string;
|
|
81
|
+
abortSignal?: AbortSignal;
|
|
82
|
+
}) => Promise<string>;
|
|
83
|
+
}): ToolSetWithMeta {
|
|
84
|
+
return {
|
|
85
|
+
tools: {
|
|
86
|
+
set_title: tool({
|
|
87
|
+
description: SET_TITLE_DESCRIPTION,
|
|
88
|
+
inputSchema: z.object({
|
|
89
|
+
title: z
|
|
90
|
+
.string()
|
|
91
|
+
.min(1)
|
|
92
|
+
.max(80)
|
|
93
|
+
.describe("The new conversation title (2-5 words)"),
|
|
94
|
+
}),
|
|
95
|
+
execute: async ({ title }) => `Conversation titled: ${title}`,
|
|
96
|
+
}),
|
|
97
|
+
ask_user: tool({
|
|
98
|
+
description: ASK_USER_DESCRIPTION,
|
|
99
|
+
inputSchema: agentQuestionInputSchema,
|
|
100
|
+
execute: ({ questions, blocking }, { toolCallId, abortSignal }) =>
|
|
101
|
+
input.ask({
|
|
102
|
+
questions,
|
|
103
|
+
blocking,
|
|
104
|
+
toolCallId,
|
|
105
|
+
...(abortSignal ? { abortSignal } : {}),
|
|
106
|
+
}),
|
|
107
|
+
}),
|
|
108
|
+
websearch: tool({
|
|
109
|
+
description:
|
|
110
|
+
"Search the web and return results with content excerpts optimized for reading. Use it for up-to-date information, documentation, or anything outside the project.",
|
|
111
|
+
inputSchema: z.object({
|
|
112
|
+
query: z.string().describe("Web search query"),
|
|
113
|
+
numResults: z
|
|
114
|
+
.number()
|
|
115
|
+
.int()
|
|
116
|
+
.positive()
|
|
117
|
+
.max(20)
|
|
118
|
+
.optional()
|
|
119
|
+
.describe("Number of results to return (default 8)"),
|
|
120
|
+
}),
|
|
121
|
+
execute: async ({ query, numResults }) =>
|
|
122
|
+
truncateToolOutput(await exaWebSearch(query, numResults ?? 8)),
|
|
123
|
+
}),
|
|
124
|
+
webfetch: tool({
|
|
125
|
+
description:
|
|
126
|
+
"Fetch a URL and return its content as text. Use it to read pages found via websearch or URLs provided by the user.",
|
|
127
|
+
inputSchema: z.object({
|
|
128
|
+
url: z.string().describe("The http(s) URL to fetch"),
|
|
129
|
+
}),
|
|
130
|
+
execute: async ({ url }) => truncateToolOutput(await webFetch(url)),
|
|
131
|
+
}),
|
|
132
|
+
},
|
|
133
|
+
meta: new Map<string, ToolMeta>([
|
|
134
|
+
["set_title", { kind: "title" }],
|
|
135
|
+
["ask_user", { kind: "ask" }],
|
|
136
|
+
["websearch", { kind: "tool", server: null, source: "builtin" }],
|
|
137
|
+
["webfetch", { kind: "tool", server: null, source: "builtin" }],
|
|
138
|
+
]),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* The project tools on the session's sandbox: `read`, `write`, `edit`, and
|
|
144
|
+
* the shell (`bash`, plus background commands where the sandbox runs
|
|
145
|
+
* processes). Paths never escape the working directory, except reads of
|
|
146
|
+
* the host's read-only roots.
|
|
147
|
+
*/
|
|
148
|
+
export function workspaceTools(context: WorkspaceToolContext): ToolSetWithMeta {
|
|
149
|
+
let mutationQueue = Promise.resolve();
|
|
150
|
+
const serializeMutation = async <T>(operation: () => Promise<T>) => {
|
|
151
|
+
const result = mutationQueue.then(operation, operation);
|
|
152
|
+
mutationQueue = result.then(
|
|
153
|
+
() => undefined,
|
|
154
|
+
() => undefined,
|
|
155
|
+
);
|
|
156
|
+
return result;
|
|
157
|
+
};
|
|
158
|
+
const resolveReadablePath = (filePath: string): string => {
|
|
159
|
+
const resolved = path.posix.resolve(
|
|
160
|
+
path.posix.resolve(context.workingDirectory),
|
|
161
|
+
filePath,
|
|
162
|
+
);
|
|
163
|
+
if (context.readableRoots.some((root) => within(resolved, root)))
|
|
164
|
+
return resolved;
|
|
165
|
+
return resolveProjectPath(context.workingDirectory, filePath);
|
|
166
|
+
};
|
|
167
|
+
const relative = (absolutePath: string) =>
|
|
168
|
+
path.posix.relative(context.workingDirectory, absolutePath);
|
|
169
|
+
|
|
170
|
+
const shell = shellTools({
|
|
171
|
+
provider: context.provider,
|
|
172
|
+
sandboxId: context.sandboxId,
|
|
173
|
+
root: () => context.workingDirectory,
|
|
174
|
+
state: context.shell,
|
|
175
|
+
...(context.budgetSeconds ? { budgetSeconds: context.budgetSeconds } : {}),
|
|
176
|
+
...(context.envFiles ? { envFiles: context.envFiles } : {}),
|
|
177
|
+
stopWaiting: context.stopWaiting,
|
|
178
|
+
});
|
|
179
|
+
const tools: Record<string, Tool> = {
|
|
180
|
+
read: tool({
|
|
181
|
+
description:
|
|
182
|
+
"Read a UTF-8 text file from the project, or a file the user attached by its absolute path.",
|
|
183
|
+
inputSchema: z.object({
|
|
184
|
+
path: z.string().describe("Project-relative or absolute file path"),
|
|
185
|
+
}),
|
|
186
|
+
execute: async ({ path: filePath }) =>
|
|
187
|
+
truncateToolOutput(
|
|
188
|
+
await context.provider.downloadFile(
|
|
189
|
+
context.sandboxId,
|
|
190
|
+
resolveReadablePath(filePath),
|
|
191
|
+
),
|
|
192
|
+
),
|
|
193
|
+
}),
|
|
194
|
+
write: tool({
|
|
195
|
+
description: "Create or replace a UTF-8 text file in the project.",
|
|
196
|
+
inputSchema: z.object({
|
|
197
|
+
path: z.string().describe("Project-relative or absolute file path"),
|
|
198
|
+
content: z.string(),
|
|
199
|
+
}),
|
|
200
|
+
execute: async ({ path: filePath, content }) =>
|
|
201
|
+
serializeMutation(async () => {
|
|
202
|
+
const relativePath = relative(
|
|
203
|
+
resolveProjectPath(context.workingDirectory, filePath),
|
|
204
|
+
);
|
|
205
|
+
await context.provider.uploadFiles(
|
|
206
|
+
context.sandboxId,
|
|
207
|
+
{ [relativePath]: content },
|
|
208
|
+
context.workingDirectory,
|
|
209
|
+
);
|
|
210
|
+
return `Wrote ${relativePath}`;
|
|
211
|
+
}),
|
|
212
|
+
}),
|
|
213
|
+
edit: tool({
|
|
214
|
+
description: "Replace one exact string occurrence in a project file.",
|
|
215
|
+
inputSchema: z.object({
|
|
216
|
+
path: z.string().describe("Project-relative or absolute file path"),
|
|
217
|
+
oldText: z.string().describe("Exact text to replace"),
|
|
218
|
+
newText: z.string().describe("Replacement text"),
|
|
219
|
+
}),
|
|
220
|
+
execute: async ({ path: filePath, oldText, newText }) =>
|
|
221
|
+
serializeMutation(async () => {
|
|
222
|
+
const absolutePath = resolveProjectPath(
|
|
223
|
+
context.workingDirectory,
|
|
224
|
+
filePath,
|
|
225
|
+
);
|
|
226
|
+
const content = await context.provider.downloadFile(
|
|
227
|
+
context.sandboxId,
|
|
228
|
+
absolutePath,
|
|
229
|
+
);
|
|
230
|
+
const first = content.indexOf(oldText);
|
|
231
|
+
if (first === -1) throw new Error(`Text not found in ${filePath}`);
|
|
232
|
+
if (content.indexOf(oldText, first + oldText.length) !== -1)
|
|
233
|
+
throw new Error(`Text occurs more than once in ${filePath}`);
|
|
234
|
+
const updated = `${content.slice(0, first)}${newText}${content.slice(first + oldText.length)}`;
|
|
235
|
+
const relativePath = relative(absolutePath);
|
|
236
|
+
await context.provider.uploadFiles(
|
|
237
|
+
context.sandboxId,
|
|
238
|
+
{ [relativePath]: updated },
|
|
239
|
+
context.workingDirectory,
|
|
240
|
+
);
|
|
241
|
+
return `Edited ${relativePath}`;
|
|
242
|
+
}),
|
|
243
|
+
}),
|
|
244
|
+
...shell,
|
|
245
|
+
};
|
|
246
|
+
const meta = new Map<string, ToolMeta>([
|
|
247
|
+
["read", { kind: "tool", server: null, source: "builtin" }],
|
|
248
|
+
["write", { kind: "file", change: null }],
|
|
249
|
+
["edit", { kind: "file", change: "modified" }],
|
|
250
|
+
["bash", { kind: "command" }],
|
|
251
|
+
]);
|
|
252
|
+
for (const name of Object.keys(shell))
|
|
253
|
+
if (!meta.has(name))
|
|
254
|
+
meta.set(name, { kind: "tool", server: null, source: "builtin" });
|
|
255
|
+
return { tools, meta };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** A project-relative or absolute path, kept inside the working directory. */
|
|
259
|
+
export function resolveProjectPath(
|
|
260
|
+
workingDirectory: string,
|
|
261
|
+
filePath: string,
|
|
262
|
+
): string {
|
|
263
|
+
const root = path.posix.resolve(workingDirectory);
|
|
264
|
+
const resolved = path.posix.resolve(root, filePath);
|
|
265
|
+
if (!within(resolved, root))
|
|
266
|
+
throw new Error(`Path escapes the project working directory: ${filePath}`);
|
|
267
|
+
return resolved;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function within(resolved: string, directory: string): boolean {
|
|
271
|
+
const root = path.posix.resolve(directory);
|
|
272
|
+
return resolved === root || resolved.startsWith(`${root}/`);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* The host's tools (ADR 0198 host calls): offered under their own names,
|
|
277
|
+
* run by the host. `call` returns MCP-shaped content; an `isError` result
|
|
278
|
+
* reads to the model as the tool's error.
|
|
279
|
+
*/
|
|
280
|
+
export function hostTools(input: {
|
|
281
|
+
descriptors: readonly HostToolDescriptor[];
|
|
282
|
+
call: (args: {
|
|
283
|
+
name: string;
|
|
284
|
+
input: unknown;
|
|
285
|
+
toolCallId: string;
|
|
286
|
+
abortSignal?: AbortSignal;
|
|
287
|
+
}) => Promise<HostToolResult>;
|
|
288
|
+
}): ToolSetWithMeta {
|
|
289
|
+
const tools: Record<string, Tool> = {};
|
|
290
|
+
const meta = new Map<string, ToolMeta>();
|
|
291
|
+
for (const descriptor of input.descriptors) {
|
|
292
|
+
tools[descriptor.name] = dynamicTool({
|
|
293
|
+
description: descriptor.description,
|
|
294
|
+
inputSchema: toolInputSchema(descriptor.inputSchema),
|
|
295
|
+
toModelOutput: ({ output }) => hostModelOutput(output),
|
|
296
|
+
execute: (args, { toolCallId, abortSignal }) =>
|
|
297
|
+
input.call({
|
|
298
|
+
name: descriptor.name,
|
|
299
|
+
input: args,
|
|
300
|
+
toolCallId,
|
|
301
|
+
...(abortSignal ? { abortSignal } : {}),
|
|
302
|
+
}),
|
|
303
|
+
});
|
|
304
|
+
meta.set(descriptor.name, {
|
|
305
|
+
kind: "tool",
|
|
306
|
+
server: descriptor.server ?? "workspace",
|
|
307
|
+
source: "host",
|
|
308
|
+
});
|
|
309
|
+
}
|
|
310
|
+
return { tools, meta };
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const hostToolResultSchema = z.object({
|
|
314
|
+
content: z.array(
|
|
315
|
+
z.discriminatedUnion("type", [
|
|
316
|
+
z.object({ type: z.literal("text"), text: z.string() }),
|
|
317
|
+
z.object({
|
|
318
|
+
type: z.literal("image"),
|
|
319
|
+
data: z.string(),
|
|
320
|
+
mimeType: z.string(),
|
|
321
|
+
}),
|
|
322
|
+
]),
|
|
323
|
+
),
|
|
324
|
+
structured: z.unknown().optional(),
|
|
325
|
+
isError: z.boolean().optional(),
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
/** A host tool's output, when it is one. */
|
|
329
|
+
export function parseHostToolResult(
|
|
330
|
+
output: unknown,
|
|
331
|
+
): z.output<typeof hostToolResultSchema> | undefined {
|
|
332
|
+
const parsed = hostToolResultSchema.safeParse(output);
|
|
333
|
+
return parsed.success ? parsed.data : undefined;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function hostModelOutput(output: unknown) {
|
|
337
|
+
const result = parseHostToolResult(output);
|
|
338
|
+
if (!result)
|
|
339
|
+
return { type: "text" as const, value: JSON.stringify(output ?? null) };
|
|
340
|
+
const text = result.content
|
|
341
|
+
.filter((part) => part.type === "text")
|
|
342
|
+
.map((part) => part.text)
|
|
343
|
+
.join("\n");
|
|
344
|
+
if (result.isError) return { type: "error-text" as const, value: text };
|
|
345
|
+
return {
|
|
346
|
+
type: "content" as const,
|
|
347
|
+
value: [
|
|
348
|
+
...result.content.map((part) =>
|
|
349
|
+
part.type === "image"
|
|
350
|
+
? {
|
|
351
|
+
type: "file" as const,
|
|
352
|
+
data: { type: "data" as const, data: part.data },
|
|
353
|
+
mediaType: part.mimeType,
|
|
354
|
+
}
|
|
355
|
+
: { type: "text" as const, text: truncateToolOutput(part.text) },
|
|
356
|
+
),
|
|
357
|
+
...(result.structured !== undefined &&
|
|
358
|
+
!result.content.some((part) => part.type === "text")
|
|
359
|
+
? [{ type: "text" as const, text: JSON.stringify(result.structured) }]
|
|
360
|
+
: []),
|
|
361
|
+
],
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Model APIs take tool names of at most 64 letters, digits, `_` and `-`. */
|
|
366
|
+
const MODEL_TOOL_NAME_MAX = 64;
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* The name the model calls an MCP tool by: `mcp__<server>__<tool>`, with
|
|
370
|
+
* what model APIs refuse (MCP allows dots, `chat.postMessage`) as `_`. A
|
|
371
|
+
* name that is too long, or already names another tool (`a.b` beside
|
|
372
|
+
* `a_b`), ends in a short hash of the server and tool instead.
|
|
373
|
+
*/
|
|
374
|
+
export function mcpModelToolName(args: {
|
|
375
|
+
server: string;
|
|
376
|
+
tool: string;
|
|
377
|
+
taken: Readonly<Record<string, unknown>>;
|
|
378
|
+
}): string {
|
|
379
|
+
const safeServer = args.server.replace(/[^A-Za-z0-9-]+/g, "_");
|
|
380
|
+
const safeTool = args.tool.replace(/[^A-Za-z0-9_-]+/g, "_");
|
|
381
|
+
const name = `mcp__${safeServer}__${safeTool}`;
|
|
382
|
+
if (name.length <= MODEL_TOOL_NAME_MAX && !Object.hasOwn(args.taken, name))
|
|
383
|
+
return name;
|
|
384
|
+
const hash = createHash("sha256")
|
|
385
|
+
.update(`${args.server}\0${args.tool}`)
|
|
386
|
+
.digest("hex")
|
|
387
|
+
.slice(0, 8);
|
|
388
|
+
return `${name.slice(0, MODEL_TOOL_NAME_MAX - hash.length - 1)}_${hash}`;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* MCP server tools as AI SDK dynamic tools named `mcp__<server>__<tool>`
|
|
393
|
+
* (the namespacing Claude Code uses, so transcripts read alike across
|
|
394
|
+
* harnesses). `authorize` runs before every call and throws to refuse it;
|
|
395
|
+
* the model reads the refusal as the tool's error and the turn goes on.
|
|
396
|
+
*/
|
|
397
|
+
export function mcpTools(input: {
|
|
398
|
+
servers: ReadonlyMap<string, ConnectedMcpServer>;
|
|
399
|
+
taken: Readonly<Record<string, unknown>>;
|
|
400
|
+
authorize: (args: {
|
|
401
|
+
server: string;
|
|
402
|
+
tool: McpToolInfo;
|
|
403
|
+
input: Record<string, unknown>;
|
|
404
|
+
toolCallId: string;
|
|
405
|
+
abortSignal?: AbortSignal;
|
|
406
|
+
}) => Promise<void>;
|
|
407
|
+
}): ToolSetWithMeta {
|
|
408
|
+
const tools: Record<string, Tool> = {};
|
|
409
|
+
const meta = new Map<string, ToolMeta>();
|
|
410
|
+
for (const [serverName, server] of input.servers) {
|
|
411
|
+
for (const info of server.tools) {
|
|
412
|
+
// Calls use `info.name`; the model sees a name its API accepts.
|
|
413
|
+
const name = mcpModelToolName({
|
|
414
|
+
server: serverName,
|
|
415
|
+
tool: info.name,
|
|
416
|
+
taken: { ...input.taken, ...tools },
|
|
417
|
+
});
|
|
418
|
+
meta.set(name, { kind: "tool", server: serverName, source: "mcp" });
|
|
419
|
+
tools[name] = dynamicTool({
|
|
420
|
+
description: info.description,
|
|
421
|
+
inputSchema: toolInputSchema(info.inputSchema),
|
|
422
|
+
toModelOutput: ({ output }) => mediaModelOutput(output),
|
|
423
|
+
execute: async (args, { toolCallId, abortSignal }) => {
|
|
424
|
+
const pruned = pruneEmptyOptionalArgs(
|
|
425
|
+
isRecord(args) ? args : {},
|
|
426
|
+
info.inputSchema,
|
|
427
|
+
);
|
|
428
|
+
await input.authorize({
|
|
429
|
+
server: serverName,
|
|
430
|
+
tool: info,
|
|
431
|
+
input: pruned,
|
|
432
|
+
toolCallId,
|
|
433
|
+
...(abortSignal ? { abortSignal } : {}),
|
|
434
|
+
});
|
|
435
|
+
abortSignal?.throwIfAborted();
|
|
436
|
+
return mcpCallResult(await server.callToolRaw(info.name, pruned));
|
|
437
|
+
},
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
return { tools, meta };
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Prefer structured content: MCP Apps views render it, and the model reads
|
|
446
|
+
* JSON fine. Media results keep their images for the model; text-only
|
|
447
|
+
* results stay text, and `flattenToolResult` throws on `isError` results.
|
|
448
|
+
*/
|
|
449
|
+
function mcpCallResult(raw: Record<string, unknown>): unknown {
|
|
450
|
+
const blocks = z.array(z.unknown()).parse(raw.content ?? []);
|
|
451
|
+
const media = blocks.flatMap((block) => {
|
|
452
|
+
const image = z
|
|
453
|
+
.object({
|
|
454
|
+
type: z.literal("image"),
|
|
455
|
+
data: z.string(),
|
|
456
|
+
mimeType: z.enum([
|
|
457
|
+
"image/png",
|
|
458
|
+
"image/jpeg",
|
|
459
|
+
"image/webp",
|
|
460
|
+
"image/gif",
|
|
461
|
+
]),
|
|
462
|
+
})
|
|
463
|
+
.safeParse(block);
|
|
464
|
+
return image.success ? [image.data] : [];
|
|
465
|
+
});
|
|
466
|
+
const isError = raw.isError === true;
|
|
467
|
+
if (media.length > 0 && !isError) {
|
|
468
|
+
const text = blocks.flatMap((block) => {
|
|
469
|
+
const part = z
|
|
470
|
+
.object({ type: z.literal("text"), text: z.string() })
|
|
471
|
+
.safeParse(block);
|
|
472
|
+
return part.success
|
|
473
|
+
? [{ type: "text" as const, text: truncateToolOutput(part.data.text) }]
|
|
474
|
+
: [];
|
|
475
|
+
});
|
|
476
|
+
if (raw.structuredContent !== undefined)
|
|
477
|
+
text.push({ type: "text", text: JSON.stringify(raw.structuredContent) });
|
|
478
|
+
return agentToolResult({ content: [...text, ...media] });
|
|
479
|
+
}
|
|
480
|
+
if (raw.structuredContent !== undefined && !isError)
|
|
481
|
+
return raw.structuredContent;
|
|
482
|
+
return truncateToolOutput(
|
|
483
|
+
flattenToolResult({
|
|
484
|
+
content: blocks.filter(isRecord),
|
|
485
|
+
...(raw.structuredContent !== undefined
|
|
486
|
+
? { structuredContent: raw.structuredContent }
|
|
487
|
+
: {}),
|
|
488
|
+
isError,
|
|
489
|
+
}),
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* A JSON Schema from a host or an MCP server as the AI SDK's tool input
|
|
495
|
+
* schema. Servers validate their own input; the model sees the schema as is.
|
|
496
|
+
*/
|
|
497
|
+
function toolInputSchema(schema: Record<string, unknown>) {
|
|
498
|
+
return jsonSchema<Record<string, unknown>>(
|
|
499
|
+
// JSON Schema arrives as data; the AI SDK types it as JSONSchema7.
|
|
500
|
+
schema as Parameters<typeof jsonSchema>[0],
|
|
501
|
+
);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/**
|
|
505
|
+
* Some models (OpenAI-family especially) fill every declared property and
|
|
506
|
+
* send `""`/`null` for the ones they have no value for; servers that
|
|
507
|
+
* validate optional fields then reject the call ("value is not a channel
|
|
508
|
+
* ID" for `context_channel_id: ""`, from Slack's search tool). Drop such
|
|
509
|
+
* values for optional properties, but ONLY when the property's own schema
|
|
510
|
+
* could not have meant them: a `null` a schema admits (`type: [...,
|
|
511
|
+
* "null"]`, `nullable`, an `anyOf` null branch, an `enum` with null) is a
|
|
512
|
+
* value ("clear this field"), and so is `""` on a plain string with no
|
|
513
|
+
* `format`/`pattern`/`minLength`/`enum` ruling it out. Unknown properties
|
|
514
|
+
* (no schema) keep the blanket rule.
|
|
515
|
+
*/
|
|
516
|
+
export function pruneEmptyOptionalArgs(
|
|
517
|
+
input: Record<string, unknown>,
|
|
518
|
+
schema: Record<string, unknown>,
|
|
519
|
+
): Record<string, unknown> {
|
|
520
|
+
const required = new Set(
|
|
521
|
+
Array.isArray(schema.required)
|
|
522
|
+
? schema.required.filter((key) => typeof key === "string")
|
|
523
|
+
: [],
|
|
524
|
+
);
|
|
525
|
+
const properties = isRecord(schema.properties) ? schema.properties : {};
|
|
526
|
+
const pruned: Record<string, unknown> = {};
|
|
527
|
+
for (const [key, value] of Object.entries(input)) {
|
|
528
|
+
if (required.has(key) || (value !== "" && value !== null)) {
|
|
529
|
+
pruned[key] = value;
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
const property = properties[key];
|
|
533
|
+
const schemaOf = isRecord(property) ? property : undefined;
|
|
534
|
+
const meaningful =
|
|
535
|
+
value === null
|
|
536
|
+
? schemaAdmitsNull(schemaOf)
|
|
537
|
+
: schemaAdmitsEmptyString(schemaOf);
|
|
538
|
+
if (meaningful) pruned[key] = value;
|
|
539
|
+
}
|
|
540
|
+
return pruned;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
function schemaAdmitsNull(
|
|
544
|
+
property: Record<string, unknown> | undefined,
|
|
545
|
+
): boolean {
|
|
546
|
+
if (!property) return false;
|
|
547
|
+
if (property.nullable === true) return true;
|
|
548
|
+
const type = property.type;
|
|
549
|
+
if (type === "null" || (Array.isArray(type) && type.includes("null")))
|
|
550
|
+
return true;
|
|
551
|
+
if (Array.isArray(property.enum) && property.enum.includes(null)) return true;
|
|
552
|
+
for (const branchKey of ["anyOf", "oneOf"] as const) {
|
|
553
|
+
const branches = property[branchKey];
|
|
554
|
+
if (
|
|
555
|
+
Array.isArray(branches) &&
|
|
556
|
+
branches.some((branch) =>
|
|
557
|
+
schemaAdmitsNull(isRecord(branch) ? branch : undefined),
|
|
558
|
+
)
|
|
559
|
+
)
|
|
560
|
+
return true;
|
|
561
|
+
}
|
|
562
|
+
return false;
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function schemaAdmitsEmptyString(
|
|
566
|
+
property: Record<string, unknown> | undefined,
|
|
567
|
+
): boolean {
|
|
568
|
+
if (!property) return false;
|
|
569
|
+
const type = property.type;
|
|
570
|
+
const isString =
|
|
571
|
+
type === "string" || (Array.isArray(type) && type.includes("string"));
|
|
572
|
+
if (!isString) return false;
|
|
573
|
+
if (Array.isArray(property.enum)) return property.enum.includes("");
|
|
574
|
+
if (typeof property.minLength === "number" && property.minLength > 0)
|
|
575
|
+
return false;
|
|
576
|
+
if (property.format !== undefined || property.pattern !== undefined)
|
|
577
|
+
return false;
|
|
578
|
+
return true;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
582
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
export function truncateToolOutput(output: string): string {
|
|
586
|
+
if (output.length <= MAX_TOOL_OUTPUT_LENGTH) return output;
|
|
587
|
+
return `${output.slice(0, MAX_TOOL_OUTPUT_LENGTH)}\n...[output truncated]`;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/** Keep media in what the model reads; keep image bytes out of the transcript. */
|
|
591
|
+
export function transcriptToolResult(output: unknown): unknown {
|
|
592
|
+
if (!isRecord(output) || output.kind !== "agent-tool-result") {
|
|
593
|
+
const host = parseHostToolResult(output);
|
|
594
|
+
if (!host) return output;
|
|
595
|
+
return {
|
|
596
|
+
content: host.content.map((part) =>
|
|
597
|
+
part.type === "image"
|
|
598
|
+
? { type: "image", mimeType: part.mimeType }
|
|
599
|
+
: part,
|
|
600
|
+
),
|
|
601
|
+
...(host.structured !== undefined ? { structured: host.structured } : {}),
|
|
602
|
+
...(host.isError ? { isError: true } : {}),
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
return {
|
|
606
|
+
content: extraToolResult(output).content.map((part) =>
|
|
607
|
+
part.type === "image" ? { type: "image", mimeType: part.mimeType } : part,
|
|
608
|
+
),
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
function mediaModelOutput(output: unknown) {
|
|
613
|
+
const result = extraToolResult(output);
|
|
614
|
+
if (result.isError)
|
|
615
|
+
return {
|
|
616
|
+
type: "error-text" as const,
|
|
617
|
+
value: result.content
|
|
618
|
+
.filter((part) => part.type === "text")
|
|
619
|
+
.map((part) => part.text)
|
|
620
|
+
.join("\n"),
|
|
621
|
+
};
|
|
622
|
+
return {
|
|
623
|
+
type: "content" as const,
|
|
624
|
+
value: result.content.map((part) =>
|
|
625
|
+
part.type === "image"
|
|
626
|
+
? {
|
|
627
|
+
type: "file" as const,
|
|
628
|
+
data: { type: "data" as const, data: part.data },
|
|
629
|
+
mediaType: part.mimeType,
|
|
630
|
+
}
|
|
631
|
+
: part,
|
|
632
|
+
),
|
|
633
|
+
};
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
/** Free keyless web search via Exa's public MCP endpoint (same approach as opencode). */
|
|
637
|
+
async function exaWebSearch(
|
|
638
|
+
query: string,
|
|
639
|
+
numResults: number,
|
|
640
|
+
): Promise<string> {
|
|
641
|
+
const response = await fetch(EXA_MCP_URL, {
|
|
642
|
+
method: "POST",
|
|
643
|
+
headers: {
|
|
644
|
+
"Content-Type": "application/json",
|
|
645
|
+
Accept: "application/json, text/event-stream",
|
|
646
|
+
},
|
|
647
|
+
body: JSON.stringify({
|
|
648
|
+
jsonrpc: "2.0",
|
|
649
|
+
id: 1,
|
|
650
|
+
method: "tools/call",
|
|
651
|
+
params: {
|
|
652
|
+
name: "web_search_exa",
|
|
653
|
+
arguments: { query, numResults, type: "auto", livecrawl: "fallback" },
|
|
654
|
+
},
|
|
655
|
+
}),
|
|
656
|
+
signal: AbortSignal.timeout(WEBFETCH_TIMEOUT_MS),
|
|
657
|
+
});
|
|
658
|
+
if (!response.ok)
|
|
659
|
+
throw new Error(`Web search failed with status ${response.status}`);
|
|
660
|
+
const result = parseMcpToolResult(await response.text());
|
|
661
|
+
return result ?? "No search results found. Try a different query.";
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const mcpTextResultSchema = z.object({
|
|
665
|
+
result: z.object({
|
|
666
|
+
content: z.array(z.object({ text: z.string().optional() })).optional(),
|
|
667
|
+
}),
|
|
668
|
+
});
|
|
669
|
+
|
|
670
|
+
function parseMcpToolResult(body: string): string | undefined {
|
|
671
|
+
const payloads = body.trim().startsWith("{")
|
|
672
|
+
? [body.trim()]
|
|
673
|
+
: body
|
|
674
|
+
.split("\n")
|
|
675
|
+
.filter((line) => line.startsWith("data: "))
|
|
676
|
+
.map((line) => line.slice(6));
|
|
677
|
+
for (const payload of payloads) {
|
|
678
|
+
try {
|
|
679
|
+
const data = mcpTextResultSchema.safeParse(JSON.parse(payload));
|
|
680
|
+
const text = data.success
|
|
681
|
+
? data.data.result.content?.find((item) => item.text)?.text
|
|
682
|
+
: undefined;
|
|
683
|
+
if (text) return text;
|
|
684
|
+
} catch {
|
|
685
|
+
// skip malformed SSE payloads
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return undefined;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
async function webFetch(url: string): Promise<string> {
|
|
692
|
+
if (!url.startsWith("http://") && !url.startsWith("https://"))
|
|
693
|
+
throw new Error("URL must start with http:// or https://");
|
|
694
|
+
const response = await fetch(url, {
|
|
695
|
+
headers: {
|
|
696
|
+
"User-Agent":
|
|
697
|
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",
|
|
698
|
+
Accept:
|
|
699
|
+
"text/markdown;q=1.0, text/plain;q=0.9, text/html;q=0.8, */*;q=0.1",
|
|
700
|
+
"Accept-Language": "en-US,en;q=0.9",
|
|
701
|
+
},
|
|
702
|
+
signal: AbortSignal.timeout(WEBFETCH_TIMEOUT_MS),
|
|
703
|
+
redirect: "follow",
|
|
704
|
+
});
|
|
705
|
+
if (!response.ok)
|
|
706
|
+
throw new Error(`Fetch failed with status ${response.status}`);
|
|
707
|
+
const contentLength = response.headers.get("content-length");
|
|
708
|
+
if (contentLength && Number.parseInt(contentLength, 10) > WEBFETCH_MAX_BYTES)
|
|
709
|
+
throw new Error("Response too large (exceeds 5MB limit)");
|
|
710
|
+
const buffer = await response.arrayBuffer();
|
|
711
|
+
if (buffer.byteLength > WEBFETCH_MAX_BYTES)
|
|
712
|
+
throw new Error("Response too large (exceeds 5MB limit)");
|
|
713
|
+
const contentType = response.headers.get("content-type") ?? "";
|
|
714
|
+
if (
|
|
715
|
+
contentType &&
|
|
716
|
+
!/text|json|xml|javascript|markdown|html/i.test(contentType)
|
|
717
|
+
)
|
|
718
|
+
throw new Error(`Unsupported content type: ${contentType}`);
|
|
719
|
+
const text = new TextDecoder().decode(buffer);
|
|
720
|
+
return contentType.includes("html") ? htmlToText(text) : text;
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function htmlToText(html: string): string {
|
|
724
|
+
return html
|
|
725
|
+
.replace(/<script[\s\S]*?<\/script>/gi, "")
|
|
726
|
+
.replace(/<style[\s\S]*?<\/style>/gi, "")
|
|
727
|
+
.replace(/<!--[\s\S]*?-->/g, "")
|
|
728
|
+
.replace(/<br\s*\/?>/gi, "\n")
|
|
729
|
+
.replace(/<\/(p|div|h[1-6]|li|tr|section|article|blockquote|pre)>/gi, "\n")
|
|
730
|
+
.replace(/<[^>]+>/g, " ")
|
|
731
|
+
.replace(/ /g, " ")
|
|
732
|
+
.replace(/&/g, "&")
|
|
733
|
+
.replace(/</g, "<")
|
|
734
|
+
.replace(/>/g, ">")
|
|
735
|
+
.replace(/"/g, '"')
|
|
736
|
+
.replace(/'/g, "'")
|
|
737
|
+
.replace(/[ \t]+/g, " ")
|
|
738
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
739
|
+
.trim();
|
|
740
|
+
}
|