Elffuss BraidHub

kikocis/continue public

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