@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,316 @@
1
+ // session-recovery.ts
2
+ //
3
+ // Streamable HTTP session recovery.
4
+ //
5
+ // Per the MCP spec (Streamable HTTP transport):
6
+ // "When a client receives HTTP 404 in response to a request containing an
7
+ // Mcp-Session-Id, it MUST start a new session by sending a new
8
+ // InitializeRequest without a session ID attached."
9
+ //
10
+ // A 404 for a request that carried a session ID is therefore the spec's own
11
+ // definition of "this session no longer exists" (e.g. the remote server
12
+ // process restarted and lost its in-memory session table). Because the spec
13
+ // requires the server to reject the request *before* processing it, retrying
14
+ // the same call against a freshly initialized session cannot double-execute
15
+ // the original request.
16
+ //
17
+ // This module intentionally does NOT:
18
+ // - match broad error messages without a prior session id
19
+ // - match generic HTTP 400 responses, which are ambiguous and can mean
20
+ // many things other than "your session is gone"
21
+ // - treat generic -32000/ConnectionClosed errors as session expiry
22
+ // - treat AbortError/cancellation as a session failure
23
+ import { AsyncLocalStorage } from "node:async_hooks";
24
+ import { SdkHttpError, SdkErrorCode, ProtocolError, InsufficientScopeError, UnauthorizedError, type FetchLike, type Transport } from "@modelcontextprotocol/client";
25
+ import { logger } from "./logger.ts";
26
+ import { abortable, throwIfAborted } from "./abort.ts";
27
+ import { isServerDisabled, isNonInteractiveOAuth, type McpConfig } from "./types.ts";
28
+ import type { McpServerManager, ServerConnection } from "./server-manager.ts";
29
+ import { supportsOAuth } from "./mcp-auth-flow.ts";
30
+
31
+ const toolTransportFailures = new WeakSet<object>();
32
+ export function isToolTransportFailure(error: unknown): boolean {
33
+ return error instanceof Error && toolTransportFailures.has(error);
34
+ }
35
+ type ToolSend = {
36
+ id: string | number;
37
+ streaming: boolean;
38
+ responseReceived: boolean;
39
+ bodyFailure: Error | undefined;
40
+ otherFailure: Error | undefined;
41
+ finishSend: () => void;
42
+ };
43
+ const toolSend = new AsyncLocalStorage<ToolSend | undefined>();
44
+
45
+ /** Retain fetch/body-error origin without parsing or buffering the SSE response. */
46
+ export const trackToolTransportFailure: FetchLike = async (input, init) => {
47
+ const pending = toolSend.getStore();
48
+ if (pending) pending.bodyFailure = undefined;
49
+ try {
50
+ const response = await fetch(input, init);
51
+ if (!pending || !response.ok || !response.body
52
+ || response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "text/event-stream") return response;
53
+ pending.streaming = true;
54
+ // The native end hook has no error argument. Only a failed body read proves loss.
55
+ const reader = response.body.getReader();
56
+ return new Response(new ReadableStream({
57
+ async pull(controller) {
58
+ try {
59
+ const { done, value } = await reader.read();
60
+ if (done) { controller.close(); reader.releaseLock(); }
61
+ else controller.enqueue(value);
62
+ } catch (error) {
63
+ // Native intentional closure suppresses onRequestStreamEnd.
64
+ if (init?.signal?.aborted) pending.finishSend();
65
+ else if (error instanceof Error) pending.bodyFailure = error;
66
+ controller.error(error);
67
+ reader.releaseLock();
68
+ }
69
+ },
70
+ cancel: reason => reader.cancel(reason).finally(() => reader.releaseLock()),
71
+ }), response);
72
+ } catch (error) {
73
+ if (error instanceof Error && !init?.signal?.aborted && init?.method === "POST"
74
+ && new Headers(init.headers).get("Mcp-Method") === "tools/call") {
75
+ toolTransportFailures.add(error);
76
+ }
77
+ throw error;
78
+ }
79
+ };
80
+
81
+ /** Observe only the originating tool send, not OAuth or catalog requests. */
82
+ export function trackToolHttpFailures(transport: Transport): void {
83
+ const onmessage = transport.onmessage;
84
+ transport.onmessage = (message, extra) => {
85
+ const pending = toolSend.getStore();
86
+ if (pending && "id" in message && message.id === pending.id && ("result" in message || "error" in message)) {
87
+ pending.responseReceived = true;
88
+ pending.finishSend();
89
+ }
90
+ onmessage?.(message, extra);
91
+ };
92
+ const onerror = transport.onerror;
93
+ transport.onerror = error => {
94
+ const pending = toolSend.getStore();
95
+ // Reader failures are observed before the SDK reports them; earlier parser errors are not retryable.
96
+ if (pending && !pending.bodyFailure) pending.otherFailure ??= error;
97
+ onerror?.(error);
98
+ };
99
+ const send = transport.send.bind(transport);
100
+ transport.send = async (message, options) => {
101
+ try {
102
+ if (!("method" in message && message.method === "tools/call" && "id" in message && options?.requestSignal)) {
103
+ return await toolSend.run(undefined, () => send(message, options));
104
+ }
105
+ const pending: ToolSend = {
106
+ id: message.id, streaming: false, responseReceived: false,
107
+ bodyFailure: undefined, otherFailure: undefined,
108
+ finishSend: () => {},
109
+ };
110
+ try {
111
+ await abortable(new Promise<void>((resolve, reject) => {
112
+ pending.finishSend = resolve;
113
+ void toolSend.run(pending, () => send(message, {
114
+ ...options,
115
+ onRequestStreamEnd: () => {
116
+ options.onRequestStreamEnd?.();
117
+ const error = pending.otherFailure ?? pending.bodyFailure;
118
+ if (!pending.responseReceived && error) {
119
+ if (!pending.otherFailure) toolTransportFailures.add(error);
120
+ reject(error);
121
+ } else resolve();
122
+ },
123
+ })).then(() => { if (!pending.streaming) resolve(); }, reject);
124
+ }), options.requestSignal);
125
+ } finally {
126
+ pending.finishSend = () => {};
127
+ }
128
+ } catch (error) {
129
+ if ("method" in message && message.method === "tools/call"
130
+ && error instanceof SdkHttpError && error.code === SdkErrorCode.ClientHttpNotImplemented
131
+ && error.status >= 500 && error.status < 600) {
132
+ let errorBody = false;
133
+ try {
134
+ const body = JSON.parse(String(error.data.text));
135
+ errorBody = body?.jsonrpc === "2.0" && body.error !== undefined;
136
+ } catch {}
137
+ if (!errorBody) toolTransportFailures.add(error);
138
+ }
139
+ throw error;
140
+ }
141
+ };
142
+ }
143
+
144
+ /**
145
+ * True when `err` is a stale Streamable HTTP session signal for a request
146
+ * sent while carrying an `Mcp-Session-Id`: the spec's 404 transport
147
+ * response, or the narrowly-known `-32000 Server not initialized` protocol
148
+ * gate response some servers emit before dispatching to a handler.
149
+ *
150
+ * `hadSessionId` must reflect the transport's session id from *before* the
151
+ * call that produced `err` was made. The SDK does not
152
+ * clear `transport.sessionId` on a 404 response, so callers must capture it
153
+ * before the call rather than rely on catch-time transport state.
154
+ */
155
+ const SERVER_NOT_INITIALIZED_MCP_MESSAGES = new Set([
156
+ "Server not initialized",
157
+ "Bad Request: Server not initialized",
158
+ ]);
159
+
160
+ export function isTerminatedSession(err: unknown, hadSessionId: boolean): boolean {
161
+ if (!hadSessionId) return false;
162
+ if (err instanceof SdkHttpError) {
163
+ return err.status === 404
164
+ || (err.status === 400
165
+ && /"code"\s*:\s*-32000/.test(err.message)
166
+ && /"message"\s*:\s*"Bad Request: Server not initialized"/.test(err.message));
167
+ }
168
+ return err instanceof ProtocolError
169
+ && err.code === -32000
170
+ && SERVER_NOT_INITIALIZED_MCP_MESSAGES.has(err.message);
171
+ }
172
+
173
+ function hasSessionId(connection: ServerConnection): boolean {
174
+ // Only StreamableHTTPClientTransport exposes `sessionId`; stdio/SSE
175
+ // transports (and test doubles that omit `transport` entirely) simply
176
+ // read as `undefined` here.
177
+ const transport = connection.transport as { sessionId?: string } | undefined;
178
+ return transport?.sessionId != null;
179
+ }
180
+
181
+ export class SessionRecoveryAuthRequiredError extends Error {
182
+ constructor(readonly serverName: string, readonly authMessage?: string) {
183
+ super(authMessage ?? `MCP server "${serverName}" requires OAuth authentication after reconnect.`);
184
+ this.name = "SessionRecoveryAuthRequiredError";
185
+ }
186
+ }
187
+
188
+ export interface AuthChallengeContext {
189
+ connection: ServerConnection;
190
+ error: Error;
191
+ }
192
+
193
+ export interface SessionRecoveryDeps {
194
+ manager: McpServerManager;
195
+ config: McpConfig;
196
+ signal?: AbortSignal;
197
+ /** Only replay-safe tool calls may opt into a same-client retry of a proven modern POST transport failure. */
198
+ retryOnTransportFailure?: boolean;
199
+ onNeedsAuth?: (serverName: string, signal?: AbortSignal, challenge?: AuthChallengeContext) => Promise<ServerConnection | undefined>;
200
+ }
201
+
202
+ /**
203
+ * Retry once on the same modern client when explicitly enabled, or reconnect
204
+ * an expired legacy session once. Neither path retries its second failure.
205
+ */
206
+ export async function withSessionRecovery<T>(
207
+ deps: SessionRecoveryDeps,
208
+ serverName: string,
209
+ fn: (conn: ServerConnection) => Promise<T>,
210
+ ): Promise<T> {
211
+ if (isServerDisabled(deps.config.mcpServers[serverName])) {
212
+ throw new Error(`MCP server "${serverName}" is disabled`);
213
+ }
214
+ throwIfAborted(deps.signal);
215
+ let connection = deps.manager.getConnection(serverName);
216
+ if (!connection) {
217
+ throw new Error(`Server "${serverName}" is not connected`);
218
+ }
219
+
220
+ const reconnect = async (stale: ServerConnection, error: unknown): Promise<ServerConnection> => {
221
+ const definition = deps.config.mcpServers[serverName];
222
+ if (!definition) throw error;
223
+ throwIfAborted(deps.signal);
224
+ let fresh = stale;
225
+ if (fresh.status !== "needs-auth") {
226
+ fresh = deps.signal
227
+ ? await deps.manager.reconnect(serverName, definition, stale, deps.signal)
228
+ : await deps.manager.reconnect(serverName, definition, stale);
229
+ }
230
+ throwIfAborted(deps.signal);
231
+ if (fresh.status === "needs-auth" && deps.onNeedsAuth) {
232
+ fresh = await abortable(deps.onNeedsAuth(serverName, deps.signal), deps.signal) ?? fresh;
233
+ throwIfAborted(deps.signal);
234
+ }
235
+ if (fresh.status === "needs-auth") throw new SessionRecoveryAuthRequiredError(serverName);
236
+ if (fresh.status !== "connected") throw error;
237
+ return fresh;
238
+ };
239
+
240
+ const isRecoverableAuth = (error: unknown, failed: ServerConnection, activating = false): error is Error => {
241
+ const definition = deps.config.mcpServers[serverName];
242
+ if (!definition || isServerDisabled(definition) || !supportsOAuth(definition)) return false;
243
+ if (error instanceof SdkHttpError) {
244
+ // A provider's exhausted native 401/M2M retry is terminal, not another consent cycle.
245
+ return failed.oauthProvider === false && error.status === 401 && error.code !== SdkErrorCode.ClientHttpAuthentication;
246
+ }
247
+ if (failed.oauthProvider && isNonInteractiveOAuth(definition.oauth)) return false;
248
+ return error instanceof InsufficientScopeError || (activating && error instanceof UnauthorizedError);
249
+ };
250
+
251
+ const terminalDispatch = async (fresh: ServerConnection): Promise<T> => {
252
+ throwIfAborted(deps.signal);
253
+ try {
254
+ return await fn(fresh);
255
+ } catch (error) {
256
+ throwIfAborted(deps.signal);
257
+ if (isRecoverableAuth(error, fresh)) throw new SessionRecoveryAuthRequiredError(serverName);
258
+ throw error;
259
+ }
260
+ };
261
+
262
+ const recoverAuth = async (failed: ServerConnection, error: Error): Promise<T> => {
263
+ const definition = deps.config.mcpServers[serverName]!;
264
+ const current = deps.manager.getConnection(serverName);
265
+ if (current && current !== failed && failed.oauthProvider !== false) {
266
+ return terminalDispatch(current.status === "connected" ? current : await reconnect(current, error));
267
+ }
268
+
269
+ if (failed.oauthProvider === false) {
270
+ // One anonymous rejection may activate the provider without asking the user to sign in.
271
+ failed = await deps.manager.reconnect(serverName, definition, failed, deps.signal);
272
+ throwIfAborted(deps.signal);
273
+ if (failed.status === "connected") {
274
+ try {
275
+ return await fn(failed);
276
+ } catch (providerError) {
277
+ throwIfAborted(deps.signal);
278
+ if (!isRecoverableAuth(providerError, failed, true)) throw providerError;
279
+ error = providerError;
280
+ }
281
+ }
282
+ }
283
+ if (isNonInteractiveOAuth(definition.oauth)) throw error;
284
+ const fresh = await abortable(deps.onNeedsAuth?.(serverName, deps.signal, { connection: failed, error }) ?? Promise.resolve(undefined), deps.signal);
285
+ throwIfAborted(deps.signal);
286
+ if (!fresh || fresh === failed || fresh.status !== "connected") throw new SessionRecoveryAuthRequiredError(serverName);
287
+ return terminalDispatch(fresh);
288
+ };
289
+
290
+ // Nothing has been dispatched yet: wait for replacement/auth begun during UI preparation.
291
+ if (connection.status !== "connected") {
292
+ connection = await reconnect(connection, new Error(`Server "${serverName}" is not connected`));
293
+ }
294
+ const hadSessionId = hasSessionId(connection);
295
+
296
+ try {
297
+ return await fn(connection);
298
+ } catch (err) {
299
+ throwIfAborted(deps.signal);
300
+ if (isRecoverableAuth(err, connection)) return recoverAuth(connection, err);
301
+ if (deps.retryOnTransportFailure === true
302
+ && deps.config.mcpServers[serverName]?.retryOnTransportFailure === true
303
+ && connection.client.getProtocolEra?.() === "modern"
304
+ && isToolTransportFailure(err)) {
305
+ return terminalDispatch(connection);
306
+ }
307
+ if (!isTerminatedSession(err, hadSessionId)) {
308
+ throw err;
309
+ }
310
+
311
+ logger.debug(`MCP session for "${serverName}" expired; reconnecting`, {
312
+ server: serverName,
313
+ });
314
+ return terminalDispatch(await reconnect(connection, err));
315
+ }
316
+ }
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: mcp-scripting
3
+ description: Write mcp_script JavaScript for discovering, inspecting, and calling MCP tools.
4
+ ---
5
+
6
+ # MCP scripting
7
+
8
+ For multi-call MCP work, write ordinary JavaScript with loops, filtering, chaining, fan-out, or other logic between calls. Run that source with `mcp_script`; it is the primary MCP orchestration surface. For a single MCP search, describe, status check, auth action, or tool call, use `mcp` instead.
9
+
10
+ Write the source naturally, then pass it as `mcp_script`'s `code` argument:
11
+
12
+ ```js
13
+ const { items } = await tools.search({ query: "search issues", server: "github" });
14
+ const candidate = items[0];
15
+ if (!candidate) return { error: "No matching tool" };
16
+
17
+ const details = await tools.describe({ path: candidate.path });
18
+ if (details.error) return details;
19
+
20
+ const result = await tools.call(details.path, { query: "is:open label:bug" });
21
+ if (!result.ok) return result;
22
+ emit({ tool: details.path, completed: true });
23
+ return result.data?.structuredContent ?? result.data;
24
+ ```
25
+
26
+ ## Workflow
27
+
28
+ 1. Find candidate tools with `await tools.search({ query, server?, limit?, offset? })`. `limit` defaults to 12 and is capped at 100.
29
+ 2. Inspect the exact returned path with `await tools.describe({ path })`. Arguments are described by `inputTypeScript` when representable, otherwise by the original JSON Schema in `inputSchema`; only one is included.
30
+ 3. Call it with `tools.call(path, args)`.
31
+
32
+ Calls resolve to `{ ok: true, data }` or `{ ok: false, error }`; handle failed calls instead of expecting them to stop the script. Successful `data` is the raw MCP result: tool calls usually return `{ content, structuredContent? }`, while resource reads return `{ contents }`. Prefer `structuredContent` when present, and only parse a text block when that server documents JSON text. `emit(value)` adds user-visible output before the final `return` value. `console` output is captured too.
33
+
34
+ `tools` is a non-enumerable proxy: `Object.keys(tools)` throws. Always use `tools.search` for discovery. When a known flat path is a valid identifier, direct calls such as `tools.github_search_issues(args)` are supported; use bracket syntax for hyphenated names: `tools["server_tool-name"](args)`. `search`, `call`, `describe`, and promise/serialization names (`then`, `catch`, `finally`, `toJSON`, `toString`, `valueOf`) are reserved on the proxy; if a flat path collides with one, call it via `tools.call("exact-path", args)`.
35
+
36
+ `tools.search` and `tools.describe` are asynchronous and must be awaited. The default script timeout is 30 seconds unless the SDK host overrides or disables it (see the registered `timeoutMs` description); explicit per-script timeouts still apply, and the worker is terminated on timeout or cancellation, including for infinite loops. Every invocation still uses normal lazy connection, authentication, output guarding, and approval gates. Raw call results are cloned into the worker so scripts can reduce them before the model-facing guard; request scoped data instead of unnecessarily large payloads. Result details contain a concise `calls` trace with every search, describe, and call operation; each entry includes its query or path, outcome, and duration.
37
+
38
+ Use plain JavaScript loops and Promise utilities for composition. The sandbox has no Node, filesystem, or network globals such as `process`, `Buffer`, or `fetch`. Fluent helpers such as `tools.find(...).one()`, `tools.parallel(...)`, and `tools.retry(...)` are not provided.
package/state.ts ADDED
@@ -0,0 +1,64 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { ConsentManager } from "./consent-manager.ts";
3
+ import type { McpLifecycleManager } from "./lifecycle.ts";
4
+ import type { McpServerManager } from "./server-manager.ts";
5
+ import type { AuthStorageOptions } from "./mcp-auth.ts";
6
+ import type { ToolMetadata, PromptMetadata, McpConfig, McpAdapterOptions, UiSessionMessages, UiStreamSummary } from "./types.ts";
7
+ import type { UiResourceHandler } from "./ui-resource-handler.ts";
8
+ import type { UiServerHandle } from "./ui-server.ts";
9
+ import type { McpRuntimeOwner } from "./runtime-owner.ts";
10
+ import type { McpOAuthRuntime } from "./mcp-auth-flow.ts";
11
+ import type { McpStatusEventBus } from "./mcp-status.ts";
12
+
13
+ export interface CompletedUiSession {
14
+ serverName: string;
15
+ toolName: string;
16
+ completedAt: Date;
17
+ reason: string;
18
+ messages: UiSessionMessages;
19
+ stream?: UiStreamSummary;
20
+ }
21
+
22
+ export type SendMessageFn = (
23
+ message: {
24
+ customType: string;
25
+ content: Array<{ type: "text"; text: string }>;
26
+ display?: string;
27
+ details?: unknown;
28
+ },
29
+ options?: { triggerTurn?: boolean }
30
+ ) => void;
31
+
32
+ export interface McpExtensionState {
33
+ owner: McpRuntimeOwner;
34
+ manager: McpServerManager;
35
+ lifecycle: McpLifecycleManager;
36
+ toolMetadata: Map<string, ToolMetadata[]>;
37
+ /** Resource counts retained separately because tool metadata includes resource tools. */
38
+ resourceCounts: Map<string, number>;
39
+ promptMetadata: Map<string, PromptMetadata[]>;
40
+ /** Servers whose prompt inventory came from successful live discovery. */
41
+ promptMetadataLive: Set<string>;
42
+ serverInstructions: Map<string, string>;
43
+ config: McpConfig;
44
+ programmaticConfig?: boolean;
45
+ outputDirectory?: string;
46
+ onToolCall?: McpAdapterOptions["onToolCall"];
47
+ oauthRuntime: McpOAuthRuntime;
48
+ authStorageOptions: AuthStorageOptions;
49
+ metadataCacheEnabled: boolean;
50
+ failureTracker: Map<string, number>;
51
+ failureMessages: Map<string, string>;
52
+ /** Session-only approvals keyed by server and original tool name. */
53
+ approvedToolCalls: Map<string, true>;
54
+ uiResourceHandler: UiResourceHandler;
55
+ consentManager: ConsentManager;
56
+ uiServer: UiServerHandle | null;
57
+ completedUiSessions: CompletedUiSession[];
58
+ activeScripts: number;
59
+ openBrowser: (url: string) => Promise<void>;
60
+ ui?: ExtensionContext["ui"];
61
+ sendMessage?: SendMessageFn;
62
+ onToolMetadataUpdated?: (serverName: string, reason: string) => void | Promise<void>;
63
+ statusEvents?: McpStatusEventBus;
64
+ }
@@ -0,0 +1,78 @@
1
+ import { abortable } from "./abort.ts";
2
+ import { combineAbortSignals } from "./runtime-owner.ts";
3
+ import type { McpExtensionState } from "./state.ts";
4
+ import {
5
+ getToolNameCandidates,
6
+ matchesToolPattern,
7
+ resolveToolPrefix,
8
+ type McpConfig,
9
+ type ToolMetadata,
10
+ } from "./types.ts";
11
+ import { sanitizeTerminalText } from "./utils.ts";
12
+
13
+ export type ToolCallApprovalResult =
14
+ | { ok: true }
15
+ | { ok: false; reason: "denied" | "approval_required_headless" };
16
+
17
+ export function isToolCallApprovalRequired(
18
+ config: McpConfig,
19
+ serverName: string,
20
+ toolMeta: Pick<ToolMetadata, "originalName">,
21
+ ): boolean {
22
+ const definition = config.mcpServers[serverName];
23
+ const approval = definition?.approveTools !== undefined
24
+ ? definition.approveTools
25
+ : config.settings?.approveTools;
26
+
27
+ if (approval === true) return true;
28
+ if (!Array.isArray(approval) || approval.length === 0) return false;
29
+
30
+ const prefix = resolveToolPrefix(definition, config.settings?.toolPrefix);
31
+ return matchesToolPattern(
32
+ getToolNameCandidates(toolMeta.originalName, serverName, prefix),
33
+ approval,
34
+ );
35
+ }
36
+
37
+ export async function ensureToolCallApproved(
38
+ state: McpExtensionState,
39
+ serverName: string,
40
+ toolMeta: ToolMetadata,
41
+ args: Record<string, unknown> | undefined,
42
+ signal?: AbortSignal,
43
+ ): Promise<ToolCallApprovalResult> {
44
+ if (!isToolCallApprovalRequired(state.config, serverName, toolMeta)) {
45
+ return { ok: true };
46
+ }
47
+
48
+ const cacheKey = `${serverName}\u0000${toolMeta.originalName}`;
49
+ if (state.approvedToolCalls.has(cacheKey)) {
50
+ return { ok: true };
51
+ }
52
+
53
+ if (!state.ui) {
54
+ return { ok: false, reason: "approval_required_headless" };
55
+ }
56
+
57
+ const json = JSON.stringify(args ?? {}, null, 2);
58
+ const sanitized = sanitizeTerminalText(json);
59
+ const preview = sanitized.length > 500 ? `${sanitized.slice(0, 500)}...` : sanitized;
60
+ const title = `MCP: ${sanitizeTerminalText(serverName)} wants to run ${sanitizeTerminalText(toolMeta.originalName)}`;
61
+ const ownedSignal = combineAbortSignals(state.owner?.signal, signal);
62
+ const decision = await abortable(
63
+ state.ui.select(
64
+ `${title}\n\nArguments:\n${preview}`,
65
+ ["Allow once", "Allow for session", "Deny"],
66
+ ),
67
+ ownedSignal,
68
+ );
69
+
70
+ if (decision === "Allow once") {
71
+ return { ok: true };
72
+ }
73
+ if (decision === "Allow for session") {
74
+ state.approvedToolCalls.set(cacheKey, true);
75
+ return { ok: true };
76
+ }
77
+ return { ok: false, reason: "denied" };
78
+ }