pi-mcp-extension 1.12.3 → 1.13.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 CHANGED
@@ -27,7 +27,7 @@
27
27
  - **Stable tool names** — Sanitized, collision-avoiding names (`<prefix>_<server>_<tool>`, max 64 chars) that stay constant across reconnects
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
- - **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
30
+ - **Rich tool results & annotations** — MCP `text`, `image` (`ImageContent`), `structuredContent`, embedded `resource` text/images/binary blobs, `resource_link` hints, and `audio` fallback descriptions, plus `readOnlyHint`, `destructiveHint`, `idempotentHint`, and `openWorldHint` surfaced in tool descriptions
31
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
@@ -229,7 +229,7 @@ Server-name arguments provide autocomplete suggestions from the configured MCP s
229
229
  | Slash Command | Description |
230
230
  |---|---|
231
231
  | `/mcp` | Show status summary of all configured servers |
232
- | `/mcp <name>` | Show detailed status for one server: config source, transport/lifecycle, tool activation, OAuth credential status, failure hint, and stderr log |
232
+ | `/mcp <name>` | Show detailed status for one server: config source, transport/lifecycle, tool activation, handshake instructions, OAuth credential status, failure hint, and stderr log |
233
233
  | `/mcp:start <name>` | Connect a server and wait for tool discovery |
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 |
@@ -242,13 +242,20 @@ In addition to user slash commands, built-in **agent tools** let the LLM inspect
242
242
 
243
243
  | Agent Tool | Parameters | Description |
244
244
  |---|---|---|
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) |
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) |
245
+ | `mcp_status` | `{}` | List configured servers with `lifecycle`, `state`, `tools` (`discovered` / `active`), `auth` credential summary, `source` (`"global"` / `"project"` / `"extension"` / `"unknown"`), optional `instructions` (when connected), and safe `error` action hints (never returns tokens, headers, or authorization URLs) |
246
+ | `mcp_connect` | `{ name: string }` | Connect one named server, run interactive OAuth if needed, and verify that discovered tools are active before returning success (includes sanitized server `instructions` when provided; returns fixed actionable categories on failure instead of raw server response text) |
247
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
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) |
249
249
 
250
250
  `mcp_status` returns a JSON array of [`ServerStatusRow`](./src/server-status.ts) objects:
251
251
 
252
+ Connected servers that provide MCP handshake instructions also include an optional
253
+ `instructions` string. `/mcp <name>` displays the same guidance as `Instructions:`,
254
+ and `mcp_connect` includes it after a successful connection. Instructions are
255
+ secret-redacted, stripped of terminal controls, collapsed to one line, and capped
256
+ at 500 UTF-16 code units. Blank instructions and stopped servers omit the field.
257
+ These are server-provided usage hints, not trusted local policy.
258
+
252
259
  ```json
253
260
  [
254
261
  {
@@ -366,7 +373,7 @@ flowchart TD
366
373
  2. **Eager servers connect** at `session_start` via `ConnectionCoordinator` (offering a sequential `Authorize now` / `Not now` prompt when an eager OAuth server needs authorization in an interactive session); lazy servers wait for `mcp_connect`, `/mcp:start`, or `/mcp:auth`
367
374
  3. **Tools are discovered** via paginated `tools/list` calls (cursor-based, up to 100 pages) before a server enters `ready`
368
375
  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)
369
- 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`, and `audio` results
376
+ 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. Embedded image resources become image blocks, binary resources include MIME type and byte count, and resource links include a `mcp_read_resource` hint.
370
377
  6. **Tools activate/deactivate** automatically as servers connect/disconnect
371
378
  7. **AbortSignal** is wired through to `notifications/cancelled` for clean cancellation
372
379
  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
@@ -388,15 +395,13 @@ Implements the **MCP 2025-03-26** specification for tool and resource clients:
388
395
  | Cursor-based `resources/list` and `resources/templates/list` pagination | ✅ |
389
396
  | `resources/read` with text, image blobs, and binary size summaries | ✅ |
390
397
  | `notifications/resources/list_changed` (catalog invalidation) | ✅ |
391
- | `tools/call` with parameters, `image` (`ImageContent`), `structuredContent`, and `resource` conversion | ✅ |
398
+ | `tools/call` with parameters, `image` (`ImageContent`), `structuredContent`, `resource`, and `resource_link` conversion | ✅ |
392
399
  | `roots/list` capability (workspace root) | ✅ |
393
400
  | `notifications/tools/list_changed` (live refresh) | ✅ |
394
401
  | `notifications/cancelled` (AbortSignal) | ✅ |
395
402
  | `notifications/message` (structured logging) | ✅ |
