@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,366 @@
1
+ import { formatWithOptions } from "node:util";
2
+ import { Worker } from "node:worker_threads";
3
+ import { guardMcpOutput, guardedMcpDetails, resolveMcpOutputGuardOptions } from "./mcp-output-guard.js";
4
+ import { executeCall } from "./proxy-modes.js";
5
+ import { combineAbortSignals } from "./runtime-owner.js";
6
+ import { paginate, rankSuggestions, rankToolMatches } from "./search-ranking.js";
7
+ import { findToolByName } from "./tool-metadata.js";
8
+ import { renderTsShape } from "./ts-shape.js";
9
+ export const DEFAULT_MCP_SCRIPT_TIMEOUT_MS = 30_000;
10
+ class McpScriptTimeoutError extends Error {
11
+ constructor(timeoutMs) {
12
+ super(`mcp_script timed out after ${timeoutMs}ms`);
13
+ this.name = "McpScriptTimeoutError";
14
+ }
15
+ }
16
+ function needsInspectableFormatting(value, stack = new WeakSet()) {
17
+ if (value === undefined || typeof value === "bigint" || typeof value === "function" || typeof value === "symbol")
18
+ return true;
19
+ if (typeof value !== "object" || value === null)
20
+ return false;
21
+ if (stack.has(value))
22
+ return true;
23
+ if (value instanceof Map || value instanceof Set || value instanceof WeakMap || value instanceof WeakSet)
24
+ return true;
25
+ stack.add(value);
26
+ try {
27
+ return Object.values(value).some((entry) => needsInspectableFormatting(entry, stack));
28
+ }
29
+ finally {
30
+ stack.delete(value);
31
+ }
32
+ }
33
+ function formatValue(value) {
34
+ if (typeof value === "string")
35
+ return value;
36
+ try {
37
+ if (!needsInspectableFormatting(value)) {
38
+ const json = JSON.stringify(value, null, 2);
39
+ if (json !== undefined)
40
+ return json;
41
+ }
42
+ return formatWithOptions({ colors: false, depth: 6 }, value);
43
+ }
44
+ catch {
45
+ return "[unserializable value]";
46
+ }
47
+ }
48
+ function toContentBlock(value) {
49
+ if (typeof value === "object" && value !== null) {
50
+ const block = value;
51
+ if (block.type === "text" && typeof block.text === "string") {
52
+ return { type: "text", text: block.text };
53
+ }
54
+ if (block.type === "image" && typeof block.data === "string" && typeof block.mimeType === "string") {
55
+ return { type: "image", data: block.data, mimeType: block.mimeType };
56
+ }
57
+ }
58
+ return { type: "text", text: formatValue(value) };
59
+ }
60
+ function textFromContent(content) {
61
+ return content
62
+ .filter((block) => block.type === "text")
63
+ .map((block) => block.text)
64
+ .join("\n");
65
+ }
66
+ function abortReasonError(reason) {
67
+ return reason instanceof Error ? reason : new Error(String(reason ?? "MCP request aborted"));
68
+ }
69
+ function parseWorkerMessage(value) {
70
+ if (typeof value !== "object" || value === null)
71
+ return null;
72
+ const message = value;
73
+ if (message.type === "emit" && "block" in message)
74
+ return { type: "emit", block: message.block };
75
+ if (message.type === "call" && typeof message.id === "number" && typeof message.path === "string") {
76
+ return "args" in message
77
+ ? { type: "call", id: message.id, path: message.path, args: message.args }
78
+ : { type: "call", id: message.id, path: message.path };
79
+ }
80
+ if ((message.type === "search" || message.type === "describe") && typeof message.id === "number") {
81
+ return "input" in message
82
+ ? { type: message.type, id: message.id, input: message.input }
83
+ : { type: message.type, id: message.id };
84
+ }
85
+ if (message.type === "done") {
86
+ return "returnBlock" in message ? { type: "done", returnBlock: message.returnBlock } : { type: "done" };
87
+ }
88
+ if (message.type === "error" && typeof message.message === "string") {
89
+ return { type: "error", message: message.message };
90
+ }
91
+ return null;
92
+ }
93
+ class McpScriptCaptureError extends Error {
94
+ recovery;
95
+ constructor(recovery, message) {
96
+ super(message);
97
+ this.recovery = recovery;
98
+ }
99
+ }
100
+ export const runMcpScript = async (...args) => {
101
+ const state = args[0];
102
+ state.owner?.beforeActivity();
103
+ state.activeScripts = (state.activeScripts ?? 0) + 1;
104
+ try {
105
+ return await runMcpScriptOperation(...args);
106
+ }
107
+ finally {
108
+ state.activeScripts--;
109
+ }
110
+ };
111
+ async function runMcpScriptOperation(state, code, timeoutMs = DEFAULT_MCP_SCRIPT_TIMEOUT_MS, getPiTools, signal, toolCallId, beforeDispatch) {
112
+ const resolvedTimeoutMs = timeoutMs === null ? null : Number.isFinite(timeoutMs) && timeoutMs > 0
113
+ ? Math.floor(timeoutMs)
114
+ : DEFAULT_MCP_SCRIPT_TIMEOUT_MS;
115
+ const output = [];
116
+ const externalSignal = combineAbortSignals(state.owner?.signal, signal);
117
+ const timeoutController = new AbortController();
118
+ const callSignal = combineAbortSignals(externalSignal, timeoutController.signal);
119
+ const calls = [];
120
+ const snapshotCalls = () => calls.map(({ startedAt, ...operation }) => ({
121
+ ...operation,
122
+ durationMs: "error" in operation && operation.error === "incomplete"
123
+ ? Math.max(0, Date.now() - startedAt)
124
+ : operation.durationMs,
125
+ }));
126
+ let callsSnapshot;
127
+ const callTool = async (innerCallId, path, args) => {
128
+ // Record before dispatch so calls still in flight at timeout/abort appear in the trace.
129
+ const startedAt = Date.now();
130
+ const index = calls.push({ operation: "call", path, ok: false, error: "incomplete", durationMs: 0, startedAt }) - 1;
131
+ let rawResult;
132
+ let hasRawResult = false;
133
+ const result = await executeCall(state, path, args, undefined, getPiTools, callSignal, (raw) => {
134
+ rawResult = raw;
135
+ hasRawResult = true;
136
+ }, { ...(toolCallId !== undefined ? { toolCallId } : {}), innerCallId }, beforeDispatch);
137
+ const details = result.details;
138
+ if (details.error !== undefined) {
139
+ const errorCode = String(details.error);
140
+ const suggestions = Array.isArray(details.suggestions)
141
+ ? details.suggestions.filter((suggestion) => typeof suggestion === "string")
142
+ : [];
143
+ const message = errorCode === "tool_not_found"
144
+ ? `Tool "${path}" not found. Use await tools.search({ query: "..." }) inside mcp_script.${suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}` : ""}`
145
+ : typeof details.message === "string"
146
+ ? details.message
147
+ : textFromContent(result.content);
148
+ calls[index] = {
149
+ operation: "call", path, ok: false, error: errorCode, durationMs: Date.now() - startedAt, startedAt,
150
+ ...(errorCode === "ambiguous_outcome" ? { recovery: details.recovery } : {}),
151
+ };
152
+ if (errorCode === "call_capture_failed")
153
+ throw new McpScriptCaptureError(details.recovery, message);
154
+ if (errorCode === "ambiguous_outcome")
155
+ output.push({ type: "text", text: message });
156
+ return {
157
+ ok: false,
158
+ error: { code: errorCode, message, ...(details.recovery ? { recovery: details.recovery } : {}) },
159
+ };
160
+ }
161
+ calls[index] = { operation: "call", path, ok: true, durationMs: Date.now() - startedAt, startedAt };
162
+ return {
163
+ ok: true,
164
+ data: hasRawResult ? rawResult : details.mcpResult !== undefined ? details.mcpResult : textFromContent(result.content),
165
+ };
166
+ };
167
+ const searchTools = (input) => {
168
+ const startedAt = Date.now();
169
+ const query = typeof input?.query === "string" ? input.query : "";
170
+ let error;
171
+ try {
172
+ if (query.trim() === "") {
173
+ return { items: [], total: 0, hasMore: false, nextOffset: null };
174
+ }
175
+ const server = typeof input?.server === "string" ? input.server : undefined;
176
+ const limit = typeof input?.limit === "number" ? input.limit : 12;
177
+ const offset = typeof input?.offset === "number" ? input.offset : 0;
178
+ const page = paginate(rankToolMatches(state, query, server), offset, limit);
179
+ return {
180
+ ...page,
181
+ items: page.items.map(({ server: matchServer, tool, score }) => ({
182
+ path: tool.name,
183
+ name: tool.originalName,
184
+ server: matchServer,
185
+ ...(tool.description ? { description: tool.description } : {}),
186
+ score,
187
+ })),
188
+ };
189
+ }
190
+ catch (caught) {
191
+ error = caught;
192
+ throw caught;
193
+ }
194
+ finally {
195
+ calls.push(error === undefined
196
+ ? { operation: "search", query, ok: true, durationMs: Date.now() - startedAt, startedAt }
197
+ : { operation: "search", query, ok: false, error: error instanceof Error ? error.message : String(error), durationMs: Date.now() - startedAt, startedAt });
198
+ }
199
+ };
200
+ const describeTool = (input) => {
201
+ const startedAt = Date.now();
202
+ const path = typeof input?.path === "string" ? input.path : "";
203
+ let error;
204
+ try {
205
+ for (const [server, metadata] of state.toolMetadata) {
206
+ const tool = findToolByName(metadata, path);
207
+ if (!tool)
208
+ continue;
209
+ const inputTypeScript = tool.inputSchema ? renderTsShape(tool.inputSchema) : null;
210
+ return {
211
+ path: tool.name,
212
+ name: tool.originalName,
213
+ server,
214
+ ...(tool.description ? { description: tool.description } : {}),
215
+ ...(inputTypeScript ? { inputTypeScript } : tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
216
+ ...(tool.annotations !== undefined ? { annotations: tool.annotations } : {}),
217
+ };
218
+ }
219
+ const suggestions = path ? rankSuggestions(state, path, 5) : [];
220
+ error = "tool_not_found";
221
+ return {
222
+ path,
223
+ error: {
224
+ code: "tool_not_found",
225
+ message: `Tool not found: ${path}`,
226
+ suggestions,
227
+ },
228
+ };
229
+ }
230
+ catch (caught) {
231
+ error = caught;
232
+ throw caught;
233
+ }
234
+ finally {
235
+ calls.push(error === undefined
236
+ ? { operation: "describe", path, ok: true, durationMs: Date.now() - startedAt, startedAt }
237
+ : { operation: "describe", path, ok: false, error: error instanceof Error ? error.message : String(error), durationMs: Date.now() - startedAt, startedAt });
238
+ }
239
+ };
240
+ let worker;
241
+ let timer;
242
+ let removeAbortListener = () => { };
243
+ let errorCode;
244
+ let recovery;
245
+ let errorMessage;
246
+ try {
247
+ if (externalSignal?.aborted) {
248
+ throw abortReasonError(externalSignal.reason);
249
+ }
250
+ worker = new Worker(new URL("./mcp-script-worker.mjs", import.meta.url), {
251
+ workerData: { code },
252
+ env: {},
253
+ });
254
+ const activeWorker = worker;
255
+ const execution = new Promise((resolve, reject) => {
256
+ let completed = false;
257
+ activeWorker.on("message", (value) => {
258
+ const message = parseWorkerMessage(value);
259
+ if (!message || completed)
260
+ return;
261
+ if (message.type === "emit") {
262
+ output.push(toContentBlock(message.block));
263
+ return;
264
+ }
265
+ if (message.type === "done") {
266
+ completed = true;
267
+ if ("returnBlock" in message)
268
+ output.push(toContentBlock(message.returnBlock));
269
+ resolve();
270
+ return;
271
+ }
272
+ if (message.type === "error") {
273
+ completed = true;
274
+ reject(new Error(message.message));
275
+ return;
276
+ }
277
+ void (async () => {
278
+ let envelope;
279
+ if (message.type === "call") {
280
+ envelope = await callTool(message.id, message.path, message.args);
281
+ }
282
+ else if (message.type === "search") {
283
+ envelope = searchTools(message.input);
284
+ }
285
+ else {
286
+ envelope = describeTool(message.input);
287
+ }
288
+ const response = { type: "result", id: message.id, envelope };
289
+ activeWorker.postMessage(response);
290
+ })().catch(reject);
291
+ });
292
+ activeWorker.once("error", reject);
293
+ activeWorker.once("exit", (code) => {
294
+ if (!completed && code !== 0)
295
+ reject(new Error(`mcp_script worker exited with code ${code}`));
296
+ });
297
+ });
298
+ const timeout = new Promise((_resolve, reject) => {
299
+ if (resolvedTimeoutMs === null)
300
+ return;
301
+ const timeoutError = new McpScriptTimeoutError(resolvedTimeoutMs);
302
+ timer = setTimeout(() => {
303
+ callsSnapshot = snapshotCalls();
304
+ timeoutController.abort(timeoutError);
305
+ void activeWorker.terminate();
306
+ reject(timeoutError);
307
+ }, resolvedTimeoutMs);
308
+ });
309
+ const aborted = externalSignal
310
+ ? new Promise((_resolve, reject) => {
311
+ const onAbort = () => {
312
+ callsSnapshot = snapshotCalls();
313
+ void activeWorker.terminate();
314
+ reject(abortReasonError(externalSignal.reason));
315
+ };
316
+ externalSignal.addEventListener("abort", onAbort, { once: true });
317
+ removeAbortListener = () => externalSignal.removeEventListener("abort", onAbort);
318
+ })
319
+ : new Promise(() => { });
320
+ await Promise.race([execution, timeout, aborted]);
321
+ }
322
+ catch (error) {
323
+ if (error instanceof McpScriptCaptureError) {
324
+ errorCode = "call_capture_failed";
325
+ errorMessage = error.message;
326
+ recovery = error.recovery;
327
+ }
328
+ else if (error instanceof McpScriptTimeoutError) {
329
+ errorCode = "timeout";
330
+ errorMessage = `mcp_script timed out after ${resolvedTimeoutMs}ms`;
331
+ }
332
+ else if (externalSignal?.aborted) {
333
+ errorCode = "aborted";
334
+ errorMessage = error instanceof Error ? error.message : String(error);
335
+ }
336
+ else {
337
+ errorCode = "script_error";
338
+ errorMessage = error instanceof Error ? error.message : String(error);
339
+ }
340
+ output.push({ type: "text", text: errorMessage });
341
+ }
342
+ finally {
343
+ clearTimeout(timer);
344
+ removeAbortListener();
345
+ // "incomplete" means the call had not settled when the script finished
346
+ // (deadline, abort, or early return). Snapshot before aborting stragglers.
347
+ callsSnapshot ??= snapshotCalls();
348
+ // A script may finish without awaiting every call; abort leftovers so
349
+ // parent-side dispatches do not outlive the script.
350
+ timeoutController.abort(new Error("mcp_script finished"));
351
+ await worker?.terminate();
352
+ }
353
+ // Snapshot before the asynchronous output guard; the terminated worker can no longer emit.
354
+ const guarded = await guardMcpOutput(output.length > 0 ? [...output] : [{ type: "text", text: "(no output)" }], resolveMcpOutputGuardOptions(state.config.settings, state.outputDirectory));
355
+ return {
356
+ content: guarded.content,
357
+ details: {
358
+ mode: "script",
359
+ ...(errorCode ? { error: errorCode, message: errorMessage } : {}),
360
+ timeoutMs: resolvedTimeoutMs,
361
+ ...(recovery !== undefined ? { recovery } : {}),
362
+ ...(callsSnapshot.length > 0 ? { calls: callsSnapshot } : {}),
363
+ ...guardedMcpDetails(guarded),
364
+ },
365
+ };
366
+ }
@@ -0,0 +1,89 @@
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
+ })();
@@ -0,0 +1,154 @@
1
+ /**
2
+ * MCP OAuth Provider
3
+ *
4
+ * Implementation of the MCP SDK's OAuthClientProvider interface.
5
+ * Handles OAuth client registration, token storage, and authorization redirection.
6
+ */
7
+ import { type FetchLike, type AddClientAuthentication, type OAuthClientProvider, type OAuthClientInformationContext, type StoredOAuthClientInformation, type StoredOAuthTokens, type OAuthDiscoveryState } from "@modelcontextprotocol/client";
8
+ import type { OAuthClientMetadata } from "@modelcontextprotocol/client";
9
+ import { type AuthStorageOptions } from "./mcp-auth.ts";
10
+ import { type OAuthPrivateKeyJwtConfig, type OAuthCrossAppAccessConfig } from "./types.ts";
11
+ /** Validate explicit document URLs without echoing possible credentials in errors. */
12
+ export declare function validateOAuthClientMetadataUrl(value: string | false | undefined): void;
13
+ /** Only the port may differ; keep raw host, path and query spelling exact. */
14
+ export declare function loopbackRedirectsMatch(first: string, second: unknown): boolean;
15
+ export declare function issuersMatch(first: string, second: string): boolean;
16
+ declare const DEFAULT_OAUTH_CALLBACK_PORT = 19876;
17
+ declare const DEFAULT_OAUTH_CALLBACK_PATH = "/callback";
18
+ export declare function getConfiguredOAuthCallbackPort(): number;
19
+ export declare function getOAuthCallbackPort(): number;
20
+ export declare function setOAuthCallbackPort(port: number): void;
21
+ export declare function getOAuthCallbackPath(): string;
22
+ export declare function setOAuthCallbackPath(path: string): void;
23
+ /** Configuration options for OAuth */
24
+ export interface McpOAuthConfig {
25
+ skipIssuerMetadataValidation?: boolean;
26
+ grantType?: "authorization_code" | "client_credentials";
27
+ clientId?: string;
28
+ clientSecret?: string;
29
+ privateKeyJwt?: OAuthPrivateKeyJwtConfig;
30
+ crossAppAccess?: OAuthCrossAppAccessConfig;
31
+ scope?: string;
32
+ authorizationParams?: Record<string, string>;
33
+ redirectUri?: string;
34
+ clientName?: string;
35
+ clientUri?: string;
36
+ /** Custom client document URL; false disables automatic CIMD for new registrations. */
37
+ clientMetadataUrl?: string | false;
38
+ }
39
+ /** Validate shapes and method conflicts without resolving or disclosing key sources. */
40
+ export declare function validateOAuthPrivateKeyJwt(config: McpOAuthConfig): void;
41
+ export declare function validateOAuthCrossAppAccess(config: McpOAuthConfig): void;
42
+ /** Callbacks for OAuth flow interactions */
43
+ export interface McpOAuthCallbacks {
44
+ onRedirect: (url: URL) => void | Promise<void>;
45
+ onDiscoveryState?: (state: OAuthDiscoveryState) => void;
46
+ }
47
+ /**
48
+ * OAuth provider implementation for MCP servers.
49
+ * Implements the OAuthClientProvider interface from the MCP SDK.
50
+ */
51
+ export declare class McpOAuthProvider implements OAuthClientProvider {
52
+ private serverName;
53
+ private serverUrl;
54
+ private config;
55
+ private callbacks;
56
+ private storageOptions;
57
+ private readonly redirectUrlSnapshot;
58
+ readonly clientMetadataUrl?: string;
59
+ private readonly controller;
60
+ readonly lifetimeSignal: AbortSignal;
61
+ private readonly requestSignals;
62
+ private flowAuthorizationServerUrl;
63
+ private flowResourceUrl;
64
+ private flowClientInfo;
65
+ private flowCodeVerifier;
66
+ private flowDiscoveryState;
67
+ private flowIssuerMismatch;
68
+ private flowState;
69
+ constructor(serverName: string, serverUrl: string, config: McpOAuthConfig, callbacks: McpOAuthCallbacks, storageOptions?: AuthStorageOptions, runtimeSignal?: AbortSignal, initialState?: string);
70
+ private get isNonInteractive();
71
+ private get discoveredIssuer();
72
+ get signal(): AbortSignal;
73
+ runWithSignal<T>(signal: AbortSignal | undefined, operation: () => T): T;
74
+ deactivate(): void;
75
+ private assertStoredIssuerBindings;
76
+ private throwIfInactive;
77
+ /**
78
+ * The redirect URL for OAuth callbacks.
79
+ * This must match the redirect_uri in client metadata.
80
+ */
81
+ get redirectUrl(): string | undefined;
82
+ /**
83
+ * Client metadata for dynamic registration.
84
+ * Describes this client to the OAuth authorization server.
85
+ */
86
+ get clientMetadata(): OAuthClientMetadata;
87
+ /**
88
+ * Get client information (for pre-registered or dynamically registered clients).
89
+ * Returns undefined if no client info exists or if the server URL has changed.
90
+ */
91
+ clientInformation(context?: OAuthClientInformationContext): Promise<StoredOAuthClientInformation | undefined>;
92
+ /**
93
+ * Save client information from dynamic registration.
94
+ */
95
+ saveClientInformation(info: StoredOAuthClientInformation, context?: OAuthClientInformationContext): Promise<void>;
96
+ /**
97
+ * Get stored OAuth tokens.
98
+ * Returns undefined if no tokens exist or if the server URL has changed.
99
+ */
100
+ tokens(context?: OAuthClientInformationContext): Promise<StoredOAuthTokens | undefined>;
101
+ /**
102
+ * Save OAuth tokens.
103
+ */
104
+ saveTokens(tokens: StoredOAuthTokens, context?: OAuthClientInformationContext): Promise<void>;
105
+ /**
106
+ * Redirect the user to the authorization URL.
107
+ * This opens the browser for the user to authenticate.
108
+ *
109
+ * Throws UnauthorizedError when called outside of a user-initiated flow
110
+ * (no oauthState saved by startAuth). That path is reached when the SDK
111
+ * falls through from a failed refresh into a fresh authorization_code
112
+ * flow, which library hosts cannot complete in-process.
113
+ */
114
+ redirectToAuthorization(authorizationUrl: URL): Promise<void>;
115
+ /**
116
+ * Save the PKCE code verifier.
117
+ */
118
+ saveCodeVerifier(codeVerifier: string): Promise<void>;
119
+ /**
120
+ * Get the stored PKCE code verifier.
121
+ * @throws Error if no code verifier is stored
122
+ */
123
+ codeVerifier(): Promise<string>;
124
+ /**
125
+ * Keep discovery with the in-flight PKCE verifier. The callback leg uses it
126
+ * to validate the authorization response issuer before token exchange.
127
+ */
128
+ saveDiscoveryState(state: OAuthDiscoveryState): Promise<void>;
129
+ saveAuthorizationServerUrl(issuer: string): void;
130
+ saveResourceUrl(resource: string): void;
131
+ readonly fetch: FetchLike;
132
+ discoveryState(): Promise<OAuthDiscoveryState | undefined>;
133
+ /**
134
+ * Save the OAuth state parameter for CSRF protection.
135
+ */
136
+ saveState(state: string): Promise<void>;
137
+ /**
138
+ * Get the stored OAuth state parameter.
139
+ * @throws UnauthorizedError if no flow is in progress (see redirectToAuthorization)
140
+ */
141
+ state(): Promise<string>;
142
+ /**
143
+ * Invalidate credentials when authentication fails.
144
+ * Clears tokens, client info, or all credentials based on the type.
145
+ */
146
+ invalidateCredentials(type: "all" | "client" | "tokens" | "verifier" | "discovery"): Promise<void>;
147
+ /**
148
+ * Adds configured scope and client authentication to native token requests.
149
+ */
150
+ addClientAuthentication: AddClientAuthentication;
151
+ private prepareCrossAppRequest;
152
+ prepareTokenRequest(scope?: string): URLSearchParams | Promise<URLSearchParams> | undefined;
153
+ }
154
+ export { DEFAULT_OAUTH_CALLBACK_PORT, DEFAULT_OAUTH_CALLBACK_PATH };