pi-mcp-extension 1.11.10 → 1.12.1

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 CHANGED
@@ -28,7 +28,7 @@
28
28
  - **No tool churn** — Activate/deactivate pattern ensures tools don't flicker during reconnection
29
29
  - **Layered config & trust boundary** — Global `<agent dir>/mcp.json`, project `.pi/mcp.json` (loaded only in trusted projects, including Pi 1.3.0 partial overrides), and Pi 1.x extension-registered servers (`pi.registerMcpServer()`)
30
30
  - **Rich tool results & annotations** — MCP `text`, `image` (`ImageContent`), `structuredContent`, embedded `resource` text/blobs, and `audio` fallback descriptions, plus `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint` surfaced in tool descriptions
31
- - **On-demand agent tools & commands** — `mcp_status` and `mcp_connect` agent tools plus `/mcp`, `/mcp <name>` (with config provenance and failure hints), `/mcp:start`, `/mcp:stop`, and `/mcp:auth` slash commands with server-name autocomplete
31
+ - **On-demand agent tools & commands** — `mcp_status`, `mcp_connect`, `mcp_list_resources`, and `mcp_read_resource` agent tools plus `/mcp`, `/mcp <name>` (with config provenance and failure hints), `/mcp:start`, `/mcp:stop`, `/mcp:auth`, and `/mcp:resources` slash commands with server-name autocomplete
32
32
  - **Structured error handling** — Distinct error codes (`config`, `connection`, `auth`, `timeout`, `protocol`, `tool`) and actionable failure hints
33
33
  - **Redacted debug logging** — Opt-in `PI_MCP_DEBUG=1` JSON Lines log (`<agent dir>/logs/pi-mcp.log`, `0600`, ~2 MB rotation) with automatic secret masking and zero TUI `stderr` noise
34
34
  - **OAuth 2.1** — Browser and headless/SSH authorization with PKCE, protected-resource discovery, Dynamic Client Registration, startup prompts for eager servers, cross-process lock recovery, token refresh, and origin/issuer-bound local persistence (see [OAUTH.md](./OAUTH.md))
@@ -234,13 +234,18 @@ Server-name arguments provide autocomplete suggestions from the configured MCP s
234
234
  | `/mcp:stop <name>` | Cancel a pending connection, startup prompt, or authorization, or stop a running server and deactivate its tools |
235
235
  | `/mcp:auth <name>` | Connect (or force a fresh reconnect if already `ready`) using stored OAuth credentials and client registration; request browser authorization only if needed |
236
236
  | `/mcp:auth <name> --reset` | Discard stored tokens and client registration (re-running Dynamic Client Registration) and request fresh authorization (`--reset` may appear before or after `<name>`) |
237
+ | `/mcp:resources` | Show resource and template counts for every connected server |
238
+ | `/mcp:resources <name>` | List one server's resources (`uri`, description, MIME type) and URI templates, capped at 50 rows plus an "and N more" line |
239
+ | `/mcp:resources <name> <uri>` | Read one resource (template URIs filled in) and preview its text or image summary in a notification |
237
240
 
238
- In addition to user slash commands, two built-in **agent tools** let the LLM inspect and connect configured servers directly:
241
+ In addition to user slash commands, built-in **agent tools** let the LLM inspect servers, connect them, and read their resources directly:
239
242
 
240
243
  | Agent Tool | Parameters | Description |
241
244
  |---|---|---|
242
245
  | `mcp_status` | `{}` | List configured servers with `lifecycle`, `state`, `tools` (`discovered` / `active`), `auth` credential summary, `source` (`"global"` / `"project"` / `"extension"` / `"unknown"`), and safe `error` action hints (never returns tokens, headers, or authorization URLs) |
243
246
  | `mcp_connect` | `{ name: string }` | Connect one named server, run interactive OAuth if needed, and verify that discovered tools are active before returning success (returns fixed actionable categories on failure instead of raw server response text) |
247
+ | `mcp_list_resources` | `{ server?: string }` | List `resources/list` entries (`uri`, `name`, `description`, `mimeType`) and `resources/templates/list` URI templates for connected servers, naming configured servers that are stopped (`stoppedServers`), servers that do not advertise the `resources` capability (`resourcesUnsupported`), and servers whose listing failed (`error`) without dropping the healthy servers' rows (read-only) |
248
+ | `mcp_read_resource` | `{ server: string, uri: string }` | Read one resource with `resources/read`: text resources return their text (including empty text), `image/*` blobs return an image block, and other binary blobs return a `[Binary resource: uri (mimeType, N bytes)]` summary instead of filling the context window; a server without the `resources` capability is reported as such rather than as a protocol error (read-only) |
244
249
 
245
250
  `mcp_status` returns a JSON array of [`ServerStatusRow`](./src/server-status.ts) objects:
246
251
 
@@ -365,12 +370,12 @@ flowchart TD
365
370
  6. **Tools activate/deactivate** automatically as servers connect/disconnect
366
371
  7. **AbortSignal** is wired through to `notifications/cancelled` for clean cancellation
367
372
  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
368
- 9. **`list_changed` notifications** trigger re-discovery, deactivating stale tools automatically
373
+ 9. **`list_changed` notifications** trigger re-discovery, deactivating stale tools automatically and invalidating the cached resource catalog
369
374
  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` and pipe cleanup for `stdio` child processes)
370
375
 
371
376
  ## MCP Spec Compliance
372
377
 
373
- Implements the **MCP 2025-03-26** specification for tool clients:
378
+ Implements the **MCP 2025-03-26** specification for tool and resource clients:
374
379
 
375
380
  | Feature | Status |
376
381
  |---|---|
@@ -380,6 +385,9 @@ Implements the **MCP 2025-03-26** specification for tool clients:
380
385
  | `sse` transport (legacy backwards compat) | ✅ |
381
386
  | OAuth 2.1 authorization (PKCE S256, RFC 9728 Protected Resource Metadata, RFC 7591 DCR) | ✅ |
382
387
  | Cursor-based `tools/list` pagination | ✅ |
388
+ | Cursor-based `resources/list` and `resources/templates/list` pagination | ✅ |
389
+ | `resources/read` with text, image blobs, and binary size summaries | ✅ |
390
+ | `notifications/resources/list_changed` (catalog invalidation) | ✅ |
383
391
  | `tools/call` with parameters, `image` (`ImageContent`), `structuredContent`, and `resource` conversion | ✅ |
384
392
  | `roots/list` capability (workspace root) | ✅ |
385
393
  | `notifications/tools/list_changed` (live refresh) | ✅ |
@@ -387,7 +395,6 @@ Implements the **MCP 2025-03-26** specification for tool clients:
387
395
  | `notifications/message` (structured logging) | ✅ |
388
396
  | `isError: true` distinction (protocol vs tool errors, non-text filtered on error) | ✅ |
389
397
  | Tool annotations (`readOnlyHint`, `destructiveHint`, etc.) | ✅ |
390
- | Resources bridge | ⏳ v2 |
391
398
  | Prompts bridge | ⏳ v2 |
392
399
  | Sampling | ⏳ v2 |
393
400
 
@@ -429,6 +436,7 @@ The test suite includes:
429
436
  - **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
430
437
  - **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
431
438
  - **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
439
+ - **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`
432
440
  - **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
433
441
  - **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
434
442
  - **End-to-end integration** — Real mock MCP and OAuth servers over `stdio` and HTTP with tool discovery and execution
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.11.10",
3
+ "version": "1.12.1",
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/commands.ts CHANGED
@@ -27,6 +27,35 @@ export function parseAuthArguments(args = "", serverNames: string[] = []): { nam
27
27
  return stripResetFlag(name);
28
28
  }
