project-mcp.integration.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. import {
  2. mkdtemp,
  3. mkdir,
  4. writeFile,
  5. readFile,
  6. rm,
  7. access,
  8. realpath,
  9. } from "node:fs/promises";
  10. import { tmpdir } from "node:os";
  11. import { join } from "node:path";
  12. import { pathToFileURL } from "node:url";
  13. import { createServer } from "node:http";
  14. import { afterEach, expect, it, vi } from "vitest";
  15. import { McpConnectionPool } from "@mavis/mcp/runtime/connection-pool";
  16. import { LocalMcpService } from "../../../src/service/mcp/index.js";
  17. import { LocalMcpPublicFacade } from "../../../src/service/mcp/tools/public-facade.js";
  18. const roots: string[] = [];
  19. const services: LocalMcpService[] = [];
  20. afterEach(async () => {
  21. vi.unstubAllEnvs();
  22. for (const service of services.splice(0)) await service.close();
  23. for (const root of roots.splice(0))
  24. await rm(root, { recursive: true, force: true });
  25. });
  26. const fixture = `
  27. const fs = require('node:fs');
  28. const readline = require('node:readline');
  29. fs.writeFileSync('started', 'yes');
  30. // Windows locks a live process cwd. Keep the transport open without holding the disappearing directory.
  31. if (process.env.PROJECT_MCP_TEST === 'release-cwd') process.chdir(require('node:os').tmpdir());
  32. const send = value => process.stdout.write(JSON.stringify(value) + '\\n');
  33. let callId;
  34. readline.createInterface({input: process.stdin}).on('line', line => {
  35. const request = JSON.parse(line);
  36. if (request.method === 'initialize') send({jsonrpc:'2.0', id:request.id, result:{protocolVersion:'2024-11-05', capabilities:{tools:{}}, serverInfo:{name:'fixture',version:'1'}}});
  37. if (request.method === 'tools/list') send({jsonrpc:'2.0',id:request.id,result:{tools:[{name:'where',inputSchema:{type:'object'}}]}});
  38. if (request.method === 'tools/call' && request.params.arguments.hold) { fs.writeFileSync('called', 'yes'); return; }
  39. if (request.method === 'tools/call') { callId = request.id; send({jsonrpc:'2.0',id:'roots',method:'roots/list'}); }
  40. if (request.id === 'roots' && request.result) send({jsonrpc:'2.0',id:callId,result:{content:[{type:'text',text:JSON.stringify({cwd:process.cwd(),root:request.result.roots[0].uri,env:process.env.PROJECT_MCP_TEST})}]}});
  41. });
  42. `;
  43. async function setup() {
  44. const data = await realpath(
  45. await mkdtemp(join(tmpdir(), "project-mcp-live-")),
  46. );
  47. roots.push(data);
  48. const a = join(data, "a");
  49. const b = join(data, "b");
  50. await mkdir(a);
  51. await mkdir(b);
  52. for (const root of [a, b]) await writeFile(join(root, "server.cjs"), fixture);
  53. let service: LocalMcpService;
  54. const pool = new McpConnectionPool({
  55. getResolvedServer: (name) =>
  56. service.getServerLookup().getResolvedServer(name),
  57. });
  58. service = new LocalMcpService(() => data, { connectionPool: pool });
  59. services.push(service);
  60. return { data, a, b, service };
  61. }
  62. async function configure(root: string, env = "one") {
  63. await writeFile(
  64. join(root, ".mcp.json"),
  65. JSON.stringify({
  66. mcpServers: {
  67. repo: {
  68. command: process.execPath,
  69. args: ["./server.cjs"],
  70. env: { PROJECT_MCP_TEST: env },
  71. },
  72. },
  73. }),
  74. );
  75. }
  76. it("loads automatically at first discovery with project cwd, roots and isolated connections", async () => {
  77. const { a, b, service } = await setup();
  78. await configure(a, "a");
  79. await configure(b, "b");
  80. const ca = { sessionId: "a", workspaceRoot: a };
  81. const cb = { sessionId: "b", workspaceRoot: b };
  82. await expect(access(join(a, "started"))).rejects.toThrow();
  83. expect((await service.inspectProjectMcp(ca))?.servers[0]?.status).toBe(
  84. "configured",
  85. );
  86. await expect(access(join(a, "started"))).rejects.toThrow();
  87. expect(await service.listNativeToolsForTurn(ca)).toHaveLength(1);
  88. const [ra, rb] = await Promise.all([
  89. service.call("repo", "where", {}, { context: ca }),
  90. service.call("repo", "where", {}, { context: cb }),
  91. ]);
  92. expect(ra.content).toEqual([
  93. {
  94. type: "text",
  95. text: JSON.stringify({ cwd: a, root: pathToFileURL(a).href, env: "a" }),
  96. },
  97. ]);
  98. expect(rb.content).toEqual([
  99. {
  100. type: "text",
  101. text: JSON.stringify({ cwd: b, root: pathToFileURL(b).href, env: "b" }),
  102. },
  103. ]);
  104. expect((await service.inspectProjectMcp(ca))?.servers[0]?.status).toBe(
  105. "available",
  106. );
  107. });
  108. it("shadows profile entries, survives ACP clear, and reloads automatically on edit or deletion", async () => {
  109. const { data, a, service } = await setup();
  110. await configure(a);
  111. const profile = JSON.stringify({
  112. mcpServers: { repo: { command: "should-never-start" } },
  113. });
  114. await writeFile(join(data, "mcp.json"), profile);
  115. const context = { sessionId: "one", workspaceRoot: a };
  116. expect((await service.getServerConfig("repo", context))?.command).toBe(
  117. process.execPath,
  118. );
  119. await service.configureSessionServers("one", [
  120. { name: "repo", config: { command: "client-wins" } },
  121. ]);
  122. expect((await service.getServerConfig("repo", context))?.command).toBe(
  123. "client-wins",
  124. );
  125. await service.clearSessionServers("one");
  126. expect(
  127. (await service.call("repo", "where", {}, { context })).isError,
  128. ).not.toBe(true);
  129. const facade = new LocalMcpPublicFacade(service);
  130. expect(
  131. (await facade.listMcpCapabilities({ context })).servers.filter(
  132. (server) => server.name === "repo",
  133. ),
  134. ).toMatchObject([{ sourceScope: "project", status: "available" }]);
  135. await configure(a, "changed");
  136. expect((await service.inspectProjectMcp(context))?.servers[0]?.status).toBe(
  137. "configured",
  138. );
  139. expect(
  140. (await service.call("repo", "where", {}, { context })).content,
  141. ).toEqual([
  142. {
  143. type: "text",
  144. text: JSON.stringify({
  145. cwd: a,
  146. root: pathToFileURL(a).href,
  147. env: "changed",
  148. }),
  149. },
  150. ]);
  151. expect(await readFile(join(data, "mcp.json"), "utf8")).toBe(profile);
  152. await rm(join(a, ".mcp.json"));
  153. expect((await service.getServerConfig("repo", context))?.command).toBe(
  154. "should-never-start",
  155. );
  156. });
  157. it("invalidates malformed files without retaining the old executable", async () => {
  158. const { a, service } = await setup();
  159. await configure(a);
  160. const context = { sessionId: "one", workspaceRoot: a };
  161. expect(await service.listNativeToolsForTurn(context)).toHaveLength(1);
  162. await writeFile(join(a, ".mcp.json"), "{bad json");
  163. expect(await service.listNativeToolsForTurn(context)).toEqual([]);
  164. expect((await service.inspectProjectMcp(context))?.error).toContain(
  165. "Cannot read",
  166. );
  167. });
  168. it("uses HTTP headers on a real loopback server and does not expose them in inspection", async () => {
  169. const { a, service } = await setup();
  170. const seen: string[] = [];
  171. const server = createServer(async (req, res) => {
  172. seen.push(String(req.headers.authorization));
  173. if (req.method !== "POST") {
  174. res.writeHead(405).end();
  175. return;
  176. }
  177. const chunks = [];
  178. for await (const chunk of req) chunks.push(chunk);
  179. const body = JSON.parse(Buffer.concat(chunks).toString());
  180. if (!body.id && body.id !== 0) {
  181. res.writeHead(202).end();
  182. return;
  183. }
  184. const result =
  185. body.method === "initialize"
  186. ? {
  187. protocolVersion: "2024-11-05",
  188. capabilities: { tools: {} },
  189. serverInfo: { name: "http-fixture", version: "1" },
  190. }
  191. : { tools: [{ name: "remote", inputSchema: { type: "object" } }] };
  192. res
  193. .writeHead(200, { "Content-Type": "application/json" })
  194. .end(JSON.stringify({ jsonrpc: "2.0", id: body.id, result }));
  195. });
  196. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  197. try {
  198. const address = server.address();
  199. if (!address || typeof address === "string")
  200. throw new Error("Expected port.");
  201. await writeFile(
  202. join(a, ".mcp.json"),
  203. JSON.stringify({
  204. mcpServers: {
  205. remote: {
  206. type: "http",
  207. url: `http://127.0.0.1:${address.port}/mcp?token=hidden`,
  208. headers: { Authorization: "Bearer private-token" },
  209. },
  210. },
  211. }),
  212. );
  213. const context = { sessionId: "http", workspaceRoot: a };
  214. expect(
  215. JSON.stringify(await service.inspectProjectMcp(context)),
  216. ).not.toMatch(/private-token|token=hidden/);
  217. expect(seen).toEqual([]);
  218. expect(await service.listNativeToolsForTurn(context)).toHaveLength(1);
  219. expect(seen.length).toBeGreaterThan(0);
  220. expect(seen.every((value) => value === "Bearer private-token")).toBe(true);
  221. } finally {
  222. await service.close();
  223. await new Promise<void>((resolve) => server.close(() => resolve()));
  224. }
  225. });
  226. it("aborts an old project call on reload without marking the replacement as available", async () => {
  227. const { a, service } = await setup();
  228. await configure(a);
  229. const context = { sessionId: "one", workspaceRoot: a };
  230. const calling = service.call("repo", "where", { hold: true }, { context });
  231. // Real subprocess startup under CI coverage can exceed Vitest's default one second.
  232. await vi.waitFor(
  233. async () => {
  234. expect(await readFile(join(a, "called"), "utf8")).toBe("yes");
  235. },
  236. { timeout: 10_000 },
  237. );
  238. await configure(a, "replacement");
  239. await service.inspectProjectMcp(context);
  240. expect((await calling).isError).toBe(true);
  241. expect((await service.inspectProjectMcp(context))?.servers[0]?.status).toBe(
  242. "configured",
  243. );
  244. expect(
  245. (await service.call("repo", "where", {}, { context })).content,
  246. ).toEqual([
  247. {
  248. type: "text",
  249. text: JSON.stringify({
  250. cwd: a,
  251. root: pathToFileURL(a).href,
  252. env: "replacement",
  253. }),
  254. },
  255. ]);
  256. });
  257. it("keeps built-in reserved names intact even when the project declares them", async () => {
  258. const { data, a } = await setup();
  259. // This case inspects reserved-name configuration without starting Matrix.
  260. // Use the local fixture instead of requiring an unrelated package dist build.
  261. vi.stubEnv("MAVIS_MATRIX_MCP_STDIO_ENTRYPOINT", join(a, "server.cjs"));
  262. const service = new LocalMcpService(() => data, {
  263. builtinMatrix: { enabled: true },
  264. connectionPool: new McpConnectionPool({ getResolvedServer: () => null }),
  265. });
  266. services.push(service);
  267. await writeFile(
  268. join(a, ".mcp.json"),
  269. JSON.stringify({ mcpServers: { matrix: { command: "malicious" } } }),
  270. );
  271. const context = { sessionId: "reserved", workspaceRoot: a };
  272. expect((await service.inspectProjectMcp(context))?.servers[0]?.status).toBe(
  273. "error",
  274. );
  275. expect((await service.getServerConfig("matrix", context))?.builtin).toBe(
  276. true,
  277. );
  278. });
  279. it("keeps disabled and invalid project entries from executing or falling back to profile", async () => {
  280. const { data, a, service } = await setup();
  281. await writeFile(
  282. join(data, "mcp.json"),
  283. JSON.stringify({ mcpServers: { repo: { command: "profile" } } }),
  284. );
  285. const context = { sessionId: "disabled", workspaceRoot: a };
  286. for (const config of [
  287. { command: process.execPath, args: ["./server.cjs"], enabled: false },
  288. { type: "invalid" },
  289. ]) {
  290. await writeFile(
  291. join(a, ".mcp.json"),
  292. JSON.stringify({ mcpServers: { repo: config } }),
  293. );
  294. expect(await service.listNativeToolsForTurn(context)).toEqual([]);
  295. expect((await service.getServerConfig("repo", context))?.enabled).toBe(
  296. false,
  297. );
  298. await expect(access(join(a, "started"))).rejects.toThrow();
  299. }
  300. });
  301. it("keeps profile tools available when a workspace disappears and releases old project connections", async () => {
  302. const { data, a, service } = await setup();
  303. await configure(a, "release-cwd");
  304. const context = { sessionId: "deleted", workspaceRoot: a };
  305. expect(await service.listNativeToolsForTurn(context)).toHaveLength(1);
  306. await writeFile(
  307. join(data, "mcp.json"),
  308. JSON.stringify({ mcpServers: { fallback: { command: "profile" } } }),
  309. );
  310. await rm(a, { recursive: true, force: true });
  311. expect(await service.getServerConfig("repo", context)).toBeUndefined();
  312. expect((await service.getServerConfig("fallback", context))?.command).toBe(
  313. "profile",
  314. );
  315. });
  316. it("disposes project calls and ACP configuration together for a deleted session", async () => {
  317. const { a, service } = await setup();
  318. await configure(a);
  319. const context = { sessionId: "deleted", workspaceRoot: a };
  320. await service.configureSessionServers("deleted", [
  321. { name: "client-only", config: { command: "unused" } },
  322. ]);
  323. const calling = service.call("repo", "where", { hold: true }, { context });
  324. // Real subprocess startup under CI coverage can exceed Vitest's default one second.
  325. await vi.waitFor(
  326. async () => {
  327. expect(await readFile(join(a, "called"), "utf8")).toBe("yes");
  328. },
  329. { timeout: 10_000 },
  330. );
  331. await service.disposeSession("deleted");
  332. expect((await calling).isError).toBe(true);
  333. expect(service.getSessionMcpServers("deleted")).toBeUndefined();
  334. expect((await service.inspectProjectMcp(context)).servers[0]?.status).toBe(
  335. "configured",
  336. );
  337. });