@herbertgao/pi-extensions 2026.9.11 → 2026.9.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (192) hide show
  1. package/README.md +4 -4
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
  4. package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +8 -0
  5. package/node_modules/@herbertgao/pi-subagents/package.json +1 -1
  6. package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +5 -4
  7. package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +39 -16
  8. package/node_modules/@juicesharp/rpiv-ask-user-question/package.json +2 -2
  9. package/node_modules/@narumitw/pi-btw/README.md +21 -4
  10. package/node_modules/@narumitw/pi-btw/dist/index.ts +1668 -958
  11. package/node_modules/@narumitw/pi-btw/dist/index.ts.map +4 -4
  12. package/node_modules/@narumitw/pi-btw/docs/workflows.md +10 -2
  13. package/node_modules/@narumitw/pi-btw/package.json +1 -1
  14. package/node_modules/@narumitw/pi-btw/src/btw.ts +17 -79
  15. package/node_modules/@narumitw/pi-btw/src/conversation-context.ts +74 -0
  16. package/node_modules/@narumitw/pi-btw/src/fullscreen-ui.ts +196 -7
  17. package/node_modules/@narumitw/pi-btw/src/main-thread-updates.ts +40 -0
  18. package/node_modules/@narumitw/pi-btw/src/menu.ts +34 -2
  19. package/node_modules/@narumitw/pi-btw/src/settings.ts +49 -0
  20. package/node_modules/@narumitw/pi-btw/src/transcript-pager.ts +9 -1
  21. package/node_modules/@narumitw/pi-btw/src/workspace-layout.ts +559 -0
  22. package/node_modules/pi-mcp-adapter/CHANGELOG.md +62 -0
  23. package/node_modules/pi-mcp-adapter/README.md +75 -7
  24. package/node_modules/pi-mcp-adapter/bearer-command-resolver.ts +193 -0
  25. package/node_modules/pi-mcp-adapter/cli.js +56 -5
  26. package/node_modules/pi-mcp-adapter/commands.ts +96 -5
  27. package/node_modules/pi-mcp-adapter/config.ts +73 -6
  28. package/node_modules/pi-mcp-adapter/direct-tool-surface.ts +22 -28
  29. package/node_modules/pi-mcp-adapter/direct-tools.ts +13 -5
  30. package/node_modules/pi-mcp-adapter/dist/abort.d.ts +2 -0
  31. package/node_modules/pi-mcp-adapter/dist/abort.js +36 -0
  32. package/node_modules/pi-mcp-adapter/dist/abort.js.map +1 -0
  33. package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.d.ts +6 -0
  34. package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.js +194 -0
  35. package/node_modules/pi-mcp-adapter/dist/bearer-command-resolver.js.map +1 -0
  36. package/node_modules/pi-mcp-adapter/dist/config.d.ts +5 -0
  37. package/node_modules/pi-mcp-adapter/dist/config.js +75 -6
  38. package/node_modules/pi-mcp-adapter/dist/config.js.map +1 -1
  39. package/node_modules/pi-mcp-adapter/dist/consent-manager.d.ts +18 -0
  40. package/node_modules/pi-mcp-adapter/dist/consent-manager.js +88 -0
  41. package/node_modules/pi-mcp-adapter/dist/consent-manager.js.map +1 -0
  42. package/node_modules/pi-mcp-adapter/dist/elicitation-handler.d.ts +17 -0
  43. package/node_modules/pi-mcp-adapter/dist/elicitation-handler.js +316 -0
  44. package/node_modules/pi-mcp-adapter/dist/elicitation-handler.js.map +1 -0
  45. package/node_modules/pi-mcp-adapter/dist/errors.d.ts +131 -0
  46. package/node_modules/pi-mcp-adapter/dist/errors.js +278 -0
  47. package/node_modules/pi-mcp-adapter/dist/errors.js.map +1 -0
  48. package/node_modules/pi-mcp-adapter/dist/http-ca.d.ts +8 -0
  49. package/node_modules/pi-mcp-adapter/dist/http-ca.js +88 -0
  50. package/node_modules/pi-mcp-adapter/dist/http-ca.js.map +1 -0
  51. package/node_modules/pi-mcp-adapter/dist/jev-client.d.ts +15 -0
  52. package/node_modules/pi-mcp-adapter/dist/jev-client.js +340 -0
  53. package/node_modules/pi-mcp-adapter/dist/jev-client.js.map +1 -0
  54. package/node_modules/pi-mcp-adapter/dist/jev-contracts.d.ts +77 -0
  55. package/node_modules/pi-mcp-adapter/dist/jev-contracts.js +2 -0
  56. package/node_modules/pi-mcp-adapter/dist/jev-contracts.js.map +1 -0
  57. package/node_modules/pi-mcp-adapter/dist/jev-key-store.d.ts +22 -0
  58. package/node_modules/pi-mcp-adapter/dist/jev-key-store.js +85 -0
  59. package/node_modules/pi-mcp-adapter/dist/jev-key-store.js.map +1 -0
  60. package/node_modules/pi-mcp-adapter/dist/json-schema-validator.d.ts +2 -0
  61. package/node_modules/pi-mcp-adapter/dist/json-schema-validator.js +55 -0
  62. package/node_modules/pi-mcp-adapter/dist/json-schema-validator.js.map +1 -0
  63. package/node_modules/pi-mcp-adapter/dist/lifecycle.d.ts +56 -0
  64. package/node_modules/pi-mcp-adapter/dist/lifecycle.js +410 -0
  65. package/node_modules/pi-mcp-adapter/dist/lifecycle.js.map +1 -0
  66. package/node_modules/pi-mcp-adapter/dist/logger.d.ts +51 -0
  67. package/node_modules/pi-mcp-adapter/dist/logger.js +131 -0
  68. package/node_modules/pi-mcp-adapter/dist/logger.js.map +1 -0
  69. package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.d.ts +26 -0
  70. package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.js +103 -0
  71. package/node_modules/pi-mcp-adapter/dist/mcp-auth-fetch.js.map +1 -0
  72. package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.d.ts +118 -0
  73. package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.js +1098 -0
  74. package/node_modules/pi-mcp-adapter/dist/mcp-auth-flow.js.map +1 -0
  75. package/node_modules/pi-mcp-adapter/dist/mcp-auth.d.ts +168 -0
  76. package/node_modules/pi-mcp-adapter/dist/mcp-auth.js +1117 -0
  77. package/node_modules/pi-mcp-adapter/dist/mcp-auth.js.map +1 -0
  78. package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.js +7 -140
  79. package/node_modules/pi-mcp-adapter/dist/mcp-bearer-store.js.map +1 -1
  80. package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.d.ts +53 -0
  81. package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.js +441 -0
  82. package/node_modules/pi-mcp-adapter/dist/mcp-callback-server.js.map +1 -0
  83. package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.d.ts +148 -0
  84. package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.js +689 -0
  85. package/node_modules/pi-mcp-adapter/dist/mcp-oauth-provider.js.map +1 -0
  86. package/node_modules/pi-mcp-adapter/dist/mcp-probe.d.ts +6 -0
  87. package/node_modules/pi-mcp-adapter/dist/mcp-probe.js +166 -0
  88. package/node_modules/pi-mcp-adapter/dist/mcp-probe.js.map +1 -0
  89. package/node_modules/pi-mcp-adapter/dist/mcp-tasks.d.ts +102 -0
  90. package/node_modules/pi-mcp-adapter/dist/mcp-tasks.js +369 -0
  91. package/node_modules/pi-mcp-adapter/dist/mcp-tasks.js.map +1 -0
  92. package/node_modules/pi-mcp-adapter/dist/mcp-trace.d.ts +95 -0
  93. package/node_modules/pi-mcp-adapter/dist/mcp-trace.js +242 -0
  94. package/node_modules/pi-mcp-adapter/dist/mcp-trace.js.map +1 -0
  95. package/node_modules/pi-mcp-adapter/dist/metadata-cache.js +2 -11
  96. package/node_modules/pi-mcp-adapter/dist/metadata-cache.js.map +1 -1
  97. package/node_modules/pi-mcp-adapter/dist/npx-resolver.d.ts +6 -0
  98. package/node_modules/pi-mcp-adapter/dist/npx-resolver.js +505 -0
  99. package/node_modules/pi-mcp-adapter/dist/npx-resolver.js.map +1 -0
  100. package/node_modules/pi-mcp-adapter/dist/request-headers-command.d.ts +10 -0
  101. package/node_modules/pi-mcp-adapter/dist/request-headers-command.js +312 -0
  102. package/node_modules/pi-mcp-adapter/dist/request-headers-command.js.map +1 -0
  103. package/node_modules/pi-mcp-adapter/dist/runtime-owner.d.ts +13 -0
  104. package/node_modules/pi-mcp-adapter/dist/runtime-owner.js +97 -0
  105. package/node_modules/pi-mcp-adapter/dist/runtime-owner.js.map +1 -0
  106. package/node_modules/pi-mcp-adapter/dist/sampling-handler.d.ts +17 -0
  107. package/node_modules/pi-mcp-adapter/dist/sampling-handler.js +203 -0
  108. package/node_modules/pi-mcp-adapter/dist/sampling-handler.js.map +1 -0
  109. package/node_modules/pi-mcp-adapter/dist/secure-keyring.d.ts +11 -0
  110. package/node_modules/pi-mcp-adapter/dist/secure-keyring.js +172 -0
  111. package/node_modules/pi-mcp-adapter/dist/secure-keyring.js.map +1 -0
  112. package/node_modules/pi-mcp-adapter/dist/server-manager.d.ts +157 -0
  113. package/node_modules/pi-mcp-adapter/dist/server-manager.js +1743 -0
  114. package/node_modules/pi-mcp-adapter/dist/server-manager.js.map +1 -0
  115. package/node_modules/pi-mcp-adapter/dist/session-approvals.d.ts +34 -0
  116. package/node_modules/pi-mcp-adapter/dist/session-approvals.js +140 -0
  117. package/node_modules/pi-mcp-adapter/dist/session-approvals.js.map +1 -0
  118. package/node_modules/pi-mcp-adapter/dist/session-recovery.d.ts +26 -0
  119. package/node_modules/pi-mcp-adapter/dist/session-recovery.js +142 -0
  120. package/node_modules/pi-mcp-adapter/dist/session-recovery.js.map +1 -0
  121. package/node_modules/pi-mcp-adapter/dist/state.d.ts +73 -0
  122. package/node_modules/pi-mcp-adapter/dist/state.js +2 -0
  123. package/node_modules/pi-mcp-adapter/dist/state.js.map +1 -0
  124. package/node_modules/pi-mcp-adapter/dist/types.d.ts +36 -0
  125. package/node_modules/pi-mcp-adapter/dist/types.js +18 -0
  126. package/node_modules/pi-mcp-adapter/dist/types.js.map +1 -1
  127. package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.d.ts +17 -0
  128. package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.js +219 -0
  129. package/node_modules/pi-mcp-adapter/dist/ui-resource-handler.js.map +1 -0
  130. package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.d.ts +15 -0
  131. package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.js +85 -0
  132. package/node_modules/pi-mcp-adapter/dist/unix-socket-transport.js.map +1 -0
  133. package/node_modules/pi-mcp-adapter/dist/utils.d.ts +1 -0
  134. package/node_modules/pi-mcp-adapter/dist/utils.js +13 -0
  135. package/node_modules/pi-mcp-adapter/dist/utils.js.map +1 -1
  136. package/node_modules/pi-mcp-adapter/elicitation-handler.ts +29 -19
  137. package/node_modules/pi-mcp-adapter/examples/jev-accessibility-loop.mjs +85 -0
  138. package/node_modules/pi-mcp-adapter/examples/jev-semantic-filter.mjs +34 -0
  139. package/node_modules/pi-mcp-adapter/index.ts +129 -6
  140. package/node_modules/pi-mcp-adapter/init.ts +6 -19
  141. package/node_modules/pi-mcp-adapter/jev-client.ts +273 -0
  142. package/node_modules/pi-mcp-adapter/jev-contracts.ts +53 -0
  143. package/node_modules/pi-mcp-adapter/jev-key-store.ts +79 -0
  144. package/node_modules/pi-mcp-adapter/lifecycle.ts +14 -3
  145. package/node_modules/pi-mcp-adapter/mcp-bearer-store.ts +7 -142
  146. package/node_modules/pi-mcp-adapter/mcp-code.ts +119 -11
  147. package/node_modules/pi-mcp-adapter/mcp-output-guard.ts +4 -0
  148. package/node_modules/pi-mcp-adapter/mcp-references.ts +5 -3
  149. package/node_modules/pi-mcp-adapter/mcp-script-worker.mjs +5 -0
  150. package/node_modules/pi-mcp-adapter/mcp-tasks.ts +467 -0
  151. package/node_modules/pi-mcp-adapter/metadata-cache.ts +2 -13
  152. package/node_modules/pi-mcp-adapter/namespace-tools.ts +1 -1
  153. package/node_modules/pi-mcp-adapter/package.json +17 -9
  154. package/node_modules/pi-mcp-adapter/proxy-modes.ts +319 -166
  155. package/node_modules/pi-mcp-adapter/request-headers-command.ts +6 -3
  156. package/node_modules/pi-mcp-adapter/search-ranking.ts +38 -7
  157. package/node_modules/pi-mcp-adapter/secure-keyring.ts +170 -0
  158. package/node_modules/pi-mcp-adapter/semantic-search.ts +186 -0
  159. package/node_modules/pi-mcp-adapter/server-manager.ts +293 -50
  160. package/node_modules/pi-mcp-adapter/session-approvals.ts +14 -0
  161. package/node_modules/pi-mcp-adapter/skills/mcp-scripting/SKILL.md +2 -0
  162. package/node_modules/pi-mcp-adapter/state.ts +3 -1
  163. package/node_modules/pi-mcp-adapter/tool-approval.ts +26 -4
  164. package/node_modules/pi-mcp-adapter/tool-metadata.ts +6 -14
  165. package/node_modules/pi-mcp-adapter/tool-registrar.ts +8 -6
  166. package/node_modules/pi-mcp-adapter/tool-result-renderer.ts +4 -1
  167. package/node_modules/pi-mcp-adapter/types.ts +53 -0
  168. package/node_modules/pi-mcp-adapter/ui-server.ts +17 -9
  169. package/node_modules/pi-mcp-adapter/utils.ts +16 -0
  170. package/node_modules/pi-multi-account/CHANGELOG.md +23 -0
  171. package/node_modules/pi-multi-account/README.md +38 -11
  172. package/node_modules/pi-multi-account/index.ts +371 -96
  173. package/node_modules/pi-multi-account/package.json +5 -4
  174. package/node_modules/pi-multi-account/provider-payload-stream.ts +36 -28
  175. package/node_modules/pi-multi-account/usage.ts +31 -2
  176. package/node_modules/pi-typesafe/README.md +3 -1
  177. package/node_modules/pi-typesafe/dist/auth.d.ts +10 -3
  178. package/node_modules/pi-typesafe/dist/auth.js +13 -7
  179. package/node_modules/pi-typesafe/dist/backends.d.ts +31 -0
  180. package/node_modules/pi-typesafe/dist/backends.js +33 -0
  181. package/node_modules/pi-typesafe/dist/client.d.ts +3 -9
  182. package/node_modules/pi-typesafe/dist/client.js +63 -39
  183. package/node_modules/pi-typesafe/dist/credentials.d.ts +11 -5
  184. package/node_modules/pi-typesafe/dist/credentials.js +15 -8
  185. package/node_modules/pi-typesafe/dist/extension.js +4 -1
  186. package/node_modules/pi-typesafe/dist/index.d.ts +1 -1
  187. package/node_modules/pi-typesafe/dist/index.js +1 -1
  188. package/node_modules/pi-typesafe/dist/login.d.ts +13 -7
  189. package/node_modules/pi-typesafe/dist/login.js +17 -8
  190. package/node_modules/pi-typesafe/dist/schema.js +19 -13
  191. package/node_modules/pi-typesafe/package.json +1 -1
  192. package/package.json +11 -10