29
29
 
30
+ /** Parsed `/mcp:resources [server] [uri]` arguments. */
31
+ export interface ResourceArguments {
32
+ server: string;
33
+ uri: string;
34
+ }
35
+
36
+ function findMatchingServerPrefix(trimmed: string, serverNames: readonly string[]): string | undefined {
37
+ const sorted = [...serverNames].sort((a, b) => b.length - a.length);
38
+ return sorted.find((name) => name.length > 0 && trimmed.startsWith(name) && /\s/.test(trimmed[name.length] ?? ""));
39
+ }
40
+
41
+ /**
42
+ * Split `/mcp:resources` arguments into an optional server name and an optional URI.
43
+ * Exact and prefix matches against configured `serverNames` are checked first so server names
44
+ * containing spaces (`"team server"`) are preserved, and the URI keeps everything after the
45
+ * server delimiter so a URI containing spaces (`file:///path/with space`) is not truncated.
46
+ */
47
+ export function parseResourceArguments(args = "", serverNames: readonly string[] = []): ResourceArguments {
48
+ const trimmed = args.trim();
49
+ if (!trimmed) return { server: "", uri: "" };
50
+ if (serverNames.includes(trimmed)) return { server: trimmed, uri: "" };
51
+ const matchedServer = findMatchingServerPrefix(trimmed, serverNames);
52
+ if (matchedServer) return { server: matchedServer, uri: trimmed.slice(matchedServer.length).trim() };
53
+ const separator = trimmed.search(/\s/);
54
+ return separator === -1
55
+ ? { server: trimmed, uri: "" }
56
+ : { server: trimmed.slice(0, separator), uri: trimmed.slice(separator).trim() };
57
+ }
58
+
30
59
  export interface ServerCompletionEntry {
31
60
  name: string;
32
61
  state: string;
package/src/index.ts CHANGED
@@ -40,6 +40,12 @@ import {
40
40
  import { AuthLockError, AuthRequiredError } from "./oauth-provider.js";
41
41
  import * as Type from "typebox";
42
42
  import { ToolBridge } from "./tool-bridge.js";
43
+ import {
44
+ ResourceBridge,
45
+ type McpResourceDefinition,
46
+ type McpResourceTemplateDefinition,
47
+ type PiResourceContent,
48
+ } from "./resource-bridge.js";
43
49
  import { McpError, AuthCancelledError } from "./errors.js";
44
50
  import {
45
51
  ConnectionCoordinator,
@@ -130,6 +136,7 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
130
136
  // ── 2. Initialize bridge components ──────────────────────────────────────
131
137
  const manager = new ServerManager(config, paths.authStorageDir);
132
138
  const bridge = new ToolBridge(config.settings, pi);
139
+ const resources = new ResourceBridge();
133
140
  const callbackServer = paths.callbackServer ?? new CallbackServer();
134
141
  const coordinator = new ConnectionCoordinator({
135
142
  manager,
@@ -158,7 +165,10 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
158
165
  },
159
166
  );
160
167
  });
161
- manager.setServerStoppedCallback((name) => bridge.deactivateServer(name));
168
+ manager.setServerStoppedCallback((name) => {
169
+ bridge.deactivateServer(name);
170
+ resources.forget(name);
171
+ });
162
172
  manager.setRecoveryFailedCallback((serverName, error) => {
163
173
  coordinator.handleRecoveryFailed(serverName, error);
164
174
  });
@@ -168,7 +178,12 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
168
178
  // survives a server that has since connected cleanly.
169
179
  coordinator.syncStatus();
170
180
  });
171
- bridge.setAuthErrorCallback(async (serverName) => {
181
+ manager.setResourceListChangedCallback((name) => {
182
+ // WHY: resources are listed on demand, so a notification only has to make the cached
183
+ // catalog stale; the next read re-fetches it from the same client.
184
+ resources.invalidate(name);
185
+ });
186
+ const handleAuthError = async (serverName: string): Promise<void> => {
172
187
  const authError = await manager.handleUnauthorizedServerError(serverName);
173
188
  if (authError) {
174
189
  // WHY: A mid-session 401/403 stops the server synchronously, which cancels the
@@ -176,7 +191,11 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
176
191
  // failure here or the re-auth warning and the footer hint never appear.
177
192
  coordinator.handleRecoveryFailed(serverName, authError);
178
193
  }
179
- });
194
+ };
195
+ bridge.setAuthErrorCallback(handleAuthError);
196
+ // WHY: a resources/* request can be the first call to hit an expired token, so it needs
197
+ // the same re-authorization path as tools/call.
198
+ resources.setAuthErrorCallback(handleAuthError);
180
199
 
181
200
  // ── 3. Session lifecycle ──────────────────────────────────────────────────
