@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,31 @@
1
+ import { type FetchLike, type Transport } from "@modelcontextprotocol/client";
2
+ import { type McpConfig } from "./types.ts";
3
+ import type { McpServerManager, ServerConnection } from "./server-manager.ts";
4
+ export declare function isToolTransportFailure(error: unknown): boolean;
5
+ /** Retain fetch/body-error origin without parsing or buffering the SSE response. */
6
+ export declare const trackToolTransportFailure: FetchLike;
7
+ /** Observe only the originating tool send, not OAuth or catalog requests. */
8
+ export declare function trackToolHttpFailures(transport: Transport): void;
9
+ export declare function isTerminatedSession(err: unknown, hadSessionId: boolean): boolean;
10
+ export declare class SessionRecoveryAuthRequiredError extends Error {
11
+ readonly serverName: string;
12
+ readonly authMessage?: string | undefined;
13
+ constructor(serverName: string, authMessage?: string | undefined);
14
+ }
15
+ export interface AuthChallengeContext {
16
+ connection: ServerConnection;
17
+ error: Error;
18
+ }
19
+ export interface SessionRecoveryDeps {
20
+ manager: McpServerManager;
21
+ config: McpConfig;
22
+ signal?: AbortSignal;
23
+ /** Only replay-safe tool calls may opt into a same-client retry of a proven modern POST transport failure. */
24
+ retryOnTransportFailure?: boolean;
25
+ onNeedsAuth?: (serverName: string, signal?: AbortSignal, challenge?: AuthChallengeContext) => Promise<ServerConnection | undefined>;
26
+ }
27
+ /**
28
+ * Retry once on the same modern client when explicitly enabled, or reconnect
29
+ * an expired legacy session once. Neither path retries its second failure.
30
+ */
31
+ export declare function withSessionRecovery<T>(deps: SessionRecoveryDeps, serverName: string, fn: (conn: ServerConnection) => Promise<T>): Promise<T>;
@@ -0,0 +1,310 @@
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 } from "@modelcontextprotocol/client";
25
+ import { logger } from "./logger.js";
26
+ import { abortable, throwIfAborted } from "./abort.js";
27
+ import { isServerDisabled, isNonInteractiveOAuth } from "./types.js";
28
+ import { supportsOAuth } from "./mcp-auth-flow.js";
29
+ const toolTransportFailures = new WeakSet();
30
+ export function isToolTransportFailure(error) {
31
+ return error instanceof Error && toolTransportFailures.has(error);
32
+ }
33
+ const toolSend = new AsyncLocalStorage();
34
+ /** Retain fetch/body-error origin without parsing or buffering the SSE response. */
35
+ export const trackToolTransportFailure = async (input, init) => {
36
+ const pending = toolSend.getStore();
37
+ if (pending)
38
+ pending.bodyFailure = undefined;
39
+ try {
40
+ const response = await fetch(input, init);
41
+ if (!pending || !response.ok || !response.body
42
+ || response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() !== "text/event-stream")
43
+ return response;
44
+ pending.streaming = true;
45
+ // The native end hook has no error argument. Only a failed body read proves loss.
46
+ const reader = response.body.getReader();
47
+ return new Response(new ReadableStream({
48
+ async pull(controller) {
49
+ try {
50
+ const { done, value } = await reader.read();
51
+ if (done) {
52
+ controller.close();
53
+ reader.releaseLock();
54
+ }
55
+ else
56
+ controller.enqueue(value);
57
+ }
58
+ catch (error) {
59
+ // Native intentional closure suppresses onRequestStreamEnd.
60
+ if (init?.signal?.aborted)
61
+ pending.finishSend();
62
+ else if (error instanceof Error)
63
+ pending.bodyFailure = error;
64
+ controller.error(error);
65
+ reader.releaseLock();
66
+ }
67
+ },
68
+ cancel: reason => reader.cancel(reason).finally(() => reader.releaseLock()),
69
+ }), response);
70
+ }
71
+ catch (error) {
72
+ if (error instanceof Error && !init?.signal?.aborted && init?.method === "POST"
73
+ && new Headers(init.headers).get("Mcp-Method") === "tools/call") {
74
+ toolTransportFailures.add(error);
75
+ }
76
+ throw error;
77
+ }
78
+ };
79
+ /** Observe only the originating tool send, not OAuth or catalog requests. */
80
+ export function trackToolHttpFailures(transport) {
81
+ const onmessage = transport.onmessage;
82
+ transport.onmessage = (message, extra) => {
83
+ const pending = toolSend.getStore();
84
+ if (pending && "id" in message && message.id === pending.id && ("result" in message || "error" in message)) {
85
+ pending.responseReceived = true;
86
+ pending.finishSend();
87
+ }
88
+ onmessage?.(message, extra);
89
+ };
90
+ const onerror = transport.onerror;
91
+ transport.onerror = error => {
92
+ const pending = toolSend.getStore();
93
+ // Reader failures are observed before the SDK reports them; earlier parser errors are not retryable.
94
+ if (pending && !pending.bodyFailure)
95
+ pending.otherFailure ??= error;
96
+ onerror?.(error);
97
+ };
98
+ const send = transport.send.bind(transport);
99
+ transport.send = async (message, options) => {
100
+ try {
101
+ if (!("method" in message && message.method === "tools/call" && "id" in message && options?.requestSignal)) {
102
+ return await toolSend.run(undefined, () => send(message, options));
103
+ }
104
+ const pending = {
105
+ id: message.id, streaming: false, responseReceived: false,
106
+ bodyFailure: undefined, otherFailure: undefined,
107
+ finishSend: () => { },
108
+ };
109
+ try {
110
+ await abortable(new Promise((resolve, reject) => {
111
+ pending.finishSend = resolve;
112
+ void toolSend.run(pending, () => send(message, {
113
+ ...options,
114
+ onRequestStreamEnd: () => {
115
+ options.onRequestStreamEnd?.();
116
+ const error = pending.otherFailure ?? pending.bodyFailure;
117
+ if (!pending.responseReceived && error) {
118
+ if (!pending.otherFailure)
119
+ toolTransportFailures.add(error);
120
+ reject(error);
121
+ }
122
+ else
123
+ resolve();
124
+ },
125
+ })).then(() => { if (!pending.streaming)
126
+ resolve(); }, reject);
127
+ }), options.requestSignal);
128
+ }
129
+ finally {
130
+ pending.finishSend = () => { };
131
+ }
132
+ }
133
+ catch (error) {
134
+ if ("method" in message && message.method === "tools/call"
135
+ && error instanceof SdkHttpError && error.code === SdkErrorCode.ClientHttpNotImplemented
136
+ && error.status >= 500 && error.status < 600) {
137
+ let errorBody = false;
138
+ try {
139
+ const body = JSON.parse(String(error.data.text));
140
+ errorBody = body?.jsonrpc === "2.0" && body.error !== undefined;
141
+ }
142
+ catch { }
143
+ if (!errorBody)
144
+ toolTransportFailures.add(error);
145
+ }
146
+ throw error;
147
+ }
148
+ };
149
+ }
150
+ /**
151
+ * True when `err` is a stale Streamable HTTP session signal for a request
152
+ * sent while carrying an `Mcp-Session-Id`: the spec's 404 transport
153
+ * response, or the narrowly-known `-32000 Server not initialized` protocol
154
+ * gate response some servers emit before dispatching to a handler.
155
+ *
156
+ * `hadSessionId` must reflect the transport's session id from *before* the
157
+ * call that produced `err` was made. The SDK does not
158
+ * clear `transport.sessionId` on a 404 response, so callers must capture it
159
+ * before the call rather than rely on catch-time transport state.
160
+ */
161
+ const SERVER_NOT_INITIALIZED_MCP_MESSAGES = new Set([
162
+ "Server not initialized",
163
+ "Bad Request: Server not initialized",
164
+ ]);
165
+ export function isTerminatedSession(err, hadSessionId) {
166
+ if (!hadSessionId)
167
+ return false;
168
+ if (err instanceof SdkHttpError) {
169
+ return err.status === 404
170
+ || (err.status === 400
171
+ && /"code"\s*:\s*-32000/.test(err.message)
172
+ && /"message"\s*:\s*"Bad Request: Server not initialized"/.test(err.message));
173
+ }
174
+ return err instanceof ProtocolError
175
+ && err.code === -32000
176
+ && SERVER_NOT_INITIALIZED_MCP_MESSAGES.has(err.message);
177
+ }
178
+ function hasSessionId(connection) {
179
+ // Only StreamableHTTPClientTransport exposes `sessionId`; stdio/SSE
180
+ // transports (and test doubles that omit `transport` entirely) simply
181
+ // read as `undefined` here.
182
+ const transport = connection.transport;
183
+ return transport?.sessionId != null;
184
+ }
185
+ export class SessionRecoveryAuthRequiredError extends Error {
186
+ serverName;
187
+ authMessage;
188
+ constructor(serverName, authMessage) {
189
+ super(authMessage ?? `MCP server "${serverName}" requires OAuth authentication after reconnect.`);
190
+ this.serverName = serverName;
191
+ this.authMessage = authMessage;
192
+ this.name = "SessionRecoveryAuthRequiredError";
193
+ }
194
+ }
195
+ /**
196
+ * Retry once on the same modern client when explicitly enabled, or reconnect
197
+ * an expired legacy session once. Neither path retries its second failure.
198
+ */
199
+ export async function withSessionRecovery(deps, serverName, fn) {
200
+ if (isServerDisabled(deps.config.mcpServers[serverName])) {
201
+ throw new Error(`MCP server "${serverName}" is disabled`);
202
+ }
203
+ throwIfAborted(deps.signal);
204
+ let connection = deps.manager.getConnection(serverName);
205
+ if (!connection) {
206
+ throw new Error(`Server "${serverName}" is not connected`);
207
+ }
208
+ const reconnect = async (stale, error) => {
209
+ const definition = deps.config.mcpServers[serverName];
210
+ if (!definition)
211
+ throw error;
212
+ throwIfAborted(deps.signal);
213
+ let fresh = stale;
214
+ if (fresh.status !== "needs-auth") {
215
+ fresh = deps.signal
216
+ ? await deps.manager.reconnect(serverName, definition, stale, deps.signal)
217
+ : await deps.manager.reconnect(serverName, definition, stale);
218
+ }
219
+ throwIfAborted(deps.signal);
220
+ if (fresh.status === "needs-auth" && deps.onNeedsAuth) {
221
+ fresh = await abortable(deps.onNeedsAuth(serverName, deps.signal), deps.signal) ?? fresh;
222
+ throwIfAborted(deps.signal);
223
+ }
224
+ if (fresh.status === "needs-auth")
225
+ throw new SessionRecoveryAuthRequiredError(serverName);
226
+ if (fresh.status !== "connected")
227
+ throw error;
228
+ return fresh;
229
+ };
230
+ const isRecoverableAuth = (error, failed, activating = false) => {
231
+ const definition = deps.config.mcpServers[serverName];
232
+ if (!definition || isServerDisabled(definition) || !supportsOAuth(definition))
233
+ return false;
234
+ if (error instanceof SdkHttpError) {
235
+ // A provider's exhausted native 401/M2M retry is terminal, not another consent cycle.
236
+ return failed.oauthProvider === false && error.status === 401 && error.code !== SdkErrorCode.ClientHttpAuthentication;
237
+ }
238
+ if (failed.oauthProvider && isNonInteractiveOAuth(definition.oauth))
239
+ return false;
240
+ return error instanceof InsufficientScopeError || (activating && error instanceof UnauthorizedError);
241
+ };
242
+ const terminalDispatch = async (fresh) => {
243
+ throwIfAborted(deps.signal);
244
+ try {
245
+ return await fn(fresh);
246
+ }
247
+ catch (error) {
248
+ throwIfAborted(deps.signal);
249
+ if (isRecoverableAuth(error, fresh))
250
+ throw new SessionRecoveryAuthRequiredError(serverName);
251
+ throw error;
252
+ }
253
+ };
254
+ const recoverAuth = async (failed, error) => {
255
+ const definition = deps.config.mcpServers[serverName];
256
+ const current = deps.manager.getConnection(serverName);
257
+ if (current && current !== failed && failed.oauthProvider !== false) {
258
+ return terminalDispatch(current.status === "connected" ? current : await reconnect(current, error));
259
+ }
260
+ if (failed.oauthProvider === false) {
261
+ // One anonymous rejection may activate the provider without asking the user to sign in.
262
+ failed = await deps.manager.reconnect(serverName, definition, failed, deps.signal);
263
+ throwIfAborted(deps.signal);
264
+ if (failed.status === "connected") {
265
+ try {
266
+ return await fn(failed);
267
+ }
268
+ catch (providerError) {
269
+ throwIfAborted(deps.signal);
270
+ if (!isRecoverableAuth(providerError, failed, true))
271
+ throw providerError;
272
+ error = providerError;
273
+ }
274
+ }
275
+ }
276
+ if (isNonInteractiveOAuth(definition.oauth))
277
+ throw error;
278
+ const fresh = await abortable(deps.onNeedsAuth?.(serverName, deps.signal, { connection: failed, error }) ?? Promise.resolve(undefined), deps.signal);
279
+ throwIfAborted(deps.signal);
280
+ if (!fresh || fresh === failed || fresh.status !== "connected")
281
+ throw new SessionRecoveryAuthRequiredError(serverName);
282
+ return terminalDispatch(fresh);
283
+ };
284
+ // Nothing has been dispatched yet: wait for replacement/auth begun during UI preparation.
285
+ if (connection.status !== "connected") {
286
+ connection = await reconnect(connection, new Error(`Server "${serverName}" is not connected`));
287
+ }
288
+ const hadSessionId = hasSessionId(connection);
289
+ try {
290
+ return await fn(connection);
291
+ }
292
+ catch (err) {
293
+ throwIfAborted(deps.signal);
294
+ if (isRecoverableAuth(err, connection))
295
+ return recoverAuth(connection, err);
296
+ if (deps.retryOnTransportFailure === true
297
+ && deps.config.mcpServers[serverName]?.retryOnTransportFailure === true
298
+ && connection.client.getProtocolEra?.() === "modern"
299
+ && isToolTransportFailure(err)) {
300
+ return terminalDispatch(connection);
301
+ }
302
+ if (!isTerminatedSession(err, hadSessionId)) {
303
+ throw err;
304
+ }
305
+ logger.debug(`MCP session for "${serverName}" expired; reconnecting`, {
306
+ server: serverName,
307
+ });
308
+ return terminalDispatch(await reconnect(connection, err));
309
+ }
310
+ }
@@ -0,0 +1,63 @@
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
+ export interface CompletedUiSession {
13
+ serverName: string;
14
+ toolName: string;
15
+ completedAt: Date;
16
+ reason: string;
17
+ messages: UiSessionMessages;
18
+ stream?: UiStreamSummary;
19
+ }
20
+ export type SendMessageFn = (message: {
21
+ customType: string;
22
+ content: Array<{
23
+ type: "text";
24
+ text: string;
25
+ }>;
26
+ display?: string;
27
+ details?: unknown;
28
+ }, options?: {
29
+ triggerTurn?: boolean;
30
+ }) => void;
31
+ export interface McpExtensionState {
32
+ owner: McpRuntimeOwner;
33
+ manager: McpServerManager;
34
+ lifecycle: McpLifecycleManager;
35
+ toolMetadata: Map<string, ToolMetadata[]>;
36
+ /** Resource counts retained separately because tool metadata includes resource tools. */
37
+ resourceCounts: Map<string, number>;
38
+ promptMetadata: Map<string, PromptMetadata[]>;
39
+ /** Servers whose prompt inventory came from successful live discovery. */
40
+ promptMetadataLive: Set<string>;
41
+ serverInstructions: Map<string, string>;
42
+ config: McpConfig;
43
+ programmaticConfig?: boolean;
44
+ outputDirectory?: string;
45
+ onToolCall?: McpAdapterOptions["onToolCall"];
46
+ oauthRuntime: McpOAuthRuntime;
47
+ authStorageOptions: AuthStorageOptions;
48
+ metadataCacheEnabled: boolean;
49
+ failureTracker: Map<string, number>;
50
+ failureMessages: Map<string, string>;
51
+ /** Session-only approvals keyed by server and original tool name. */
52
+ approvedToolCalls: Map<string, true>;
53
+ uiResourceHandler: UiResourceHandler;
54
+ consentManager: ConsentManager;
55
+ uiServer: UiServerHandle | null;
56
+ completedUiSessions: CompletedUiSession[];
57
+ activeScripts: number;
58
+ openBrowser: (url: string) => Promise<void>;
59
+ ui?: ExtensionContext["ui"];
60
+ sendMessage?: SendMessageFn;
61
+ onToolMetadataUpdated?: (serverName: string, reason: string) => void | Promise<void>;
62
+ statusEvents?: McpStatusEventBus;
63
+ }
package/dist/state.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ import type { McpExtensionState } from "./state.ts";
2
+ import { type McpConfig, type ToolMetadata } from "./types.ts";
3
+ export type ToolCallApprovalResult = {
4
+ ok: true;
5
+ } | {
6
+ ok: false;
7
+ reason: "denied" | "approval_required_headless";
8
+ };
9
+ export declare function isToolCallApprovalRequired(config: McpConfig, serverName: string, toolMeta: Pick<ToolMetadata, "originalName">): boolean;
10
+ export declare function ensureToolCallApproved(state: McpExtensionState, serverName: string, toolMeta: ToolMetadata, args: Record<string, unknown> | undefined, signal?: AbortSignal): Promise<ToolCallApprovalResult>;
@@ -0,0 +1,42 @@
1
+ import { abortable } from "./abort.js";
2
+ import { combineAbortSignals } from "./runtime-owner.js";
3
+ import { getToolNameCandidates, matchesToolPattern, resolveToolPrefix, } from "./types.js";
4
+ import { sanitizeTerminalText } from "./utils.js";
5
+ export function isToolCallApprovalRequired(config, serverName, toolMeta) {
6
+ const definition = config.mcpServers[serverName];
7
+ const approval = definition?.approveTools !== undefined
8
+ ? definition.approveTools
9
+ : config.settings?.approveTools;
10
+ if (approval === true)
11
+ return true;
12
+ if (!Array.isArray(approval) || approval.length === 0)
13
+ return false;
14
+ const prefix = resolveToolPrefix(definition, config.settings?.toolPrefix);
15
+ return matchesToolPattern(getToolNameCandidates(toolMeta.originalName, serverName, prefix), approval);
16
+ }
17
+ export async function ensureToolCallApproved(state, serverName, toolMeta, args, signal) {
18
+ if (!isToolCallApprovalRequired(state.config, serverName, toolMeta)) {
19
+ return { ok: true };
20
+ }
21
+ const cacheKey = `${serverName}\u0000${toolMeta.originalName}`;
22
+ if (state.approvedToolCalls.has(cacheKey)) {
23
+ return { ok: true };
24
+ }
25
+ if (!state.ui) {
26
+ return { ok: false, reason: "approval_required_headless" };
27
+ }
28
+ const json = JSON.stringify(args ?? {}, null, 2);
29
+ const sanitized = sanitizeTerminalText(json);
30
+ const preview = sanitized.length > 500 ? `${sanitized.slice(0, 500)}...` : sanitized;
31
+ const title = `MCP: ${sanitizeTerminalText(serverName)} wants to run ${sanitizeTerminalText(toolMeta.originalName)}`;
32
+ const ownedSignal = combineAbortSignals(state.owner?.signal, signal);
33
+ const decision = await abortable(state.ui.select(`${title}\n\nArguments:\n${preview}`, ["Allow once", "Allow for session", "Deny"]), ownedSignal);
34
+ if (decision === "Allow once") {
35
+ return { ok: true };
36
+ }
37
+ if (decision === "Allow for session") {
38
+ state.approvedToolCalls.set(cacheKey, true);
39
+ return { ok: true };
40
+ }
41
+ return { ok: false, reason: "denied" };
42
+ }
@@ -0,0 +1,9 @@
1
+ import type { McpExtensionState } from "./state.ts";
2
+ import type { ToolMetadata, McpTool, McpResource, ServerEntry, ToolPrefix } from "./types.ts";
3
+ export declare function buildToolMetadata(tools: McpTool[], resources: McpResource[], definition: ServerEntry, serverName: string, prefix: ToolPrefix): {
4
+ metadata: ToolMetadata[];
5
+ failedTools: string[];
6
+ };
7
+ export declare function totalToolCount(state: McpExtensionState): number;
8
+ export declare function findToolByName(metadata: ToolMetadata[] | undefined, toolName: string): ToolMetadata | undefined;
9
+ export declare function formatSchema(schema: unknown, indent?: string): string;
@@ -0,0 +1,193 @@
1
+ import { getToolUiResourceUri } from "@modelcontextprotocol/ext-apps/app-bridge";
2
+ import { formatToolName, isToolAllowed, resolveToolPrefix } from "./types.js";
3
+ import { resourceNameToToolName } from "./resource-tools.js";
4
+ import { extractToolUiStreamMode } from "./utils.js";
5
+ import { extractUiToolVisibility, isUiToolVisibleToModel } from "./ui-tool-visibility.js";
6
+ export function buildToolMetadata(tools, resources, definition, serverName, prefix) {
7
+ const metadata = [];
8
+ const failedTools = [];
9
+ const seenNames = new Set();
10
+ const effectivePrefix = resolveToolPrefix(definition, prefix);
11
+ for (const tool of tools) {
12
+ if (!tool?.name) {
13
+ failedTools.push("(unnamed)");
14
+ continue;
15
+ }
16
+ if (!isToolAllowed(tool.name, serverName, effectivePrefix, definition.includeTools, definition.excludeTools)) {
17
+ continue;
18
+ }
19
+ const name = formatToolName(tool.name, serverName, effectivePrefix);
20
+ if (seenNames.has(name)) {
21
+ continue;
22
+ }
23
+ const uiVisibility = extractUiToolVisibility(tool._meta);
24
+ if (!isUiToolVisibleToModel(uiVisibility)) {
25
+ continue;
26
+ }
27
+ seenNames.add(name);
28
+ let uiResourceUri;
29
+ try {
30
+ uiResourceUri = getToolUiResourceUri({ _meta: tool._meta });
31
+ }
32
+ catch {
33
+ failedTools.push(tool.name);
34
+ }
35
+ const uiStreamMode = extractToolUiStreamMode(tool._meta);
36
+ metadata.push({
37
+ name,
38
+ originalName: tool.name,
39
+ description: tool.description ?? "",
40
+ ...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
41
+ ...(tool.annotations !== undefined ? { annotations: tool.annotations } : {}),
42
+ ...(uiResourceUri !== undefined ? { uiResourceUri } : {}),
43
+ ...(uiVisibility !== undefined ? { uiVisibility } : {}),
44
+ ...(uiStreamMode !== undefined ? { uiStreamMode } : {}),
45
+ });
46
+ }
47
+ if (definition.exposeResources !== false) {
48
+ for (const resource of resources) {
49
+ const baseName = `read_${resourceNameToToolName(resource.name)}`;
50
+ if (!isToolAllowed(baseName, serverName, effectivePrefix, definition.includeTools, definition.excludeTools)) {
51
+ continue;
52
+ }
53
+ const name = formatToolName(baseName, serverName, effectivePrefix);
54
+ if (seenNames.has(name)) {
55
+ continue;
56
+ }
57
+ seenNames.add(name);
58
+ metadata.push({
59
+ name,
60
+ originalName: baseName,
61
+ description: resource.description ?? `Read resource: ${resource.uri}`,
62
+ resourceUri: resource.uri,
63
+ });
64
+ }
65
+ }
66
+ return { metadata, failedTools };
67
+ }
68
+ export function totalToolCount(state) {
69
+ let count = 0;
70
+ for (const metadata of state.toolMetadata.values()) {
71
+ count += metadata.length;
72
+ }
73
+ return count;
74
+ }
75
+ export function findToolByName(metadata, toolName) {
76
+ if (!metadata)
77
+ return undefined;
78
+ const exact = metadata.find(m => m.name === toolName);
79
+ if (exact)
80
+ return exact;
81
+ const normalized = toolName.replace(/-/g, "_");
82
+ return metadata.find(m => m.name.replace(/-/g, "_") === normalized);
83
+ }
84
+ export function formatSchema(schema, indent = " ") {
85
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
86
+ return `${indent}(no schema)`;
87
+ }
88
+ const s = schema;
89
+ if (s.type === "object" && s.properties && typeof s.properties === "object" && !Array.isArray(s.properties)) {
90
+ const props = s.properties;
91
+ const required = Array.isArray(s.required) ? s.required.filter((name) => typeof name === "string") : [];
92
+ if (Object.keys(props).length === 0) {
93
+ return `${indent}(no parameters)`;
94
+ }
95
+ const lines = [];
96
+ for (const [name, propSchema] of Object.entries(props)) {
97
+ lines.push(...formatProperty(name, propSchema, required.includes(name), indent));
98
+ }
99
+ return lines.join("\n");
100
+ }
101
+ const lines = formatNestedSchema(s, indent);
102
+ if (lines.length > 0) {
103
+ return lines.join("\n");
104
+ }
105
+ const typeStr = formatType(s);
106
+ if (typeStr) {
107
+ return `${indent}(${typeStr})`;
108
+ }
109
+ return `${indent}(complex schema)`;
110
+ }
111
+ function formatProperty(name, schema, required, indent) {
112
+ if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
113
+ return [`${indent}${name}${required ? " *required*" : ""}`];
114
+ }
115
+ const s = schema;
116
+ const parts = [`${indent}${name}`];
117
+ const typeStr = formatType(s);
118
+ if (typeStr)
119
+ parts.push(`(${typeStr})`);
120
+ if (required)
121
+ parts.push("*required*");
122
+ appendSchemaAnnotations(parts, s);
123
+ return [parts.join(" "), ...formatNestedSchema(s, `${indent} `)];
124
+ }
125
+ function formatNestedSchema(schema, indent) {
126
+ const lines = [];
127
+ if (Array.isArray(schema.anyOf)) {
128
+ lines.push(...formatVariants("anyOf", schema.anyOf, indent));
129
+ }
130
+ if (Array.isArray(schema.oneOf)) {
131
+ lines.push(...formatVariants("oneOf", schema.oneOf, indent));
132
+ }
133
+ if (schema.items !== undefined) {
134
+ lines.push(...formatProperty("items", schema.items, false, indent));
135
+ }
136
+ if (schema.properties && typeof schema.properties === "object" && !Array.isArray(schema.properties)) {
137
+ const required = Array.isArray(schema.required) ? schema.required.filter((name) => typeof name === "string") : [];
138
+ for (const [name, propSchema] of Object.entries(schema.properties)) {
139
+ lines.push(...formatProperty(name, propSchema, required.includes(name), indent));
140
+ }
141
+ }
142
+ return lines;
143
+ }
144
+ function formatVariants(keyword, variants, indent) {
145
+ const lines = [`${indent}${keyword}:`];
146
+ for (const variant of variants) {
147
+ if (!variant || typeof variant !== "object" || Array.isArray(variant)) {
148
+ lines.push(`${indent} - ${JSON.stringify(variant)}`);
149
+ continue;
150
+ }
151
+ const s = variant;
152
+ const typeStr = formatType(s) || "schema";
153
+ const parts = [`${indent} - ${typeStr}`];
154
+ appendSchemaAnnotations(parts, s);
155
+ lines.push(parts.join(" "));
156
+ lines.push(...formatNestedSchema(s, `${indent} `));
157
+ }
158
+ return lines;
159
+ }
160
+ function formatType(schema) {
161
+ if (Object.hasOwn(schema, "const")) {
162
+ return `const ${JSON.stringify(schema.const)}`;
163
+ }
164
+ if (Array.isArray(schema.enum)) {
165
+ return `enum: ${schema.enum.map(v => JSON.stringify(v)).join(", ")}`;
166
+ }
167
+ if (Array.isArray(schema.type)) {
168
+ return schema.type.map(type => String(type)).join(" | ");
169
+ }
170
+ if (schema.type) {
171
+ return String(schema.type);
172
+ }
173
+ if (schema.properties && typeof schema.properties === "object" && !Array.isArray(schema.properties)) {
174
+ return "object";
175
+ }
176
+ if (schema.items !== undefined) {
177
+ return "array";
178
+ }
179
+ return "";
180
+ }
181
+ function appendSchemaAnnotations(parts, schema) {
182
+ if (schema.description && typeof schema.description === "string") {
183
+ parts.push(`- ${schema.description}`);
184
+ }
185
+ for (const key of ["minLength", "maxLength", "minimum", "maximum", "minItems", "maxItems", "format", "pattern"]) {
186
+ if (schema[key] !== undefined) {
187
+ parts.push(`[${key}: ${JSON.stringify(schema[key])}]`);
188
+ }
189
+ }
190
+ if (schema.default !== undefined) {
191
+ parts.push(`[default: ${JSON.stringify(schema.default)}]`);
192
+ }
193
+ }
@@ -0,0 +1,10 @@
1
+ import type { McpContent, ContentBlock } from "./types.ts";
2
+ /**
3
+ * Transform MCP content types to Pi content blocks.
4
+ */
5
+ export declare function transformMcpContent(content: McpContent[]): ContentBlock[];
6
+ /**
7
+ * Resolve a tool result's content blocks, falling back to structuredContent
8
+ * when content is empty.
9
+ */
10
+ export declare function resolveMcpResultContent(result: Record<string, unknown>): ContentBlock[];