396
403
  | `isError: true` distinction (protocol vs tool errors, non-text filtered on error) | ✅ |
397
404
  | Tool annotations (`readOnlyHint`, `destructiveHint`, etc.) | ✅ |
398
- | Prompts bridge | ⏳ v2 |
399
- | Sampling | ⏳ v2 |
400
405
 
401
406
  ## Contributing / Architecture
402
407
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.12.3",
3
+ "version": "1.13.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": [
@@ -43,6 +43,7 @@
43
43
  "typebox": "*"
44
44
  },
45
45
  "overrides": {
46
+ "minimatch": "^11.0.4",
46
47
  "undici": "^8.12.3"
47
48
  },
48
49
  "devDependencies": {
package/src/index.ts CHANGED
@@ -34,6 +34,7 @@ import { registerCommands } from "./register-commands.js";
34
34
  import { ServerManager, type ManagedServer } from "./server-manager.js";
35
35
  import {
36
36
  collectServerStatus,
37
+ getServerInstructions,
37
38
  toStatusRow,
38
39
  type ServerStatusRow,
39
40
  } from "./server-status.js";
@@ -491,7 +492,10 @@ function registerManagementTools(
491
492
  if (activity.active !== activity.discovered) {
492
493
  throw new Error("MCP server connected, but some discovered tools are inactive. Check Pi tool restrictions or extension conflicts; mcp_status reports discovered and active counts.");
493
494
  }
494
- return { content: [{ type: "text", text: `MCP server ${name} ready; tools discovered and active.` }], details: {} };
495
+ const instructions = getServerInstructions(manager.getServer(name));
496
+ const ready = `MCP server ${name} ready; tools discovered and active.`;
497
+ const text = instructions === undefined ? ready : `${ready}\nInstructions: ${instructions}`;
498
+ return { content: [{ type: "text", text }], details: {} };
495
499
  },
496
500
  });
497
501
 
@@ -261,7 +261,12 @@ export function convertResourceContents(contents: readonly unknown[]): PiResourc
261
261
  return contents.map(convertResourceContent);
262
262
  }
263
263
 
