@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,642 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import type { CallToolResult, Tool } from "@modelcontextprotocol/client";
3
+ import type {
4
+ LocalMcpServerConfig,
5
+ RemoteMcpServerConfig,
6
+ ResolvedMcpServerConfig,
7
+ } from "@wincode/mcp";
8
+ import {
9
+ createSdkMcpClient,
10
+ McpClientError,
11
+ type McpClientFactoryDeps,
12
+ type McpClientTool,
13
+ } from "@wincode/mcp";
14
+
15
+ type FakeClient = {
16
+ close(): Promise<void>;
17
+ connect(
18
+ transport: unknown,
19
+ options?: { signal?: AbortSignal }
20
+ ): Promise<void>;
21
+ listTools(
22
+ params?: unknown,
23
+ options?: { signal?: AbortSignal }
24
+ ): Promise<{ tools: Tool[] }>;
25
+ callTool(
26
+ params: { name: string; arguments?: unknown },
27
+ options?: { signal?: AbortSignal }
28
+ ): Promise<CallToolResult>;
29
+ };
30
+
31
+ const fakeTransport = {
32
+ close: async () => {
33
+ return;
34
+ },
35
+ start: async () => {
36
+ return;
37
+ },
38
+ };
39
+ const fakeClient = (): FakeClient => ({
40
+ close: async () => {
41
+ return;
42
+ },
43
+ connect: async () => {
44
+ return;
45
+ },
46
+ listTools: async () => ({ tools: [] }),
47
+ callTool: async () => ({ content: [] }),
48
+ });
49
+ const rejectedMcpError = async (
50
+ promise: Promise<unknown>
51
+ ): Promise<McpClientError> => {
52
+ try {
53
+ await promise;
54
+ } catch (error) {
55
+ if (error instanceof McpClientError) {
56
+ return error;
57
+ }
58
+ throw new Error("expected McpClientError rejection", { cause: error });
59
+ }
60
+ throw new Error("expected rejection");
61
+ };
62
+ const failHttp: McpClientFactoryDeps["createHttpTransport"] = () => {
63
+ throw new Error("unexpected http transport");
64
+ };
65
+ const failStdio: McpClientFactoryDeps["createStdioTransport"] = () => {
66
+ throw new Error("unexpected stdio transport");
67
+ };
68
+ const tool = (name: string, patch: Partial<Tool> = {}): Tool => ({
69
+ name,
70
+ inputSchema: { type: "object" },
71
+ ...patch,
72
+ });
73
+ const baseLocal: LocalMcpServerConfig = {
74
+ name: "demo",
75
+ type: "local",
76
+ command: ["bun", "x", "demo"],
77
+ disabled: false,
78
+ timeout: { startup: 30_000, catalog: 30_000, execution: 43_200_000 },
79
+ };
80
+ const baseRemote: RemoteMcpServerConfig = {
81
+ name: "remote-demo",
82
+ type: "remote",
83
+ url: "https://mcp.deepwiki.com/mcp",
84
+ disabled: false,
85
+ timeout: { startup: 30_000, catalog: 30_000, execution: 43_200_000 },
86
+ };
87
+ const localConfig = (
88
+ patch: Partial<LocalMcpServerConfig> = {}
89
+ ): ResolvedMcpServerConfig => ({ ...baseLocal, ...patch });
90
+ const remoteConfig = (
91
+ patch: Partial<RemoteMcpServerConfig> = {}
92
+ ): ResolvedMcpServerConfig => ({ ...baseRemote, ...patch });
93
+ const baseDeps = (
94
+ overrides: Partial<McpClientFactoryDeps> = {}
95
+ ): McpClientFactoryDeps => ({
96
+ environment: {},
97
+ workspace: "/workspace",
98
+ createClient: () => fakeClient(),
99
+ createStdioTransport: () => fakeTransport,
100
+ createHttpTransport: () => fakeTransport,
101
+ createStartupSignal: () => new AbortController().signal,
102
+ ...overrides,
103
+ });
104
+
105
+ describe("createSdkMcpClient", () => {
106
+ test("retries transient remote catalog failures without replaying tool calls", async () => {
107
+ let catalogAttempts = 0;
108
+ let toolCallAttempts = 0;
109
+ const adapter = createSdkMcpClient(
110
+ remoteConfig(),
111
+ baseDeps({
112
+ createClient: () => ({
113
+ ...fakeClient(),
114
+ listTools: async () => {
115
+ catalogAttempts += 1;
116
+ if (catalogAttempts < 3) {
117
+ throw new Error("HTTP 503 Service Unavailable");
118
+ }
119
+ return { tools: [tool("echo")] };
120
+ },
121
+ callTool: async () => {
122
+ toolCallAttempts += 1;
123
+ throw new Error("HTTP 503 Service Unavailable");
124
+ },
125
+ }),
126
+ })
127
+ );
128
+ await adapter.connect();
129
+
130
+ await expect(adapter.listTools()).resolves.toEqual([
131
+ { name: "echo", inputSchema: { type: "object" } },
132
+ ]);
133
+ await expect(adapter.callTool("echo", {})).rejects.toBeInstanceOf(
134
+ McpClientError
135
+ );
136
+ expect(catalogAttempts).toBe(3);
137
+ expect(toolCallAttempts).toBe(1);
138
+ });
139
+
140
+ test("constructs local stdio transport from argv without shell", async () => {
141
+ const transports: unknown[] = [];
142
+ const adapter = createSdkMcpClient(
143
+ localConfig({ cwd: "/workspace", environment: { LOG_LEVEL: "info" } }),
144
+ baseDeps({
145
+ environment: { PATH: "/bin" },
146
+ createStdioTransport: (options) => {
147
+ transports.push(options);
148
+ return fakeTransport;
149
+ },
150
+ createHttpTransport: failHttp,
151
+ })
152
+ );
153
+ await adapter.connect();
154
+ expect(transports).toEqual([
155
+ {
156
+ args: ["x", "demo"],
157
+ command: "bun",
158
+ cwd: "/workspace",
159
+ env: { LOG_LEVEL: "info", PATH: "/bin" },
160
+ stderr: "ignore",
161
+ },
162
+ ]);
163
+ });
164
+
165
+ test("resolves relative cwd against the workspace and normalizes it", async () => {
166
+ const transports: unknown[] = [];
167
+ const adapter = createSdkMcpClient(
168
+ localConfig({ cwd: "./tools/../servers" }),
169
+ baseDeps({
170
+ workspace: "/workspace/project",
171
+ createStdioTransport: (options) => {
172
+ transports.push(options);
173
+ return fakeTransport;
174
+ },
175
+ createHttpTransport: failHttp,
176
+ })
177
+ );
178
+ await adapter.connect();
179
+ expect(transports[0]).toMatchObject({ cwd: "/workspace/project/servers" });
180
+ });
181
+
182
+ test("keeps absolute cwd as-is", async () => {
183
+ const transports: unknown[] = [];
184
+ const adapter = createSdkMcpClient(
185
+ localConfig({ cwd: "/abs/custom" }),
186
+ baseDeps({
187
+ workspace: "/workspace",
188
+ createStdioTransport: (options) => {
189
+ transports.push(options);
190
+ return fakeTransport;
191
+ },
192
+ createHttpTransport: failHttp,
193
+ })
194
+ );
195
+ await adapter.connect();
196
+ expect(transports[0]).toMatchObject({ cwd: "/abs/custom" });
197
+ });
198
+
199
+ test("merges inherited environment with overrides where overrides win", async () => {
200
+ const transports: unknown[] = [];
201
+ const adapter = createSdkMcpClient(
202
+ localConfig({
203
+ environment: { LOG_LEVEL: "info", OVERRIDE: "server" },
204
+ }),
205
+ baseDeps({
206
+ environment: { PATH: "/bin", OVERRIDE: "process" },
207
+ createStdioTransport: (options) => {
208
+ transports.push(options);
209
+ return fakeTransport;
210
+ },
211
+ createHttpTransport: failHttp,
212
+ })
213
+ );
214
+ await adapter.connect();
215
+ expect(transports[0]).toMatchObject({
216
+ env: { PATH: "/bin", LOG_LEVEL: "info", OVERRIDE: "server" },
217
+ });
218
+ });
219
+
220
+ test("constructs remote transport from url and requestInit headers only", async () => {
221
+ const httpCalls: {
222
+ url: URL;
223
+ options: { requestInit: { headers: Record<string, string> } };
224
+ }[] = [];
225
+ const adapter = createSdkMcpClient(
226
+ remoteConfig({
227
+ url: "https://mcp.deepwiki.com/mcp",
228
+ headers: { Authorization: "Bearer abc", "X-Key": "v" },
229
+ }),
230
+ baseDeps({
231
+ createStdioTransport: failStdio,
232
+ createHttpTransport: (url, options) => {
233
+ httpCalls.push({ url, options });
234
+ return fakeTransport;
235
+ },
236
+ })
237
+ );
238
+ await adapter.connect();
239
+ expect(httpCalls).toHaveLength(1);
240
+ expect(httpCalls[0]?.url).toBeInstanceOf(URL);
241
+ expect(httpCalls[0]?.url.toString()).toBe("https://mcp.deepwiki.com/mcp");
242
+ expect(httpCalls[0]?.options).toEqual({
243
+ requestInit: {
244
+ headers: { Authorization: "Bearer abc", "X-Key": "v" },
245
+ },
246
+ });
247
+ });
248
+
249
+ test("remote without headers sends an empty header record", async () => {
250
+ const httpCalls: { options: unknown }[] = [];
251
+ const adapter = createSdkMcpClient(
252
+ remoteConfig(),
253
+ baseDeps({
254
+ createStdioTransport: failStdio,
255
+ createHttpTransport: (_url, options) => {
256
+ httpCalls.push({ options });
257
+ return fakeTransport;
258
+ },
259
+ })
260
+ );
261
+ await adapter.connect();
262
+ expect(httpCalls[0]?.options).toEqual({
263
+ requestInit: { headers: {} },
264
+ });
265
+ });
266
+
267
+ test("registers listChanged handler and forwards refreshed tools to set listener", async () => {
268
+ let capturedOnChanged:
269
+ | ((error: Error | null, tools: Tool[] | null) => void)
270
+ | undefined;
271
+ const received: McpClientTool[][] = [];
272
+ const adapter = createSdkMcpClient(
273
+ localConfig(),
274
+ baseDeps({
275
+ createClient: (options) => {
276
+ capturedOnChanged = options.listChanged.tools.onChanged;
277
+ return fakeClient();
278
+ },
279
+ createHttpTransport: failHttp,
280
+ })
281
+ );
282
+ adapter.setToolsChangedListener((tools) => {
283
+ received.push([...tools]);
284
+ });
285
+ expect(capturedOnChanged).toBeUndefined();
286
+ await adapter.connect();
287
+ expect(capturedOnChanged).toBeTypeOf("function");
288
+ capturedOnChanged?.(null, [tool("a", { description: "A" }), tool("b")]);
289
+ expect(received).toEqual([
290
+ [
291
+ { name: "a", description: "A", inputSchema: { type: "object" } },
292
+ { name: "b", inputSchema: { type: "object" } },
293
+ ],
294
+ ]);
295
+ });
296
+
297
+ test("does not forward listChanged errors to the listener", async () => {
298
+ let capturedOnChanged:
299
+ | ((error: Error | null, tools: Tool[] | null) => void)
300
+ | undefined;
301
+ const received: McpClientTool[][] = [];
302
+ const adapter = createSdkMcpClient(
303
+ localConfig(),
304
+ baseDeps({
305
+ createClient: (options) => {
306
+ capturedOnChanged = options.listChanged.tools.onChanged;
307
+ return fakeClient();
308
+ },
309
+ createHttpTransport: failHttp,
310
+ })
311
+ );
312
+ adapter.setToolsChangedListener((tools) => {
313
+ received.push([...tools]);
314
+ });
315
+ await adapter.connect();
316
+ capturedOnChanged?.(new Error("refresh failed"), null);
317
+ expect(received).toEqual([]);
318
+ });
319
+
320
+ test("connect delegates to the SDK client with transport and startup signal", async () => {
321
+ const startup = new AbortController().signal;
322
+ const calls: { transport: unknown; signal?: AbortSignal }[] = [];
323
+ const adapter = createSdkMcpClient(
324
+ localConfig(),
325
+ baseDeps({
326
+ createStartupSignal: () => startup,
327
+ createClient: () => ({
328
+ close: async () => {
329
+ return;
330
+ },
331
+ connect: (transport, options) => {
332
+ calls.push({ transport, signal: options?.signal });
333
+ return Promise.resolve();
334
+ },
335
+ listTools: async () => ({ tools: [] }),
336
+ callTool: async () => ({ content: [] }),
337
+ }),
338
+ createHttpTransport: failHttp,
339
+ })
340
+ );
341
+ await adapter.connect();
342
+ expect(calls).toHaveLength(1);
343
+ expect(calls[0]?.transport).toBe(fakeTransport);
344
+ expect(calls[0]?.signal).toBe(startup);
345
+ });
346
+
347
+ test("combines a caller signal with the startup signal", async () => {
348
+ const caller = new AbortController();
349
+ const calls: { signal?: AbortSignal }[] = [];
350
+ const adapter = createSdkMcpClient(
351
+ localConfig(),
352
+ baseDeps({
353
+ createClient: () => ({
354
+ close: async () => {
355
+ return;
356
+ },
357
+ connect: (_transport, options) => {
358
+ calls.push({ signal: options?.signal });
359
+ return Promise.resolve();
360
+ },
361
+ listTools: async () => ({ tools: [] }),
362
+ callTool: async () => ({ content: [] }),
363
+ }),
364
+ createHttpTransport: failHttp,
365
+ })
366
+ );
367
+ await adapter.connect(caller.signal);
368
+ const combined = calls[0]?.signal;
369
+ expect(combined).toBeInstanceOf(AbortSignal);
370
+ expect(combined?.aborted).toBe(false);
371
+ caller.abort();
372
+ expect(combined?.aborted).toBe(true);
373
+ });
374
+
375
+ test("times out connect with a sanitized error naming the server", async () => {
376
+ const timeouts: number[] = [];
377
+ const adapter = createSdkMcpClient(
378
+ localConfig({
379
+ timeout: { startup: 1, catalog: 30_000, execution: 43_200_000 },
380
+ }),
381
+ baseDeps({
382
+ createStartupSignal: (timeoutMs) => {
383
+ timeouts.push(timeoutMs);
384
+ return AbortSignal.abort();
385
+ },
386
+ createClient: () => ({
387
+ close: async () => {
388
+ return;
389
+ },
390
+ connect: (_transport, options) =>
391
+ options?.signal?.aborted
392
+ ? Promise.reject(new DOMException("Aborted", "AbortError"))
393
+ : Promise.resolve(),
394
+ listTools: async () => ({ tools: [] }),
395
+ callTool: async () => ({ content: [] }),
396
+ }),
397
+ createHttpTransport: failHttp,
398
+ })
399
+ );
400
+ const error = await rejectedMcpError(adapter.connect());
401
+ expect(timeouts).toEqual([1]);
402
+ expect(error).toMatchObject({
403
+ serverName: "demo",
404
+ message: "demo: connect timed out",
405
+ });
406
+ });
407
+
408
+ test("sanitizes remote connect errors so headers, url, and secrets never leak", async () => {
409
+ const adapter = createSdkMcpClient(
410
+ remoteConfig({
411
+ url: "https://mcp.deepwiki.com/mcp?case=redaction",
412
+ headers: { Authorization: "Bearer super-secret-token" },
413
+ }),
414
+ baseDeps({
415
+ createStdioTransport: failStdio,
416
+ createClient: () => ({
417
+ close: async () => {
418
+ return;
419
+ },
420
+ connect: () =>
421
+ Promise.reject(
422
+ new Error(
423
+ "auth failed at https://mcp.deepwiki.com/mcp?case=redaction with Bearer super-secret-token"
424
+ )
425
+ ),
426
+ listTools: async () => ({ tools: [] }),
427
+ callTool: async () => ({ content: [] }),
428
+ }),
429
+ })
430
+ );
431
+ const error = await rejectedMcpError(adapter.connect());
432
+ expect(error).toMatchObject({ serverName: "remote-demo" });
433
+ expect(error.message).toContain("remote-demo");
434
+ expect(error.message).not.toContain("super-secret-token");
435
+ expect(error.message).not.toContain("mcp.deepwiki.com");
436
+ expect(error.message).not.toContain("Bearer");
437
+ });
438
+
439
+ test("sanitizes local connect errors so env values never leak", async () => {
440
+ const adapter = createSdkMcpClient(
441
+ localConfig({ environment: { API_KEY: "env-super-secret" } }),
442
+ baseDeps({
443
+ createClient: () => ({
444
+ close: async () => {
445
+ return;
446
+ },
447
+ connect: () =>
448
+ Promise.reject(new Error("failed with env-super-secret")),
449
+ listTools: async () => ({ tools: [] }),
450
+ callTool: async () => ({ content: [] }),
451
+ }),
452
+ createHttpTransport: failHttp,
453
+ })
454
+ );
455
+ const error = await rejectedMcpError(adapter.connect());
456
+ expect(error.message).toContain("demo");
457
+ expect(error.message).not.toContain("env-super-secret");
458
+ });
459
+
460
+ test("listTools delegates to the SDK and maps to the narrow tool shape", async () => {
461
+ const signal = new AbortController().signal;
462
+ const calls: { signal?: AbortSignal }[] = [];
463
+ const adapter = createSdkMcpClient(
464
+ localConfig(),
465
+ baseDeps({
466
+ createClient: () => ({
467
+ close: async () => {
468
+ return;
469
+ },
470
+ connect: async () => {
471
+ return;
472
+ },
473
+ listTools: (_params, options) => {
474
+ calls.push(options ?? {});
475
+ return Promise.resolve({
476
+ tools: [tool("a", { description: "A" }), tool("b")],
477
+ });
478
+ },
479
+ callTool: async () => ({ content: [] }),
480
+ }),
481
+ createHttpTransport: failHttp,
482
+ })
483
+ );
484
+ const result = await adapter.listTools(signal);
485
+ expect(result).toEqual([
486
+ { name: "a", description: "A", inputSchema: { type: "object" } },
487
+ { name: "b", inputSchema: { type: "object" } },
488
+ ]);
489
+ expect(calls).toEqual([{ signal }]);
490
+ });
491
+
492
+ test("callTool delegates name and arguments and returns the SDK result", async () => {
493
+ const signal = new AbortController().signal;
494
+ const result: CallToolResult = {
495
+ content: [{ type: "text", text: "ok" }],
496
+ isError: false,
497
+ };
498
+ const calls: {
499
+ params: { name: string; arguments?: unknown };
500
+ signal?: AbortSignal;
501
+ }[] = [];
502
+ const adapter = createSdkMcpClient(
503
+ localConfig(),
504
+ baseDeps({
505
+ createClient: () => ({
506
+ close: async () => {
507
+ return;
508
+ },
509
+ connect: async () => {
510
+ return;
511
+ },
512
+ listTools: async () => ({ tools: [] }),
513
+ callTool: (params, options) => {
514
+ calls.push({ params, signal: options?.signal });
515
+ return Promise.resolve(result);
516
+ },
517
+ }),
518
+ createHttpTransport: failHttp,
519
+ })
520
+ );
521
+ await expect(
522
+ adapter.callTool("echo", { text: "hi" }, signal)
523
+ ).resolves.toBe(result);
524
+ expect(calls).toEqual([
525
+ { params: { name: "echo", arguments: { text: "hi" } }, signal },
526
+ ]);
527
+ });
528
+
529
+ test("listTools sanitizes thrown errors so tokens and urls never leak", async () => {
530
+ const adapter = createSdkMcpClient(
531
+ remoteConfig({
532
+ url: "https://mcp.deepwiki.com/mcp?case=x",
533
+ headers: { Authorization: "Bearer leaked-token" },
534
+ }),
535
+ baseDeps({
536
+ createStdioTransport: failStdio,
537
+ createClient: () => ({
538
+ close: async () => {
539
+ return;
540
+ },
541
+ connect: async () => {
542
+ return;
543
+ },
544
+ listTools: () =>
545
+ Promise.reject(
546
+ new Error(
547
+ "Bearer leaked-token https://mcp.deepwiki.com/mcp?case=upstream-list-tools"
548
+ )
549
+ ),
550
+ callTool: async () => ({ content: [] }),
551
+ }),
552
+ })
553
+ );
554
+ const error = await rejectedMcpError(adapter.listTools());
555
+ expect(error).toMatchObject({ serverName: "remote-demo" });
556
+ expect(error.message).toContain("remote-demo");
557
+ expect(error.message).not.toContain("leaked-token");
558
+ expect(error.message).not.toContain("https://mcp.deepwiki.com/mcp?case=x");
559
+ expect(error.message).not.toContain("Bearer");
560
+ });
561
+
562
+ test("callTool sanitizes thrown errors so tokens and urls never leak", async () => {
563
+ const adapter = createSdkMcpClient(
564
+ remoteConfig({
565
+ url: "https://mcp.deepwiki.com/mcp?case=x",
566
+ headers: { Authorization: "Bearer leaked-token" },
567
+ }),
568
+ baseDeps({
569
+ createStdioTransport: failStdio,
570
+ createClient: () => ({
571
+ close: async () => {
572
+ return;
573
+ },
574
+ connect: async () => {
575
+ return;
576
+ },
577
+ listTools: async () => ({ tools: [] }),
578
+ callTool: () =>
579
+ Promise.reject(
580
+ new Error(
581
+ "Bearer leaked-token https://mcp.deepwiki.com/mcp?case=upstream-call-tool"
582
+ )
583
+ ),
584
+ }),
585
+ })
586
+ );
587
+ const error = await rejectedMcpError(
588
+ adapter.callTool("echo", { text: "hi" })
589
+ );
590
+ expect(error).toMatchObject({ serverName: "remote-demo" });
591
+ expect(error.message).toContain("remote-demo");
592
+ expect(error.message).not.toContain("leaked-token");
593
+ expect(error.message).not.toContain("https://mcp.deepwiki.com/mcp?case=x");
594
+ expect(error.message).not.toContain("Bearer");
595
+ });
596
+
597
+ test("close delegates to the SDK client", async () => {
598
+ let closed = 0;
599
+ const adapter = createSdkMcpClient(
600
+ localConfig(),
601
+ baseDeps({
602
+ createClient: () => ({
603
+ close: async () => {
604
+ closed += 1;
605
+ },
606
+ connect: async () => {
607
+ return;
608
+ },
609
+ listTools: async () => ({ tools: [] }),
610
+ callTool: async () => ({ content: [] }),
611
+ }),
612
+ createHttpTransport: failHttp,
613
+ })
614
+ );
615
+ await adapter.close();
616
+ expect(closed).toBe(1);
617
+ });
618
+
619
+ test("close sanitizes thrown errors so env secrets never leak", async () => {
620
+ const adapter = createSdkMcpClient(
621
+ localConfig({ environment: { API_KEY: "close-super-secret" } }),
622
+ baseDeps({
623
+ createClient: () => ({
624
+ close: () =>
625
+ Promise.reject(
626
+ new Error("shutdown failed with close-super-secret")
627
+ ),
628
+ connect: async () => {
629
+ return;
630
+ },
631
+ listTools: async () => ({ tools: [] }),
632
+ callTool: async () => ({ content: [] }),
633
+ }),
634
+ createHttpTransport: failHttp,
635
+ })
636
+ );
637
+ const error = await rejectedMcpError(adapter.close());
638
+ expect(error).toMatchObject({ serverName: "demo" });
639
+ expect(error.message).toContain("demo");
640
+ expect(error.message).not.toContain("close-super-secret");
641
+ });
642
+ });