@fitchmultz/pi-mcp-adapter 6.0.0 → 7.0.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 (105) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +12 -8
  3. package/dist/app-bridge.bundle.js +14 -14
  4. package/dist/config.js +41 -16
  5. package/dist/gateway-arguments.d.ts +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/lifecycle.d.ts +2 -2
  8. package/dist/lifecycle.js +2 -2
  9. package/dist/mcp-auth-flow.js +2 -2
  10. package/dist/mcp-auth.d.ts +1 -1
  11. package/dist/mcp-auth.js +3 -3
  12. package/dist/mcp-code.d.ts +6 -6
  13. package/dist/mcp-code.js +11 -10
  14. package/dist/mcp-oauth-provider.d.ts +5 -5
  15. package/dist/mcp-oauth-provider.js +5 -5
  16. package/dist/mcp-output-guard.d.ts +1 -1
  17. package/dist/mcp-panel.d.ts +2 -2
  18. package/dist/mcp-panel.js +2 -2
  19. package/dist/mcp-setup-panel.d.ts +5 -4
  20. package/dist/mcp-setup-panel.js +15 -7
  21. package/dist/mcp-trace.d.ts +1 -1
  22. package/dist/mcp-trace.js +1 -1
  23. package/dist/npx-resolver.js +8 -4
  24. package/dist/proxy-modes.d.ts +2 -2
  25. package/dist/proxy-modes.js +9 -9
  26. package/dist/sampling-handler.js +1 -0
  27. package/dist/search-ranking.js +6 -2
  28. package/dist/server-manager.d.ts +2 -2
  29. package/dist/server-manager.js +44 -27
  30. package/dist/session-recovery.d.ts +7 -4
  31. package/dist/session-recovery.js +76 -10
  32. package/dist/tool-metadata.d.ts +43 -43
  33. package/dist/tool-result-renderer.d.ts +3 -3
  34. package/dist/tool-result-renderer.js +3 -3
  35. package/dist/ui-resource-handler.d.ts +2 -2
  36. package/dist/ui-resource-handler.js +2 -2
  37. package/dist/ui-server.js +4 -3
  38. package/dist/ui-stream-types.d.ts +8 -8
  39. package/dist/unix-socket-transport.d.ts +1 -1
  40. package/dist/unix-socket-transport.js +1 -1
  41. package/dist/utils.d.ts +1 -0
  42. package/dist/utils.js +14 -0
  43. package/package.json +34 -98
  44. package/abort.ts +0 -34
  45. package/agent-dir.ts +0 -24
  46. package/app-bridge.bundle.js +0 -109
  47. package/banner.png +0 -0
  48. package/checkpoint.ts +0 -55
  49. package/commands.ts +0 -622
  50. package/config.ts +0 -1204
  51. package/consent-manager.ts +0 -25
  52. package/direct-tools.ts +0 -75
  53. package/elicitation-handler.ts +0 -349
  54. package/error-signal.ts +0 -21
  55. package/gateway-arguments.ts +0 -73
  56. package/glimpse-ui.ts +0 -80
  57. package/host-html-template.ts +0 -456
  58. package/index.ts +0 -767
  59. package/init.ts +0 -613
  60. package/legacy-migration.ts +0 -47
  61. package/lifecycle.ts +0 -165
  62. package/logger.ts +0 -127
  63. package/mcp-auth-flow.ts +0 -975
  64. package/mcp-auth.ts +0 -793
  65. package/mcp-callback-server.ts +0 -450
  66. package/mcp-code.ts +0 -412
  67. package/mcp-keyring-helper.cjs +0 -89
  68. package/mcp-oauth-provider.ts +0 -774
  69. package/mcp-output-guard.ts +0 -530
  70. package/mcp-panel.ts +0 -907
  71. package/mcp-script-worker.mjs +0 -131
  72. package/mcp-setup-panel.ts +0 -666
  73. package/mcp-status.ts +0 -110
  74. package/mcp-trace.ts +0 -295
  75. package/metadata-cache.ts +0 -271
  76. package/npx-resolver.ts +0 -488
  77. package/onboarding-state.ts +0 -58
  78. package/panel-keys.ts +0 -37
  79. package/prompts.ts +0 -337
  80. package/proxy-modes.ts +0 -1109
  81. package/resource-tools.ts +0 -52
  82. package/runtime-owner.ts +0 -123
  83. package/sampling-handler.ts +0 -276
  84. package/scripts/build-app-bridge.mjs +0 -15
  85. package/scripts/build.mjs +0 -132
  86. package/scripts/prepare.mjs +0 -103
  87. package/search-ranking.ts +0 -132
  88. package/server-manager.ts +0 -1320
  89. package/session-recovery.ts +0 -316
  90. package/state.ts +0 -64
  91. package/tool-approval.ts +0 -78
  92. package/tool-loader.ts +0 -153
  93. package/tool-metadata.ts +0 -240
  94. package/tool-registrar.ts +0 -74
  95. package/tool-result-renderer.ts +0 -294
  96. package/tsconfig.build.json +0 -13
  97. package/tsconfig.json +0 -16
  98. package/types.ts +0 -785
  99. package/ui-resource-handler.ts +0 -249
  100. package/ui-server.ts +0 -808
  101. package/ui-session.ts +0 -568
  102. package/ui-stream-types.ts +0 -89
  103. package/ui-tool-visibility.ts +0 -25
  104. package/unix-socket-transport.ts +0 -85
  105. package/utils.ts +0 -307
