pi-mcp-extension 1.14.6 → 1.15.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/README.md +6 -4
- package/package.json +1 -1
- package/src/connect-policy.ts +28 -0
- package/src/debug-log-format.ts +41 -0
- package/src/server-manager.ts +13 -6
- package/src/tool-bridge.ts +88 -11
package/README.md
CHANGED
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
- **Multi-transport** — `stdio` subprocesses, `streamable-http` (including `"http"` and URL-only shorthand), and legacy `sse` out of the box
|
|
21
21
|
- **Auto-discovery** — Paginated `tools/list` with cursor following (MCP 2025-03-26 spec)
|
|
22
22
|
- **Live tool refresh** — `notifications/tools/list_changed` triggers re-discovery without restart
|
|
23
|
+
- **Live tool progress** — a server's `notifications/progress` events stream into Pi as live tool-call updates (server text is sanitized and secret-redacted, repeated lines are collapsed), and every notification restarts the per-request timeout, so a long-running tool that keeps reporting — a browser flow, migration, or test runner — is no longer killed at `requestTimeoutMs` while it is demonstrably working
|
|
23
24
|
- **Clean cancellation** — `AbortSignal` propagation via `notifications/cancelled`
|
|
24
25
|
- **Smart reconnection** — Fixed delay retry schedule (1s → 3s → 5s → 10s → 30s), configurable max retries, automatic recovery when a server transport closes or errors unexpectedly, and mid-session HTTP `401` / `403 insufficient_scope` detection that invalidates stale tokens and prompts for re-authorization
|
|
25
26
|
- **Health checks** — Opt-in periodic pings to detect stale connections
|
|
@@ -167,7 +168,7 @@ In project-level `.pi/mcp.json`, `settings` keys carry no defaults — only the
|
|
|
167
168
|
| Field | Type | Default | Description |
|
|
168
169
|
|---|---|---|---|
|
|
169
170
|
| `toolPrefix` | `string` | `"mcp"` | Prefix for registered tools: `<prefix>_<server>_<tool>`. Must match `^[a-zA-Z][a-zA-Z0-9_]*$`. |
|
|
170
|
-
| `requestTimeoutMs` | `number` | `30000` | Default per-request timeout in milliseconds |
|
|
171
|
+
| `requestTimeoutMs` | `number` | `30000` | Default per-request timeout in milliseconds. For `tools/call` this is an inactivity deadline: every `notifications/progress` event from the server restarts it, so page-by-page work is not cut off mid-flight. A server that reports progress indefinitely has no wall-clock cap — cancel the tool to stop it |
|
|
171
172
|
| `maxRetries` | `number` | `5` | Max reconnection attempts (0–10) before giving up |
|
|
172
173
|
|
|
173
174
|
### Per-Server Config
|
|
@@ -334,7 +335,7 @@ The log is written to `<agent dir>/logs/pi-mcp.log` (JSON Lines, one event per l
|
|
|
334
335
|
- API keys and other JSON or key/value secrets (`api_key`, `x-api-key`, `private_key`, `password`, `secret`, `token`, and prefixed forms such as `db_password` or `aws_secret_access_key`)
|
|
335
336
|
- Credential-bearing query parameters on a server URL (`?api_key=…`, `?token=…`, `?code=…`)
|
|
336
337
|
- `Authorization` headers in any scheme or quoting, and URL userinfo passwords (`https://user:password@host`)
|
|
337
|
-
- The same redactor protects the per-server `Recent output:` (`stderr`) buffer, the `Last error:` line in `/mcp` and `/mcp <name>`, and user-facing start/auth/recovery failure notifications.
|
|
338
|
+
- The same redactor protects the per-server `Recent output:` (`stderr`) buffer, handshake `instructions`, `notifications/progress` tool updates, the `Last error:` line in `/mcp` and `/mcp <name>`, and user-facing start/auth/recovery failure notifications.
|
|
338
339
|
- **Best-effort.** A failed log write never breaks a connection or a tool call.
|
|
339
340
|
|
|
340
341
|
Attach the file to a bug report. It contains no credentials.
|
|
@@ -378,7 +379,7 @@ flowchart TD
|
|
|
378
379
|
4. **JSON Schema → TypeBox** conversion registers tools with Pi-compatible parameter schemas (preserving nullable union ordering, resolving `$ref`s cycle-safely, and inferring/flattening `allOf` object schemas)
|
|
379
380
|
5. **Pi tools are registered** as `<prefix>_<server>_<tool>` (sanitized `[a-zA-Z0-9_]`, max 64 chars with an 8-char SHA-256 suffix on truncation or collision) and convert MCP `text`, `image` (`ImageContent`), `structuredContent`, `resource`, `resource_link`, and `audio` results. When one server exposes two tools that sanitize to the same identifier, the name that needed no substitution keeps the unhashed form (`my_tool` over `my-tool`), remaining ties break by the raw name's code-point order, and the assignment does not depend on `tools/list` order — so a reconnect cannot swap which MCP tool a Pi name executes. Embedded image resources become image blocks, binary resources include MIME type and byte count, and resource links include a `mcp_read_resource` hint.
|
|
380
381
|
6. **Tools activate/deactivate** automatically as servers connect/disconnect, always in one deterministic order — the bridge's tools are sorted by Pi name among the slots they occupy, and other extensions' tools keep their positions — so connect timing and `tools/list` order cannot change the prompt head
|
|
381
|
-
7. **AbortSignal**
|
|
382
|
+
7. **AbortSignal and progress** are wired through to `notifications/cancelled` for clean cancellation and `notifications/progress` for live sanitized tool updates plus inactivity-timeout resets
|
|
382
383
|
8. **Reconnection & recovery** uses a fixed delay schedule with configurable max retries on initial failure, health check failure, or unexpected transport close/error (`client.onclose` / `client.onerror`), while mid-session HTTP `401` / `403 insufficient_scope` invalidates stale tokens and surfaces a re-authorization hint
|
|
383
384
|
9. **`list_changed` notifications** trigger re-discovery, deactivating stale tools automatically and invalidating the cached resource catalog
|
|
384
385
|
10. **Session shutdown** cancels pending auth/connection flows, stops the callback server, deactivates all tools, flushes the debug log, and cleanly stops all servers (with process-tree `SIGTERM` → `SIGKILL` — a PID the kernel refuses to signal is left alone instead of being polled — and pipe cleanup for `stdio` child processes)
|
|
@@ -402,6 +403,7 @@ Implements the **MCP 2025-03-26** specification for tool and resource clients:
|
|
|
402
403
|
| `roots/list` capability (workspace root) | ✅ |
|
|
403
404
|
| `notifications/tools/list_changed` (live refresh) | ✅ |
|
|
404
405
|
| `notifications/cancelled` (AbortSignal) | ✅ |
|
|
406
|
+
| `notifications/progress` (live sanitized tool updates + inactivity timeout reset) | ✅ |
|
|
405
407
|
| `notifications/message` (structured logging) | ✅ |
|
|
406
408
|
| `isError: true` distinction (protocol vs tool errors, non-text filtered on error) | ✅ |
|
|
407
409
|
| Tool annotations (`readOnlyHint`, `destructiveHint`, etc.) in descriptions and as structured Pi `annotations` | ✅ |
|
|
@@ -443,7 +445,7 @@ The test suite includes:
|
|
|
443
445
|
- **Config & Pi 1.x / 1.3.0 compatibility** (`tests/config.test.ts`, `tests/pi-1x-compat.test.ts`) — Zod schema, JSONC comments, `$PI_CODING_AGENT_DIR` resolution, global/project merge, project trust boundary (`ctx.isProjectTrusted()`), Pi 1.3.0 `enabled: false` and partial project overrides, `stdio` `cwd`, `oauth.clientName`, Pi 1.x schema aliases (`type: "http"`, URL-only HTTP, `oauth`, `timeout`), and dynamic `pi.getMcpServers()` / `mcp_servers_change`
|
|
444
446
|
- **Server lifecycle & coordination** (`tests/server-manager.test.ts`, `tests/stdio-process.test.ts`, `tests/transport-factory.test.ts`, `tests/connection-coordinator.test.ts`, `tests/connection-coordination.test.ts`) — Connect, retry, unexpected close recovery, shutdown with PID `SIGKILL` safety net, health check, concurrent connect/reset coordination, and cancellation
|
|
445
447
|
- **OAuth 2.1 & auth locks** (`tests/oauth-fixes.test.ts`, `tests/authorize-flow.test.ts`, `tests/auth-lock.test.ts`, `tests/auth-commands.test.ts`, `tests/auth-arguments.test.ts`, `tests/fake-oauth-server.test.ts`) — Challenge discovery, PKCE, Dynamic Client Registration, origin and issuer binding, startup authorization prompts, headless/SSH redirect URL paste-back, URL scheme validation, cross-process lock heartbeat, and stale lock reclamation
|
|
446
|
-
- **Tool bridge, status diagnostics & debug log** (`tests/tool-bridge.test.ts`, `tests/management-tools.test.ts`, `tests/server-status.test.ts`, `tests/status-commands.test.ts`, `tests/completions.test.ts`, `tests/debug-log.test.ts`) — JSON Schema → TypeBox conversion (`allOf` object inference, `$ref` cycle protection, union `null` ordering), name sanitization, image content passthrough, `isError` filtering, activate/deactivate, `mcp_status` / `mcp_connect`, `/mcp <name>` config provenance and failure hints, slash command completions, and redacted `PI_MCP_DEBUG=1` JSONL logging
|
|
448
|
+
- **Tool bridge, status diagnostics & debug log** (`tests/tool-bridge.test.ts`, `tests/tool-progress.test.ts`, `tests/management-tools.test.ts`, `tests/server-status.test.ts`, `tests/status-commands.test.ts`, `tests/completions.test.ts`, `tests/debug-log.test.ts`) — JSON Schema → TypeBox conversion (`allOf` object inference, `$ref` cycle protection, union `null` ordering), name sanitization, image content passthrough, `isError` filtering, activate/deactivate, `notifications/progress` forwarding (sanitizing, redaction, dedupe, and the timeout reset over a real stdio server), `mcp_status` / `mcp_connect`, `/mcp <name>` config provenance and failure hints, slash command completions, and redacted `PI_MCP_DEBUG=1` JSONL logging
|
|
447
449
|
- **Resource bridge** (`tests/resource-bridge.test.ts`) — paginated `resources/list` / `resources/templates/list`, `-32601` degradation, catalog caching with `notifications/resources/list_changed` invalidation, stale in-flight discard, text/image/binary `resources/read` conversion, abort/timeout/401 mapping, `mcp_list_resources` / `mcp_read_resource`, and `/mcp:resources`
|
|
448
450
|
- **Property-based fuzzing** (`tests/fuzz.test.ts`) — `fast-check` properties covering JSONC comment stripping, callback/redirect URL validation, `WWW-Authenticate` challenge parsing, JSON Schema → TypeBox conversion, tool naming, terminal/log secret sanitization, and custom header merging
|
|
449
451
|
- **Release flow & repository policy** (`tests/release.test.ts`, `tests/ruleset-audit.test.ts`, `tests/repo-policy.test.ts`) — Release PR orchestration and npm/git self-healing (`scripts/release.ts`), live GitHub ruleset drift auditing (`scripts/ruleset-audit.ts`), and CI/ESLint/Qlty policy invariants
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-mcp-extension",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.15.0",
|
|
4
4
|
"description": "Full-featured, lightweight MCP extension for the Pi coding agent: stdio, SSE & Streamable HTTP transports, OAuth 2.1 (PKCE + DCR), lazy/eager lifecycles — minimal dependencies, zero bloat.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
package/src/connect-policy.ts
CHANGED
|
@@ -193,6 +193,34 @@ export function isCancellationError(err: unknown, signal?: AbortSignal | undefin
|
|
|
193
193
|
return err.name === "AbortError" || ((err as { code?: unknown }).code === -32001 && /abort/i.test(err.message));
|
|
194
194
|
}
|
|
195
195
|
|
|
196
|
+
/**
|
|
197
|
+
* Whether a `client.onerror` message came from `Protocol._onnotification` rejecting an
|
|
198
|
+
* incoming notification (for example `notifications/progress` carrying `total: null` once
|
|
199
|
+
* `tools/call` attaches `_meta.progressToken`, or a throwing notification callback).
|
|
200
|
+
*/
|
|
201
|
+
export function isNotificationHandlerError(rawMsg: string): boolean {
|
|
202
|
+
return /^Uncaught error in notification handler:/i.test(rawMsg);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Whether a `client.onerror` message is non-fatal protocol noise rather than a broken
|
|
207
|
+
* SSE / Streamable HTTP transport stream.
|
|
208
|
+
*
|
|
209
|
+
* Late responses or `notifications/progress` events for an already-settled or cancelled
|
|
210
|
+
* request report `unknown message ID` / `unknown token`, and malformed notifications or
|
|
211
|
+
* throwing notification callbacks report `Uncaught error in notification handler: …`.
|
|
212
|
+
* Reconnecting on any of these would close a healthy HTTP/SSE session and abort in-flight
|
|
213
|
+
* `tools/call` requests with `Connection closed`.
|
|
214
|
+
*/
|
|
215
|
+
export function isNonFatalClientError(rawMsg: string): boolean {
|
|
216
|
+
return (
|
|
217
|
+
isNotificationHandlerError(rawMsg) ||
|
|
218
|
+
/unknown message ID|Received a response for an unknown message ID|notifications\/progress|unknown token/i.test(
|
|
219
|
+
rawMsg,
|
|
220
|
+
)
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
|
|
196
224
|
export type TransportType = ServerConfig["transport"];
|
|
197
225
|
|
|
198
226
|
export type ConnectFailureAction =
|
package/src/debug-log-format.ts
CHANGED
|
@@ -239,6 +239,46 @@ function readBareValue(
|
|
|
239
239
|
return end > start ? { end, delimiter: "" } : undefined;
|
|
240
240
|
}
|
|
241
241
|
|
|
242
|
+
const REDACTED_MASKS: readonly string[] = [
|
|
243
|
+
"[REDACTED]",
|
|
244
|
+
'"[REDACTED]"',
|
|
245
|
+
"'[REDACTED]'",
|
|
246
|
+
'\\"[REDACTED]\\"',
|
|
247
|
+
"\\'[REDACTED]\\'",
|
|
248
|
+
];
|
|
249
|
+
|
|
250
|
+
const AUTH_SCHEME_NAMES: readonly string[] = [
|
|
251
|
+
"bearer",
|
|
252
|
+
"basic",
|
|
253
|
+
"digest",
|
|
254
|
+
"token",
|
|
255
|
+
"apikey",
|
|
256
|
+
"dpop",
|
|
257
|
+
"oauth",
|
|
258
|
+
"negotiate",
|
|
259
|
+
];
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* True when `text.slice(start)` is an already-redacted mask (or known `Authorization` scheme
|
|
263
|
+
* prefix) that post-redaction length capping sliced with a trailing `…` (`[REDACTED…`,
|
|
264
|
+
* `"[RED…`, `Authorization: Bea…`, `token=…`). Skipping it keeps `redactSecrets` + truncation
|
|
265
|
+
* idempotent without sparing any free secret characters.
|
|
266
|
+
*/
|
|
267
|
+
function isTruncatedRedactedTail(
|
|
268
|
+
text: string,
|
|
269
|
+
start: number,
|
|
270
|
+
terminators: Set<string>,
|
|
271
|
+
): boolean {
|
|
272
|
+
if (!text.endsWith("…")) return false;
|
|
273
|
+
const body = text.slice(start, -1);
|
|
274
|
+
if (REDACTED_MASKS.some((mask) => mask.startsWith(body))) return true;
|
|
275
|
+
const lower = body.toLowerCase();
|
|
276
|
+
return (
|
|
277
|
+
terminators === AUTHORIZATION_VALUE_TERMINATORS &&
|
|
278
|
+
AUTH_SCHEME_NAMES.some((scheme) => scheme.startsWith(lower))
|
|
279
|
+
);
|
|
280
|
+
}
|
|
281
|
+
|
|
242
282
|
/**
|
|
243
283
|
* Read the credential value that starts at `start`, honouring its opening delimiter: a quoted
|
|
244
284
|
* value runs to its matching quote, a `{`/`[` value runs to its matching bracket, and an
|
|
@@ -249,6 +289,7 @@ function readCredentialValue(
|
|
|
249
289
|
start: number,
|
|
250
290
|
terminators: Set<string> = UNQUOTED_VALUE_TERMINATORS,
|
|
251
291
|
): CredentialValue | undefined {
|
|
292
|
+
if (isTruncatedRedactedTail(text, start, terminators)) return undefined;
|
|
252
293
|
// An out-of-range start yields an empty opening and falls through to `readBareValue`, which
|
|
253
294
|
// returns `undefined` for an empty value.
|
|
254
295
|
const quote = openingQuoteAt(text, start);
|
package/src/server-manager.ts
CHANGED
|
@@ -38,6 +38,8 @@ import {
|
|
|
38
38
|
import { createTransport } from "./transport-factory.js";
|
|
39
39
|
import {
|
|
40
40
|
classifyConnectFailure,
|
|
41
|
+
isNonFatalClientError,
|
|
42
|
+
isNotificationHandlerError,
|
|
41
43
|
isOAuthUnauthorizedError,
|
|
42
44
|
isSdkTimeoutError,
|
|
43
45
|
type ConnectFailureAction,
|
|
@@ -869,14 +871,19 @@ export class ServerManager {
|
|
|
869
871
|
return;
|
|
870
872
|
}
|
|
871
873
|
const rawMsg = err instanceof Error ? err.message : String(err);
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
874
|
+
const msg = sanitizeTerminalText(rawMsg);
|
|
875
|
+
if (isNonFatalClientError(rawMsg)) {
|
|
876
|
+
if (isNotificationHandlerError(rawMsg)) {
|
|
877
|
+
reportDiagnostic({
|
|
878
|
+
level: "info",
|
|
879
|
+
event: "server.notification_error",
|
|
880
|
+
server: server.name,
|
|
881
|
+
message: msg,
|
|
882
|
+
fields: { transport: server.config.transport },
|
|
883
|
+
});
|
|
884
|
+
}
|
|
877
885
|
return;
|
|
878
886
|
}
|
|
879
|
-
const msg = sanitizeTerminalText(rawMsg);
|
|
880
887
|
if (server.config.transport === "sse") {
|
|
881
888
|
reportDiagnostic({
|
|
882
889
|
level: "warn",
|
package/src/tool-bridge.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* - Tool name sanitization (Pi-compatible identifiers)
|
|
8
8
|
* - Tool annotations → description hints + structured Pi `annotations`
|
|
9
9
|
* - AbortSignal → SDK's built-in cancellation (notifications/cancelled)
|
|
10
|
+
* - notifications/progress → sanitized, redacted live tool updates + inactivity timeout reset
|
|
10
11
|
* - Protocol error vs tool execution error distinction
|
|
11
12
|
* - Activate/deactivate pattern (register once, toggle on server state change)
|
|
12
13
|
* - Images and embedded image resources → ImageContent; resource links → read hints
|
|
@@ -14,9 +15,11 @@
|
|
|
14
15
|
|
|
15
16
|
import { createHash } from "node:crypto";
|
|
16
17
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
17
|
-
import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
18
|
+
import { CallToolResultSchema, type Progress } from "@modelcontextprotocol/sdk/types.js";
|
|
18
19
|
import type { ExtensionAPI, ToolAnnotations } from "@earendil-works/pi-coding-agent";
|
|
19
20
|
import { McpError, AuthCancelledError } from "./errors.js";
|
|
21
|
+
import { redactSecrets } from "./debug-log.js";
|
|
22
|
+
import { sanitizeTerminalText } from "./terminal-text.js";
|
|
20
23
|
import type { Settings } from "./config.js";
|
|
21
24
|
import { isCancellationError, isOAuthUnauthorizedError, isSdkTimeoutError } from "./connect-policy.js";
|
|
22
25
|
import { convertJsonSchemaToTypebox } from "./schema-convert.js";
|
|
@@ -202,6 +205,15 @@ interface ToolCallOutcome {
|
|
|
202
205
|
details: Record<string, never>;
|
|
203
206
|
}
|
|
204
207
|
|
|
208
|
+
/** Pi's partial-result callback — the `onUpdate` argument of a tool's `execute`. */
|
|
209
|
+
export type ToolUpdateCallback = (update: ToolCallOutcome) => void;
|
|
210
|
+
|
|
211
|
+
/** Per-call streaming and cancellation options for one `tools/call`. */
|
|
212
|
+
interface ToolCallOptions {
|
|
213
|
+
signal: AbortSignal | undefined;
|
|
214
|
+
onUpdate: ToolUpdateCallback | undefined;
|
|
215
|
+
}
|
|
216
|
+
|
|
205
217
|
/**
|
|
206
218
|
* The subset of an SDK `tools/call` response the bridge consumes.
|
|
207
219
|
* Legacy servers answer with `toolResult` instead of `content`, so every field
|
|
@@ -254,19 +266,81 @@ function buildToolAnnotations(
|
|
|
254
266
|
return Object.keys(result).length > 0 ? result : undefined;
|
|
255
267
|
}
|
|
256
268
|
|
|
269
|
+
/** Character budget for one progress line; Pi renders the latest line while the tool runs. */
|
|
270
|
+
const PROGRESS_MESSAGE_MAX_LENGTH = 200;
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Render one MCP `notifications/progress` payload as a single Pi-visible line.
|
|
274
|
+
*
|
|
275
|
+
* `message` is server-controlled and lands in Pi's UI stream, so it is sanitized (ANSI and
|
|
276
|
+
* control sequences stripped, length bounded) and stripped of token-like substrings first.
|
|
277
|
+
* A server that sends no usable text gets a numeric `Progress 3/10` line instead.
|
|
278
|
+
*
|
|
279
|
+
* WHY: sanitize before redacting, as `sanitizeLogText` does — the sanitizer deletes escape
|
|
280
|
+
* sequences, and an escape *inside* a credential (`\u001b[1mtoken\u001b[0m=sk-…`) hides the
|
|
281
|
+
* `key=value` shape from `redactSecrets`, which would then pass the token through verbatim.
|
|
282
|
+
*/
|
|
283
|
+
export function formatProgressText(progress: Progress): string {
|
|
284
|
+
const rawMessage = typeof progress.message === "string" ? progress.message : "";
|
|
285
|
+
// WHY: decide usability on the full text (`maxLength` = its own length disables truncation) and
|
|
286
|
+
// trim surrounding whitespace first. `sanitizeTerminalText` appends `…` when it truncates and
|
|
287
|
+
// turns trailing newlines into spaces, so untrimmed padding would either defeat the fallback,
|
|
288
|
+
// consume the 200-char budget into a blank ` …` row, or split dedupe across `msg` vs `msg\n`.
|
|
289
|
+
const message = sanitizeTerminalText(rawMessage, { maxLength: rawMessage.length }).trim();
|
|
290
|
+
if (message.length > 0) {
|
|
291
|
+
// WHY: bound after redaction — a `[REDACTED]` mask is longer than the value it replaces, so
|
|
292
|
+
// capping first would let the emitted line grow past the budget (or slice a token before the
|
|
293
|
+
// redactor can recognise it).
|
|
294
|
+
return sanitizeTerminalText(redactSecrets(message), {
|
|
295
|
+
maxLength: PROGRESS_MESSAGE_MAX_LENGTH,
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
const current = Number.isFinite(progress.progress) ? String(progress.progress) : "?";
|
|
299
|
+
const total = Number.isFinite(progress.total) ? `/${progress.total}` : "";
|
|
300
|
+
return `Progress ${current}${total}`;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* Build the SDK `onprogress` handler for one `tools/call`.
|
|
305
|
+
*
|
|
306
|
+
* WHY: the handler is installed even when Pi passes no `onUpdate` callback. The SDK attaches
|
|
307
|
+
* `_meta.progressToken` only when `onprogress` is set, and the timer reset that keeps a long,
|
|
308
|
+
* actively-reporting tool alive (`resetTimeoutOnProgress`) hangs off that token (#254).
|
|
309
|
+
*
|
|
310
|
+
* Consecutive identical lines are dropped: some servers repeat one message on every tick, and
|
|
311
|
+
* each emission re-renders Pi's in-progress tool row.
|
|
312
|
+
*/
|
|
313
|
+
function createProgressReporter(
|
|
314
|
+
onUpdate: ToolUpdateCallback | undefined,
|
|
315
|
+
): (progress: Progress) => void {
|
|
316
|
+
let lastText: string | undefined;
|
|
317
|
+
return (progress: Progress): void => {
|
|
318
|
+
if (!onUpdate) return;
|
|
319
|
+
const text = formatProgressText(progress);
|
|
320
|
+
if (text === lastText) return;
|
|
321
|
+
lastText = text;
|
|
322
|
+
onUpdate({ content: [{ type: "text", text }], details: {} });
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
|
|
257
326
|
/** Call tools/call through the typed helper when present, else a raw JSON-RPC request. */
|
|
258
327
|
function callToolWithClient(
|
|
259
328
|
client: Client,
|
|
260
329
|
toolName: string,
|
|
261
330
|
params: unknown,
|
|
262
331
|
timeoutMs: number,
|
|
263
|
-
|
|
332
|
+
options: ToolCallOptions,
|
|
264
333
|
): Promise<ToolCallResponse> {
|
|
265
334
|
const requestOptions = {
|
|
266
335
|
timeout: timeoutMs,
|
|
336
|
+
// WHY: without these two the SDK never attaches a progress token, so it drops the server's
|
|
337
|
+
// `notifications/progress` as an unknown token and keeps the original inactivity deadline —
|
|
338
|
+
// a tool that reports progress every few seconds was still killed at `requestTimeoutMs` (#254).
|
|
339
|
+
resetTimeoutOnProgress: true,
|
|
340
|
+
onprogress: createProgressReporter(options.onUpdate),
|
|
267
341
|
// Pass AbortSignal to SDK — it will automatically send
|
|
268
342
|
// notifications/cancelled when the signal fires
|
|
269
|
-
...(signal ? { signal } : {}),
|
|
343
|
+
...(options.signal ? { signal: options.signal } : {}),
|
|
270
344
|
};
|
|
271
345
|
if (typeof client.callTool === "function") {
|
|
272
346
|
return client.callTool(
|
|
@@ -651,8 +725,11 @@ export class ToolBridge {
|
|
|
651
725
|
const annotations = tool.annotations;
|
|
652
726
|
const description = buildToolDescription(tool, annotations);
|
|
653
727
|
const toolAnnotations = buildToolAnnotations(annotations);
|
|
654
|
-
const runTool = (
|
|
655
|
-
|
|
728
|
+
const runTool = (
|
|
729
|
+
params: unknown,
|
|
730
|
+
signal: AbortSignal | undefined,
|
|
731
|
+
onUpdate: ToolUpdateCallback | undefined,
|
|
732
|
+
) => this._executeToolCall(serverName, tool.name, client, params, { signal, onUpdate });
|
|
656
733
|
// WHY: `execute` runs with `this` bound to the registered-tool literal rather than the
|
|
657
734
|
// bridge, so the rethrow helper is reached through a captured closure.
|
|
658
735
|
const rethrowToolCallError = (err: unknown): Promise<never> =>
|
|
@@ -666,9 +743,9 @@ export class ToolBridge {
|
|
|
666
743
|
parameters: convertJsonSchemaToTypebox(tool.inputSchema),
|
|
667
744
|
...(toolAnnotations ? { annotations: toolAnnotations } : {}),
|
|
668
745
|
|
|
669
|
-
async execute(_toolCallId, params, signal,
|
|
746
|
+
async execute(_toolCallId, params, signal, onUpdate, _ctx) {
|
|
670
747
|
try {
|
|
671
|
-
return await runTool(params, signal);
|
|
748
|
+
return await runTool(params, signal, onUpdate);
|
|
672
749
|
} catch (err) {
|
|
673
750
|
return await rethrowToolCallError(err);
|
|
674
751
|
}
|
|
@@ -707,9 +784,9 @@ export class ToolBridge {
|
|
|
707
784
|
toolName: string,
|
|
708
785
|
client: Client,
|
|
709
786
|
params: unknown,
|
|
710
|
-
|
|
787
|
+
options: ToolCallOptions,
|
|
711
788
|
): Promise<ToolCallOutcome> {
|
|
712
|
-
if (signal?.aborted) {
|
|
789
|
+
if (options.signal?.aborted) {
|
|
713
790
|
throw new McpError("Tool execution cancelled", serverName, "protocol");
|
|
714
791
|
}
|
|
715
792
|
|
|
@@ -720,13 +797,13 @@ export class ToolBridge {
|
|
|
720
797
|
toolName,
|
|
721
798
|
params,
|
|
722
799
|
this.serverTimeouts.get(serverName) ?? this.settings.requestTimeoutMs,
|
|
723
|
-
|
|
800
|
+
options,
|
|
724
801
|
);
|
|
725
802
|
} catch (err) {
|
|
726
803
|
// WHY: an abort mid-call is rejected by the SDK with its RequestTimeout error, so the
|
|
727
804
|
// cancellation has to be recognised here — otherwise a caller cancellation is reported
|
|
728
805
|
// as a server timeout, and blamed on the server (#209).
|
|
729
|
-
if (isCancellationError(err, signal)) {
|
|
806
|
+
if (isCancellationError(err, options.signal)) {
|
|
730
807
|
throw new McpError("Tool execution cancelled", serverName, "protocol");
|
|
731
808
|
}
|
|
732
809
|
throw err;
|