-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathtool-bridge.ts
More file actions
454 lines (414 loc) · 15.3 KB
/
Copy pathtool-bridge.ts
File metadata and controls
454 lines (414 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
/**
* MCP to CustomTool bridge.
*
* Converts MCP tool definitions to CustomTool format for the agent.
*/
import type { AgentToolUpdateCallback } from "@oh-my-pi/pi-agent-core";
import type { TSchema } from "@oh-my-pi/pi-ai";
import { normalizeSchemaForMCP } from "@oh-my-pi/pi-ai/utils/schema";
import { untilAborted } from "@oh-my-pi/pi-utils";
import type { SourceMeta } from "../capability/types";
import type {
CustomTool,
CustomToolContext,
CustomToolResult,
RenderResultOptions,
} from "../extensibility/custom-tools/types";
import type { Theme } from "../modes/theme/theme";
import type { OutputMeta } from "../tools/output-meta";
import { ToolAbortError, throwIfAborted } from "../tools/tool-errors";
import { callTool } from "./client";
import { renderMCPCall, renderMCPResult } from "./render";
import type { MCPContent, MCPServerConnection, MCPToolCallParams, MCPToolCallResult, MCPToolDefinition } from "./types";
/** Reconnect callback: tears down stale connection, returns new one or null. */
export type MCPReconnect = () => Promise<MCPServerConnection | null>;
/**
* Network-level and stale-session errors that warrant a reconnect + single retry.
* Conservative: only catches errors where the server is likely alive but the
* connection object is stale (dead SSE, expired session, refused after restart).
*/
const RETRIABLE_PATTERNS = [
"econnrefused",
"econnreset",
"epipe",
"enetunreach",
"ehostunreach",
"fetch failed",
"transport not connected",
"transport closed",
"network error",
];
export function isRetriableConnectionError(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const msg = error.message.toLowerCase();
// Stale session (server restarted, old session ID is gone)
if (/^http (404|502|503):/.test(msg)) return true;
return RETRIABLE_PATTERNS.some(p => msg.includes(p));
}
type MCPToolArgs = NonNullable<MCPToolCallParams["arguments"]>;
function normalizeToolArgs(value: unknown): MCPToolArgs {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
return {};
}
return value as MCPToolArgs;
}
function isUnusedOptionalPlaceholder(value: unknown): boolean {
return (
value === undefined ||
value === "" ||
(typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length === 0)
);
}
function omitUnusedOptionalArgs(args: MCPToolArgs, inputSchema: MCPToolDefinition["inputSchema"]): MCPToolArgs {
const properties = inputSchema.properties;
if (!properties) return args;
let cleaned: MCPToolArgs | undefined;
const required = new Set(inputSchema.required ?? []);
for (const [key, value] of Object.entries(args)) {
if (required.has(key) || !Object.hasOwn(properties, key) || !isUnusedOptionalPlaceholder(value)) {
continue;
}
cleaned ??= { ...args };
delete cleaned[key];
}
return cleaned ?? args;
}
/** Details included in MCP tool results for rendering */
export interface MCPToolDetails {
/** Server name */
serverName: string;
/** Original MCP tool name */
mcpToolName: string;
/** Whether the call resulted in an error */
isError?: boolean;
/** Raw content from MCP response */
rawContent?: MCPContent[];
/** Provider ID (e.g., "claude", "mcp-json") */
provider?: string;
/** Provider display name (e.g., "Claude Code", "MCP Config") */
providerName?: string;
/** Structured output metadata (set by the spill wrapper when output is truncated to an artifact). */
meta?: OutputMeta;
}
/**
* Format MCP content for LLM consumption.
*/
function formatMCPContent(content: MCPContent[]): string {
const parts: string[] = [];
for (const item of content) {
switch (item.type) {
case "text":
parts.push(item.text);
break;
case "image":
parts.push(`[Image: ${item.mimeType}]`);
break;
case "resource":
if (item.resource.text) {
parts.push(`[Resource: ${item.resource.uri}]\n${item.resource.text}`);
} else {
parts.push(`[Resource: ${item.resource.uri}]`);
}
break;
}
}
return parts.join("\n\n");
}
/** Build a CustomToolResult from a callTool response. */
function buildResult(
result: MCPToolCallResult,
serverName: string,
mcpToolName: string,
provider?: string,
providerName?: string,
): CustomToolResult<MCPToolDetails> {
const text = formatMCPContent(result.content);
const details: MCPToolDetails = {
serverName,
mcpToolName,
isError: result.isError,
rawContent: result.content,
provider,
providerName,
};
const contentText = result.isError ? `Error: ${text}` : text;
const toolResult: CustomToolResult<MCPToolDetails> = { content: [{ type: "text", text: contentText }], details };
if (result.isError) {
toolResult.isError = true;
}
return toolResult;
}
/** Build an error CustomToolResult from a caught exception. */
function buildErrorResult(
error: unknown,
serverName: string,
mcpToolName: string,
provider?: string,
providerName?: string,
): CustomToolResult<MCPToolDetails> {
const message = error instanceof Error ? error.message : String(error);
return {
content: [{ type: "text", text: `MCP error: ${message}` }],
details: { serverName, mcpToolName, isError: true, provider, providerName },
isError: true,
};
}
/** Re-throw abort-related errors so they bypass error-result handling. */
function rethrowIfAborted(error: unknown, signal?: AbortSignal): void {
if (error instanceof ToolAbortError) throw error;
if (error instanceof Error && error.name === "AbortError") throw new ToolAbortError();
if (signal?.aborted) throw new ToolAbortError();
}
async function reconnectWithAbort(reconnect: MCPReconnect, signal?: AbortSignal): Promise<MCPServerConnection | null> {
try {
return await untilAborted(signal, reconnect);
} catch (error) {
rethrowIfAborted(error, signal);
return null;
}
}
/**
* Create a unique tool name for an MCP tool.
*
* Prefixes with server name to avoid conflicts. If the tool name already
* starts with the server name (e.g., server "puppeteer" with tool
* "puppeteer_screenshot"), strips the redundant prefix to produce
* "mcp__puppeteer_screenshot" instead of "mcp__puppeteer_puppeteer_screenshot".
*/
function sanitizeMCPToolNamePart(value: string, fallback: string): string {
const sanitized = value
.toLowerCase()
.replace(/[^a-z_]+/g, "_")
.replace(/_+/g, "_")
.replace(/^_+|_+$/g, "");
return sanitized.length > 0 ? sanitized : fallback;
}
export function createMCPToolName(serverName: string, toolName: string): string {
const sanitizedServerName = sanitizeMCPToolNamePart(serverName, "server");
const sanitizedToolName = sanitizeMCPToolNamePart(toolName, "tool");
// Strip redundant server name prefix from tool name if present
const prefixWithUnderscore = `${sanitizedServerName}_`;
let normalizedToolName = sanitizedToolName;
if (sanitizedToolName.startsWith(prefixWithUnderscore)) {
normalizedToolName = sanitizedToolName.slice(prefixWithUnderscore.length);
}
return `mcp__${sanitizedServerName}_${normalizedToolName}`;
}
/**
* Parse an MCP tool name back to server and tool components.
*
* Note: This returns the normalized tool name (with server prefix stripped).
* The original MCP tool name may have had the server name as a prefix.
*/
export function parseMCPToolName(name: string): { serverName: string; toolName: string } | null {
if (!name.startsWith("mcp__")) return null;
const rest = name.slice(5);
const underscoreIdx = rest.indexOf("_");
if (underscoreIdx === -1) return null;
return {
serverName: rest.slice(0, underscoreIdx),
toolName: rest.slice(underscoreIdx + 1),
};
}
/**
* CustomTool wrapping an MCP tool with an active connection.
*/
export class MCPTool implements CustomTool<TSchema, MCPToolDetails> {
readonly name: string;
readonly label: string;
readonly description: string;
readonly parameters: TSchema;
/** Original MCP tool name (before normalization) */
readonly mcpToolName: string;
/** Server name */
readonly mcpServerName: string;
readonly approval = "write" as const;
/** Render completed MCP calls with the result header replacing the pending call header. */
readonly mergeCallAndResult = true;
/** Create MCPTool instances for all tools from an MCP server connection */
static fromTools(connection: MCPServerConnection, tools: MCPToolDefinition[], reconnect?: MCPReconnect): MCPTool[] {
return tools.map(tool => new MCPTool(connection, tool, reconnect));
}
constructor(
private connection: MCPServerConnection,
private readonly tool: MCPToolDefinition,
private readonly reconnect?: MCPReconnect,
) {
this.name = createMCPToolName(connection.name, tool.name);
this.label = `${connection.name}/${tool.name}`;
this.description = tool.description ?? `MCP tool from ${connection.name}`;
this.parameters = normalizeSchemaForMCP(tool.inputSchema) as TSchema;
this.mcpToolName = tool.name;
this.mcpServerName = connection.name;
}
renderCall(args: unknown, _options: RenderResultOptions, theme: Theme) {
return renderMCPCall(normalizeToolArgs(args), theme, this.label);
}
renderResult(result: CustomToolResult<MCPToolDetails>, options: RenderResultOptions, theme: Theme, args?: unknown) {
return renderMCPResult(result, options, theme, normalizeToolArgs(args));
}
async execute(
_toolCallId: string,
params: unknown,
_onUpdate: AgentToolUpdateCallback<MCPToolDetails> | undefined,
_ctx: CustomToolContext,
signal?: AbortSignal,
): Promise<CustomToolResult<MCPToolDetails>> {
throwIfAborted(signal);
const args = omitUnusedOptionalArgs(normalizeToolArgs(params), this.tool.inputSchema);
const provider = this.connection._source?.provider;
const providerName = this.connection._source?.providerName;
try {
const result = await callTool(this.connection, this.tool.name, args, { signal });
return buildResult(result, this.connection.name, this.tool.name, provider, providerName);
} catch (error) {
rethrowIfAborted(error, signal);
if (this.reconnect && isRetriableConnectionError(error)) {
const newConn = await reconnectWithAbort(this.reconnect, signal);
if (newConn) {
// Rebind so subsequent calls on this instance use the fresh connection
this.connection = newConn;
const retryProvider = newConn._source?.provider ?? provider;
const retryProviderName = newConn._source?.providerName ?? providerName;
try {
const result = await callTool(newConn, this.tool.name, args, { signal });
return buildResult(result, newConn.name, this.tool.name, retryProvider, retryProviderName);
} catch (retryError) {
rethrowIfAborted(retryError, signal);
return buildErrorResult(
retryError,
this.connection.name,
this.tool.name,
retryProvider,
retryProviderName,
);
}
}
}
return buildErrorResult(error, this.connection.name, this.tool.name, provider, providerName);
}
}
}
/**
* CustomTool wrapping an MCP tool with deferred connection resolution.
*/
export class DeferredMCPTool implements CustomTool<TSchema, MCPToolDetails> {
readonly name: string;
readonly label: string;
readonly description: string;
readonly parameters: TSchema;
/** Original MCP tool name (before normalization) */
readonly mcpToolName: string;
/** Server name */
readonly mcpServerName: string;
readonly approval = "write" as const;
/** Render completed MCP calls with the result header replacing the pending call header. */
readonly mergeCallAndResult = true;
readonly #fallbackProvider: string | undefined;
readonly #fallbackProviderName: string | undefined;
/** Create DeferredMCPTool instances for all tools from an MCP server */
static fromTools(
serverName: string,
tools: MCPToolDefinition[],
getConnection: () => Promise<MCPServerConnection>,
source?: SourceMeta,
reconnect?: MCPReconnect,
): DeferredMCPTool[] {
return tools.map(tool => new DeferredMCPTool(serverName, tool, getConnection, source, reconnect));
}
constructor(
private readonly serverName: string,
private readonly tool: MCPToolDefinition,
private readonly getConnection: () => Promise<MCPServerConnection>,
source?: SourceMeta,
private readonly reconnect?: MCPReconnect,
) {
this.name = createMCPToolName(serverName, tool.name);
this.label = `${serverName}/${tool.name}`;
this.description = tool.description ?? `MCP tool from ${serverName}`;
this.parameters = normalizeSchemaForMCP(tool.inputSchema) as TSchema;
this.mcpToolName = tool.name;
this.mcpServerName = serverName;
this.#fallbackProvider = source?.provider;
this.#fallbackProviderName = source?.providerName;
}
renderCall(args: unknown, _options: RenderResultOptions, theme: Theme) {
return renderMCPCall(normalizeToolArgs(args), theme, this.label);
}
renderResult(result: CustomToolResult<MCPToolDetails>, options: RenderResultOptions, theme: Theme, args?: unknown) {
return renderMCPResult(result, options, theme, normalizeToolArgs(args));
}
async execute(
_toolCallId: string,
params: unknown,
_onUpdate: AgentToolUpdateCallback<MCPToolDetails> | undefined,
_ctx: CustomToolContext,
signal?: AbortSignal,
): Promise<CustomToolResult<MCPToolDetails>> {
throwIfAborted(signal);
const args = omitUnusedOptionalArgs(normalizeToolArgs(params), this.tool.inputSchema);
const provider = this.#fallbackProvider;
const providerName = this.#fallbackProviderName;
try {
const connection = await untilAborted(signal, () => this.getConnection());
throwIfAborted(signal);
try {
const result = await callTool(connection, this.tool.name, args, { signal });
return buildResult(
result,
this.serverName,
this.tool.name,
connection._source?.provider ?? provider,
connection._source?.providerName ?? providerName,
);
} catch (callError) {
rethrowIfAborted(callError, signal);
if (this.reconnect && isRetriableConnectionError(callError)) {
const newConn = await reconnectWithAbort(this.reconnect, signal);
if (newConn) {
const retryProvider = newConn._source?.provider ?? provider;
const retryProviderName = newConn._source?.providerName ?? providerName;
try {
const result = await callTool(newConn, this.tool.name, args, { signal });
return buildResult(result, this.serverName, this.tool.name, retryProvider, retryProviderName);
} catch (retryError) {
rethrowIfAborted(retryError, signal);
return buildErrorResult(
retryError,
this.serverName,
this.tool.name,
retryProvider,
retryProviderName,
);
}
}
}
return buildErrorResult(callError, this.serverName, this.tool.name, provider, providerName);
}
} catch (connError) {
// getConnection() failed — server never connected or connection lost.
// This is always worth a reconnect attempt for deferred tools, since the
// error ("MCP server not connected") isn't a network error from callTool.
rethrowIfAborted(connError, signal);
if (this.reconnect) {
const newConn = await reconnectWithAbort(this.reconnect, signal);
if (newConn) {
try {
const result = await callTool(newConn, this.tool.name, args, { signal });
return buildResult(
result,
this.serverName,
this.tool.name,
newConn._source?.provider ?? provider,
newConn._source?.providerName ?? providerName,
);
} catch (retryError) {
rethrowIfAborted(retryError, signal);
return buildErrorResult(retryError, this.serverName, this.tool.name, provider, providerName);
}
}
}
return buildErrorResult(connError, this.serverName, this.tool.name, provider, providerName);
}
}
}