@wincode/mcp 0.0.0-stage → 0.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.
@@ -0,0 +1,501 @@
1
+ import * as path from "node:path";
2
+ import type { ToolCallOutput } from "@wincode/agent-core";
3
+ import type {
4
+ PluginFactory,
5
+ PluginLoadContext,
6
+ PluginStatus,
7
+ PluginStatusPanelActionContext,
8
+ PluginStatusPanelRegistration,
9
+ } from "@wincode/coding-agent";
10
+ import open from "open";
11
+ import { z } from "zod";
12
+ import {
13
+ createMcpOAuthProvider,
14
+ loginMcpServer,
15
+ logoutMcpServer,
16
+ type McpSecretStore,
17
+ } from "../oauth";
18
+ import {
19
+ createMcpRegistry,
20
+ type McpOAuthRedirectReader,
21
+ type McpRegistry,
22
+ type McpRegistryDeps,
23
+ type McpServerStatus,
24
+ } from "../registry";
25
+ import { createMcpToolExecutor, normalizeMcpResourceContents } from "../result";
26
+ import { createMcpConfigLoader } from "./config";
27
+
28
+ export type McpPluginDependencies = Readonly<
29
+ Pick<McpRegistryDeps, "createClient" | "createOAuthProvider" | "env"> &
30
+ Partial<
31
+ Pick<McpRegistryDeps, "loadConfig" | "loginOAuth" | "logoutOAuth">
32
+ > &
33
+ Readonly<{ createSecretStore?: (userDataDir: string) => McpSecretStore }>
34
+ >;
35
+
36
+ const statusFor = (state: McpServerStatus["state"]): PluginStatus => {
37
+ switch (state) {
38
+ case "connected":
39
+ return "success";
40
+ case "connecting":
41
+ return "pending";
42
+ case "degraded":
43
+ return "warning";
44
+ case "failed":
45
+ return "error";
46
+ default:
47
+ return "idle";
48
+ }
49
+ };
50
+
51
+ const STATUS_ACTION_IDS = {
52
+ exposure: "exposure",
53
+ login: "login",
54
+ logout: "logout",
55
+ reconnect: "reconnect",
56
+ toggle: "toggle",
57
+ } as const;
58
+
59
+ type StatusActionId =
60
+ (typeof STATUS_ACTION_IDS)[keyof typeof STATUS_ACTION_IDS];
61
+
62
+ type StatusAction = Readonly<{
63
+ id: StatusActionId;
64
+ label: string;
65
+ shortcut: "space";
66
+ }>;
67
+
68
+ const connectionActions = (
69
+ server: McpServerStatus
70
+ ): readonly StatusAction[] => {
71
+ if (server.state === "connecting") {
72
+ return [];
73
+ }
74
+ if (server.state === "degraded" || server.state === "failed") {
75
+ return [
76
+ {
77
+ id: STATUS_ACTION_IDS.reconnect,
78
+ label: "Reconnect",
79
+ shortcut: "space",
80
+ },
81
+ ];
82
+ }
83
+ return [
84
+ {
85
+ id: STATUS_ACTION_IDS.toggle,
86
+ label: server.state === "disabled" ? "Enable" : "Disable",
87
+ shortcut: "space",
88
+ },
89
+ ];
90
+ };
91
+
92
+ const authenticationActions = (
93
+ server: McpServerStatus
94
+ ): readonly StatusAction[] => {
95
+ if (server.auth === "required") {
96
+ return [
97
+ { id: STATUS_ACTION_IDS.login, label: "Sign in", shortcut: "space" },
98
+ ];
99
+ }
100
+ if (server.auth === "authenticated") {
101
+ return [
102
+ { id: STATUS_ACTION_IDS.logout, label: "Sign out", shortcut: "space" },
103
+ ];
104
+ }
105
+ return [];
106
+ };
107
+
108
+ const statusActions = (server: McpServerStatus): readonly StatusAction[] => [
109
+ ...connectionActions(server),
110
+ ...authenticationActions(server),
111
+ {
112
+ id: STATUS_ACTION_IDS.exposure,
113
+ label: server.exposure === "direct" ? "Hide tools" : "Expose tools",
114
+ shortcut: "space",
115
+ },
116
+ ];
117
+
118
+ const authenticationLabel = (auth: McpServerStatus["auth"]): string => {
119
+ if (auth === "authenticated") {
120
+ return "authenticated";
121
+ }
122
+ if (auth === "required") {
123
+ return "auth required";
124
+ }
125
+ return "no auth";
126
+ };
127
+
128
+ const redirectReaderFor =
129
+ (
130
+ requestTextInput: PluginStatusPanelActionContext["requestTextInput"]
131
+ ): McpOAuthRedirectReader =>
132
+ async (callback) => {
133
+ const controller = new AbortController();
134
+ try {
135
+ const pastedUrl = requestTextInput(
136
+ "Paste the full OAuth redirect URL if the browser cannot return to Wincode.",
137
+ controller.signal
138
+ ).then((value) => {
139
+ if (value === undefined) {
140
+ throw new Error("OAuth sign-in was canceled.");
141
+ }
142
+ try {
143
+ return new URL(value.trim());
144
+ } catch {
145
+ throw new Error("The OAuth redirect URL is invalid.");
146
+ }
147
+ });
148
+ return await Promise.race([callback, pastedUrl]);
149
+ } finally {
150
+ controller.abort();
151
+ }
152
+ };
153
+
154
+ const persistServerField = async (
155
+ context: PluginLoadContext,
156
+ server: McpServerStatus,
157
+ field: "enabled" | "exposure",
158
+ value: boolean | "direct" | "hidden"
159
+ ): Promise<void> => {
160
+ const snapshot = await context.configFiles.getSnapshot("mcp");
161
+ const origin =
162
+ snapshot.sourceFor(["mcpServers", server.name, field]) ??
163
+ snapshot.sourceFor(["mcpServers", server.name]);
164
+ const trustedWorkspace = context.trustedProjectRoots?.some(
165
+ (root) => path.resolve(root) === path.resolve(context.workspace)
166
+ );
167
+ let scope: "global" | "project" =
168
+ origin?.scope === "project" || (origin === undefined && trustedWorkspace)
169
+ ? "project"
170
+ : "global";
171
+ if (field === "enabled" && scope === "global" && trustedWorkspace) {
172
+ scope = "project";
173
+ }
174
+ if (scope === "project" && !trustedWorkspace) {
175
+ throw new Error("Project MCP configuration requires a trusted project.");
176
+ }
177
+ const owner =
178
+ server.source?.scope === scope
179
+ ? snapshot.sources.find(
180
+ (source) =>
181
+ source.scope === scope && source.path === server.source?.path
182
+ )
183
+ : undefined;
184
+ const originSource =
185
+ origin?.scope === scope
186
+ ? snapshot.sources.find(
187
+ (source) => source.scope === scope && source.path === origin.path
188
+ )
189
+ : undefined;
190
+ const target =
191
+ owner ??
192
+ originSource ??
193
+ (scope === "project"
194
+ ? snapshot.sources.findLast((source) => source.scope === scope)
195
+ : snapshot.sources.find((source) => source.scope === scope));
196
+ if (target === undefined) {
197
+ throw new Error(`Could not find the ${scope} MCP configuration file.`);
198
+ }
199
+ await context.configFiles.setValue(
200
+ "mcp",
201
+ scope,
202
+ ["mcpServers", server.name, field],
203
+ value,
204
+ target.path
205
+ );
206
+ };
207
+
208
+ type StatusActionExecution = Readonly<{
209
+ actionContext?: PluginStatusPanelActionContext;
210
+ context: PluginLoadContext;
211
+ registry: McpRegistry;
212
+ server: McpServerStatus;
213
+ serverName: string;
214
+ }>;
215
+
216
+ type StatusActionHandler = (execution: StatusActionExecution) => Promise<void>;
217
+
218
+ const statusActionHandlers = {
219
+ [STATUS_ACTION_IDS.reconnect]: ({ registry, serverName }) =>
220
+ registry.reconnect(serverName),
221
+ [STATUS_ACTION_IDS.login]: ({ actionContext, registry, serverName }) =>
222
+ registry.login(
223
+ serverName,
224
+ actionContext === undefined
225
+ ? undefined
226
+ : redirectReaderFor(actionContext.requestTextInput)
227
+ ),
228
+ [STATUS_ACTION_IDS.logout]: ({ registry, serverName }) =>
229
+ registry.logout(serverName),
230
+ [STATUS_ACTION_IDS.toggle]: async ({
231
+ context,
232
+ registry,
233
+ server,
234
+ serverName,
235
+ }) => {
236
+ await persistServerField(
237
+ context,
238
+ server,
239
+ "enabled",
240
+ server.state === "disabled"
241
+ );
242
+ await registry.toggle(serverName);
243
+ },
244
+ [STATUS_ACTION_IDS.exposure]: async ({ context, registry, server }) => {
245
+ await persistServerField(
246
+ context,
247
+ server,
248
+ "exposure",
249
+ server.exposure === "direct" ? "hidden" : "direct"
250
+ );
251
+ await registry.initialize();
252
+ },
253
+ } satisfies Record<StatusActionId, StatusActionHandler>;
254
+
255
+ const isStatusActionId = (actionId: string): actionId is StatusActionId =>
256
+ Object.hasOwn(statusActionHandlers, actionId);
257
+
258
+ const createStatusPanel = (
259
+ getRegistry: () => McpRegistry | undefined,
260
+ context: PluginLoadContext
261
+ ): PluginStatusPanelRegistration => ({
262
+ emptyText: "No MCP servers",
263
+ getSnapshot: () => {
264
+ const statuses = getRegistry()?.getStatuses() ?? [];
265
+ const connected = statuses.filter(
266
+ ({ state }) => state === "connected"
267
+ ).length;
268
+ const hasFailures = statuses.some(
269
+ ({ state }) => state === "degraded" || state === "failed"
270
+ );
271
+ let status: PluginStatus = "idle";
272
+ if (hasFailures) {
273
+ status = "warning";
274
+ } else if (connected > 0) {
275
+ status = "success";
276
+ }
277
+ return {
278
+ items: statuses.map((server) => {
279
+ const sourceLabel =
280
+ server.source?.scope === "plugin"
281
+ ? `Plugin ${server.source.path.slice("plugin:".length)}`
282
+ : (server.source?.scope ?? "unknown source");
283
+ return {
284
+ actions: statusActions(server),
285
+ detail: server.error ?? server.source?.path,
286
+ id: server.name,
287
+ label: server.name,
288
+ status: statusFor(server.state),
289
+ summary: `${server.toolCount} tools • ${server.transport} • ${server.exposure} • ${authenticationLabel(server.auth)} • ${sourceLabel}`,
290
+ };
291
+ }),
292
+ status,
293
+ summary: String(connected),
294
+ };
295
+ },
296
+ id: "servers",
297
+ indicatorLabel: "MCPs",
298
+ refresh: async () => {
299
+ await getRegistry()?.initialize();
300
+ },
301
+ runAction: async (serverName, actionId, actionContext) => {
302
+ const registry = getRegistry();
303
+ if (registry === undefined) {
304
+ throw new Error("MCP registry is unavailable.");
305
+ }
306
+ const server = registry
307
+ .getStatuses()
308
+ .find((status) => status.name === serverName);
309
+ if (server === undefined) {
310
+ throw new Error(`MCP Server '${serverName}' is unavailable.`);
311
+ }
312
+ if (!isStatusActionId(actionId)) {
313
+ throw new Error(`Unknown MCP status action '${actionId}'.`);
314
+ }
315
+ await statusActionHandlers[actionId]({
316
+ ...(actionContext === undefined ? {} : { actionContext }),
317
+ context,
318
+ registry,
319
+ server,
320
+ serverName,
321
+ });
322
+ },
323
+ subscribe: (listener) =>
324
+ getRegistry()?.subscribe(listener) ?? (() => undefined),
325
+ title: "MCP Servers",
326
+ });
327
+
328
+ const failure = (errorText: string): ToolCallOutput => ({
329
+ errorText,
330
+ type: "failure",
331
+ });
332
+
333
+ /** Creates MCP's Plugin factory with injectable OAuth storage and runtime adapters. */
334
+ export const createMcpPluginFactory =
335
+ (dependencies: McpPluginDependencies = {}): PluginFactory =>
336
+ async (api, context) => {
337
+ let registry: McpRegistry | undefined;
338
+ const getRegistry = (): McpRegistry => {
339
+ if (registry === undefined) {
340
+ throw new Error("MCP registry has not started.");
341
+ }
342
+ return registry;
343
+ };
344
+ const plugin = api.definePlugin({ id: "mcp" });
345
+ const secrets = dependencies.createSecretStore?.(context.userDataDir);
346
+ const requireSecrets = (): McpSecretStore => {
347
+ if (secrets === undefined) {
348
+ throw new Error(
349
+ "MCP OAuth requires an MCP secret store from the host."
350
+ );
351
+ }
352
+ return secrets;
353
+ };
354
+ plugin.onStart(async () => {
355
+ const nextRegistry = createMcpRegistry({
356
+ ...(dependencies.createClient === undefined
357
+ ? {}
358
+ : { createClient: dependencies.createClient }),
359
+ ...(dependencies.createOAuthProvider === undefined
360
+ ? {
361
+ createOAuthProvider: (config) =>
362
+ createMcpOAuthProvider({
363
+ oauth: config.oauth,
364
+ secrets: requireSecrets(),
365
+ serverName: config.name,
366
+ }),
367
+ }
368
+ : { createOAuthProvider: dependencies.createOAuthProvider }),
369
+ ...(dependencies.env === undefined ? {} : { env: dependencies.env }),
370
+ loadConfig:
371
+ dependencies.loadConfig ??
372
+ createMcpConfigLoader(
373
+ context.configFiles,
374
+ context.getMcpServerRegistrations
375
+ ),
376
+ loginOAuth:
377
+ dependencies.loginOAuth ??
378
+ (async (config, readRedirectUrl) => {
379
+ await loginMcpServer({
380
+ openAuthorizationUrl: async (url) => {
381
+ await open(url.toString());
382
+ },
383
+ oauth: config.oauth,
384
+ ...(readRedirectUrl === undefined ? {} : { readRedirectUrl }),
385
+ secrets: requireSecrets(),
386
+ serverName: config.name,
387
+ serverUrl: config.url,
388
+ });
389
+ }),
390
+ logoutOAuth:
391
+ dependencies.logoutOAuth ??
392
+ (async (config) => {
393
+ await logoutMcpServer(requireSecrets(), config.name);
394
+ }),
395
+ workspace: context.workspace,
396
+ });
397
+ registry = nextRegistry;
398
+ await nextRegistry.initialize(false);
399
+ });
400
+ plugin.onShutdown(async () => {
401
+ const currentRegistry = registry;
402
+ registry = undefined;
403
+ await currentRegistry?.close();
404
+ });
405
+ plugin.registerStatusPanel(createStatusPanel(() => registry, context));
406
+ plugin.registerCommand({
407
+ description: "Enable, disable, and inspect MCP servers",
408
+ name: "mcps",
409
+ statusPanelId: "servers",
410
+ });
411
+ plugin.onBeforeAgentTurn(async (turn, registration) => {
412
+ const currentRegistry = getRegistry();
413
+ const execute = createMcpToolExecutor(currentRegistry.execute);
414
+ const snapshot = await currentRegistry.createSnapshot(turn.agentId);
415
+ turn.registerTurnCleanup?.(() =>
416
+ currentRegistry.releaseSnapshot?.(snapshot)
417
+ );
418
+ registration.registerTool({
419
+ name: "mcp_list_resources",
420
+ description:
421
+ "List resources exposed by connected, direct-exposure MCP servers. Pass a server and cursor to continue a paginated listing.",
422
+ modelName: "mcp_list_resources",
423
+ inputSchema: z
424
+ .object({
425
+ server: z.string().optional(),
426
+ cursor: z.string().optional(),
427
+ })
428
+ .strict(),
429
+ handler: async (input, toolContext) => ({
430
+ output: await currentRegistry.listResources(
431
+ input.server,
432
+ input.cursor,
433
+ toolContext.signal
434
+ ),
435
+ type: "success",
436
+ }),
437
+ });
438
+ registration.registerTool({
439
+ name: "mcp_list_resource_templates",
440
+ description:
441
+ "List resource templates exposed by connected, direct-exposure MCP servers. Pass a server and cursor to continue a paginated listing.",
442
+ modelName: "mcp_list_resource_templates",
443
+ inputSchema: z
444
+ .object({
445
+ server: z.string().optional(),
446
+ cursor: z.string().optional(),
447
+ })
448
+ .strict(),
449
+ handler: async (input, toolContext) => ({
450
+ output: await currentRegistry.listResourceTemplates(
451
+ input.server,
452
+ input.cursor,
453
+ toolContext.signal
454
+ ),
455
+ type: "success",
456
+ }),
457
+ });
458
+ registration.registerTool({
459
+ name: "mcp_read_resource",
460
+ description:
461
+ "Read a resource from a connected, direct-exposure MCP server. Oversized text includes a bounded excerpt and is saved to a private temporary artifact; images are preserved and other binary content is saved there.",
462
+ modelName: "mcp_read_resource",
463
+ inputSchema: z.object({ server: z.string(), uri: z.string() }).strict(),
464
+ handler: async (input, toolContext) => {
465
+ const result = await currentRegistry.readResource(
466
+ input.server,
467
+ input.uri,
468
+ toolContext.signal
469
+ );
470
+ return {
471
+ output: {
472
+ server: result.server,
473
+ contents: await normalizeMcpResourceContents(result.contents),
474
+ },
475
+ type: "success",
476
+ };
477
+ },
478
+ });
479
+ for (const entry of snapshot.manifest) {
480
+ const tool = snapshot.tools.get(entry.name);
481
+ if (tool === undefined) {
482
+ continue;
483
+ }
484
+ registration.registerTool({
485
+ description: entry.description,
486
+ inputSchema: { jsonSchema: entry.inputSchema },
487
+ modelName: entry.name,
488
+ name: entry.name,
489
+ handler: async (input, toolContext) => {
490
+ if (execute === undefined) {
491
+ return failure("MCP execution is unavailable.");
492
+ }
493
+ return execute(snapshot, entry.name, input, toolContext.signal);
494
+ },
495
+ });
496
+ }
497
+ });
498
+ };
499
+
500
+ export const mcpPluginFactory = createMcpPluginFactory();
501
+ export default mcpPluginFactory;