182
201
  pi.on("session_start", async (_event, ctx: ExtensionContext) => {
@@ -305,6 +324,7 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
305
324
  for (const name of removedOrChanged) {
306
325
  coordinator.cancelServer(name);
307
326
  bridge.removeServer(name);
327
+ resources.forget(name);
308
328
  await manager.removeServer(name);
309
329
  }
310
330
  if (removedOrChanged.length > 0) {
@@ -347,7 +367,7 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
347
367
  // ── 4. Slash commands ───────────────────────────────────────────────────
348
368
  const getProvenance = (): ConfigProvenance =>
349
369
  withExtensionServers(fileProvenance, Object.keys(extensionServers));
350
- registerCommands(pi, { manager, coordinator, bridge, getProvenance });
370
+ registerCommands(pi, { manager, coordinator, bridge, resources, getProvenance });
351
371
 
352
372
  const authorize = (serverName: string, ctx: ExtensionContext, signal: AbortSignal, reset: boolean) =>
353
373
  runAuthorize(
@@ -364,13 +384,14 @@ export default async function (pi: ExtensionAPI, paths: { bootstrapCwd?: string;
364
384
  reset,
365
385
  );
366
386
 
367
- registerManagementTools(pi, { manager, coordinator, bridge, getProvenance });
387
+ registerManagementTools(pi, { manager, coordinator, bridge, resources, getProvenance });
368
388
  }
369
389
 
370
390
  interface ManagementToolDeps {
371
391
  manager: ServerManager;
372
392
  coordinator: ConnectionCoordinator;
373
393
  bridge: ToolBridge;
394
+ resources: ResourceBridge;
374
395
  getProvenance: () => ConfigProvenance;
375
396
  }
376
397
 
@@ -473,4 +494,122 @@ function registerManagementTools(
473
494
  return { content: [{ type: "text", text: `MCP server ${name} ready; tools discovered and active.` }], details: {} };
474
495
  },
475
496
  });
497
+
498
+ pi.registerTool({
499
+ name: "mcp_list_resources",
500
+ label: "List MCP resources",
501
+ description: "List MCP resources and URI templates exposed by connected servers. Use mcp_read_resource to read one by URI.",
502
+ promptSnippet: "Discover read-only MCP resources (documents, schemas, data streams) and URI templates, optionally for one server.",
503
+ parameters: Type.Object({
504
+ server: Type.Optional(Type.String({ description: "Exact configured MCP server name (default: all connected servers)" })),
505
+ }),
506
+ annotations: { readOnlyHint: true },
507
+ async execute(_id, { server }, signal) {
508
+ const rows = await listResourceRows(deps, server, signal);
509
+ return { content: [{ type: "text", text: JSON.stringify(rows) }], details: {} };
510
+ },
511
+ });
512
+
513
+ pi.registerTool({
514
+ name: "mcp_read_resource",
515
+ label: "Read MCP resource",
516
+ description: "Read one MCP resource by server and URI. Text resources return their text; image blobs return an image; other binary blobs return a size summary.",
517
+ promptSnippet: "Read an MCP resource document or data stream by its URI from a connected server.",
518
+ parameters: Type.Object({
519
+ server: Type.String({ description: "Exact configured MCP server name" }),
520
+ uri: Type.String({ description: "Resource URI, or a URI template filled in by the caller" }),
521
+ }),
522
+ annotations: { readOnlyHint: true },
523
+ async execute(_id, { server, uri }, signal) {
524
+ const content = await readResourceForTool(deps, server, uri, signal);
525
+ return { content, details: {} };
526
+ },
527
+ });
528
+ }
529
+
530
+ /** One `mcp_list_resources` row: a connected server's resources and templates. */
531
+ interface ResourceToolRow {
532
+ server: string;
533
+ resources: McpResourceDefinition[];
534
+ templates: McpResourceTemplateDefinition[];
535
+ resourcesUnsupported?: boolean;
536
+ error?: string;
537
+ }
538
+
539
+ /**
540
+ * Collect one server's catalog.
541
+ * WHY: a server that never advertised the `resources` capability must not be asked — the raw
542
+ * request would come back as a protocol error rather than an empty catalog. A server that does
543
+ * advertise it but fails keeps its row instead of rejecting every other server's listing.
544
+ */
545
+ async function collectResourcesForServer(
546
+ server: ManagedServer,
547
+ deps: ManagementToolDeps,
548
+ signal: AbortSignal | undefined,
549
+ ): Promise<ResourceToolRow> {
550
+ if (signal?.aborted) throw new AuthCancelledError(server.name);
551
+ const client = server.client;
552
+ if (!client || !client.getServerCapabilities()?.resources) {
553
+ return { server: server.name, resources: [], templates: [], resourcesUnsupported: true };
554
+ }
555
+ try {
556
+ const catalog = await deps.resources.getCatalog(server.name, client, {
557
+ requestTimeoutMs: deps.manager.resolveRequestTimeoutMs(server),
558
+ ...(signal ? { signal } : {}),
559
+ });
560
+ return { server: server.name, ...catalog };
561
+ } catch (err) {
562
+ if (err instanceof AuthCancelledError || signal?.aborted) {
563
+ throw err instanceof AuthCancelledError ? err : new AuthCancelledError(server.name);
564
+ }
565
+ return { server: server.name, resources: [], templates: [], error: formatErrorMessage(err) };
566
+ }
567
+ }
568
+
569
+ /** Gather `mcp_list_resources` rows for every connected server, or one explicitly named server. */
570
+ async function listResourceRows(
571
+ deps: ManagementToolDeps,
572
+ filter: string | undefined,
573
+ signal: AbortSignal | undefined,
574
+ ): Promise<{ servers: ResourceToolRow[]; stoppedServers: string[] }> {
575
+ if (signal?.aborted) throw new AuthCancelledError(filter ?? "mcp_list_resources");
576
+ const all = deps.manager.getAllServers();
577
+ if (filter) {
578
+ const target = all.find((server) => server.name === filter);
579
+ if (!target) throw new Error("Unknown MCP server name. Use mcp_status to list configured servers.");
580
+ if (target.state !== "ready") {
581
+ throw new Error(`MCP server ${filter} is not connected. Use mcp_connect to connect it.`);
582
+ }
583
+ return { servers: [await collectResourcesForServer(target, deps, signal)], stoppedServers: [] };
584
+ }
585
+ const connected = all.filter((server) => server.state === "ready");
586
+ const servers = await Promise.all(connected.map((server) => collectResourcesForServer(server, deps, signal)));
587
+ const stoppedServers = all.filter((server) => server.state !== "ready").map((server) => server.name);
588
+ return { servers, stoppedServers };
589
+ }
590
+
591
+ /** Resolve the server for `mcp_read_resource` and read one URI from its live client. */
592
+ async function readResourceForTool(
593
+ deps: ManagementToolDeps,
594
+ serverName: string,
595
+ uri: string,
596
+ signal: AbortSignal | undefined,
597
+ ): Promise<PiResourceContent[]> {
598
+ if (signal?.aborted) throw new AuthCancelledError(serverName);
599
+ const target = deps.manager.getServer(serverName);
600
+ if (!target) throw new Error("Unknown MCP server name. Use mcp_status to list configured servers.");
601
+ const client = target.client;
602
+ if (!client || target.state !== "ready") {
603
+ throw new Error(`MCP server ${serverName} is not connected. Use mcp_connect to connect it.`);
604
+ }
605
+ // WHY: without this a capability-less server answers resources/read with JSON-RPC -32601,
606
+ // which surfaces as a cryptic protocol error instead of the same actionable wording the
607
+ // listing and /mcp:resources use.
608
+ if (!client.getServerCapabilities()?.resources) {
609
+ throw new McpError(`MCP server ${serverName} does not expose MCP resources`, serverName, "protocol");
610
+ }
611
+ return deps.resources.readResource(serverName, client, uri, {
612
+ requestTimeoutMs: deps.manager.resolveRequestTimeoutMs(target),
613
+ ...(signal ? { signal } : {}),
614
+ });
476
615
  }
@@ -6,8 +6,10 @@ import type {
6
6
  ExtensionAPI,
7
7
  ExtensionCommandContext,
8
8
  } from "@earendil-works/pi-coding-agent";
9
+ import type { Client } from "@modelcontextprotocol/sdk/client/index.js";
9
10
  import {
10
11
  parseAuthArguments,
12
+ parseResourceArguments,
11
13
  serverNameCompletions,
12
14
  } from "./commands.js";
13
15
  import {
@@ -21,11 +23,13 @@ import { lookupServerSource, type ConfigProvenance } from "./server-provenance.j
21
23
  import { collectServerStatus, formatServerDetail } from "./server-status.js";
22
24
  import { sanitizeTerminalText } from "./terminal-text.js";
23
25
  import type { ToolBridge } from "./tool-bridge.js";
26
+ import type { PiResourceContent, ResourceBridge, ResourceCatalog } from "./resource-bridge.js";
24
27
 
25
28
  export interface RegisterCommandsDeps {
26
29
  manager: ServerManager;
27
30
  coordinator: ConnectionCoordinator;
28
31
  bridge: ToolBridge;
32
+ resources: ResourceBridge;
29
33
  /** Session config provenance (file origins merged with extension-registered servers). */
30
34
  getProvenance: () => ConfigProvenance;
31
35
  }
@@ -143,6 +147,160 @@ async function handleMcpAuth(
143
147
  }
144
148
  }
145
149
 
150
+ // ─── /mcp:resources ──────────────────────────────────────────────────────────
151
+
152
+ const RESOURCE_FIELD_MAX_LENGTH = 120;
153
+
154
+ interface ResourceTarget {
155
+ server: ManagedServer;
156
+ client: Client;
157
+ }
158
+
159
+ function supportsResources(client: Client): boolean {
160
+ return Boolean(client.getServerCapabilities()?.resources);
161
+ }
162
+
163
+ function formatResourceLine(label: string, detail: string | undefined, mimeType: string | undefined): string {
164
+ const parts = [sanitizeTerminalText(label, { maxLength: RESOURCE_FIELD_MAX_LENGTH })];
165
+ if (detail) parts.push(sanitizeTerminalText(detail, { maxLength: RESOURCE_FIELD_MAX_LENGTH }));
166
+ if (mimeType) parts.push(sanitizeTerminalText(mimeType, { maxLength: 60 }));
167
+ return ` ${parts.join(" — ")}`;
168
+ }
169
+
170
+ /** Maximum catalog rows rendered in one notification; the rest are summarized. */
171
+ const MAX_CATALOG_ROWS = 50;
172
+
173
+ export function formatResourceCatalog(serverName: string, catalog: ResourceCatalog): string {
174
+ const header = `pi-mcp: ${sanitizeTerminalText(serverName, { maxLength: 64 })} — ${catalog.resources.length} resource(s), ${catalog.templates.length} template(s)`;
175
+ const rows = [
176
+ ...catalog.resources.map((resource) =>
177
+ formatResourceLine(resource.uri, resource.description ?? resource.name, resource.mimeType),
178
+ ),
179
+ ...catalog.templates.map((template) =>
180
+ formatResourceLine(template.uriTemplate, template.description ?? template.name, template.mimeType),
181
+ ),
182
+ ];
183
+ if (rows.length === 0) return `${header}\n (none)`;
184
+ const shown = rows.slice(0, MAX_CATALOG_ROWS);
185
+ const hidden = rows.length - shown.length;
186
+ // WHY: a spec-conformant server may advertise thousands of entries (100 pages × 100 rows),
187
+ // and this string reaches a terminal notification — bound it like the read preview.
188
+ if (hidden > 0) shown.push(` … and ${hidden} more`);
189
+ return [header, ...shown].join("\n");
190
+ }
191
+
192
+ function describeResourceContent(content: PiResourceContent): string {
193
+ if (content.type === "image") {
194
+ return `[image ${sanitizeTerminalText(content.mimeType, { maxLength: 60 })}, ${content.data.length} base64 chars]`;
195
+ }
196
+ return content.text;
197
+ }
198
+
199
+ function formatResourcePreview(serverName: string, uri: string, content: PiResourceContent[]): string {
200
+ const header = `pi-mcp: ${sanitizeTerminalText(serverName, { maxLength: 64 })} — ${sanitizeTerminalText(uri, { maxLength: RESOURCE_FIELD_MAX_LENGTH })}`;
201
+ const body = sanitizeTerminalText(content.map(describeResourceContent).join("\n"), { maxLength: 1200 });
202
+ // WHY: a notification is a single terminal line, so server-controlled resource content is
203
+ // sanitized and bounded before it reaches the UI; an empty text payload renders the same
204
+ // placeholder as an empty contents array instead of a trailing blank line.
205
+ return `${header}\n${body || "(empty resource)"}`;
206
+ }
207
+
208
+ /** Row for `/mcp:resources` with no server argument: resource and template counts per server. */
209
+ async function describeServerResources(server: ManagedServer, deps: RegisterCommandsDeps): Promise<string> {
210
+ const label = sanitizeTerminalText(server.name, { maxLength: 64 });
211
+ const client = server.client;
212
+ if (!client || !supportsResources(client)) return ` ${label} — no MCP resources`;
213
+ try {
214
+ const catalog = await deps.resources.getCatalog(server.name, client, {
215
+ requestTimeoutMs: deps.manager.resolveRequestTimeoutMs(server),
216
+ });
217
+ return ` ${label} — ${catalog.resources.length} resource(s), ${catalog.templates.length} template(s)`;
218
+ } catch (err) {
219
+ return ` ${label} — failed: ${formatErrorMessage(err)}`;
220
+ }
221
+ }
222
+
223
+ async function notifyResourceSummary(deps: RegisterCommandsDeps, ctx: ExtensionCommandContext): Promise<void> {
224
+ const connected = deps.manager.getAllServers().filter((server) => server.state === "ready");
225
+ if (connected.length === 0) {
226
+ ctx.ui.notify("pi-mcp: No connected MCP servers. Use /mcp:start <name> to connect one.", "info");
227
+ return;
228
+ }
229
+ const rows = await Promise.all(connected.map((server) => describeServerResources(server, deps)));
230
+ ctx.ui.notify(["pi-mcp: MCP resources", ...rows].join("\n"), "info");
231
+ }
232
+
233
+ /** Resolve `/mcp:resources <server>` to a live client, notifying the user when it cannot. */
234
+ function resolveResourceTarget(
235
+ serverName: string,
236
+ ctx: ExtensionCommandContext,
237
+ deps: RegisterCommandsDeps,
238
+ ): ResourceTarget | null {
239
+ const label = sanitizeTerminalText(serverName, { maxLength: 64 });
240
+ const server = deps.manager.getServer(serverName);
241
+ if (!server) {
242
+ ctx.ui.notify(`pi-mcp: No server named "${label}"`, "error");
243
+ return null;
244
+ }
245
+ const client = server.client;
246
+ if (!client || server.state !== "ready") {
247
+ ctx.ui.notify(`pi-mcp: ${label} is not connected. Run /mcp:start ${label}.`, "error");
248
+ return null;
249
+ }
250
+ if (!supportsResources(client)) {
251
+ ctx.ui.notify(`pi-mcp: ${label} does not expose MCP resources.`, "info");
252
+ return null;
253
+ }
254
+ return { server, client };
255
+ }
256
+
257
+ async function notifyResourceList(
258
+ target: ResourceTarget,
259
+ deps: RegisterCommandsDeps,
260
+ ctx: ExtensionCommandContext,
261
+ ): Promise<void> {
262
+ try {
263
+ const catalog = await deps.resources.getCatalog(target.server.name, target.client, {
264
+ requestTimeoutMs: deps.manager.resolveRequestTimeoutMs(target.server),
265
+ });
266
+ ctx.ui.notify(formatResourceCatalog(target.server.name, catalog), "info");
267
+ } catch (err) {
268
+ const label = sanitizeTerminalText(target.server.name, { maxLength: 64 });
269
+ ctx.ui.notify(`pi-mcp: Failed to list resources for ${label} — ${formatErrorMessage(err)}`, "error");
270
+ }
271
+ }
272
+
273
+ async function notifyResourceContent(
274
+ target: ResourceTarget,
275
+ uri: string,
276
+ deps: RegisterCommandsDeps,
277
+ ctx: ExtensionCommandContext,
278
+ ): Promise<void> {
279
+ try {
280
+ const content = await deps.resources.readResource(target.server.name, target.client, uri, {
281
+ requestTimeoutMs: deps.manager.resolveRequestTimeoutMs(target.server),
282
+ });
283
+ ctx.ui.notify(formatResourcePreview(target.server.name, uri, content), "info");
284
+ } catch (err) {
285
+ const label = sanitizeTerminalText(uri, { maxLength: RESOURCE_FIELD_MAX_LENGTH });
286
+ ctx.ui.notify(`pi-mcp: Failed to read ${label} — ${formatErrorMessage(err)}`, "error");
287
+ }
288
+ }
289
+
290
+ async function handleMcpResources(
291
+ args: string,
292
+ ctx: ExtensionCommandContext,
293
+ deps: RegisterCommandsDeps,
294
+ ): Promise<void> {
295
+ const serverNames = deps.manager.getAllServers().map((server) => server.name);
296
+ const { server: serverName, uri } = parseResourceArguments(args, serverNames);
297
+ if (!serverName) return notifyResourceSummary(deps, ctx);
298
+ const target = resolveResourceTarget(serverName, ctx, deps);
299
+ if (!target) return;
300
+ if (uri) return notifyResourceContent(target, uri, deps, ctx);
301
+ return notifyResourceList(target, deps, ctx);
302
+ }
303
+
146
304
  export function registerCommands(pi: ExtensionAPI, deps: RegisterCommandsDeps): void {
147
305
  const { manager } = deps;
148
306
 
@@ -175,4 +333,11 @@ export function registerCommands(pi: ExtensionAPI, deps: RegisterCommandsDeps):
175
333
  handler: (args, ctx) => handleMcpAuth(args, ctx, deps),
176
334
  getArgumentCompletions: (prefix) => serverNameCompletions(prefix, manager.getAllServers(), { authOnly: true }),
177
335
  });
