@fitchmultz/pi-mcp-adapter 5.0.0

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 (176) hide show
  1. package/CHANGELOG.md +750 -0
  2. package/LICENSE +21 -0
  3. package/OAUTH.md +462 -0
  4. package/README.md +820 -0
  5. package/abort.ts +34 -0
  6. package/agent-dir.ts +24 -0
  7. package/app-bridge.bundle.js +67 -0
  8. package/banner.png +0 -0
  9. package/checkpoint.ts +55 -0
  10. package/cli.js +222 -0
  11. package/commands.ts +619 -0
  12. package/config.ts +1204 -0
  13. package/consent-manager.ts +25 -0
  14. package/direct-tools.ts +408 -0
  15. package/dist/abort.d.ts +2 -0
  16. package/dist/abort.js +35 -0
  17. package/dist/agent-dir.d.ts +3 -0
  18. package/dist/agent-dir.js +21 -0
  19. package/dist/app-bridge.bundle.js +67 -0
  20. package/dist/checkpoint.d.ts +18 -0
  21. package/dist/checkpoint.js +53 -0
  22. package/dist/commands.d.ts +20 -0
  23. package/dist/commands.js +521 -0
  24. package/dist/config.d.ts +109 -0
  25. package/dist/config.js +1013 -0
  26. package/dist/consent-manager.d.ts +8 -0
  27. package/dist/consent-manager.js +21 -0
  28. package/dist/direct-tools.d.ts +10 -0
  29. package/dist/direct-tools.js +350 -0
  30. package/dist/docs/client-metadata.json +14 -0
  31. package/dist/elicitation-handler.d.ts +17 -0
  32. package/dist/elicitation-handler.js +308 -0
  33. package/dist/error-signal.d.ts +15 -0
  34. package/dist/error-signal.js +21 -0
  35. package/dist/glimpse-ui.d.ts +9 -0
  36. package/dist/glimpse-ui.js +75 -0
  37. package/dist/host-html-template.d.ts +15 -0
  38. package/dist/host-html-template.js +429 -0
  39. package/dist/index.d.ts +7 -0
  40. package/dist/index.js +840 -0
  41. package/dist/init.d.ts +25 -0
  42. package/dist/init.js +562 -0
  43. package/dist/legacy-migration.d.ts +18 -0
  44. package/dist/legacy-migration.js +45 -0
  45. package/dist/lifecycle.d.ts +40 -0
  46. package/dist/lifecycle.js +167 -0
  47. package/dist/logger.d.ts +38 -0
  48. package/dist/logger.js +102 -0
  49. package/dist/mcp-auth-flow.d.ts +113 -0
  50. package/dist/mcp-auth-flow.js +834 -0
  51. package/dist/mcp-auth.d.ts +127 -0
  52. package/dist/mcp-auth.js +658 -0
  53. package/dist/mcp-callback-server.d.ts +56 -0
  54. package/dist/mcp-callback-server.js +371 -0
  55. package/dist/mcp-code.d.ts +51 -0
  56. package/dist/mcp-code.js +366 -0
  57. package/dist/mcp-keyring-helper.cjs +89 -0
  58. package/dist/mcp-oauth-provider.d.ts +154 -0
  59. package/dist/mcp-oauth-provider.js +672 -0
  60. package/dist/mcp-output-guard.d.ts +59 -0
  61. package/dist/mcp-output-guard.js +332 -0
  62. package/dist/mcp-panel.d.ts +66 -0
  63. package/dist/mcp-panel.js +889 -0
  64. package/dist/mcp-script-worker.mjs +128 -0
  65. package/dist/mcp-setup-panel.d.ts +84 -0
  66. package/dist/mcp-setup-panel.js +561 -0
  67. package/dist/mcp-status.d.ts +11 -0
  68. package/dist/mcp-status.js +96 -0
  69. package/dist/mcp-trace.d.ts +95 -0
  70. package/dist/mcp-trace.js +233 -0
  71. package/dist/metadata-cache.d.ts +18 -0
  72. package/dist/metadata-cache.js +277 -0
  73. package/dist/npx-resolver.d.ts +6 -0
  74. package/dist/npx-resolver.js +448 -0
  75. package/dist/onboarding-state.d.ts +11 -0
  76. package/dist/onboarding-state.js +47 -0
  77. package/dist/panel-keys.d.ts +16 -0
  78. package/dist/panel-keys.js +15 -0
  79. package/dist/prompts.d.ts +56 -0
  80. package/dist/prompts.js +284 -0
  81. package/dist/proxy-modes.d.ts +38 -0
  82. package/dist/proxy-modes.js +1235 -0
  83. package/dist/resource-tools.d.ts +1 -0
  84. package/dist/resource-tools.js +14 -0
  85. package/dist/runtime-owner.d.ts +18 -0
  86. package/dist/runtime-owner.js +117 -0
  87. package/dist/sampling-handler.d.ts +15 -0
  88. package/dist/sampling-handler.js +211 -0
  89. package/dist/search-ranking.d.ts +20 -0
  90. package/dist/search-ranking.js +180 -0
  91. package/dist/server-manager.d.ts +114 -0
  92. package/dist/server-manager.js +1175 -0
  93. package/dist/session-recovery.d.ts +31 -0
  94. package/dist/session-recovery.js +310 -0
  95. package/dist/state.d.ts +63 -0
  96. package/dist/state.js +1 -0
  97. package/dist/tool-approval.d.ts +10 -0
  98. package/dist/tool-approval.js +42 -0
  99. package/dist/tool-metadata.d.ts +9 -0
  100. package/dist/tool-metadata.js +193 -0
  101. package/dist/tool-registrar.d.ts +10 -0
  102. package/dist/tool-registrar.js +64 -0
  103. package/dist/tool-result-renderer.d.ts +45 -0
  104. package/dist/tool-result-renderer.js +224 -0
  105. package/dist/ts-shape.d.ts +2 -0
  106. package/dist/ts-shape.js +147 -0
  107. package/dist/types.d.ts +516 -0
  108. package/dist/types.js +168 -0
  109. package/dist/ui-resource-handler.d.ts +17 -0
  110. package/dist/ui-resource-handler.js +209 -0
  111. package/dist/ui-server.d.ts +51 -0
  112. package/dist/ui-server.js +669 -0
  113. package/dist/ui-session.d.ts +39 -0
  114. package/dist/ui-session.js +463 -0
  115. package/dist/ui-stream-types.d.ts +104 -0
  116. package/dist/ui-stream-types.js +58 -0
  117. package/dist/ui-tool-visibility.d.ts +4 -0
  118. package/dist/ui-tool-visibility.js +26 -0
  119. package/dist/unix-socket-transport.d.ts +15 -0
  120. package/dist/unix-socket-transport.js +84 -0
  121. package/dist/utils.d.ts +30 -0
  122. package/dist/utils.js +276 -0
  123. package/docs/client-metadata.json +14 -0
  124. package/elicitation-handler.ts +349 -0
  125. package/error-signal.ts +21 -0
  126. package/glimpse-ui.ts +80 -0
  127. package/host-html-template.ts +456 -0
  128. package/index.ts +900 -0
  129. package/init.ts +627 -0
  130. package/legacy-migration.ts +47 -0
  131. package/lifecycle.ts +165 -0
  132. package/logger.ts +127 -0
  133. package/mcp-auth-flow.ts +975 -0
  134. package/mcp-auth.ts +793 -0
  135. package/mcp-callback-server.ts +450 -0
  136. package/mcp-code.ts +386 -0
  137. package/mcp-keyring-helper.cjs +89 -0
  138. package/mcp-oauth-provider.ts +774 -0
  139. package/mcp-output-guard.ts +412 -0
  140. package/mcp-panel.ts +978 -0
  141. package/mcp-script-worker.mjs +128 -0
  142. package/mcp-setup-panel.ts +666 -0
  143. package/mcp-status.ts +109 -0
  144. package/mcp-trace.ts +295 -0
  145. package/metadata-cache.ts +333 -0
  146. package/npx-resolver.ts +488 -0
  147. package/onboarding-state.ts +58 -0
  148. package/package.json +182 -0
  149. package/panel-keys.ts +37 -0
  150. package/prompts.ts +337 -0
  151. package/proxy-modes.ts +1361 -0
  152. package/resource-tools.ts +17 -0
  153. package/runtime-owner.ts +123 -0
  154. package/sampling-handler.ts +273 -0
  155. package/scripts/build.mjs +131 -0
  156. package/scripts/prepare.mjs +102 -0
  157. package/search-ranking.ts +196 -0
  158. package/server-manager.ts +1320 -0
  159. package/session-recovery.ts +316 -0
  160. package/skills/mcp-scripting/SKILL.md +38 -0
  161. package/state.ts +64 -0
  162. package/tool-approval.ts +78 -0
  163. package/tool-metadata.ts +235 -0
  164. package/tool-registrar.ts +69 -0
  165. package/tool-result-renderer.ts +286 -0
  166. package/ts-shape.ts +145 -0
  167. package/tsconfig.build.json +13 -0
  168. package/tsconfig.json +16 -0
  169. package/types.ts +810 -0
  170. package/ui-resource-handler.ts +249 -0
  171. package/ui-server.ts +808 -0
  172. package/ui-session.ts +568 -0
  173. package/ui-stream-types.ts +89 -0
  174. package/ui-tool-visibility.ts +25 -0
  175. package/unix-socket-transport.ts +85 -0
  176. package/utils.ts +309 -0
