pi-mcp-adapter 2.23.0 → 2.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -7,6 +7,31 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.25.0] - 2026-08-13
11
+
12
+ ### Added
13
+ - Added `settings.notifyOnStartupConnect` to suppress successful MCP startup connection notices. Thanks @pierre-mgmt for issue #341.
14
+ - Added compact self-rendered MCP proxy and direct-tool result rows by default, with `settings.toolResultRendering: "boxed"` for the legacy boxed row and `settings.collapsedResultLines` for 1-3 collapsed result lines. Thanks @pierre-mgmt for issue #349.
15
+
16
+ ### Changed
17
+ - Removed unused TypeScript declarations found by stricter compiler checks.
18
+
19
+ ### Fixed
20
+ - Kept `mcpScript` tool-call replies flowing when Pi runs as a Bun-compiled binary by starting worker execution without module-level top-level await. Thanks @AndreiKopylov for issue #340 and @thesobercoder for the verified fix.
21
+ - Fixed direct-tool server prefixes to preserve provider-valid underscores and hyphens, including `codebase-memory-mcp`, while retaining safe escaping, collision handling, and exact proxy routing. Thanks @mightymatth for issue #342 and @JasonLandbridge for issue #343.
22
+
23
+ ## [2.24.0] - 2026-08-13
24
+
25
+ ### Added
26
+ - Added per-server `searchKeywords` so `mcp({ search })` and `mcpScript` `tools.search` understand user-defined synonyms and aliases for tools. Keywords are keyed by tool name or glob and boost ranked and regex search only. They never appear in tool schemas, describe output, or the metadata cache. Thanks @Serisium for PR #336.
27
+
28
+ ### Fixed
29
+ - Interpolated environment placeholders in stdio server arguments. Thanks @vjik for issue #333.
30
+ - Kept remote `/mcp-auth` authorization links reachable before the callback input opens. Thanks @trevorleibert-mixpanel for PR #331.
31
+ - Cached OAuth credentials in memory and refreshed them after OAuth-backed 401 responses. Thanks @daniel-sampliner for PR #335.
32
+ - Sanitized MCP server-name prefixes for provider-safe tool names while preserving server resolution. Thanks @triple-dex for issue #334.
33
+ - Validated persisted npx resolver cache entries before reuse, including malformed and prototype-sensitive persisted keys.
34
+
10
35
  ## [2.23.0] - 2026-08-11
11
36
 
12
37
  ### Added
