oauth-provider.ts 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import type { FetchLike, AuthProvider } from "@modelcontextprotocol/client";
  2. import type { Logger, McpOAuthConfig } from "@zcode/contracts";
  3. import type { SharedZCodeCredentialStore } from "../auth/shared-credentials.js";
  4. import { isCanonicalTokenNearExpiry, loadCredentialPair } from "./oauth-credentials.js";
  5. import { createInteractiveAuthorizationRequiredError } from "./oauth-errors.js";
  6. import { refreshMcpOAuthTokensUnderLock } from "./oauth-refresh.js";
  7. type McpAuthorizationCodeOAuthConfig = Extract<McpOAuthConfig, { type: "authorization_code" }>;
  8. export interface CreateMcpOAuthTokenProviderInput {
  9. config: McpAuthorizationCodeOAuthConfig;
  10. credentialStore: SharedZCodeCredentialStore;
  11. fetchFn?: FetchLike;
  12. keyPrefix: string;
  13. logger?: Logger;
  14. serverName: string;
  15. serverUrl: string;
  16. }
  17. /**
  18. * Phase 1 运行期 AuthProvider。
  19. *
  20. * 只实现 `token()` 与 `onUnauthorized()`,**不是** `OAuthClientProvider`:transport 的
  21. * `isOAuthClientProvider()` 判定因此为 false,`_oauthProvider` 保持为空
  22. * (client@2.0.0 `index.mjs:4977-4980`),于是:
  23. *
  24. * - 建连不做 discovery、不做 DCR、不开 callback listener;
  25. * - 401 只调用我们的 `onUnauthorized()` 并自动重试一次,SDK 的 `auth()` 完全不参与,
  26. * 所有 refresh 都被强制汇入我们的跨进程单飞锁。
  27. *
  28. * 绝不要把 `OAuthClientProvider` 传给运行期 transport:它会被 `adaptOAuthProvider` 包裹,
  29. * 401 走 SDK 的 `handleOAuthUnauthorized()` → `auth()`,绕过 refresh 锁,并发刷新问题立即复发。
  30. */
  31. export function createMcpOAuthTokenProvider(
  32. input: CreateMcpOAuthTokenProviderInput,
  33. ): AuthProvider {
  34. const refreshInput = {
  35. credentialStore: input.credentialStore,
  36. ...(input.fetchFn ? { fetchFn: input.fetchFn } : {}),
  37. keyPrefix: input.keyPrefix,
  38. ...(input.logger ? { logger: input.logger } : {}),
  39. serverName: input.serverName,
  40. serverUrl: input.serverUrl,
  41. ...(input.config.clientId ? { staticClientId: input.config.clientId } : {}),
  42. };
  43. return {
  44. async token(): Promise<string | undefined> {
  45. const pair = await loadCredentialPair(input.credentialStore, input.keyPrefix);
  46. // 没有 token 时返回 undefined:请求照发、拿到 401,再由 onUnauthorized 统一分类。
  47. if (!pair?.tokens) return undefined;
  48. if (!isCanonicalTokenNearExpiry(pair)) return pair.tokens.access_token;
  49. // 临期主动刷新。没有 refresh token 就直接用现值撑到 401,不虚构刷新。
  50. if (!pair.tokens.refresh_token) return pair.tokens.access_token;
  51. return await refreshMcpOAuthTokensUnderLock({ ...refreshInput, reactive: false });
  52. },
  53. async onUnauthorized(): Promise<void> {
  54. const pair = await loadCredentialPair(input.credentialStore, input.keyPrefix);
  55. if (!pair?.tokens?.refresh_token) {
  56. throw createInteractiveAuthorizationRequiredError({
  57. reason: pair?.tokens ? "no_refresh_token" : "no_credentials",
  58. serverName: input.serverName,
  59. });
  60. }
  61. // 契约是「让下一次 token() 返回可用 token」,返回值本身被 SDK 忽略;刷新结果已发布到
  62. // canonical,下一次 token() 会重新读取。
  63. await refreshMcpOAuthTokensUnderLock({ ...refreshInput, reactive: true });
  64. },
  65. };
  66. }