@fitchmultz/pi-mcp-adapter 5.0.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/OAUTH.md +3 -3
  3. package/README.md +160 -88
  4. package/dist/app-bridge.bundle.js +75 -33
  5. package/dist/commands.js +9 -6
  6. package/dist/config.js +41 -16
  7. package/dist/direct-tools.d.ts +2 -4
  8. package/dist/direct-tools.js +21 -319
  9. package/dist/gateway-arguments.d.ts +33 -0
  10. package/dist/gateway-arguments.js +63 -0
  11. package/dist/index.js +181 -276
  12. package/dist/init.js +6 -20
  13. package/dist/lifecycle.d.ts +2 -2
  14. package/dist/lifecycle.js +2 -2
  15. package/dist/mcp-auth-flow.js +2 -2
  16. package/dist/mcp-auth.d.ts +1 -1
  17. package/dist/mcp-auth.js +3 -3
  18. package/dist/mcp-code.d.ts +7 -6
  19. package/dist/mcp-code.js +98 -51
  20. package/dist/mcp-oauth-provider.d.ts +5 -5
  21. package/dist/mcp-oauth-provider.js +5 -5
  22. package/dist/mcp-output-guard.d.ts +57 -2
  23. package/dist/mcp-output-guard.js +129 -24
  24. package/dist/mcp-panel.d.ts +3 -3
  25. package/dist/mcp-panel.js +36 -99
  26. package/dist/mcp-script-worker.mjs +5 -2
  27. package/dist/mcp-setup-panel.d.ts +5 -4
  28. package/dist/mcp-setup-panel.js +15 -7
  29. package/dist/mcp-status.js +2 -1
  30. package/dist/mcp-trace.d.ts +1 -1
  31. package/dist/mcp-trace.js +1 -1
  32. package/dist/metadata-cache.d.ts +1 -1
  33. package/dist/metadata-cache.js +25 -88
  34. package/dist/npx-resolver.js +8 -4
  35. package/dist/prompts.d.ts +1 -1
  36. package/dist/prompts.js +1 -1
  37. package/dist/proxy-modes.d.ts +41 -7
  38. package/dist/proxy-modes.js +275 -490
  39. package/dist/resource-tools.d.ts +15 -0
  40. package/dist/resource-tools.js +26 -1
  41. package/dist/sampling-handler.js +5 -1
  42. package/dist/search-ranking.d.ts +0 -2
  43. package/dist/search-ranking.js +70 -137
  44. package/dist/server-manager.d.ts +2 -2
  45. package/dist/server-manager.js +44 -27
  46. package/dist/session-recovery.d.ts +7 -4
  47. package/dist/session-recovery.js +76 -10
  48. package/dist/state.d.ts +1 -1
  49. package/dist/tool-loader.d.ts +32 -0
  50. package/dist/tool-loader.js +152 -0
  51. package/dist/tool-metadata.d.ts +67 -0
  52. package/dist/tool-metadata.js +23 -17
  53. package/dist/tool-registrar.d.ts +4 -4
  54. package/dist/tool-registrar.js +18 -13
  55. package/dist/tool-result-renderer.d.ts +6 -3
  56. package/dist/tool-result-renderer.js +11 -6
  57. package/dist/types.d.ts +11 -36
  58. package/dist/ui-resource-handler.d.ts +2 -2
  59. package/dist/ui-resource-handler.js +2 -2
  60. package/dist/ui-server.js +4 -3
  61. package/dist/ui-stream-types.d.ts +8 -8
  62. package/dist/unix-socket-transport.d.ts +1 -1
  63. package/dist/unix-socket-transport.js +1 -1
  64. package/dist/utils.d.ts +1 -0
  65. package/dist/utils.js +16 -4
  66. package/package.json +37 -96
  67. package/skills/mcp-scripting/SKILL.md +67 -20
  68. package/abort.ts +0 -34
  69. package/agent-dir.ts +0 -24
  70. package/app-bridge.bundle.js +0 -67
  71. package/banner.png +0 -0
  72. package/checkpoint.ts +0 -55
  73. package/commands.ts +0 -619
  74. package/config.ts +0 -1204
  75. package/consent-manager.ts +0 -25
  76. package/direct-tools.ts +0 -408
  77. package/dist/ts-shape.d.ts +0 -2
  78. package/dist/ts-shape.js +0 -147
  79. package/elicitation-handler.ts +0 -349
  80. package/error-signal.ts +0 -21
  81. package/glimpse-ui.ts +0 -80
  82. package/host-html-template.ts +0 -456
  83. package/index.ts +0 -900
  84. package/init.ts +0 -627
  85. package/legacy-migration.ts +0 -47
  86. package/lifecycle.ts +0 -165
  87. package/logger.ts +0 -127
  88. package/mcp-auth-flow.ts +0 -975
  89. package/mcp-auth.ts +0 -793
  90. package/mcp-callback-server.ts +0 -450
  91. package/mcp-code.ts +0 -386
  92. package/mcp-keyring-helper.cjs +0 -89
  93. package/mcp-oauth-provider.ts +0 -774
  94. package/mcp-output-guard.ts +0 -412
  95. package/mcp-panel.ts +0 -978
  96. package/mcp-script-worker.mjs +0 -128
  97. package/mcp-setup-panel.ts +0 -666
  98. package/mcp-status.ts +0 -109
  99. package/mcp-trace.ts +0 -295
  100. package/metadata-cache.ts +0 -333
  101. package/npx-resolver.ts +0 -488
  102. package/onboarding-state.ts +0 -58
  103. package/panel-keys.ts +0 -37
  104. package/prompts.ts +0 -337
  105. package/proxy-modes.ts +0 -1361
  106. package/resource-tools.ts +0 -17
  107. package/runtime-owner.ts +0 -123
  108. package/sampling-handler.ts +0 -273
  109. package/scripts/build.mjs +0 -131
  110. package/scripts/prepare.mjs +0 -102
  111. package/search-ranking.ts +0 -196
  112. package/server-manager.ts +0 -1320
  113. package/session-recovery.ts +0 -316
  114. package/state.ts +0 -64
  115. package/tool-approval.ts +0 -78
  116. package/tool-metadata.ts +0 -235
  117. package/tool-registrar.ts +0 -69
  118. package/tool-result-renderer.ts +0 -286
  119. package/ts-shape.ts +0 -145
  120. package/tsconfig.build.json +0 -13
  121. package/tsconfig.json +0 -16
  122. package/types.ts +0 -810
  123. package/ui-resource-handler.ts +0 -249
  124. package/ui-server.ts +0 -808
  125. package/ui-session.ts +0 -568
  126. package/ui-stream-types.ts +0 -89
  127. package/ui-tool-visibility.ts +0 -25
  128. package/unix-socket-transport.ts +0 -85
  129. package/utils.ts +0 -309