package/README.md CHANGED
@@ -227,6 +227,7 @@ In the configuration examples below, `30000` is illustrative only. If `requestTi
227
227
  | `toolPrefix` | Override global `settings.toolPrefix` for this server (`"server"`, `"short"`, `"none"`, or `"mcp"`) |
228
228
  | `includeTools` | `string[]` of tool names or glob patterns to expose (matches original names like `get_screenshot`, generated resource names like `read_figjam`, and prefixed names like `figma_get_screenshot`) |
229
229
  | `excludeTools` | `string[]` of tool names or glob patterns to hide (applied after `includeTools`) |
230
+ | `searchKeywords` | `{ "tool-or-glob": ["keyword", ...] }` — extra keywords that boost `mcp({ search })` ranking for matching tools; never shown to the model |
230
231
  | `debug` | Show server stderr (default: false) |
231
232
  | `trace` | Enable metadata-only JSONL protocol tracing for this server; payloads, prompts, tool arguments/results, authorization data, and URLs are never persisted |
232
233
  | `disabled` | Keep the server visible in config and status, but prevent connections, authentication, tools, and resource calls (only literal `true` disables it) |
@@ -265,7 +266,7 @@ The adapter owns only its client socket and closes that connection when the Pi r
265
266
 
266
267
  ### Remote/headless OAuth
267
268
 
268
- If Pi is running on a remote server, `/mcp-auth <server>` prints the authorization URL and opens a callback input. Open the URL in your local browser. After approval, the browser may fail to load the localhost callback page because localhost refers to your workstation; copy the full URL from its address bar and paste it into Pi. The input closes automatically instead when the browser can reach Pi's callback directly.
269
+ If Pi is running on a remote server, `/mcp-auth <server>` shows a clickable authorization URL first. Open it in your local browser and approve access, then select **Yes** in Pi to open the callback input. The browser may fail to load the localhost callback page because localhost refers to your workstation; copy the full URL from its address bar and paste it into Pi. The authorization screen closes automatically instead when the browser can reach Pi's callback directly.
269
270
 
270
271
  The same flow is available through the proxy tool for non-interactive clients. Persistent OAuth still requires an available OS credential store; on headless Linux that usually means an unlocked Secret Service/libsecret keyring. The adapter fails closed instead of falling back to plaintext credentials when the secure store is unavailable.
271
272
 
@@ -306,6 +307,9 @@ When any enabled server uses `eager` or `keep-alive`, initialization also starts
306
307
  "requestTimeoutMs": 30000,
307
308
  "showStatusIcon": true,
308
309
  "mcpFooterStatus": "full",
310
+ "toolResultRendering": "compact",
311
+ "collapsedResultLines": 1,
312
+ "notifyOnStartupConnect": true,
309
313
  "hostConfigDiscovery": "off",
310
314
  "approveTools": ["github_delete_*", "notion_update_*"],
311
315
  "oauthDir": ".pi/mcp-oauth",
@@ -327,6 +331,9 @@ When any enabled server uses `eager` or `keep-alive`, initialization also starts
327
331
  | `requestTimeoutMs` | Global request timeout in milliseconds for live MCP calls (if omitted or `<= 0`, the MCP SDK default timeout is used) |
328
332
  | `showStatusIcon` | Show the plug icon in MCP status and connection text (default: `true`). Set to `false` for plain `MCP: ...` text. |
329
333
  | `mcpFooterStatus` | MCP footer verbosity: `"full"` (default), `"compact"` for `MCP connected/enabled`, or `"off"` to clear the persistent footer status. `/mcp status` remains available. |
334
+ | `toolResultRendering` | MCP tool result row style: `"compact"` (default) uses self-rendered rows, or `"boxed"` restores the legacy Pi boxed tool row. |
335
+ | `collapsedResultLines` | Number of result text lines to show before expansion: `1`, `2`, or `3`. Defaults to `1` in compact mode and `3` in boxed mode. |
336
+ | `notifyOnStartupConnect` | Show successful startup connection notices (default: `true`). Set to `false` to suppress routine `MCP: N servers connected (M tools)` notices. Connection errors and authentication warnings remain visible. |
330
337
  | `hostConfigDiscovery` | Host-specific config policy: `"off"` (default), `"prompt"` (detect/report only), or `"on"` (explicitly load detected host configs as the lowest-precedence fallback) |
331
338
  | `agentPluginPaths` | Agent Plugins package directories to load MCP servers from. Relative paths resolve from the active project cwd. |
332
339
  | `approveTools` | `true` to require approval before every MCP tool call, or an array of glob patterns such as `["github_delete_*", "notion_update_*"]`. Per-server `approveTools` overrides this. |
@@ -648,12 +655,35 @@ Prefer `.mcp.json` for project-local shared MCP config. Use `.pi/mcp.json` only
648
655
 
649
656
  `mcp({ connect: "server-name" })` refreshes an already connected server, so new tools, resources, prompts, and instructions can load without restarting Pi.
650
657
 
651
- MCP proxy and direct-tool results render compactly by default: long text shows the first three terminal-wrapped lines plus a `Ctrl+O to expand` hint, while the full result remains available when expanded and is still returned unchanged to the model.
658
+ MCP proxy and direct-tool results use compact self-rendered rows by default. Collapsed success output shows the call title and the first result line, with a `Ctrl+O to expand` hint when more text is hidden. The full result remains available when expanded and is still returned unchanged to the model. Set `settings.toolResultRendering` to `"boxed"` to restore the legacy boxed Pi row, or set `settings.collapsedResultLines` to `2` or `3` when you want more collapsed text.
652
659
 
653
- Search includes both MCP tools and Pi tools (from extensions). Pi tools appear first with `[pi tool]` prefix. Space-separated words are ranked by weighted matches across name, server, and description, then returned one page at a time (`limit` defaults to 12). Use `details.nextOffset` for the next page. Regex search is still available with `regex: true`, but regex results are paginated without ranking.
660
+ Search includes both MCP tools and Pi tools (from extensions). Pi tools appear first with `[pi tool]` prefix. Space-separated words are ranked by weighted matches across name, server, description, and any configured `searchKeywords`, then returned one page at a time (`limit` defaults to 12). Use `details.nextOffset` for the next page. Regex search is still available with `regex: true`, but regex results are paginated without ranking.
654
661
 
655
662
  Tool names are fuzzy-matched on hyphens and underscores — `context7_resolve_library_id` finds `context7_resolve-library-id`. When `describe` or `tool` cannot resolve a name, the result includes top suggestions so the agent can correct a typo or missing prefix in the same turn.
656
663
 
664
+ ### Search keywords
665
+
666
+ Search uses literal matching so a tool whose name and description use different vocabulary than the query won't be found. Per-server `searchKeywords` adds extra vocabulary for matching tools:
667
+
668
+ ```json
669
+ {
670
+ "mcpServers": {
671
+ "github": {
672
+ "command": "npx",
673
+ "args": ["-y", "@modelcontextprotocol/server-github"],
674
+ "searchKeywords": {
675
+ "search_code": ["grep"],
676
+ "*": ["gh"]
677
+ }
678
+ }
679
+ }
680
+ }
681
+ ```
682
+
683
+ With this config, `mcp({ search: "grep" })` finds `github_search_code` even though neither its name nor description contains that word. Similarly, `mcp({ search: "gh" })` finds all tools provided by the github server.
684
+
685
+ Keys match a tool's original name, prefixed name, or a glob (`*` applies to every tool on the server) and all matching entries combine. Keywords are weighted like description text, with an extra boost when the query exactly matches a configured phrase. They affect ranked and regex search only (including `tools.search` in `mcpScript`): they never appear in tool schemas, `describe` output, direct-tool registration, or the metadata cache, and search with keywords works offline from cached metadata.
686
+
657
687
  When `includeSchemas` is enabled, search and describe render common JSON Schema parameters as compact TypeScript shapes like `{ query: string; limit?: number; }`, with the older schema formatter retained as a fallback for unsupported schemas.
658
688
 
659
689
  For HTTP servers, failed connects run a one-request shape probe that can turn opaque transport errors into setup hints such as `endpoint returned HTML (200) — this URL does not appear to speak MCP`. Healthy connections are not probed.
@@ -699,4 +729,5 @@ Advertised tool `outputSchema` values support JSON Schema draft-07 and 2020-12.
699
729
 
700
730
  - Cross-session server sharing not yet implemented (each Pi session runs its own server processes)
701
731
  - Compact MCP result rendering summarizes text, but inline images are still controlled by Pi's image display settings and may render below the compact text summary.
732
+ - Pi still owns one separator row before self-rendered tool output, so compact mode reduces adapter rendering height but cannot promise true zero-gap rows.
702
733
  - MCP sampling support is text-only; context inclusion, tools, stop sequences, audio, and image content are rejected with explicit errors.
@@ -1,4 +1,4 @@
1
- import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
1
+ import { existsSync, readFileSync, statSync } from "node:fs";
2
2
  import { isAbsolute, relative, resolve, sep } from "node:path";
3
3
  import { getAgentPath } from "./agent-dir.ts";
4
4
  import type { McpConfig, ServerEntry } from "./types.ts";
package/commands.ts CHANGED
@@ -12,7 +12,6 @@ import {
12
12
  previewSharedServerEntry,
13
13
  previewStarterProjectConfig,
14
14
  writeDirectToolsConfig,
15
- writeProjectServerDisabledOverride,
16
15
  writeSharedServerEntry,
17
16
  writeStarterProjectConfig,
18
17
  } from "./config.ts";
@@ -170,7 +169,7 @@ export async function reconnectServer(
170
169
  }
171
170
 
172
171
  const prefix = state.config.settings?.toolPrefix ?? "server";
173
- const { metadata, failedTools } = buildToolMetadata(connection.tools, connection.resources, definition, name, prefix);
172
+ const { metadata, failedTools } = buildToolMetadata(connection.tools, connection.resources, definition, name, prefix, state.config.mcpServers, state.toolMetadata);
174
173
  state.toolMetadata.set(name, metadata);
175
174
  if (!connection.promptDiscoveryFailed) {
176
175
  state.promptMetadata?.set(name, reconstructPromptMetadata(name, connection.prompts ?? [], prefix, definition));
@@ -283,11 +282,20 @@ export async function authenticateServer(
283
282
  "info"
284
283
  );
285
284
  },
286
- onAuthorizationInput: (_authorizationUrl, inputSignal) => ui.input(
287
- `Complete ${serverName} OAuth`,
288
- "Paste the full callback URL, or wait for automatic completion",
289
- { signal: inputSignal },
290
- ),
285
+ onAuthorizationInput: async (authorizationUrl, inputSignal) => {
286
+ const readyToPaste = await ui.confirm(
287
+ `Authorize ${serverName}`,
288
+ `Open this link in your browser:\n${terminalHyperlink(authorizationUrl, authorizationUrl)}\n\n` +
289
+ "After approving access, select Yes to paste the callback URL.",
290
+ { signal: inputSignal },
291
+ );
292
+ if (!readyToPaste || inputSignal.aborted) return undefined;
293
+ return ui.input(
294
+ `Complete ${serverName} OAuth`,
295
+ "Paste the full callback URL",
296
+ { signal: inputSignal },
297
+ );
298
+ },
291
299
  ...(signal ? { signal } : {}),
292
300
  ...(runtime ? { runtime } : {}),
293
301
  });
package/direct-tools.ts CHANGED
@@ -11,7 +11,8 @@ import { formatSchema } from "./tool-metadata.ts";
11
11
  import { resolveMcpResultContent, transformMcpContent, transformMcpResourceContents } from "./tool-registrar.ts";
12
12
  import { guardMcpOutput, guardedMcpDetails, resolveMcpOutputGuardOptions } from "./mcp-output-guard.ts";
13
13
  import { maybeStartUiSession, summarizeUiSessionResult, type UiSessionRuntime } from "./ui-session.ts";
14
- import { formatToolName, isServerDisabled, isToolAllowed, resolveToolPrefix } from "./types.ts";
14
+ import { formatToolName, getToolNameCandidates, isServerDisabled, isToolAllowed, resolveToolPrefix } from "./types.ts";
15
+ import { isUiToolVisibleToModel } from "./ui-tool-visibility.ts";
15
16
  import { resourceNameToToolName } from "./resource-tools.ts";
16
17
  import { authenticate, supportsOAuth } from "./mcp-auth-flow.ts";
17
18
  import { formatAuthRequiredMessage, resolveServerUrl, truncateAtWord } from "./utils.ts";
@@ -149,10 +150,31 @@ export function resolveDirectTools(
149
150
  if (!toolFilter) continue;
150
151
 
151
152
  const effectivePrefix = resolveToolPrefix(definition, prefix);
153
+ const getOtherCurrentCandidates = (toolName: string): Set<string> => {
154
+ const candidates = new Set<string>();
155
+ for (const [otherServerName, otherDefinition] of Object.entries(config.mcpServers)) {
156
+ const otherCache = cache.servers[otherServerName];
157
+ if (!otherCache || !isServerCacheValid(otherCache, otherDefinition) || isServerDisabled(otherDefinition)) continue;
158
+ const otherPrefix = resolveToolPrefix(otherDefinition, prefix);
159
+ for (const otherTool of otherCache.tools ?? []) {
160
+ if (!isUiToolVisibleToModel(otherTool.uiVisibility)) continue;
161
+ for (const candidate of getToolNameCandidates(otherTool.name, otherServerName, otherPrefix, false)) candidates.add(candidate);
162
+ }
163
+ if (otherDefinition.exposeResources !== false) {
164
+ for (const resource of otherCache.resources ?? []) {
165
+ const baseName = `read_${resourceNameToToolName(resource.name)}`;
166
+ for (const candidate of getToolNameCandidates(baseName, otherServerName, otherPrefix, false)) candidates.add(candidate);
167
+ }
168
+ }
169
+ }
170
+ for (const candidate of getToolNameCandidates(toolName, serverName, effectivePrefix, false)) candidates.delete(candidate);
171
+ return candidates;
172
+ };
152
173
 
153
174
  for (const tool of serverCache.tools ?? []) {
175
+ if (!isUiToolVisibleToModel(tool.uiVisibility)) continue;
154
176
  if (toolFilter !== true && !toolFilter.includes(tool.name)) continue;
155
- if (!isToolAllowed(tool.name, serverName, effectivePrefix, definition.includeTools, definition.excludeTools)) continue;
177
+ if (!isToolAllowed(tool.name, serverName, effectivePrefix, definition.includeTools, definition.excludeTools, getOtherCurrentCandidates(tool.name))) continue;
156
178
  const prefixedName = formatToolName(tool.name, serverName, effectivePrefix);
157
179
  if (BUILTIN_NAMES.has(prefixedName)) {
158
180
  console.warn(`MCP: skipping direct tool "${prefixedName}" (collides with builtin)`);
@@ -178,7 +200,7 @@ export function resolveDirectTools(
178
200
  for (const resource of serverCache.resources ?? []) {
179
201
  const baseName = `read_${resourceNameToToolName(resource.name)}`;
180
202
  if (toolFilter !== true && !toolFilter.includes(baseName)) continue;
181
- if (!isToolAllowed(baseName, serverName, effectivePrefix, definition.includeTools, definition.excludeTools)) continue;
203
+ if (!isToolAllowed(baseName, serverName, effectivePrefix, definition.includeTools, definition.excludeTools, getOtherCurrentCandidates(baseName))) continue;
182
204
  const prefixedName = formatToolName(baseName, serverName, effectivePrefix);
183
205
  if (BUILTIN_NAMES.has(prefixedName)) {
184
206
  console.warn(`MCP: skipping direct resource tool "${prefixedName}" (collides with builtin)`);
@@ -230,15 +252,38 @@ export function buildProxyDescription(
230
252
  for (const serverName of Object.keys(config.mcpServers)) {
231
253
  const definition = config.mcpServers[serverName];
232
254
  if (!definition || isServerDisabled(definition)) continue;
233
- const entry = cache?.servers?.[serverName];
255
+ const cachedEntry = cache?.servers?.[serverName];
256
+ const entry = cachedEntry && isServerCacheValid(cachedEntry, definition) ? cachedEntry : undefined;
234
257
  const effectivePrefix = resolveToolPrefix(definition, prefix);
258
+ const getOtherCurrentCandidates = (toolName: string): Set<string> | undefined => {
259
+ if (!cache) return undefined;
260
+ const candidates = new Set<string>();
261
+ for (const [otherServerName, otherDefinition] of Object.entries(config.mcpServers)) {
262
+ const otherEntry = cache.servers[otherServerName];
263
+ if (!otherEntry || !isServerCacheValid(otherEntry, otherDefinition) || isServerDisabled(otherDefinition)) continue;
264
+ const otherPrefix = resolveToolPrefix(otherDefinition, prefix);
265
+ for (const otherTool of otherEntry.tools ?? []) {
266
+ if (!isUiToolVisibleToModel(otherTool.uiVisibility)) continue;
267
+ for (const candidate of getToolNameCandidates(otherTool.name, otherServerName, otherPrefix, false)) candidates.add(candidate);
268
+ }
269
+ if (otherDefinition.exposeResources !== false) {
270
+ for (const resource of otherEntry.resources ?? []) {
271
+ const baseName = `read_${resourceNameToToolName(resource.name)}`;
272
+ for (const candidate of getToolNameCandidates(baseName, otherServerName, otherPrefix, false)) candidates.add(candidate);
273
+ }
274
+ }
275
+ }
276
+ for (const candidate of getToolNameCandidates(toolName, serverName, effectivePrefix, false)) candidates.delete(candidate);
277
+ return candidates;
278
+ };
235
279
  const toolCount = (entry?.tools ?? []).filter(
236
- (tool) => isToolAllowed(tool.name, serverName, effectivePrefix, definition.includeTools, definition.excludeTools),
280
+ (tool) => isUiToolVisibleToModel(tool.uiVisibility)
281
+ && isToolAllowed(tool.name, serverName, effectivePrefix, definition.includeTools, definition.excludeTools, getOtherCurrentCandidates(tool.name)),
237
282
  ).length;
238
283
  const resourceCount = definition?.exposeResources !== false
239
284
  ? (entry?.resources ?? []).filter((resource) => {
240
285
  const baseName = `read_${resourceNameToToolName(resource.name)}`;
241
- return isToolAllowed(baseName, serverName, effectivePrefix, definition.includeTools, definition.excludeTools);
286
+ return isToolAllowed(baseName, serverName, effectivePrefix, definition.includeTools, definition.excludeTools, getOtherCurrentCandidates(baseName));
242
287
  }).length
243
288
  : 0;
244
289
  const totalItems = toolCount + resourceCount;
@@ -264,7 +309,9 @@ export function buildProxyDescription(
264
309
  const instructionSummaries: string[] = [];
265
310
  for (const serverName of Object.keys(config.mcpServers)) {
266
311
  if (isServerDisabled(config.mcpServers[serverName])) continue;
267
- const instructions = cache?.servers?.[serverName]?.instructions;
312
+ const definition = config.mcpServers[serverName];
313
+ const entry = definition && cache?.servers?.[serverName];
314
+ const instructions = entry && definition && isServerCacheValid(entry, definition) ? entry.instructions : undefined;
268
315
  if (!instructions) continue;
269
316
  const snippet = truncateAtWord(instructions.replace(/\s+/g, " ").trim(), INSTRUCTIONS_SNIPPET_LENGTH);
270
317
  instructionSummaries.push(` ${serverName}: ${snippet}`);
@@ -459,11 +459,3 @@ function escapeHtml(value: string): string {
459
459
  .replace(/"/g, "&quot;")
460
460
  .replace(/'/g, "&#39;");
461
461
  }
462
-
463
- function escapeHtmlAttribute(value: string): string {
464
- return value
465
- .replace(/&/g, "&amp;")
466
- .replace(/"/g, "&quot;")
467
- .replace(/</g, "&lt;")
468
- .replace(/>/g, "&gt;");
469
- }
package/index.ts CHANGED
@@ -14,7 +14,7 @@ import { logger } from "./logger.ts";
14
14
  import { executeAuthComplete, executeAuthStart, executeCall, executeConnect, executeDescribe, executeInstructions, executeList, executeSearch, executeStatus, executeUiMessages } from "./proxy-modes.ts";
15
15
  import { formatTerminalError, getConfigPathFromArgv, normalizeDirectToolInputSchema, truncateAtWord } from "./utils.ts";
16
16
  import { createOAuthRuntime, shutdownOAuth } from "./mcp-auth-flow.ts";
17
- import { createMcpDirectToolCallRenderer, renderMcpProxyToolCall, renderMcpToolResult } from "./tool-result-renderer.ts";
17
+ import { createMcpDirectToolCallRenderer, createMcpProxyToolCallRenderer, createMcpToolResultRenderer, resolveMcpToolRenderOptions } from "./tool-result-renderer.ts";
18
18
  import { toolErrorOverride } from "./error-signal.ts";
19
19
  import { createMcpRuntimeOwner, createOwnedUi, isAbortError, type McpRuntimeOwner } from "./runtime-owner.ts";
20
20
  import { publishMcpStatusShutdown } from "./mcp-status.ts";
@@ -124,6 +124,9 @@ function installMcpAdapter(pi: ExtensionAPI, options: McpAdapterOptions) {
124
124
  const envDirectToolOverride = envRaw?.split(",").map(s => s.trim()).filter(Boolean);
125
125
  const registeredDirectTools = new Map<string, string>();
126
126
  const fallbackDeactivatedTools = new Set<string>();
127
+ const toolRenderOptions = resolveMcpToolRenderOptions(earlyConfig.settings);
128
+ const toolRenderShell = toolRenderOptions.resultRendering === "compact" ? "self" : "default";
129
+ const renderMcpToolResult = createMcpToolResultRenderer(toolRenderOptions);
127
130
  let proxyToolRegistered = false;
128
131
  let proxyToolDescription: string | null = null;
129
132
  let directToolsFrozen = false;
@@ -158,7 +161,8 @@ function installMcpAdapter(pi: ExtensionAPI, options: McpAdapterOptions) {
158
161
  promptSnippet: truncateAtWord(spec.description, 100) || `MCP tool from ${spec.serverName}`,
159
162
  parameters: toToolParameters(normalizeDirectToolInputSchema(spec.inputSchema)),
160
163
  execute: createDirectToolExecutor(() => state, () => initPromise, spec),
161
- renderCall: createMcpDirectToolCallRenderer(spec.prefixedName),
164
+ renderShell: toolRenderShell,
165
+ renderCall: createMcpDirectToolCallRenderer(spec.prefixedName, toolRenderOptions),
162
166
  renderResult: renderMcpToolResult,
163
167
  });
164
168
  }
@@ -695,7 +699,8 @@ function installMcpAdapter(pi: ExtensionAPI, options: McpAdapterOptions) {
695
699
  label: "MCP",
696
700
  description,
697
701
  promptSnippet: "MCP gateway — status, search, describe, auth, and single MCP tool calls",
698
- renderCall: renderMcpProxyToolCall,
702
+ renderShell: toolRenderShell,
703
+ renderCall: createMcpProxyToolCallRenderer(toolRenderOptions),
699
704
  parameters: Type.Object({
700
705
  tool: Type.Optional(Type.String({ description: "Tool name to call (e.g., 'xcodebuild_list_sims')" })),
701
706
  args: Type.Optional(Type.Union([
package/init.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import type { McpExtensionState } from "./state.ts";
3
- import { isServerDisabled, type McpAdapterOptions, type PromptMetadata, type ToolMetadata } from "./types.ts";
3
+ import { formatToolName, isServerDisabled, resolveToolPrefix, type McpAdapterOptions, type PromptMetadata, type ToolMetadata } from "./types.ts";
4
4
  import { existsSync } from "node:fs";
5
5
  import { cloneMcpConfig, loadMcpConfig } from "./config.ts";
6
6
  import { ConsentManager } from "./consent-manager.ts";
@@ -21,6 +21,7 @@ import {
21
21
  } from "./metadata-cache.ts";
22
22
  import { McpServerManager } from "./server-manager.ts";
23
23
  import { buildToolMetadata, totalToolCount } from "./tool-metadata.ts";
24
+ import { resourceNameToToolName } from "./resource-tools.ts";
24
25
  import { UiResourceHandler } from "./ui-resource-handler.ts";
25
26
  import { formatMcpStatus, openUrl, parallelLimit, sanitizeTerminalText } from "./utils.ts";
26
27
  import { logger } from "./logger.ts";
@@ -242,7 +243,7 @@ export async function initializeMcp(
242
243
 
243
244
  const cachedEntry = cache?.servers?.[name];
244
245
  if (cachedEntry && isServerCacheValid(cachedEntry, definition)) {
245
- const metadata = reconstructToolMetadata(name, cachedEntry, prefix, definition);
246
+ const metadata = reconstructToolMetadata(name, cachedEntry, prefix, definition, config.mcpServers, cache ?? undefined);
246
247
  toolMetadata.set(name, metadata);
247
248
  if (Array.isArray(cachedEntry.resources)) {
248
249
  resourceCounts.set(name, cachedEntry.resources.length);
@@ -288,6 +289,29 @@ export async function initializeMcp(
288
289
  if (initialSignal?.aborted) return state;
289
290
  owner.throwIfInactive();
290
291
 
292
+ const startupKnownMetadata = new Map<string, ToolMetadata[]>();
293
+ for (const { name, definition, connection } of results) {
294
+ if (!connection) continue;
295
+ const effectivePrefix = resolveToolPrefix(definition, prefix);
296
+ const metadata: ToolMetadata[] = [
297
+ ...connection.tools.filter(tool => tool?.name).map(tool => ({
298
+ name: formatToolName(tool.name, name, effectivePrefix),
299
+ originalName: tool.name,
300
+ description: tool.description ?? "",
301
+ })),
302
+ ...(definition.exposeResources !== false ? connection.resources.filter(resource => resource?.name && resource?.uri).map(resource => {
303
+ const originalName = `read_${resourceNameToToolName(resource.name)}`;
304
+ return {
305
+ name: formatToolName(originalName, name, effectivePrefix),
306
+ originalName,
307
+ description: resource.description ?? `Read resource: ${resource.uri}`,
308
+ resourceUri: resource.uri,
309
+ };
310
+ }) : []),
311
+ ];
312
+ startupKnownMetadata.set(name, metadata);
313
+ }
314
+
291
315
  for (const { name, definition, connection, error } of results) {
292
316
  owner.throwIfInactive();
293
317
  if (error || !connection) {
@@ -301,7 +325,7 @@ export async function initializeMcp(
301
325
  continue;
302
326
  }
303
327
 
304
- const { metadata, failedTools } = buildToolMetadata(connection.tools, connection.resources, definition, name, prefix);
328
+ const { metadata, failedTools } = buildToolMetadata(connection.tools, connection.resources, definition, name, prefix, config.mcpServers, startupKnownMetadata, true);
305
329
  toolMetadata.set(name, metadata);
306
330
  resourceCounts.set(name, connection.resources.length);
307
331
  if (!connection.promptDiscoveryFailed) {
@@ -327,7 +351,7 @@ export async function initializeMcp(
327
351
 
328
352
  const connectedCount = results.filter(r => r.connection).length;
329
353
  const failedCount = results.filter(r => r.error).length;
330
- if (ui && connectedCount > 0) {
354
+ if (ui && connectedCount > 0 && config.settings?.notifyOnStartupConnect !== false) {
331
355
  const totalTools = totalToolCount(state);
332
356
  const msg = failedCount > 0
333
357
  ? `MCP: ${connectedCount}/${startupServers.length} servers connected (${totalTools} tools)`
@@ -437,7 +461,7 @@ export function updateServerMetadata(state: McpExtensionState, serverName: strin
437
461
 
438
462
  const prefix = state.config.settings?.toolPrefix ?? "server";
439
463
 
440
- const { metadata } = buildToolMetadata(connection.tools, connection.resources, definition, serverName, prefix);
464
+ const { metadata } = buildToolMetadata(connection.tools, connection.resources, definition, serverName, prefix, state.config.mcpServers, state.toolMetadata);
441
465
  state.toolMetadata.set(serverName, metadata);
442
466
  state.resourceCounts?.set(serverName, connection.resources.length);
443
467
  if (!connection.promptDiscoveryFailed) {
package/lifecycle.ts CHANGED
@@ -19,7 +19,6 @@ export class McpLifecycleManager {
19
19
  private activeHealthCheck: Promise<void> | undefined;
20
20
  private shutdownPromise: Promise<void> | undefined;
21
21
  private stopped = false;
22
- private healthSignal: AbortSignal | undefined;
23
22
  private removeHealthAbortListener: (() => void) | undefined;
24
23
 
25
24
  constructor(
@@ -58,10 +57,8 @@ export class McpLifecycleManager {
58
57
  const signal = typeof signalOrInterval === "number" ? undefined : signalOrInterval;
59
58
  const intervalMs = typeof signalOrInterval === "number" ? signalOrInterval : maybeIntervalMs;
60
59
  this.stopped = false;
61
- this.healthSignal = signal;
62
60
  if (signal?.aborted) {
63
61
  this.stopped = true;
64
- this.healthSignal = undefined;
65
62
  return;
66
63
  }
67
64
  const stop = () => {
@@ -138,7 +135,6 @@ export class McpLifecycleManager {
138
135
  this.healthCheckInterval = undefined;
139
136
  this.removeHealthAbortListener?.();
140
137
  this.removeHealthAbortListener = undefined;
141
- this.healthSignal = undefined;
142
138
  await this.activeHealthCheck;
143
139
  this.activeHealthCheck = undefined;
144
140
  this.onReconnect = undefined;
package/mcp-auth-flow.ts CHANGED
@@ -633,7 +633,6 @@ export async function completeAuthFromInput(
633
633
  const signal = combineAbortSignals(runtime.signal, options.signal)
634
634
  throwIfAborted(signal)
635
635
  const key = getPendingAuthKey(serverName, fallbackAuthStorageOptions)
636
- const authStorageOptions = runtimeState.pendingAuths.get(key)?.authStorageOptions ?? fallbackAuthStorageOptions
637
636
  const oauthState = runtimeState.pendingAuthStates.get(key)
638
637
  throwIfAborted(signal)
639
638
  const parsed = parseAuthorizationRedirectInput(input, oauthState)
@@ -899,7 +898,7 @@ export async function getValidToken(
899
898
  * @returns The current auth status
900
899
  */
901
900
  export async function getAuthStatus(serverName: string, options: AuthenticateOptions = {}): Promise<AuthStatus> {
902
- const runtime = getRuntime(options)
901
+ getRuntime(options)
903
902
  const authStorageOptions = options.authStorageOptions ?? {}
904
903
  const hasTokens = await hasStoredTokens(serverName, authStorageOptions)
905
904
  if (!hasTokens) return "not_authenticated"
package/mcp-auth.ts CHANGED
@@ -37,6 +37,7 @@ const KEYRING_RECOVERY_KEYCTL_ENV = 'PI_MCP_ADAPTER_KEYRING_RECOVERY_KEYCTL';
37
37
  const KEYRING_RECOVERY_NODE_ENV = 'PI_MCP_ADAPTER_KEYRING_RECOVERY_NODE';
38
38
  const KEYRING_RECOVERY_HELPER_ENV = 'PI_MCP_ADAPTER_KEYRING_RECOVERY_HELPER';
39
39
  const TEST_LINUX_KEYRING_RECOVERY_ENV = 'PI_MCP_ADAPTER_TEST_LINUX_KEYRING_RECOVERY';
40
+ const AUTH_CACHE_DISABLED_ENV = 'PI_MCP_ADAPTER_DISABLE_AUTH_CACHE';
40
41
  const KEYRING_RECOVERY_TIMEOUT_MS = 10_000;
41
42
  const AUTH_CHUNK_MANIFEST_KEY = '__piMcpAdapterOAuthChunked';
42
43
 
@@ -148,8 +149,20 @@ interface AuthEntryChunkManifest {
148
149
  let KeyringEntryClass: KeyringEntryConstructor | undefined;
149
150
  const memoryAuthEntries = new Map<string, string>();
150
151
 
152
+ let testAuthSecretStoreReadCount = 0;
153
+ const authEntryCache = new Map<string, AuthEntry | undefined>();
154
+
155
+ function isAuthEntryCacheEnabled(): boolean {
156
+ return process.env[AUTH_CACHE_DISABLED_ENV] !== '1';
157
+ }
158
+
159
+ function cloneAuthEntry(entry: AuthEntry | undefined): AuthEntry | undefined {
160
+ return entry === undefined ? undefined : structuredClone(entry);
161
+ }
162
+
151
163
  const memoryAuthSecretStore: AuthSecretStore = {
152
164
  read(account) {
165
+ testAuthSecretStoreReadCount++;
153
166
  return memoryAuthEntries.get(account);
154
167
  },
155
168
  write(account, payload) {
@@ -175,6 +188,7 @@ const keyringAuthSecretStore: AuthSecretStore = {
175
188
  /** Mimics the Windows Credential Manager per-value ceiling for tests. */
176
189
  const sizeLimitedAuthSecretStore: AuthSecretStore = {
177
190
  read(account) {
191
+ testAuthSecretStoreReadCount++;
178
192
  return memoryAuthEntries.get(account);
179
193
  },
180
194
  write(account, payload) {
@@ -190,6 +204,7 @@ const sizeLimitedAuthSecretStore: AuthSecretStore = {
190
204
 
191
205
  const unavailableAuthSecretStore: AuthSecretStore = {
192
206
  read() {
207
+ testAuthSecretStoreReadCount++;
193
208
  throw new Error('simulated secure credential store unavailable');
194
209
  },
195
210
  write() {
@@ -206,6 +221,7 @@ function createKeyRevokedTestError(): Error {
206
221
 
207
222
  const keyRevokedAuthSecretStore: AuthSecretStore = {
208
223
  read() {
224
+ testAuthSecretStoreReadCount++;
209
225
  throw createKeyRevokedTestError();
210
226
  },
211
227
  write() {
@@ -218,6 +234,16 @@ const keyRevokedAuthSecretStore: AuthSecretStore = {
218
234
 
219
235
  export function resetTestAuthSecretStore(): void {
220
236
  memoryAuthEntries.clear();
237
+ authEntryCache.clear();
238
+ testAuthSecretStoreReadCount = 0;
239
+ }
240
+
241
+ export function resetAuthEntryCache(): void {
242
+ authEntryCache.clear();
243
+ }
244
+
245
+ export function getTestAuthSecretStoreReadCount(): number {
246
+ return testAuthSecretStoreReadCount;
221
247
  }
222
248
 
223
249
  export function getTestAuthSecretStoreEntries(): [string, string][] {
@@ -649,6 +675,19 @@ function writeSecureAuthEntryToStore(store: AuthSecretStore, serverName: string,
649
675
  error,
650
676
  );
651
677
  }
678
+
679
+ publishAuthEntryToCache(serverName, payload);
680
+ }
681
+
682
+ function publishAuthEntryToCache(serverName: string, payload: string): void {
683
+ if (!isAuthEntryCacheEnabled()) return;
684
+ // Cache the same normalized shape a fresh persistent-store read returns.
685
+ const normalized = toAuthEntry(JSON.parse(payload) as unknown);
686
+ if (!normalized) {
687
+ authEntryCache.delete(serverName);
688
+ return;
689
+ }
690
+ authEntryCache.set(serverName, cloneAuthEntry(normalized));
652
691
  }
653
692
 
654
693
  function writeSecureAuthEntry(serverName: string, entry: AuthEntry): void {
@@ -704,12 +743,23 @@ function readAuthEntry(
704
743
  options?: AuthStorageOptions,
705
744
  behavior: { migrateLegacy?: boolean } = {},
706
745
  ): AuthEntry | undefined {
746
+ // Status-only reads deliberately bypass the cache because they do not
747
+ // migrate legacy entries.
748
+ const cacheable = behavior.migrateLegacy !== false && isAuthEntryCacheEnabled();
749
+ if (cacheable && authEntryCache.has(serverName)) {
750
+ return cloneAuthEntry(authEntryCache.get(serverName));
751
+ }
752
+
753
+ let entry: AuthEntry | undefined;
707
754
  try {
708
- return readAuthEntryFromStore(getAuthSecretStore(), serverName, options, behavior);
755
+ entry = readAuthEntryFromStore(getAuthSecretStore(), serverName, options, behavior);
709
756
  } catch (error) {
710
757
  if (!shouldAttemptLinuxKeyringRecovery(error)) throw error;
711
- return readAuthEntryFromStore(linuxKeyringRecoveryAuthSecretStore, serverName, options, behavior);
758
+ entry = readAuthEntryFromStore(linuxKeyringRecoveryAuthSecretStore, serverName, options, behavior);
712
759
  }
760
+
761
+ if (cacheable) authEntryCache.set(serverName, cloneAuthEntry(entry));
762
+ return entry;
713
763
  }
714
764
 
715
765
  /**
@@ -794,9 +844,17 @@ export function removeAuthEntry(serverName: string, options?: AuthStorageOptions
794
844
  if (!shouldAttemptLinuxKeyringRecovery(error)) throw error;
795
845
  removeAuthEntryFromStore(linuxKeyringRecoveryAuthSecretStore, serverName);
796
846
  }
847
+ authEntryCache.delete(serverName);
797
848
  removeLegacyAuthEntry(serverName, options);
798
849
  }
799
850
 
851
+ /**
852
+ * Forget a cached entry so the next ordinary read reloads secure storage.
853
+ */
854
+ export function invalidateAuthEntryCache(serverName: string): void {
855
+ authEntryCache.delete(serverName);
856
+ }
857
+
800
858
  /**
801
859
  * Update tokens for a server.
802
860
  */