mcp-official-auth-integration.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. /* fake 官方 Plugin + fake Streamable HTTP MCP 的端到端验证。
  2. *
  3. * 覆盖真实链路:Plugin 解析 -> provenance -> 可信 Origin 校验 -> tools/call 动态身份头注入 ->
  4. * 匿名 initialize / tools/list 与受保护 tools/call 的实际请求头,并验证官方鉴权路径**不会**创建
  5. * OAuth session(spec §6.3.1)。
  6. *
  7. * fake fixture 只存在于测试目录,不进入 OFFICIAL_PLUGIN_DEFINITIONS / SEA asset /
  8. * desktop bundle / remote prebuild 清单。
  9. */
  10. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  11. import { createServer, type Server } from "node:http";
  12. import type { AddressInfo } from "node:net";
  13. import { tmpdir } from "node:os";
  14. import { join } from "node:path";
  15. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  16. import type {
  17. McpServerConfig,
  18. OfficialMcpAuthHeadersPort,
  19. OfficialMcpTrustedOriginRegistry,
  20. } from "@zcode/contracts";
  21. import { createMcpAdapter } from "../src/mcp/index.js";
  22. import { createNodePluginAdapter } from "../src/plugins/index.js";
  23. const PLUGIN_NAME = "zcode-official-http-mcp";
  24. const MCP_KEY = "fake-official-search";
  25. const TOOL_NAME = "fake_search";
  26. const IDENTITY_HEADERS = {
  27. Authorization: "Bearer fake-jwt",
  28. "Bigmodel-Organization": "org-1",
  29. "Bigmodel-Project": "project-1",
  30. "Bigmodel-Target-Type": "TEAM",
  31. "X-Bigmodel-Authorization": "Bearer fake-maas-jwt",
  32. };
  33. interface ReceivedRequest {
  34. headers: Record<string, string | string[] | undefined>;
  35. method: string;
  36. rpcMethod?: string;
  37. }
  38. let server: Server;
  39. let origin: string;
  40. let requests: ReceivedRequest[];
  41. let tempDir: string;
  42. /** 服务端每个响应回带的 x-request-id,按 rpc 方法记下来供断言比对。 */
  43. let emittedRequestIds: Array<{ requestId: string; rpcMethod?: string }>;
  44. /** 置为 true 时 tools/call 返回 in-band 失败(HTTP 200 + isError),模拟配额耗尽。 */
  45. let toolCallReturnsInBandError: boolean;
  46. /** 最小 Streamable HTTP MCP 服务端:只实现本测试需要的四个协议动作。 */
  47. function createFakeMcpServer(): Server {
  48. return createServer((request, response) => {
  49. if (request.method === "GET") {
  50. // 官方 MCP 第一阶段不启用服务端推流:GET 返回 405,SDK 视为"不支持推流"正常继续。
  51. requests.push({ headers: request.headers, method: "GET" });
  52. response.writeHead(405).end();
  53. return;
  54. }
  55. const chunks: Buffer[] = [];
  56. request.on("data", (chunk: Buffer) => chunks.push(chunk));
  57. request.on("end", () => {
  58. const raw = Buffer.concat(chunks).toString("utf8");
  59. const message = raw ? (JSON.parse(raw) as { id?: unknown; method?: string }) : {};
  60. requests.push({
  61. headers: request.headers,
  62. method: "POST",
  63. ...(message.method ? { rpcMethod: message.method } : {}),
  64. });
  65. if (message.method === "notifications/initialized") {
  66. // 返回 202 是 MCP 惯例,也正是 SDK 尝试开 GET 推流的触发点。
  67. response.writeHead(202).end();
  68. return;
  69. }
  70. const result =
  71. message.method === "initialize"
  72. ? {
  73. capabilities: { tools: {} },
  74. protocolVersion: "2025-06-18",
  75. serverInfo: { name: "fake-official-mcp", version: "0.0.1" },
  76. }
  77. : message.method === "tools/list"
  78. ? {
  79. tools: [
  80. {
  81. description: "fake official search",
  82. inputSchema: { properties: {}, type: "object" },
  83. name: TOOL_NAME,
  84. },
  85. ],
  86. }
  87. : message.method === "tools/call"
  88. ? request.headers.authorization === undefined
  89. ? {
  90. content: [
  91. {
  92. text: '{"error_code":"coding_plan_required","message":"coding plan required"}',
  93. type: "text",
  94. },
  95. ],
  96. isError: true,
  97. }
  98. : toolCallReturnsInBandError
  99. ? {
  100. content: [
  101. {
  102. text: '{"error_code":"quota_exceeded","message":"daily quota exceeded"}',
  103. type: "text",
  104. },
  105. ],
  106. isError: true,
  107. }
  108. : { content: [{ text: "fake result", type: "text" }] }
  109. : {};
  110. // 真实服务端由 logx.RequestID() 生成并回带,客户端只能从响应头读。
  111. const requestId = `req-${emittedRequestIds.length + 1}`;
  112. emittedRequestIds.push({
  113. requestId,
  114. ...(message.method ? { rpcMethod: message.method } : {}),
  115. });
  116. response.writeHead(200, { "content-type": "application/json", "x-request-id": requestId });
  117. response.end(JSON.stringify({ id: message.id ?? null, jsonrpc: "2.0", result }));
  118. });
  119. });
  120. }
  121. beforeEach(async () => {
  122. requests = [];
  123. emittedRequestIds = [];
  124. toolCallReturnsInBandError = false;
  125. server = createFakeMcpServer();
  126. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  127. origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  128. tempDir = await mkdtemp(join(tmpdir(), "zcode-official-mcp-e2e-"));
  129. });
  130. afterEach(async () => {
  131. await new Promise<void>((resolve) => server.close(() => resolve()));
  132. await rm(tempDir, { force: true, recursive: true });
  133. });
  134. /** 写出 fake 官方 Plugin fixture,URL 经模板变量注入 loopback endpoint。 */
  135. async function discoverFakeOfficialPlugin(): Promise<{
  136. config: McpServerConfig;
  137. runtimeName: string;
  138. }> {
  139. const pluginRoot = join(tempDir, PLUGIN_NAME);
  140. await mkdir(join(pluginRoot, ".zcode-plugin"), { recursive: true });
  141. await writeFile(
  142. join(pluginRoot, ".zcode-plugin", "plugin.json"),
  143. JSON.stringify({ name: PLUGIN_NAME }),
  144. );
  145. await writeFile(
  146. join(pluginRoot, ".mcp.json"),
  147. JSON.stringify({
  148. mcpServers: {
  149. [MCP_KEY]: {
  150. auth: { provider: "jwt_token", type: "zcode_official" },
  151. timeoutMs: 30_000,
  152. type: "http",
  153. url: "${ZCODE_FAKE_OFFICIAL_MCP_URL}",
  154. },
  155. },
  156. }),
  157. );
  158. const outcome = await createNodePluginAdapter({
  159. storageRoot: join(tempDir, "plugins"),
  160. }).discoverPlugins({
  161. config: { dirs: [pluginRoot], enabled: true, enabledPlugins: {}, options: {} },
  162. env: { ZCODE_FAKE_OFFICIAL_MCP_URL: `${origin}/mcp` },
  163. storageRoot: join(tempDir, "plugins"),
  164. workingDirectory: tempDir,
  165. });
  166. const runtimeName = `plugin:${PLUGIN_NAME}:${MCP_KEY}`;
  167. const config = outcome.mcpServers[runtimeName];
  168. if (!config) {
  169. throw new Error(
  170. `fixture plugin did not produce an MCP config; diagnostics: ${JSON.stringify(outcome.diagnostics)}`,
  171. );
  172. }
  173. return { config, runtimeName };
  174. }
  175. function authPort(): OfficialMcpAuthHeadersPort & { calls: number } {
  176. let calls = 0;
  177. return {
  178. get calls() {
  179. return calls;
  180. },
  181. resolveHeaders: async () => {
  182. calls += 1;
  183. return { headers: IDENTITY_HEADERS, ok: true };
  184. },
  185. };
  186. }
  187. function loopbackRegistry(pluginId: string): OfficialMcpTrustedOriginRegistry {
  188. // loopback 例外只在测试通过依赖注入提供,不写入正式清单。
  189. return {
  190. isTrusted: async (input) => ({
  191. trusted: input.pluginId === pluginId && input.mcpKey === MCP_KEY && input.origin === origin,
  192. }),
  193. };
  194. }
  195. describe("official mcp end-to-end over a fake plugin and fake HTTP MCP", () => {
  196. it("OMCP-CALL-001: carries identity on discovery, listing, probes, and tools/call", async () => {
  197. const { config, runtimeName } = await discoverFakeOfficialPlugin();
  198. const official = (config as { official: { pluginId: string } }).official;
  199. const port = authPort();
  200. const adapter = createMcpAdapter({
  201. officialMcpAuth: {
  202. authHeadersPort: port,
  203. trustedOrigins: loopbackRegistry(official.pluginId),
  204. },
  205. workingDirectory: tempDir,
  206. });
  207. try {
  208. const status = await adapter.connectServer(runtimeName, config);
  209. expect(status.status).toBe("connected");
  210. const tools = await adapter.listTools();
  211. expect(tools.map((tool) => tool.toolName)).toContain(TOOL_NAME);
  212. // SG-02:http 官方 MCP 的结果来自已校验 origin 的 ZCode 后端,因此可以给结果背书
  213. // (UI 据此显示额度耗尽 / 无套餐提示)。stdio 不置位,见 stdio-meta 用例。
  214. expect(tools[0]?.official).toBe(true);
  215. const result = await adapter.callTool({ serverName: runtimeName, toolName: TOOL_NAME });
  216. expect(result.isError).not.toBe(true);
  217. const posts = requests.filter((entry) => entry.method === "POST");
  218. expect(posts.length).toBeGreaterThanOrEqual(3);
  219. const rpcMethods = posts.map((entry) => entry.rpcMethod);
  220. expect(rpcMethods).toContain("initialize");
  221. expect(rpcMethods).toContain("tools/call");
  222. expect(requests.filter((entry) => entry.rpcMethod === "tools/call")).toHaveLength(1);
  223. for (const entry of requests) {
  224. expect(entry.headers["authorization"]).toBe("Bearer fake-jwt");
  225. expect(entry.headers["x-bigmodel-authorization"]).toBe("Bearer fake-maas-jwt");
  226. expect(entry.headers["x-coding-plan-api-key"]).toBeUndefined();
  227. expect(entry.headers["bigmodel-target-type"]).toBe("TEAM");
  228. expect(entry.headers["bigmodel-organization"]).toBe("org-1");
  229. expect(entry.headers["bigmodel-project"]).toBe("project-1");
  230. }
  231. expect(port.calls).toBe(requests.length);
  232. // §6.3.4 的事实核对:SDK 在 initialized 收到 202 后确实会尝试 GET 推流,
  233. // 服务端 405 让它安全放弃且不影响连接(上面已断言 connected)。
  234. // §6.3.4 的事实固化:SDK 在 initialized 收到 202 后会尝试开 GET 推流,恰好一次。
  235. // 服务端 405 让它安全放弃且不重试(上面已断言 connected),这就是"不启用推流"的落地方式。
  236. expect(requests.filter((entry) => entry.method === "GET").length).toBe(1);
  237. } finally {
  238. await adapter.close();
  239. }
  240. });
  241. it("OMCP-013: creates no OAuth session and reports no authorization prompt", async () => {
  242. const { config, runtimeName } = await discoverFakeOfficialPlugin();
  243. const official = (config as { official: { pluginId: string } }).official;
  244. let authorizationRequired = 0;
  245. let openedAuthorizationUrl = 0;
  246. const adapter = createMcpAdapter({
  247. mcpOAuth: {
  248. onAuthorizationRequired: () => {
  249. authorizationRequired += 1;
  250. },
  251. openAuthorizationUrl: async () => {
  252. openedAuthorizationUrl += 1;
  253. },
  254. },
  255. officialMcpAuth: {
  256. authHeadersPort: authPort(),
  257. trustedOrigins: loopbackRegistry(official.pluginId),
  258. },
  259. workingDirectory: tempDir,
  260. });
  261. try {
  262. const status = await adapter.connectServer(runtimeName, config);
  263. expect(status.status).toBe("connected");
  264. // 官方鉴权路径必须完全绕开 OAuth:无授权回调、无 authorizationUrl
  265. expect(status.authorization).toBeUndefined();
  266. expect(authorizationRequired).toBe(0);
  267. expect(openedAuthorizationUrl).toBe(0);
  268. } finally {
  269. await adapter.close();
  270. }
  271. });
  272. it("OMCP-014: fails closed on 401 without falling back to an OAuth prompt", async () => {
  273. const { config, runtimeName } = await discoverFakeOfficialPlugin();
  274. const official = (config as { official: { pluginId: string } }).official;
  275. // 让 fake server 对所有 POST 返回 401
  276. await new Promise<void>((resolve) => server.close(() => resolve()));
  277. server = createServer((request, response) => {
  278. requests.push({ headers: request.headers, method: request.method ?? "" });
  279. response.writeHead(401, { "x-request-id": "req-auth-rejected" }).end();
  280. });
  281. await new Promise<void>((resolve) =>
  282. server.listen(Number(new URL(origin).port), "127.0.0.1", resolve),
  283. );
  284. let authorizationRequired = 0;
  285. const adapter = createMcpAdapter({
  286. mcpOAuth: {
  287. onAuthorizationRequired: () => {
  288. authorizationRequired += 1;
  289. },
  290. },
  291. officialMcpAuth: {
  292. authHeadersPort: authPort(),
  293. trustedOrigins: loopbackRegistry(official.pluginId),
  294. },
  295. workingDirectory: tempDir,
  296. });
  297. try {
  298. const status = await adapter.connectServer(runtimeName, config);
  299. expect(status.status).toBe("failed");
  300. expect(status.error).toBe(
  301. "Version negotiation probe failed: official MCP rejected the current credential - req-auth-rejected",
  302. );
  303. expect(status.authorization).toBeUndefined();
  304. expect(authorizationRequired).toBe(0);
  305. // 401 至多重试一次:不自旋
  306. expect(requests.filter((entry) => entry.method === "POST").length).toBeLessThanOrEqual(2);
  307. } finally {
  308. await adapter.close();
  309. }
  310. });
  311. it("OMCP-003: fails closed when the endpoint origin is not in the trusted registry", async () => {
  312. const { config, runtimeName } = await discoverFakeOfficialPlugin();
  313. const adapter = createMcpAdapter({
  314. officialMcpAuth: {
  315. authHeadersPort: authPort(),
  316. trustedOrigins: { isTrusted: async () => ({ trusted: false }) },
  317. },
  318. workingDirectory: tempDir,
  319. });
  320. try {
  321. const status = await adapter.connectServer(runtimeName, config);
  322. expect(status.status).toBe("failed");
  323. expect(requests).toHaveLength(0);
  324. } finally {
  325. await adapter.close();
  326. }
  327. });
  328. it("projects connection-stage server diagnostics into the failed status", async () => {
  329. const { config, runtimeName } = await discoverFakeOfficialPlugin();
  330. const official = (config as { official: { pluginId: string } }).official;
  331. await new Promise<void>((resolve) => server.close(() => resolve()));
  332. server = createServer((request, response) => {
  333. requests.push({ headers: request.headers, method: request.method ?? "" });
  334. response
  335. .writeHead(400, {
  336. "content-type": "application/json",
  337. "x-request-id": "req-settings-3001",
  338. })
  339. .end(JSON.stringify({ code: 3001, msg: "parameter error" }));
  340. });
  341. await new Promise<void>((resolve) =>
  342. server.listen(Number(new URL(origin).port), "127.0.0.1", resolve),
  343. );
  344. const adapter = createMcpAdapter({
  345. officialMcpAuth: {
  346. authHeadersPort: authPort(),
  347. trustedOrigins: loopbackRegistry(official.pluginId),
  348. },
  349. workingDirectory: tempDir,
  350. });
  351. try {
  352. await expect(adapter.connectServer(runtimeName, config)).resolves.toMatchObject({
  353. failureKind: "server_not_found",
  354. serverRequestId: "req-settings-3001",
  355. status: "failed",
  356. });
  357. } finally {
  358. await adapter.close();
  359. }
  360. });
  361. it("records the stable failure kind in the failure log, not only the message", async () => {
  362. // spec §6.3.3 的分类必须可 grep:message 文本里多数分类并不出现。
  363. const { config, runtimeName } = await discoverFakeOfficialPlugin();
  364. const logs: Array<{ context?: Record<string, unknown>; message: string }> = [];
  365. const logger = {
  366. child: () => logger,
  367. debug: () => {},
  368. error: () => {},
  369. info: () => {},
  370. warn: (message: string, context?: Record<string, unknown>) => {
  371. logs.push({ ...(context ? { context } : {}), message });
  372. },
  373. };
  374. const adapter = createMcpAdapter({
  375. logger: logger as unknown as Parameters<typeof createMcpAdapter>[0]["logger"],
  376. officialMcpAuth: {
  377. authHeadersPort: authPort(),
  378. trustedOrigins: { isTrusted: async () => ({ trusted: false }) },
  379. },
  380. workingDirectory: tempDir,
  381. });
  382. try {
  383. await adapter.connectServer(runtimeName, config);
  384. const failure = logs.find((entry) => entry.context?.["event"] === "mcp.server.failed");
  385. // message 被 SDK 包装成 "Version negotiation probe failed: ...",分类仍须可 grep
  386. expect(failure?.context?.["officialAuthKind"]).toBe("official_mcp_origin_untrusted");
  387. } finally {
  388. await adapter.close();
  389. }
  390. });
  391. it("records official_auth_rejected when the backend keeps returning 401", async () => {
  392. const { config, runtimeName } = await discoverFakeOfficialPlugin();
  393. const official = (config as { official: { pluginId: string } }).official;
  394. await new Promise<void>((resolve) => server.close(() => resolve()));
  395. server = createServer((request, response) => {
  396. requests.push({ headers: request.headers, method: request.method ?? "" });
  397. response.writeHead(401).end();
  398. });
  399. await new Promise<void>((resolve) =>
  400. server.listen(Number(new URL(origin).port), "127.0.0.1", resolve),
  401. );
  402. const logs: Array<{ context?: Record<string, unknown>; message: string }> = [];
  403. const logger = {
  404. child: () => logger,
  405. debug: () => {},
  406. error: () => {},
  407. info: () => {},
  408. warn: (message: string, context?: Record<string, unknown>) => {
  409. logs.push({ ...(context ? { context } : {}), message });
  410. },
  411. };
  412. const adapter = createMcpAdapter({
  413. logger: logger as unknown as Parameters<typeof createMcpAdapter>[0]["logger"],
  414. officialMcpAuth: {
  415. authHeadersPort: authPort(),
  416. trustedOrigins: loopbackRegistry(official.pluginId),
  417. },
  418. workingDirectory: tempDir,
  419. });
  420. try {
  421. await adapter.connectServer(runtimeName, config);
  422. const failure = logs.find((entry) => entry.context?.["event"] === "mcp.server.failed");
  423. expect(failure?.context?.["officialAuthKind"]).toBe("official_auth_rejected");
  424. } finally {
  425. await adapter.close();
  426. }
  427. });
  428. it("carries the server request id into an in-band tool failure result and log", async () => {
  429. // in-band 失败(配额耗尽、无套餐)是 HTTP 200 + isError:wrapper 的非 2xx warn 覆盖不到,
  430. // 而 request id 只有 wrapper 能看到,因此必须按 span 关联回 tool result。
  431. toolCallReturnsInBandError = true;
  432. const { config, runtimeName } = await discoverFakeOfficialPlugin();
  433. const official = (config as { official: { pluginId: string } }).official;
  434. const logs: Array<{ context?: Record<string, unknown>; message: string }> = [];
  435. const logger = {
  436. child: () => logger,
  437. debug: () => {},
  438. error: () => {},
  439. info: () => {},
  440. warn: (message: string, context?: Record<string, unknown>) => {
  441. logs.push({ ...(context ? { context } : {}), message });
  442. },
  443. };
  444. const adapter = createMcpAdapter({
  445. logger: logger as unknown as Parameters<typeof createMcpAdapter>[0]["logger"],
  446. officialMcpAuth: {
  447. authHeadersPort: authPort(),
  448. trustedOrigins: loopbackRegistry(official.pluginId),
  449. },
  450. workingDirectory: tempDir,
  451. });
  452. try {
  453. expect((await adapter.connectServer(runtimeName, config)).status).toBe("connected");
  454. const result = await adapter.callTool({
  455. serverName: runtimeName,
  456. toolName: TOOL_NAME,
  457. trace: { spanId: "span-quota-1", traceId: "trace-session-1" },
  458. });
  459. expect(result.isError).toBe(true);
  460. const expected = emittedRequestIds.find((entry) => entry.rpcMethod === "tools/call");
  461. expect(expected?.requestId).toBeTruthy();
  462. expect(result._meta?.["zcode/officialMcpServerRequestId"]).toBe(expected?.requestId);
  463. // 生产日志级别是 Info,所以这条必须是 warn,不能只有 debug。
  464. const failure = logs.find((entry) => entry.context?.["event"] === "mcp.tool.call");
  465. expect(failure?.context).toMatchObject({
  466. isError: true,
  467. serverRequestId: expected?.requestId,
  468. status: "failed",
  469. });
  470. } finally {
  471. await adapter.close();
  472. }
  473. });
  474. it("omits the request id when the call succeeds or cannot be correlated", async () => {
  475. const { config, runtimeName } = await discoverFakeOfficialPlugin();
  476. const official = (config as { official: { pluginId: string } }).official;
  477. const adapter = createMcpAdapter({
  478. officialMcpAuth: {
  479. authHeadersPort: authPort(),
  480. trustedOrigins: loopbackRegistry(official.pluginId),
  481. },
  482. workingDirectory: tempDir,
  483. });
  484. try {
  485. await adapter.connectServer(runtimeName, config);
  486. // 成功路径:id 不进结果,避免每次调用都往 _meta 里塞排障字段。
  487. const ok = await adapter.callTool({
  488. serverName: runtimeName,
  489. toolName: TOOL_NAME,
  490. trace: { spanId: "span-ok", traceId: "trace-session-1" },
  491. });
  492. expect(ok._meta?.["zcode/officialMcpServerRequestId"]).toBeUndefined();
  493. // 无 span 可关联时宁缺不猜:绝不把"最近一次响应"的 id 贴上来。
  494. toolCallReturnsInBandError = true;
  495. const failed = await adapter.callTool({ serverName: runtimeName, toolName: TOOL_NAME });
  496. expect(failed.isError).toBe(true);
  497. expect(failed._meta?.["zcode/officialMcpServerRequestId"]).toBeUndefined();
  498. } finally {
  499. await adapter.close();
  500. }
  501. });
  502. it("OMCP-CALL-002: connects and lists tools when no official auth port is injected", async () => {
  503. const { config, runtimeName } = await discoverFakeOfficialPlugin();
  504. const official = (config as { official: { pluginId: string } }).official;
  505. const adapter = createMcpAdapter({
  506. officialMcpAuth: {
  507. trustedOrigins: loopbackRegistry(official.pluginId),
  508. },
  509. workingDirectory: tempDir,
  510. });
  511. try {
  512. const status = await adapter.connectServer(runtimeName, config);
  513. expect(status.status).toBe("connected");
  514. expect((await adapter.listTools()).map((tool) => tool.toolName)).toContain(TOOL_NAME);
  515. const result = await adapter.callTool({ serverName: runtimeName, toolName: TOOL_NAME });
  516. expect(result.isError).toBe(true);
  517. expect(result.content).toEqual([
  518. expect.objectContaining({ text: expect.stringContaining("coding_plan_required") }),
  519. ]);
  520. expect((await adapter.status())[runtimeName]?.status).toBe("connected");
  521. } finally {
  522. await adapter.close();
  523. }
  524. });
  525. it("re-resolves credentials after login without reconnecting", async () => {
  526. const { config, runtimeName } = await discoverFakeOfficialPlugin();
  527. const official = (config as { official: { pluginId: string } }).official;
  528. let loggedIn = false;
  529. const adapter = createMcpAdapter({
  530. officialMcpAuth: {
  531. authHeadersPort: {
  532. resolveHeaders: async () =>
  533. loggedIn
  534. ? { headers: IDENTITY_HEADERS, ok: true as const }
  535. : { ok: false as const, reason: "official_auth_unavailable" as const },
  536. },
  537. trustedOrigins: loopbackRegistry(official.pluginId),
  538. },
  539. workingDirectory: tempDir,
  540. });
  541. try {
  542. expect((await adapter.connectServer(runtimeName, config)).status).toBe("connected");
  543. const denied = await adapter.callTool({ serverName: runtimeName, toolName: TOOL_NAME });
  544. expect(denied.isError).toBe(true);
  545. loggedIn = true;
  546. const allowed = await adapter.callTool({ serverName: runtimeName, toolName: TOOL_NAME });
  547. expect(allowed.isError).not.toBe(true);
  548. expect((await adapter.status())[runtimeName]?.status).toBe("connected");
  549. } finally {
  550. await adapter.close();
  551. }
  552. });
  553. });