@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.
- package/CHANGELOG.md +750 -0
- package/LICENSE +21 -0
- package/OAUTH.md +462 -0
- package/README.md +820 -0
- package/abort.ts +34 -0
- package/agent-dir.ts +24 -0
- package/app-bridge.bundle.js +67 -0
- package/banner.png +0 -0
- package/checkpoint.ts +55 -0
- package/cli.js +222 -0
- package/commands.ts +619 -0
- package/config.ts +1204 -0
- package/consent-manager.ts +25 -0
- package/direct-tools.ts +408 -0
- package/dist/abort.d.ts +2 -0
- package/dist/abort.js +35 -0
- package/dist/agent-dir.d.ts +3 -0
- package/dist/agent-dir.js +21 -0
- package/dist/app-bridge.bundle.js +67 -0
- package/dist/checkpoint.d.ts +18 -0
- package/dist/checkpoint.js +53 -0
- package/dist/commands.d.ts +20 -0
- package/dist/commands.js +521 -0
- package/dist/config.d.ts +109 -0
- package/dist/config.js +1013 -0
- package/dist/consent-manager.d.ts +8 -0
- package/dist/consent-manager.js +21 -0
- package/dist/direct-tools.d.ts +10 -0
- package/dist/direct-tools.js +350 -0
- package/dist/docs/client-metadata.json +14 -0
- package/dist/elicitation-handler.d.ts +17 -0
- package/dist/elicitation-handler.js +308 -0
- package/dist/error-signal.d.ts +15 -0
- package/dist/error-signal.js +21 -0
- package/dist/glimpse-ui.d.ts +9 -0
- package/dist/glimpse-ui.js +75 -0
- package/dist/host-html-template.d.ts +15 -0
- package/dist/host-html-template.js +429 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +840 -0
- package/dist/init.d.ts +25 -0
- package/dist/init.js +562 -0
- package/dist/legacy-migration.d.ts +18 -0
- package/dist/legacy-migration.js +45 -0
- package/dist/lifecycle.d.ts +40 -0
- package/dist/lifecycle.js +167 -0
- package/dist/logger.d.ts +38 -0
- package/dist/logger.js +102 -0
- package/dist/mcp-auth-flow.d.ts +113 -0
- package/dist/mcp-auth-flow.js +834 -0
- package/dist/mcp-auth.d.ts +127 -0
- package/dist/mcp-auth.js +658 -0
- package/dist/mcp-callback-server.d.ts +56 -0
- package/dist/mcp-callback-server.js +371 -0
- package/dist/mcp-code.d.ts +51 -0
- package/dist/mcp-code.js +366 -0
- package/dist/mcp-keyring-helper.cjs +89 -0
- package/dist/mcp-oauth-provider.d.ts +154 -0
- package/dist/mcp-oauth-provider.js +672 -0
- package/dist/mcp-output-guard.d.ts +59 -0
- package/dist/mcp-output-guard.js +332 -0
- package/dist/mcp-panel.d.ts +66 -0
- package/dist/mcp-panel.js +889 -0
- package/dist/mcp-script-worker.mjs +128 -0
- package/dist/mcp-setup-panel.d.ts +84 -0
- package/dist/mcp-setup-panel.js +561 -0
- package/dist/mcp-status.d.ts +11 -0
- package/dist/mcp-status.js +96 -0
- package/dist/mcp-trace.d.ts +95 -0
- package/dist/mcp-trace.js +233 -0
- package/dist/metadata-cache.d.ts +18 -0
- package/dist/metadata-cache.js +277 -0
- package/dist/npx-resolver.d.ts +6 -0
- package/dist/npx-resolver.js +448 -0
- package/dist/onboarding-state.d.ts +11 -0
- package/dist/onboarding-state.js +47 -0
- package/dist/panel-keys.d.ts +16 -0
- package/dist/panel-keys.js +15 -0
- package/dist/prompts.d.ts +56 -0
- package/dist/prompts.js +284 -0
- package/dist/proxy-modes.d.ts +38 -0
- package/dist/proxy-modes.js +1235 -0
- package/dist/resource-tools.d.ts +1 -0
- package/dist/resource-tools.js +14 -0
- package/dist/runtime-owner.d.ts +18 -0
- package/dist/runtime-owner.js +117 -0
- package/dist/sampling-handler.d.ts +15 -0
- package/dist/sampling-handler.js +211 -0
- package/dist/search-ranking.d.ts +20 -0
- package/dist/search-ranking.js +180 -0
- package/dist/server-manager.d.ts +114 -0
- package/dist/server-manager.js +1175 -0
- package/dist/session-recovery.d.ts +31 -0
- package/dist/session-recovery.js +310 -0
- package/dist/state.d.ts +63 -0
- package/dist/state.js +1 -0
- package/dist/tool-approval.d.ts +10 -0
- package/dist/tool-approval.js +42 -0
- package/dist/tool-metadata.d.ts +9 -0
- package/dist/tool-metadata.js +193 -0
- package/dist/tool-registrar.d.ts +10 -0
- package/dist/tool-registrar.js +64 -0
- package/dist/tool-result-renderer.d.ts +45 -0
- package/dist/tool-result-renderer.js +224 -0
- package/dist/ts-shape.d.ts +2 -0
- package/dist/ts-shape.js +147 -0
- package/dist/types.d.ts +516 -0
- package/dist/types.js +168 -0
- package/dist/ui-resource-handler.d.ts +17 -0
- package/dist/ui-resource-handler.js +209 -0
- package/dist/ui-server.d.ts +51 -0
- package/dist/ui-server.js +669 -0
- package/dist/ui-session.d.ts +39 -0
- package/dist/ui-session.js +463 -0
- package/dist/ui-stream-types.d.ts +104 -0
- package/dist/ui-stream-types.js +58 -0
- package/dist/ui-tool-visibility.d.ts +4 -0
- package/dist/ui-tool-visibility.js +26 -0
- package/dist/unix-socket-transport.d.ts +15 -0
- package/dist/unix-socket-transport.js +84 -0
- package/dist/utils.d.ts +30 -0
- package/dist/utils.js +276 -0
- package/docs/client-metadata.json +14 -0
- package/elicitation-handler.ts +349 -0
- package/error-signal.ts +21 -0
- package/glimpse-ui.ts +80 -0
- package/host-html-template.ts +456 -0
- package/index.ts +900 -0
- package/init.ts +627 -0
- package/legacy-migration.ts +47 -0
- package/lifecycle.ts +165 -0
- package/logger.ts +127 -0
- package/mcp-auth-flow.ts +975 -0
- package/mcp-auth.ts +793 -0
- package/mcp-callback-server.ts +450 -0
- package/mcp-code.ts +386 -0
- package/mcp-keyring-helper.cjs +89 -0
- package/mcp-oauth-provider.ts +774 -0
- package/mcp-output-guard.ts +412 -0
- package/mcp-panel.ts +978 -0
- package/mcp-script-worker.mjs +128 -0
- package/mcp-setup-panel.ts +666 -0
- package/mcp-status.ts +109 -0
- package/mcp-trace.ts +295 -0
- package/metadata-cache.ts +333 -0
- package/npx-resolver.ts +488 -0
- package/onboarding-state.ts +58 -0
- package/package.json +182 -0
- package/panel-keys.ts +37 -0
- package/prompts.ts +337 -0
- package/proxy-modes.ts +1361 -0
- package/resource-tools.ts +17 -0
- package/runtime-owner.ts +123 -0
- package/sampling-handler.ts +273 -0
- package/scripts/build.mjs +131 -0
- package/scripts/prepare.mjs +102 -0
- package/search-ranking.ts +196 -0
- package/server-manager.ts +1320 -0
- package/session-recovery.ts +316 -0
- package/skills/mcp-scripting/SKILL.md +38 -0
- package/state.ts +64 -0
- package/tool-approval.ts +78 -0
- package/tool-metadata.ts +235 -0
- package/tool-registrar.ts +69 -0
- package/tool-result-renderer.ts +286 -0
- package/ts-shape.ts +145 -0
- package/tsconfig.build.json +13 -0
- package/tsconfig.json +16 -0
- package/types.ts +810 -0
- package/ui-resource-handler.ts +249 -0
- package/ui-server.ts +808 -0
- package/ui-session.ts +568 -0
- package/ui-stream-types.ts +89 -0
- package/ui-tool-visibility.ts +25 -0
- package/unix-socket-transport.ts +85 -0
- 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
|
+
}
|
package/tool-approval.ts
ADDED
|
@@ -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
|
+
}
|