-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathindex.ts
More file actions
336 lines (306 loc) · 11.4 KB
/
index.ts
File metadata and controls
336 lines (306 loc) · 11.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import type { ExtensionAPI, ToolInfo } from "@earendil-works/pi-coding-agent";
import type { McpExtensionState } from "./state.ts";
import { Type } from "typebox";
import { showStatus, showTools, reconnectServers, authenticateServer, logoutServer, openMcpAuthPanel, openMcpPanel, openMcpSetup } from "./commands.ts";
import { loadMcpConfig } from "./config.ts";
import { buildProxyDescription, createDirectToolExecutor, getMissingConfiguredDirectToolServers, resolveDirectTools } from "./direct-tools.ts";
import { flushMetadataCache, initializeMcp, updateStatusBar } from "./init.ts";
import { loadMetadataCache } from "./metadata-cache.ts";
import { executeCall, executeConnect, executeDescribe, executeList, executeSearch, executeStatus, executeUiMessages } from "./proxy-modes.ts";
import { getConfigPathFromArgv, truncateAtWord } from "./utils.ts";
import { initializeOAuth, shutdownOAuth } from "./mcp-auth-flow.ts";
import { createMcpDirectToolCallRenderer, renderMcpProxyToolCall, renderMcpToolResult } from "./tool-result-renderer.ts";
export default function mcpAdapter(pi: ExtensionAPI) {
let state: McpExtensionState | null = null;
let initPromise: Promise<McpExtensionState> | null = null;
let lifecycleGeneration = 0;
async function shutdownState(currentState: McpExtensionState | null, reason: string): Promise<void> {
if (!currentState) return;
if (currentState.uiServer) {
currentState.uiServer.close(reason);
currentState.uiServer = null;
}
let flushError: unknown;
try {
flushMetadataCache(currentState);
} catch (error) {
flushError = error;
}
try {
await currentState.lifecycle.gracefulShutdown();
} catch (error) {
if (flushError) {
console.error("MCP: graceful shutdown failed after metadata flush error", error);
} else {
throw error;
}
}
if (flushError) {
throw flushError;
}
}
const earlyConfigPath = getConfigPathFromArgv();
const earlyConfig = loadMcpConfig(earlyConfigPath);
const earlyCache = loadMetadataCache();
const prefix = earlyConfig.settings?.toolPrefix ?? "server";
const envRaw = process.env.MCP_DIRECT_TOOLS;
const directSpecs = envRaw === "__none__"
? []
: resolveDirectTools(
earlyConfig,
earlyCache,
prefix,
envRaw?.split(",").map(s => s.trim()).filter(Boolean),
);
const missingConfiguredDirectToolServers = getMissingConfiguredDirectToolServers(earlyConfig, earlyCache);
const shouldRegisterProxyTool =
earlyConfig.settings?.disableProxyTool !== true
|| directSpecs.length === 0
|| missingConfiguredDirectToolServers.length > 0;
for (const spec of directSpecs) {
(pi.registerTool as (tool: unknown) => unknown)({
name: spec.prefixedName,
label: `MCP: ${spec.originalName}`,
description: spec.description || "(no description)",
promptSnippet: truncateAtWord(spec.description, 100) || `MCP tool from ${spec.serverName}`,
parameters: Type.Unsafe((spec.inputSchema || { type: "object", properties: {} }) as never),
execute: createDirectToolExecutor(() => state, () => initPromise, spec),
renderCall: createMcpDirectToolCallRenderer(spec.prefixedName),
renderResult: renderMcpToolResult,
});
}
const getPiTools = (): ToolInfo[] => pi.getAllTools();
pi.registerFlag("mcp-config", {
description: "Path to MCP config file",
type: "string",
});
pi.on("session_start", async (_event, ctx) => {
const generation = ++lifecycleGeneration;
const previousState = state;
state = null;
initPromise = null;
try {
await Promise.all([
shutdownState(previousState, "session_restart"),
shutdownOAuth(),
]);
} catch (error) {
console.error("MCP: failed to shut down previous session state", error);
}
if (generation !== lifecycleGeneration) {
return;
}
await initializeOAuth().catch(err => {
console.error("MCP OAuth initialization failed:", err);
});
const promise = initializeMcp(pi, ctx);
initPromise = promise;
promise.then(async (nextState) => {
if (generation !== lifecycleGeneration || initPromise !== promise) {
try {
await shutdownState(nextState, "stale_session_start");
} catch (error) {
console.error("MCP: failed to clean stale session state", error);
}
return;
}
state = nextState;
updateStatusBar(nextState);
initPromise = null;
}).catch(err => {
if (generation !== lifecycleGeneration) {
return;
}
if (initPromise !== promise && initPromise !== null) {
return;
}
console.error("MCP initialization failed:", err);
initPromise = null;
});
});
pi.on("session_shutdown", async () => {
++lifecycleGeneration;
const currentState = state;
state = null;
initPromise = null;
try {
await Promise.all([
shutdownState(currentState, "session_shutdown"),
shutdownOAuth(),
]);
} catch (error) {
console.error("MCP: session shutdown cleanup failed", error);
}
});
pi.registerCommand("mcp", {
description: "Show MCP server status",
handler: async (args, ctx) => {
if (!state && initPromise) {
try {
state = await initPromise;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (ctx.hasUI) ctx.ui.notify(`MCP initialization failed: ${message}`, "error");
return;
}
}
if (!state) {
if (ctx.hasUI) ctx.ui.notify("MCP not initialized", "error");
return;
}
const parts = args?.trim()?.split(/\s+/) ?? [];
const subcommand = parts[0] ?? "";
const targetServer = parts[1];
const rest = parts.slice(1).join(" ");
switch (subcommand) {
case "reconnect":
await reconnectServers(state, ctx, targetServer);
break;
case "tools":
await showTools(state, ctx);
break;
case "setup": {
const result = await openMcpSetup(state, pi, ctx, earlyConfigPath, "setup");
if (result?.configChanged) {
await ctx.reload();
return;
}
break;
}
case "logout": {
const serverName = rest;
if (!serverName) {
if (ctx.hasUI) ctx.ui.notify("Usage: /mcp logout <server>", "error");
return;
}
await logoutServer(serverName, state, ctx);
break;
}
case "status":
case "":
default:
if (ctx.hasUI) {
const result = await openMcpPanel(state, pi, ctx, earlyConfigPath);
if (result?.configChanged) {
await ctx.reload();
return;
}
} else {
await showStatus(state, ctx);
}
break;
}
},
});
pi.registerCommand("mcp-auth", {
description: "Authenticate with an MCP server (OAuth)",
handler: async (args, ctx) => {
const serverName = args?.trim();
if (!serverName && !ctx.hasUI) {
return;
}
if (!state && initPromise) {
try {
state = await initPromise;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (ctx.hasUI) ctx.ui.notify(`MCP initialization failed: ${message}`, "error");
return;
}
}
if (!state) {
if (ctx.hasUI) ctx.ui.notify("MCP not initialized", "error");
return;
}
if (!serverName) {
await openMcpAuthPanel(state, pi, ctx, earlyConfigPath);
return;
}
await authenticateServer(serverName, state.config, ctx);
},
});
if (shouldRegisterProxyTool) {
(pi.registerTool as (tool: unknown) => unknown)({
name: "mcp",
label: "MCP",
description: buildProxyDescription(earlyConfig, earlyCache, directSpecs),
promptSnippet: "MCP gateway - connect to MCP servers and call their tools",
renderCall: renderMcpProxyToolCall,
parameters: Type.Object({
tool: Type.Optional(Type.String({ description: "Tool name to call (e.g., 'xcodebuild_list_sims')" })),
args: Type.Optional(Type.String({ description: "Arguments as JSON string (e.g., '{\"key\": \"value\"}')" })),
connect: Type.Optional(Type.String({ description: "Server name to connect (lazy connect + metadata refresh)" })),
describe: Type.Optional(Type.String({ description: "Tool name to describe (shows parameters)" })),
search: Type.Optional(Type.String({ description: "Search tools by name/description" })),
regex: Type.Optional(Type.Boolean({ description: "Treat search as regex (default: substring match)" })),
includeSchemas: Type.Optional(Type.Boolean({ description: "Include parameter schemas in search results (default: true)" })),
server: Type.Optional(Type.String({ description: "Filter to specific server (also disambiguates tool calls)" })),
action: Type.Optional(Type.String({ description: "Action: 'ui-messages' to retrieve prompts/intents from UI sessions" })),
}),
renderResult: renderMcpToolResult,
async execute(_toolCallId, params: {
tool?: string;
args?: string;
connect?: string;
describe?: string;
search?: string;
regex?: boolean;
includeSchemas?: boolean;
server?: string;
action?: string;
}, _signal, _onUpdate, _ctx) {
let parsedArgs: Record<string, unknown> | undefined;
if (params.args) {
try {
parsedArgs = JSON.parse(params.args);
if (typeof parsedArgs !== "object" || parsedArgs === null || Array.isArray(parsedArgs)) {
const gotType = Array.isArray(parsedArgs) ? "array" : parsedArgs === null ? "null" : typeof parsedArgs;
throw new Error(`Invalid args: expected a JSON object, got ${gotType}`);
}
} catch (error) {
if (error instanceof SyntaxError) {
throw new Error(`Invalid args JSON: ${error.message}`, { cause: error });
}
throw error;
}
}
if (!state && initPromise) {
try {
state = await initPromise;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
content: [{ type: "text" as const, text: `MCP initialization failed: ${message}` }],
details: { error: "init_failed", message },
};
}
}
if (!state) {
return {
content: [{ type: "text" as const, text: "MCP not initialized" }],
details: { error: "not_initialized" },
};
}
if (params.action === "ui-messages") {
return executeUiMessages(state);
}
if (params.tool) {
return executeCall(state, params.tool, parsedArgs, params.server, getPiTools);
}
if (params.connect) {
return executeConnect(state, params.connect);
}
if (params.describe) {
return executeDescribe(state, params.describe);
}
if (params.search) {
return executeSearch(state, params.search, params.regex, params.server, params.includeSchemas);
}
if (params.server) {
return executeList(state, params.server);
}
return executeStatus(state);
},
});
}
}