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