@@ -0,0 +1,1098 @@
1
+ /**
2
+ * MCP Auth Flow
3
+ *
4
+ * High-level OAuth flow management using the MCP SDK's built-in auth functions.
5
+ */
6
+ import { auth as runSdkAuth, extractWWWAuthenticateParams, LATEST_PROTOCOL_VERSION, UnauthorizedError, validateClientMetadataUrl, } from "@modelcontextprotocol/client";
7
+ import open from "open";
8
+ import { getOAuthCallbackPort, McpOAuthProvider, } from "./mcp-oauth-provider.js";
9
+ import { ensureCallbackServer, waitForCallback, cancelPendingCallback, stopCallbackServer, stopCallbackServerIfIdle, releaseCallbackServer, } from "./mcp-callback-server.js";
10
+ import { getAuthForUrl, getAuthEntry, clearAllCredentials, clearClientInfo, clearCodeVerifier, getOAuthState, clearOAuthState, getAuthBaseDir, beginOAuthRevocation, captureOAuthAuthority, OAuthCredentialStoreError, } from "./mcp-auth.js";
11
+ import { isServerDisabled } from "./types.js";
12
+ import { formatTerminalError, interpolateEnvVars } from "./utils.js";
13
+ import { createOAuthFetch, oauthHeaderResolver, resolveOAuthHeaders } from "./mcp-auth-fetch.js";
14
+ import { isBuiltInAgentPlugin } from "./agent-plugin-provenance.js";
15
+ import { abortable, throwIfAborted } from "./abort.js";
16
+ import { combineAbortSignals, isAbortError } from "./runtime-owner.js";
17
+ function pluginAwareOAuthHeaders(definition) {
18
+ return oauthHeaderResolver(definition?.headers, {
19
+ literal: definition ? isBuiltInAgentPlugin(definition, "headers") : false,
20
+ });
21
+ }
22
+ function applyOAuthConfig(discovery, config) {
23
+ return {
24
+ ...discovery,
25
+ ...(config.scope !== undefined ? { scope: config.scope } : {}),
26
+ ...(config.skipIssuerMetadataValidation === true ? { skipIssuerMetadataValidation: true } : {}),
27
+ };
28
+ }
29
+ const runtimeStates = new WeakMap();
30
+ const activeRuntimes = new Set();
31
+ export function createOAuthRuntime(signal) {
32
+ const controller = new AbortController();
33
+ const runtime = { signal: combineAbortSignals(signal, controller.signal) };
34
+ runtimeStates.set(runtime, {
35
+ controller,
36
+ generation: 0,
37
+ pendingAuths: new Map(),
38
+ pendingAuthStates: new Map(),
39
+ pendingAuthCleanupTimers: new Map(),
40
+ pendingAuthentications: new Map(),
41
+ });
42
+ activeRuntimes.add(runtime);
43
+ return runtime;
44
+ }
45
+ let legacyRuntime = createOAuthRuntime();
46
+ activeRuntimes.delete(legacyRuntime);
47
+ function getRuntime(options) {
48
+ if (options?.runtime) {
49
+ options.runtime.signal.throwIfAborted();
50
+ activeRuntimes.add(options.runtime);
51
+ return options.runtime;
52
+ }
53
+ if (legacyRuntime.signal.aborted)
54
+ legacyRuntime = createOAuthRuntime();
55
+ activeRuntimes.add(legacyRuntime);
56
+ return legacyRuntime;
57
+ }
58
+ function getRuntimeState(runtime) {
59
+ const state = runtimeStates.get(runtime);
60
+ if (!state)
61
+ throw new Error("Unknown OAuth runtime");
62
+ return state;
63
+ }
64
+ function getAuthStorageIdentity(options) {
65
+ return options.credentialStore === "encrypted-file"
66
+ ? ["encrypted-file"]
67
+ : ["os", getAuthBaseDir(options)];
68
+ }
69
+ function getPendingAuthKey(serverName, options) {
70
+ return JSON.stringify([serverName, ...getAuthStorageIdentity(options)]);
71
+ }
72
+ function hasOAuthAuthority(authority) {
73
+ try {
74
+ authority();
75
+ return true;
76
+ }
77
+ catch {
78
+ return false;
79
+ }
80
+ }
81
+ export function hasPendingAuth(serverName, options, runtime) {
82
+ const state = getRuntimeState(runtime ?? legacyRuntime);
83
+ if (options) {
84
+ return state.pendingAuths.has(getPendingAuthKey(serverName, options));
85
+ }
86
+ return Array.from(state.pendingAuths.values()).some(pendingAuth => pendingAuth.serverName === serverName);
87
+ }
88
+ /** Timeout for manual auth completion (5 minutes) */
89
+ const MANUAL_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
90
+ /**
91
+ * Generate a cryptographically secure random state parameter.
92
+ */
93
+ function generateState() {
94
+ return Array.from(crypto.getRandomValues(new Uint8Array(32)))
95
+ .map((b) => b.toString(16).padStart(2, "0"))
96
+ .join("");
97
+ }
98
+ /**
99
+ * Extract OAuth configuration from a ServerEntry.
100
+ */
101
+ export function extractOAuthConfig(definition) {
102
+ if (definition.oauth === false) {
103
+ return {};
104
+ }
105
+ const config = {};
106
+ if (definition.oauth?.grantType !== undefined)
107
+ config.grantType = definition.oauth.grantType;
108
+ if (definition.oauth?.clientId !== undefined) {
109
+ if (typeof definition.oauth.clientId !== "string")
110
+ throw new Error("OAuth clientId must be a string");
111
+ config.clientId = interpolateEnvVars(definition.oauth.clientId);
112
+ }
113
+ if (definition.oauth?.clientSecret !== undefined) {
114
+ if (typeof definition.oauth.clientSecret !== "string")
115
+ throw new Error("OAuth clientSecret must be a string");
116
+ // Preserve command expressions for the provider; interpolation remains eager for ordinary values.
117
+ config.clientSecret = definition.oauth.clientSecret.startsWith("!")
118
+ ? definition.oauth.clientSecret
119
+ : interpolateEnvVars(definition.oauth.clientSecret);
120
+ }
121
+ if (definition.oauth?.clientMetadataUrl !== undefined) {
122
+ if (typeof definition.oauth.clientMetadataUrl !== "string") {
123
+ throw new Error("OAuth clientMetadataUrl must be a string");
124
+ }
125
+ const clientMetadataUrl = interpolateEnvVars(definition.oauth.clientMetadataUrl).trim();
126
+ if (!clientMetadataUrl) {
127
+ throw new Error("OAuth clientMetadataUrl must not be empty");
128
+ }
129
+ validateClientMetadataUrl(clientMetadataUrl);
130
+ config.clientMetadataUrl = clientMetadataUrl;
131
+ }
132
+ if (config.clientMetadataUrl !== undefined && config.clientSecret !== undefined && !config.clientId) {
133
+ throw new Error("OAuth clientSecret requires an explicit clientId when clientMetadataUrl is configured");
134
+ }
135
+ if (definition.oauth?.scope !== undefined) {
136
+ if (typeof definition.oauth.scope !== "string")
137
+ throw new Error("OAuth scope must be a string");
138
+ config.scope = interpolateEnvVars(definition.oauth.scope);
139
+ }
140
+ if (definition.oauth?.authorizationParams !== undefined) {
141
+ const params = definition.oauth.authorizationParams;
142
+ if (!params || typeof params !== "object" || Array.isArray(params)) {
143
+ throw new Error("OAuth authorizationParams must be an object");
144
+ }
145
+ config.authorizationParams = {};
146
+ for (const [key, value] of Object.entries(params)) {
147
+ if (!key)
148
+ throw new Error("OAuth authorizationParams keys must not be empty");
149
+ if (typeof value !== "string")
150
+ throw new Error(`OAuth authorizationParams.${key} must be a string`);
151
+ config.authorizationParams[key] = interpolateEnvVars(value);
152
+ }
153
+ }
154
+ if (definition.oauth?.redirectUri !== undefined) {
155
+ if (typeof definition.oauth.redirectUri !== "string") {
156
+ throw new Error("OAuth redirectUri must be a string");
157
+ }
158
+ const redirectUri = interpolateEnvVars(definition.oauth.redirectUri).trim();
159
+ if (!redirectUri) {
160
+ throw new Error("OAuth redirectUri must not be empty");
161
+ }
162
+ config.redirectUri = redirectUri;
163
+ }
164
+ if (definition.oauth?.clientName !== undefined) {
165
+ if (typeof definition.oauth.clientName !== "string") {
166
+ throw new Error("OAuth clientName must be a string");
167
+ }
168
+ const clientName = interpolateEnvVars(definition.oauth.clientName).trim();
169
+ if (!clientName) {
170
+ throw new Error("OAuth clientName must not be empty");
171
+ }
172
+ config.clientName = clientName;
173
+ }
174
+ if (definition.oauth?.clientUri !== undefined) {
175
+ if (typeof definition.oauth.clientUri !== "string") {
176
+ throw new Error("OAuth clientUri must be a string");
177
+ }
178
+ const clientUri = interpolateEnvVars(definition.oauth.clientUri).trim();
179
+ if (!clientUri) {
180
+ throw new Error("OAuth clientUri must not be empty");
181
+ }
182
+ config.clientUri = clientUri;
183
+ }
184
+ if (definition.oauth?.logoUri !== undefined) {
185
+ if (typeof definition.oauth.logoUri !== "string") {
186
+ throw new Error("OAuth logoUri must be a string");
187
+ }
188
+ const logoUri = interpolateEnvVars(definition.oauth.logoUri).trim();
189
+ if (!logoUri) {
190
+ throw new Error("OAuth logoUri must not be empty");
191
+ }
192
+ // Consent screens fetch this server-side, so a local path silently renders
193
+ // nothing. Fail here instead, where the message can say why.
194
+ let parsed;
195
+ try {
196
+ parsed = new URL(logoUri);
197
+ }
198
+ catch {
199
+ throw new Error("OAuth logoUri must be an absolute http(s) URL");
200
+ }
201
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
202
+ throw new Error("OAuth logoUri must be an absolute http(s) URL");
203
+ }
204
+ config.logoUri = logoUri;
205
+ }
206
+ if (definition.oauth?.authServerMetadataUrl !== undefined) {
207
+ if (typeof definition.oauth.authServerMetadataUrl !== "string") {
208
+ throw new Error("OAuth authServerMetadataUrl must be a string");
209
+ }
210
+ const authServerMetadataUrl = interpolateEnvVars(definition.oauth.authServerMetadataUrl).trim();
211
+ if (!authServerMetadataUrl) {
212
+ throw new Error("OAuth authServerMetadataUrl must not be empty");
213
+ }
214
+ let parsed;
215
+ try {
216
+ parsed = new URL(authServerMetadataUrl);
217
+ }
218
+ catch {
219
+ throw new Error("OAuth authServerMetadataUrl must be an absolute https:// URL");
220
+ }
221
+ if (parsed.protocol !== "https:") {
222
+ throw new Error("OAuth authServerMetadataUrl must be an absolute https:// URL");
223
+ }
224
+ config.authServerMetadataUrl = authServerMetadataUrl;
225
+ }
226
+ if (definition.oauth?.skipIssuerMetadataValidation !== undefined) {
227
+ if (typeof definition.oauth.skipIssuerMetadataValidation !== "boolean") {
228
+ throw new Error("OAuth skipIssuerMetadataValidation must be a boolean");
229
+ }
230
+ config.skipIssuerMetadataValidation = definition.oauth.skipIssuerMetadataValidation;
231
+ }
232
+ return config;
233
+ }
234
+ async function probeAuthDiscovery(serverUrl, definition, signal) {
235
+ // The preliminary probe is command-free; real SDK discovery resolves commands.
236
+ const serviceHeaders = resolveOAuthHeaders(definition?.headers, {
237
+ commands: false,
238
+ literal: definition ? isBuiltInAgentPlugin(definition, "headers") : false,
239
+ });
240
+ const probeFetch = createOAuthFetch(serverUrl, () => serviceHeaders, signal, { timeout: false });
241
+ const headers = new Headers({ "content-type": "application/json" });
242
+ const controller = new AbortController();
243
+ const discoverySignal = combineAbortSignals(signal, controller.signal);
244
+ const timer = setTimeout(() => controller.abort(), 5000);
245
+ try {
246
+ headers.set("accept", "application/json, text/event-stream");
247
+ const response = await probeFetch(new URL(serverUrl), {
248
+ method: "POST",
249
+ headers,
250
+ body: JSON.stringify({
251
+ jsonrpc: "2.0",
252
+ id: 0,
253
+ method: "initialize",
254
+ params: {
255
+ protocolVersion: LATEST_PROTOCOL_VERSION,
256
+ capabilities: {},
257
+ clientInfo: { name: "pi-mcp-adapter", version: "2.11.0" },
258
+ },
259
+ }),
260
+ ...(discoverySignal ? { signal: discoverySignal } : {}),
261
+ });
262
+ const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
263
+ await response.body?.cancel().catch(() => { });
264
+ return { ...(resourceMetadataUrl ? { resourceMetadataUrl } : {}), ...(scope ? { scope } : {}) };
265
+ }
266
+ catch (error) {
267
+ if (signal?.aborted)
268
+ throwIfAborted(signal);
269
+ return {};
270
+ }
271
+ finally {
272
+ clearTimeout(timer);
273
+ }
274
+ }
275
+ function parseOAuthRedirectUri(redirectUri) {
276
+ const dynamicPortPlaceholder = "{port}";
277
+ const placeholderCount = redirectUri.split(dynamicPortPlaceholder).length - 1;
278
+ if (placeholderCount > 1) {
279
+ throw new Error("OAuth redirectUri may contain at most one {port} placeholder");
280
+ }
281
+ let parsedRedirectUri = redirectUri;
282
+ const dynamicPort = placeholderCount === 1;
283
+ if (dynamicPort) {
284
+ const authorityStart = redirectUri.indexOf("://") + 3;
285
+ const pathStart = redirectUri.slice(authorityStart).search(/[/?#]/);
286
+ const authorityEnd = pathStart === -1 ? redirectUri.length : authorityStart + pathStart;
287
+ const authority = redirectUri.slice(authorityStart, authorityEnd);
288
+ if (authorityStart < 3 || !authority.endsWith(`:${dynamicPortPlaceholder}`)) {
289
+ throw new Error("OAuth redirectUri {port} placeholder must be the loopback URI port");
290
+ }
291
+ // Parse with a real port, then replace the placeholder only after the OS
292
+ // assigns the callback listener's port.
293
+ parsedRedirectUri = redirectUri.replace(dynamicPortPlaceholder, "1");
294
+ }
295
+ let url;
296
+ try {
297
+ url = new URL(parsedRedirectUri);
298
+ }
299
+ catch (error) {
300
+ throw new Error(`Invalid OAuth redirectUri: ${redirectUri}`, { cause: error });
301
+ }
302
+ if (url.username || url.password) {
303
+ throw new Error("OAuth redirectUri must not include username or password");
304
+ }
305
+ if (url.hash) {
306
+ throw new Error("OAuth redirectUri must not include a fragment");
307
+ }
308
+ const hostname = url.hostname.toLowerCase();
309
+ const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
310
+ if (dynamicPort && (url.protocol !== "http:" || !isLocalhost)) {
311
+ throw new Error("OAuth redirectUri {port} placeholder is allowed only for an http:// localhost or loopback URI");
312
+ }
313
+ if (url.port) {
314
+ const parsedPort = Number.parseInt(url.port, 10);
315
+ if (!Number.isInteger(parsedPort) || parsedPort <= 0 || parsedPort > 65535) {
316
+ throw new Error("OAuth redirectUri port must be a positive numeric port");
317
+ }
318
+ }
319
+ if (url.protocol === "https:" && !isLocalhost) {
320
+ return { mode: "manual" };
321
+ }
322
+ if (url.protocol !== "http:" || !isLocalhost) {
323
+ throw new Error("OAuth redirectUri must be an https:// URI or an http:// localhost or loopback URI");
324
+ }
325
+ if (!url.port) {
326
+ throw new Error("OAuth localhost redirectUri must include an explicit numeric port");
327
+ }
328
+ const port = Number.parseInt(url.port, 10);
329
+ const callbackHost = hostname === "[::1]" ? "::1" : hostname;
330
+ return {
331
+ mode: "local",
332
+ ...(dynamicPort ? {} : { port }),
333
+ callbackHost,
334
+ callbackPath: url.pathname,
335
+ dynamicPort,
336
+ resolveRedirectUri: assignedPort => dynamicPort
337
+ ? redirectUri.replace(dynamicPortPlaceholder, String(assignedPort))
338
+ : redirectUri,
339
+ };
340
+ }
341
+ /**
342
+ * Start OAuth authentication flow for a server.
343
+ * Returns the authorization URL when browser authorization is required.
344
+ */
345
+ export async function startAuth(serverName, serverUrl, definition, options = {}, operationAuthority) {
346
+ if (isServerDisabled(definition))
347
+ throw new Error(`MCP server "${serverName}" is disabled`);
348
+ const authority = operationAuthority ?? captureOAuthAuthority(serverName);
349
+ authority();
350
+ const runtime = getRuntime(options);
351
+ const runtimeState = getRuntimeState(runtime);
352
+ const config = definition ? extractOAuthConfig(definition) : {};
353
+ const authStorageOptions = options.authStorageOptions ?? {};
354
+ const signal = combineAbortSignals(runtime.signal, options.signal);
355
+ const generation = runtimeState.generation;
356
+ throwIfAborted(signal);
357
+ if (config.grantType === "client_credentials") {
358
+ const storedAuth = await getAuthForUrl(serverName, serverUrl, authStorageOptions);
359
+ authority();
360
+ if (storedAuth?.clientInfo && !storedAuth.tokens && !config.clientId) {
361
+ clearClientInfo(serverName, authStorageOptions);
362
+ clearCodeVerifier(serverName, authStorageOptions);
363
+ clearOAuthState(serverName, authStorageOptions);
364
+ }
365
+ authority();
366
+ const authProvider = new McpOAuthProvider(serverName, serverUrl, config, {
367
+ onRedirect: async () => {
368
+ throw new Error("Browser redirect is not used for client_credentials flow");
369
+ },
370
+ }, authStorageOptions, runtime.signal, undefined, authority);
371
+ try {
372
+ const fetchFn = createOAuthFetch(serverUrl, pluginAwareOAuthHeaders(definition), signal);
373
+ authProvider.setAuthFetch(fetchFn);
374
+ const discovery = applyOAuthConfig(await probeAuthDiscovery(serverUrl, definition, signal), config);
375
+ authority();
376
+ throwIfAborted(signal);
377
+ const result = await abortable(runSdkAuth(authProvider, { serverUrl, ...discovery, fetchFn }), signal);
378
+ authority();
379
+ throwIfAborted(signal);
380
+ if (result !== "AUTHORIZED") {
381
+ throw new UnauthorizedError("Failed to authorize");
382
+ }
383
+ return { authorizationUrl: "" };
384
+ }
385
+ finally {
386
+ authProvider.deactivate();
387
+ }
388
+ }
389
+ const existingPendingAuth = runtimeState.pendingAuths.get(getPendingAuthKey(serverName, authStorageOptions));
390
+ if (existingPendingAuth?.serverUrl === serverUrl) {
391
+ existingPendingAuth.authority();
392
+ return { authorizationUrl: existingPendingAuth.authorizationUrl };
393
+ }
394
+ const redirectTarget = config.redirectUri !== undefined ? parseOAuthRedirectUri(config.redirectUri) : undefined;
395
+ const manualRedirect = redirectTarget?.mode === "manual";
396
+ const oauthState = generateState();
397
+ if (!manualRedirect) {
398
+ try {
399
+ await ensureCallbackServer({
400
+ strictPort: redirectTarget?.mode === "local"
401
+ ? !redirectTarget.dynamicPort
402
+ : Boolean(config.clientId),
403
+ oauthState,
404
+ reserveState: true,
405
+ ...(redirectTarget?.mode === "local"
406
+ ? {
407
+ ...(redirectTarget.port !== undefined ? { port: redirectTarget.port } : {}),
408
+ callbackHost: redirectTarget.callbackHost,
409
+ callbackPath: redirectTarget.callbackPath,
410
+ }
411
+ : {}),
412
+ });
413
+ authority();
414
+ throwIfAborted(signal);
415
+ if (redirectTarget?.mode === "local" && redirectTarget.dynamicPort) {
416
+ config.redirectUri = redirectTarget.resolveRedirectUri(getOAuthCallbackPort());
417
+ }
418
+ }
419
+ catch (error) {
420
+ releaseCallbackServer(oauthState);
421
+ try {
422
+ await cleanupAndReleaseCallbackServerIfIdle(() => {
423
+ if (hasOAuthAuthority(authority))
424
+ clearOAuthState(serverName, authStorageOptions);
425
+ });
426
+ }
427
+ catch (cleanupError) {
428
+ throw new AggregateError([error, cleanupError], "OAuth startup cleanup failed");
429
+ }
430
+ throw error;
431
+ }
432
+ }
433
+ let capturedUrl;
434
+ authority();
435
+ const authProvider = new McpOAuthProvider(serverName, serverUrl, config, {
436
+ onRedirect: async (url) => {
437
+ capturedUrl = url;
438
+ },
439
+ }, authStorageOptions, runtime.signal, oauthState, authority);
440
+ try {
441
+ const storedAuth = await getAuthForUrl(serverName, serverUrl, authStorageOptions);
442
+ authority();
443
+ if (storedAuth?.clientInfo && !config.clientId) {
444
+ if (!storedAuth.tokens) {
445
+ clearClientInfo(serverName, authStorageOptions);
446
+ clearCodeVerifier(serverName, authStorageOptions);
447
+ clearOAuthState(serverName, authStorageOptions);
448
+ }
449
+ else {
450
+ const redirectUris = storedAuth.clientInfo.redirectUris;
451
+ const redirectUriMatches = Array.isArray(redirectUris)
452
+ && redirectUris.includes(authProvider.redirectUrl ?? "");
453
+ if (!redirectUriMatches && !storedAuth.tokens.refreshToken) {
454
+ // A stale redirect URI only blocks the interactive leg; refresh does
455
+ // not send redirect_uri, so keep refresh-capable credentials intact.
456
+ clearClientInfo(serverName, authStorageOptions);
457
+ clearCodeVerifier(serverName, authStorageOptions);
458
+ clearOAuthState(serverName, authStorageOptions);
459
+ }
460
+ }
461
+ }
462
+ throwIfAborted(signal);
463
+ const getHeaders = pluginAwareOAuthHeaders(definition);
464
+ const fetchFn = createOAuthFetch(serverUrl, getHeaders, signal);
465
+ authProvider.setAuthFetch(fetchFn);
466
+ const discovery = applyOAuthConfig(await probeAuthDiscovery(serverUrl, definition, signal), config);
467
+ authority();
468
+ throwIfAborted(signal);
469
+ const result = await abortable(runSdkAuth(authProvider, { serverUrl, ...discovery, fetchFn }), signal);
470
+ authority();
471
+ throwIfAborted(signal);
472
+ if (result === "AUTHORIZED") {
473
+ authProvider.deactivate();
474
+ releaseCallbackServer(oauthState);
475
+ clearOAuthState(serverName, authStorageOptions);
476
+ await stopCallbackServerIfIdle();
477
+ authority();
478
+ return { authorizationUrl: "" };
479
+ }
480
+ if (!capturedUrl) {
481
+ throw new UnauthorizedError("OAuth authorization URL was not provided");
482
+ }
483
+ await setPendingAuth(runtime, serverName, {
484
+ serverName,
485
+ authProvider,
486
+ serverUrl,
487
+ authorizationUrl: capturedUrl.toString(),
488
+ manualRedirect,
489
+ ...(manualRedirect ? { manualCompletionController: new AbortController() } : {}),
490
+ discovery,
491
+ getHeaders,
492
+ authStorageOptions,
493
+ authority,
494
+ }, oauthState, signal, generation);
495
+ authority();
496
+ return { authorizationUrl: capturedUrl.toString() };
497
+ }
498
+ catch (error) {
499
+ authProvider.deactivate();
500
+ try {
501
+ await clearPendingAuthAndReleaseIfIdle(runtime, serverName, oauthState, authStorageOptions);
502
+ }
503
+ catch (cleanupError) {
504
+ throw new AggregateError([error, cleanupError], "OAuth startup cleanup failed");
505
+ }
506
+ throw error;
507
+ }
508
+ }
509
+ async function setPendingAuth(runtime, serverName, pendingAuth, oauthState, signal, generation = getRuntimeState(runtime).generation) {
510
+ const state = getRuntimeState(runtime);
511
+ const key = getPendingAuthKey(serverName, pendingAuth.authStorageOptions);
512
+ pendingAuth.authority();
513
+ await clearPendingAuth(runtime, serverName, undefined, pendingAuth.authStorageOptions);
514
+ pendingAuth.authority();
515
+ throwIfAborted(signal);
516
+ if (generation !== state.generation)
517
+ throw new Error("OAuth runtime stopped");
518
+ state.pendingAuths.set(key, pendingAuth);
519
+ state.pendingAuthStates.set(key, oauthState);
520
+ const cleanupTimer = setTimeout(() => {
521
+ void clearPendingAuthAndReleaseIfIdle(runtime, serverName, oauthState, pendingAuth.authStorageOptions, new Error("OAuth authorization timeout - authorization took too long")).catch(error => {
522
+ console.error(`MCP Auth: Timed-out flow cleanup failed: ${formatTerminalError(error)}`);
523
+ });
524
+ }, MANUAL_AUTH_TIMEOUT_MS);
525
+ cleanupTimer.unref?.();
526
+ state.pendingAuthCleanupTimers.set(key, cleanupTimer);
527
+ }
528
+ async function clearPendingAuth(runtime, serverName, oauthState, fallbackStorageOptions = {}, reason = new Error("Authorization cancelled")) {
529
+ const state = getRuntimeState(runtime);
530
+ const key = getPendingAuthKey(serverName, fallbackStorageOptions);
531
+ const pendingState = state.pendingAuthStates.get(key);
532
+ if (oauthState && pendingState !== oauthState) {
533
+ cancelPendingCallback(oauthState);
534
+ return;
535
+ }
536
+ const { pendingAuth } = detachPending(state, key, reason);
537
+ const authStorageOptions = pendingAuth?.authStorageOptions ?? fallbackStorageOptions;
538
+ const stateToRelease = pendingState ?? oauthState;
539
+ if (stateToRelease) {
540
+ if (!pendingState)
541
+ cancelPendingCallback(stateToRelease);
542
+ if (pendingAuth && hasOAuthAuthority(pendingAuth.authority)) {
543
+ const storedState = getOAuthState(serverName, authStorageOptions);
544
+ if (storedState === stateToRelease)
545
+ clearOAuthState(serverName, authStorageOptions);
546
+ }
547
+ }
548
+ }
549
+ function detachPending(state, key, reason) {
550
+ const pendingAuth = state.pendingAuths.get(key);
551
+ const oauthState = state.pendingAuthStates.get(key);
552
+ const timer = state.pendingAuthCleanupTimers.get(key);
553
+ if (timer)
554
+ clearTimeout(timer);
555
+ state.pendingAuthCleanupTimers.delete(key);
556
+ state.pendingAuths.delete(key);
557
+ state.pendingAuthStates.delete(key);
558
+ pendingAuth?.manualCompletionController?.abort(reason);
559
+ pendingAuth?.authProvider.deactivate();
560
+ if (oauthState)
561
+ cancelPendingCallback(oauthState);
562
+ return { pendingAuth, oauthState };
563
+ }
564
+ async function clearPendingAuthAndReleaseIfIdle(runtime, serverName, oauthState, fallbackStorageOptions = {}, reason) {
565
+ await cleanupAndReleaseCallbackServerIfIdle(() => clearPendingAuth(runtime, serverName, oauthState, fallbackStorageOptions, reason));
566
+ }
567
+ async function cleanupAndReleaseCallbackServerIfIdle(cleanup) {
568
+ let cleanupFailure;
569
+ try {
570
+ await cleanup();
571
+ }
572
+ catch (error) {
573
+ cleanupFailure = { error };
574
+ }
575
+ try {
576
+ await stopCallbackServerIfIdle();
577
+ }
578
+ catch (releaseError) {
579
+ if (cleanupFailure) {
580
+ throw new AggregateError([cleanupFailure.error, releaseError], "OAuth callback cleanup failed");
581
+ }
582
+ throw releaseError;
583
+ }
584
+ if (cleanupFailure)
585
+ throw cleanupFailure.error;
586
+ }
587
+ function detachPendingAuthsForServer(serverName, reason) {
588
+ for (const runtime of activeRuntimes) {
589
+ const state = getRuntimeState(runtime);
590
+ for (const [key, pendingAuth] of state.pendingAuths) {
591
+ if (pendingAuth.serverName !== serverName)
592
+ continue;
593
+ if (state.pendingAuths.get(key) !== pendingAuth)
594
+ continue;
595
+ detachPending(state, key, reason);
596
+ }
597
+ }
598
+ }
599
+ function getSearchParamsFromInput(input) {
600
+ try {
601
+ const url = new URL(input);
602
+ const params = new URLSearchParams(url.search);
603
+ if (url.hash) {
604
+ const hash = url.hash.startsWith("#") ? url.hash.slice(1) : url.hash;
605
+ const hashParams = new URLSearchParams(hash);
606
+ for (const [key, value] of hashParams) {
607
+ if (!params.has(key))
608
+ params.set(key, value);
609
+ }
610
+ }
611
+ return params;
612
+ }
613
+ catch {
614
+ const query = input.includes("?") ? input.slice(input.indexOf("?") + 1) : input;
615
+ const params = new URLSearchParams(query.startsWith("#") ? query.slice(1) : query);
616
+ return params.has("code") || params.has("state") || params.has("error") ? params : undefined;
617
+ }
618
+ }
619
+ /**
620
+ * Extract an OAuth authorization code (and the RFC 9207 `iss` parameter, when
621
+ * present) from either a raw code, a query string, or the full localhost
622
+ * redirect URL copied from the browser address bar.
623
+ */
624
+ export function parseAuthorizationRedirectInput(input, expectedState) {
625
+ const trimmed = input.trim();
626
+ if (!trimmed) {
627
+ throw new Error("Authorization code or redirect URL is required");
628
+ }
629
+ const params = getSearchParamsFromInput(trimmed);
630
+ if (params) {
631
+ const error = params.get("error");
632
+ if (error) {
633
+ const description = params.get("error_description");
634
+ throw new Error(description ? `${error}: ${description}` : error);
635
+ }
636
+ const state = params.get("state");
637
+ if (expectedState && !state) {
638
+ throw new Error("OAuth state missing from redirect URL");
639
+ }
640
+ if (expectedState && state !== expectedState) {
641
+ throw new Error("OAuth state mismatch - potential CSRF attack");
642
+ }
643
+ const code = params.get("code");
644
+ if (code) {
645
+ const iss = params.get("iss");
646
+ return { code, ...(iss !== null ? { iss } : {}) };
647
+ }
648
+ }
649
+ if (/^[A-Za-z0-9._~+/=-]+$/.test(trimmed)) {
650
+ return { code: trimmed };
651
+ }
652
+ throw new Error("Could not find an OAuth authorization code in the provided input");
653
+ }
654
+ /**
655
+ * Extract an OAuth authorization code from either a raw code, a query string,
656
+ * or the full localhost redirect URL copied from the browser address bar.
657
+ */
658
+ export function parseAuthorizationCodeInput(input, expectedState) {
659
+ return parseAuthorizationRedirectInput(input, expectedState).code;
660
+ }
661
+ function waitForManualCompletionCancellation(signal) {
662
+ return new Promise((_, reject) => {
663
+ const rejectFromSignal = () => {
664
+ reject(signal.reason instanceof Error ? signal.reason : new Error("Authorization cancelled"));
665
+ };
666
+ if (signal.aborted) {
667
+ rejectFromSignal();
668
+ return;
669
+ }
670
+ signal.addEventListener("abort", rejectFromSignal, { once: true });
671
+ });
672
+ }
673
+ /**
674
+ * Wait for either the localhost callback or a manually pasted redirect URL.
675
+ * The manual input prompt is dismissed as soon as either path finishes.
676
+ */
677
+ export async function waitForAuthorizationResponse(callbackPromise, authorizationUrl, expectedState, onAuthorizationInput, signal) {
678
+ if (!onAuthorizationInput) {
679
+ return {
680
+ input: await abortable(callbackPromise, signal),
681
+ source: "callback",
682
+ };
683
+ }
684
+ const inputController = new AbortController();
685
+ try {
686
+ const response = await abortable(Promise.race([
687
+ callbackPromise.then((input) => ({ input, source: "callback" })),
688
+ onAuthorizationInput(authorizationUrl, inputController.signal).then((input) => ({
689
+ input,
690
+ source: "manual",
691
+ })),
692
+ ]), signal);
693
+ if (response.source === "callback")
694
+ return response;
695
+ if (!response.input?.trim())
696
+ throw new Error("OAuth authentication cancelled");
697
+ if (!getSearchParamsFromInput(response.input.trim())) {
698
+ throw new Error("Paste the full OAuth callback URL, including its code and state parameters");
699
+ }
700
+ return {
701
+ input: parseAuthorizationRedirectInput(response.input, expectedState),
702
+ source: "manual",
703
+ };
704
+ }
705
+ finally {
706
+ inputController.abort();
707
+ }
708
+ }
709
+ /**
710
+ * Complete OAuth authentication from manual user input.
711
+ */
712
+ export async function completeAuthFromInput(serverName, input, options = {}) {
713
+ const runtime = getRuntime(options);
714
+ const runtimeState = getRuntimeState(runtime);
715
+ const fallbackAuthStorageOptions = options.authStorageOptions ?? {};
716
+ const signal = combineAbortSignals(runtime.signal, options.signal);
717
+ throwIfAborted(signal);
718
+ const key = getPendingAuthKey(serverName, fallbackAuthStorageOptions);
719
+ const oauthState = runtimeState.pendingAuthStates.get(key);
720
+ const pendingAuth = runtimeState.pendingAuths.get(key);
721
+ throwIfAborted(signal);
722
+ if (pendingAuth?.manualRedirect && !getSearchParamsFromInput(input.trim())) {
723
+ throw new Error("Paste the full OAuth callback URL, including its code and state parameters");
724
+ }
725
+ const parsed = parseAuthorizationRedirectInput(input, oauthState);
726
+ return completeAuth(serverName, parsed, options);
727
+ }
728
+ /**
729
+ * Complete OAuth authentication with the authorization code.
730
+ */
731
+ export async function completeAuth(serverName, authorizationCode, options = {}) {
732
+ const runtime = getRuntime(options);
733
+ const runtimeState = getRuntimeState(runtime);
734
+ const { code, iss } = typeof authorizationCode === "string"
735
+ ? { code: authorizationCode, iss: undefined }
736
+ : authorizationCode;
737
+ const fallbackAuthStorageOptions = options.authStorageOptions ?? {};
738
+ const signal = combineAbortSignals(runtime.signal, options.signal);
739
+ throwIfAborted(signal);
740
+ const key = getPendingAuthKey(serverName, fallbackAuthStorageOptions);
741
+ const pendingAuth = runtimeState.pendingAuths.get(key);
742
+ const authStorageOptions = pendingAuth?.authStorageOptions ?? fallbackAuthStorageOptions;
743
+ if (!pendingAuth) {
744
+ throw new Error(`No pending OAuth flow for server: ${serverName}`);
745
+ }
746
+ pendingAuth.authority();
747
+ const oauthState = runtimeState.pendingAuthStates.get(key);
748
+ throwIfAborted(signal);
749
+ let keepPendingForRetry = false;
750
+ let caughtError;
751
+ try {
752
+ const fetchFn = createOAuthFetch(pendingAuth.serverUrl, pendingAuth.getHeaders, signal);
753
+ pendingAuth.authProvider.setAuthFetch(fetchFn);
754
+ const discoveryState = await pendingAuth.authProvider.discoveryState();
755
+ pendingAuth.authority();
756
+ const metadata = discoveryState?.authorizationServerMetadata;
757
+ const expectedIssuer = metadata?.issuer ?? discoveryState?.authorizationServerUrl;
758
+ const requiresIssuer = metadata
759
+ ?.authorization_response_iss_parameter_supported === true;
760
+ if (expectedIssuer !== undefined && iss === undefined && requiresIssuer) {
761
+ keepPendingForRetry = true;
762
+ throw new Error(`The authorization server for ${serverName} requires the RFC 9207 "iss" parameter. ` +
763
+ "Paste the full redirect URL from the browser address bar (not just the authorization code).");
764
+ }
765
+ if (expectedIssuer !== undefined && iss !== undefined && iss !== expectedIssuer) {
766
+ throw new Error(`The OAuth authorization response issuer does not match the discovered issuer for ${serverName}.`);
767
+ }
768
+ const result = await abortable(runSdkAuth(pendingAuth.authProvider, {
769
+ serverUrl: pendingAuth.serverUrl,
770
+ authorizationCode: code,
771
+ ...(iss !== undefined ? { iss } : {}),
772
+ ...pendingAuth.discovery,
773
+ fetchFn,
774
+ }), signal);
775
+ pendingAuth.authority();
776
+ throwIfAborted(signal);
777
+ if (result !== "AUTHORIZED") {
778
+ throw new UnauthorizedError("Failed to authorize");
779
+ }
780
+ return "authenticated";
781
+ }
782
+ catch (error) {
783
+ caughtError = error;
784
+ throw error;
785
+ }
786
+ finally {
787
+ if (!keepPendingForRetry) {
788
+ try {
789
+ await clearPendingAuthAndReleaseIfIdle(runtime, serverName, oauthState, authStorageOptions);
790
+ }
791
+ catch (cleanupError) {
792
+ if (caughtError !== undefined) {
793
+ throw new AggregateError([caughtError, cleanupError], "OAuth completion cleanup failed");
794
+ }
795
+ throw cleanupError;
796
+ }
797
+ if (caughtError === undefined)
798
+ pendingAuth.authority();
799
+ }
800
+ }
801
+ }
802
+ /**
803
+ * Perform the complete OAuth authentication flow for a server.
804
+ *
805
+ * @param serverName - The name of the MCP server
806
+ * @param serverUrl - The URL of the MCP server
807
+ * @param definition - The server definition (optional)
808
+ * @returns The final auth status
809
+ */
810
+ export async function authenticate(serverName, serverUrl, definition, options = {}) {
811
+ if (isServerDisabled(definition))
812
+ throw new Error(`MCP server "${serverName}" is disabled`);
813
+ const authority = captureOAuthAuthority(serverName);
814
+ const runtime = getRuntime(options);
815
+ const runtimeState = getRuntimeState(runtime);
816
+ const authStorageOptions = options.authStorageOptions ?? {};
817
+ const signal = combineAbortSignals(runtime.signal, options.signal);
818
+ throwIfAborted(signal);
819
+ const authKey = JSON.stringify([serverName, serverUrl, ...getAuthStorageIdentity(authStorageOptions)]);
820
+ const inFlight = runtimeState.pendingAuthentications.get(authKey);
821
+ if (inFlight) {
822
+ try {
823
+ inFlight.authority();
824
+ return inFlight.promise;
825
+ }
826
+ catch {
827
+ if (runtimeState.pendingAuthentications.get(authKey) === inFlight) {
828
+ runtimeState.pendingAuthentications.delete(authKey);
829
+ }
830
+ }
831
+ }
832
+ const operation = (async () => {
833
+ const { authorizationUrl } = await startAuth(serverName, serverUrl, definition, {
834
+ ...options,
835
+ ...(signal ? { signal } : {}),
836
+ runtime,
837
+ }, authority);
838
+ authority();
839
+ if (!authorizationUrl) {
840
+ return "authenticated";
841
+ }
842
+ let oauthState;
843
+ try {
844
+ // Get the state that was already generated and stored in startAuth().
845
+ // Keep this lookup and its abort check inside the cleanup boundary because
846
+ // startAuth already owns the pending flow at this point.
847
+ oauthState = runtimeState.pendingAuthStates.get(getPendingAuthKey(serverName, authStorageOptions));
848
+ throwIfAborted(signal);
849
+ if (!oauthState) {
850
+ throw new Error("OAuth state not found - this should not happen");
851
+ }
852
+ const pendingAuth = runtimeState.pendingAuths.get(getPendingAuthKey(serverName, authStorageOptions));
853
+ if (!pendingAuth) {
854
+ throw new Error(`No pending OAuth flow for server: ${serverName}`);
855
+ }
856
+ if (pendingAuth.manualRedirect && !options.onAuthorizationInput) {
857
+ throw new Error(`OAuth for ${serverName} uses a remote redirect URI. Complete it with auth-start/auth-complete or /mcp-auth.`);
858
+ }
859
+ // Register the localhost callback before opening the browser. Remote
860
+ // pre-registered callbacks are completed by pasting their full URL.
861
+ const callbackPromise = pendingAuth.manualRedirect
862
+ ? waitForManualCompletionCancellation(pendingAuth.manualCompletionController.signal)
863
+ : waitForCallback(oauthState);
864
+ void callbackPromise.catch(() => { });
865
+ // Open browser. Always surface the URL first so remote/headless users can copy it
866
+ // even when the OS browser handoff is unavailable or invisible.
867
+ if (options.onAuthorizationUrl) {
868
+ await abortable(Promise.resolve(options.onAuthorizationUrl(authorizationUrl)), signal);
869
+ }
870
+ else {
871
+ console.log(`MCP Auth: Open this URL to authenticate ${serverName}:\n${authorizationUrl}`);
872
+ }
873
+ try {
874
+ await abortable(Promise.resolve(options.openAuthorizationUrl
875
+ ? options.openAuthorizationUrl(authorizationUrl)
876
+ : open(authorizationUrl)), signal);
877
+ }
878
+ catch (error) {
879
+ if (isAbortError(error, signal))
880
+ throw error;
881
+ console.warn(`MCP Auth: Failed to open browser for ${serverName}; waiting for manual callback`, { error });
882
+ }
883
+ const authorizationResponse = await waitForAuthorizationResponse(callbackPromise, authorizationUrl, oauthState, options.onAuthorizationInput, signal);
884
+ if (authorizationResponse.source === "manual") {
885
+ cancelPendingCallback(oauthState);
886
+ }
887
+ // The callback server accepted only the flow-local reserved state. Manual
888
+ // input is checked against the same state before token exchange.
889
+ throwIfAborted(signal);
890
+ return await completeAuth(serverName, authorizationResponse.input, {
891
+ ...options,
892
+ ...(signal ? { signal } : {}),
893
+ runtime,
894
+ });
895
+ }
896
+ catch (error) {
897
+ if (oauthState)
898
+ cancelPendingCallback(oauthState);
899
+ try {
900
+ await clearPendingAuthAndReleaseIfIdle(runtime, serverName, oauthState, authStorageOptions);
901
+ }
902
+ catch (cleanupError) {
903
+ throw new AggregateError([error, cleanupError], "OAuth cancellation cleanup failed");
904
+ }
905
+ throw error;
906
+ }
907
+ })();
908
+ const pendingAuthentication = { promise: operation, authority };
909
+ runtimeState.pendingAuthentications.set(authKey, pendingAuthentication);
910
+ try {
911
+ const result = await operation;
912
+ authority();
913
+ return result;
914
+ }
915
+ finally {
916
+ if (runtimeState.pendingAuthentications.get(authKey) === pendingAuthentication) {
917
+ runtimeState.pendingAuthentications.delete(authKey);
918
+ }
919
+ }
920
+ }
921
+ /**
922
+ * Get a valid access token for a server, refreshing if necessary.
923
+ *
924
+ * @param serverName - The name of the MCP server
925
+ * @param serverUrl - The URL of the MCP server
926
+ * @returns The valid tokens or null if not authenticated
927
+ */
928
+ export async function getValidToken(serverName, serverUrl, options = {}) {
929
+ const authority = captureOAuthAuthority(serverName);
930
+ const runtime = getRuntime(options);
931
+ const authStorageOptions = options.authStorageOptions ?? {};
932
+ const signal = combineAbortSignals(runtime.signal, options.signal);
933
+ throwIfAborted(signal);
934
+ const entry = await getAuthForUrl(serverName, serverUrl, authStorageOptions);
935
+ if (!hasOAuthAuthority(authority))
936
+ return null;
937
+ throwIfAborted(signal);
938
+ if (!entry?.tokens) {
939
+ return null;
940
+ }
941
+ const expired = entry.tokens.expiresAt
942
+ ? entry.tokens.expiresAt < Date.now() / 1000
943
+ : false;
944
+ if (expired === false) {
945
+ authority();
946
+ return entry.tokens;
947
+ }
948
+ if (expired === true && entry.tokens.refreshToken) {
949
+ console.log(`MCP Auth: Token expired for ${serverName}, attempting refresh`);
950
+ try {
951
+ const config = options.definition ? extractOAuthConfig(options.definition) : {};
952
+ const fetchFn = createOAuthFetch(serverUrl, pluginAwareOAuthHeaders(options.definition), signal);
953
+ authority();
954
+ const authProvider = new McpOAuthProvider(serverName, serverUrl, config, {
955
+ onRedirect: async () => { },
956
+ }, authStorageOptions, runtime.signal, undefined, authority);
957
+ try {
958
+ authProvider.setAuthFetch(fetchFn);
959
+ const clientInfo = await authProvider.clientInformation();
960
+ authority();
961
+ throwIfAborted(signal);
962
+ if (!clientInfo) {
963
+ console.log(`MCP Auth: No client info for refresh for ${serverName}`);
964
+ return null;
965
+ }
966
+ const discovery = applyOAuthConfig(await probeAuthDiscovery(serverUrl, options.definition, signal), config);
967
+ authority();
968
+ throwIfAborted(signal);
969
+ const result = await abortable(runSdkAuth(authProvider, {
970
+ serverUrl,
971
+ ...discovery,
972
+ ...(options.skipIssuerMetadataValidation === true ? { skipIssuerMetadataValidation: true } : {}),
973
+ fetchFn,
974
+ }), signal);
975
+ authority();
976
+ throwIfAborted(signal);
977
+ if (result !== "AUTHORIZED") {
978
+ return null;
979
+ }
980
+ const refreshed = await getAuthForUrl(serverName, serverUrl, authStorageOptions);
981
+ authority();
982
+ throwIfAborted(signal);
983
+ return refreshed?.tokens ?? null;
984
+ }
985
+ finally {
986
+ authProvider.deactivate();
987
+ }
988
+ }
989
+ catch (error) {
990
+ if (isAbortError(error, signal) || error instanceof OAuthCredentialStoreError)
991
+ throw error;
992
+ console.error(`MCP Auth: Token refresh failed for ${serverName}`);
993
+ return null;
994
+ }
995
+ }
996
+ // No expiration info or no refresh token, assume valid
997
+ authority();
998
+ return entry.tokens;
999
+ }
1000
+ /**
1001
+ * Check the authentication status for a server.
1002
+ *
1003
+ * @param serverName - The name of the MCP server
1004
+ * @returns The current auth status
1005
+ */
1006
+ export async function getAuthStatus(serverName, options = {}) {
1007
+ getRuntime(options);
1008
+ const authStorageOptions = options.authStorageOptions ?? {};
1009
+ const entry = getAuthEntry(serverName, authStorageOptions);
1010
+ if (!entry?.tokens)
1011
+ return "not_authenticated";
1012
+ return entry.tokens.expiresAt && entry.tokens.expiresAt < Date.now() / 1000 ? "expired" : "authenticated";
1013
+ }
1014
+ /**
1015
+ * Remove all OAuth credentials for a server.
1016
+ *
1017
+ * @param serverName - The name of the MCP server
1018
+ */
1019
+ export async function removeAuth(serverName, options = {}) {
1020
+ const runtime = getRuntime(options);
1021
+ const signal = combineAbortSignals(runtime.signal, options.signal);
1022
+ throwIfAborted(signal);
1023
+ const authStorageOptions = options.authStorageOptions ?? {};
1024
+ const releaseRevocation = beginOAuthRevocation(serverName);
1025
+ try {
1026
+ detachPendingAuthsForServer(serverName, new Error("Authorization cancelled by logout"));
1027
+ const storedOAuthState = getOAuthState(serverName, authStorageOptions);
1028
+ if (storedOAuthState)
1029
+ cancelPendingCallback(storedOAuthState);
1030
+ await stopCallbackServerIfIdle();
1031
+ throwIfAborted(signal);
1032
+ clearAllCredentials(serverName, authStorageOptions);
1033
+ console.log(`MCP Auth: Removed credentials for ${serverName}`);
1034
+ }
1035
+ finally {
1036
+ releaseRevocation();
1037
+ }
1038
+ }
1039
+ /**
1040
+ * Check if OAuth is supported for a server configuration.
1041
+ * OAuth is supported for HTTP servers unless explicitly disabled.
1042
+ *
1043
+ * @param definition - The server definition
1044
+ * @returns True if OAuth is supported
1045
+ */
1046
+ export function supportsOAuth(definition) {
1047
+ // OAuth requires a URL
1048
+ if (!definition.url)
1049
+ return false;
1050
+ // Explicitly disabled via auth: false or oauth: false
1051
+ if (definition.auth === false)
1052
+ return false;
1053
+ if (definition.oauth === false)
1054
+ return false;
1055
+ if (definition.auth === "oauth")
1056
+ return true;
1057
+ // Configured custom headers take precedence over implicit OAuth auto-detection.
1058
+ if (definition.headers && Object.keys(definition.headers).length > 0)
1059
+ return false;
1060
+ // OAuth is enabled when auth is not specified (auto-detect)
1061
+ return definition.auth === undefined;
1062
+ }
1063
+ /**
1064
+ * Initialize the OAuth system on startup.
1065
+ * OAuth callback binding is lazy and starts from startAuth() only.
1066
+ */
1067
+ export async function initializeOAuth(runtimeOrSignal) {
1068
+ if (runtimeOrSignal && "signal" in runtimeOrSignal) {
1069
+ runtimeOrSignal.signal.throwIfAborted();
1070
+ activeRuntimes.add(runtimeOrSignal);
1071
+ return runtimeOrSignal;
1072
+ }
1073
+ await shutdownOAuth(legacyRuntime);
1074
+ legacyRuntime = createOAuthRuntime(runtimeOrSignal);
1075
+ return legacyRuntime;
1076
+ }
1077
+ /**
1078
+ * Shutdown one OAuth runtime. The callback server remains process-shared while
1079
+ * another runtime has pending/reserved callback state or is still active.
1080
+ */
1081
+ export async function shutdownOAuth(runtime = legacyRuntime) {
1082
+ const state = getRuntimeState(runtime);
1083
+ if (state.controller.signal.aborted)
1084
+ return;
1085
+ state.generation += 1;
1086
+ state.controller.abort(new Error("OAuth runtime stopped"));
1087
+ for (const callbackState of Array.from(state.pendingAuthStates.values()))
1088
+ cancelPendingCallback(callbackState);
1089
+ for (const pendingAuth of Array.from(state.pendingAuths.values())) {
1090
+ await clearPendingAuth(runtime, pendingAuth.serverName, undefined, pendingAuth.authStorageOptions);
1091
+ }
1092
+ state.pendingAuthentications.clear();
1093
+ activeRuntimes.delete(runtime);
1094
+ if (activeRuntimes.size === 0) {
1095
+ await stopCallbackServer();
1096
+ }
1097
+ }
1098
+ //# sourceMappingURL=mcp-auth-flow.js.map