@fitchmultz/pi-mcp-adapter 5.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 (176) hide show
  1. package/CHANGELOG.md +750 -0
  2. package/LICENSE +21 -0
  3. package/OAUTH.md +462 -0
  4. package/README.md +820 -0
  5. package/abort.ts +34 -0
  6. package/agent-dir.ts +24 -0
  7. package/app-bridge.bundle.js +67 -0
  8. package/banner.png +0 -0
  9. package/checkpoint.ts +55 -0
  10. package/cli.js +222 -0
  11. package/commands.ts +619 -0
  12. package/config.ts +1204 -0
  13. package/consent-manager.ts +25 -0
  14. package/direct-tools.ts +408 -0
  15. package/dist/abort.d.ts +2 -0
  16. package/dist/abort.js +35 -0
  17. package/dist/agent-dir.d.ts +3 -0
  18. package/dist/agent-dir.js +21 -0
  19. package/dist/app-bridge.bundle.js +67 -0
  20. package/dist/checkpoint.d.ts +18 -0
  21. package/dist/checkpoint.js +53 -0
  22. package/dist/commands.d.ts +20 -0
  23. package/dist/commands.js +521 -0
  24. package/dist/config.d.ts +109 -0
  25. package/dist/config.js +1013 -0
  26. package/dist/consent-manager.d.ts +8 -0
  27. package/dist/consent-manager.js +21 -0
  28. package/dist/direct-tools.d.ts +10 -0
  29. package/dist/direct-tools.js +350 -0
  30. package/dist/docs/client-metadata.json +14 -0
  31. package/dist/elicitation-handler.d.ts +17 -0
  32. package/dist/elicitation-handler.js +308 -0
  33. package/dist/error-signal.d.ts +15 -0
  34. package/dist/error-signal.js +21 -0
  35. package/dist/glimpse-ui.d.ts +9 -0
  36. package/dist/glimpse-ui.js +75 -0
  37. package/dist/host-html-template.d.ts +15 -0
  38. package/dist/host-html-template.js +429 -0
  39. package/dist/index.d.ts +7 -0
  40. package/dist/index.js +840 -0
  41. package/dist/init.d.ts +25 -0
  42. package/dist/init.js +562 -0
  43. package/dist/legacy-migration.d.ts +18 -0
  44. package/dist/legacy-migration.js +45 -0
  45. package/dist/lifecycle.d.ts +40 -0
  46. package/dist/lifecycle.js +167 -0
  47. package/dist/logger.d.ts +38 -0
  48. package/dist/logger.js +102 -0
  49. package/dist/mcp-auth-flow.d.ts +113 -0
  50. package/dist/mcp-auth-flow.js +834 -0
  51. package/dist/mcp-auth.d.ts +127 -0
  52. package/dist/mcp-auth.js +658 -0
  53. package/dist/mcp-callback-server.d.ts +56 -0
  54. package/dist/mcp-callback-server.js +371 -0
  55. package/dist/mcp-code.d.ts +51 -0
  56. package/dist/mcp-code.js +366 -0
  57. package/dist/mcp-keyring-helper.cjs +89 -0
  58. package/dist/mcp-oauth-provider.d.ts +154 -0
  59. package/dist/mcp-oauth-provider.js +672 -0
  60. package/dist/mcp-output-guard.d.ts +59 -0
  61. package/dist/mcp-output-guard.js +332 -0
  62. package/dist/mcp-panel.d.ts +66 -0
  63. package/dist/mcp-panel.js +889 -0
  64. package/dist/mcp-script-worker.mjs +128 -0
  65. package/dist/mcp-setup-panel.d.ts +84 -0
  66. package/dist/mcp-setup-panel.js +561 -0
  67. package/dist/mcp-status.d.ts +11 -0
  68. package/dist/mcp-status.js +96 -0
  69. package/dist/mcp-trace.d.ts +95 -0
  70. package/dist/mcp-trace.js +233 -0
  71. package/dist/metadata-cache.d.ts +18 -0
  72. package/dist/metadata-cache.js +277 -0
  73. package/dist/npx-resolver.d.ts +6 -0
  74. package/dist/npx-resolver.js +448 -0
  75. package/dist/onboarding-state.d.ts +11 -0
  76. package/dist/onboarding-state.js +47 -0
  77. package/dist/panel-keys.d.ts +16 -0
  78. package/dist/panel-keys.js +15 -0
  79. package/dist/prompts.d.ts +56 -0
  80. package/dist/prompts.js +284 -0
  81. package/dist/proxy-modes.d.ts +38 -0
  82. package/dist/proxy-modes.js +1235 -0
  83. package/dist/resource-tools.d.ts +1 -0
  84. package/dist/resource-tools.js +14 -0
  85. package/dist/runtime-owner.d.ts +18 -0
  86. package/dist/runtime-owner.js +117 -0
  87. package/dist/sampling-handler.d.ts +15 -0
  88. package/dist/sampling-handler.js +211 -0
  89. package/dist/search-ranking.d.ts +20 -0
  90. package/dist/search-ranking.js +180 -0
  91. package/dist/server-manager.d.ts +114 -0
  92. package/dist/server-manager.js +1175 -0
  93. package/dist/session-recovery.d.ts +31 -0
  94. package/dist/session-recovery.js +310 -0
  95. package/dist/state.d.ts +63 -0
  96. package/dist/state.js +1 -0
  97. package/dist/tool-approval.d.ts +10 -0
  98. package/dist/tool-approval.js +42 -0
  99. package/dist/tool-metadata.d.ts +9 -0
  100. package/dist/tool-metadata.js +193 -0
  101. package/dist/tool-registrar.d.ts +10 -0
  102. package/dist/tool-registrar.js +64 -0
  103. package/dist/tool-result-renderer.d.ts +45 -0
  104. package/dist/tool-result-renderer.js +224 -0
  105. package/dist/ts-shape.d.ts +2 -0
  106. package/dist/ts-shape.js +147 -0
  107. package/dist/types.d.ts +516 -0
  108. package/dist/types.js +168 -0
  109. package/dist/ui-resource-handler.d.ts +17 -0
  110. package/dist/ui-resource-handler.js +209 -0
  111. package/dist/ui-server.d.ts +51 -0
  112. package/dist/ui-server.js +669 -0
  113. package/dist/ui-session.d.ts +39 -0
  114. package/dist/ui-session.js +463 -0
  115. package/dist/ui-stream-types.d.ts +104 -0
  116. package/dist/ui-stream-types.js +58 -0
  117. package/dist/ui-tool-visibility.d.ts +4 -0
  118. package/dist/ui-tool-visibility.js +26 -0
  119. package/dist/unix-socket-transport.d.ts +15 -0
  120. package/dist/unix-socket-transport.js +84 -0
  121. package/dist/utils.d.ts +30 -0
  122. package/dist/utils.js +276 -0
  123. package/docs/client-metadata.json +14 -0
  124. package/elicitation-handler.ts +349 -0
  125. package/error-signal.ts +21 -0
  126. package/glimpse-ui.ts +80 -0
  127. package/host-html-template.ts +456 -0
  128. package/index.ts +900 -0
  129. package/init.ts +627 -0
  130. package/legacy-migration.ts +47 -0
  131. package/lifecycle.ts +165 -0
  132. package/logger.ts +127 -0
  133. package/mcp-auth-flow.ts +975 -0
  134. package/mcp-auth.ts +793 -0
  135. package/mcp-callback-server.ts +450 -0
  136. package/mcp-code.ts +386 -0
  137. package/mcp-keyring-helper.cjs +89 -0
  138. package/mcp-oauth-provider.ts +774 -0
  139. package/mcp-output-guard.ts +412 -0
  140. package/mcp-panel.ts +978 -0
  141. package/mcp-script-worker.mjs +128 -0
  142. package/mcp-setup-panel.ts +666 -0
  143. package/mcp-status.ts +109 -0
  144. package/mcp-trace.ts +295 -0
  145. package/metadata-cache.ts +333 -0
  146. package/npx-resolver.ts +488 -0
  147. package/onboarding-state.ts +58 -0
  148. package/package.json +182 -0
  149. package/panel-keys.ts +37 -0
  150. package/prompts.ts +337 -0
  151. package/proxy-modes.ts +1361 -0
  152. package/resource-tools.ts +17 -0
  153. package/runtime-owner.ts +123 -0
  154. package/sampling-handler.ts +273 -0
  155. package/scripts/build.mjs +131 -0
  156. package/scripts/prepare.mjs +102 -0
  157. package/search-ranking.ts +196 -0
  158. package/server-manager.ts +1320 -0
  159. package/session-recovery.ts +316 -0
  160. package/skills/mcp-scripting/SKILL.md +38 -0
  161. package/state.ts +64 -0
  162. package/tool-approval.ts +78 -0
  163. package/tool-metadata.ts +235 -0
  164. package/tool-registrar.ts +69 -0
  165. package/tool-result-renderer.ts +286 -0
  166. package/ts-shape.ts +145 -0
  167. package/tsconfig.build.json +13 -0
  168. package/tsconfig.json +16 -0
  169. package/types.ts +810 -0
  170. package/ui-resource-handler.ts +249 -0
  171. package/ui-server.ts +808 -0
  172. package/ui-session.ts +568 -0
  173. package/ui-stream-types.ts +89 -0
  174. package/ui-tool-visibility.ts +25 -0
  175. package/unix-socket-transport.ts +85 -0
  176. package/utils.ts +309 -0
