Elffuss BraidHub

kikocis/continue public

627d7d0d1f85 · 10.0 KiBRawPermalink
1import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2import { beforeEach, describe, expect, it, vi } from "vitest";
3import MCPConnection from "./MCPConnection";
4import { StdioOptions } from "../../index.d.js";
5
6// Mock the shell path utility
7vi.mock("../../util/shellPath", () => ({
8 getEnvPathFromUserShell: vi
9 .fn()
10 .mockResolvedValue("/usr/local/bin:/usr/bin:/bin"),
11}));
12
13describe("MCPConnection", () => {
14 beforeEach(() => {
15 vi.restoreAllMocks();
16 });
17
18 describe("constructor", () => {
19 it("should create instance with stdio transport", () => {
20 const options = {
21 name: "test-mcp",
22 id: "test-id",
23 transport: {
24 type: "stdio" as const,
25 command: "test-cmd",
26 args: ["--test"],
27 env: { TEST: "true" },
28 },
29 };
30
31 const conn = new MCPConnection(options);
32 expect(conn).toBeInstanceOf(MCPConnection);
33 expect(conn.status).toBe("not-connected");
34 });
35
36 it("should create instance with stdio transport including cwd", () => {
37 const options = {
38 name: "test-mcp",
39 id: "test-id",
40 transport: {
41 type: "stdio" as const,
42 command: "test-cmd",
43 args: ["--test"],
44 env: { TEST: "true" },
45 cwd: "/path/to/working/directory",
46 },
47 };
48
49 const conn = new MCPConnection(options);
50 expect(conn).toBeInstanceOf(MCPConnection);
51 expect(conn.status).toBe("not-connected");
52 if (conn.options.transport.type === "stdio") {
53 expect(conn.options.transport.cwd).toBe("/path/to/working/directory");
54 }
55 });
56
57 it("should create instance with websocket transport", () => {
58 const options = {
59 name: "test-mcp",
60 id: "test-id",
61 transport: {
62 type: "websocket" as const,
63 url: "ws://test.com",
64 },
65 };
66
67 const conn = new MCPConnection(options);
68 expect(conn).toBeInstanceOf(MCPConnection);
69 expect(conn.status).toBe("not-connected");
70 });
71
72 it("should create instance with SSE transport", () => {
73 const options = {
74 name: "test-mcp",
75 id: "test-id",
76 transport: {
77 type: "sse" as const,
78 url: "http://test.com/events",
79 },
80 };
81
82 const conn = new MCPConnection(options);
83 expect(conn).toBeInstanceOf(MCPConnection);
84 expect(conn.status).toBe("not-connected");
85 });
86
87 it("should create instance with SSE transport and custom headers", () => {
88 const options = {
89 name: "test-mcp",
90 id: "test-id",
91 transport: {
92 type: "sse" as const,
93 url: "http://test.com/events",
94 requestOptions: {
95 headers: {
96 Authorization: "Bearer token123",
97 "X-Custom-Header": "custom-value",
98 },
99 },
100 },
101 };
102
103 const conn = new MCPConnection(options);
104 expect(conn).toBeInstanceOf(MCPConnection);
105 expect(conn.status).toBe("not-connected");
106 });
107
108 it("should throw on invalid transport type", async () => {
109 const options = {
110 name: "test-mcp",
111 id: "test-id",
112 transport: {
113 type: "invalid",
114 } as any,
115 };
116
117 const conn = new MCPConnection(options);
118 const abortController = new AbortController();
119
120 // The validation now happens during connectClient, not constructor
121 await conn.connectClient(false, abortController.signal);
122
123 expect(conn.status).toBe("error");
124 expect(conn.errors[0]).toContain("Unsupported transport type: invalid");
125 });
126 });
127
128 describe("getStatus", () => {
129 it("should return current status", () => {
130 const options = {
131 name: "test-mcp",
132 id: "test-id",
133 transport: {
134 type: "stdio" as const,
135 command: "test",
136 args: [],
137 },
138 };
139
140 const conn = new MCPConnection(options);
141 const status = conn.getStatus();
142
143 expect(status).toEqual({
144 ...options,
145 errors: [],
146 prompts: [],
147 resources: [],
148 resourceTemplates: [],
149 tools: [],
150 status: "not-connected",
151 });
152 });
153 });
154
155 describe("connectClient", () => {
156 const options = {
157 name: "test-mcp",
158 id: "test-id",
159 transport: {
160 type: "stdio" as const,
161 command: "test-cmd",
162 args: [],
163 },
164 };
165
166 it("should connect successfully", async () => {
167 const conn = new MCPConnection(options);
168 const mockConnect = vi
169 .spyOn(Client.prototype, "connect")
170 .mockResolvedValue(undefined);
171 const mockGetServerCapabilities = vi
172 .spyOn(Client.prototype, "getServerCapabilities")
173 .mockReturnValue({
174 resources: {},
175 tools: {},
176 prompts: {},
177 });
178
179 const mockListResources = vi
180 .spyOn(Client.prototype, "listResources")
181 .mockResolvedValue({
182 resources: [{ name: "test-resource", uri: "test-uri" }],
183 });
184 const mockListTools = vi
185 .spyOn(Client.prototype, "listTools")
186 .mockResolvedValue({
187 tools: [
188 {
189 name: "test-tool",
190 inputSchema: {
191 type: "object",
192 },
193 },
194 ],
195 });
196 const mockListPrompts = vi
197 .spyOn(Client.prototype, "listPrompts")
198 .mockResolvedValue({ prompts: [{ name: "test-prompt" }] });
199
200 const abortController = new AbortController();
201 await conn.connectClient(false, abortController.signal);
202
203 expect(conn.status).toBe("connected");
204 expect(conn.resources).toHaveLength(1);
205 expect(conn.tools).toHaveLength(1);
206 expect(conn.prompts).toHaveLength(1);
207 expect(mockConnect).toHaveBeenCalled();
208 });
209
210 it("should handle custom connection timeout", async () => {
211 const conn = new MCPConnection({ ...options, timeout: 1500 });
212 const mockConnect = vi
213 .spyOn(Client.prototype, "connect")
214 .mockImplementation(
215 () => new Promise((resolve) => setTimeout(resolve, 1000)),
216 );
217
218 // Mock the required methods for successful connection
219 const mockGetServerCapabilities = vi
220 .spyOn(Client.prototype, "getServerCapabilities")
221 .mockReturnValue({
222 resources: {},
223 tools: {},
224 prompts: {},
225 });
226
227 const abortController = new AbortController();
228 await conn.connectClient(false, abortController.signal);
229
230 expect(conn.status).toBe("connected");
231 expect(mockConnect).toHaveBeenCalled();
232 });
233
234 it("should handle connection timeout", async () => {
235 const conn = new MCPConnection({ ...options, timeout: 50 });
236 const mockConnect = vi
237 .spyOn(Client.prototype, "connect")
238 .mockImplementation(
239 () => new Promise((resolve) => setTimeout(resolve, 100)),
240 );
241
242 const abortController = new AbortController();
243 await conn.connectClient(false, abortController.signal);
244
245 expect(conn.status).toBe("error");
246 expect(conn.errors[0]).toContain("Failed to connect");
247 // The connection should timeout before connect is called due to transport construction
248 // Since transport construction happens first, and we're not mocking that,
249 // the timeout will happen during transport construction or connect attempt
250 });
251
252 it("should handle already connected state", async () => {
253 const conn = new MCPConnection(options);
254 conn.status = "connected";
255
256 const mockConnect = vi.spyOn(Client.prototype, "connect");
257 const abortController = new AbortController();
258
259 await conn.connectClient(false, abortController.signal);
260
261 expect(mockConnect).not.toHaveBeenCalled();
262 expect(conn.status).toBe("connected");
263 });
264
265 it("should handle transport errors", async () => {
266 const conn = new MCPConnection(options);
267 const mockConnect = vi
268 .spyOn(Client.prototype, "connect")
269 .mockRejectedValue(new Error("spawn test-cmd ENOENT"));
270
271 const abortController = new AbortController();
272 await conn.connectClient(false, abortController.signal);
273
274 expect(conn.status).toBe("error");
275 expect(conn.errors[0]).toContain('command "test-cmd" not found');
276 expect(mockConnect).toHaveBeenCalled();
277 });
278
279 it.skip("should include stderr output in error message when stdio command fails", async () => {
280 // Clear any existing mocks to ensure we get real behavior
281 vi.restoreAllMocks();
282
283 // Use a command that will definitely fail and produce stderr output
284 const failingOptions = {
285 name: "failing-mcp",
286 id: "failing-id",
287 transport: {
288 type: "stdio" as const,
289 command: "node",
290 args: [
291 "-e",
292 "console.error('Custom error message from stderr'); process.exit(1);",
293 ],
294 },
295 timeout: 5000, // Give enough time for the command to run and fail
296 };
297
298 const conn = new MCPConnection(failingOptions);
299 const abortController = new AbortController();
300
301 await conn.connectClient(false, abortController.signal);
302
303 expect(conn.status).toBe("error");
304 expect(conn.errors).toHaveLength(1);
305 expect(conn.errors[0]).toContain("Failed to connect");
306 expect(conn.errors[0]).toContain("Process output:");
307 expect(conn.errors[0]).toContain("STDERR:");
308 expect(conn.errors[0]).toContain("Custom error message from stderr");
309 });
310 });
311
312 describe.skip("actually connect to Filesystem MCP", () => {
313 it("should connect and include correct tools", async () => {
314 const conn = new MCPConnection({
315 id: "filesystem",
316 name: "Filesystem",
317 transport: {
318 type: "stdio" as const,
319 command: "npx",
320 args: ["-y", "@modelcontextprotocol/server-filesystem", "."],
321 },
322 });
323
324 try {
325 const abortController = new AbortController();
326 await conn.connectClient(false, abortController.signal);
327 expect(conn.status).toBe("connected");
328 } finally {
329 await conn.disconnect();
330 }
331 });
332 });
333});