Elffuss BraidHub

kikocis/continue public

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