mcp-oauth-child-driver.ts 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /**
  2. * 跨进程 E2E 的子进程驱动。
  3. *
  4. * 由 tests/mcp-oauth-cross-process.e2e.test.ts 用 tsx 以真实 OS 进程拉起:真实文件锁、
  5. * 真实凭据文件、真实网络请求都在子进程里发生,主进程只负责托管假服务器与断言。
  6. * 这正是线上事故形态——竞态发生在多个 CLI 进程之间,同进程测试盖不住。
  7. *
  8. * 协议:argv[2] 是 JSON 配置;结束向 stdout 打印一行 JSON 结果;失败 exit 1。
  9. */
  10. import { createSharedZCodeCredentialStore } from "../../src/auth/shared-credentials.js";
  11. import { createMcpAdapter } from "../../src/mcp/index.js";
  12. import { createMcpOAuthTokenProvider } from "../../src/mcp/oauth-provider.js";
  13. interface DriverConfig {
  14. autoDrive?: boolean;
  15. credentialsPath: string;
  16. keyPrefix?: string;
  17. mcpUrl: string;
  18. mode: "refresh-race" | "authorize";
  19. secret: string;
  20. serverName?: string;
  21. }
  22. async function main(): Promise<void> {
  23. const config = JSON.parse(process.argv[2] ?? "{}") as DriverConfig;
  24. const credentialStore = createSharedZCodeCredentialStore({
  25. env: { ZCODE_CREDENTIAL_SECRET: config.secret },
  26. filePath: config.credentialsPath,
  27. });
  28. if (config.mode === "refresh-race") {
  29. // 直接驱动 Phase 1 provider:并发临期刷新的单飞语义不依赖 transport。
  30. const provider = createMcpOAuthTokenProvider({
  31. config: { type: "authorization_code", scope: "mcp:tools" },
  32. credentialStore,
  33. keyPrefix: config.keyPrefix ?? "",
  34. serverName: "cross-process",
  35. serverUrl: config.mcpUrl,
  36. });
  37. const token = await provider.token();
  38. process.stdout.write(JSON.stringify({ token }));
  39. return;
  40. }
  41. // authorize 模式:完整建连。leader 会走到 openAuthorizationUrl(autoDrive 时自动完成
  42. // 浏览器动作);follower 只会收到 onAuthorizationRequired,绝不能重复驱动授权 URL。
  43. const authorizationUrls: string[] = [];
  44. const adapter = createMcpAdapter({
  45. mcpOAuth: {
  46. credentialStore,
  47. ...(config.autoDrive
  48. ? {
  49. openAuthorizationUrl: async ({ authorizationUrl }) => {
  50. authorizationUrls.push(authorizationUrl);
  51. const response = await fetch(authorizationUrl, { redirect: "manual" });
  52. const location = response.headers.get("location");
  53. if (location) await fetch(location);
  54. },
  55. }
  56. : {}),
  57. onAuthorizationRequired: () => undefined,
  58. },
  59. });
  60. try {
  61. const status = await adapter.connectServer(config.serverName ?? "cross-process", {
  62. type: "http",
  63. url: config.mcpUrl,
  64. oauth: { type: "authorization_code", scope: "mcp:tools" },
  65. });
  66. process.stdout.write(JSON.stringify({ authorizationUrls, status }));
  67. } finally {
  68. await adapter.close();
  69. }
  70. }
  71. void main().then(
  72. () => undefined,
  73. (error: unknown) => {
  74. process.stderr.write(error instanceof Error ? (error.stack ?? error.message) : String(error));
  75. process.exit(1);
  76. },
  77. );