@fitchmultz/pi-mcp-adapter 5.0.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.
Files changed (176) hide show
  1. package/CHANGELOG.md +750 -0
  2. package/LICENSE +21 -0
  3. package/OAUTH.md +462 -0
  4. package/README.md +820 -0
  5. package/abort.ts +34 -0
  6. package/agent-dir.ts +24 -0
  7. package/app-bridge.bundle.js +67 -0
  8. package/banner.png +0 -0
  9. package/checkpoint.ts +55 -0
  10. package/cli.js +222 -0
  11. package/commands.ts +619 -0
  12. package/config.ts +1204 -0
  13. package/consent-manager.ts +25 -0
  14. package/direct-tools.ts +408 -0
  15. package/dist/abort.d.ts +2 -0
  16. package/dist/abort.js +35 -0
  17. package/dist/agent-dir.d.ts +3 -0
  18. package/dist/agent-dir.js +21 -0
  19. package/dist/app-bridge.bundle.js +67 -0
  20. package/dist/checkpoint.d.ts +18 -0
  21. package/dist/checkpoint.js +53 -0
  22. package/dist/commands.d.ts +20 -0
  23. package/dist/commands.js +521 -0
  24. package/dist/config.d.ts +109 -0
  25. package/dist/config.js +1013 -0
  26. package/dist/consent-manager.d.ts +8 -0
  27. package/dist/consent-manager.js +21 -0
  28. package/dist/direct-tools.d.ts +10 -0
  29. package/dist/direct-tools.js +350 -0
  30. package/dist/docs/client-metadata.json +14 -0
  31. package/dist/elicitation-handler.d.ts +17 -0
  32. package/dist/elicitation-handler.js +308 -0
  33. package/dist/error-signal.d.ts +15 -0
  34. package/dist/error-signal.js +21 -0
  35. package/dist/glimpse-ui.d.ts +9 -0
  36. package/dist/glimpse-ui.js +75 -0
  37. package/dist/host-html-template.d.ts +15 -0
  38. package/dist/host-html-template.js +429 -0
  39. package/dist/index.d.ts +7 -0
  40. package/dist/index.js +840 -0
  41. package/dist/init.d.ts +25 -0
  42. package/dist/init.js +562 -0
  43. package/dist/legacy-migration.d.ts +18 -0
  44. package/dist/legacy-migration.js +45 -0
  45. package/dist/lifecycle.d.ts +40 -0
  46. package/dist/lifecycle.js +167 -0
  47. package/dist/logger.d.ts +38 -0
  48. package/dist/logger.js +102 -0
  49. package/dist/mcp-auth-flow.d.ts +113 -0
  50. package/dist/mcp-auth-flow.js +834 -0
  51. package/dist/mcp-auth.d.ts +127 -0
  52. package/dist/mcp-auth.js +658 -0
  53. package/dist/mcp-callback-server.d.ts +56 -0
  54. package/dist/mcp-callback-server.js +371 -0
  55. package/dist/mcp-code.d.ts +51 -0
  56. package/dist/mcp-code.js +366 -0
  57. package/dist/mcp-keyring-helper.cjs +89 -0
  58. package/dist/mcp-oauth-provider.d.ts +154 -0
  59. package/dist/mcp-oauth-provider.js +672 -0
  60. package/dist/mcp-output-guard.d.ts +59 -0
  61. package/dist/mcp-output-guard.js +332 -0
  62. package/dist/mcp-panel.d.ts +66 -0
  63. package/dist/mcp-panel.js +889 -0
  64. package/dist/mcp-script-worker.mjs +128 -0
  65. package/dist/mcp-setup-panel.d.ts +84 -0
  66. package/dist/mcp-setup-panel.js +561 -0
  67. package/dist/mcp-status.d.ts +11 -0
  68. package/dist/mcp-status.js +96 -0
  69. package/dist/mcp-trace.d.ts +95 -0
  70. package/dist/mcp-trace.js +233 -0
  71. package/dist/metadata-cache.d.ts +18 -0
  72. package/dist/metadata-cache.js +277 -0
  73. package/dist/npx-resolver.d.ts +6 -0
  74. package/dist/npx-resolver.js +448 -0
  75. package/dist/onboarding-state.d.ts +11 -0
  76. package/dist/onboarding-state.js +47 -0
  77. package/dist/panel-keys.d.ts +16 -0
  78. package/dist/panel-keys.js +15 -0
  79. package/dist/prompts.d.ts +56 -0
  80. package/dist/prompts.js +284 -0
  81. package/dist/proxy-modes.d.ts +38 -0
  82. package/dist/proxy-modes.js +1235 -0
  83. package/dist/resource-tools.d.ts +1 -0
  84. package/dist/resource-tools.js +14 -0
  85. package/dist/runtime-owner.d.ts +18 -0
  86. package/dist/runtime-owner.js +117 -0
  87. package/dist/sampling-handler.d.ts +15 -0
  88. package/dist/sampling-handler.js +211 -0
  89. package/dist/search-ranking.d.ts +20 -0
  90. package/dist/search-ranking.js +180 -0
  91. package/dist/server-manager.d.ts +114 -0
  92. package/dist/server-manager.js +1175 -0
  93. package/dist/session-recovery.d.ts +31 -0
  94. package/dist/session-recovery.js +310 -0
  95. package/dist/state.d.ts +63 -0
  96. package/dist/state.js +1 -0
  97. package/dist/tool-approval.d.ts +10 -0
  98. package/dist/tool-approval.js +42 -0
  99. package/dist/tool-metadata.d.ts +9 -0
  100. package/dist/tool-metadata.js +193 -0
  101. package/dist/tool-registrar.d.ts +10 -0
  102. package/dist/tool-registrar.js +64 -0
  103. package/dist/tool-result-renderer.d.ts +45 -0
  104. package/dist/tool-result-renderer.js +224 -0
  105. package/dist/ts-shape.d.ts +2 -0
  106. package/dist/ts-shape.js +147 -0
  107. package/dist/types.d.ts +516 -0
  108. package/dist/types.js +168 -0
  109. package/dist/ui-resource-handler.d.ts +17 -0
  110. package/dist/ui-resource-handler.js +209 -0
  111. package/dist/ui-server.d.ts +51 -0
  112. package/dist/ui-server.js +669 -0
  113. package/dist/ui-session.d.ts +39 -0
  114. package/dist/ui-session.js +463 -0
  115. package/dist/ui-stream-types.d.ts +104 -0
  116. package/dist/ui-stream-types.js +58 -0
  117. package/dist/ui-tool-visibility.d.ts +4 -0
  118. package/dist/ui-tool-visibility.js +26 -0
  119. package/dist/unix-socket-transport.d.ts +15 -0
  120. package/dist/unix-socket-transport.js +84 -0
  121. package/dist/utils.d.ts +30 -0
  122. package/dist/utils.js +276 -0
  123. package/docs/client-metadata.json +14 -0
  124. package/elicitation-handler.ts +349 -0
  125. package/error-signal.ts +21 -0
  126. package/glimpse-ui.ts +80 -0
  127. package/host-html-template.ts +456 -0
  128. package/index.ts +900 -0
  129. package/init.ts +627 -0
  130. package/legacy-migration.ts +47 -0
  131. package/lifecycle.ts +165 -0
  132. package/logger.ts +127 -0
  133. package/mcp-auth-flow.ts +975 -0
  134. package/mcp-auth.ts +793 -0
  135. package/mcp-callback-server.ts +450 -0
  136. package/mcp-code.ts +386 -0
  137. package/mcp-keyring-helper.cjs +89 -0
  138. package/mcp-oauth-provider.ts +774 -0
  139. package/mcp-output-guard.ts +412 -0
  140. package/mcp-panel.ts +978 -0
  141. package/mcp-script-worker.mjs +128 -0
  142. package/mcp-setup-panel.ts +666 -0
  143. package/mcp-status.ts +109 -0
  144. package/mcp-trace.ts +295 -0
  145. package/metadata-cache.ts +333 -0
  146. package/npx-resolver.ts +488 -0
  147. package/onboarding-state.ts +58 -0
  148. package/package.json +182 -0
  149. package/panel-keys.ts +37 -0
  150. package/prompts.ts +337 -0
  151. package/proxy-modes.ts +1361 -0
  152. package/resource-tools.ts +17 -0
  153. package/runtime-owner.ts +123 -0
  154. package/sampling-handler.ts +273 -0
  155. package/scripts/build.mjs +131 -0
  156. package/scripts/prepare.mjs +102 -0
  157. package/search-ranking.ts +196 -0
  158. package/server-manager.ts +1320 -0
  159. package/session-recovery.ts +316 -0
  160. package/skills/mcp-scripting/SKILL.md +38 -0
  161. package/state.ts +64 -0
  162. package/tool-approval.ts +78 -0
  163. package/tool-metadata.ts +235 -0
  164. package/tool-registrar.ts +69 -0
  165. package/tool-result-renderer.ts +286 -0
  166. package/ts-shape.ts +145 -0
  167. package/tsconfig.build.json +13 -0
  168. package/tsconfig.json +16 -0
  169. package/types.ts +810 -0
  170. package/ui-resource-handler.ts +249 -0
  171. package/ui-server.ts +808 -0
  172. package/ui-session.ts +568 -0
  173. package/ui-stream-types.ts +89 -0
  174. package/ui-tool-visibility.ts +25 -0
  175. package/unix-socket-transport.ts +85 -0
  176. package/utils.ts +309 -0
