@fitchmultz/pi-mcp-adapter 6.0.0 → 7.1.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.
Files changed (111) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/OAUTH.md +1 -1
  3. package/README.md +27 -18
  4. package/dist/app-bridge.bundle.js +14 -14
  5. package/dist/config.js +41 -16
  6. package/dist/direct-tools.js +1 -1
  7. package/dist/gateway-arguments.d.ts +1 -1
  8. package/dist/index.js +38 -59
  9. package/dist/lifecycle.d.ts +2 -2
  10. package/dist/lifecycle.js +2 -2
  11. package/dist/mcp-auth-flow.js +2 -2
  12. package/dist/mcp-auth.d.ts +1 -1
  13. package/dist/mcp-auth.js +3 -3
  14. package/dist/mcp-code.d.ts +6 -6
  15. package/dist/mcp-code.js +11 -10
  16. package/dist/mcp-oauth-provider.d.ts +5 -5
  17. package/dist/mcp-oauth-provider.js +5 -5
  18. package/dist/mcp-output-guard.d.ts +1 -1
  19. package/dist/mcp-output-guard.js +1 -1
  20. package/dist/mcp-panel.d.ts +2 -2
  21. package/dist/mcp-panel.js +2 -2
  22. package/dist/mcp-setup-panel.d.ts +5 -4
  23. package/dist/mcp-setup-panel.js +15 -7
  24. package/dist/mcp-trace.d.ts +1 -1
  25. package/dist/mcp-trace.js +1 -1
  26. package/dist/npx-resolver.js +8 -4
  27. package/dist/proxy-modes.d.ts +2 -2
  28. package/dist/proxy-modes.js +20 -19
  29. package/dist/sampling-handler.js +1 -0
  30. package/dist/search-ranking.js +6 -2
  31. package/dist/server-manager.d.ts +2 -2
  32. package/dist/server-manager.js +44 -27
  33. package/dist/session-recovery.d.ts +7 -4
  34. package/dist/session-recovery.js +76 -10
  35. package/dist/tool-loader.d.ts +7 -2
  36. package/dist/tool-loader.js +56 -5
  37. package/dist/tool-metadata.d.ts +43 -43
  38. package/dist/tool-result-renderer.d.ts +3 -3
  39. package/dist/tool-result-renderer.js +3 -3
  40. package/dist/ui-resource-handler.d.ts +2 -2
  41. package/dist/ui-resource-handler.js +2 -2
  42. package/dist/ui-server.js +5 -4
  43. package/dist/ui-stream-types.d.ts +8 -8
  44. package/dist/unix-socket-transport.d.ts +1 -1
  45. package/dist/unix-socket-transport.js +1 -1
  46. package/dist/utils.d.ts +1 -0
  47. package/dist/utils.js +14 -0
  48. package/package.json +34 -98
  49. package/skills/mcp-scripting/SKILL.md +2 -0
  50. package/abort.ts +0 -34
  51. package/agent-dir.ts +0 -24
  52. package/app-bridge.bundle.js +0 -109
  53. package/banner.png +0 -0
  54. package/checkpoint.ts +0 -55
  55. package/commands.ts +0 -622
  56. package/config.ts +0 -1204
  57. package/consent-manager.ts +0 -25
  58. package/direct-tools.ts +0 -75
  59. package/elicitation-handler.ts +0 -349
  60. package/error-signal.ts +0 -21
  61. package/gateway-arguments.ts +0 -73
  62. package/glimpse-ui.ts +0 -80
  63. package/host-html-template.ts +0 -456
  64. package/index.ts +0 -767
  65. package/init.ts +0 -613
  66. package/legacy-migration.ts +0 -47
  67. package/lifecycle.ts +0 -165
  68. package/logger.ts +0 -127
  69. package/mcp-auth-flow.ts +0 -975
  70. package/mcp-auth.ts +0 -793
  71. package/mcp-callback-server.ts +0 -450
  72. package/mcp-code.ts +0 -412
  73. package/mcp-keyring-helper.cjs +0 -89
  74. package/mcp-oauth-provider.ts +0 -774
  75. package/mcp-output-guard.ts +0 -530
  76. package/mcp-panel.ts +0 -907
  77. package/mcp-script-worker.mjs +0 -131
  78. package/mcp-setup-panel.ts +0 -666
  79. package/mcp-status.ts +0 -110
  80. package/mcp-trace.ts +0 -295
  81. package/metadata-cache.ts +0 -271
  82. package/npx-resolver.ts +0 -488
  83. package/onboarding-state.ts +0 -58
  84. package/panel-keys.ts +0 -37
  85. package/prompts.ts +0 -337
  86. package/proxy-modes.ts +0 -1109
  87. package/resource-tools.ts +0 -52
  88. package/runtime-owner.ts +0 -123
  89. package/sampling-handler.ts +0 -276
  90. package/scripts/build-app-bridge.mjs +0 -15
  91. package/scripts/build.mjs +0 -132
  92. package/scripts/prepare.mjs +0 -103
  93. package/search-ranking.ts +0 -132
  94. package/server-manager.ts +0 -1320
  95. package/session-recovery.ts +0 -316
  96. package/state.ts +0 -64
  97. package/tool-approval.ts +0 -78
  98. package/tool-loader.ts +0 -153
  99. package/tool-metadata.ts +0 -240
  100. package/tool-registrar.ts +0 -74
  101. package/tool-result-renderer.ts +0 -294
  102. package/tsconfig.build.json +0 -13
  103. package/tsconfig.json +0 -16
  104. package/types.ts +0 -785
  105. package/ui-resource-handler.ts +0 -249
  106. package/ui-server.ts +0 -808
  107. package/ui-session.ts +0 -568
  108. package/ui-stream-types.ts +0 -89
  109. package/ui-tool-visibility.ts +0 -25
  110. package/unix-socket-transport.ts +0 -85
  111. package/utils.ts +0 -307