@@ -1,316 +0,0 @@
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
- }
package/state.ts DELETED
@@ -1,64 +0,0 @@
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
- }
package/tool-approval.ts DELETED
@@ -1,78 +0,0 @@
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
- }
package/tool-metadata.ts DELETED
@@ -1,235 +0,0 @@
1
- import { getToolUiResourceUri } from "@modelcontextprotocol/ext-apps/app-bridge";
2
- import type { McpExtensionState } from "./state.ts";
3
- import type { ToolMetadata, McpTool, McpResource, ServerEntry, ToolPrefix } from "./types.ts";
4
- import { formatToolName, isToolAllowed, resolveToolPrefix } from "./types.ts";
5
- import { resourceNameToToolName } from "./resource-tools.ts";
6
- import { extractToolUiStreamMode } from "./utils.ts";
7
- import { extractUiToolVisibility, isUiToolVisibleToModel } from "./ui-tool-visibility.ts";
8
-
9
- export function buildToolMetadata(
10
- tools: McpTool[],
11
- resources: McpResource[],
12
- definition: ServerEntry,
13
- serverName: string,
14
- prefix: ToolPrefix
15
- ): { metadata: ToolMetadata[]; failedTools: string[] } {
16
- const metadata: ToolMetadata[] = [];
17
- const failedTools: string[] = [];
18
- const seenNames = new Set<string>();
19
- const effectivePrefix = resolveToolPrefix(definition, prefix);
20
-
21
- for (const tool of tools) {
22
- if (!tool?.name) {
23
- failedTools.push("(unnamed)");
24
- continue;
25
- }
26
- if (!isToolAllowed(tool.name, serverName, effectivePrefix, definition.includeTools, definition.excludeTools)) {
27
- continue;
28
- }
29
-
30
- const name = formatToolName(tool.name, serverName, effectivePrefix);
31
- if (seenNames.has(name)) {
32
- continue;
33
- }
34
-
35
- const uiVisibility = extractUiToolVisibility(tool._meta);
36
- if (!isUiToolVisibleToModel(uiVisibility)) {
37
- continue;
38
- }
39
- seenNames.add(name);
40
-
41
- let uiResourceUri: string | undefined;
42
- try {
43
- uiResourceUri = getToolUiResourceUri({ _meta: tool._meta });
44
- } catch {
45
- failedTools.push(tool.name);
46
- }
47
- const uiStreamMode = extractToolUiStreamMode(tool._meta);
48
- metadata.push({
49
- name,
50
- originalName: tool.name,
51
- description: tool.description ?? "",
52
- ...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
53
- ...(tool.annotations !== undefined ? { annotations: tool.annotations } : {}),
54
- ...(uiResourceUri !== undefined ? { uiResourceUri } : {}),
55
- ...(uiVisibility !== undefined ? { uiVisibility } : {}),
56
- ...(uiStreamMode !== undefined ? { uiStreamMode } : {}),
57
- });
58
- }
59
-
60
- if (definition.exposeResources !== false) {
61
- for (const resource of resources) {
62
- const baseName = `read_${resourceNameToToolName(resource.name)}`;
63
- if (!isToolAllowed(baseName, serverName, effectivePrefix, definition.includeTools, definition.excludeTools)) {
64
- continue;
65
- }
66
-
67
- const name = formatToolName(baseName, serverName, effectivePrefix);
68
- if (seenNames.has(name)) {
69
- continue;
70
- }
71
- seenNames.add(name);
72
-
73
- metadata.push({
74
- name,
75
- originalName: baseName,
76
- description: resource.description ?? `Read resource: ${resource.uri}`,
77
- resourceUri: resource.uri,
78
- });
79
- }
80
- }
81
-
82
- return { metadata, failedTools };
83
- }
84
-
85
- export function totalToolCount(state: McpExtensionState): number {
86
- let count = 0;
87
- for (const metadata of state.toolMetadata.values()) {
88
- count += metadata.length;
89
- }
90
- return count;
91
- }
92
-
93
- export function findToolByName(metadata: ToolMetadata[] | undefined, toolName: string): ToolMetadata | undefined {
94
- if (!metadata) return undefined;
95
- const exact = metadata.find(m => m.name === toolName);
96
- if (exact) return exact;
97
- const normalized = toolName.replace(/-/g, "_");
98
- return metadata.find(m => m.name.replace(/-/g, "_") === normalized);
99
- }
100
-
101
- export function formatSchema(schema: unknown, indent = " "): string {
102
- if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
103
- return `${indent}(no schema)`;
104
- }
105
-
106
- const s = schema as Record<string, unknown>;
107
-
108
- if (s.type === "object" && s.properties && typeof s.properties === "object" && !Array.isArray(s.properties)) {
109
- const props = s.properties as Record<string, unknown>;
110
- const required = Array.isArray(s.required) ? s.required.filter((name): name is string => typeof name === "string") : [];
111
-
112
- if (Object.keys(props).length === 0) {
113
- return `${indent}(no parameters)`;
114
- }
115
-
116
- const lines: string[] = [];
117
- for (const [name, propSchema] of Object.entries(props)) {
118
- lines.push(...formatProperty(name, propSchema, required.includes(name), indent));
119
- }
120
- return lines.join("\n");
121
- }
122
-
123
- const lines = formatNestedSchema(s, indent);
124
- if (lines.length > 0) {
125
- return lines.join("\n");
126
- }
127
-
128
- const typeStr = formatType(s);
129
- if (typeStr) {
130
- return `${indent}(${typeStr})`;
131
- }
132
-
133
- return `${indent}(complex schema)`;
134
- }
135
-
136
- function formatProperty(name: string, schema: unknown, required: boolean, indent: string): string[] {
137
- if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
138
- return [`${indent}${name}${required ? " *required*" : ""}`];
139
- }
140
-
141
- const s = schema as Record<string, unknown>;
142
- const parts = [`${indent}${name}`];
143
- const typeStr = formatType(s);
144
- if (typeStr) parts.push(`(${typeStr})`);
145
- if (required) parts.push("*required*");
146
- appendSchemaAnnotations(parts, s);
147
-
148
- return [parts.join(" "), ...formatNestedSchema(s, `${indent} `)];
149
- }
150
-
151
- function formatNestedSchema(schema: Record<string, unknown>, indent: string): string[] {
152
- const lines: string[] = [];
153
-
154
- if (Array.isArray(schema.anyOf)) {
155
- lines.push(...formatVariants("anyOf", schema.anyOf, indent));
156
- }
157
- if (Array.isArray(schema.oneOf)) {
158
- lines.push(...formatVariants("oneOf", schema.oneOf, indent));
159
- }
160
- if (schema.items !== undefined) {
161
- lines.push(...formatProperty("items", schema.items, false, indent));
162
- }
163
- if (schema.properties && typeof schema.properties === "object" && !Array.isArray(schema.properties)) {
164
- const required = Array.isArray(schema.required) ? schema.required.filter((name): name is string => typeof name === "string") : [];
165
- for (const [name, propSchema] of Object.entries(schema.properties as Record<string, unknown>)) {
166
- lines.push(...formatProperty(name, propSchema, required.includes(name), indent));
167
- }
168
- }
169
-
170
- return lines;
171
- }
172
-
173
- function formatVariants(keyword: "anyOf" | "oneOf", variants: unknown[], indent: string): string[] {
174
- const lines = [`${indent}${keyword}:`];
175
-
176
- for (const variant of variants) {
177
- if (!variant || typeof variant !== "object" || Array.isArray(variant)) {
178
- lines.push(`${indent} - ${JSON.stringify(variant)}`);
179
- continue;
180
- }
181
-
182
- const s = variant as Record<string, unknown>;
183
- const typeStr = formatType(s) || "schema";
184
- const parts = [`${indent} - ${typeStr}`];
185
- appendSchemaAnnotations(parts, s);
186
- lines.push(parts.join(" "));
187
- lines.push(...formatNestedSchema(s, `${indent} `));
188
- }
189
-
190
- return lines;
191
- }
192
-
193
- function formatType(schema: Record<string, unknown>): string {
194
- if (Object.hasOwn(schema, "const")) {
195
- return `const ${JSON.stringify(schema.const)}`;
196
- }
197
-
198
- if (Array.isArray(schema.enum)) {
199
- return `enum: ${schema.enum.map(v => JSON.stringify(v)).join(", ")}`;
200
- }
201
-
202
- if (Array.isArray(schema.type)) {
203
- return schema.type.map(type => String(type)).join(" | ");
204
- }
205
-
206
- if (schema.type) {
207
- return String(schema.type);
208
- }
209
-
210
- if (schema.properties && typeof schema.properties === "object" && !Array.isArray(schema.properties)) {
211
- return "object";
212
- }
213
-
214
- if (schema.items !== undefined) {
215
- return "array";
216
- }
217
-
218
- return "";
219
- }
220
-
221
- function appendSchemaAnnotations(parts: string[], schema: Record<string, unknown>): void {
222
- if (schema.description && typeof schema.description === "string") {
223
- parts.push(`- ${schema.description}`);
224
- }
225
-
226
- for (const key of ["minLength", "maxLength", "minimum", "maximum", "minItems", "maxItems", "format", "pattern"] as const) {
227
- if (schema[key] !== undefined) {
228
- parts.push(`[${key}: ${JSON.stringify(schema[key])}]`);
229
- }
230
- }
231
-
232
- if (schema.default !== undefined) {
233
- parts.push(`[default: ${JSON.stringify(schema.default)}]`);
234
- }
235
- }