264
- function convertResourceContent(item: unknown): PiResourceContent {
264
+ function resolveResourceUri(raw: unknown): string {
265
+ const trimmed = typeof raw === "string" ? raw.trim() : "";
266
+ return trimmed.length > 0 ? trimmed : "unknown";
267
+ }
268
+
269
+ export function convertResourceContent(item: unknown): PiResourceContent {
265
270
  if (typeof item !== "object" || item === null) {
266
271
  return { type: "text", text: String(item) };
267
272
  }
@@ -274,7 +279,7 @@ function convertResourceContent(item: unknown): PiResourceContent {
274
279
  if (typeof entry["blob"] === "string") {
275
280
  return convertBlobResource(entry);
276
281
  }
277
- return { type: "text", text: `[Resource: ${String(entry["uri"] ?? "unknown")}]` };
282
+ return { type: "text", text: `[Resource: ${resolveResourceUri(entry["uri"])}]` };
278
283
  }
279
284
 
280
285
  function resolveBlobMimeType(raw: unknown): string {
@@ -283,9 +288,9 @@ function resolveBlobMimeType(raw: unknown): string {
283
288
  }
284
289
 
285
290
  function convertBlobResource(entry: Record<string, unknown>): PiResourceContent {
286
- const uri = String(entry["uri"] ?? "unknown");
291
+ const uri = resolveResourceUri(entry["uri"]);
287
292
  const mimeType = resolveBlobMimeType(entry["mimeType"]);
288
- const blob = String(entry["blob"]);
293
+ const blob = entry["blob"] as string;
289
294
  if (mimeType.startsWith("image/")) {
290
295
  return { type: "image", data: blob, mimeType };
291
296
  }
@@ -2,13 +2,13 @@
2
2
  * Per-server status snapshots shared by `/mcp <name>` and the `mcp_status` tool.
3
3
  *
4
4
  * `collectServerStatus` gathers connection state, tool activation counts, the OAuth
5
- * credential summary, and config provenance in one place; `formatServerDetail` renders
5
+ * credential summary, server instructions, and config provenance in one place; `formatServerDetail` renders
6
6
  * the `/mcp <name>` view and `toStatusRow` renders an `mcp_status` row from the same
7
7
  * snapshot, so the command and the tool can never drift apart.
8
8
  */
9
9
 
10
10
  import type { ServerConfig } from "./config.js";
11
- import { describeError, reportDiagnostic, sanitizeLogText } from "./debug-log.js";
11
+ import { describeError, redactSecrets, reportDiagnostic, sanitizeLogText } from "./debug-log.js";
12
12
  import { McpError } from "./errors.js";
13
13
  import { AuthLockError, AuthRequiredError } from "./oauth-provider.js";
14
14
  import type { ManagedServer } from "./server-manager.js";
@@ -38,6 +38,8 @@ export interface ServerStatusSnapshot {
38
38
  lastError: Error | null;
39
39
  /** Recent sanitized stderr output, or the caller's "(no stderr output)" note. */
40
40
  recentOutput: string;
41
+ /** Sanitized initialize-handshake guidance, only while the server is ready. */
42
+ instructions?: string | undefined;
41
43
  }
42
44
 
43
45
  export interface ServerStatusRow {
@@ -48,6 +50,7 @@ export interface ServerStatusRow {
48
50
  auth: string;
49
51
  error: string | undefined;
50
52
  source: ServerConfigSource | "unknown";
53
+ instructions?: string | undefined;
51
54
  }
52
55
 
53
56
  export interface CollectServerStatusParams {
@@ -113,6 +116,7 @@ function isDefined(value: string | undefined): value is string {
113
116
 
114
117
  /** `/mcp <name>` detail view: config provenance, tool counts, credentials, and next steps. */
115
118
  export function formatServerDetail(snapshot: ServerStatusSnapshot, provenance: ConfigProvenance): string {
119
+ const instructions = sanitizeServerInstructions(snapshot.instructions);
116
120
  const lines: Array<string | undefined> = [
117
121
  `Server: ${sanitizeTerminalText(snapshot.name)}`,
118
122
  `State: ${snapshot.state}`,
@@ -121,6 +125,7 @@ export function formatServerDetail(snapshot: ServerStatusSnapshot, provenance: C
121
125
  `Lifecycle: ${snapshot.lifecycle}`,
122
126
  `Source: ${formatServerSource(snapshot.source)}`,
123
127
  `Tools: ${snapshot.tools.active}/${snapshot.tools.discovered} active`,
128
+ instructions === undefined ? undefined : `Instructions: ${instructions}`,
124
129
  snapshot.auth === undefined ? undefined : `OAuth: ${snapshot.auth}`,
125
130
  formatProjectConfigNote(provenance),
126
131
  // WHY: a connect/stream failure usually quotes the request URL, and that URL can carry a
@@ -133,6 +138,7 @@ export function formatServerDetail(snapshot: ServerStatusSnapshot, provenance: C
133
138
 
134
139
  /** `mcp_status` row for one server. */
135
140
  export function toStatusRow(snapshot: ServerStatusSnapshot): ServerStatusRow {
141
+ const instructions = sanitizeServerInstructions(snapshot.instructions);
136
142
  return {
137
143
  name: snapshot.name,
138
144
  lifecycle: snapshot.lifecycle,
@@ -141,6 +147,7 @@ export function toStatusRow(snapshot: ServerStatusSnapshot): ServerStatusRow {
141
147
  auth: snapshot.auth ?? "not configured",
142
148
  error: formatStatusError(snapshot.lastError),
143
149
  source: formatServerSource(snapshot.source),
150
+ ...(instructions === undefined ? {} : { instructions }),
144
151
  };
145
152
  }
146
153
 
@@ -169,8 +176,27 @@ async function summarizeAuth(params: CollectServerStatusParams): Promise<string
169
176
  }
170
177
  }
171
178
 
179
+ /**
180
+ * Sanitize raw MCP initialize-handshake instructions: strip terminal escapes,
181
+ * redact credential-shaped substrings, and bound to 500 UTF-16 code units.
182
+ */
183
+ export function sanitizeServerInstructions(raw: unknown): string | undefined {
184
+ if (typeof raw !== "string") return undefined;
185
+ // WHY: remove escapes before redaction so they cannot hide a credential key;
186
+ // bound the redacted result so masking cannot grow it beyond the UI budget.
187
+ const cleaned = sanitizeTerminalText(raw, { maxLength: raw.length }).trim();
188
+ return sanitizeTerminalText(redactSecrets(cleaned), { maxLength: 500 }).trim() || undefined;
189
+ }
190
+
191
+ /** Read and sanitize handshake instructions from a ready server. */
192
+ export function getServerInstructions(server: ManagedServer | undefined): string | undefined {
193
+ if (server?.state !== "ready") return undefined;
194
+ return sanitizeServerInstructions(server.client?.getInstructions());
195
+ }
196
+
172
197
  export async function collectServerStatus(params: CollectServerStatusParams): Promise<ServerStatusSnapshot> {
173
198
  const { server } = params;
199
+ const instructions = getServerInstructions(server);
174
200
  return {
175
201
  name: server.name,
176
202
  state: server.state,
@@ -182,5 +208,6 @@ export async function collectServerStatus(params: CollectServerStatusParams): Pr
182
208
  auth: await summarizeAuth(params),
183
209
  lastError: server.lastError,
184
210
  recentOutput: params.recentOutput ?? "",
211
+ ...(instructions === undefined ? {} : { instructions }),
185
212
  };
186
213
  }
@@ -9,7 +9,7 @@
9
9
  * - AbortSignal → SDK's built-in cancellation (notifications/cancelled)
10
10
  * - Protocol error vs tool execution error distinction
11
11
  * - Activate/deactivate pattern (register once, toggle on server state change)
12
- * - Image content → ImageContent passthrough; audio/resource → text description
12
+ * - Images and embedded image resources → ImageContent; resource links → read hints
13
13
  */
14
14
 
15
15
  import { createHash } from "node:crypto";
@@ -21,6 +21,7 @@ import type { Settings } from "./config.js";
21
21
  import { isCancellationError, isOAuthUnauthorizedError, isSdkTimeoutError } from "./connect-policy.js";
22
22
  import { convertJsonSchemaToTypebox } from "./schema-convert.js";
23
23
  import { listAllTools, type McpToolDefinition } from "./tool-discovery.js";
24
+ import { convertResourceContent } from "./resource-bridge.js";
24
25
 
25
26
  // ─── Types ────────────────────────────────────────────────────────────────────
26
27
 
@@ -69,13 +70,31 @@ export function buildToolName(
69
70
  type PiTextContent = { type: "text"; text: string };
70
71
  type PiImageContent = { type: "image"; data: string; mimeType: string };
71
72
 
72
- function convertResourceContent(obj: Record<string, unknown>): PiTextContent {
73
- const r = obj["resource"] as Record<string, unknown> | undefined;
74
- // WHY: Check `typeof r?.["text"] === "string"` rather than truthiness so
75
- // empty text resources (`text: ""`) are preserved as `""` instead of `[Resource: uri]`.
76
- if (typeof r?.["text"] === "string") return { type: "text", text: r["text"] };
77
- if (r?.["blob"]) return { type: "text", text: `[Resource blob: ${String(r["uri"])}]` };
78
- return { type: "text", text: `[Resource: ${String(r?.["uri"] ?? "unknown")}]` };
73
+ function pickNonEmptyText(value: unknown): string | undefined {
74
+ if (typeof value !== "string") return undefined;
75
+ const trimmed = value.trim();
76
+ return trimmed.length > 0 ? trimmed : undefined;
77
+ }
78
+
79
+ function convertResourceLink(obj: Record<string, unknown>): PiTextContent {
80
+ const uri = pickNonEmptyText(obj["uri"]) ?? "unknown";
81
+ const title = pickNonEmptyText(obj["title"]) ?? pickNonEmptyText(obj["name"]);
82
+ const label = title ? ` ${JSON.stringify(title)}` : "";
83
+ const details: string[] = [];
84
+ const mimeType = pickNonEmptyText(obj["mimeType"]);
85
+ if (mimeType) {
86
+ details.push(mimeType);
87
+ }
88
+ if (typeof obj["size"] === "number" && Number.isSafeInteger(obj["size"]) && obj["size"] >= 0) {
89
+ details.push(`${obj["size"]} bytes`);
90
+ }
91
+ const metadata = details.length > 0 ? ` (${details.join(", ")})` : "";
92
+ const descriptionText = pickNonEmptyText(obj["description"]);
93
+ const description = descriptionText ? `\n${descriptionText}` : "";
94
+ return {
95
+ type: "text",
96
+ text: `[Resource link: ${uri}${label}${metadata} — Use mcp_read_resource to read]${description}`,
97
+ };
79
98
  }
80
99
 
81
100
  function convertNonTextContent(obj: Record<string, unknown>): PiImageContent | PiTextContent | undefined {
@@ -93,9 +112,10 @@ function convertNonTextContent(obj: Record<string, unknown>): PiImageContent | P
93
112
  };
94
113
  }
95
114
  if (obj["type"] === "resource") {
96
- return convertResourceContent(obj);
115
+ const resource = obj["resource"];
116
+ return convertResourceContent(typeof resource === "object" && resource !== null ? resource : {});
97
117
  }
98
- return undefined;
118
+ return obj["type"] === "resource_link" ? convertResourceLink(obj) : undefined;
99
119
  }
100
120
 
101
121
  function convertMcpContentItem(item: unknown): PiTextContent | PiImageContent {