@@ -1,530 +0,0 @@
1
- import { randomBytes } from "node:crypto";
2
- import { mkdir, mkdtemp, readFile, realpath, writeFile } from "node:fs/promises";
3
- import { tmpdir } from "node:os";
4
- import { basename, dirname, join, resolve } from "node:path";
5
- import type { ContentBlock, McpSettings } from "./types.ts";
6
-
7
- export const DEFAULT_MCP_OUTPUT_MAX_BYTES = 50 * 1024;
8
- export const DEFAULT_MCP_OUTPUT_MAX_LINES = 2000;
9
- export const DEFAULT_MCP_DETAILS_MAX_BYTES = 16 * 1024;
10
-
11
- const CONTENT_SUMMARY_LIMIT = 20;
12
- const KEY_PREVIEW_LIMIT = 20;
13
- const KEY_MAX_CHARS = 120;
14
-
15
- type Recordish = Record<string, unknown>;
16
-
17
- export interface McpOutputGuardDetails {
18
- truncated: true;
19
- originalBytes: number;
20
- returnedBytes: number;
21
- originalLines: number;
22
- returnedLines: number;
23
- /** Number of image content blocks returned untouched alongside the truncated text. */
24
- imageBlocksPassedThrough?: number;
25
- fullOutputPath?: string;
26
- writeError?: string;
27
- }
28
-
29
- export interface McpResultSummary {
30
- omitted: true;
31
- reason: string;
32
- isError: boolean;
33
- contentBlocks: number;
34
- contentSummary: Array<Record<string, unknown>>;
35
- structuredContentSummary?: Record<string, unknown>;
36
- meta?: Record<string, unknown>;
37
- extraFields?: Array<Record<string, unknown>>;
38
- rawResultBytes: number;
39
- fullResultPath?: string;
40
- resultWriteError?: string;
41
- }
42
-
43
- export interface McpOutputGuardOptions {
44
- enabled?: boolean;
45
- outputDirectory?: string;
46
- prefix?: string;
47
- suffix?: string;
48
- emptyTextFallback?: string;
49
- maxBytes?: number;
50
- maxLines?: number;
51
- detailsMaxBytes?: number;
52
- /**
53
- * Raw MCP result to expose as details.mcpResult. Kept raw when its JSON
54
- * fits detailsMaxBytes (or when the guard is disabled); otherwise replaced
55
- * with a compact summary and spilled to a file. Payloads that are not fully
56
- * visible as plain text also get a model-visible reference for local readback.
57
- */
58
- rawMcpResult?: unknown;
59
- retainedMcpResult?: RetainedMcpResult;
60
- }
61
-
62
- export interface GuardedMcpOutput {
63
- content: ContentBlock[];
64
- outputGuard?: McpOutputGuardDetails;
65
- mcpResult?: unknown;
66
- resultRef?: string;
67
- resultWriteError?: string;
68
- payloadFiles?: McpPayloadFile[];
69
- }
70
-
71
- export interface McpPayloadFile {
72
- index: number;
73
- kind: "audio" | "resource";
74
- uri?: string;
75
- mimeType?: string;
76
- path?: string;
77
- error?: string;
78
- }
79
- export type RetainedMcpResult = Pick<GuardedMcpOutput, "mcpResult" | "resultRef" | "resultWriteError" | "payloadFiles">;
80
-
81
- export function resolveMcpOutputGuardOptions(settings?: McpSettings, outputDirectory?: string): Pick<McpOutputGuardOptions, "enabled" | "maxBytes" | "maxLines" | "detailsMaxBytes" | "outputDirectory"> {
82
- const configured = settings?.outputGuard;
83
- const tuning = typeof configured === "object" && configured !== null ? configured : undefined;
84
- return {
85
- enabled: envKillSwitch("MCP_OUTPUT_GUARD") ?? configured !== false,
86
- ...(outputDirectory !== undefined ? { outputDirectory } : {}),
87
- maxBytes: positiveInt(tuning?.maxBytes) ?? DEFAULT_MCP_OUTPUT_MAX_BYTES,
88
- maxLines: positiveInt(tuning?.maxLines) ?? DEFAULT_MCP_OUTPUT_MAX_LINES,
89
- detailsMaxBytes: positiveInt(tuning?.detailsMaxBytes) ?? DEFAULT_MCP_DETAILS_MAX_BYTES,
90
- };
91
- }
92
-
93
- /** Spread helper for tool-result details: includes mcpResult/outputGuard only when present. */
94
- export function guardedMcpDetails(guarded: GuardedMcpOutput): Record<string, unknown> {
95
- return {
96
- ...(guarded.mcpResult !== undefined ? { mcpResult: guarded.mcpResult } : {}),
97
- ...(guarded.outputGuard ? { outputGuard: guarded.outputGuard } : {}),
98
- ...(guarded.resultRef ? { resultRef: guarded.resultRef } : {}),
99
- ...(guarded.resultWriteError ? { resultWriteError: guarded.resultWriteError } : {}),
100
- ...(guarded.payloadFiles?.length ? { payloadFiles: guarded.payloadFiles } : {}),
101
- };
102
- }
103
-
104
- /**
105
- * Bound model-facing MCP output. Text output is capped at maxBytes/maxLines and
106
- * spilled to a temp file when oversized. Image blocks pass through untouched —
107
- * they are delivered to the provider as native image content, not text context.
108
- */
109
- export async function guardMcpOutput(
110
- content: ContentBlock[],
111
- options: McpOutputGuardOptions = {},
112
- ): Promise<GuardedMcpOutput> {
113
- const maxBytes = options.maxBytes ?? DEFAULT_MCP_OUTPUT_MAX_BYTES;
114
- const maxLines = options.maxLines ?? DEFAULT_MCP_OUTPUT_MAX_LINES;
115
- const prefix = options.prefix ?? "";
116
- const suffix = options.suffix ?? "";
117
-
118
- const normalizedContent = withEmptyTextFallback(
119
- content.length > 0
120
- ? sanitizeContent(content)
121
- : [{ type: "text" as const, text: options.emptyTextFallback ?? "(empty result)" }],
122
- options.emptyTextFallback,
123
- );
124
-
125
- const retained = options.retainedMcpResult ?? (options.rawMcpResult === undefined ? {} : await retainMcpResult(options.rawMcpResult, options));
126
- const reference = retained.resultRef ? formatMcpResultReference(retained.resultRef)
127
- : retained.resultWriteError ? `[MCP result could not be saved: ${retained.resultWriteError}]` : undefined;
128
- const withReference = (blocks: ContentBlock[]) => reference ? [...blocks, { type: "text" as const, text: reference }] : blocks;
129
- if (options.enabled === false) return { content: withReference(addAffixes(normalizedContent, prefix, suffix)), ...retained };
130
-
131
- const imageBlocks = normalizedContent.filter((block) => block.type === "image");
132
- const textOutput = normalizedContent
133
- .filter((block) => block.type === "text")
134
- .map((block) => (block as { text: string }).text)
135
- .join("\n");
136
- const composedOutput = `${prefix}${textOutput}${suffix}`;
137
- const stats = textStats(composedOutput);
138
- const referenceSuffix = reference ? `\n${reference}` : "";
139
- const totalStats = textStats(composedOutput ? composedOutput + referenceSuffix : reference ?? "");
140
-
141
- let guardedContent: ContentBlock[] = addAffixes(normalizedContent, prefix, suffix);
142
- let outputGuard: McpOutputGuardDetails | undefined;
143
-
144
- if (totalStats.bytes > maxBytes || totalStats.lines > maxLines) {
145
- const { path: fullOutputPath, error: writeError } = await saveArtifact("output", composedOutput, options.outputDirectory);
146
- const notice = formatTruncationNotice(stats, fullOutputPath, writeError);
147
- const previewBudget = reserveBudget(maxBytes, maxLines, notice + referenceSuffix);
148
- const preview = truncateHead(composedOutput, previewBudget.maxBytes, previewBudget.maxLines);
149
- const finalText = `${preview.content}\n\n${notice}`;
150
- const finalStats = textStats(finalText + referenceSuffix);
151
-
152
- guardedContent = [{ type: "text" as const, text: finalText }, ...imageBlocks];
153
- outputGuard = {
154
- truncated: true,
155
- originalBytes: stats.bytes,
156
- returnedBytes: finalStats.bytes,
157
- originalLines: stats.lines,
158
- returnedLines: finalStats.lines,
159
- ...(imageBlocks.length > 0 ? { imageBlocksPassedThrough: imageBlocks.length } : {}),
160
- ...(fullOutputPath !== undefined ? { fullOutputPath } : {}),
161
- ...(writeError !== undefined ? { writeError } : {}),
162
- };
163
- }
164
-
165
- return {
166
- content: withReference(guardedContent),
167
- ...(outputGuard ? { outputGuard } : {}),
168
- ...retained,
169
- };
170
- }
171
-
172
- function sanitizeContent(content: ContentBlock[]): ContentBlock[] {
173
- return content.map((block) => {
174
- if (block.type !== "image") return block;
175
- const mimeType = typeof block.mimeType === "string" && block.mimeType.trim()
176
- ? block.mimeType.trim().slice(0, 100)
177
- : "image/png";
178
- return { ...block, mimeType };
179
- });
180
- }
181
-
182
- function withEmptyTextFallback(content: ContentBlock[], fallback: string | undefined): ContentBlock[] {
183
- if (!fallback) return content;
184
- const textOutput = content
185
- .filter((block) => block.type === "text")
186
- .map((block) => (block as { text: string }).text)
187
- .join("\n");
188
- if (textOutput) return content;
189
- return [{ type: "text", text: fallback }, ...content.filter((block) => block.type === "image")];
190
- }
191
-
192
- function addAffixes(content: ContentBlock[], prefix: string, suffix: string): ContentBlock[] {
193
- if (!prefix && !suffix) return content;
194
- const next: ContentBlock[] = [...content];
195
-
196
- if (prefix) {
197
- const index = next.findIndex((block) => block.type === "text");
198
- const block = next[index];
199
- if (block?.type === "text") {
200
- next[index] = { ...block, text: `${prefix}${block.text}` };
201
- } else {
202
- next.unshift({ type: "text", text: prefix });
203
- }
204
- }
205
-
206
- if (suffix) {
207
- let index = -1;
208
- for (let i = next.length - 1; i >= 0; i--) {
209
- if (next[i]?.type === "text") {
210
- index = i;
211
- break;
212
- }
213
- }
214
- const block = next[index];
215
- if (block?.type === "text") {
216
- next[index] = { ...block, text: `${block.text}${suffix}` };
217
- } else {
218
- next.push({ type: "text", text: suffix });
219
- }
220
- }
221
-
222
- return next;
223
- }
224
-
225
- function reserveBudget(maxBytes: number, maxLines: number, notice: string): { maxBytes: number; maxLines: number } {
226
- const noticeStats = textStats(`\n\n${notice}`);
227
- return {
228
- maxBytes: Math.max(0, maxBytes - noticeStats.bytes),
229
- maxLines: Math.max(0, maxLines - noticeStats.lines),
230
- };
231
- }
232
-
233
- function truncateHead(text: string, maxBytes: number, maxLines: number): { content: string; bytes: number; lines: number } {
234
- const lines = text.split("\n");
235
- const output: string[] = [];
236
- let bytes = 0;
237
-
238
- for (const line of lines) {
239
- if (output.length >= maxLines) break;
240
- const separatorBytes = output.length > 0 ? 1 : 0;
241
- const lineBytes = byteLength(line);
242
- if (bytes + separatorBytes + lineBytes > maxBytes) {
243
- const remaining = maxBytes - bytes - separatorBytes;
244
- if (remaining > 0) {
245
- output.push(truncateStringToBytes(line, remaining));
246
- }
247
- break;
248
- }
249
- output.push(line);
250
- bytes += separatorBytes + lineBytes;
251
- }
252
-
253
- const content = output.join("\n");
254
- const stats = textStats(content);
255
- return { content, bytes: stats.bytes, lines: stats.lines };
256
- }
257
-
258
- function truncateStringToBytes(value: string, maxBytes: number): string {
259
- if (byteLength(value) <= maxBytes) return value;
260
- const buffer = Buffer.from(value, "utf8");
261
- let end = Number.isFinite(maxBytes) ? Math.max(0, Math.floor(maxBytes)) : 0;
262
- while (end > 0 && (buffer.readUInt8(end) & 0xc0) === 0x80) end--;
263
- return buffer.subarray(0, end).toString("utf8");
264
- }
265
-
266
- function formatTruncationNotice(
267
- stats: { bytes: number; lines: number },
268
- fullOutputPath: string | undefined,
269
- writeError: string | undefined,
270
- ): string {
271
- const base = `[MCP text output truncated: original ${stats.lines.toLocaleString()} lines / ${formatSize(stats.bytes)}.`;
272
- if (fullOutputPath) {
273
- return `${base} Full text saved to: ${fullOutputPath} — use read with offset/limit or grep to inspect.]`;
274
- }
275
- return `${base} Full output could not be saved: ${writeError ?? "unknown error"}]`;
276
- }
277
-
278
- /**
279
- * Bound details.mcpResult: keep the raw result when its JSON fits within
280
- * detailsMaxBytes; otherwise replace it with a compact summary and spill the
281
- * raw JSON to a temp file.
282
- */
283
- export async function retainMcpResult(result: unknown, options: McpOutputGuardOptions = {}, rawResult = false): Promise<RetainedMcpResult> {
284
- const raw = safeStringify(result);
285
- const rawBytes = byteLength(raw);
286
- const record = asRecord(result);
287
- const content = Array.isArray(record?.content) ? record.content
288
- : Array.isArray(record?.contents) ? record.contents.map(resource => ({ type: "resource", resource })) : [];
289
- const payloadFiles = (await Promise.all(content.map(async (block, index): Promise<McpPayloadFile | undefined> => {
290
- const item = asRecord(block);
291
- const resource = asRecord(item?.resource);
292
- const data = item?.type === "audio" ? item.data : item?.type === "resource" ? resource?.blob : undefined;
293
- if (typeof data !== "string") return undefined;
294
- const mimeType = item?.mimeType ?? resource?.mimeType;
295
- return { index, kind: item!.type as "audio" | "resource", ...(typeof resource?.uri === "string" ? { uri: resource.uri } : {}), ...(typeof mimeType === "string" ? { mimeType } : {}), ...await saveArtifact("payload", Buffer.from(data, "base64"), options.outputDirectory) };
296
- }))).filter((file): file is McpPayloadFile => file !== undefined);
297
- const oversized = options.enabled !== false && rawBytes > (options.detailsMaxBytes ?? DEFAULT_MCP_DETAILS_MAX_BYTES);
298
- const shouldSave = oversized || !record || Object.keys(record).some(key => key !== "content" && key !== "isError")
299
- || content.some(block => {
300
- const item = asRecord(block);
301
- return item?.type !== "text" || Object.keys(item).some(key => key !== "type" && key !== "text");
302
- });
303
- if (!shouldSave) return { mcpResult: result };
304
- const artifact = await saveArtifact("mcp-result", raw, options.outputDirectory);
305
- return {
306
- mcpResult: oversized && !rawResult ? summarizeMcpResult(result, rawBytes, artifact) : result,
307
- ...(artifact.path ? { resultRef: artifact.path } : {}),
308
- ...(artifact.error ? { resultWriteError: artifact.error } : {}),
309
- ...(payloadFiles.length ? { payloadFiles } : {}),
310
- };
311
- }
312
-
313
- export function formatMcpPayloadFile(file: McpPayloadFile): string {
314
- return `[MCP ${file.kind === "audio" ? "audio" : "binary resource"}${file.uri ? ` (${file.uri})` : ""}: ${file.mimeType ?? "unknown MIME type"}; not rendered. ${file.path ? `Saved file: ${file.path}` : `Could not save: ${file.error}`}]`;
315
- }
316
-
317
- export function formatMcpResultReference(ref: string): string {
318
- return `[MCP result saved: ${JSON.stringify(ref)}. Inspect without repeating the call using mcp action "read-result" or tools.readResult with this ref. Optionally select a JSON Pointer with path.]`;
319
- }
320
-
321
- function summarizeMcpResult(result: unknown, rawBytes: number, artifact: { path?: string; error?: string }): McpResultSummary {
322
- const { path: fullResultPath, error: resultWriteError } = artifact;
323
- const record = asRecord(result);
324
- const content = Array.isArray(record?.content) ? record.content : [];
325
- const summary: McpResultSummary = {
326
- omitted: true,
327
- reason: "Raw MCP result exceeded the details size limit and was replaced with this summary to keep session context bounded.",
328
- isError: record?.isError === true,
329
- contentBlocks: content.length,
330
- contentSummary: summarizeContent(content),
331
- rawResultBytes: rawBytes,
332
- ...(fullResultPath !== undefined ? { fullResultPath } : {}),
333
- ...(resultWriteError !== undefined ? { resultWriteError } : {}),
334
- };
335
-
336
- if (record && "structuredContent" in record) {
337
- summary.structuredContentSummary = summarizeValue(record.structuredContent);
338
- }
339
- if (record && "_meta" in record) {
340
- summary.meta = summarizeValue(record._meta);
341
- }
342
- if (record) {
343
- const standard = new Set(["content", "isError", "structuredContent", "_meta"]);
344
- const extraFields = Object.keys(record)
345
- .filter((key) => !standard.has(key))
346
- .slice(0, KEY_PREVIEW_LIMIT)
347
- .map((key) => ({ key: truncateKey(key), type: typeof record[key], estimatedBytes: estimateValueBytes(record[key]), omitted: true }));
348
- if (extraFields.length > 0) summary.extraFields = extraFields;
349
- }
350
-
351
- return summary;
352
- }
353
-
354
- function summarizeContent(content: unknown[]): Array<Record<string, unknown>> {
355
- const summaries: Array<Record<string, unknown>> = content.slice(0, CONTENT_SUMMARY_LIMIT).map((block) => {
356
- const record = asRecord(block);
357
- if (!record) return { type: typeof block, omitted: true };
358
- if (record.type === "text") {
359
- const text = typeof record.text === "string" ? record.text : "";
360
- return { type: "text", bytes: byteLength(text), lines: textStats(text).lines, textOmitted: true };
361
- }
362
- if (record.type === "image") {
363
- const data = typeof record.data === "string" ? record.data : "";
364
- return { type: "image", mimeType: typeof record.mimeType === "string" ? record.mimeType : undefined, dataBytes: byteLength(data), dataOmitted: true };
365
- }
366
- return { type: typeof record.type === "string" ? record.type : "unknown", estimatedBytes: estimateValueBytes(record), omitted: true };
367
- });
368
- if (content.length > CONTENT_SUMMARY_LIMIT) {
369
- summaries.push({ type: "omitted", count: content.length - CONTENT_SUMMARY_LIMIT });
370
- }
371
- return summaries;
372
- }
373
-
374
- function summarizeValue(value: unknown): Record<string, unknown> {
375
- const record = asRecord(value);
376
- if (!record) {
377
- return { type: value === null ? "null" : typeof value, estimatedBytes: estimateValueBytes(value), omitted: true };
378
- }
379
- const keys = Object.keys(record);
380
- return {
381
- type: Array.isArray(value) ? "array" : "object",
382
- estimatedBytes: estimateValueBytes(value),
383
- keyCount: keys.length,
384
- keysPreview: keys.slice(0, KEY_PREVIEW_LIMIT).map(truncateKey),
385
- omitted: true,
386
- };
387
- }
388
-
389
- function estimateValueBytes(value: unknown, depth = 0): number {
390
- if (value === null || value === undefined) return 0;
391
- if (typeof value === "string") return byteLength(value);
392
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return byteLength(String(value));
393
- const record = asRecord(value);
394
- if (!record || depth >= 2) return 0;
395
- const values = Array.isArray(value) ? value.slice(0, KEY_PREVIEW_LIMIT) : Object.values(record).slice(0, KEY_PREVIEW_LIMIT);
396
- return values.reduce((total, item) => total + estimateValueBytes(item, depth + 1), 0);
397
- }
398
-
399
- function truncateKey(key: string): string {
400
- return key.length <= KEY_MAX_CHARS ? key : `${key.slice(0, KEY_MAX_CHARS - 1)}…`;
401
- }
402
-
403
- async function saveArtifact(kind: string, text: string | Uint8Array, outputDirectory?: string): Promise<{ path?: string; error?: string }> {
404
- try {
405
- const parent = outputDirectory === undefined ? tmpdir() : resolve(outputDirectory);
406
- if (outputDirectory !== undefined) await mkdir(parent, { recursive: true, mode: 0o700 });
407
- const dir = await mkdtemp(join(parent, "pi-mcp-output-"));
408
- const path = join(dir, `${kind}-${randomBytes(4).toString("hex")}.${typeof text === "string" ? "txt" : "bin"}`);
409
- await writeFile(path, text, { encoding: "utf8", mode: 0o600 });
410
- return { path };
411
- } catch (error) {
412
- return { error: error instanceof Error ? error.message : String(error) };
413
- }
414
- }
415
-
416
- export interface ReadMcpResultInput {
417
- ref: string;
418
- /** RFC 6901 JSON Pointer. Omit to read the entire retained result. */
419
- path?: string;
420
- fields?: string[];
421
- /** Zero-based character offset in the selected, pretty-printed value. */
422
- offset?: number;
423
- /** Maximum characters, additionally bounded by the configured output limits. */
424
- limit?: number;
425
- }
426
-
427
- export async function readMcpResult(input: ReadMcpResultInput, options: McpOutputGuardOptions = {}) {
428
- try {
429
- if (!input || typeof input.ref !== "string") throw new Error("ref must be a retained MCP result path");
430
- // Script-only hosts deliberately have no general filesystem capability.
431
- const root = await realpath(options.outputDirectory === undefined ? tmpdir() : resolve(options.outputDirectory));
432
- const ref = await realpath(resolve(input.ref));
433
- if (dirname(dirname(ref)) !== root || !/^pi-mcp-output-/.test(basename(dirname(ref)))
434
- || !/^(mcp-result|output)-[a-f0-9]+\.txt$/.test(basename(ref))) throw new Error("ref is not an MCP output artifact in this host's output directory");
435
- let rendered = await readFile(ref, "utf8");
436
- if (input.path !== undefined || input.fields !== undefined || basename(ref).startsWith("mcp-result-")) {
437
- let value: unknown = JSON.parse(rendered);
438
- if (input.path !== undefined && input.path !== "") {
439
- if (typeof input.path !== "string" || !input.path.startsWith("/") || /~(?:[^01]|$)/.test(input.path)) throw new Error("path must be an RFC 6901 JSON Pointer");
440
- for (const token of input.path.slice(1).split("/")) {
441
- const key = token.replace(/~1/g, "/").replace(/~0/g, "~");
442
- if (value === null || typeof value !== "object" || (Array.isArray(value) && !/^(0|[1-9]\d*)$/.test(key)) || !Object.hasOwn(value, key)) throw new Error(`JSON Pointer does not exist: ${input.path}`);
443
- value = (value as Record<string, unknown>)[key];
444
- }
445
- }
446
- if (input.fields !== undefined) {
447
- if (!Array.isArray(input.fields) || input.fields.some(field => typeof field !== "string")) throw new Error("fields must be an array of keys");
448
- const select = (item: unknown) => {
449
- if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error("fields requires an object or array of objects");
450
- return Object.fromEntries(input.fields!.filter(key => Object.hasOwn(item, key)).map(key => [key, (item as Record<string, unknown>)[key]]));
451
- };
452
- value = Array.isArray(value) ? value.map(select) : select(value);
453
- }
454
- rendered = JSON.stringify(value, null, 2);
455
- }
456
- const offset = input.offset ?? 0;
457
- const limit = input.limit ?? 12_000;
458
- if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1) throw new Error("offset must be a non-negative integer and limit a positive integer");
459
- if (offset > 0 && rendered.codePointAt(offset - 1)! > 0xffff) throw new Error("offset must not split a Unicode surrogate pair");
460
- const maxBytes = options.maxBytes ?? DEFAULT_MCP_OUTPUT_MAX_BYTES;
461
- const maxLines = options.maxLines ?? DEFAULT_MCP_OUTPUT_MAX_LINES;
462
- const notice = (end: number) => `[MCP result page: ${offset}–${end} of ${rendered.length} characters. Continue with offset: ${end}.]`;
463
- const pageEnd = (byteCap: number, lineCap: number) => {
464
- let end = offset;
465
- let bytes = 0;
466
- let lines = 1;
467
- while (end < rendered.length && end - offset < limit) {
468
- const width = rendered.codePointAt(end)! > 0xffff ? 2 : 1;
469
- const char = rendered.slice(end, end + width);
470
- bytes += byteLength(char);
471
- if (char === "\n") lines++;
472
- // Tiny caps still return one complete character plus recovery guidance.
473
- if (end > offset && (bytes > byteCap || lines > lineCap || end + width - offset > limit)) break;
474
- end += width;
475
- }
476
- return end;
477
- };
478
- let end = pageEnd(maxBytes, maxLines);
479
- if (end < rendered.length) {
480
- // The final offset cannot need more digits than the total length. Include the block separator.
481
- end = pageEnd(maxBytes - byteLength(notice(rendered.length)) - 1, maxLines - 1);
482
- }
483
- const nextOffset = end < rendered.length ? end : null;
484
- return { content: [{ type: "text" as const, text: rendered.slice(offset, end) }, ...(nextOffset !== null ? [{ type: "text" as const, text: notice(end) }] : [])], details: { ref, offset, nextOffset, totalCharacters: rendered.length, ...(input.path !== undefined ? { path: input.path } : {}) } };
485
- } catch (error) {
486
- const message = error instanceof Error ? error.message : String(error);
487
- return { content: [{ type: "text" as const, text: message }], details: { error: "result_read_failed", message } };
488
- }
489
- }
490
-
491
- function asRecord(value: unknown): Recordish | undefined {
492
- return typeof value === "object" && value !== null ? value as Recordish : undefined;
493
- }
494
-
495
- function safeStringify(value: unknown): string {
496
- try {
497
- // The output guard measures and spills raw MCP results; it does not render this JSON for the model.
498
- return JSON.stringify(value);
499
- } catch {
500
- return String(value);
501
- }
502
- }
503
-
504
- function textStats(text: string): { bytes: number; lines: number } {
505
- return { bytes: byteLength(text), lines: text.length === 0 ? 0 : text.split("\n").length };
506
- }
507
-
508
- function byteLength(text: string): number {
509
- return Buffer.byteLength(text, "utf8");
510
- }
511
-
512
- function positiveInt(value: unknown): number | undefined {
513
- if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
514
- const integer = Math.floor(value);
515
- return integer > 0 ? integer : undefined;
516
- }
517
-
518
- function envKillSwitch(name: string): boolean | undefined {
519
- const value = process.env[name]?.trim().toLowerCase();
520
- if (!value) return undefined;
521
- if (["0", "false", "no", "off"].includes(value)) return false;
522
- if (["1", "true", "yes", "on"].includes(value)) return true;
523
- return undefined;
524
- }
525
-
526
- function formatSize(bytes: number): string {
527
- if (bytes < 1024) return `${bytes} B`;
528
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
529
- return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
530
- }