Elffuss BraidHub

kikocis/continue public

dfc814e4318e · 10.0 KiBRawPermalink
1import { Client } from "@modelcontextprotocol/sdk/client/index.js";
2import { beforeEach, describe, expect, it, vi } from "vitest";
3import MCPConnection from "./MCPConnection";
4
5// Mock the shell path utility
6vi.mock("../../util/shellPath", () => ({
7 getEnvPathFromUserShell: vi
8 .fn()
9 .mockResolvedValue("/usr/local/bin:/usr/bin:/bin"),
10}));
11
12describe("MCPConnection", () => {
13 beforeEach(() => {
14 vi.restoreAllMocks();
15 });
16
17 describe("constructor", () => {
18 it("should create instance with stdio transport", () => {
19 const options = {
20 name: "test-mcp",
21 id: "test-id",
22 transport: {
23 type: "stdio" as const,
24 command: "test-cmd",
25 args: ["--test"],
26 env: { TEST: "true" },
27 },
28 };
29
30 const conn = new MCPConnection(options);
31 expect(conn).toBeInstanceOf(MCPConnection);
32 expect(conn.status).toBe("not-connected");
33 });
34
35 it("should create instance with stdio transport including cwd", () => {
36 const options = {
37 name: "test-mcp",
38 id: "test-id",
39 transport: {
40 type: "stdio" as const,
41 command: "test-cmd",
42 args: ["--test"],
43 env: { TEST: "true" },
44 cwd: "/path/to/working/directory",
45 },
46 };
47
48 const conn = new MCPConnection(options);
49 expect(conn).toBeInstanceOf(MCPConnection);
50 expect(conn.status).toBe("not-connected");
51 if (conn.options.transport.type === "stdio") {
52 expect(conn.options.transport.cwd).toBe("/path/to/working/directory");
53 }
54 });
55
56 it("should create instance with websocket transport", () => {
57 const options = {
58 name: "test-mcp",
59 id: "test-id",
60 transport: {
61 type: "websocket" as const,
62 url: "ws://test.com",
63 },
64 };
65
66 const conn = new MCPConnection(options);
67 expect(conn).toBeInstanceOf(MCPConnection);
68 expect(conn.status).toBe("not-connected");
69 });
70
71 it("should create instance with SSE transport", () => {
72 const options = {
73 name: "test-mcp",
74 id: "test-id",
75 transport: {
76 type: "sse" as const,
77 url: "http://test.com/events",
78 },
79 };
80
81 const conn = new MCPConnection(options);
82 expect(conn).toBeInstanceOf(MCPConnection);
83 expect(conn.status).toBe("not-connected");
84 });
85
86 it("should create instance with SSE transport and custom headers", () => {
87 const options = {
88 name: "test-mcp",
89 id: "test-id",
90 transport: {
91 type: "sse" as const,
92 url: "http://test.com/events",
93 requestOptions: {
94 headers: {
95 Authorization: "Bearer token123",
96 "X-Custom-Header": "custom-value",
97 },
98 },
99 },
100 };
101
102 const conn = new MCPConnection(options);
103 expect(conn).toBeInstanceOf(MCPConnection);
104 expect(conn.status).toBe("not-connected");
105 });
106
107 it("should throw on invalid transport type", async () => {
108 const options = {
109 name: "test-mcp",
110 id: "test-id",
111 transport: {
112 type: "invalid",
113 } as any,
114 };
115
116 const conn = new MCPConnection(options);
117 const abortController = new AbortController();
118
119 // The validation now happens during connectClient, not constructor
120 await conn.connectClient(false, abortController.signal);
121
122 expect(conn.status).toBe("error");
123 expect(conn.errors[0]).toContain("Unsupported transport type: invalid");
124 });
125 });
126
127 describe("getStatus", () => {
128 it("should return current status", () => {
129 const options = {
130 name: "test-mcp",
131 id: "test-id",
132 transport: {
133 type: "stdio" as const,
134 command: "test",
135 args: [],
136 },
137 };
138
139 const conn = new MCPConnection(options);
140 const status = conn.getStatus();
141
142 expect(status).toEqual({
143 ...options,
144 errors: [],
145 isProtectedResource: false,
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});