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