package/mcp-code.ts DELETED
@@ -1,412 +0,0 @@
1
- import type { ToolInfo } from "@earendil-works/pi-coding-agent";
2
- import { formatWithOptions } from "node:util";
3
- import { Worker } from "node:worker_threads";
4
- import { guardMcpOutput, guardedMcpDetails, resolveMcpOutputGuardOptions, readMcpResult, formatMcpResultReference, formatMcpPayloadFile, type McpPayloadFile, type ReadMcpResultInput } from "./mcp-output-guard.ts";
5
- import { executeCall, executeConnect } from "./proxy-modes.ts";
6
- import { executeResourceList, executeResourceRead } from "./resource-tools.ts";
7
- import { combineAbortSignals } from "./runtime-owner.ts";
8
- import { paginate, rankSuggestions, rankToolMatches } from "./search-ranking.ts";
9
- import type { McpExtensionState } from "./state.ts";
10
- import { catalogCoverage, toToolDescriptor } from "./tool-metadata.ts";
11
- import { isServerDisabled, type ContentBlock, type McpOperationContext } from "./types.ts";
12
-
13
- export const DEFAULT_MCP_SCRIPT_TIMEOUT_MS = 30_000;
14
-
15
- class McpScriptTimeoutError extends Error {
16
- constructor(timeoutMs: number) {
17
- super(`mcp_script timed out after ${timeoutMs}ms`);
18
- this.name = "McpScriptTimeoutError";
19
- }
20
- }
21
-
22
- type SearchInput = { query?: unknown; server?: unknown; limit?: unknown; offset?: unknown };
23
- type DescribeInput = { path?: unknown; server?: unknown };
24
- type WorkerMessage =
25
- | { type: "emit"; block: unknown }
26
- | { type: "call"; id: number; path: string; args?: unknown; server?: string }
27
- | { type: "search"; id: number; input?: unknown }
28
- | { type: "describe" | "resources" | "readResource" | "readResult"; id: number; input?: unknown }
29
- | { type: "done"; returnBlock?: unknown }
30
- | { type: "error"; message: string };
31
-
32
- type WorkerResultMessage = { type: "result"; id: number; envelope: unknown };
33
-
34
- function needsInspectableFormatting(value: unknown, stack = new WeakSet<object>()): boolean {
35
- if (value === undefined || typeof value === "bigint" || typeof value === "function" || typeof value === "symbol") return true;
36
- if (typeof value !== "object" || value === null) return false;
37
- if (stack.has(value)) return true;
38
- if (value instanceof Map || value instanceof Set || value instanceof WeakMap || value instanceof WeakSet) return true;
39
- stack.add(value);
40
- try {
41
- return Object.values(value).some((entry) => needsInspectableFormatting(entry, stack));
42
- } finally {
43
- stack.delete(value);
44
- }
45
- }
46
-
47
- function formatValue(value: unknown): string {
48
- if (typeof value === "string") return value;
49
- try {
50
- if (!needsInspectableFormatting(value)) {
51
- const json = JSON.stringify(value, null, 2);
52
- if (json !== undefined) return json;
53
- }
54
- return formatWithOptions({ colors: false, depth: 6 }, value);
55
- } catch {
56
- return "[unserializable value]";
57
- }
58
- }
59
-
60
- function toContentBlock(value: unknown): ContentBlock {
61
- if (typeof value === "object" && value !== null) {
62
- const block = value as Record<string, unknown>;
63
- if (block.type === "text" && typeof block.text === "string") {
64
- return { type: "text", text: block.text };
65
- }
66
- if (block.type === "image" && typeof block.data === "string" && typeof block.mimeType === "string") {
67
- return { type: "image", data: block.data, mimeType: block.mimeType };
68
- }
69
- }
70
- return { type: "text", text: formatValue(value) };
71
- }
72
-
73
- function textFromContent(content: ContentBlock[]): string {
74
- return content
75
- .filter((block) => block.type === "text")
76
- .map((block) => block.text)
77
- .join("\n");
78
- }
79
-
80
- function abortReasonError(reason: unknown): Error {
81
- return reason instanceof Error ? reason : new Error(String(reason ?? "MCP request aborted"));
82
- }
83
-
84
- function parseWorkerMessage(value: unknown): WorkerMessage | null {
85
- if (typeof value !== "object" || value === null) return null;
86
- const message = value as Record<string, unknown>;
87
- if (message.type === "emit" && "block" in message) return { type: "emit", block: message.block };
88
- if (message.type === "call" && typeof message.id === "number" && typeof message.path === "string") {
89
- return { type: "call", id: message.id, path: message.path, ...(message.args !== undefined ? { args: message.args } : {}), ...(typeof message.server === "string" ? { server: message.server } : {}) };
90
- }
91
- if ((message.type === "search" || message.type === "describe" || message.type === "resources" || message.type === "readResource" || message.type === "readResult") && typeof message.id === "number") {
92
- return "input" in message
93
- ? { type: message.type, id: message.id, input: message.input }
94
- : { type: message.type, id: message.id };
95
- }
96
- if (message.type === "done") {
97
- return "returnBlock" in message ? { type: "done", returnBlock: message.returnBlock } : { type: "done" };
98
- }
99
- if (message.type === "error" && typeof message.message === "string") {
100
- return { type: "error", message: message.message };
101
- }
102
- return null;
103
- }
104
-
105
- class McpScriptCaptureError extends Error {
106
- constructor(readonly recovery: unknown, message: string) {
107
- super(message);
108
- }
109
- }
110
-
111
- export const runMcpScript: typeof runMcpScriptOperation = async (...args) => {
112
- const state = args[0];
113
- state.owner?.beforeActivity();
114
- state.activeScripts = (state.activeScripts ?? 0) + 1;
115
- try { return await runMcpScriptOperation(...args); }
116
- finally { state.activeScripts--; }
117
- };
118
-
119
- async function runMcpScriptOperation(
120
- state: McpExtensionState,
121
- code: string,
122
- timeoutMs: number | null = DEFAULT_MCP_SCRIPT_TIMEOUT_MS,
123
- getPiTools?: () => ToolInfo[],
124
- signal?: AbortSignal,
125
- toolCallId?: string,
126
- beforeDispatch?: (signal: AbortSignal | undefined, operation: McpOperationContext) => Promise<void>,
127
- ) {
128
- const resolvedTimeoutMs = timeoutMs === null ? null : Number.isFinite(timeoutMs) && timeoutMs > 0
129
- ? Math.floor(timeoutMs)
130
- : DEFAULT_MCP_SCRIPT_TIMEOUT_MS;
131
- const output: ContentBlock[] = [];
132
- const externalSignal = combineAbortSignals(state.owner?.signal, signal);
133
- const timeoutController = new AbortController();
134
- const callSignal = combineAbortSignals(externalSignal, timeoutController.signal);
135
-
136
- type ScriptOperation =
137
- | { operation: "call"; path: string; ok: true; durationMs: number }
138
- | { operation: "call"; path: string; ok: false; error: string; durationMs: number; recovery?: unknown }
139
- | { operation: "search"; query: string; ok: true; durationMs: number }
140
- | { operation: "search"; query: string; ok: false; error: string; durationMs: number }
141
- | { operation: "describe"; path: string; ok: true; durationMs: number }
142
- | { operation: "describe"; path: string; ok: false; error: string; durationMs: number };
143
- type TrackedScriptOperation = ScriptOperation & { startedAt: number };
144
- const calls: TrackedScriptOperation[] = [];
145
- const snapshotCalls = (): ScriptOperation[] => calls.map(({ startedAt, ...operation }) => ({
146
- ...operation,
147
- durationMs: "error" in operation && operation.error === "incomplete"
148
- ? Math.max(0, Date.now() - startedAt)
149
- : operation.durationMs,
150
- }));
151
- let callsSnapshot: ScriptOperation[] | undefined;
152
- const resultRefs = new Set<string>();
153
- const payloadNotices = new Set<string>();
154
- const recordCall = async (path: string, dispatch: () => ReturnType<typeof executeCall>) => {
155
- // Record before dispatch so calls still in flight at timeout/abort appear in the trace.
156
- const startedAt = Date.now();
157
- const index = calls.push({ operation: "call", path, ok: false, error: "incomplete", durationMs: 0, startedAt }) - 1;
158
- const result = await dispatch();
159
- const details = result.details;
160
- if (typeof details.resultRef === "string") resultRefs.add(details.resultRef);
161
- if (typeof details.resultWriteError === "string") payloadNotices.add(`[MCP result could not be saved: ${details.resultWriteError}]`);
162
- for (const file of (details.payloadFiles ?? []) as McpPayloadFile[]) payloadNotices.add(formatMcpPayloadFile(file));
163
- if (details.error !== undefined) {
164
- const errorCode = String(details.error);
165
- const suggestions = Array.isArray(details.suggestions)
166
- ? details.suggestions.filter((suggestion): suggestion is string => typeof suggestion === "string")
167
- : [];
168
- const message = errorCode === "tool_not_found"
169
- ? `Tool "${path}" not found. Use await tools.search({ query: "..." }) inside mcp_script.${suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}` : ""}`
170
- : typeof details.message === "string"
171
- ? details.message
172
- : textFromContent(result.content);
173
- calls[index] = {
174
- operation: "call", path, ok: false, error: errorCode, durationMs: Date.now() - startedAt, startedAt,
175
- ...(errorCode === "ambiguous_outcome" ? { recovery: details.recovery } : {}),
176
- };
177
- if (errorCode === "call_capture_failed") throw new McpScriptCaptureError(details.recovery, message);
178
- if (errorCode === "ambiguous_outcome") output.push({ type: "text", text: message });
179
- return {
180
- ok: false as const,
181
- ...(details.mcpResult !== undefined ? { data: details.mcpResult } : {}),
182
- ...(details.resultRef ? { resultRef: details.resultRef } : {}),
183
- error: { code: errorCode, message, ...(details.recovery ? { recovery: details.recovery } : {}) },
184
- };
185
- }
186
- calls[index] = { operation: "call", path, ok: true, durationMs: Date.now() - startedAt, startedAt };
187
- return {
188
- ok: true as const,
189
- data: details.mcpResult !== undefined ? details.mcpResult : textFromContent(result.content),
190
- ...(details.resultRef ? { resultRef: details.resultRef } : {}),
191
- };
192
- };
193
-
194
- const callIdentity = (innerCallId: number) => ({ ...(toolCallId !== undefined ? { toolCallId } : {}), innerCallId });
195
- const callTool = (innerCallId: number, path: string, args?: Record<string, unknown>, server?: string) => recordCall(path,
196
- () => executeCall(state, path, args, server, getPiTools, callSignal, callIdentity(innerCallId), beforeDispatch, { raw: true }));
197
-
198
- const discoverServer = async (server?: string) => {
199
- if (!server) return undefined;
200
- if (isServerDisabled(state.config.mcpServers[server])) return { code: "server_disabled", message: `Server "${server}" is disabled.` };
201
- if (state.config.mcpServers[server] && state.toolMetadata.has(server)) return undefined;
202
- const result = await executeConnect(state, server, callSignal);
203
- return result.details.error ? { code: result.details.error, message: textFromContent(result.content) } : undefined;
204
- };
205
- const searchTools = async (input?: SearchInput) => {
206
- const startedAt = Date.now();
207
- const query = typeof input?.query === "string" ? input.query : "";
208
- let error: unknown;
209
- try {
210
- const server = typeof input?.server === "string" ? input.server : undefined;
211
- const discoveryError = await discoverServer(server);
212
- const coverage = catalogCoverage(state, server);
213
- if (discoveryError) { error = discoveryError.code; return { error: discoveryError, coverage }; }
214
- if (query.trim() === "") return { items: [], total: 0, hasMore: false, nextOffset: null, coverage };
215
- const limit = typeof input?.limit === "number" ? input.limit : 12;
216
- const offset = typeof input?.offset === "number" ? input.offset : 0;
217
- const page = paginate(rankToolMatches(state, query, server).filter(match => !match.tool.resourceUri), offset, limit);
218
- return {
219
- ...page, coverage,
220
- items: page.items.map(({ server: matchServer, tool, score }) => ({
221
- path: tool.name,
222
- name: tool.originalName,
223
- server: matchServer,
224
- ...(tool.description ? { description: tool.description } : {}),
225
- score,
226
- })),
227
- };
228
- } catch (caught) {
229
- error = caught;
230
- throw caught;
231
- } finally {
232
- calls.push(error === undefined
233
- ? { operation: "search", query, ok: true, durationMs: Date.now() - startedAt, startedAt }
234
- : { operation: "search", query, ok: false, error: error instanceof Error ? error.message : String(error), durationMs: Date.now() - startedAt, startedAt });
235
- }
236
- };
237
-
238
- const describeTool = async (input?: DescribeInput) => {
239
- const startedAt = Date.now();
240
- const path = typeof input?.path === "string" ? input.path : "";
241
- let error: unknown;
242
- try {
243
- const selectedServer = typeof input?.server === "string" ? input.server : undefined;
244
- const discoveryError = await discoverServer(selectedServer);
245
- if (discoveryError) { error = discoveryError.code; return { path, error: discoveryError }; }
246
- const matches = [...state.toolMetadata].flatMap(([server, metadata]) => {
247
- if ((selectedServer && server !== selectedServer) || !state.config.mcpServers[server] || isServerDisabled(state.config.mcpServers[server])) return [];
248
- const tools = metadata.filter(tool => !tool.resourceUri);
249
- const originals = selectedServer ? tools.filter(tool => tool.originalName === path) : [];
250
- return (originals.length ? originals : tools.filter(tool => tool.name === path)).map(tool => toToolDescriptor(server, tool));
251
- });
252
- if (matches.length === 1) return matches[0];
253
- if (matches.length > 1) { error = "ambiguous_tool"; return { path, error: { code: "ambiguous_tool", message: "Specify server and exact tool name." } }; }
254
- const suggestions = path ? rankSuggestions(state, path, 5, selectedServer) : [];
255
- error = "tool_not_found";
256
- return {
257
- path,
258
- error: {
259
- code: "tool_not_found",
260
- message: `Tool not found: ${path}`,
261
- suggestions,
262
- },
263
- };
264
- } catch (caught) {
265
- error = caught;
266
- throw caught;
267
- } finally {
268
- calls.push(error === undefined
269
- ? { operation: "describe", path, ok: true, durationMs: Date.now() - startedAt, startedAt }
270
- : { operation: "describe", path, ok: false, error: error instanceof Error ? error.message : String(error), durationMs: Date.now() - startedAt, startedAt });
271
- }
272
- };
273
-
274
- let worker: Worker | undefined;
275
- let timer: ReturnType<typeof setTimeout> | undefined;
276
- let removeAbortListener = () => {};
277
- let errorCode: "timeout" | "aborted" | "script_error" | "call_capture_failed" | undefined;
278
- let recovery: unknown;
279
- let errorMessage: string | undefined;
280
-
281
- try {
282
- if (externalSignal?.aborted) {
283
- throw abortReasonError(externalSignal.reason);
284
- }
285
-
286
- worker = new Worker(new URL("./mcp-script-worker.mjs", import.meta.url), {
287
- workerData: { code },
288
- env: {},
289
- });
290
- const activeWorker = worker;
291
- const execution = new Promise<void>((resolve, reject) => {
292
- let completed = false;
293
- activeWorker.on("message", (value: unknown) => {
294
- const message = parseWorkerMessage(value);
295
- if (!message || completed) return;
296
- if (message.type === "emit") {
297
- output.push(toContentBlock(message.block));
298
- return;
299
- }
300
- if (message.type === "done") {
301
- completed = true;
302
- if ("returnBlock" in message) output.push(toContentBlock(message.returnBlock));
303
- resolve();
304
- return;
305
- }
306
- if (message.type === "error") {
307
- completed = true;
308
- reject(new Error(message.message));
309
- return;
310
- }
311
-
312
- void (async () => {
313
- let envelope: unknown;
314
- if (message.type === "call") {
315
- envelope = await callTool(message.id, message.path, message.args as Record<string, unknown> | undefined, message.server);
316
- } else if (message.type === "search") {
317
- envelope = await searchTools(message.input as SearchInput | undefined);
318
- } else if (message.type === "describe") {
319
- envelope = await describeTool(message.input as DescribeInput | undefined);
320
- } else if (message.type === "readResult") {
321
- envelope = await readMcpResult(message.input as ReadMcpResultInput, resolveMcpOutputGuardOptions(state.config.settings, state.outputDirectory));
322
- } else {
323
- const input = message.input as { server?: unknown; uri?: unknown; limit?: unknown; offset?: unknown } | undefined;
324
- if (typeof input?.server !== "string" || !input.server || (message.type === "readResource" && (typeof input.uri !== "string" || !input.uri))) {
325
- envelope = { error: { code: "invalid_arguments", message: "Specify server and, for reads, resource uri." } };
326
- } else if (message.type === "resources") {
327
- const result = await executeResourceList(state, input.server, typeof input.limit === "number" ? input.limit : 12, typeof input.offset === "number" ? input.offset : 0, callSignal);
328
- envelope = result.details.error ? { error: { code: result.details.error, message: textFromContent(result.content) } } : result.details;
329
- } else {
330
- const server = input.server;
331
- const uri = input.uri as string;
332
- envelope = await recordCall(`${server}:${uri}`, () => executeResourceRead(state, server, uri, callSignal, callIdentity(message.id), beforeDispatch, true));
333
- }
334
- }
335
- const response: WorkerResultMessage = { type: "result", id: message.id, envelope };
336
- activeWorker.postMessage(response);
337
- })().catch(reject);
338
- });
339
- activeWorker.once("error", reject);
340
- activeWorker.once("exit", (code) => {
341
- if (!completed && code !== 0) reject(new Error(`mcp_script worker exited with code ${code}`));
342
- });
343
- });
344
- const timeout = new Promise<never>((_resolve, reject) => {
345
- if (resolvedTimeoutMs === null) return;
346
- const timeoutError = new McpScriptTimeoutError(resolvedTimeoutMs);
347
- timer = setTimeout(() => {
348
- callsSnapshot = snapshotCalls();
349
- timeoutController.abort(timeoutError);
350
- void activeWorker.terminate();
351
- reject(timeoutError);
352
- }, resolvedTimeoutMs);
353
- });
354
- const aborted = externalSignal
355
- ? new Promise<never>((_resolve, reject) => {
356
- const onAbort = () => {
357
- callsSnapshot = snapshotCalls();
358
- void activeWorker.terminate();
359
- reject(abortReasonError(externalSignal.reason));
360
- };
361
- externalSignal.addEventListener("abort", onAbort, { once: true });
362
- removeAbortListener = () => externalSignal.removeEventListener("abort", onAbort);
363
- })
364
- : new Promise<never>(() => {});
365
-
366
- await Promise.race([execution, timeout, aborted]);
367
- } catch (error) {
368
- if (error instanceof McpScriptCaptureError) {
369
- errorCode = "call_capture_failed";
370
- errorMessage = error.message;
371
- recovery = error.recovery;
372
- } else if (error instanceof McpScriptTimeoutError) {
373
- errorCode = "timeout";
374
- errorMessage = `mcp_script timed out after ${resolvedTimeoutMs}ms`;
375
- } else if (externalSignal?.aborted) {
376
- errorCode = "aborted";
377
- errorMessage = error instanceof Error ? error.message : String(error);
378
- } else {
379
- errorCode = "script_error";
380
- errorMessage = error instanceof Error ? error.message : String(error);
381
- }
382
- output.push({ type: "text", text: errorMessage });
383
- } finally {
384
- clearTimeout(timer);
385
- removeAbortListener();
386
- // "incomplete" means the call had not settled when the script finished
387
- // (deadline, abort, or early return). Snapshot before aborting stragglers.
388
- callsSnapshot ??= snapshotCalls();
389
- // A script may finish without awaiting every call; abort leftovers so
390
- // parent-side dispatches do not outlive the script.
391
- timeoutController.abort(new Error("mcp_script finished"));
392
- await worker?.terminate();
393
- }
394
-
395
- // Snapshot before the asynchronous output guard; the terminated worker can no longer emit.
396
- const guarded = await guardMcpOutput(
397
- [...(output.length > 0 ? output : [{ type: "text" as const, text: "(no output)" }]), ...[...payloadNotices].map(text => ({ type: "text" as const, text })), ...[...resultRefs].map(ref => ({ type: "text" as const, text: formatMcpResultReference(ref) }))],
398
- resolveMcpOutputGuardOptions(state.config.settings, state.outputDirectory),
399
- );
400
- return {
401
- content: guarded.content,
402
- details: {
403
- mode: "script",
404
- ...(resultRefs.size ? { resultRefs: [...resultRefs] } : {}),
405
- ...(errorCode ? { error: errorCode, message: errorMessage } : {}),
406
- timeoutMs: resolvedTimeoutMs,
407
- ...(recovery !== undefined ? { recovery } : {}),
408
- ...(callsSnapshot.length > 0 ? { calls: callsSnapshot } : {}),
409
- ...guardedMcpDetails(guarded),
410
- },
411
- };
412
- }
@@ -1,89 +0,0 @@
1
- #!/usr/bin/env node
2
- 'use strict';
3
-
4
- const { createRequire } = require('node:module');
5
- const { dirname, join } = require('node:path');
6
-
7
- const requireFromHere = createRequire(__filename);
8
-
9
- function loadKeyringEntryClass() {
10
- try {
11
- return requireFromHere('@napi-rs/keyring').Entry;
12
- } catch (loaderError) {
13
- const suffixes = getNativeBindingSuffixes(process.platform, process.arch);
14
- let lastError;
15
- for (const suffix of suffixes) {
16
- try {
17
- const packageJsonPath = requireFromHere.resolve(`@napi-rs/keyring-${suffix}/package.json`);
18
- return requireFromHere(join(dirname(packageJsonPath), `keyring.${suffix}.node`)).Entry;
19
- } catch (error) {
20
- lastError = error;
21
- }
22
- }
23
- const error = new Error(`Failed to load @napi-rs/keyring in recovery helper: ${lastError?.message ?? loaderError.message}`);
24
- error.cause = loaderError;
25
- throw error;
26
- }
27
- }
28
-
29
- function getNativeBindingSuffixes(platform, arch) {
30
- if (platform === 'linux') {
31
- if (arch === 'arm64') return ['linux-arm64-gnu', 'linux-arm64-musl'];
32
- if (arch === 'arm') return ['linux-arm-gnueabihf'];
33
- if (arch === 'riscv64') return ['linux-riscv64-gnu'];
34
- if (arch === 'x64') return ['linux-x64-gnu', 'linux-x64-musl'];
35
- }
36
- return [];
37
- }
38
-
39
- function readStdin() {
40
- return new Promise((resolve, reject) => {
41
- let input = '';
42
- process.stdin.setEncoding('utf8');
43
- process.stdin.on('data', chunk => {
44
- input += chunk;
45
- if (input.length > 1024 * 1024) {
46
- reject(new Error('request too large'));
47
- process.stdin.destroy();
48
- }
49
- });
50
- process.stdin.on('error', reject);
51
- process.stdin.on('end', () => resolve(input));
52
- });
53
- }
54
-
55
- function writeResponse(response) {
56
- process.stdout.write(`${JSON.stringify(response)}\n`);
57
- }
58
-
59
- (async () => {
60
- try {
61
- const request = JSON.parse(await readStdin());
62
- if (!request || typeof request !== 'object') throw new Error('invalid request');
63
- const { operation, service, account, payload } = request;
64
- if (!['read', 'write', 'remove'].includes(operation)) throw new Error('invalid operation');
65
- if (typeof service !== 'string' || !service) throw new Error('invalid service');
66
- if (typeof account !== 'string' || !account) throw new Error('invalid account');
67
-
68
- const Entry = loadKeyringEntryClass();
69
- const entry = new Entry(service, account);
70
-
71
- if (operation === 'read') {
72
- const value = entry.getPassword();
73
- writeResponse(value === null ? { ok: true, found: false } : { ok: true, found: true, value });
74
- return;
75
- }
76
- if (operation === 'write') {
77
- if (typeof payload !== 'string') throw new Error('invalid payload');
78
- entry.setPassword(payload);
79
- writeResponse({ ok: true });
80
- return;
81
- }
82
-
83
- entry.deleteCredential();
84
- writeResponse({ ok: true });
85
- } catch (error) {
86
- writeResponse({ ok: false, error: error instanceof Error ? error.message : String(error) });
87
- process.exitCode = 1;
88
- }
89
- })();