336
+
337
+ // ── 7. /mcp:resources — list or read MCP resources ───────────────────────
338
+ pi.registerCommand("mcp:resources", {
339
+ description: "List MCP resources. Usage: /mcp:resources [server] [uri] to read one resource.",
340
+ handler: (args, ctx) => handleMcpResources(args, ctx, deps),
341
+ getArgumentCompletions: (prefix) => serverNameCompletions(prefix, manager.getAllServers()),
342
+ });
178
343
  }
@@ -0,0 +1,431 @@
1
+ /**
2
+ * MCP resource bridge for pi-mcp.
3
+ *
4
+ * Bridges server-exposed resources and resource templates into Pi:
5
+ * - Paginated `resources/list` and `resources/templates/list` (cursor loop, max-page guard)
6
+ * - On-demand `resources/read` with text/image/binary conversion
7
+ * - A per-server catalog cache invalidated by `notifications/resources/list_changed`
8
+ * - AbortSignal, request timeouts, and OAuth 401/403 routing
9
+ */
10
+
11
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
12
+ import {
13
+ ListResourcesResultSchema,
14
+ ListResourceTemplatesResultSchema,
15
+ ReadResourceResultSchema,
16
+ type ListResourcesResult,
17
+ type ListResourceTemplatesResult,
18
+ type ReadResourceResult,
19
+ } from "@modelcontextprotocol/sdk/types.js";
20
+ import { AuthCancelledError, McpError } from "./errors.js";
21
+ import { isCancellationError, isOAuthUnauthorizedError, isSdkTimeoutError } from "./connect-policy.js";
22
+ import { redactSecrets, reportDiagnostic } from "./debug-log.js";
23
+ import { sanitizeTerminalText } from "./terminal-text.js";
24
+
25
+ // ─── Types ────────────────────────────────────────────────────────────────────
26
+
27
+ /** One `resources/list` entry, reduced to the fields Pi can act on. */
28
+ export interface McpResourceDefinition {
29
+ uri: string;
30
+ name: string;
31
+ description?: string | undefined;
32
+ mimeType?: string | undefined;
33
+ }
34
+
35
+ /** One `resources/templates/list` entry. */
36
+ export interface McpResourceTemplateDefinition {
37
+ uriTemplate: string;
38
+ name: string;
39
+ description?: string | undefined;
40
+ mimeType?: string | undefined;
41
+ }
42
+
43
+ /** A server's advertised resources plus its URI templates. */
44
+ export interface ResourceCatalog {
45
+ resources: McpResourceDefinition[];
46
+ templates: McpResourceTemplateDefinition[];
47
+ }
48
+
49
+ export interface ResourceRequestOptions {
50
+ requestTimeoutMs: number;
51
+ signal?: AbortSignal | undefined;
52
+ }
53
+
54
+ /** Pi content block produced from one `resources/read` content entry. */
55
+ export type PiResourceContent =
56
+ | { type: "text"; text: string }
57
+ | { type: "image"; data: string; mimeType: string };
58
+
59
+ /** Upper bound on pages per list method, so a malfunctioning server cannot page us forever. */
60
+ const MAX_PAGES = 100;
61
+
62
+ export interface ResourcePage<T> {
63
+ items: T[];
64
+ nextCursor: string | undefined;
65
+ }
66
+
67
+ // ─── Pagination & method-not-found degradation ────────────────────────────────
68
+
69
+ function reportPaginationLimit(serverName: string, method: string): void {
70
+ reportDiagnostic({
71
+ level: "warn",
72
+ event: "resources.pagination_limit",
73
+ server: serverName,
74
+ message: `${method} pagination exceeded ${MAX_PAGES} pages, stopping. The server may be malfunctioning.`,
75
+ fields: { pages: MAX_PAGES },
76
+ });
77
+ }
78
+
79
+ /**
80
+ * True for a JSON-RPC `-32601 Method not found` response.
81
+ * WHY: A server may advertise the `resources` capability and still not implement
82
+ * `resources/templates/list` (templates are optional in practice). That answer means
83
+ * "this server has no templates", not "the catalog failed".
84
+ */
85
+ function isMethodNotFoundError(err: unknown): boolean {
86
+ if (typeof err !== "object" || err === null || !("code" in err)) return false;
87
+ return (err as { code?: unknown }).code === -32601;
88
+ }
89
+
90
+ /**
91
+ * Race an in-flight resource request against an abort signal.
92
+ * Abort wins as {@link AuthCancelledError}; the in-flight request is left to
93
+ * settle on its own (its rejection is suppressed).
94
+ */
95
+ async function raceWithAbort<T>(
96
+ callPromise: Promise<T>,
97
+ signal: AbortSignal | undefined,
98
+ serverName: string,
99
+ ): Promise<T> {
100
+ if (!signal) return callPromise;
101
+ callPromise.catch(() => {
102
+ // WHY: Suppress unhandled rejection if in-flight request rejects after abort wins the race.
103
+ });
104
+ let onAbort!: () => void;
105
+ const abortPromise = new Promise<never>((_resolve, reject) => {
106
+ onAbort = () => reject(new AuthCancelledError(serverName));
107
+ signal.addEventListener("abort", onAbort, { once: true });
108
+ });
109
+ try {
110
+ return await Promise.race([callPromise, abortPromise]);
111
+ } finally {
112
+ signal.removeEventListener("abort", onAbort);
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Follow a cursor across pages until the server stops sending one, degrading a JSON-RPC
118
+ * `-32601 Method not found` response to an empty list.
119
+ * Aborts surface as {@link AuthCancelledError}; every other failure reaches the caller.
120
+ */
121
+ export async function collectPages<T>(
122
+ serverName: string,
123
+ method: string,
124
+ signal: AbortSignal | undefined,
125
+ fetchPage: (cursor: string | undefined) => Promise<ResourcePage<T>>,
126
+ ): Promise<T[]> {
127
+ try {
128
+ return await collectCursorPages(serverName, method, signal, fetchPage);
129
+ } catch (err) {
130
+ if (isCancellationError(err, signal)) {
131
+ throw err instanceof AuthCancelledError ? err : new AuthCancelledError(serverName);
132
+ }
133
+ if (isMethodNotFoundError(err)) return [];
134
+ throw err;
135
+ }
136
+ }
137
+
138
+ async function collectCursorPages<T>(
139
+ serverName: string,
140
+ method: string,
141
+ signal: AbortSignal | undefined,
142
+ fetchPage: (cursor: string | undefined) => Promise<ResourcePage<T>>,
143
+ ): Promise<T[]> {
144
+ const items: T[] = [];
145
+ let cursor: string | undefined;
146
+ for (let page = 0; page < MAX_PAGES; page++) {
147
+ if (signal?.aborted) throw new AuthCancelledError(serverName);
148
+ const result = await raceWithAbort(fetchPage(cursor), signal, serverName);
149
+ items.push(...result.items);
150
+ // WHY: The spec ends pagination by omitting `nextCursor`; an empty string means the same
151
+ // thing and some servers send it, so neither may win another round trip.
152
+ cursor = result.nextCursor;
153
+ if (!cursor) return items;
154
+ }
155
+ reportPaginationLimit(serverName, method);
156
+ return items;
157
+ }
158
+
159
+ // ─── Typed requests ───────────────────────────────────────────────────────────
160
+
161
+ function requestOptionsFor(options: ResourceRequestOptions): { timeout: number; signal?: AbortSignal } {
162
+ return {
163
+ timeout: options.requestTimeoutMs,
164
+ ...(options.signal ? { signal: options.signal } : {}),
165
+ };
166
+ }
167
+
168
+ function cursorParams(cursor: string | undefined): { cursor: string } | undefined {
169
+ return cursor ? { cursor } : undefined;
170
+ }
171
+
172
+ /** Fetch one `resources/list` page through the typed helper, falling back to a raw request. */
173
+ function fetchResourcesPage(
174
+ client: Client,
175
+ cursor: string | undefined,
176
+ options: ResourceRequestOptions,
177
+ ): Promise<ListResourcesResult> {
178
+ const reqOpts = requestOptionsFor(options);
179
+ const params = cursorParams(cursor);
180
+ if (typeof client.listResources === "function") return client.listResources(params, reqOpts);
181
+ return client.request({ method: "resources/list", params: params ?? {} }, ListResourcesResultSchema, reqOpts);
182
+ }
183
+
184
+ /** Fetch one `resources/templates/list` page. */
185
+ function fetchResourceTemplatesPage(
186
+ client: Client,
187
+ cursor: string | undefined,
188
+ options: ResourceRequestOptions,
189
+ ): Promise<ListResourceTemplatesResult> {
190
+ const reqOpts = requestOptionsFor(options);
191
+ const params = cursorParams(cursor);
192
+ if (typeof client.listResourceTemplates === "function") return client.listResourceTemplates(params, reqOpts);
193
+ return client.request(
194
+ { method: "resources/templates/list", params: params ?? {} },
195
+ ListResourceTemplatesResultSchema,
196
+ reqOpts,
197
+ );
198
+ }
199
+
200
+ function readResourceOnce(client: Client, uri: string, options: ResourceRequestOptions): Promise<ReadResourceResult> {
201
+ const requestOptions = requestOptionsFor(options);
202
+ if (typeof client.readResource === "function") {
203
+ return client.readResource({ uri }, requestOptions);
204
+ }
205
+ return client.request({ method: "resources/read", params: { uri } }, ReadResourceResultSchema, requestOptions);
206
+ }
207
+
208
+ // ─── Discovery ────────────────────────────────────────────────────────────────
209
+
210
+ export async function listAllResources(
211
+ client: Client,
212
+ serverName: string,
213
+ options: ResourceRequestOptions,
214
+ ): Promise<McpResourceDefinition[]> {
215
+ return collectPages(serverName, "resources/list", options.signal, async (cursor) => {
216
+ const result = await fetchResourcesPage(client, cursor, options);
217
+ return { items: result.resources.map(toResourceDefinition), nextCursor: result.nextCursor };
218
+ });
219
+ }
220
+
221
+ export async function listAllResourceTemplates(
222
+ client: Client,
223
+ serverName: string,
224
+ options: ResourceRequestOptions,
225
+ ): Promise<McpResourceTemplateDefinition[]> {
226
+ return collectPages(serverName, "resources/templates/list", options.signal, async (cursor) => {
227
+ const result = await fetchResourceTemplatesPage(client, cursor, options);
228
+ return { items: result.resourceTemplates.map(toResourceTemplateDefinition), nextCursor: result.nextCursor };
229
+ });
230
+ }
231
+
232
+ function toResourceDefinition(resource: ListResourcesResult["resources"][number]): McpResourceDefinition {
233
+ return {
234
+ uri: resource.uri,
235
+ name: resource.name,
236
+ description: resource.description,
237
+ mimeType: resource.mimeType,
238
+ };
239
+ }
240
+
241
+ function toResourceTemplateDefinition(
242
+ template: ListResourceTemplatesResult["resourceTemplates"][number],
243
+ ): McpResourceTemplateDefinition {
244
+ return {
245
+ uriTemplate: template.uriTemplate,
246
+ name: template.name,
247
+ description: template.description,
248
+ mimeType: template.mimeType,
249
+ };
250
+ }
251
+
252
+ // ─── Content conversion ───────────────────────────────────────────────────────
253
+
254
+ /**
255
+ * Convert `resources/read` contents into Pi content blocks.
256
+ *
257
+ * WHY: Inline image blobs are what the model can actually consume; every other binary payload
258
+ * becomes a bounded summary so a large archive cannot flood the context window.
259
+ */
260
+ export function convertResourceContents(contents: readonly unknown[]): PiResourceContent[] {
261
+ return contents.map(convertResourceContent);
262
+ }
263
+
264
+ function convertResourceContent(item: unknown): PiResourceContent {
265
+ if (typeof item !== "object" || item === null) {
266
+ return { type: "text", text: String(item) };
267
+ }
268
+ const entry = item as Record<string, unknown>;
269
+ // WHY: Check `typeof text === "string"` rather than truthiness so an empty text resource
270
+ // (`text: ""`) stays empty instead of degrading to a `[Resource: uri]` placeholder.
271
+ if (typeof entry["text"] === "string") {
272
+ return { type: "text", text: entry["text"] };
273
+ }
274
+ if (typeof entry["blob"] === "string") {
275
+ return convertBlobResource(entry);
276
+ }
277
+ return { type: "text", text: `[Resource: ${String(entry["uri"] ?? "unknown")}]` };
278
+ }
279
+
280
+ function resolveBlobMimeType(raw: unknown): string {
281
+ const trimmed = typeof raw === "string" ? raw.trim() : "";
282
+ return trimmed.length > 0 ? trimmed : "application/octet-stream";
283
+ }
284
+
285
+ function convertBlobResource(entry: Record<string, unknown>): PiResourceContent {
286
+ const uri = String(entry["uri"] ?? "unknown");
287
+ const mimeType = resolveBlobMimeType(entry["mimeType"]);
288
+ const blob = String(entry["blob"]);
289
+ if (mimeType.startsWith("image/")) {
290
+ return { type: "image", data: blob, mimeType };
291
+ }
292
+ return { type: "text", text: `[Binary resource: ${uri} (${mimeType}, ${Buffer.byteLength(blob, "base64")} bytes)]` };
293
+ }
294
+
295
+ // ─── Resource bridge ──────────────────────────────────────────────────────────
296
+
297
+ interface CachedCatalog {
298
+ generation: number;
299
+ catalog: ResourceCatalog;
300
+ }
301
+
302
+ function cloneCatalog(catalog: ResourceCatalog): ResourceCatalog {
303
+ return { resources: [...catalog.resources], templates: [...catalog.templates] };
304
+ }
305
+
306
+ function formatFailureDetail(err: unknown): string {
307
+ const raw = err instanceof Error ? err.message : String((err as { message?: unknown } | null)?.message ?? err);
308
+ return redactSecrets(sanitizeTerminalText(raw));
309
+ }
310
+
311
+ /**
312
+ * Caches each server's resource catalog and serves `resources/read` on demand.
313
+ *
314
+ * The catalog is fetched lazily (the first `mcp_list_resources` call for a server) and kept
315
+ * until the server reports `notifications/resources/list_changed`, which bumps a monotonic
316
+ * generation. A page set that was in flight when the notification arrived is discarded rather
317
+ * than cached, because the server has already declared it stale.
318
+ */
319
+ export class ResourceBridge {
320
+ private readonly catalogs = new Map<string, CachedCatalog>();
321
+ private readonly generations = new Map<string, number>();
322
+ private onAuthError?: ((serverName: string, error: unknown) => Promise<void> | void) | undefined;
323
+
324
+ /** Register callback invoked when a `resources/*` request fails with 401/403. */
325
+ setAuthErrorCallback(cb: (serverName: string, error: unknown) => Promise<void> | void): void {
326
+ this.onAuthError = cb;
327
+ }
328
+
329
+ /** Drop a server's cached catalog after `notifications/resources/list_changed`. */
330
+ invalidate(serverName: string): void {
331
+ this.generations.set(serverName, this._generation(serverName) + 1);
332
+ this.catalogs.delete(serverName);
333
+ }
334
+
335
+ /** Forget a server's cached catalog when it stops or leaves the config. */
336
+ forget(serverName: string): void {
337
+ // WHY: advance the generation instead of deleting it. A page set that was in flight when
338
+ // the server stopped would otherwise be stamped with the same generation a restarted
339
+ // server reads, resurrecting a catalog fetched from the previous client.
340
+ this.generations.set(serverName, this._generation(serverName) + 1);
341
+ this.catalogs.delete(serverName);
342
+ }
343
+
344
+ /** Return the server's resources and templates, fetching the catalog on first use. */
345
+ async getCatalog(
346
+ serverName: string,
347
+ client: Client,
348
+ options: ResourceRequestOptions,
349
+ ): Promise<ResourceCatalog> {
350
+ if (options.signal?.aborted) throw new AuthCancelledError(serverName);
351
+ const generation = this._generation(serverName);
352
+ const cached = this.catalogs.get(serverName);
353
+ if (cached?.generation === generation) {
354
+ return cloneCatalog(cached.catalog);
355
+ }
356
+ const catalog = await this._fetchCatalog(serverName, client, options);
357
+ // WHY: only cache when the generation has not advanced while these pages were in flight;
358
+ // otherwise a slow stale response would overwrite a newer generation's catalog or
359
+ // repopulate a server that was forgotten while in flight.
360
+ if (this._generation(serverName) === generation) {
361
+ this.catalogs.set(serverName, { generation, catalog });
362
+ }
363
+ return cloneCatalog(catalog);
364
+ }
365
+
366
+ /** Read one resource and convert its contents into Pi content blocks. */
367
+ async readResource(
368
+ serverName: string,
369
+ client: Client,
370
+ uri: string,
371
+ options: ResourceRequestOptions,
372
+ ): Promise<PiResourceContent[]> {
373
+ if (options.signal?.aborted) throw new AuthCancelledError(serverName);
374
+ try {
375
+ const result = await raceWithAbort(
376
+ readResourceOnce(client, uri, options),
377
+ options.signal,
378
+ serverName,
379
+ );
380
+ return convertResourceContents(result.contents);
381
+ } catch (err) {
382
+ return await this._rethrowFailure(serverName, err, options.signal);
383
+ }
384
+ }
385
+
386
+ // ─── Internal ───────────────────────────────────────────────────────────────
387
+
388
+ private _generation(serverName: string): number {
389
+ return this.generations.get(serverName) ?? 0;
390
+ }
391
+
392
+ private async _fetchCatalog(
393
+ serverName: string,
394
+ client: Client,
395
+ options: ResourceRequestOptions,
396
+ ): Promise<ResourceCatalog> {
397
+ try {
398
+ const resources = await listAllResources(client, serverName, options);
399
+ const templates = await listAllResourceTemplates(client, serverName, options);
400
+ return { resources, templates };
401
+ } catch (err) {
402
+ return await this._rethrowFailure(serverName, err, options.signal);
403
+ }
404
+ }
405
+
406
+ /**
407
+ * Normalize a `resources/*` failure after notifying the OAuth handler when the server needs
408
+ * authorization: cancellation stays a cancellation, an SDK request timeout keeps `"timeout"`,
409
+ * and everything else is a protocol failure.
410
+ */
411
+ private async _rethrowFailure(
412
+ serverName: string,
413
+ err: unknown,
414
+ signal: AbortSignal | undefined,
415
+ ): Promise<never> {
416
+ // WHY: an abort mid-request is authoritative and must be recognized before the protocol
417
+ // mapping — the SDK rejects an in-flight abort with its own RequestTimeout error.
418
+ if (isCancellationError(err, signal)) {
419
+ throw err instanceof AuthCancelledError ? err : new AuthCancelledError(serverName);
420
+ }
421
+ if (isOAuthUnauthorizedError(err)) {
422
+ await this.onAuthError?.(serverName, err);
423
+ }
424
+ throw new McpError(
425
+ `MCP resource request failed for ${serverName}: ${formatFailureDetail(err)}`,
426
+ serverName,
427
+ isSdkTimeoutError(err) ? "timeout" : "protocol",
428
+ err,
429
+ );
430
+ }
431
+ }
@@ -371,16 +371,65 @@ function convertMultiTypeSchema(
371
371
  return Type.Union(orderUnionMembers(members), opts);
372
372
  }
373
373
 
374
+ /**
375
+ * Convert one tuple rest schema (an object schema or a boolean) to a TypeBox schema.
376
+ * Any other value (`undefined`, `null`, a number, a string, an array) is not a schema
377
+ * keyword: later positions stay unconstrained instead of inheriting the closed default.
378
+ */
379
+ function convertTupleRestSchema(rest: unknown, ctx: ConversionContext): TSchema | boolean {
380
+ if (typeof rest === "boolean") {
381
+ return rest;
382
+ }
383
+ if (isPlainObject(rest)) {
384
+ return convertJsonSchemaToTypebox(rest, ctx.rootDefs, ctx.effectiveRoot, ctx.seenRefs);
385
+ }
386
+ return true;
387
+ }
388
+
389
+ /**
390
+ * Add a tuple's rest schema to its TypeBox options as `additionalItems`.
391
+ * WHY: `Type.Tuple` forces `additionalItems: false`, so a variadic tuple such as
392
+ * `{ prefixItems: [{ type: "string" }], items: { type: "integer" } }` (`[string, ...integer[]]`)
393
+ * rejects every rest element with `schema is false` in Pi's `validateToolArguments`.
394
+ * TypeBox types `TTuple.additionalItems` as the literal `false` and `Type.TupleOptions()`
395
+ * drops the key, so this override is runtime-only: any `Type.Instantiate`-style rebuild of a
396
+ * tuple loses it and has to re-apply it. The rest schema is also validated but never
397
+ * `Value.Convert`-coerced — TypeBox's tuple converter only visits the declared positions —
398
+ * so `["ls", "1"]` stays a string and is rejected where a plain array would coerce it.
399
+ */
400
+ function withTupleRestSchema(
401
+ rest: unknown,
402
+ opts: Record<string, unknown>,
403
+ ctx: ConversionContext,
404
+ ): Record<string, unknown> {
405
+ return { ...opts, additionalItems: convertTupleRestSchema(rest, ctx) };
406
+ }
407
+
408
+ /**
409
+ * The rest keyword of a tuple: 2020-12 `items` after `prefixItems` (falling back to a legacy
410
+ * sibling `additionalItems`), or draft-07 `additionalItems` after an array `items`.
411
+ * WHY: both drafts leave later positions unconstrained when that keyword is absent, while
412
+ * `Type.Tuple` defaults to `additionalItems: false` — which would reject every rest element
413
+ * with the same `schema is false` failure this conversion exists to prevent. A tuple is closed
414
+ * only when the source schema says so (`items: false` / `additionalItems: false`).
415
+ */
416
+ function tupleRestKeyword(hasPrefixItems: boolean, schema: Record<string, unknown>): unknown {
417
+ if (!hasPrefixItems) {
418
+ return schema["additionalItems"];
419
+ }
420
+ return schema["items"] ?? schema["additionalItems"];
421
+ }
422
+
374
423
  function convertArraySchema(
375
424
  schema: Record<string, unknown>,
376
425
  opts: Record<string, unknown>,
377
426
  ctx: ConversionContext,
378
427
  ): TSchema {
379
- const tupleItems = Array.isArray(schema["prefixItems"])
428
+ const prefixItems = Array.isArray(schema["prefixItems"])
380
429
  ? (schema["prefixItems"] as unknown[])
381
- : Array.isArray(schema["items"])
382
- ? (schema["items"] as unknown[])
383
- : undefined;
430
+ : undefined;
431
+ const tupleItems =
432
+ prefixItems ?? (Array.isArray(schema["items"]) ? (schema["items"] as unknown[]) : undefined);
384
433
  if (tupleItems) {
385
434
  return Type.Tuple(
386
435
  tupleItems.map((item) =>
@@ -391,7 +440,7 @@ function convertArraySchema(
391
440
  ctx.seenRefs,
392
441
  ),
393
442
  ),
394
- opts,
443
+ withTupleRestSchema(tupleRestKeyword(prefixItems !== undefined, schema), opts, ctx),
395
444
  );
396
445
  }
397
446
  const items = schema["items"];
@@ -655,7 +704,9 @@ function resolveNonTypedSchema(
655
704
  * Convert a JSON Schema object to a TypeBox schema.
656
705
  * Handles the common subset used by real-world MCP servers:
657
706
  * - Primitives (string, number, integer, boolean, null)
658
- * - Arrays, tuples (prefixItems / array items), objects (with required/optional/additionalProperties)
707
+ * - Arrays, tuples (prefixItems / array items, with a variadic `items` after
708
+ * `prefixItems` or `additionalItems` after a draft-07 tuple), objects
709
+ * (with required/optional/additionalProperties)
659
710
  * - Enums and const (string, numeric, boolean, and nullable enums → Union of Literals)
660
711
  * - Nullable and multi-type arrays ("type": ["string", "null"]) with Type.Null() ordered first
661
712
  * - Cycle-safe $ref (#, #/$defs/, #/definitions/, and arbitrary RFC 6901 JSON Pointers)
@@ -20,6 +20,7 @@ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
20
20
  import {
21
21
  ListRootsRequestSchema,
22
22
  ToolListChangedNotificationSchema,
23
+ ResourceListChangedNotificationSchema,
23
24
  LoggingMessageNotificationSchema,
24
25
  } from "@modelcontextprotocol/sdk/types.js";
25
26
  import { McpError, AuthCancelledError } from "./errors.js";
@@ -209,6 +210,7 @@ export class ServerManager {
209
210
  private readonly servers = new Map<string, ManagedServer>();
210
211
  private settings: Settings;
211
212
  private onToolRefresh: ToolRefreshCallback | null = null;
213
+ private onResourceListChanged: ((name: string) => void) | null = null;
212
214
  private onServerStopped: ((name: string) => void) | null = null;
213
215
  private onRecoveryFailed: RecoveryFailedCallback | null = null;
214
216
  private onServerReady: ServerReadyCallback | null = null;
@@ -237,6 +239,11 @@ export class ServerManager {
237
239
  this.onToolRefresh = cb;
238
240
  }
239
241
 
242
+ /** Register callback invoked when a server reports `notifications/resources/list_changed`. */
243
+ setResourceListChangedCallback(cb: (name: string) => void): void {
244
+ this.onResourceListChanged = cb;
245
+ }
246
+
240
247
  setServerStoppedCallback(cb: (name: string) => void): void {
241
248
  this.onServerStopped = cb;
242
249
  }
@@ -250,7 +257,8 @@ export class ServerManager {
250
257
  this.onServerReady = cb;
251
258
  }
252
259
 
253
- private _resolveTimeoutMs(server: ManagedServer): number {
260
+ /** Effective request timeout for a server: its own override, else the session default. */
261
+ resolveRequestTimeoutMs(server: ManagedServer): number {
254
262
  return server.config.requestTimeoutMs ?? this.settings.requestTimeoutMs;
255
263
  }
256
264
 
@@ -595,6 +603,12 @@ export class ServerManager {
595
603
  await this._handleToolListChanged(server, client, signal);
596
604
  });
597
605
 
606
+ // resources/list_changed: drop the cached resource catalog so the next
607
+ // `mcp_list_resources` / `/mcp:resources` call re-reads it.
608
+ client.setNotificationHandler(ResourceListChangedNotificationSchema, () => {
609
+ this._handleResourceListChanged(server, client);
610
+ });
611
+
598
612
  // notifications/message: structured logging from MCP servers
599
613
  client.setNotificationHandler(
600
614
  LoggingMessageNotificationSchema,
@@ -637,7 +651,7 @@ export class ServerManager {
637
651
  return;
638
652
  }
639
653
  try {
640
- const refreshTimeoutMs = this._resolveTimeoutMs(server);
654
+ const refreshTimeoutMs = this.resolveRequestTimeoutMs(server);
641
655
  await onToolRefresh(server.name, server.client, {
642
656
  requestTimeoutMs: refreshTimeoutMs,
643
657
  signal,
@@ -663,6 +677,19 @@ export class ServerManager {
663
677
  }
664
678
  }
665
679
 
680
+ /**
681
+ * Invalidate a server's cached resource catalog after a
682
+ * `notifications/resources/list_changed`.
683
+ *
684
+ * Only the current client of a ready server may invalidate: a notification from a
685
+ * superseded client (reconnect race) or from a server that is being torn down must not
686
+ * touch the cache the live connection owns.
687
+ */
688
+ private _handleResourceListChanged(server: ManagedServer, client: Client): void {
689
+ if (server.state !== "ready" || server.client !== client) return;
690
+ this.onResourceListChanged?.(server.name);
691
+ }
692
+
666
693
  private async _handshakeAndDiscover(params: HandshakeParams): Promise<void> {
667
694
  const { server, client, transport, timeoutMs, signal, currentCwd } = params;
668
695
  await this._connectWithTimeoutAndSignal(client, transport, timeoutMs, signal, server.name);
@@ -966,7 +993,7 @@ export class ServerManager {
966
993
  server.lastError = null;
967
994
  const currentCwd = server.cwd ?? cwd;
968
995
  server.cwd = currentCwd;
969
- const timeoutMs = this._resolveTimeoutMs(server);
996
+ const timeoutMs = this.resolveRequestTimeoutMs(server);
970
997
  // Note: retryCount is NOT reset here — it's only reset after successful connect.
971
998
  // This ensures the retry limit is respected across reconnection attempts.
972
999
  // It IS reset when startServer() is called explicitly (e.g. /mcp:start)