contract.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import { expect, it, vi } from "vitest";
  2. import { createSessionId, type McpServerToolSnapshot } from "@zcode/contracts";
  3. import type { AgentRuntimeInternal } from "../../src/runtime/internal.js";
  4. import { createRuntime, createSnapshotMcpPort, mcpStatus, tool } from "../mcp-runtime-fixture.js";
  5. import { createTestAgentRuntime } from "../test-agent-runtime.js";
  6. import { createTestSessionEventStore } from "../test-event-store.js";
  7. import { isBorrowedMcpPort } from "../../src/subagent/borrowed-mcp-port.js";
  8. it.each(["missing", "connected", "failed", "empty", "pending"])(
  9. "uses cached tools only for an admitted pending record with an unknown list: %s",
  10. async (status) => {
  11. const snapshot: Record<string, McpServerToolSnapshot> =
  12. status === "missing"
  13. ? {}
  14. : {
  15. local: {
  16. status: mcpStatus(
  17. status === "pending"
  18. ? "connecting"
  19. : status === "empty"
  20. ? "connected"
  21. : (status as "connected" | "failed"),
  22. ),
  23. ...(status === "empty" ? { tools: [] } : {}),
  24. },
  25. };
  26. const { runtime } = createRuntime({
  27. label: `cache-${status}`,
  28. snapshot,
  29. mcpToolCatalogPort: {
  30. prepare: () => ({
  31. lookup: { status: "complete", byServer: { local: [tool("local", "cached")] } },
  32. publish() {},
  33. }),
  34. },
  35. });
  36. try {
  37. const session = (runtime as unknown as AgentRuntimeInternal).mcpSession!;
  38. session.start();
  39. expect(session.read().tools.map((item) => item.toolName)).toEqual(
  40. status === "pending" ? ["cached"] : [],
  41. );
  42. } finally {
  43. runtime.beginShutdown();
  44. }
  45. },
  46. );
  47. it("reports background recovery only as pending and does not classify authorization as failure", async () => {
  48. const snapshot: Record<string, McpServerToolSnapshot> = {
  49. local: { status: mcpStatus("connecting", { error: "socket closed" }) },
  50. };
  51. const { runtime } = createRuntime({
  52. label: "recovery-facts",
  53. snapshot,
  54. toolSearchMode: "native",
  55. });
  56. try {
  57. await runtime.executeTurn("first");
  58. expect((runtime as unknown as AgentRuntimeInternal).mcpServerStatusFacts).toMatchObject({
  59. pending: ["local"],
  60. failed: [],
  61. });
  62. snapshot.local = {
  63. status: mcpStatus("failed", {
  64. authorization: {
  65. type: "oauth_authorization_code",
  66. authorizationUrl: "https://example.com/authorize",
  67. startedAt: "2026-01-01T00:00:00Z",
  68. },
  69. }),
  70. };
  71. await runtime.executeTurn("authorization required");
  72. expect((runtime as unknown as AgentRuntimeInternal).mcpServerStatusFacts).toMatchObject({
  73. pending: [],
  74. needsAuth: ["local"],
  75. failed: [],
  76. });
  77. } finally {
  78. runtime.beginShutdown();
  79. }
  80. });
  81. it("compares normalized connection diagnostics before deciding whether to repeat an announcement", async () => {
  82. const snapshot = {
  83. local: { status: mcpStatus("failed", { error: "socket\nclosed", errorCode: "ECONNRESET" }) },
  84. };
  85. const { runtime } = createRuntime({
  86. label: "normalized-diagnostic",
  87. snapshot,
  88. toolSearchMode: "native",
  89. });
  90. try {
  91. await runtime.executeTurn("first");
  92. const before = (runtime as unknown as AgentRuntimeInternal).mcpServerStatusFacts;
  93. expect(before.failed).toEqual([
  94. { name: "local", errorCode: "ECONNRESET", error: "socket closed" },
  95. ]);
  96. snapshot.local.status = mcpStatus("failed", {
  97. error: "socket\tclosed",
  98. errorCode: "ECONNRESET",
  99. });
  100. await runtime.executeTurn("same fact");
  101. expect((runtime as unknown as AgentRuntimeInternal).mcpServerStatusFacts).toEqual(before);
  102. } finally {
  103. runtime.beginShutdown();
  104. }
  105. });
  106. it("reads new connection records before notifications without publishing from reads", async () => {
  107. const snapshot: Record<string, McpServerToolSnapshot> = {
  108. local: { status: mcpStatus("connecting") },
  109. };
  110. const publish = vi.fn();
  111. const { runtime } = createRuntime({
  112. label: "pure-read",
  113. snapshot,
  114. mcpPort: { onSnapshotChanged: () => () => {} },
  115. mcpToolCatalogPort: {
  116. prepare: () => ({ lookup: { status: "incomplete", byServer: {} }, publish }),
  117. },
  118. });
  119. try {
  120. await runtime.executeTurn("first");
  121. publish.mockClear();
  122. snapshot.local = {
  123. status: mcpStatus("connected"),
  124. tools: [tool("local", "fresh")],
  125. toolsVersion: "1",
  126. };
  127. const session = (runtime as unknown as AgentRuntimeInternal).mcpSession!;
  128. expect(session.read().tools.map((item) => item.toolName)).toEqual(["fresh"]);
  129. session.read();
  130. expect(publish).not.toHaveBeenCalled();
  131. } finally {
  132. runtime.beginShutdown();
  133. }
  134. });
  135. it("registers the wait tool only with an MCP session and offers it only while a server connects", () => {
  136. const { runtime } = createRuntime({ label: "wait-registry", snapshot: {} });
  137. const withoutMcp = createTestAgentRuntime(
  138. createSessionId("wait-registry-without-mcp"),
  139. {},
  140. { eventStore: createTestSessionEventStore() },
  141. );
  142. try {
  143. expect(
  144. (runtime as unknown as AgentRuntimeInternal).registry.get("WaitForMcpServers"),
  145. ).toBeDefined();
  146. // 没有 server 在连接、也没有发送过:工具名单与没有该工具时相同。
  147. expect(runtime.getTools().map((entry) => entry.name)).not.toContain("WaitForMcpServers");
  148. expect(
  149. (withoutMcp as unknown as AgentRuntimeInternal).registry.get("WaitForMcpServers"),
  150. ).toBeUndefined();
  151. } finally {
  152. runtime.beginShutdown();
  153. withoutMcp.beginShutdown();
  154. }
  155. });
  156. it("preserves an injected port's directory when the parent does not own server configuration", async () => {
  157. const parentId = createSessionId("injected-parent");
  158. const port = createSnapshotMcpPort({
  159. local: { status: mcpStatus("connected"), tools: [tool("local", "ping")], toolsVersion: "1" },
  160. });
  161. const parent = createTestAgentRuntime(
  162. parentId,
  163. {},
  164. {
  165. eventStore: createTestSessionEventStore(),
  166. mcpPort: port,
  167. },
  168. );
  169. const access = await parent.createChildMcpAccess();
  170. // 所有权由端口标记推导,child 入口不再需要单独传递所有权参数。
  171. expect(isBorrowedMcpPort(access.deps.mcpPort)).toBe(true);
  172. expect(isBorrowedMcpPort(port)).toBe(false);
  173. const child = createTestAgentRuntime(
  174. createSessionId("injected-child"),
  175. {
  176. parentSessionId: parentId,
  177. mcp: access.config,
  178. },
  179. { eventStore: createTestSessionEventStore(), ...access.deps },
  180. );
  181. try {
  182. expect((child as unknown as AgentRuntimeInternal).mcpSession!.read().tools).toEqual([
  183. tool("local", "ping"),
  184. ]);
  185. } finally {
  186. child.beginShutdown();
  187. parent.beginShutdown();
  188. }
  189. });
  190. it("a fork owns its connection even though its history has a parent", async () => {
  191. const connectConfiguredServers = vi.fn(async () => ({ statuses: {}, tools: [] }));
  192. const runtime = createTestAgentRuntime(
  193. createSessionId("fork-owner"),
  194. {
  195. parentSessionId: createSessionId("fork-parent"),
  196. mcp: { enabled: true, servers: { local: { type: "stdio", command: "node" } } },
  197. },
  198. {
  199. eventStore: createTestSessionEventStore(),
  200. mcpPort: createSnapshotMcpPort({}, { connectConfiguredServers }),
  201. },
  202. );
  203. try {
  204. await (runtime as unknown as AgentRuntimeInternal).mcpSession!.start();
  205. expect(connectConfiguredServers).toHaveBeenCalledOnce();
  206. } finally {
  207. runtime.beginShutdown();
  208. }
  209. });
  210. it("a view without a catalog publisher does not subscribe to connection notifications", () => {
  211. const subscribe = vi.fn(() => vi.fn());
  212. const { runtime } = createRuntime({
  213. label: "no-publisher",
  214. snapshot: {},
  215. mcpPort: { onSnapshotChanged: subscribe },
  216. });
  217. try {
  218. (runtime as unknown as AgentRuntimeInternal).mcpSession!.start();
  219. expect(subscribe).not.toHaveBeenCalled();
  220. } finally {
  221. runtime.beginShutdown();
  222. }
  223. });
  224. it("target check follows the live connection and rejects only a missing tool or server", async () => {
  225. const target = tool("local", "run");
  226. const snapshot: Record<string, McpServerToolSnapshot> = {
  227. local: { status: mcpStatus("connected"), tools: [target], toolsVersion: "1" },
  228. };
  229. const { runtime } = createRuntime({ label: "target-admission", snapshot });
  230. try {
  231. const admission = await (runtime as unknown as AgentRuntimeInternal).mcpSession!.resolve(
  232. target,
  233. );
  234. if (!("checkTarget" in admission)) throw new Error("Tool admission failed");
  235. expect(admission.checkTarget()).toBeUndefined();
  236. snapshot.local = {
  237. ...snapshot.local!,
  238. tools: [
  239. { ...target, inputSchema: { type: "object", properties: { added: { type: "string" } } } },
  240. tool("local", "other"),
  241. ],
  242. toolsVersion: "2",
  243. };
  244. // 定义刷新或同配置重连不影响已批准的调用。
  245. expect(admission.checkTarget()).toBeUndefined();
  246. snapshot.local = { ...snapshot.local!, tools: [tool("local", "other")], toolsVersion: "3" };
  247. expect(admission.checkTarget()).toBe(
  248. "Its MCP server 'local' is connected but does not offer this tool here. Continue without it.",
  249. );
  250. snapshot.local = { status: mcpStatus("failed") };
  251. expect(admission.checkTarget()).toBe(
  252. "Its MCP server 'local' has disconnected. Continue without this tool; it becomes callable again only if the server reconnects.",
  253. );
  254. } finally {
  255. runtime.beginShutdown();
  256. }
  257. });
  258. it.each(["failed", "connecting", "disabled"] as const)(
  259. "execution rejection explains the current server state: %s",
  260. async (status) => {
  261. const snapshot = {
  262. local: { status: mcpStatus(status), tools: [tool("local", "run")], toolsVersion: "1" },
  263. };
  264. const { runtime } = createRuntime({ label: `unavailable-${status}`, snapshot });
  265. try {
  266. const resolved = await (runtime as unknown as AgentRuntimeInternal).mcpSession!.resolve(
  267. tool("local", "run"),
  268. );
  269. expect(resolved).toMatchObject({
  270. unavailableReason: expect.stringMatching(
  271. status === "connecting"
  272. ? /still connecting/
  273. : status === "disabled"
  274. ? /disabled/
  275. : /disconnected/,
  276. ),
  277. });
  278. } finally {
  279. runtime.beginShutdown();
  280. }
  281. },
  282. );