needs-auth.test.ts 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { expect, it } from "vitest";
  2. // 需要用户授权的 server:保留的目录仍在视图里,调用结果告诉模型去哪里授权。
  3. import type { McpServerToolSnapshot, ToolExecutionContext } from "@zcode/contracts";
  4. import type { AgentRuntimeInternal } from "../../src/runtime/internal.js";
  5. import { createRuntime, mcpStatus, stdioServer, tool } from "../mcp-runtime-fixture.js";
  6. const TOOL_NAME = "mcp__remote__search";
  7. const AUTHORIZATION = { type: "oauth_authorization_code" } as const;
  8. const NEEDS_AUTH_TEXT =
  9. "MCP tool is unavailable in the current session: mcp__remote__search. Its MCP server 'remote' needs the user to re-authorize it before its tools work again. Ask the user to authorize it in the ZCode MCP settings.";
  10. function connectedRemote(): Record<string, McpServerToolSnapshot> {
  11. return {
  12. remote: {
  13. status: mcpStatus("connected", { toolCount: 1 }),
  14. tools: [tool("remote", "search")],
  15. toolsVersion: "1",
  16. },
  17. };
  18. }
  19. async function resolveReady(runtime: ReturnType<typeof createRuntime>["runtime"]) {
  20. await runtime.executeTurn("prepare");
  21. const entry = (runtime as unknown as AgentRuntimeInternal).registry.get(TOOL_NAME)!;
  22. const live = await entry.resolveForExecution!({});
  23. if (live.status !== "ready") throw new Error(`expected a ready tool, got ${live.status}`);
  24. return live.entry;
  25. }
  26. it("keeps retained tools of a server whose authorization ended without completing", async () => {
  27. const snapshot: Record<string, McpServerToolSnapshot> = {
  28. remote: {
  29. status: mcpStatus("failed", { failureKind: "oauth_authorization_failed" }),
  30. tools: [tool("remote", "search")],
  31. toolsVersion: "1",
  32. },
  33. };
  34. const { runtime } = createRuntime({
  35. label: "needs-auth-retained",
  36. snapshot,
  37. servers: { remote: stdioServer() },
  38. });
  39. try {
  40. // 修复前视图只列 connected/connecting 的工具:授权失败后工具离开视图,产生撤销提醒。
  41. const view = (runtime as unknown as AgentRuntimeInternal).mcpSession!.read();
  42. expect(view.tools.map((item) => item.toolName)).toEqual(["search"]);
  43. } finally {
  44. runtime.beginShutdown();
  45. }
  46. });
  47. it("tells the model to ask for authorization when a call starts one", async () => {
  48. const snapshot = connectedRemote();
  49. const { runtime } = createRuntime({
  50. label: "needs-auth-call",
  51. snapshot,
  52. servers: { remote: stdioServer() },
  53. mcpPort: {
  54. // 调用期 401:adapter 发起授权、发布链接后以原始错误结束这次调用。
  55. callTool: async () => {
  56. snapshot.remote = {
  57. ...snapshot.remote!,
  58. status: mcpStatus("connecting", { authorization: AUTHORIZATION }),
  59. };
  60. throw new Error("Unauthorized");
  61. },
  62. },
  63. });
  64. try {
  65. const entry = await resolveReady(runtime);
  66. await expect(
  67. entry.handler({}, { abortSignal: new AbortController().signal } as ToolExecutionContext),
  68. ).rejects.toThrow(NEEDS_AUTH_TEXT);
  69. } finally {
  70. runtime.beginShutdown();
  71. }
  72. });
  73. it("keeps the original error when a call fails for a reason other than authorization", async () => {
  74. const snapshot = connectedRemote();
  75. const { runtime } = createRuntime({
  76. label: "needs-auth-other-error",
  77. snapshot,
  78. servers: { remote: stdioServer() },
  79. mcpPort: {
  80. callTool: async () => {
  81. snapshot.remote = { status: mcpStatus("failed") };
  82. throw new Error("Connection closed");
  83. },
  84. },
  85. });
  86. try {
  87. const entry = await resolveReady(runtime);
  88. // 恢复耗尽等普通失败返回原始错误,不改写成状态文本。
  89. await expect(
  90. entry.handler({}, { abortSignal: new AbortController().signal } as ToolExecutionContext),
  91. ).rejects.toThrow(/^Connection closed$/);
  92. } finally {
  93. runtime.beginShutdown();
  94. }
  95. });