@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
@@ -0,0 +1,25 @@
1
+ import { logger } from "./logger.ts";
2
+
3
+ export class ConsentManager {
4
+ private decisions = new Map<string, boolean>();
5
+ private log = logger.child({ component: "ConsentManager" });
6
+
7
+ hasDecisions(): boolean { return this.decisions.size > 0; }
8
+
9
+ requiresPrompt(serverName: string): boolean {
10
+ return this.decisions.get(serverName) !== true;
11
+ }
12
+
13
+ registerDecision(serverName: string, approved: boolean): void {
14
+ this.decisions.set(serverName, approved);
15
+ this.log.debug(`Consent ${approved ? "granted" : "denied"}`, { server: serverName });
16
+ }
17
+
18
+ ensureApproved(serverName: string): void {
19
+ const decision = this.decisions.get(serverName);
20
+ if (decision === true) return;
21
+ throw new Error(decision === false
22
+ ? `Tool calls for "${serverName}" were denied for this session`
23
+ : `Tool call approval required for "${serverName}"`);
24
+ }
25
+ }
@@ -0,0 +1,408 @@
1
+ import type { AgentToolResult, AgentToolUpdateCallback, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { McpExtensionState } from "./state.ts";
3
+ import type { DirectToolSpec, McpAdapterOptions, McpConfig, ToolPrefix } from "./types.ts";
4
+ import type { MetadataCache } from "./metadata-cache.ts";
5
+ import { lazyConnect, getFailureAgeSeconds, clearFailure, recordFailure, updateStatusBar } from "./init.ts";
6
+ import { abortable, throwIfAborted } from "./abort.ts";
7
+ import { isServerCacheValid, parseDirectToolSelectors } from "./metadata-cache.ts";
8
+ export { getMissingConfiguredDirectToolServers } from "./metadata-cache.ts";
9
+ import { runToolCall } from "./proxy-modes.ts";
10
+ import { formatToolName, isServerDisabled, isNonInteractiveOAuth, isToolAllowed, resolveToolPrefix } from "./types.ts";
11
+ import { resourceNameToToolName } from "./resource-tools.ts";
12
+ import { authenticate, supportsOAuth } from "./mcp-auth-flow.ts";
13
+ import { formatAuthRequiredMessage, resolveServerUrl } from "./utils.ts";
14
+ import { SessionRecoveryAuthRequiredError, type SessionRecoveryDeps } from "./session-recovery.ts";
15
+ import { combineAbortSignals, isAbortError } from "./runtime-owner.ts";
16
+ import { ensureToolCallApproved } from "./tool-approval.ts";
17
+
18
+ const BUILTIN_NAMES = new Set(["read", "bash", "edit", "write", "grep", "find", "ls", "mcp"]);
19
+ export const DIRECT_TOOLS_ADVISORY_THRESHOLD = 75;
20
+ const advisedDirectToolSets = new Set<string>();
21
+
22
+ type DirectAutoAuthResult =
23
+ | { status: "skipped" }
24
+ | { status: "success" }
25
+ | { status: "failed"; message: string };
26
+
27
+ function getDirectAuthRequiredMessage(
28
+ state: McpExtensionState,
29
+ serverName: string,
30
+ defaultMessage = `MCP server "${serverName}" requires OAuth authentication. Run mcp({ action: "auth-start", server: "${serverName}" }) to get a browser URL, or /mcp-auth ${serverName} in an interactive local session.`,
31
+ ): string {
32
+ const oauth = state.config.mcpServers[serverName]?.oauth;
33
+ if (oauth && oauth.crossAppAccess) defaultMessage = `MCP server "${serverName}" requires enterprise authorization. Check oauth.crossAppAccess IdP configuration and ID-token source, then retry.`;
34
+ return formatAuthRequiredMessage(state.config, serverName, defaultMessage);
35
+ }
36
+
37
+ function getDirectAuthFailedMessage(state: McpExtensionState, serverName: string, message: string): string {
38
+ const customGuidance = state.config.settings?.authRequiredMessage;
39
+ const oauth = state.config.mcpServers[serverName]?.oauth;
40
+ if (customGuidance || (oauth && oauth.crossAppAccess)) {
41
+ return `OAuth authentication failed for "${serverName}": ${message}. ${getDirectAuthRequiredMessage(state, serverName)}`;
42
+ }
43
+ return `OAuth authentication failed for "${serverName}": ${message}. Run mcp({ action: "auth-start", server: "${serverName}" }) to get a browser URL, or /mcp-auth ${serverName} in an interactive local session.`;
44
+ }
45
+
46
+ async function attemptDirectAutoAuth(
47
+ state: McpExtensionState,
48
+ serverName: string,
49
+ signal?: AbortSignal,
50
+ ): Promise<DirectAutoAuthResult> {
51
+ if (state.config.settings?.autoAuth !== true) {
52
+ return { status: "skipped" };
53
+ }
54
+
55
+ const definition = state.config.mcpServers[serverName];
56
+ if (!definition || isServerDisabled(definition) || !supportsOAuth(definition)) {
57
+ return { status: "skipped" };
58
+ }
59
+
60
+ let serverUrl: string | undefined;
61
+ try {
62
+ serverUrl = resolveServerUrl(definition);
63
+ } catch (error) {
64
+ const message = error instanceof Error ? error.message : String(error);
65
+ return { status: "failed", message: getDirectAuthFailedMessage(state, serverName, message) };
66
+ }
67
+ if (!serverUrl) {
68
+ return { status: "skipped" };
69
+ }
70
+
71
+ if (!state.ui && !isNonInteractiveOAuth(definition.oauth)) {
72
+ return {
73
+ status: "failed",
74
+ message: getDirectAuthRequiredMessage(
75
+ state,
76
+ serverName,
77
+ `MCP server "${serverName}" requires OAuth authentication. Run mcp({ action: "auth-start", server: "${serverName}" }) to get a browser URL, or /mcp-auth ${serverName} in an interactive local session.`,
78
+ ),
79
+ };
80
+ }
81
+
82
+ try {
83
+ if (state.authStorageOptions) {
84
+ await authenticate(
85
+ serverName,
86
+ serverUrl,
87
+ definition,
88
+ signal
89
+ ? { authStorageOptions: state.authStorageOptions, signal, runtime: state.oauthRuntime }
90
+ : { authStorageOptions: state.authStorageOptions, runtime: state.oauthRuntime },
91
+ );
92
+ } else {
93
+ await authenticate(serverName, serverUrl, definition, {
94
+ ...(signal ? { signal } : {}),
95
+ runtime: state.oauthRuntime,
96
+ });
97
+ }
98
+ return { status: "success" };
99
+ } catch (error) {
100
+ if (isAbortError(error, signal)) throw error;
101
+ const message = error instanceof Error ? error.message : String(error);
102
+ return {
103
+ status: "failed",
104
+ message: getDirectAuthFailedMessage(state, serverName, message),
105
+ };
106
+ }
107
+ }
108
+
109
+ export function resolveDirectTools(
110
+ config: McpConfig,
111
+ cache: MetadataCache | null,
112
+ prefix: ToolPrefix,
113
+ envOverride?: string[],
114
+ ): DirectToolSpec[] {
115
+ const specs: DirectToolSpec[] = [];
116
+ if (!cache) return specs;
117
+
118
+ const seenNames = new Set<string>();
119
+
120
+ const envSelection = envOverride ? parseDirectToolSelectors(envOverride) : null;
121
+ const globalDirect = config.settings?.directTools;
122
+
123
+ for (const [serverName, definition] of Object.entries(config.mcpServers)) {
124
+ if (isServerDisabled(definition)) continue;
125
+ const serverCache = cache.servers[serverName];
126
+ if (!serverCache || !isServerCacheValid(serverCache, definition)) continue;
127
+
128
+ let toolFilter: true | string[] | false = false;
129
+
130
+ if (envSelection) {
131
+ if (envSelection.servers.has(serverName)) {
132
+ toolFilter = true;
133
+ } else if (envSelection.tools.has(serverName)) {
134
+ toolFilter = [...envSelection.tools.get(serverName)!];
135
+ }
136
+ } else {
137
+ if (definition.directTools !== undefined) {
138
+ toolFilter = definition.directTools;
139
+ } else if (globalDirect) {
140
+ toolFilter = globalDirect;
141
+ }
142
+ }
143
+
144
+ if (!toolFilter) continue;
145
+
146
+ const effectivePrefix = resolveToolPrefix(definition, prefix);
147
+
148
+ for (const tool of serverCache.tools ?? []) {
149
+ if (toolFilter !== true && !toolFilter.includes(tool.name)) continue;
150
+ if (!isToolAllowed(tool.name, serverName, effectivePrefix, definition.includeTools, definition.excludeTools)) continue;
151
+ const prefixedName = formatToolName(tool.name, serverName, effectivePrefix);
152
+ if (BUILTIN_NAMES.has(prefixedName)) {
153
+ console.warn(`MCP: skipping direct tool "${prefixedName}" (collides with builtin)`);
154
+ continue;
155
+ }
156
+ if (seenNames.has(prefixedName)) {
157
+ console.warn(`MCP: skipping duplicate direct tool "${prefixedName}" from "${serverName}"`);
158
+ continue;
159
+ }
160
+ seenNames.add(prefixedName);
161
+ specs.push({
162
+ serverName,
163
+ originalName: tool.name,
164
+ prefixedName,
165
+ description: tool.description ?? "",
166
+ ...(tool.inputSchema !== undefined ? { inputSchema: tool.inputSchema } : {}),
167
+ ...(tool.annotations !== undefined ? { annotations: tool.annotations } : {}),
168
+ ...(tool.uiResourceUri !== undefined ? { uiResourceUri: tool.uiResourceUri } : {}),
169
+ ...(tool.uiStreamMode !== undefined ? { uiStreamMode: tool.uiStreamMode } : {}),
170
+ });
171
+ }
172
+
173
+ if (definition.exposeResources !== false) {
174
+ for (const resource of serverCache.resources ?? []) {
175
+ const baseName = `read_${resourceNameToToolName(resource.name)}`;
176
+ if (toolFilter !== true && !toolFilter.includes(baseName)) continue;
177
+ if (!isToolAllowed(baseName, serverName, effectivePrefix, definition.includeTools, definition.excludeTools)) continue;
178
+ const prefixedName = formatToolName(baseName, serverName, effectivePrefix);
179
+ if (BUILTIN_NAMES.has(prefixedName)) {
180
+ console.warn(`MCP: skipping direct resource tool "${prefixedName}" (collides with builtin)`);
181
+ continue;
182
+ }
183
+ if (seenNames.has(prefixedName)) {
184
+ console.warn(`MCP: skipping duplicate direct resource tool "${prefixedName}" from "${serverName}"`);
185
+ continue;
186
+ }
187
+ seenNames.add(prefixedName);
188
+ specs.push({
189
+ serverName,
190
+ originalName: baseName,
191
+ prefixedName,
192
+ description: resource.description ?? `Read resource: ${resource.uri}`,
193
+ resourceUri: resource.uri,
194
+ });
195
+ }
196
+ }
197
+ }
198
+
199
+ const advisoryKey = specs.map(spec => spec.prefixedName).sort().join("\0");
200
+ if (specs.length >= DIRECT_TOOLS_ADVISORY_THRESHOLD && !advisedDirectToolSets.has(advisoryKey)) {
201
+ advisedDirectToolSets.add(advisoryKey);
202
+ console.warn(`MCP: ${specs.length} direct tools resolved. Each direct tool adds prompt context; README guidance recommends targeted sets of 5-20 tools and using the proxy or an explicit string[] when 75+ direct tools would be registered.`);
203
+ }
204
+
205
+ return specs;
206
+ }
207
+
208
+ export function buildProxyDescription(config: McpConfig): string {
209
+ let desc = `MCP gateway — server status, tool search/describe, auth, and single MCP tool calls. When one request needs several MCP calls with logic between them, use mcp_script. Non-MCP Pi tools should be called directly, not through mcp.\n`;
210
+
211
+ // Catalog counts and instruction previews change on connect and break prompt caching.
212
+ // Keep this directory config-only; discovery and instructions belong in tool results.
213
+ const enabledServers = Object.entries(config.mcpServers)
214
+ .filter(([, definition]) => !isServerDisabled(definition))
215
+ .map(([serverName]) => serverName)
216
+ .sort();
217
+ if (enabledServers.length > 0) {
218
+ desc += `\nConfigured servers (call mcp({}) for live status): ${enabledServers.join(", ")}\n`;
219
+ }
220
+
221
+ const disabledServers = Object.entries(config.mcpServers)
222
+ .filter(([, definition]) => isServerDisabled(definition))
223
+ .map(([serverName]) => serverName);
224
+ if (disabledServers.length > 0) {
225
+ desc += `\nDisabled servers (enable with /mcp enable <server> and /reload): ${disabledServers.join(", ")}\n`;
226
+ }
227
+
228
+ desc += `\nUsage:\n`;
229
+ desc += ` mcp({ }) → Show server status\n`;
230
+ desc += ` mcp({ server: "name", limit: 12 }) → Browse a server's tools (use offset for more)\n`;
231
+ desc += ` mcp({ search: "query" }) → Search MCP tools by name/description\n`;
232
+ desc += ` mcp({ describe: "tool_name" }) → Show tool details and parameters\n`;
233
+ desc += ` mcp({ instructions: "name" }) → Show full server usage instructions\n`;
234
+ desc += ` mcp({ connect: "server-name" }) → Connect to a server and refresh metadata\n`;
235
+ desc += ` mcp({ tool: "name", args: { key: "value" } }) → Call a tool (object args; JSON string also accepted)\n`;
236
+ desc += ` mcp({ action: "ui-messages" }) → Retrieve accumulated messages from completed UI sessions\n`;
237
+ desc += ` mcp({ action: "auth-start", server: "name" }) → Start manual OAuth and get a browser URL\n`;
238
+ desc += ` mcp({ action: "auth-complete", server: "name", args: { redirectUrl: "..." } }) → Complete manual OAuth\n`;
239
+ desc += `\nMode: action > tool (call) > connect > describe > instructions > search > server (list) > nothing (status)`;
240
+
241
+ return desc;
242
+ }
243
+
244
+ type DirectToolExecute = (
245
+ toolCallId: string,
246
+ params: Record<string, unknown>,
247
+ signal: AbortSignal | undefined,
248
+ onUpdate: AgentToolUpdateCallback<Record<string, unknown>> | undefined,
249
+ ctx: ExtensionContext,
250
+ ) => Promise<AgentToolResult<Record<string, unknown>>>;
251
+
252
+ export function createDirectToolExecutor(
253
+ getState: () => McpExtensionState | null,
254
+ getInitPromise: () => Promise<McpExtensionState> | null,
255
+ spec: DirectToolSpec,
256
+ beforeExecute?: McpAdapterOptions["beforeExecute"],
257
+ ): DirectToolExecute {
258
+ return async function execute(toolCallId, params, signal, _onUpdate, ctx) {
259
+ throwIfAborted(signal);
260
+ let state = getState();
261
+ const initPromise = getInitPromise();
262
+
263
+ if (!state && initPromise) {
264
+ try {
265
+ state = await abortable(initPromise, signal);
266
+ } catch (error) {
267
+ throwIfAborted(signal);
268
+ const message = error instanceof Error ? error.message : String(error);
269
+ return {
270
+ content: [{ type: "text" as const, text: `MCP initialization failed: ${message}` }],
271
+ details: { error: "init_failed", message },
272
+ };
273
+ }
274
+ }
275
+ if (!state) {
276
+ return {
277
+ content: [{ type: "text" as const, text: "MCP not initialized" }],
278
+ details: { error: "not_initialized" },
279
+ };
280
+ }
281
+
282
+ const definition = state.config.mcpServers[spec.serverName];
283
+ if (isServerDisabled(definition)) {
284
+ const message = `MCP server "${spec.serverName}" is disabled. Run /mcp enable ${spec.serverName} and /reload to enable it.`;
285
+ return {
286
+ content: [{ type: "text" as const, text: message }],
287
+ details: { error: "server_disabled", server: spec.serverName, message },
288
+ };
289
+ }
290
+
291
+ const ownedSignal = combineAbortSignals(state.owner?.signal, signal);
292
+ throwIfAborted(ownedSignal);
293
+ let connected = await lazyConnect(state, spec.serverName, ownedSignal);
294
+ let autoAuthAttempted = false;
295
+
296
+ const needsAuthConnection = state.manager.getConnection(spec.serverName);
297
+ if (!connected && needsAuthConnection?.status === "needs-auth") {
298
+ autoAuthAttempted = true;
299
+ const autoAuth = await attemptDirectAutoAuth(state, spec.serverName, ownedSignal);
300
+ if (autoAuth.status === "failed") {
301
+ return {
302
+ content: [{ type: "text" as const, text: autoAuth.message }],
303
+ details: { error: "auth_required", server: spec.serverName, message: autoAuth.message },
304
+ };
305
+ }
306
+ if (autoAuth.status === "success") {
307
+ clearFailure(state, spec.serverName);
308
+ try {
309
+ const liveDefinition = state.config.mcpServers[spec.serverName];
310
+ if (liveDefinition) {
311
+ await state.manager.reconnect(spec.serverName, liveDefinition, needsAuthConnection, ownedSignal);
312
+ connected = true;
313
+ }
314
+ } catch (error) {
315
+ if (isAbortError(error, ownedSignal)) throwIfAborted(ownedSignal);
316
+ recordFailure(state, spec.serverName, error instanceof Error ? error.message : String(error));
317
+ updateStatusBar(state);
318
+ }
319
+ if (connected) connected = await lazyConnect(state, spec.serverName, ownedSignal);
320
+ }
321
+ }
322
+
323
+ if (!connected) {
324
+ const authConnection = state.manager.getConnection(spec.serverName);
325
+ if (authConnection?.status === "needs-auth") {
326
+ const message = getDirectAuthRequiredMessage(state, spec.serverName);
327
+ return {
328
+ content: [{ type: "text" as const, text: message }],
329
+ details: { error: "auth_required", server: spec.serverName, message, autoAuthAttempted },
330
+ };
331
+ }
332
+ const failedAgo = getFailureAgeSeconds(state, spec.serverName);
333
+ return {
334
+ content: [{ type: "text" as const, text: `MCP server "${spec.serverName}" not available${failedAgo !== null ? ` (failed ${failedAgo}s ago)` : ""}` }],
335
+ details: { error: "server_unavailable", server: spec.serverName },
336
+ };
337
+ }
338
+
339
+ const connection = state.manager.getConnection(spec.serverName);
340
+ if (!connection || connection.status !== "connected") {
341
+ return {
342
+ content: [{ type: "text" as const, text: `MCP server "${spec.serverName}" not connected` }],
343
+ details: { error: "not_connected", server: spec.serverName },
344
+ };
345
+ }
346
+
347
+ const approval = await ensureToolCallApproved(state, spec.serverName, {
348
+ name: spec.prefixedName,
349
+ originalName: spec.originalName,
350
+ description: spec.description,
351
+ ...(spec.inputSchema !== undefined ? { inputSchema: spec.inputSchema } : {}),
352
+ ...(spec.resourceUri !== undefined ? { resourceUri: spec.resourceUri } : {}),
353
+ ...(spec.uiResourceUri !== undefined ? { uiResourceUri: spec.uiResourceUri } : {}),
354
+ ...(spec.uiStreamMode !== undefined ? { uiStreamMode: spec.uiStreamMode } : {}),
355
+ }, params, ownedSignal);
356
+ if (approval.ok === false) {
357
+ const denied = approval.reason === "denied";
358
+ const message = denied
359
+ ? `The user declined approval to run MCP tool "${spec.originalName}" on server "${spec.serverName}".`
360
+ : `MCP tool "${spec.originalName}" on server "${spec.serverName}" is approval-gated and requires an interactive session.`;
361
+ return {
362
+ content: [{ type: "text" as const, text: message }],
363
+ details: {
364
+ error: denied ? "approval_denied" : "approval_required",
365
+ server: spec.serverName,
366
+ tool: spec.originalName,
367
+ },
368
+ };
369
+ }
370
+
371
+ const recoverAuthConnection: NonNullable<SessionRecoveryDeps["onNeedsAuth"]> = async (_serverName, recoverySignal = ownedSignal, challenge) => {
372
+ throwIfAborted(recoverySignal);
373
+ const current = state.manager.getConnection(spec.serverName);
374
+ if (current?.status === "connected" && current !== challenge?.connection) return current;
375
+
376
+ if (!autoAuthAttempted) {
377
+ autoAuthAttempted = true;
378
+ const autoAuth = await attemptDirectAutoAuth(state, spec.serverName, recoverySignal);
379
+ throwIfAborted(recoverySignal);
380
+ if (autoAuth.status === "failed") {
381
+ throw new SessionRecoveryAuthRequiredError(spec.serverName, autoAuth.message);
382
+ }
383
+ if (autoAuth.status === "success") {
384
+ const liveDefinition = state.config.mcpServers[spec.serverName];
385
+ if (!current || !liveDefinition) return undefined;
386
+ await state.manager.reconnect(spec.serverName, liveDefinition, current, recoverySignal);
387
+ clearFailure(state, spec.serverName);
388
+ const reconnected = await lazyConnect(state, spec.serverName, recoverySignal);
389
+ return reconnected ? state.manager.getConnection(spec.serverName) : undefined;
390
+ }
391
+ }
392
+ return challenge ? undefined : state.manager.getConnection(spec.serverName);
393
+ };
394
+
395
+ return runToolCall(state, spec.serverName, spec, params, {
396
+ toolCallId,
397
+ ...(beforeExecute ? { beforeDispatch: (callSignal, operation) => beforeExecute(toolCallId, { ...ctx, signal: callSignal }, operation) } : {}),
398
+ detailsBase: spec.resourceUri
399
+ ? { server: spec.serverName, resourceUri: spec.resourceUri }
400
+ : { server: spec.serverName, tool: spec.originalName },
401
+ ownedSignal,
402
+ signal,
403
+ recoverAuthConnection,
404
+ authRequiredMessage: () => getDirectAuthRequiredMessage(state, spec.serverName),
405
+ autoAuthAttempted: () => autoAuthAttempted,
406
+ });
407
+ };
408
+ }
@@ -0,0 +1,2 @@
1
+ export declare function throwIfAborted(signal?: AbortSignal): void;
2
+ export declare function abortable<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T>;
package/dist/abort.js ADDED
@@ -0,0 +1,35 @@
1
+ export function throwIfAborted(signal) {
2
+ if (!signal?.aborted)
3
+ return;
4
+ throw signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason ?? "MCP request aborted"));
5
+ }
6
+ export async function abortable(promise, signal) {
7
+ if (!signal)
8
+ return promise;
9
+ throwIfAborted(signal);
10
+ return await new Promise((resolve, reject) => {
11
+ let settled = false;
12
+ const cleanup = () => signal.removeEventListener("abort", onAbort);
13
+ const onAbort = () => {
14
+ if (settled)
15
+ return;
16
+ settled = true;
17
+ cleanup();
18
+ reject(signal.reason instanceof Error ? signal.reason : new Error(String(signal.reason ?? "MCP request aborted")));
19
+ };
20
+ signal.addEventListener("abort", onAbort, { once: true });
21
+ promise.then(value => {
22
+ if (settled)
23
+ return;
24
+ settled = true;
25
+ cleanup();
26
+ resolve(value);
27
+ }, error => {
28
+ if (settled)
29
+ return;
30
+ settled = true;
31
+ cleanup();
32
+ reject(error);
33
+ });
34
+ });
35
+ }
@@ -0,0 +1,3 @@
1
+ export declare function getAgentDir(): string;
2
+ export declare function getAgentPath(...segments: string[]): string;
3
+ export declare function getAdapterPath(...segments: string[]): string;
@@ -0,0 +1,21 @@
1
+ import { homedir } from "node:os";
2
+ import { join, resolve } from "node:path";
3
+ export function getAgentDir() {
4
+ const configured = process.env.PI_CODING_AGENT_DIR?.trim();
5
+ if (!configured) {
6
+ return join(homedir(), ".pi", "agent");
7
+ }
8
+ if (configured === "~") {
9
+ return homedir();
10
+ }
11
+ if (configured.startsWith("~/")) {
12
+ return resolve(homedir(), configured.slice(2));
13
+ }
14
+ return resolve(configured);
15
+ }
16
+ export function getAgentPath(...segments) {
17
+ return join(getAgentDir(), ...segments);
18
+ }
19
+ export function getAdapterPath(...segments) {
20
+ return getAgentPath("fitch-mcp-adapter", ...segments);
21
+ }