pi-mcp-extension 1.12.4 → 1.14.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/images/binary blobs, `resource_link` hints, 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 and passed to Pi as structured tool `annotations` (boolean hints only), so permission extensions can inspect them
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
  {
@@ -394,7 +401,7 @@ Implements the **MCP 2025-03-26** specification for tool and resource clients:
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
- | Tool annotations (`readOnlyHint`, `destructiveHint`, etc.) | ✅ |
404
+ | Tool annotations (`readOnlyHint`, `destructiveHint`, etc.) in descriptions and as structured Pi `annotations` | ✅ |
398
405
 
399
406
  ## Contributing / Architecture
400
407
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-mcp-extension",
3
- "version": "1.12.4",
3
+ "version": "1.14.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/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
 
@@ -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
  }
@@ -5,7 +5,7 @@
5
5
  * - Paginated tools/list (cursor loop per spec)
6
6
  * - JSON Schema → TypeBox conversion (common types + Type.Any() fallback)
7
7
  * - Tool name sanitization (Pi-compatible identifiers)
8
- * - Tool annotations → description hints
8
+ * - Tool annotations → description hints + structured Pi `annotations`
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)
@@ -15,7 +15,7 @@
15
15
  import { createHash } from "node:crypto";
16
16
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
17
17
  import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
18
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
18
+ import type { ExtensionAPI, ToolAnnotations } from "@earendil-works/pi-coding-agent";
19
19
  import { McpError, AuthCancelledError } from "./errors.js";
20
20
  import type { Settings } from "./config.js";
21
21
  import { isCancellationError, isOAuthUnauthorizedError, isSdkTimeoutError } from "./connect-policy.js";
@@ -173,6 +173,30 @@ function buildToolDescription(
173
173
  return hints.length > 0 ? `${description} [${hints.join(", ")}]` : description;
174
174
  }
175
175
 
176
+ const ANNOTATION_HINT_KEYS = [
177
+ "readOnlyHint",
178
+ "destructiveHint",
179
+ "idempotentHint",
180
+ "openWorldHint",
181
+ ] as const;
182
+
183
+ /**
184
+ * Build the structured `annotations` Pi reads from a registered tool, so permission extensions
185
+ * can inspect the hints. Copies only the four boolean hints (keeping `false`), ignores `title`
186
+ * and non-boolean values, and returns `undefined` when none apply so the field is omitted.
187
+ */
188
+ function buildToolAnnotations(
189
+ annotations: McpToolDefinition["annotations"],
190
+ ): ToolAnnotations | undefined {
191
+ if (!annotations) return undefined;
192
+ const result: ToolAnnotations = {};
193
+ for (const key of ANNOTATION_HINT_KEYS) {
194
+ const value = annotations[key];
195
+ if (typeof value === "boolean") result[key] = value;
196
+ }
197
+ return Object.keys(result).length > 0 ? result : undefined;
198
+ }
199
+
176
200
  /** Call tools/call through the typed helper when present, else a raw JSON-RPC request. */
177
201
  function callToolWithClient(
178
202
  client: Client,
@@ -484,6 +508,7 @@ export class ToolBridge {
484
508
  ): void {
485
509
  const annotations = tool.annotations;
486
510
  const description = buildToolDescription(tool, annotations);
511
+ const toolAnnotations = buildToolAnnotations(annotations);
487
512
  const runTool = (params: unknown, signal: AbortSignal | undefined) =>
488
513
  this._executeToolCall(serverName, tool.name, client, params, signal);
489
514
  // WHY: `execute` runs with `this` bound to the registered-tool literal rather than the
@@ -497,6 +522,7 @@ export class ToolBridge {
497
522
  description,
498
523
  promptSnippet: description.slice(0, 120),
499
524
  parameters: convertJsonSchemaToTypebox(tool.inputSchema),
525
+ ...(toolAnnotations ? { annotations: toolAnnotations } : {}),
500
526
 
501
527
  async execute(_toolCallId, params, signal, _onUpdate, _ctx) {
502
528
  try {