@@ -0,0 +1,834 @@
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, UnauthorizedError, Client, StreamableHTTPClientTransport, validateAuthorizationResponseIssuer, InsufficientScopeError, SdkHttpError, computeScopeUnion, isStrictScopeSuperset, } from "@modelcontextprotocol/client";
7
+ import open from "open";
8
+ import { McpOAuthProvider, issuersMatch, loopbackRedirectsMatch, validateOAuthClientMetadataUrl, validateOAuthPrivateKeyJwt, validateOAuthCrossAppAccess } from "./mcp-oauth-provider.js";
9
+ import { ensureCallbackServer, waitForCallback, cancelPendingCallback, stopCallbackServer, releaseCallbackServer, takeCallbackResult, } from "./mcp-callback-server.js";
10
+ import { getAuthForUrl, clearAllCredentials, clearClientInfo, clearTokens, clearCodeVerifier, getOAuthState, clearOAuthState, getAuthBaseDir, } from "./mcp-auth.js";
11
+ import { isServerDisabled, isNonInteractiveOAuth, validateServerProtocolConfig } from "./types.js";
12
+ import { formatTerminalError, interpolateEnvRecord, interpolateEnvVars, normalizeRequestTimeoutMs } from "./utils.js";
13
+ import { abortable, throwIfAborted } from "./abort.js";
14
+ import { combineAbortSignals, isAbortError } from "./runtime-owner.js";
15
+ function applyConfiguredScope(discovery, config) {
16
+ return {
17
+ ...discovery,
18
+ ...(config.scope !== undefined ? { scope: config.scope } : {}),
19
+ ...(config.skipIssuerMetadataValidation !== undefined ? { skipIssuerMetadataValidation: config.skipIssuerMetadataValidation } : {}),
20
+ };
21
+ }
22
+ function validateCallbackIssuer(serverName, context, response) {
23
+ if (response.error && context.expectedIssuer === undefined) {
24
+ throw new Error("Cannot verify the OAuth error callback issuer");
25
+ }
26
+ try {
27
+ validateAuthorizationResponseIssuer({ expectedIssuer: context.expectedIssuer ?? context.fallbackIssuer, issParameterSupported: context.issParameterSupported === true, iss: response.iss });
28
+ }
29
+ catch {
30
+ if (response.iss === undefined && context.issParameterSupported) {
31
+ throw new Error(`The authorization server for ${serverName} requires the RFC 9207 "iss" parameter. ` +
32
+ "Paste the full redirect URL from the browser address bar (not just the authorization code).");
33
+ }
34
+ throw new Error(`The OAuth authorization response issuer does not match the discovered issuer for ${serverName}.`);
35
+ }
36
+ }
37
+ const runtimeStates = new WeakMap();
38
+ const activeRuntimes = new Set();
39
+ export function createOAuthRuntime(signal) {
40
+ const controller = new AbortController();
41
+ const runtime = { signal: combineAbortSignals(signal, controller.signal) };
42
+ runtimeStates.set(runtime, {
43
+ controller,
44
+ generation: 0,
45
+ activeOperations: 0,
46
+ pendingAuths: new Map(),
47
+ pendingAuthStates: new Map(),
48
+ pendingAuthCleanupTimers: new Map(),
49
+ pendingAuthentications: new Map(),
50
+ requests: new Map(),
51
+ });
52
+ activeRuntimes.add(runtime);
53
+ return runtime;
54
+ }
55
+ let legacyRuntime = createOAuthRuntime();
56
+ activeRuntimes.delete(legacyRuntime);
57
+ function getRuntime(options) {
58
+ if (options?.runtime) {
59
+ options.runtime.signal.throwIfAborted();
60
+ activeRuntimes.add(options.runtime);
61
+ return options.runtime;
62
+ }
63
+ if (legacyRuntime.signal.aborted)
64
+ legacyRuntime = createOAuthRuntime();
65
+ activeRuntimes.add(legacyRuntime);
66
+ return legacyRuntime;
67
+ }
68
+ function getRuntimeState(runtime) {
69
+ const state = runtimeStates.get(runtime);
70
+ if (!state)
71
+ throw new Error("Unknown OAuth runtime");
72
+ return state;
73
+ }
74
+ export function holdOAuthCheckpoint(runtime, event) {
75
+ const state = getRuntimeState(runtime);
76
+ if (state.checkpoint)
77
+ throw new Error("MCP OAuth checkpoint is already held");
78
+ state.checkpoint = event;
79
+ return () => { if (state.checkpoint === event)
80
+ state.checkpoint = undefined; };
81
+ }
82
+ export function getOAuthCheckpointBlocker(runtime) {
83
+ const state = getRuntimeState(runtime);
84
+ if (state.activeOperations || state.pendingAuthentications.size)
85
+ return "MCP OAuth operation is active";
86
+ if (state.pendingAuths.size || state.pendingAuthStates.size || state.pendingAuthCleanupTimers.size)
87
+ return "MCP browser OAuth callback/flow is pending";
88
+ // requests caches server challenges/discovery, not a pending user callback.
89
+ // Cold connect re-challenges; granted scopes and issuer bindings live in the
90
+ // native credential store. Actual interactive/auth operations veto above.
91
+ return undefined;
92
+ }
93
+ async function withOAuthOperation(runtime, run) {
94
+ const state = getRuntimeState(runtime);
95
+ state.checkpoint?.invalidate();
96
+ state.activeOperations++;
97
+ try {
98
+ return await run();
99
+ }
100
+ finally {
101
+ state.activeOperations--;
102
+ }
103
+ }
104
+ function getPendingAuthKey(serverName, options) {
105
+ return JSON.stringify([serverName, getAuthBaseDir(options)]);
106
+ }
107
+ export function isOAuthChallenge(error) {
108
+ return error instanceof InsufficientScopeError || error instanceof UnauthorizedError
109
+ || (error instanceof SdkHttpError && error.status === 401);
110
+ }
111
+ export function getOAuthRequest(serverName, serverUrl, storageBase, runtime = legacyRuntime) {
112
+ if (runtime.signal.aborted)
113
+ return undefined;
114
+ const request = getRuntimeState(runtime).requests.get(JSON.stringify([serverName, storageBase]));
115
+ return request?.serverUrl === serverUrl ? request : undefined;
116
+ }
117
+ /** Observe native challenges only; no credential reads or auth work here. */
118
+ export function recordOAuthChallenge(serverName, serverUrl, storageBase, error, runtime = legacyRuntime) {
119
+ if (runtime.signal.aborted || !isOAuthChallenge(error))
120
+ return;
121
+ getRuntimeState(runtime).checkpoint?.invalidate();
122
+ const previous = getOAuthRequest(serverName, serverUrl, storageBase, runtime);
123
+ const request = { ...previous, serverName, serverUrl };
124
+ if (error instanceof InsufficientScopeError) {
125
+ const requiredScope = computeScopeUnion(previous?.challenge?.requiredScope, error.requiredScope);
126
+ const resourceMetadataUrl = error.resourceMetadataUrl ?? previous?.challenge?.resourceMetadataUrl;
127
+ request.challenge = { ...(requiredScope ? { requiredScope } : {}), ...(resourceMetadataUrl ? { resourceMetadataUrl } : {}) };
128
+ }
129
+ getRuntimeState(runtime).requests.set(JSON.stringify([serverName, storageBase]), request);
130
+ }
131
+ export function bindOAuthRequestIssuer(serverName, serverUrl, storageBase, issuer, runtime = legacyRuntime) {
132
+ const request = getOAuthRequest(serverName, serverUrl, storageBase, runtime);
133
+ if (!request)
134
+ return;
135
+ if (request.issuer && !issuersMatch(request.issuer, issuer)) {
136
+ throw new Error(`OAuth authorization server issuer changed for ${serverName}; clear credentials before authenticating again`);
137
+ }
138
+ request.issuer = issuer;
139
+ }
140
+ export function hasPendingAuth(serverName, options, runtime) {
141
+ const state = getRuntimeState(runtime ?? legacyRuntime);
142
+ if (options) {
143
+ return state.pendingAuths.has(getPendingAuthKey(serverName, options));
144
+ }
145
+ return Array.from(state.pendingAuths.values()).some(pendingAuth => pendingAuth.serverName === serverName);
146
+ }
147
+ /** Timeout for manual auth completion (5 minutes) */
148
+ const MANUAL_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
149
+ /**
150
+ * Generate a cryptographically secure random state parameter.
151
+ */
152
+ function generateState() {
153
+ return Array.from(crypto.getRandomValues(new Uint8Array(32)))
154
+ .map((b) => b.toString(16).padStart(2, "0"))
155
+ .join("");
156
+ }
157
+ /**
158
+ * Extract OAuth configuration from a ServerEntry.
159
+ */
160
+ export function extractOAuthConfig(definition) {
161
+ validateServerProtocolConfig(definition);
162
+ if (definition.oauth === false) {
163
+ return {};
164
+ }
165
+ const config = {};
166
+ if (definition.oauth?.skipIssuerMetadataValidation !== undefined)
167
+ config.skipIssuerMetadataValidation = definition.oauth.skipIssuerMetadataValidation;
168
+ if (definition.oauth?.grantType !== undefined)
169
+ config.grantType = definition.oauth.grantType;
170
+ if (definition.oauth?.clientId !== undefined) {
171
+ if (typeof definition.oauth.clientId !== "string")
172
+ throw new Error("OAuth clientId must be a string");
173
+ config.clientId = interpolateEnvVars(definition.oauth.clientId);
174
+ }
175
+ if (definition.oauth?.clientSecret !== undefined) {
176
+ if (typeof definition.oauth.clientSecret !== "string")
177
+ throw new Error("OAuth clientSecret must be a string");
178
+ // Preserve command expressions for the provider; interpolation remains eager for ordinary values.
179
+ config.clientSecret = definition.oauth.clientSecret.startsWith("!")
180
+ ? definition.oauth.clientSecret
181
+ : interpolateEnvVars(definition.oauth.clientSecret);
182
+ }
183
+ if (definition.oauth?.clientMetadataUrl !== undefined) {
184
+ const value = definition.oauth.clientMetadataUrl;
185
+ if (value !== false && typeof value !== "string")
186
+ throw new Error("OAuth clientMetadataUrl must be a string or false");
187
+ config.clientMetadataUrl = value === false ? false : interpolateEnvVars(value);
188
+ validateOAuthClientMetadataUrl(config.clientMetadataUrl);
189
+ }
190
+ if (definition.oauth?.privateKeyJwt !== undefined) {
191
+ // Keep environment and command sources lazy; each authentication resolves its own key.
192
+ config.privateKeyJwt = definition.oauth.privateKeyJwt;
193
+ }
194
+ if (definition.oauth?.crossAppAccess !== undefined)
195
+ config.crossAppAccess = definition.oauth.crossAppAccess;
196
+ validateOAuthPrivateKeyJwt(config);
197
+ validateOAuthCrossAppAccess(config);
198
+ if (definition.oauth?.scope !== undefined) {
199
+ if (typeof definition.oauth.scope !== "string")
200
+ throw new Error("OAuth scope must be a string");
201
+ config.scope = interpolateEnvVars(definition.oauth.scope);
202
+ }
203
+ if (definition.oauth?.authorizationParams !== undefined) {
204
+ const params = definition.oauth.authorizationParams;
205
+ if (!params || typeof params !== "object" || Array.isArray(params)) {
206
+ throw new Error("OAuth authorizationParams must be an object");
207
+ }
208
+ config.authorizationParams = {};
209
+ for (const [key, value] of Object.entries(params)) {
210
+ if (!key)
211
+ throw new Error("OAuth authorizationParams keys must not be empty");
212
+ if (typeof value !== "string")
213
+ throw new Error(`OAuth authorizationParams.${key} must be a string`);
214
+ config.authorizationParams[key] = interpolateEnvVars(value);
215
+ }
216
+ }
217
+ if (definition.oauth?.redirectUri !== undefined) {
218
+ if (typeof definition.oauth.redirectUri !== "string") {
219
+ throw new Error("OAuth redirectUri must be a string");
220
+ }
221
+ const redirectUri = interpolateEnvVars(definition.oauth.redirectUri).trim();
222
+ if (!redirectUri) {
223
+ throw new Error("OAuth redirectUri must not be empty");
224
+ }
225
+ config.redirectUri = redirectUri;
226
+ }
227
+ if (definition.oauth?.clientName !== undefined) {
228
+ if (typeof definition.oauth.clientName !== "string") {
229
+ throw new Error("OAuth clientName must be a string");
230
+ }
231
+ const clientName = interpolateEnvVars(definition.oauth.clientName).trim();
232
+ if (!clientName) {
233
+ throw new Error("OAuth clientName must not be empty");
234
+ }
235
+ config.clientName = clientName;
236
+ }
237
+ if (definition.oauth?.clientUri !== undefined) {
238
+ if (typeof definition.oauth.clientUri !== "string") {
239
+ throw new Error("OAuth clientUri must be a string");
240
+ }
241
+ const clientUri = interpolateEnvVars(definition.oauth.clientUri).trim();
242
+ if (!clientUri) {
243
+ throw new Error("OAuth clientUri must not be empty");
244
+ }
245
+ config.clientUri = clientUri;
246
+ }
247
+ return config;
248
+ }
249
+ async function probeAuthDiscovery(serverUrl, definition, signal) {
250
+ // Discovery must not execute config commands or send their source text.
251
+ const discoveryHeaders = definition?.headers
252
+ ? Object.fromEntries(Object.entries(definition.headers).filter(([, value]) => !value.startsWith("!") || value.startsWith("!!")))
253
+ : undefined;
254
+ const headers = new Headers(interpolateEnvRecord(discoveryHeaders));
255
+ const timeout = normalizeRequestTimeoutMs(definition?.requestTimeoutMs) ?? 5000;
256
+ const discoverySignal = combineAbortSignals(signal, AbortSignal.timeout(Math.ceil(timeout)));
257
+ let discovery = {};
258
+ const client = new Client({ name: "pi-mcp-auth-discovery", version: "4.3.1" }, {
259
+ versionNegotiation: { mode: definition?.protocolVersion ?? "auto" },
260
+ ...(isNonInteractiveOAuth(definition?.oauth)
261
+ ? { capabilities: { extensions: { [definition?.oauth && definition.oauth.crossAppAccess
262
+ ? "io.modelcontextprotocol/enterprise-managed-authorization" : "io.modelcontextprotocol/oauth-client-credentials"]: {} } } } : {}),
263
+ });
264
+ const transport = new StreamableHTTPClientTransport(new URL(serverUrl), {
265
+ requestInit: { headers },
266
+ fetch: async (input, init) => {
267
+ const response = await fetch(input, init);
268
+ const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
269
+ discovery = { ...(resourceMetadataUrl ? { resourceMetadataUrl } : {}), ...(scope ? { scope } : {}) };
270
+ return response;
271
+ },
272
+ });
273
+ try {
274
+ await abortable(client.connect(transport, { timeout }), discoverySignal);
275
+ }
276
+ catch (error) {
277
+ if (signal?.aborted)
278
+ throwIfAborted(signal);
279
+ }
280
+ finally {
281
+ await (client.transport ? client.close() : transport.close());
282
+ }
283
+ return discovery;
284
+ }
285
+ function parseOAuthRedirectUri(redirectUri) {
286
+ let url;
287
+ try {
288
+ url = new URL(redirectUri);
289
+ }
290
+ catch (error) {
291
+ throw new Error(`Invalid OAuth redirectUri: ${redirectUri}`, { cause: error });
292
+ }
293
+ const hostname = url.hostname.toLowerCase();
294
+ const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
295
+ if (url.protocol !== "http:" || !isLocalhost) {
296
+ throw new Error("OAuth redirectUri must be an http:// localhost or loopback URI");
297
+ }
298
+ if (url.username || url.password) {
299
+ throw new Error("OAuth redirectUri must not include username or password");
300
+ }
301
+ if (url.hash) {
302
+ throw new Error("OAuth redirectUri must not include a fragment");
303
+ }
304
+ if (!url.port) {
305
+ throw new Error("OAuth redirectUri must include an explicit numeric port");
306
+ }
307
+ const port = Number.parseInt(url.port, 10);
308
+ if (!Number.isInteger(port) || port <= 0 || port > 65535) {
309
+ throw new Error("OAuth redirectUri must include an explicit numeric port");
310
+ }
311
+ const callbackHost = hostname === "[::1]" ? "::1" : hostname;
312
+ return { port, callbackHost, callbackPath: url.pathname };
313
+ }
314
+ /**
315
+ * Start OAuth authentication flow for a server.
316
+ * Returns the authorization URL when browser authorization is required.
317
+ */
318
+ export const startAuth = async (...args) => withOAuthOperation(getRuntime(args[3]), () => startAuthOperation(...args));
319
+ async function startAuthOperation(serverName, serverUrl, definition, options = {}) {
320
+ if (isServerDisabled(definition))
321
+ throw new Error(`MCP server "${serverName}" is disabled`);
322
+ const runtime = getRuntime(options);
323
+ const runtimeState = getRuntimeState(runtime);
324
+ const config = definition ? extractOAuthConfig(definition) : {};
325
+ const authStorageOptions = options.authStorageOptions ?? {};
326
+ const signal = combineAbortSignals(runtime.signal, options.signal);
327
+ const generation = runtimeState.generation;
328
+ throwIfAborted(signal);
329
+ if (isNonInteractiveOAuth(config)) {
330
+ const storedAuth = await getAuthForUrl(serverName, serverUrl, authStorageOptions);
331
+ if (!config.crossAppAccess && storedAuth?.clientInfo && !storedAuth.tokens && !config.clientId) {
332
+ clearClientInfo(serverName, authStorageOptions);
333
+ clearCodeVerifier(serverName, authStorageOptions);
334
+ await clearOAuthState(serverName, authStorageOptions);
335
+ }
336
+ const authProvider = new McpOAuthProvider(serverName, serverUrl, config, {
337
+ onRedirect: async () => {
338
+ throw new Error("Browser redirect is not used for noninteractive OAuth flows");
339
+ },
340
+ }, authStorageOptions, signal);
341
+ try {
342
+ const discovery = applyConfiguredScope(await probeAuthDiscovery(serverUrl, definition, signal), config);
343
+ throwIfAborted(signal);
344
+ const result = await abortable(runSdkAuth(authProvider, { serverUrl, ...discovery, fetchFn: authProvider.fetch }), signal);
345
+ throwIfAborted(signal);
346
+ if (result !== "AUTHORIZED") {
347
+ throw new UnauthorizedError("Failed to authorize");
348
+ }
349
+ return { authorizationUrl: "" };
350
+ }
351
+ finally {
352
+ authProvider.deactivate();
353
+ }
354
+ }
355
+ const storageBase = getAuthBaseDir(authStorageOptions);
356
+ const request = getOAuthRequest(serverName, serverUrl, storageBase, runtime);
357
+ const existingPendingAuth = runtimeState.pendingAuths.get(getPendingAuthKey(serverName, authStorageOptions));
358
+ if (existingPendingAuth?.serverUrl === serverUrl) {
359
+ return { authorizationUrl: existingPendingAuth.authorizationUrl };
360
+ }
361
+ const redirectCallback = config.redirectUri !== undefined ? parseOAuthRedirectUri(config.redirectUri) : undefined;
362
+ const oauthState = generateState();
363
+ const callbackIssuer = {};
364
+ try {
365
+ await ensureCallbackServer({
366
+ strictPort: Boolean(config.clientId) || config.redirectUri !== undefined,
367
+ oauthState,
368
+ reserveState: true,
369
+ validate: response => validateCallbackIssuer(serverName, callbackIssuer, response),
370
+ ...(redirectCallback ? { port: redirectCallback.port, callbackHost: redirectCallback.callbackHost, callbackPath: redirectCallback.callbackPath } : {}),
371
+ });
372
+ throwIfAborted(signal);
373
+ }
374
+ catch (error) {
375
+ releaseCallbackServer(oauthState);
376
+ try {
377
+ await clearOAuthState(serverName, authStorageOptions);
378
+ }
379
+ catch (cleanupError) {
380
+ throw new AggregateError([error, cleanupError], "OAuth startup cleanup failed");
381
+ }
382
+ throw error;
383
+ }
384
+ let capturedUrl;
385
+ let authProvider;
386
+ try {
387
+ const storedAuth = await getAuthForUrl(serverName, serverUrl, authStorageOptions);
388
+ let discovery = applyConfiguredScope(await probeAuthDiscovery(serverUrl, definition, signal), config);
389
+ if (request?.challenge) {
390
+ const scope = computeScopeUnion(discovery.scope, request.requestedScope, storedAuth?.tokens?.scope, request.challenge.requiredScope);
391
+ discovery = { ...discovery, ...(scope ? { scope } : {}), ...(request.challenge.resourceMetadataUrl ? { resourceMetadataUrl: request.challenge.resourceMetadataUrl } : {}) };
392
+ }
393
+ throwIfAborted(signal);
394
+ const flowConfig = { ...config, ...(request?.challenge && discovery.scope ? { scope: discovery.scope } : {}) };
395
+ authProvider = new McpOAuthProvider(serverName, serverUrl, flowConfig, {
396
+ onRedirect: url => {
397
+ capturedUrl = url;
398
+ const requestedScope = url.searchParams.get("scope") ?? undefined;
399
+ if (requestedScope) {
400
+ discovery = { ...discovery, scope: requestedScope };
401
+ if (request?.challenge)
402
+ flowConfig.scope = requestedScope;
403
+ }
404
+ const current = getOAuthRequest(serverName, serverUrl, storageBase, runtime);
405
+ const scope = computeScopeUnion(current?.requestedScope, requestedScope);
406
+ if (current && scope)
407
+ current.requestedScope = scope;
408
+ },
409
+ onDiscoveryState: state => {
410
+ callbackIssuer.expectedIssuer = state.authorizationServerMetadata?.issuer;
411
+ callbackIssuer.fallbackIssuer = state.authorizationServerUrl;
412
+ callbackIssuer.issParameterSupported = state.authorizationServerMetadata?.authorization_response_iss_parameter_supported === true;
413
+ bindOAuthRequestIssuer(serverName, serverUrl, storageBase, callbackIssuer.expectedIssuer ?? state.authorizationServerUrl, runtime);
414
+ },
415
+ }, authStorageOptions, runtime.signal, oauthState);
416
+ if (storedAuth?.clientInfo && !config.clientId) {
417
+ if (!storedAuth.tokens) {
418
+ clearClientInfo(serverName, authStorageOptions);
419
+ clearCodeVerifier(serverName, authStorageOptions);
420
+ await clearOAuthState(serverName, authStorageOptions);
421
+ }
422
+ else {
423
+ const redirectUris = storedAuth.clientInfo.redirectUris;
424
+ const redirectUrl = authProvider.redirectUrl ?? "";
425
+ const matchesRedirect = Array.isArray(redirectUris) && (redirectUris.includes(redirectUrl)
426
+ || (storedAuth.clientInfo.registrationType === "cimd"
427
+ && redirectUris.some(uri => loopbackRedirectsMatch(redirectUrl, uri))));
428
+ if (!matchesRedirect) {
429
+ clearClientInfo(serverName, authStorageOptions);
430
+ clearTokens(serverName, authStorageOptions);
431
+ clearCodeVerifier(serverName, authStorageOptions);
432
+ await clearOAuthState(serverName, authStorageOptions);
433
+ }
434
+ }
435
+ }
436
+ throwIfAborted(signal);
437
+ const result = await abortable(runSdkAuth(authProvider, {
438
+ serverUrl, ...discovery,
439
+ ...(request?.challenge ? { forceReauthorization: isStrictScopeSuperset(discovery.scope, storedAuth?.tokens?.scope) } : {}),
440
+ }), signal);
441
+ throwIfAborted(signal);
442
+ if (result === "AUTHORIZED") {
443
+ authProvider.deactivate();
444
+ releaseCallbackServer(oauthState);
445
+ await clearOAuthState(serverName, authStorageOptions);
446
+ return { authorizationUrl: "" };
447
+ }
448
+ if (!capturedUrl) {
449
+ throw new UnauthorizedError("OAuth authorization URL was not provided");
450
+ }
451
+ await setPendingAuth(runtime, serverName, { serverName, authProvider, serverUrl, authorizationUrl: capturedUrl.toString(), discovery, callbackIssuer: { ...callbackIssuer }, authStorageOptions, ...(request ? { request } : {}) }, oauthState, signal, generation);
452
+ return { authorizationUrl: capturedUrl.toString() };
453
+ }
454
+ catch (error) {
455
+ authProvider?.deactivate();
456
+ try {
457
+ await clearPendingAuth(runtime, serverName, oauthState, authStorageOptions);
458
+ }
459
+ catch (cleanupError) {
460
+ throw new AggregateError([error, cleanupError], "OAuth startup cleanup failed");
461
+ }
462
+ throw error;
463
+ }
464
+ }
465
+ async function setPendingAuth(runtime, serverName, pendingAuth, oauthState, signal, generation = getRuntimeState(runtime).generation) {
466
+ const state = getRuntimeState(runtime);
467
+ const key = getPendingAuthKey(serverName, pendingAuth.authStorageOptions);
468
+ await clearPendingAuth(runtime, serverName, undefined, pendingAuth.authStorageOptions);
469
+ throwIfAborted(signal);
470
+ if (generation !== state.generation)
471
+ throw new Error("OAuth runtime stopped");
472
+ state.pendingAuths.set(key, pendingAuth);
473
+ state.pendingAuthStates.set(key, oauthState);
474
+ const cleanupTimer = setTimeout(() => {
475
+ void clearPendingAuth(runtime, serverName, oauthState, pendingAuth.authStorageOptions).catch(error => {
476
+ console.error(`MCP Auth: Timed-out flow cleanup failed: ${formatTerminalError(error)}`);
477
+ });
478
+ }, MANUAL_AUTH_TIMEOUT_MS);
479
+ cleanupTimer.unref?.();
480
+ state.pendingAuthCleanupTimers.set(key, cleanupTimer);
481
+ }
482
+ function clearPendingAuth(...args) {
483
+ return withOAuthOperation(args[0], () => clearPendingAuthOperation(...args));
484
+ }
485
+ async function clearPendingAuthOperation(runtime, serverName, oauthState, fallbackStorageOptions = {}) {
486
+ const state = getRuntimeState(runtime);
487
+ const key = getPendingAuthKey(serverName, fallbackStorageOptions);
488
+ const pendingAuth = state.pendingAuths.get(key);
489
+ const authStorageOptions = pendingAuth?.authStorageOptions ?? fallbackStorageOptions;
490
+ const pendingState = state.pendingAuthStates.get(key);
491
+ if (oauthState && pendingState && pendingState !== oauthState)
492
+ return;
493
+ const timer = state.pendingAuthCleanupTimers.get(key);
494
+ if (timer) {
495
+ clearTimeout(timer);
496
+ state.pendingAuthCleanupTimers.delete(key);
497
+ }
498
+ pendingAuth?.authProvider.deactivate();
499
+ state.pendingAuths.delete(key);
500
+ state.pendingAuthStates.delete(key);
501
+ const stateToRelease = pendingState ?? oauthState;
502
+ if (stateToRelease) {
503
+ cancelPendingCallback(stateToRelease);
504
+ const storedState = await getOAuthState(serverName, authStorageOptions);
505
+ if (storedState === stateToRelease) {
506
+ await clearOAuthState(serverName, authStorageOptions);
507
+ }
508
+ }
509
+ }
510
+ function getSearchParamsFromInput(input) {
511
+ try {
512
+ const url = new URL(input);
513
+ const params = new URLSearchParams(url.search);
514
+ if (url.hash) {
515
+ const hash = url.hash.startsWith("#") ? url.hash.slice(1) : url.hash;
516
+ const hashParams = new URLSearchParams(hash);
517
+ for (const [key, value] of hashParams) {
518
+ if (!params.has(key))
519
+ params.set(key, value);
520
+ }
521
+ }
522
+ return params;
523
+ }
524
+ catch {
525
+ const query = input.includes("?") ? input.slice(input.indexOf("?") + 1) : input;
526
+ const params = new URLSearchParams(query.startsWith("#") ? query.slice(1) : query);
527
+ return params.has("code") || params.has("state") || params.has("error") ? params : undefined;
528
+ }
529
+ }
530
+ export function parseAuthorizationRedirectInput(input, expectedState) {
531
+ const trimmed = input.trim();
532
+ if (!trimmed) {
533
+ throw new Error("Authorization code or redirect URL is required");
534
+ }
535
+ const params = getSearchParamsFromInput(trimmed);
536
+ if (params) {
537
+ const state = params.get("state");
538
+ if (expectedState && !state) {
539
+ throw new Error("OAuth state missing from redirect URL");
540
+ }
541
+ if (expectedState && state !== expectedState) {
542
+ throw new Error("OAuth state mismatch - potential CSRF attack");
543
+ }
544
+ const error = params.get("error");
545
+ if (error) {
546
+ const description = params.get("error_description");
547
+ const iss = params.get("iss");
548
+ return { error, ...(description !== null ? { errorDescription: description } : {}), ...(iss !== null ? { iss } : {}) };
549
+ }
550
+ const code = params.get("code");
551
+ if (code) {
552
+ const iss = params.get("iss");
553
+ return { code, ...(iss !== null ? { iss } : {}) };
554
+ }
555
+ }
556
+ if (/^[A-Za-z0-9._~+/=-]+$/.test(trimmed)) {
557
+ return { code: trimmed };
558
+ }
559
+ throw new Error("Could not find an OAuth authorization code in the provided input");
560
+ }
561
+ /**
562
+ * Complete OAuth authentication from pasted input or a captured browser callback.
563
+ */
564
+ export async function completeAuthFromInput(serverName, input, options = {}) {
565
+ const runtime = getRuntime(options);
566
+ const runtimeState = getRuntimeState(runtime);
567
+ const fallbackAuthStorageOptions = options.authStorageOptions ?? {};
568
+ const signal = combineAbortSignals(runtime.signal, options.signal);
569
+ throwIfAborted(signal);
570
+ const key = getPendingAuthKey(serverName, fallbackAuthStorageOptions);
571
+ const oauthState = runtimeState.pendingAuthStates.get(key);
572
+ throwIfAborted(signal);
573
+ const parsed = input === undefined ? undefined : parseAuthorizationRedirectInput(input, oauthState);
574
+ return completeAuth(serverName, parsed, options);
575
+ }
576
+ /**
577
+ * Complete OAuth authentication with an explicit code or a captured callback.
578
+ */
579
+ export const completeAuth = async (...args) => withOAuthOperation(getRuntime(args[2]), () => completeAuthOperation(...args));
580
+ async function completeAuthOperation(serverName, authorizationCode, options = {}) {
581
+ const runtime = getRuntime(options);
582
+ const runtimeState = getRuntimeState(runtime);
583
+ const fallbackAuthStorageOptions = options.authStorageOptions ?? {};
584
+ const signal = combineAbortSignals(runtime.signal, options.signal);
585
+ throwIfAborted(signal);
586
+ const key = getPendingAuthKey(serverName, fallbackAuthStorageOptions);
587
+ const pendingAuth = runtimeState.pendingAuths.get(key);
588
+ const authStorageOptions = pendingAuth?.authStorageOptions ?? fallbackAuthStorageOptions;
589
+ if (!pendingAuth) {
590
+ throw new Error(`No pending OAuth flow for server: ${serverName}. Run auth-start for this server first.`);
591
+ }
592
+ const oauthState = runtimeState.pendingAuthStates.get(key);
593
+ throwIfAborted(signal);
594
+ const response = typeof authorizationCode === "string" ? { code: authorizationCode }
595
+ : authorizationCode ?? (oauthState ? takeCallbackResult(oauthState) : undefined);
596
+ if (!response) {
597
+ throw new Error(`No OAuth callback received yet for ${serverName}. Finish authorization in the browser, then retry auth-complete. ` +
598
+ "If the browser cannot reach this Pi session's callback, pass args: { redirectUrl: \"FULL_REDIRECT_URL\" } instead.");
599
+ }
600
+ const { iss } = response;
601
+ let keepPendingForRetry = false;
602
+ let caughtError;
603
+ try {
604
+ keepPendingForRetry = iss === undefined && pendingAuth.callbackIssuer.issParameterSupported === true;
605
+ validateCallbackIssuer(serverName, pendingAuth.callbackIssuer, response);
606
+ if ("error" in response) {
607
+ keepPendingForRetry = true;
608
+ throw new Error(response.errorDescription ? `${response.error}: ${response.errorDescription}` : response.error);
609
+ }
610
+ const result = await abortable(runSdkAuth(pendingAuth.authProvider, {
611
+ serverUrl: pendingAuth.serverUrl,
612
+ authorizationCode: response.code,
613
+ ...(iss !== undefined ? { iss } : {}),
614
+ ...pendingAuth.discovery,
615
+ }), signal);
616
+ throwIfAborted(signal);
617
+ if (result !== "AUTHORIZED") {
618
+ throw new UnauthorizedError("Failed to authorize");
619
+ }
620
+ const request = pendingAuth.request;
621
+ if (request?.challenge?.requiredScope
622
+ && request === getOAuthRequest(serverName, pendingAuth.serverUrl, getAuthBaseDir(authStorageOptions), runtime)) {
623
+ const issuedScope = (await getAuthForUrl(serverName, pendingAuth.serverUrl, authStorageOptions))?.tokens?.scope;
624
+ if (issuedScope !== undefined && !isStrictScopeSuperset(request.challenge.requiredScope, issuedScope))
625
+ delete request.challenge;
626
+ }
627
+ return "authenticated";
628
+ }
629
+ catch (error) {
630
+ caughtError = error;
631
+ throw error;
632
+ }
633
+ finally {
634
+ if (!keepPendingForRetry) {
635
+ try {
636
+ await clearPendingAuth(runtime, serverName, oauthState, authStorageOptions);
637
+ }
638
+ catch (cleanupError) {
639
+ if (caughtError !== undefined) {
640
+ throw new AggregateError([caughtError, cleanupError], "OAuth completion cleanup failed");
641
+ }
642
+ throw cleanupError;
643
+ }
644
+ }
645
+ }
646
+ }
647
+ /**
648
+ * Perform the complete OAuth authentication flow for a server.
649
+ *
650
+ * @param serverName - The name of the MCP server
651
+ * @param serverUrl - The URL of the MCP server
652
+ * @param definition - The server definition (optional)
653
+ * @returns The final auth status
654
+ */
655
+ export async function authenticate(serverName, serverUrl, definition, options = {}) {
656
+ if (isServerDisabled(definition))
657
+ throw new Error(`MCP server "${serverName}" is disabled`);
658
+ const runtime = getRuntime(options);
659
+ const runtimeState = getRuntimeState(runtime);
660
+ const authStorageOptions = options.authStorageOptions ?? {};
661
+ const signal = combineAbortSignals(runtime.signal, options.signal);
662
+ throwIfAborted(signal);
663
+ const authKey = JSON.stringify([serverName, serverUrl, getAuthBaseDir(authStorageOptions)]);
664
+ const inFlight = runtimeState.pendingAuthentications.get(authKey);
665
+ if (inFlight) {
666
+ return inFlight;
667
+ }
668
+ const operation = (async () => {
669
+ // Start auth flow
670
+ const { authorizationUrl } = await startAuth(serverName, serverUrl, definition, {
671
+ ...options,
672
+ ...(signal ? { signal } : {}),
673
+ runtime,
674
+ });
675
+ // If no auth URL needed, already authenticated
676
+ if (!authorizationUrl) {
677
+ return "authenticated";
678
+ }
679
+ let oauthState;
680
+ try {
681
+ // Get the state that was already generated and stored in startAuth().
682
+ // Keep this lookup and its abort check inside the cleanup boundary because
683
+ // startAuth has already reserved callback state at this point.
684
+ oauthState = runtimeState.pendingAuthStates.get(getPendingAuthKey(serverName, authStorageOptions));
685
+ throwIfAborted(signal);
686
+ if (!oauthState) {
687
+ throw new Error("OAuth state not found - this should not happen");
688
+ }
689
+ // Register the callback BEFORE opening the browser.
690
+ const callbackPromise = waitForCallback(oauthState);
691
+ void callbackPromise.catch(() => { });
692
+ // Open browser. Always surface the URL first so remote/headless users can copy it
693
+ // even when the OS browser handoff is unavailable or invisible.
694
+ if (options.onAuthorizationUrl) {
695
+ await abortable(Promise.resolve(options.onAuthorizationUrl(authorizationUrl)), signal);
696
+ }
697
+ else {
698
+ console.log(`MCP Auth: Open this URL to authenticate ${serverName}:\n${authorizationUrl}`);
699
+ }
700
+ try {
701
+ await abortable(open(authorizationUrl), signal);
702
+ }
703
+ catch (error) {
704
+ if (isAbortError(error, signal))
705
+ throw error;
706
+ console.warn(`MCP Auth: Failed to open browser for ${serverName}; waiting for manual callback`, { error });
707
+ }
708
+ // Wait for callback
709
+ const callbackResult = await abortable(callbackPromise, signal);
710
+ // The callback server accepted only the flow-local reserved state.
711
+ throwIfAborted(signal);
712
+ // Complete the auth
713
+ return await completeAuth(serverName, callbackResult, {
714
+ ...options,
715
+ ...(signal ? { signal } : {}),
716
+ runtime,
717
+ });
718
+ }
719
+ catch (error) {
720
+ if (oauthState)
721
+ cancelPendingCallback(oauthState);
722
+ try {
723
+ await clearPendingAuth(runtime, serverName, oauthState, authStorageOptions);
724
+ }
725
+ catch (cleanupError) {
726
+ throw new AggregateError([error, cleanupError], "OAuth cancellation cleanup failed");
727
+ }
728
+ throw error;
729
+ }
730
+ })();
731
+ runtimeState.pendingAuthentications.set(authKey, operation);
732
+ try {
733
+ return await operation;
734
+ }
735
+ finally {
736
+ if (runtimeState.pendingAuthentications.get(authKey) === operation) {
737
+ runtimeState.pendingAuthentications.delete(authKey);
738
+ }
739
+ }
740
+ }
741
+ /**
742
+ * Remove all OAuth credentials for a server.
743
+ *
744
+ * @param serverName - The name of the MCP server
745
+ */
746
+ export const removeAuth = async (...args) => withOAuthOperation(getRuntime(args[1]), () => removeAuthOperation(...args));
747
+ async function removeAuthOperation(serverName, options = {}) {
748
+ const runtime = getRuntime(options);
749
+ const signal = combineAbortSignals(runtime.signal, options.signal);
750
+ throwIfAborted(signal);
751
+ const authStorageOptions = options.authStorageOptions ?? {};
752
+ const oauthState = await getOAuthState(serverName, authStorageOptions);
753
+ throwIfAborted(signal);
754
+ if (oauthState) {
755
+ cancelPendingCallback(oauthState);
756
+ }
757
+ await clearPendingAuth(runtime, serverName, oauthState, authStorageOptions);
758
+ throwIfAborted(signal);
759
+ for (const [key, request] of getRuntimeState(runtime).requests) {
760
+ if (request.serverName === serverName)
761
+ getRuntimeState(runtime).requests.delete(key);
762
+ }
763
+ clearAllCredentials(serverName, authStorageOptions);
764
+ await clearOAuthState(serverName, authStorageOptions);
765
+ throwIfAborted(signal);
766
+ console.log(`MCP Auth: Removed credentials for ${serverName}`);
767
+ }
768
+ /**
769
+ * Check if OAuth is supported for a server configuration.
770
+ * OAuth is supported for HTTP servers unless explicitly disabled.
771
+ *
772
+ * @param definition - The server definition
773
+ * @returns True if OAuth is supported
774
+ */
775
+ export function supportsOAuth(definition) {
776
+ // OAuth requires a URL
777
+ if (!definition.url)
778
+ return false;
779
+ // Explicitly disabled via auth: false or oauth: false
780
+ if (definition.auth === false)
781
+ return false;
782
+ if (definition.oauth === false)
783
+ return false;
784
+ if (definition.auth === "oauth")
785
+ return true;
786
+ // Configured custom headers take precedence over implicit OAuth auto-detection.
787
+ if (definition.headers && Object.keys(definition.headers).length > 0)
788
+ return false;
789
+ // OAuth is enabled when auth is not specified (auto-detect)
790
+ return definition.auth === undefined;
791
+ }
792
+ /**
793
+ * Initialize the OAuth system on startup.
794
+ * OAuth callback binding is lazy and starts from startAuth() only.
795
+ */
796
+ export async function initializeOAuth(runtimeOrSignal) {
797
+ if (runtimeOrSignal && "signal" in runtimeOrSignal) {
798
+ runtimeOrSignal.signal.throwIfAborted();
799
+ activeRuntimes.add(runtimeOrSignal);
800
+ return runtimeOrSignal;
801
+ }
802
+ await shutdownOAuth(legacyRuntime);
803
+ legacyRuntime = createOAuthRuntime(runtimeOrSignal);
804
+ return legacyRuntime;
805
+ }
806
+ /**
807
+ * Shutdown one OAuth runtime. The callback server remains process-shared while
808
+ * another runtime has pending/reserved callback state or is still active.
809
+ */
810
+ export async function shutdownOAuth(runtime = legacyRuntime) {
811
+ const state = getRuntimeState(runtime);
812
+ if (state.controller.signal.aborted)
813
+ return;
814
+ state.checkpoint?.invalidate();
815
+ state.generation += 1;
816
+ state.controller.abort(new Error("OAuth runtime stopped"));
817
+ for (const callbackState of Array.from(state.pendingAuthStates.values()))
818
+ cancelPendingCallback(callbackState);
819
+ const results = await Promise.allSettled(Array.from(state.pendingAuths.values(), pendingAuth => clearPendingAuth(runtime, pendingAuth.serverName, undefined, pendingAuth.authStorageOptions)));
820
+ const failures = results.flatMap(result => result.status === "rejected" ? [result.reason] : []);
821
+ state.pendingAuthentications.clear();
822
+ state.requests.clear();
823
+ activeRuntimes.delete(runtime);
824
+ if (activeRuntimes.size === 0) {
825
+ try {
826
+ await stopCallbackServer();
827
+ }
828
+ catch (error) {
829
+ failures.push(error);
830
+ }
831
+ }
832
+ if (failures.length)
833
+ throw new AggregateError(failures, "MCP OAuth cleanup failed");
834
+ }