plugin-mention-items.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. // plugins/mentionItems(docs/design/v2/plugin-compat.md「Composer Mention Items」测试 1–8)。
  2. // 会话 record 用最小桩:冻结的 plugin catalog、工具可见性、MCP App 授权链上的工具调用(callMcpToolForUi)。
  3. import { describe, expect, it, vi } from "vitest";
  4. import type {
  5. Logger,
  6. McpPort,
  7. McpToolCallResult,
  8. McpToolDescriptor,
  9. PluginReferenceCatalog,
  10. } from "@zcode/contracts";
  11. import { CoreErrorType, createCoreError } from "@zcode/contracts";
  12. import type { McpAppsToolVisibility } from "@zcode/shared/mcp-apps";
  13. import {
  14. ZCODE_PLUGIN_MENTION_ERROR_CODES,
  15. zcodePluginsMentionItemsResultSchema,
  16. zcodeProtocolErrorCodes,
  17. zcodeProtocolMethods,
  18. } from "@zcode/shared";
  19. import { DefaultRuntimeConfig } from "@zcode/contracts";
  20. import { createSessionFacade } from "../src/app/session-facade.js";
  21. import { getPluginMentionItems } from "../src/zcode-protocol/plugin-mention-items.js";
  22. import type {
  23. ZCodeProtocolAgentServerContext,
  24. ZCodeProtocolSessionRecord,
  25. } from "../src/zcode-protocol/server-types.js";
  26. const SESSION_ID = "sess_mention";
  27. const PLUGIN_ID = "gitlab@mkt";
  28. const TOOL = "search_merge_requests";
  29. const FIRST_SERVER = "plugin:gitlab:aaa";
  30. const TOOL_SERVER = "plugin:gitlab:zzz";
  31. const QUERY = "secret-query";
  32. const LEAK_MARKER = "LEAK-MARKER";
  33. const INVALID_PARAMS = -32602;
  34. const SERVER_ERROR = -32000;
  35. const MAX_ITEMS = 50;
  36. const MAX_INSERT_TEXT = 4000;
  37. interface Stub {
  38. context: ZCodeProtocolAgentServerContext;
  39. callTool: ReturnType<typeof vi.fn>;
  40. debug: ReturnType<typeof vi.fn>;
  41. }
  42. function createStub(input: {
  43. catalog?: PluginReferenceCatalog;
  44. visibility?: Record<string, readonly McpAppsToolVisibility[] | null>;
  45. call?: () => Promise<McpToolCallResult>;
  46. }): Stub {
  47. const catalog: PluginReferenceCatalog = input.catalog ?? {
  48. plugins: [
  49. {
  50. pluginId: PLUGIN_ID,
  51. name: "gitlab",
  52. marketplace: "mkt",
  53. enabled: true,
  54. conflictingPluginIds: [],
  55. skillQualifiedNames: [],
  56. // 故意乱序:CLI 要按排序后的 server 名依次找工具。
  57. mcpServerNames: [TOOL_SERVER, FIRST_SERVER],
  58. subagentNames: [],
  59. rootPath: "/plugins/gitlab",
  60. },
  61. ],
  62. };
  63. const visibility = input.visibility ?? { [TOOL_SERVER]: ["model", "app"] };
  64. const callTool = vi.fn(
  65. input.call ??
  66. (async (): Promise<McpToolCallResult> => ({
  67. content: [],
  68. structuredContent: { items: [{ id: "1", label: "!1", insertText: "MR !1" }] },
  69. })),
  70. );
  71. const debug = vi.fn();
  72. const logger = { debug, info: vi.fn(), warn: vi.fn(), error: vi.fn() } as unknown as Logger;
  73. (logger as { child: () => Logger }).child = () => logger;
  74. const record = {
  75. app: {
  76. getPluginReferenceCatalog: () => catalog,
  77. getMcpToolVisibility: async (serverName: string, toolName: string) =>
  78. toolName === TOOL ? (visibility[serverName] ?? null) : null,
  79. callMcpToolForUi: callTool,
  80. },
  81. } as unknown as ZCodeProtocolSessionRecord;
  82. return {
  83. context: {
  84. deps: {},
  85. logger,
  86. sessions: new Map([[SESSION_ID, record]]),
  87. } as unknown as ZCodeProtocolAgentServerContext,
  88. callTool,
  89. debug,
  90. };
  91. }
  92. const params = (overrides: Record<string, unknown> = {}) => ({
  93. sessionId: SESSION_ID,
  94. pluginId: PLUGIN_ID,
  95. tool: TOOL,
  96. query: QUERY,
  97. ...overrides,
  98. });
  99. describe("plugins/mentionItems", () => {
  100. it("registers the method name", () => {
  101. expect(zcodeProtocolMethods.pluginsMentionItems).toBe("plugins/mentionItems");
  102. });
  103. it("1. rejects a session that is not in memory without calling any tool", async () => {
  104. const stub = createStub({});
  105. await expect(
  106. getPluginMentionItems(stub.context, params({ sessionId: "sess_missing" })),
  107. ).rejects.toMatchObject({ code: zcodeProtocolErrorCodes.sessionUnavailable });
  108. expect(stub.callTool).not.toHaveBeenCalled();
  109. });
  110. it.each([
  111. ["missing", { plugins: [] }],
  112. [
  113. "disabled",
  114. {
  115. plugins: [
  116. {
  117. pluginId: PLUGIN_ID,
  118. name: "gitlab",
  119. marketplace: "mkt",
  120. enabled: false,
  121. conflictingPluginIds: [],
  122. skillQualifiedNames: [],
  123. mcpServerNames: [],
  124. subagentNames: [],
  125. rootPath: "/plugins/gitlab",
  126. },
  127. ],
  128. },
  129. ],
  130. [
  131. "conflicting",
  132. {
  133. plugins: [
  134. {
  135. pluginId: PLUGIN_ID,
  136. name: "gitlab",
  137. marketplace: "mkt",
  138. enabled: true,
  139. conflictingPluginIds: ["gitlab@other"],
  140. skillQualifiedNames: [],
  141. mcpServerNames: [TOOL_SERVER],
  142. subagentNames: [],
  143. rootPath: "/plugins/gitlab",
  144. },
  145. ],
  146. },
  147. ],
  148. ] as const)("2. rejects a %s plugin as unavailable", async (_label, catalog) => {
  149. const stub = createStub({ catalog: catalog as unknown as PluginReferenceCatalog });
  150. await expect(getPluginMentionItems(stub.context, params())).rejects.toMatchObject({
  151. code: INVALID_PARAMS,
  152. data: { code: ZCODE_PLUGIN_MENTION_ERROR_CODES.pluginUnavailable },
  153. });
  154. expect(stub.callTool).not.toHaveBeenCalled();
  155. });
  156. it("3. rejects a missing tool and a model-only tool without calling them", async () => {
  157. const missing = createStub({ visibility: {} });
  158. await expect(getPluginMentionItems(missing.context, params())).rejects.toMatchObject({
  159. code: INVALID_PARAMS,
  160. data: { code: ZCODE_PLUGIN_MENTION_ERROR_CODES.toolNotFound },
  161. });
  162. expect(missing.callTool).not.toHaveBeenCalled();
  163. const modelOnly = createStub({ visibility: { [TOOL_SERVER]: ["model"] } });
  164. await expect(getPluginMentionItems(modelOnly.context, params())).rejects.toMatchObject({
  165. code: INVALID_PARAMS,
  166. data: { code: ZCODE_PLUGIN_MENTION_ERROR_CODES.toolNotAppVisible },
  167. });
  168. expect(modelOnly.callTool).not.toHaveBeenCalled();
  169. });
  170. it("4. calls the tool with { query } on the plugin's own server and returns the items", async () => {
  171. const items = [
  172. {
  173. id: "1",
  174. label: "!1 Fix login",
  175. description: "opened",
  176. icon: "git-merge",
  177. insertText: "MR !1",
  178. },
  179. { id: "2", label: "!2", insertText: "MR !2" },
  180. ];
  181. const stub = createStub({
  182. visibility: { [FIRST_SERVER]: null, [TOOL_SERVER]: ["app"] },
  183. call: async () => ({ content: [], structuredContent: { items } }),
  184. });
  185. const result = await getPluginMentionItems(stub.context, params());
  186. expect(zcodePluginsMentionItemsResultSchema.parse(result)).toEqual({ items });
  187. expect(stub.callTool).toHaveBeenCalledTimes(1);
  188. expect(stub.callTool.mock.calls[0]?.slice(0, 3)).toEqual([TOOL_SERVER, TOOL, { query: QUERY }]);
  189. // debug 日志按键级频率出现,不能带 query 与结果内容。
  190. expect(stub.debug).toHaveBeenCalled();
  191. expect(JSON.stringify(stub.debug.mock.calls)).not.toContain(QUERY);
  192. expect(JSON.stringify(stub.debug.mock.calls)).not.toContain("Fix login");
  193. });
  194. it("5. maps an isError result and a thrown call to tool_failed", async () => {
  195. const isError = createStub({
  196. call: async () => ({ content: [{ type: "text", text: LEAK_MARKER }], isError: true }),
  197. });
  198. const rejectedIsError = getPluginMentionItems(isError.context, params());
  199. await expect(rejectedIsError).rejects.toMatchObject({
  200. code: SERVER_ERROR,
  201. data: { code: ZCODE_PLUGIN_MENTION_ERROR_CODES.toolFailed },
  202. });
  203. await expect(rejectedIsError).rejects.not.toThrow(LEAK_MARKER);
  204. const thrown = createStub({
  205. call: async () => {
  206. throw new Error("MCP server disconnected");
  207. },
  208. });
  209. await expect(getPluginMentionItems(thrown.context, params())).rejects.toMatchObject({
  210. code: SERVER_ERROR,
  211. data: { code: ZCODE_PLUGIN_MENTION_ERROR_CODES.toolFailed },
  212. });
  213. });
  214. it.each([
  215. [
  216. "too many items",
  217. {
  218. items: Array.from({ length: MAX_ITEMS + 1 }, (_, index) => ({
  219. id: String(index),
  220. label: LEAK_MARKER,
  221. insertText: "x",
  222. })),
  223. },
  224. ],
  225. [
  226. "an oversized insertText",
  227. {
  228. items: [{ id: "1", label: "x", insertText: LEAK_MARKER.padEnd(MAX_INSERT_TEXT + 1, "x") }],
  229. },
  230. ],
  231. ["an unknown field", { items: [{ id: "1", label: "x", insertText: "x", url: LEAK_MARKER }] }],
  232. ["missing structuredContent", undefined],
  233. ] as const)(
  234. "6. rejects %s as result_invalid without echoing content",
  235. async (_label, content) => {
  236. const stub = createStub({
  237. call: async () => ({
  238. content: [{ type: "text", text: LEAK_MARKER }],
  239. ...(content === undefined ? {} : { structuredContent: content }),
  240. }),
  241. });
  242. const error = await getPluginMentionItems(stub.context, params()).then(
  243. () => undefined,
  244. (reason: unknown) => reason,
  245. );
  246. expect(error).toMatchObject({
  247. code: SERVER_ERROR,
  248. data: { code: ZCODE_PLUGIN_MENTION_ERROR_CODES.resultInvalid },
  249. });
  250. expect(String((error as Error).message)).not.toContain(LEAK_MARKER);
  251. expect(JSON.stringify((error as { data?: unknown }).data)).not.toContain(LEAK_MARKER);
  252. },
  253. );
  254. });
  255. describe("plugins/mentionItems authorization", () => {
  256. it("7. maps a denial from the authorization chain to tool_denied", async () => {
  257. const stub = createStub({
  258. call: async () => {
  259. throw createCoreError(CoreErrorType.PermissionDenied, `Permission denied: ${LEAK_MARKER}`);
  260. },
  261. });
  262. const error = await getPluginMentionItems(stub.context, params()).then(
  263. () => undefined,
  264. (reason: unknown) => reason,
  265. );
  266. expect(error).toMatchObject({
  267. code: SERVER_ERROR,
  268. data: { code: ZCODE_PLUGIN_MENTION_ERROR_CODES.toolDenied },
  269. });
  270. // 拒绝原因可能来自用户反馈或 hook,不转进错误信息。
  271. expect(String((error as Error).message)).not.toContain(LEAK_MARKER);
  272. });
  273. it("8. waits while the approval is pending and answers after it is granted", async () => {
  274. const approval = Promise.withResolvers<McpToolCallResult>();
  275. const stub = createStub({ call: () => approval.promise });
  276. let settled = false;
  277. const pending = getPluginMentionItems(stub.context, params()).finally(() => {
  278. settled = true;
  279. });
  280. await new Promise((resolve) => setImmediate(resolve));
  281. expect(settled).toBe(false);
  282. approval.resolve({
  283. content: [],
  284. structuredContent: { items: [{ id: "1", label: "!1", insertText: "MR !1" }] },
  285. });
  286. await expect(pending).resolves.toEqual({
  287. items: [{ id: "1", label: "!1", insertText: "MR !1" }],
  288. });
  289. });
  290. });
  291. describe("session facade callMcpToolForUi (the path plugins/mentionItems uses)", () => {
  292. const descriptor: McpToolDescriptor = {
  293. name: TOOL,
  294. serverName: TOOL_SERVER,
  295. toolName: TOOL,
  296. inputSchema: { type: "object" },
  297. };
  298. const snapshot = { identity: "connection", generation: 1 };
  299. function createFacade(authorizeAppTool: ReturnType<typeof vi.fn>) {
  300. const result: McpToolCallResult = { content: [], structuredContent: { items: [] } };
  301. const callTool = vi.fn(async () => result);
  302. const mcpPort = {
  303. appConnectionSnapshot: () => snapshot,
  304. listTools: async () => [descriptor],
  305. callTool,
  306. } as unknown as McpPort;
  307. const facade = createSessionFacade({
  308. configResult: { config: DefaultRuntimeConfig },
  309. mcpPort,
  310. runtime: {
  311. getToolExecutor: () => ({ authorizeAppTool }),
  312. getToolRegistry: () => ({ list: () => [], get: () => undefined }),
  313. },
  314. traceContext: { traceId: "mention-trace" },
  315. } as never);
  316. return { facade, callTool, result };
  317. }
  318. it("runs the authorization chain, then calls the tool with the approved input", async () => {
  319. const authorizeAppTool = vi.fn(async () => ({ query: QUERY }));
  320. const { facade, callTool, result } = createFacade(authorizeAppTool);
  321. await expect(facade.callMcpToolForUi(TOOL_SERVER, TOOL, { query: QUERY })).resolves.toBe(
  322. result,
  323. );
  324. expect(authorizeAppTool).toHaveBeenCalledOnce();
  325. expect(authorizeAppTool.mock.calls[0]?.[0]).toMatchObject({ input: { query: QUERY } });
  326. expect(callTool).toHaveBeenCalledWith(
  327. expect.objectContaining({
  328. serverName: TOOL_SERVER,
  329. toolName: TOOL,
  330. arguments: { query: QUERY },
  331. runtimeScope: "main",
  332. }),
  333. expect.objectContaining({ appConnection: snapshot }),
  334. );
  335. });
  336. it("does not call the tool when the authorization chain denies", async () => {
  337. const authorizeAppTool = vi.fn(async () => {
  338. throw createCoreError(CoreErrorType.PermissionDenied, "Permission denied");
  339. });
  340. const { facade, callTool } = createFacade(authorizeAppTool);
  341. await expect(
  342. facade.callMcpToolForUi(TOOL_SERVER, TOOL, { query: QUERY }),
  343. ).rejects.toMatchObject({ type: CoreErrorType.PermissionDenied });
  344. expect(callTool).not.toHaveBeenCalled();
  345. });
  346. });