@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.
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@wincode/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./src/index.ts",
8
+ "import": "./src/index.ts"
9
+ },
10
+ "./plugin": {
11
+ "types": "./src/plugin/index.ts",
12
+ "import": "./src/plugin/index.ts"
13
+ }
14
+ },
15
+ "scripts": {
16
+ "check-types": "tsc --noEmit",
17
+ "test": "bun ../../scripts/test-portfolio.ts default --package mcp"
18
+ },
19
+ "dependencies": {
20
+ "@modelcontextprotocol/client": "^2.0.0",
21
+ "@wincode/agent-core": "0.1.0",
22
+ "@wincode/utils": "0.1.0",
23
+ "open": "^10.2.0",
24
+ "type-fest": "^5.9.0",
25
+ "zod": "^4.1.13"
26
+ },
27
+ "peerDependencies": {
28
+ "@wincode/coding-agent": "^0.1.0"
29
+ },
30
+ "devDependencies": {
31
+ "@modelcontextprotocol/server": "^2.0.0",
32
+ "@types/bun": "^1.4.2",
33
+ "@wincode/coding-agent": "0.1.0",
34
+ "typescript": "^7.0.2"
35
+ }
36
+ }
package/src/client.ts ADDED
@@ -0,0 +1,370 @@
1
+ import * as path from "node:path";
2
+ import {
3
+ type CallToolResult,
4
+ Client,
5
+ type ListResourcesRequest,
6
+ type ListResourceTemplatesRequest,
7
+ type ListToolsRequest,
8
+ type OAuthClientProvider,
9
+ type ReadResourceResult,
10
+ type Resource,
11
+ type ResourceTemplateType,
12
+ StreamableHTTPClientTransport,
13
+ type Tool,
14
+ } from "@modelcontextprotocol/client";
15
+ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
16
+ import { isNull, isUndefined, omitUndefined } from "@wincode/utils";
17
+ import type { ResolvedMcpServerConfig } from "./config";
18
+ import { sanitizeMessage } from "./sanitize";
19
+
20
+ export type McpClientTool = {
21
+ description?: string;
22
+ inputSchema: Record<string, unknown>;
23
+ name: string;
24
+ };
25
+
26
+ export type McpClientResource = Resource;
27
+ export type McpClientResourceTemplate = ResourceTemplateType;
28
+ export type McpClientResourceContent = ReadResourceResult["contents"][number];
29
+ export type McpClientResourcePage = Readonly<{
30
+ resources: readonly McpClientResource[];
31
+ nextCursor?: string;
32
+ }>;
33
+ export type McpClientResourceTemplatePage = Readonly<{
34
+ resourceTemplates: readonly McpClientResourceTemplate[];
35
+ nextCursor?: string;
36
+ }>;
37
+
38
+ export type McpClient = {
39
+ callTool(
40
+ name: string,
41
+ input: unknown,
42
+ signal?: AbortSignal
43
+ ): Promise<CallToolResult>;
44
+ close(): Promise<void>;
45
+ connect(signal?: AbortSignal): Promise<void>;
46
+ listTools(signal?: AbortSignal): Promise<readonly McpClientTool[]>;
47
+ listResources?(
48
+ cursor?: string,
49
+ signal?: AbortSignal
50
+ ): Promise<McpClientResourcePage>;
51
+ listResourceTemplates?(
52
+ cursor?: string,
53
+ signal?: AbortSignal
54
+ ): Promise<McpClientResourceTemplatePage>;
55
+ readResource?(
56
+ uri: string,
57
+ signal?: AbortSignal
58
+ ): Promise<readonly McpClientResourceContent[]>;
59
+ setToolsChangedListener(
60
+ listener: (tools: readonly McpClientTool[]) => void
61
+ ): void;
62
+ };
63
+
64
+ export type McpStdioTransportOptions = {
65
+ args: string[];
66
+ command: string;
67
+ cwd: string;
68
+ env: Record<string, string>;
69
+ stderr: "ignore";
70
+ };
71
+
72
+ export type McpHttpTransportOptions = {
73
+ authProvider?: OAuthClientProvider;
74
+ requestInit: { headers: Record<string, string> };
75
+ };
76
+
77
+ export type McpSdkClient = {
78
+ callTool(
79
+ params: { name: string; arguments?: unknown },
80
+ options?: { signal?: AbortSignal }
81
+ ): Promise<CallToolResult>;
82
+ close(): Promise<void>;
83
+ connect(
84
+ transport: McpSdkTransport,
85
+ options?: { signal?: AbortSignal }
86
+ ): Promise<void>;
87
+ listTools(
88
+ params: ListToolsRequest["params"] | undefined,
89
+ options?: { signal?: AbortSignal }
90
+ ): Promise<{ tools: Tool[] }>;
91
+ listResources?(
92
+ params: ListResourcesRequest["params"] | undefined,
93
+ options?: { signal?: AbortSignal }
94
+ ): Promise<{ resources: Resource[]; nextCursor?: string }>;
95
+ listResourceTemplates?(
96
+ params: ListResourceTemplatesRequest["params"] | undefined,
97
+ options?: { signal?: AbortSignal }
98
+ ): Promise<{
99
+ resourceTemplates: ResourceTemplateType[];
100
+ nextCursor?: string;
101
+ }>;
102
+ readResource?(
103
+ params: { uri: string },
104
+ options?: { signal?: AbortSignal }
105
+ ): Promise<ReadResourceResult>;
106
+ };
107
+
108
+ export type McpSdkTransport = {
109
+ close(): Promise<void>;
110
+ start(): Promise<void>;
111
+ };
112
+
113
+ export type McpClientFactoryDeps = {
114
+ createClient(options: {
115
+ listChanged: {
116
+ tools: {
117
+ onChanged: (error: Error | null, tools: Tool[] | null) => void;
118
+ };
119
+ };
120
+ }): McpSdkClient;
121
+ createHttpTransport(
122
+ url: URL,
123
+ options: McpHttpTransportOptions
124
+ ): McpSdkTransport;
125
+ createStartupSignal(timeoutMs: number): AbortSignal;
126
+ createStdioTransport(options: McpStdioTransportOptions): McpSdkTransport;
127
+ createOAuthProvider?: (
128
+ config: Extract<ResolvedMcpServerConfig, { type: "remote" }>
129
+ ) => OAuthClientProvider;
130
+ environment: Record<string, string>;
131
+ workspace: string;
132
+ };
133
+
134
+ export class McpClientError extends Error {
135
+ readonly serverName: string;
136
+
137
+ constructor(serverName: string, message: string) {
138
+ super(`${serverName}: ${message}`);
139
+ this.name = "McpClientError";
140
+ this.serverName = serverName;
141
+ }
142
+ }
143
+
144
+ const toClientTool = (tool: Tool): McpClientTool => ({
145
+ name: tool.name,
146
+ inputSchema: tool.inputSchema,
147
+ ...omitUndefined({ description: tool.description }),
148
+ });
149
+
150
+ const localTransportOptions = (
151
+ config: Extract<ResolvedMcpServerConfig, { type: "local" }>,
152
+ deps: McpClientFactoryDeps
153
+ ): McpStdioTransportOptions => {
154
+ const [command, ...args] = config.command;
155
+ if (isUndefined(command)) {
156
+ throw new Error(`MCP server ${config.name} has an empty command`);
157
+ }
158
+ let cwd: string;
159
+ if (isUndefined(config.cwd)) {
160
+ cwd = deps.workspace;
161
+ } else if (path.isAbsolute(config.cwd)) {
162
+ cwd = config.cwd;
163
+ } else {
164
+ cwd = path.normalize(path.resolve(deps.workspace, config.cwd));
165
+ }
166
+ return {
167
+ command,
168
+ args,
169
+ cwd,
170
+ env: { ...deps.environment, ...config.environment },
171
+ stderr: "ignore",
172
+ };
173
+ };
174
+
175
+ const transientHttpFailurePattern =
176
+ /(?:\b408\b|\b425\b|\b429\b|\b5\d{2}\b|ECONNRESET|ETIMEDOUT|EAI_AGAIN|fetch failed|network error)/iu;
177
+
178
+ const isTransientHttpFailure = (error: unknown): boolean =>
179
+ transientHttpFailurePattern.test(
180
+ error instanceof Error ? error.message : String(error)
181
+ );
182
+
183
+ const retryIdempotentRequest = async <Result>(
184
+ config: ResolvedMcpServerConfig,
185
+ operation: () => Promise<Result>
186
+ ): Promise<Result> => {
187
+ for (let attempt = 0; attempt < 3; attempt += 1) {
188
+ try {
189
+ return await operation();
190
+ } catch (error) {
191
+ if (
192
+ config.type !== "remote" ||
193
+ attempt === 2 ||
194
+ !isTransientHttpFailure(error)
195
+ ) {
196
+ throw error;
197
+ }
198
+ await Bun.sleep(150 * (attempt + 1));
199
+ }
200
+ }
201
+ throw new Error("MCP request retry limit reached");
202
+ };
203
+
204
+ const sanitizeError = (
205
+ config: ResolvedMcpServerConfig,
206
+ error: unknown
207
+ ): McpClientError =>
208
+ new McpClientError(
209
+ config.name,
210
+ sanitizeMessage(config, error, "unknown MCP client error")
211
+ );
212
+
213
+ export function createSdkMcpClient(
214
+ config: ResolvedMcpServerConfig,
215
+ deps: McpClientFactoryDeps
216
+ ): McpClient {
217
+ let toolsChanged: ((tools: readonly McpClientTool[]) => void) | undefined;
218
+ let client: McpSdkClient | undefined;
219
+
220
+ const getClient = (): McpSdkClient => {
221
+ if (!isUndefined(client)) {
222
+ return client;
223
+ }
224
+ client = deps.createClient({
225
+ listChanged: {
226
+ tools: {
227
+ onChanged: (error, tools) => {
228
+ if (!isNull(error) || isNull(tools)) {
229
+ return;
230
+ }
231
+ toolsChanged?.(tools.map(toClientTool));
232
+ },
233
+ },
234
+ },
235
+ });
236
+ return client;
237
+ };
238
+
239
+ const guard = async <T>(operation: () => Promise<T>): Promise<T> => {
240
+ try {
241
+ return await operation();
242
+ } catch (error) {
243
+ throw sanitizeError(config, error);
244
+ }
245
+ };
246
+
247
+ return {
248
+ async connect(signal?: AbortSignal) {
249
+ const startup = deps.createStartupSignal(config.timeout.startup);
250
+ const combined = signal ? AbortSignal.any([startup, signal]) : startup;
251
+ const sdkClient = getClient();
252
+ const transport =
253
+ config.type === "local"
254
+ ? deps.createStdioTransport(localTransportOptions(config, deps))
255
+ : deps.createHttpTransport(new URL(config.url), {
256
+ requestInit: { headers: config.headers ?? {} },
257
+ ...(config.auth === "oauth" &&
258
+ deps.createOAuthProvider !== undefined
259
+ ? { authProvider: deps.createOAuthProvider(config) }
260
+ : {}),
261
+ });
262
+ try {
263
+ await sdkClient.connect(transport, { signal: combined });
264
+ } catch (error) {
265
+ if (startup.aborted) {
266
+ throw new McpClientError(config.name, "connect timed out");
267
+ }
268
+ throw sanitizeError(config, error);
269
+ }
270
+ },
271
+ async close() {
272
+ return guard(async () => getClient().close());
273
+ },
274
+ async listTools(signal?: AbortSignal) {
275
+ return guard(async () => {
276
+ const { tools } = await retryIdempotentRequest(config, () =>
277
+ getClient().listTools(undefined, { signal })
278
+ );
279
+ return tools.map(toClientTool);
280
+ });
281
+ },
282
+ async listResources(cursor?: string, signal?: AbortSignal) {
283
+ return guard(async () => {
284
+ const sdkClient = getClient();
285
+ const listResources = sdkClient.listResources;
286
+ if (isUndefined(listResources)) {
287
+ throw new Error("MCP server does not support resources");
288
+ }
289
+ const result = await retryIdempotentRequest(config, () =>
290
+ listResources.call(
291
+ sdkClient,
292
+ cursor === undefined ? undefined : { cursor },
293
+ { signal }
294
+ )
295
+ );
296
+ return {
297
+ resources: result.resources,
298
+ ...omitUndefined({ nextCursor: result.nextCursor }),
299
+ };
300
+ });
301
+ },
302
+ async listResourceTemplates(cursor?: string, signal?: AbortSignal) {
303
+ return guard(async () => {
304
+ const sdkClient = getClient();
305
+ const listResourceTemplates = sdkClient.listResourceTemplates;
306
+ if (isUndefined(listResourceTemplates)) {
307
+ throw new Error("MCP server does not support resource templates");
308
+ }
309
+ const result = await retryIdempotentRequest(config, () =>
310
+ listResourceTemplates.call(
311
+ sdkClient,
312
+ cursor === undefined ? undefined : { cursor },
313
+ { signal }
314
+ )
315
+ );
316
+ return {
317
+ resourceTemplates: result.resourceTemplates,
318
+ ...omitUndefined({ nextCursor: result.nextCursor }),
319
+ };
320
+ });
321
+ },
322
+ async readResource(uri: string, signal?: AbortSignal) {
323
+ return guard(async () => {
324
+ const sdkClient = getClient();
325
+ const readResource = sdkClient.readResource;
326
+ if (isUndefined(readResource)) {
327
+ throw new Error("MCP server does not support resources");
328
+ }
329
+ const result = await retryIdempotentRequest(config, () =>
330
+ readResource.call(sdkClient, { uri }, { signal })
331
+ );
332
+ return result.contents;
333
+ });
334
+ },
335
+ async callTool(name: string, input: unknown, signal?: AbortSignal) {
336
+ return guard(async () =>
337
+ getClient().callTool({ name, arguments: input }, { signal })
338
+ );
339
+ },
340
+ setToolsChangedListener(
341
+ listener: (tools: readonly McpClientTool[]) => void
342
+ ) {
343
+ toolsChanged = listener;
344
+ },
345
+ };
346
+ }
347
+
348
+ export type McpClientDepsInput = {
349
+ clientInfo: { name: string; version: string };
350
+ createOAuthProvider?: McpClientFactoryDeps["createOAuthProvider"];
351
+ environment: Record<string, string>;
352
+ workspace: string;
353
+ };
354
+
355
+ export function createSdkMcpClientDeps(
356
+ input: McpClientDepsInput
357
+ ): McpClientFactoryDeps {
358
+ return {
359
+ ...(input.createOAuthProvider === undefined
360
+ ? {}
361
+ : { createOAuthProvider: input.createOAuthProvider }),
362
+ environment: input.environment,
363
+ workspace: input.workspace,
364
+ createClient: (options) => new Client(input.clientInfo, options),
365
+ createStdioTransport: (options) => new StdioClientTransport(options),
366
+ createHttpTransport: (url, options) =>
367
+ new StreamableHTTPClientTransport(url, options),
368
+ createStartupSignal: (timeoutMs) => AbortSignal.timeout(timeoutMs),
369
+ };
370
+ }