package/dist/init.d.ts ADDED
@@ -0,0 +1,25 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { McpExtensionState } from "./state.ts";
3
+ import { type McpAdapterOptions, type McpConfig } from "./types.ts";
4
+ import { type McpOAuthRuntime } from "./mcp-auth-flow.ts";
5
+ import { type McpRuntimeOwner } from "./runtime-owner.ts";
6
+ export declare function clearFailure(state: McpExtensionState, serverName: string): void;
7
+ export declare function recordFailure(state: McpExtensionState, serverName: string, message: string): void;
8
+ type McpInitializationOptions = McpAdapterOptions & {
9
+ oauthRuntime?: McpOAuthRuntime;
10
+ statusEvents?: McpExtensionState["statusEvents"];
11
+ resolvedConfig?: McpConfig;
12
+ };
13
+ export declare function initializeMcp(pi: ExtensionAPI, ctx: ExtensionContext, owner?: McpRuntimeOwner, options?: McpInitializationOptions): Promise<McpExtensionState>;
14
+ export declare function markKeepAliveAfterConnect(state: McpExtensionState, serverName: string): void;
15
+ export declare function updateServerMetadata(state: McpExtensionState, serverName: string): void;
16
+ export declare function updateMetadataCache(state: McpExtensionState, serverName: string, options?: {
17
+ preserveEmptyResources?: boolean;
18
+ }): void;
19
+ export declare function notifyToolMetadataUpdated(state: McpExtensionState, serverName: string, reason: string): void;
20
+ export declare function flushMetadataCache(state: McpExtensionState): void;
21
+ export declare function updateStatusBar(state: McpExtensionState): void;
22
+ export declare function getFailureAgeSeconds(state: McpExtensionState, serverName: string): number | null;
23
+ export declare function getFailureMessage(state: McpExtensionState, serverName: string): string | null;
24
+ export declare function lazyConnect(state: McpExtensionState, serverName: string, signal?: AbortSignal): Promise<boolean>;
25
+ export {};
package/dist/init.js ADDED
@@ -0,0 +1,562 @@
1
+ import { isServerDisabled } from "./types.js";
2
+ import { existsSync } from "node:fs";
3
+ import { cloneMcpConfig, isPathInsideProject, loadMcpConfig } from "./config.js";
4
+ import { ConsentManager } from "./consent-manager.js";
5
+ import { McpLifecycleManager } from "./lifecycle.js";
6
+ import { computeServerHash, getMetadataCachePath, getMissingConfiguredDirectToolServers, isServerCacheValid, loadMetadataCache, reconstructPromptMetadata, reconstructToolMetadata, saveMetadataCache, serializePrompts, serializeResources, serializeTools, } from "./metadata-cache.js";
7
+ import { McpServerManager } from "./server-manager.js";
8
+ import { buildToolMetadata, totalToolCount } from "./tool-metadata.js";
9
+ import { UiResourceHandler } from "./ui-resource-handler.js";
10
+ import { formatMcpStatus, openUrl, parallelLimit, sanitizeTerminalText } from "./utils.js";
11
+ import { logger } from "./logger.js";
12
+ import { throwIfAborted } from "./abort.js";
13
+ import { getAuthStorageOptions } from "./mcp-auth.js";
14
+ import { createOAuthRuntime, hasPendingAuth, shutdownOAuth } from "./mcp-auth-flow.js";
15
+ import { combineAbortSignals, createMcpRuntimeOwner, createOwnedUi, isAbortError, } from "./runtime-owner.js";
16
+ import { publishMcpStatusSnapshot } from "./mcp-status.js";
17
+ const FAILURE_BACKOFF_MS = 60 * 1000;
18
+ const MAX_FAILURE_MESSAGE_CHARS = 8 * 1024;
19
+ const failureExpiryTimers = new WeakMap();
20
+ function getFailureExpiryTimers(state) {
21
+ let timers = failureExpiryTimers.get(state);
22
+ if (!timers) {
23
+ timers = new Map();
24
+ failureExpiryTimers.set(state, timers);
25
+ }
26
+ return timers;
27
+ }
28
+ export function clearFailure(state, serverName) {
29
+ state.failureTracker.delete(serverName);
30
+ state.failureMessages?.delete(serverName);
31
+ const timers = failureExpiryTimers.get(state);
32
+ const timer = timers?.get(serverName);
33
+ if (timer)
34
+ clearTimeout(timer);
35
+ timers?.delete(serverName);
36
+ }
37
+ export function recordFailure(state, serverName, message) {
38
+ clearFailure(state, serverName);
39
+ const failedAt = Date.now();
40
+ state.failureTracker.set(serverName, failedAt);
41
+ state.failureMessages?.set(serverName, message.slice(0, MAX_FAILURE_MESSAGE_CHARS));
42
+ const timer = setTimeout(() => {
43
+ if (!state.owner.isActive()) {
44
+ getFailureExpiryTimers(state).delete(serverName);
45
+ return;
46
+ }
47
+ state.owner.beforeActivity();
48
+ if (state.failureTracker.get(serverName) === failedAt) {
49
+ state.failureTracker.delete(serverName);
50
+ state.failureMessages?.delete(serverName);
51
+ publishMcpStatusSnapshot(state);
52
+ }
53
+ getFailureExpiryTimers(state).delete(serverName);
54
+ }, FAILURE_BACKOFF_MS);
55
+ timer.unref?.();
56
+ getFailureExpiryTimers(state).set(serverName, timer);
57
+ }
58
+ export async function initializeMcp(pi, ctx, owner = createMcpRuntimeOwner(), options = {}) {
59
+ // Pi guards ExtensionContext getters after reload. Snapshot all values that
60
+ // can be used by asynchronous work before the first await.
61
+ const cwd = ctx.cwd;
62
+ const hasUI = ctx.hasUI;
63
+ const mode = ctx.mode;
64
+ const rawUi = hasUI ? ctx.ui : undefined;
65
+ const modelRegistry = ctx.modelRegistry;
66
+ const initialSignal = ctx.signal;
67
+ const ui = rawUi ? createOwnedUi(rawUi, owner) : undefined;
68
+ const runtimeSignal = combineAbortSignals(owner.signal, initialSignal);
69
+ const config = options.config !== undefined
70
+ ? cloneMcpConfig(options.config)
71
+ : options.resolvedConfig !== undefined
72
+ ? cloneMcpConfig(options.resolvedConfig)
73
+ : loadMcpConfig(options.configPath ?? pi.getFlag("mcp-config"), cwd);
74
+ const authStorageOptions = getAuthStorageOptions(config.settings?.oauthDir, cwd);
75
+ const metadataCacheEnabled = (ctx.isProjectTrusted?.() ?? true)
76
+ || !isPathInsideProject(getMetadataCachePath(), cwd);
77
+ const ownsOAuthRuntime = options.oauthRuntime === undefined;
78
+ const oauthRuntime = options.oauthRuntime ?? createOAuthRuntime(owner.signal);
79
+ const manager = new McpServerManager(cwd);
80
+ manager.setRuntimeSignal?.(owner.signal);
81
+ manager.setOAuthRuntime?.(oauthRuntime);
82
+ manager.setDefaultRequestTimeoutMs(config.settings?.requestTimeoutMs);
83
+ manager.setTraceConfig?.(config.settings?.trace);
84
+ manager.setAuthStorageOptions(authStorageOptions);
85
+ const samplingAutoApprove = config.settings?.samplingAutoApprove === true;
86
+ if (config.settings?.sampling !== false && (hasUI || samplingAutoApprove)) {
87
+ manager.setSamplingConfig({
88
+ autoApprove: samplingAutoApprove,
89
+ ...(ui !== undefined ? { ui } : {}),
90
+ modelRegistry,
91
+ getCurrentModel: () => owner.isActive() ? ctx.model : undefined,
92
+ getSignal: () => owner.isActive()
93
+ ? combineAbortSignals(owner.signal, ctx.signal)
94
+ : owner.signal,
95
+ });
96
+ }
97
+ const elicitationEnabled = config.settings?.elicitation !== false && hasUI;
98
+ if (elicitationEnabled && ui) {
99
+ manager.setElicitationConfig({
100
+ ui,
101
+ allowUrl: mode === "tui",
102
+ });
103
+ }
104
+ const lifecycle = new McpLifecycleManager(manager, (serverName) => hasPendingAuth(serverName, undefined, oauthRuntime));
105
+ const toolMetadata = new Map();
106
+ const resourceCounts = new Map();
107
+ const promptMetadata = new Map();
108
+ const promptMetadataLive = new Set();
109
+ const serverInstructions = new Map();
110
+ const failureTracker = new Map();
111
+ const failureMessages = new Map();
112
+ const approvedToolCalls = new Map();
113
+ const uiResourceHandler = new UiResourceHandler(manager, config);
114
+ const consentManager = new ConsentManager();
115
+ const state = {
116
+ owner,
117
+ manager,
118
+ lifecycle,
119
+ toolMetadata,
120
+ resourceCounts,
121
+ promptMetadata,
122
+ promptMetadataLive,
123
+ serverInstructions,
124
+ config,
125
+ programmaticConfig: options.config !== undefined,
126
+ ...(options.outputDirectory !== undefined ? { outputDirectory: options.outputDirectory } : {}),
127
+ oauthRuntime,
128
+ authStorageOptions,
129
+ metadataCacheEnabled,
130
+ failureTracker,
131
+ failureMessages,
132
+ approvedToolCalls,
133
+ uiResourceHandler,
134
+ consentManager,
135
+ uiServer: null,
136
+ completedUiSessions: [],
137
+ activeScripts: 0,
138
+ openBrowser: async (url) => {
139
+ owner.throwIfInactive();
140
+ await openUrl(pi, url, process.env.BROWSER, owner.signal);
141
+ owner.throwIfInactive();
142
+ },
143
+ ...(ui !== undefined ? { ui } : {}),
144
+ sendMessage: (message, options) => {
145
+ if (!owner.isActive())
146
+ return;
147
+ pi.sendMessage(message, options);
148
+ },
149
+ ...(options.statusEvents !== undefined ? { statusEvents: options.statusEvents } : {}),
150
+ ...(options.onToolCall ? { onToolCall: options.onToolCall } : {}),
151
+ };
152
+ if (ownsOAuthRuntime)
153
+ owner.addCleanup(() => shutdownOAuth(oauthRuntime));
154
+ manager.setMetadataListChangedListener?.((serverName, reason) => {
155
+ if (!owner.isActive())
156
+ return;
157
+ updateServerMetadata(state, serverName);
158
+ updateMetadataCache(state, serverName, { preserveEmptyResources: false });
159
+ notifyToolMetadataUpdated(state, serverName, reason);
160
+ updateStatusBar(state);
161
+ });
162
+ owner.addCleanup(() => lifecycle.gracefulShutdown());
163
+ owner.addCleanup(() => {
164
+ if (state.uiServer) {
165
+ state.uiServer.close("runtime_owner_stopped");
166
+ state.uiServer = null;
167
+ }
168
+ });
169
+ const allServerEntries = Object.entries(config.mcpServers);
170
+ const serverEntries = allServerEntries.filter(([, definition]) => !isServerDisabled(definition));
171
+ if (serverEntries.length === 0) {
172
+ if (allServerEntries.length > 0 && hasUI) {
173
+ ui?.notify(`MCP: All ${allServerEntries.length} server(s) are disabled`, "info");
174
+ }
175
+ publishMcpStatusSnapshot(state);
176
+ return state;
177
+ }
178
+ const idleSetting = typeof config.settings?.idleTimeout === "number" ? config.settings.idleTimeout : 10;
179
+ lifecycle.setGlobalIdleTimeout(idleSetting);
180
+ const cachePath = getMetadataCachePath();
181
+ const cacheFileExists = metadataCacheEnabled && existsSync(cachePath);
182
+ let cache = loadMetadataCache(metadataCacheEnabled);
183
+ let bootstrapAll = false;
184
+ if (!cacheFileExists) {
185
+ bootstrapAll = true;
186
+ saveMetadataCache({ version: 1, servers: {} }, metadataCacheEnabled);
187
+ }
188
+ else if (!cache) {
189
+ cache = { version: 1, servers: {} };
190
+ saveMetadataCache(cache, metadataCacheEnabled);
191
+ }
192
+ const prefix = config.settings?.toolPrefix ?? "server";
193
+ for (const [name, definition] of serverEntries) {
194
+ const lifecycleMode = definition.lifecycle ?? "lazy";
195
+ const persistsAfterFirstSpawn = lifecycleMode === "eager" || lifecycleMode === "lazy-keep-alive";
196
+ const idleOverride = definition.idleTimeout ?? (persistsAfterFirstSpawn ? 0 : undefined);
197
+ lifecycle.registerServer(name, definition, idleOverride !== undefined ? { idleTimeout: idleOverride } : undefined);
198
+ if (lifecycleMode === "keep-alive") {
199
+ lifecycle.markKeepAlive(name, definition);
200
+ }
201
+ const cachedEntry = cache?.servers?.[name];
202
+ if (cachedEntry && isServerCacheValid(cachedEntry, definition)) {
203
+ const metadata = reconstructToolMetadata(name, cachedEntry, prefix, definition);
204
+ toolMetadata.set(name, metadata);
205
+ if (Array.isArray(cachedEntry.resources)) {
206
+ resourceCounts.set(name, cachedEntry.resources.length);
207
+ }
208
+ if (cachedEntry.prompts?.length) {
209
+ promptMetadata.set(name, reconstructPromptMetadata(name, cachedEntry.prompts ?? [], prefix, definition));
210
+ }
211
+ if (cachedEntry.instructions) {
212
+ serverInstructions.set(name, cachedEntry.instructions);
213
+ }
214
+ }
215
+ }
216
+ const startupServers = bootstrapAll
217
+ ? serverEntries
218
+ : serverEntries.filter(([, definition]) => {
219
+ const mode = definition.lifecycle ?? "lazy";
220
+ return mode === "keep-alive" || mode === "eager";
221
+ });
222
+ if (ui && startupServers.length > 0) {
223
+ const status = formatMcpStatus(state.config, `connecting to ${startupServers.length} servers...`);
224
+ ui.setStatus("mcp", status);
225
+ }
226
+ const results = await parallelLimit(startupServers, 10, async ([name, definition]) => {
227
+ try {
228
+ const connection = await manager.connect(name, definition, runtimeSignal);
229
+ if (connection.status === "needs-auth") {
230
+ return { name, definition, connection: null, error: `OAuth authentication required. Run /mcp-auth ${name}.` };
231
+ }
232
+ return { name, definition, connection, error: null };
233
+ }
234
+ catch (error) {
235
+ if (isAbortError(error, runtimeSignal)) {
236
+ if (owner.signal.aborted)
237
+ throw error;
238
+ return { name, definition, connection: null, error: null };
239
+ }
240
+ const message = error instanceof Error ? error.message : String(error);
241
+ return { name, definition, connection: null, error: message };
242
+ }
243
+ });
244
+ if (initialSignal?.aborted)
245
+ return state;
246
+ owner.throwIfInactive();
247
+ for (const { name, definition, connection, error } of results) {
248
+ owner.throwIfInactive();
249
+ if (error || !connection) {
250
+ if (initialSignal?.aborted)
251
+ continue;
252
+ if (error)
253
+ recordFailure(state, name, error);
254
+ const displayError = sanitizeTerminalText(error ?? "Unknown connection failure");
255
+ if (ui) {
256
+ ui.notify(`MCP: Failed to connect to ${name}: ${displayError}`, "error");
257
+ }
258
+ console.error(`MCP: Failed to connect to ${name}: ${displayError}`);
259
+ continue;
260
+ }
261
+ const { metadata, failedTools } = buildToolMetadata(connection.tools, connection.resources, definition, name, prefix);
262
+ toolMetadata.set(name, metadata);
263
+ resourceCounts.set(name, connection.resources.length);
264
+ if (!connection.promptDiscoveryFailed) {
265
+ promptMetadata.set(name, reconstructPromptMetadata(name, connection.prompts ?? [], prefix, definition));
266
+ promptMetadataLive.add(name);
267
+ }
268
+ if (connection.instructions) {
269
+ serverInstructions.set(name, connection.instructions);
270
+ }
271
+ else {
272
+ serverInstructions.delete(name);
273
+ }
274
+ updateMetadataCache(state, name);
275
+ notifyToolMetadataUpdated(state, name, "startup");
276
+ markKeepAliveAfterConnect(state, name);
277
+ if (failedTools.length > 0 && ui) {
278
+ ui.notify(`MCP: ${name} - ${failedTools.length} tools skipped`, "warning");
279
+ }
280
+ }
281
+ const connectedCount = results.filter(r => r.connection).length;
282
+ const failedCount = results.filter(r => r.error).length;
283
+ if (ui && connectedCount > 0) {
284
+ const totalTools = totalToolCount(state);
285
+ const msg = failedCount > 0
286
+ ? `MCP: ${connectedCount}/${startupServers.length} servers connected (${totalTools} tools)`
287
+ : `MCP: ${connectedCount} servers connected (${totalTools} tools)`;
288
+ ui.notify(msg, "info");
289
+ }
290
+ const envDirect = process.env.MCP_DIRECT_TOOLS;
291
+ if (envDirect !== "__none__") {
292
+ const currentCache = loadMetadataCache(state.metadataCacheEnabled);
293
+ const envDirectToolOverride = envDirect?.split(",").map(selector => selector.trim()).filter(Boolean);
294
+ const missingCacheServers = getMissingConfiguredDirectToolServers(config, currentCache, envDirectToolOverride);
295
+ if (missingCacheServers.length > 0) {
296
+ const bootstrapResults = await parallelLimit(missingCacheServers.filter(name => !results.some(r => r.name === name && r.connection)), 10, async (name) => {
297
+ try {
298
+ const definition = config.mcpServers[name];
299
+ if (!definition)
300
+ throw new Error(`MCP server "${name}" is not configured`);
301
+ const connection = await manager.connect(name, definition, runtimeSignal);
302
+ if (connection.status === "needs-auth") {
303
+ return { name, ok: false };
304
+ }
305
+ updateServerMetadata(state, name);
306
+ updateMetadataCache(state, name);
307
+ notifyToolMetadataUpdated(state, name, "direct-tools-bootstrap");
308
+ markKeepAliveAfterConnect(state, name);
309
+ clearFailure(state, name);
310
+ return { name, ok: true };
311
+ }
312
+ catch (error) {
313
+ if (isAbortError(error, runtimeSignal)) {
314
+ if (owner.signal.aborted)
315
+ throw error;
316
+ return { name, ok: false };
317
+ }
318
+ const message = error instanceof Error ? error.message : String(error);
319
+ recordFailure(state, name, message);
320
+ logger.debug(`MCP: direct-tools bootstrap failed for ${name}: ${sanitizeTerminalText(message)}`);
321
+ return { name, ok: false };
322
+ }
323
+ });
324
+ const bootstrapped = bootstrapResults.filter(r => r.ok).map(r => r.name);
325
+ owner.throwIfInactive();
326
+ if (bootstrapped.length > 0 && ui) {
327
+ ui.notify(`MCP: direct tools for ${bootstrapped.join(", ")} will be available after restart`, "info");
328
+ }
329
+ }
330
+ }
331
+ lifecycle.setReconnectCallback((serverName) => {
332
+ if (!owner.isActive())
333
+ return;
334
+ updateServerMetadata(state, serverName);
335
+ updateMetadataCache(state, serverName);
336
+ notifyToolMetadataUpdated(state, serverName, "lifecycle-reconnect");
337
+ clearFailure(state, serverName);
338
+ updateStatusBar(state);
339
+ });
340
+ lifecycle.setReconnectFailureCallback((serverName, error) => {
341
+ if (!owner.isActive())
342
+ return;
343
+ const message = error instanceof Error ? error.message : String(error);
344
+ recordFailure(state, serverName, message);
345
+ updateStatusBar(state);
346
+ });
347
+ lifecycle.setIdleShutdownCallback((serverName) => {
348
+ if (!owner.isActive())
349
+ return;
350
+ const idleMinutes = getEffectiveIdleTimeoutMinutes(state, serverName);
351
+ logger.debug(`${serverName} shut down (idle ${idleMinutes}m)`);
352
+ updateStatusBar(state);
353
+ });
354
+ owner.throwIfInactive();
355
+ lifecycle.startHealthChecks(runtimeSignal);
356
+ if (config.settings?.mcpFooterStatus === "off") {
357
+ ui?.setStatus("mcp", undefined);
358
+ }
359
+ publishMcpStatusSnapshot(state);
360
+ return state;
361
+ }
362
+ export function markKeepAliveAfterConnect(state, serverName) {
363
+ const definition = state.config.mcpServers[serverName];
364
+ if (!definition || isServerDisabled(definition))
365
+ return;
366
+ if ((definition.lifecycle ?? "lazy") === "lazy-keep-alive") {
367
+ state.lifecycle.markKeepAlive(serverName, definition);
368
+ }
369
+ }
370
+ export function updateServerMetadata(state, serverName) {
371
+ const connection = state.manager.getConnection(serverName);
372
+ if (!connection || connection.status !== "connected")
373
+ return;
374
+ const definition = state.config.mcpServers[serverName];
375
+ if (!definition)
376
+ return;
377
+ if (isServerDisabled(definition)) {
378
+ state.toolMetadata.delete(serverName);
379
+ state.resourceCounts?.delete(serverName);
380
+ state.promptMetadata?.delete(serverName);
381
+ state.promptMetadataLive?.delete(serverName);
382
+ state.serverInstructions.delete(serverName);
383
+ return;
384
+ }
385
+ const prefix = state.config.settings?.toolPrefix ?? "server";
386
+ const { metadata } = buildToolMetadata(connection.tools, connection.resources, definition, serverName, prefix);
387
+ state.toolMetadata.set(serverName, metadata);
388
+ state.resourceCounts?.set(serverName, connection.resources.length);
389
+ if (!connection.promptDiscoveryFailed) {
390
+ state.promptMetadata?.set(serverName, reconstructPromptMetadata(serverName, connection.prompts ?? [], prefix, definition));
391
+ state.promptMetadataLive?.add(serverName);
392
+ }
393
+ if (connection.instructions) {
394
+ state.serverInstructions?.set(serverName, connection.instructions);
395
+ }
396
+ else {
397
+ state.serverInstructions?.delete(serverName);
398
+ }
399
+ }
400
+ export function updateMetadataCache(state, serverName, options = {}) {
401
+ const connection = state.manager.getConnection(serverName);
402
+ if (!connection || connection.status !== "connected")
403
+ return;
404
+ const definition = state.config.mcpServers[serverName];
405
+ if (!definition || isServerDisabled(definition))
406
+ return;
407
+ const configHash = computeServerHash(definition);
408
+ const existing = loadMetadataCache(state.metadataCacheEnabled);
409
+ const existingEntry = existing?.servers?.[serverName];
410
+ const tools = serializeTools(connection.tools);
411
+ let resources = definition.exposeResources === false ? [] : serializeResources(connection.resources);
412
+ const prompts = connection.promptDiscoveryFailed
413
+ ? existingEntry?.configHash === configHash ? existingEntry.prompts : undefined
414
+ : serializePrompts(connection.prompts ?? []);
415
+ if (definition.exposeResources !== false &&
416
+ resources.length === 0 &&
417
+ existingEntry?.resources?.length &&
418
+ existingEntry.configHash === configHash &&
419
+ options.preserveEmptyResources !== false) {
420
+ resources = existingEntry.resources;
421
+ }
422
+ const entry = {
423
+ configHash,
424
+ tools,
425
+ resources,
426
+ ...(prompts !== undefined ? { prompts } : {}),
427
+ ...(connection.instructions !== undefined ? { instructions: connection.instructions } : {}),
428
+ cachedAt: Date.now(),
429
+ };
430
+ saveMetadataCache({ version: 1, servers: { [serverName]: entry } }, state.metadataCacheEnabled);
431
+ }
432
+ export function notifyToolMetadataUpdated(state, serverName, reason) {
433
+ try {
434
+ const result = state.onToolMetadataUpdated?.(serverName, reason);
435
+ if (result && typeof result.catch === "function") {
436
+ result.catch((error) => {
437
+ const message = error instanceof Error ? error.message : String(error);
438
+ logger.debug(`MCP: metadata update hook failed for ${serverName}: ${message}`);
439
+ });
440
+ }
441
+ }
442
+ catch (error) {
443
+ const message = error instanceof Error ? error.message : String(error);
444
+ logger.debug(`MCP: metadata update hook failed for ${serverName}: ${message}`);
445
+ }
446
+ }
447
+ export function flushMetadataCache(state) {
448
+ for (const [name, connection] of state.manager.getAllConnections()) {
449
+ if (connection.status === "connected") {
450
+ updateMetadataCache(state, name);
451
+ }
452
+ }
453
+ }
454
+ export function updateStatusBar(state) {
455
+ publishMcpStatusSnapshot(state);
456
+ const ui = state.ui;
457
+ if (!ui)
458
+ return;
459
+ const entries = Object.entries(state.config.mcpServers);
460
+ const disabledCount = entries.filter(([, definition]) => isServerDisabled(definition)).length;
461
+ const enabledCount = entries.length - disabledCount;
462
+ if (entries.length === 0) {
463
+ ui.setStatus("mcp", undefined);
464
+ return;
465
+ }
466
+ const connectedCount = [...state.manager.getAllConnections()].filter(([name, connection]) => {
467
+ const definition = state.config.mcpServers[name];
468
+ return connection.status === "connected" && definition !== undefined && !isServerDisabled(definition);
469
+ }).length;
470
+ const footerStatus = state.config.settings?.mcpFooterStatus ?? "compact";
471
+ if (footerStatus === "off") {
472
+ ui.setStatus("mcp", undefined);
473
+ return;
474
+ }
475
+ let status = footerStatus === "compact"
476
+ ? `MCP ${connectedCount}/${enabledCount}`
477
+ : `${enabledCount} ${enabledCount === 1 ? "server" : "servers"} enabled`;
478
+ if (footerStatus === "full") {
479
+ if (connectedCount > 0)
480
+ status += ` (${connectedCount} connected)`;
481
+ if (disabledCount > 0)
482
+ status += ` (${disabledCount} disabled)`;
483
+ }
484
+ const formattedStatus = footerStatus === "compact" ? status : formatMcpStatus(state.config, status);
485
+ if (formattedStatus === undefined) {
486
+ ui.setStatus("mcp", undefined);
487
+ return;
488
+ }
489
+ ui.setStatus("mcp", ui.theme ? ui.theme.fg("accent", formattedStatus) : formattedStatus);
490
+ }
491
+ export function getFailureAgeSeconds(state, serverName) {
492
+ const failedAt = state.failureTracker.get(serverName);
493
+ if (!failedAt)
494
+ return null;
495
+ const ageMs = Date.now() - failedAt;
496
+ if (ageMs > FAILURE_BACKOFF_MS)
497
+ return null;
498
+ return Math.round(ageMs / 1000);
499
+ }
500
+ export function getFailureMessage(state, serverName) {
501
+ if (getFailureAgeSeconds(state, serverName) === null)
502
+ return null;
503
+ return state.failureMessages?.get(serverName) ?? null;
504
+ }
505
+ export async function lazyConnect(state, serverName, signal) {
506
+ const ownedSignal = combineAbortSignals(state.owner?.signal, signal);
507
+ throwIfAborted(ownedSignal);
508
+ const connection = state.manager.getConnection(serverName);
509
+ if (connection?.status === "needs-auth") {
510
+ return false;
511
+ }
512
+ if (connection?.status === "connected") {
513
+ updateServerMetadata(state, serverName);
514
+ markKeepAliveAfterConnect(state, serverName);
515
+ return true;
516
+ }
517
+ const failedAgo = getFailureAgeSeconds(state, serverName);
518
+ if (failedAgo !== null)
519
+ return false;
520
+ const definition = state.config.mcpServers[serverName];
521
+ if (!definition || isServerDisabled(definition))
522
+ return false;
523
+ try {
524
+ if (state.ui) {
525
+ const status = formatMcpStatus(state.config, `connecting to ${serverName}...`);
526
+ state.ui.setStatus("mcp", status);
527
+ }
528
+ const newConnection = await state.manager.connect(serverName, definition, ownedSignal);
529
+ if (newConnection.status === "needs-auth") {
530
+ return false;
531
+ }
532
+ clearFailure(state, serverName);
533
+ updateServerMetadata(state, serverName);
534
+ updateMetadataCache(state, serverName);
535
+ notifyToolMetadataUpdated(state, serverName, "lazy-connect");
536
+ markKeepAliveAfterConnect(state, serverName);
537
+ updateStatusBar(state);
538
+ return true;
539
+ }
540
+ catch (error) {
541
+ if (isAbortError(error, ownedSignal)) {
542
+ throwIfAborted(ownedSignal);
543
+ }
544
+ const message = error instanceof Error ? error.message : String(error);
545
+ recordFailure(state, serverName, message);
546
+ logger.debug(`MCP: lazy connect failed for ${serverName}: ${sanitizeTerminalText(message)}`);
547
+ updateStatusBar(state);
548
+ return false;
549
+ }
550
+ }
551
+ function getEffectiveIdleTimeoutMinutes(state, serverName) {
552
+ const definition = state.config.mcpServers[serverName];
553
+ if (!definition) {
554
+ return typeof state.config.settings?.idleTimeout === "number" ? state.config.settings.idleTimeout : 10;
555
+ }
556
+ if (typeof definition.idleTimeout === "number")
557
+ return definition.idleTimeout;
558
+ const mode = definition.lifecycle ?? "lazy";
559
+ if (mode === "eager" || mode === "lazy-keep-alive")
560
+ return 0;
561
+ return typeof state.config.settings?.idleTimeout === "number" ? state.config.settings.idleTimeout : 10;
562
+ }
@@ -0,0 +1,18 @@
1
+ import { migrateLegacyAuthEntry } from "./mcp-auth.ts";
2
+ interface FileMigration {
3
+ source: string;
4
+ destination: string;
5
+ status: "absent" | "existing" | "would-copy" | "copied";
6
+ }
7
+ /** Run explicitly before starting v5. Never overwrite a destination or remove a source. */
8
+ export declare function migrateLegacyState({ cwd, dryRun }?: {
9
+ cwd?: string;
10
+ dryRun?: boolean;
11
+ }): {
12
+ files: FileMigration[];
13
+ credentials: {
14
+ server: string;
15
+ status: ReturnType<typeof migrateLegacyAuthEntry>;
16
+ }[];
17
+ };
18
+ export {};
@@ -0,0 +1,45 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { dirname, resolve } from "node:path";
3
+ import { getAdapterPath, getAgentPath } from "./agent-dir.js";
4
+ import { getProjectPiConfigPath, loadMcpConfig, resolveConfiguredOAuthDir } from "./config.js";
5
+ import { migrateLegacyAuthEntry } from "./mcp-auth.js";
6
+ /** Run explicitly before starting v5. Never overwrite a destination or remove a source. */
7
+ export function migrateLegacyState({ cwd = process.cwd(), dryRun = false } = {}) {
8
+ const paths = ["mcp.json", "mcp-cache.json", "mcp-onboarding.json", "mcp-npx-cache.json"]
9
+ .map((name) => ({ source: getAgentPath(name), destination: getAdapterPath(name) }));
10
+ paths.push({ source: resolve(cwd, ".pi", "mcp.json"), destination: getProjectPiConfigPath(cwd) });
11
+ const files = paths.map(({ source, destination }) => {
12
+ if (!existsSync(source))
13
+ return { source, destination, status: "absent" };
14
+ if (existsSync(destination))
15
+ return { source, destination, status: "existing" };
16
+ if (dryRun)
17
+ return { source, destination, status: "would-copy" };
18
+ const contents = readFileSync(source);
19
+ mkdirSync(dirname(destination), { recursive: true, mode: 0o700 });
20
+ try {
21
+ writeFileSync(destination, contents, { flag: "wx", mode: 0o600 });
22
+ }
23
+ catch (error) {
24
+ if (error.code === "EEXIST")
25
+ return { source, destination, status: "existing" };
26
+ throw error;
27
+ }
28
+ if (!readFileSync(destination).equals(contents))
29
+ throw new Error(`Failed to verify migrated file: ${destination}`);
30
+ return { source, destination, status: "copied" };
31
+ });
32
+ const credentials = [];
33
+ if (!dryRun) {
34
+ const config = loadMcpConfig(undefined, cwd);
35
+ const legacyDirectory = process.env.MCP_OAUTH_DIR?.trim()
36
+ || resolveConfiguredOAuthDir(config.settings?.oauthDir, cwd)
37
+ || getAgentPath("mcp-oauth");
38
+ for (const [server, definition] of Object.entries(config.mcpServers)) {
39
+ if (typeof definition.url !== "string")
40
+ continue;
41
+ credentials.push({ server, status: migrateLegacyAuthEntry(server, legacyDirectory) });
42
+ }
43
+ }
44
+ return { files, credentials };
45
+ }