@@ -0,0 +1,412 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { 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 temp file. Omit for call sites
56
+ * whose details never carried the raw result (e.g. resource reads).
57
+ */
58
+ rawMcpResult?: unknown;
59
+ }
60
+
61
+ export interface GuardedMcpOutput {
62
+ content: ContentBlock[];
63
+ outputGuard?: McpOutputGuardDetails;
64
+ mcpResult?: unknown;
65
+ }
66
+
67
+ export function resolveMcpOutputGuardOptions(settings?: McpSettings, outputDirectory?: string): Pick<McpOutputGuardOptions, "enabled" | "maxBytes" | "maxLines" | "detailsMaxBytes" | "outputDirectory"> {
68
+ const configured = settings?.outputGuard;
69
+ const tuning = typeof configured === "object" && configured !== null ? configured : undefined;
70
+ return {
71
+ enabled: envKillSwitch("MCP_OUTPUT_GUARD") ?? configured !== false,
72
+ ...(outputDirectory !== undefined ? { outputDirectory } : {}),
73
+ maxBytes: positiveInt(tuning?.maxBytes) ?? DEFAULT_MCP_OUTPUT_MAX_BYTES,
74
+ maxLines: positiveInt(tuning?.maxLines) ?? DEFAULT_MCP_OUTPUT_MAX_LINES,
75
+ detailsMaxBytes: positiveInt(tuning?.detailsMaxBytes) ?? DEFAULT_MCP_DETAILS_MAX_BYTES,
76
+ };
77
+ }
78
+
79
+ /** Spread helper for tool-result details: includes mcpResult/outputGuard only when present. */
80
+ export function guardedMcpDetails(guarded: GuardedMcpOutput): Record<string, unknown> {
81
+ return {
82
+ ...(guarded.mcpResult !== undefined ? { mcpResult: guarded.mcpResult } : {}),
83
+ ...(guarded.outputGuard ? { outputGuard: guarded.outputGuard } : {}),
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Bound model-facing MCP output. Text output is capped at maxBytes/maxLines and
89
+ * spilled to a temp file when oversized. Image blocks pass through untouched —
90
+ * they are delivered to the provider as native image content, not text context.
91
+ */
92
+ export async function guardMcpOutput(
93
+ content: ContentBlock[],
94
+ options: McpOutputGuardOptions = {},
95
+ ): Promise<GuardedMcpOutput> {
96
+ const maxBytes = options.maxBytes ?? DEFAULT_MCP_OUTPUT_MAX_BYTES;
97
+ const maxLines = options.maxLines ?? DEFAULT_MCP_OUTPUT_MAX_LINES;
98
+ const detailsMaxBytes = options.detailsMaxBytes ?? DEFAULT_MCP_DETAILS_MAX_BYTES;
99
+ const prefix = options.prefix ?? "";
100
+ const suffix = options.suffix ?? "";
101
+
102
+ const normalizedContent = withEmptyTextFallback(
103
+ content.length > 0
104
+ ? sanitizeContent(content)
105
+ : [{ type: "text" as const, text: options.emptyTextFallback ?? "(empty result)" }],
106
+ options.emptyTextFallback,
107
+ );
108
+
109
+ if (options.enabled === false) {
110
+ return {
111
+ content: addAffixes(normalizedContent, prefix, suffix),
112
+ ...(options.rawMcpResult !== undefined ? { mcpResult: options.rawMcpResult } : {}),
113
+ };
114
+ }
115
+
116
+ const imageBlocks = normalizedContent.filter((block) => block.type === "image");
117
+ const textOutput = normalizedContent
118
+ .filter((block) => block.type === "text")
119
+ .map((block) => (block as { text: string }).text)
120
+ .join("\n");
121
+ const composedOutput = `${prefix}${textOutput}${suffix}`;
122
+ const stats = textStats(composedOutput);
123
+
124
+ let guardedContent: ContentBlock[] = addAffixes(normalizedContent, prefix, suffix);
125
+ let outputGuard: McpOutputGuardDetails | undefined;
126
+
127
+ if (stats.bytes > maxBytes || stats.lines > maxLines) {
128
+ const { path: fullOutputPath, error: writeError } = await saveArtifact("output", composedOutput, options.outputDirectory);
129
+ const notice = formatTruncationNotice(stats, fullOutputPath, writeError);
130
+ const previewBudget = reserveBudget(maxBytes, maxLines, notice);
131
+ const preview = truncateHead(composedOutput, previewBudget.maxBytes, previewBudget.maxLines);
132
+ const finalText = `${preview.content}\n\n${notice}`;
133
+ const finalStats = textStats(finalText);
134
+
135
+ guardedContent = [{ type: "text" as const, text: finalText }, ...imageBlocks];
136
+ outputGuard = {
137
+ truncated: true,
138
+ originalBytes: stats.bytes,
139
+ returnedBytes: finalStats.bytes,
140
+ originalLines: stats.lines,
141
+ returnedLines: finalStats.lines,
142
+ ...(imageBlocks.length > 0 ? { imageBlocksPassedThrough: imageBlocks.length } : {}),
143
+ ...(fullOutputPath !== undefined ? { fullOutputPath } : {}),
144
+ ...(writeError !== undefined ? { writeError } : {}),
145
+ };
146
+ }
147
+
148
+ const mcpResult = options.rawMcpResult === undefined
149
+ ? undefined
150
+ : await boundMcpResult(options.rawMcpResult, detailsMaxBytes, options.outputDirectory);
151
+
152
+ return {
153
+ content: guardedContent,
154
+ ...(outputGuard ? { outputGuard } : {}),
155
+ ...(mcpResult !== undefined ? { mcpResult } : {}),
156
+ };
157
+ }
158
+
159
+ function sanitizeContent(content: ContentBlock[]): ContentBlock[] {
160
+ return content.map((block) => {
161
+ if (block.type !== "image") return block;
162
+ const mimeType = typeof block.mimeType === "string" && block.mimeType.trim()
163
+ ? block.mimeType.trim().slice(0, 100)
164
+ : "image/png";
165
+ return { ...block, mimeType };
166
+ });
167
+ }
168
+
169
+ function withEmptyTextFallback(content: ContentBlock[], fallback: string | undefined): ContentBlock[] {
170
+ if (!fallback) return content;
171
+ const textOutput = content
172
+ .filter((block) => block.type === "text")
173
+ .map((block) => (block as { text: string }).text)
174
+ .join("\n");
175
+ if (textOutput) return content;
176
+ return [{ type: "text", text: fallback }, ...content.filter((block) => block.type === "image")];
177
+ }
178
+
179
+ function addAffixes(content: ContentBlock[], prefix: string, suffix: string): ContentBlock[] {
180
+ if (!prefix && !suffix) return content;
181
+ const next: ContentBlock[] = [...content];
182
+
183
+ if (prefix) {
184
+ const index = next.findIndex((block) => block.type === "text");
185
+ const block = next[index];
186
+ if (block?.type === "text") {
187
+ next[index] = { ...block, text: `${prefix}${block.text}` };
188
+ } else {
189
+ next.unshift({ type: "text", text: prefix });
190
+ }
191
+ }
192
+
193
+ if (suffix) {
194
+ let index = -1;
195
+ for (let i = next.length - 1; i >= 0; i--) {
196
+ if (next[i]?.type === "text") {
197
+ index = i;
198
+ break;
199
+ }
200
+ }
201
+ const block = next[index];
202
+ if (block?.type === "text") {
203
+ next[index] = { ...block, text: `${block.text}${suffix}` };
204
+ } else {
205
+ next.push({ type: "text", text: suffix });
206
+ }
207
+ }
208
+
209
+ return next;
210
+ }
211
+
212
+ function reserveBudget(maxBytes: number, maxLines: number, notice: string): { maxBytes: number; maxLines: number } {
213
+ const noticeStats = textStats(`\n\n${notice}`);
214
+ return {
215
+ maxBytes: Math.max(0, maxBytes - noticeStats.bytes),
216
+ maxLines: Math.max(0, maxLines - noticeStats.lines),
217
+ };
218
+ }
219
+
220
+ function truncateHead(text: string, maxBytes: number, maxLines: number): { content: string; bytes: number; lines: number } {
221
+ const lines = text.split("\n");
222
+ const output: string[] = [];
223
+ let bytes = 0;
224
+
225
+ for (const line of lines) {
226
+ if (output.length >= maxLines) break;
227
+ const separatorBytes = output.length > 0 ? 1 : 0;
228
+ const lineBytes = byteLength(line);
229
+ if (bytes + separatorBytes + lineBytes > maxBytes) {
230
+ const remaining = maxBytes - bytes - separatorBytes;
231
+ if (remaining > 0) {
232
+ output.push(truncateStringToBytes(line, remaining));
233
+ }
234
+ break;
235
+ }
236
+ output.push(line);
237
+ bytes += separatorBytes + lineBytes;
238
+ }
239
+
240
+ const content = output.join("\n");
241
+ const stats = textStats(content);
242
+ return { content, bytes: stats.bytes, lines: stats.lines };
243
+ }
244
+
245
+ function truncateStringToBytes(value: string, maxBytes: number): string {
246
+ if (byteLength(value) <= maxBytes) return value;
247
+ const buffer = Buffer.from(value, "utf8");
248
+ let end = Number.isFinite(maxBytes) ? Math.max(0, Math.floor(maxBytes)) : 0;
249
+ while (end > 0 && (buffer.readUInt8(end) & 0xc0) === 0x80) end--;
250
+ return buffer.subarray(0, end).toString("utf8");
251
+ }
252
+
253
+ function formatTruncationNotice(
254
+ stats: { bytes: number; lines: number },
255
+ fullOutputPath: string | undefined,
256
+ writeError: string | undefined,
257
+ ): string {
258
+ const base = `[MCP text output truncated: original ${stats.lines.toLocaleString()} lines / ${formatSize(stats.bytes)}.`;
259
+ if (fullOutputPath) {
260
+ return `${base} Full text saved to: ${fullOutputPath} — use read with offset/limit or grep to inspect.]`;
261
+ }
262
+ return `${base} Full output could not be saved: ${writeError ?? "unknown error"}]`;
263
+ }
264
+
265
+ /**
266
+ * Bound details.mcpResult: keep the raw result when its JSON fits within
267
+ * detailsMaxBytes; otherwise replace it with a compact summary and spill the
268
+ * raw JSON to a temp file.
269
+ */
270
+ async function boundMcpResult(result: unknown, detailsMaxBytes: number, outputDirectory?: string): Promise<unknown> {
271
+ const raw = safeStringify(result);
272
+ const rawBytes = byteLength(raw);
273
+ if (rawBytes <= detailsMaxBytes) return result;
274
+ return summarizeMcpResult(result, raw, rawBytes, outputDirectory);
275
+ }
276
+
277
+ async function summarizeMcpResult(result: unknown, raw: string, rawBytes: number, outputDirectory?: string): Promise<McpResultSummary> {
278
+ const { path: fullResultPath, error: resultWriteError } = await saveArtifact("mcp-result", raw, outputDirectory);
279
+
280
+ const record = asRecord(result);
281
+ const content = Array.isArray(record?.content) ? record.content : [];
282
+ const summary: McpResultSummary = {
283
+ omitted: true,
284
+ reason: "Raw MCP result exceeded the details size limit and was replaced with this summary to keep session context bounded.",
285
+ isError: record?.isError === true,
286
+ contentBlocks: content.length,
287
+ contentSummary: summarizeContent(content),
288
+ rawResultBytes: rawBytes,
289
+ ...(fullResultPath !== undefined ? { fullResultPath } : {}),
290
+ ...(resultWriteError !== undefined ? { resultWriteError } : {}),
291
+ };
292
+
293
+ if (record && "structuredContent" in record) {
294
+ summary.structuredContentSummary = summarizeValue(record.structuredContent);
295
+ }
296
+ if (record && "_meta" in record) {
297
+ summary.meta = summarizeValue(record._meta);
298
+ }
299
+ if (record) {
300
+ const standard = new Set(["content", "isError", "structuredContent", "_meta"]);
301
+ const extraFields = Object.keys(record)
302
+ .filter((key) => !standard.has(key))
303
+ .slice(0, KEY_PREVIEW_LIMIT)
304
+ .map((key) => ({ key: truncateKey(key), type: typeof record[key], estimatedBytes: estimateValueBytes(record[key]), omitted: true }));
305
+ if (extraFields.length > 0) summary.extraFields = extraFields;
306
+ }
307
+
308
+ return summary;
309
+ }
310
+
311
+ function summarizeContent(content: unknown[]): Array<Record<string, unknown>> {
312
+ const summaries: Array<Record<string, unknown>> = content.slice(0, CONTENT_SUMMARY_LIMIT).map((block) => {
313
+ const record = asRecord(block);
314
+ if (!record) return { type: typeof block, omitted: true };
315
+ if (record.type === "text") {
316
+ const text = typeof record.text === "string" ? record.text : "";
317
+ return { type: "text", bytes: byteLength(text), lines: textStats(text).lines, textOmitted: true };
318
+ }
319
+ if (record.type === "image") {
320
+ const data = typeof record.data === "string" ? record.data : "";
321
+ return { type: "image", mimeType: typeof record.mimeType === "string" ? record.mimeType : undefined, dataBytes: byteLength(data), dataOmitted: true };
322
+ }
323
+ return { type: typeof record.type === "string" ? record.type : "unknown", estimatedBytes: estimateValueBytes(record), omitted: true };
324
+ });
325
+ if (content.length > CONTENT_SUMMARY_LIMIT) {
326
+ summaries.push({ type: "omitted", count: content.length - CONTENT_SUMMARY_LIMIT });
327
+ }
328
+ return summaries;
329
+ }
330
+
331
+ function summarizeValue(value: unknown): Record<string, unknown> {
332
+ const record = asRecord(value);
333
+ if (!record) {
334
+ return { type: value === null ? "null" : typeof value, estimatedBytes: estimateValueBytes(value), omitted: true };
335
+ }
336
+ const keys = Object.keys(record);
337
+ return {
338
+ type: Array.isArray(value) ? "array" : "object",
339
+ estimatedBytes: estimateValueBytes(value),
340
+ keyCount: keys.length,
341
+ keysPreview: keys.slice(0, KEY_PREVIEW_LIMIT).map(truncateKey),
342
+ omitted: true,
343
+ };
344
+ }
345
+
346
+ function estimateValueBytes(value: unknown, depth = 0): number {
347
+ if (value === null || value === undefined) return 0;
348
+ if (typeof value === "string") return byteLength(value);
349
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") return byteLength(String(value));
350
+ const record = asRecord(value);
351
+ if (!record || depth >= 2) return 0;
352
+ const values = Array.isArray(value) ? value.slice(0, KEY_PREVIEW_LIMIT) : Object.values(record).slice(0, KEY_PREVIEW_LIMIT);
353
+ return values.reduce((total, item) => total + estimateValueBytes(item, depth + 1), 0);
354
+ }
355
+
356
+ function truncateKey(key: string): string {
357
+ return key.length <= KEY_MAX_CHARS ? key : `${key.slice(0, KEY_MAX_CHARS - 1)}…`;
358
+ }
359
+
360
+ async function saveArtifact(kind: string, text: string, outputDirectory?: string): Promise<{ path?: string; error?: string }> {
361
+ try {
362
+ const parent = outputDirectory === undefined ? tmpdir() : resolve(outputDirectory);
363
+ if (outputDirectory !== undefined) await mkdir(parent, { recursive: true, mode: 0o700 });
364
+ const dir = await mkdtemp(join(parent, "pi-mcp-output-"));
365
+ const path = join(dir, `${kind}-${randomBytes(4).toString("hex")}.txt`);
366
+ await writeFile(path, text, { encoding: "utf8", mode: 0o600 });
367
+ return { path };
368
+ } catch (error) {
369
+ return { error: error instanceof Error ? error.message : String(error) };
370
+ }
371
+ }
372
+
373
+ function asRecord(value: unknown): Recordish | undefined {
374
+ return typeof value === "object" && value !== null ? value as Recordish : undefined;
375
+ }
376
+
377
+ function safeStringify(value: unknown): string {
378
+ try {
379
+ // The output guard measures and spills raw MCP results; it does not render this JSON for the model.
380
+ return JSON.stringify(value);
381
+ } catch {
382
+ return String(value);
383
+ }
384
+ }
385
+
386
+ function textStats(text: string): { bytes: number; lines: number } {
387
+ return { bytes: byteLength(text), lines: text.length === 0 ? 0 : text.split("\n").length };
388
+ }
389
+
390
+ function byteLength(text: string): number {
391
+ return Buffer.byteLength(text, "utf8");
392
+ }
393
+
394
+ function positiveInt(value: unknown): number | undefined {
395
+ if (typeof value !== "number" || !Number.isFinite(value)) return undefined;
396
+ const integer = Math.floor(value);
397
+ return integer > 0 ? integer : undefined;
398
+ }
399
+
400
+ function envKillSwitch(name: string): boolean | undefined {
401
+ const value = process.env[name]?.trim().toLowerCase();
402
+ if (!value) return undefined;
403
+ if (["0", "false", "no", "off"].includes(value)) return false;
404
+ if (["1", "true", "yes", "on"].includes(value)) return true;
405
+ return undefined;
406
+ }
407
+
408
+ function formatSize(bytes: number): string {
409
+ if (bytes < 1024) return `${bytes} B`;
410
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`;
411
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
412
+ }