@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,689 @@
1
+ /**
2
+ * MCP OAuth Provider
3
+ *
4
+ * Implementation of the MCP SDK's OAuthClientProvider interface.
5
+ * Handles OAuth client registration, token storage, and authorization redirection.
6
+ */
7
+ import { UnauthorizedError, } from "@modelcontextprotocol/client";
8
+ import { getAuthForUrl, updateTokens, updateClientInfo, clearAllCredentials, clearCodeVerifier, invalidateAuthEntryCache, captureOAuthAuthority, } from "./mcp-auth.js";
9
+ import { OAuthMetadataSchema, OpenIdProviderDiscoveryMetadataSchema } from "@modelcontextprotocol/core";
10
+ import { createOAuthFetch } from "./mcp-auth-fetch.js";
11
+ import { resolveCommandSecret } from "./utils.js";
12
+ import { getAppClientUri, getAppName } from "./agent-dir.js";
13
+ /**
14
+ * Client name advertised during Dynamic Client Registration.
15
+ *
16
+ * A distribution that rebrands pi (arc, tau, …) should register under its own
17
+ * name — otherwise every consent screen its users see asks them to authorize
18
+ * an app they have never run. Stock pi keeps the long-standing
19
+ * "Pi Coding Agent" so existing registrations are unaffected.
20
+ */
21
+ function defaultClientName() {
22
+ const app = getAppName();
23
+ return app === "pi" ? "Pi Coding Agent" : app;
24
+ }
25
+ /**
26
+ * Client homepage advertised during Dynamic Client Registration.
27
+ *
28
+ * RFC 7591 defines client_uri as the home page *of the client*. Under a
29
+ * rebranded pi the client is that distribution, not this adapter, so pointing
30
+ * at the adapter's repository misidentifies it on the consent screen. There is
31
+ * no way to guess the right URL and a wrong one is worse than none, so the
32
+ * field is omitted unless a server config supplies oauth.clientUri.
33
+ *
34
+ * Stock pi keeps the historical value.
35
+ */
36
+ function defaultClientUri() {
37
+ const declared = getAppClientUri();
38
+ if (declared)
39
+ return declared;
40
+ return getAppName() === "pi" ? "https://github.com/nicobailon/pi-mcp-adapter" : undefined;
41
+ }
42
+ function issuersMatch(first, second) {
43
+ return first === second
44
+ || (first.endsWith("/") && first.slice(0, -1) === second)
45
+ || (second.endsWith("/") && second.slice(0, -1) === first);
46
+ }
47
+ function toOAuthTokens(tokens) {
48
+ const result = {
49
+ access_token: tokens.accessToken,
50
+ token_type: "Bearer",
51
+ };
52
+ if (tokens.refreshToken !== undefined)
53
+ result.refresh_token = tokens.refreshToken;
54
+ if (tokens.expiresAt !== undefined)
55
+ result.expires_in = Math.max(0, Math.floor(tokens.expiresAt - Date.now() / 1000));
56
+ if (tokens.scope !== undefined)
57
+ result.scope = tokens.scope;
58
+ if (tokens.issuer !== undefined)
59
+ result.issuer = tokens.issuer;
60
+ return result;
61
+ }
62
+ // Callback server configuration
63
+ const DEFAULT_OAUTH_CALLBACK_PORT = 19876;
64
+ const DEFAULT_OAUTH_CALLBACK_PATH = "/callback";
65
+ let configuredOAuthCallbackPort = DEFAULT_OAUTH_CALLBACK_PORT;
66
+ if (process.env.MCP_OAUTH_CALLBACK_PORT) {
67
+ const parsedPort = Number.parseInt(process.env.MCP_OAUTH_CALLBACK_PORT, 10);
68
+ if (Number.isInteger(parsedPort) && parsedPort > 0 && parsedPort <= 65535) {
69
+ configuredOAuthCallbackPort = parsedPort;
70
+ }
71
+ }
72
+ let oauthCallbackPort = configuredOAuthCallbackPort;
73
+ let oauthCallbackPath = DEFAULT_OAUTH_CALLBACK_PATH;
74
+ export function getConfiguredOAuthCallbackPort() {
75
+ return configuredOAuthCallbackPort;
76
+ }
77
+ export function getOAuthCallbackPort() {
78
+ return oauthCallbackPort;
79
+ }
80
+ export function setOAuthCallbackPort(port) {
81
+ oauthCallbackPort = port;
82
+ }
83
+ export function getOAuthCallbackPath() {
84
+ return oauthCallbackPath;
85
+ }
86
+ export function setOAuthCallbackPath(path) {
87
+ oauthCallbackPath = path.startsWith("/") ? path : `/${path}`;
88
+ }
89
+ const reservedAuthorizationParams = new Set([
90
+ "client_id",
91
+ "code_challenge",
92
+ "code_challenge_method",
93
+ "redirect_uri",
94
+ "resource",
95
+ "response_type",
96
+ "scope",
97
+ "state",
98
+ ]);
99
+ function addAuthorizationParams(authorizationUrl, params) {
100
+ if (!params)
101
+ return authorizationUrl;
102
+ const nextUrl = new URL(authorizationUrl.toString());
103
+ for (const [key, value] of Object.entries(params)) {
104
+ if (reservedAuthorizationParams.has(key) || nextUrl.searchParams.has(key)) {
105
+ throw new Error(`OAuth authorizationParams.${key} cannot override an authorization flow parameter`);
106
+ }
107
+ nextUrl.searchParams.set(key, value);
108
+ }
109
+ return nextUrl;
110
+ }
111
+ function inferIssuerFromMetadataUrl(metadataUrl) {
112
+ const url = new URL(metadataUrl);
113
+ const pathname = url.pathname.replace(/\/+$/, "") || "/";
114
+ const oauthPrefix = "/.well-known/oauth-authorization-server";
115
+ if (pathname === oauthPrefix || pathname.startsWith(`${oauthPrefix}/`)) {
116
+ const issuerPath = pathname.slice(oauthPrefix.length) || "/";
117
+ return new URL(issuerPath, url.origin).toString();
118
+ }
119
+ const oidcPath = "/.well-known/openid-configuration";
120
+ if (pathname === oidcPath || pathname.startsWith(`${oidcPath}/`)) {
121
+ const issuerPath = pathname.slice(oidcPath.length) || "/";
122
+ return new URL(issuerPath, url.origin).toString();
123
+ }
124
+ if (pathname.endsWith(oidcPath)) {
125
+ const issuerPath = pathname.slice(0, -oidcPath.length) || "/";
126
+ return new URL(issuerPath, url.origin).toString();
127
+ }
128
+ return undefined;
129
+ }
130
+ function validateConfiguredIssuer(metadataUrl, issuer, skipIssuerValidation) {
131
+ let parsedIssuer;
132
+ try {
133
+ parsedIssuer = new URL(issuer);
134
+ }
135
+ catch (error) {
136
+ throw new Error("OAuth authorization-server metadata issuer must be an absolute URL", { cause: error });
137
+ }
138
+ if (parsedIssuer.protocol !== "http:" && parsedIssuer.protocol !== "https:") {
139
+ throw new Error("OAuth authorization-server metadata issuer must use http:// or https://");
140
+ }
141
+ const expectedIssuer = inferIssuerFromMetadataUrl(metadataUrl);
142
+ if (skipIssuerValidation)
143
+ return;
144
+ if (expectedIssuer !== undefined && !issuersMatch(expectedIssuer, issuer)) {
145
+ throw new Error(`OAuth authorization-server metadata issuer does not match authServerMetadataUrl: expected ${expectedIssuer}`);
146
+ }
147
+ if (expectedIssuer === undefined && !issuersMatch(new URL(metadataUrl).origin, issuer)) {
148
+ throw new Error(`OAuth authorization-server metadata issuer does not match authServerMetadataUrl origin: expected ${new URL(metadataUrl).origin}`);
149
+ }
150
+ }
151
+ async function loadConfiguredDiscoveryState(metadataUrl, serverUrl, skipIssuerValidation, fetchFn) {
152
+ const response = await fetchFn(metadataUrl, {
153
+ headers: { accept: "application/json" },
154
+ });
155
+ if (!response.ok) {
156
+ await response.text().catch(() => { });
157
+ throw new Error(`OAuth authServerMetadataUrl request failed with HTTP ${response.status}`);
158
+ }
159
+ const payload = await response.json();
160
+ const oauthResult = OAuthMetadataSchema.safeParse(payload);
161
+ const metadata = oauthResult.success
162
+ ? oauthResult.data
163
+ : OpenIdProviderDiscoveryMetadataSchema.parse(payload);
164
+ validateConfiguredIssuer(metadataUrl, metadata.issuer, skipIssuerValidation);
165
+ const resource = new URL(serverUrl);
166
+ resource.hash = "";
167
+ return {
168
+ authorizationServerUrl: metadata.issuer,
169
+ authorizationServerMetadata: metadata,
170
+ // The configured AS document is authoritative, so avoid a second PRM
171
+ // lookup while still binding the token request to the configured resource.
172
+ resourceMetadata: { resource: resource.toString() },
173
+ };
174
+ }
175
+ /**
176
+ * OAuth provider implementation for MCP servers.
177
+ * Implements the OAuthClientProvider interface from the MCP SDK.
178
+ */
179
+ export class McpOAuthProvider {
180
+ serverName;
181
+ serverUrl;
182
+ config;
183
+ callbacks;
184
+ storageOptions;
185
+ runtimeSignal;
186
+ clientMetadataUrl;
187
+ redirectUrlSnapshot;
188
+ authFetch;
189
+ active = true;
190
+ flowClientInfo;
191
+ flowCodeVerifier;
192
+ flowDiscoveryState;
193
+ flowIssuerMismatch = false;
194
+ flowState;
195
+ invalidatedAccessToken;
196
+ invalidatedClientId;
197
+ staleRedirectClientId;
198
+ lastObservedClientId;
199
+ lastSavedAccessToken;
200
+ pendingAuthAccessToken;
201
+ assertAuthority;
202
+ constructor(serverName, serverUrl, config, callbacks, storageOptions = {}, runtimeSignal, initialState, authority) {
203
+ this.serverName = serverName;
204
+ this.serverUrl = serverUrl;
205
+ this.config = config;
206
+ this.callbacks = callbacks;
207
+ this.storageOptions = storageOptions;
208
+ this.runtimeSignal = runtimeSignal;
209
+ this.assertAuthority = authority ?? captureOAuthAuthority(serverName);
210
+ this.assertAuthority();
211
+ if (config.clientId === undefined && config.clientMetadataUrl !== undefined) {
212
+ this.clientMetadataUrl = config.clientMetadataUrl;
213
+ }
214
+ this.authFetch = createOAuthFetch(serverUrl, undefined, runtimeSignal);
215
+ this.flowState = initialState;
216
+ this.redirectUrlSnapshot = config.grantType === "client_credentials"
217
+ ? undefined
218
+ : config.redirectUri ?? `http://localhost:${getOAuthCallbackPort()}${getOAuthCallbackPath()}`;
219
+ }
220
+ setAuthFetch(fetchFn) {
221
+ this.authFetch = fetchFn;
222
+ }
223
+ get usesClientCredentials() {
224
+ return this.config.grantType === "client_credentials";
225
+ }
226
+ get discoveredIssuer() {
227
+ return this.flowDiscoveryState?.authorizationServerMetadata?.issuer
228
+ ?? this.flowDiscoveryState?.authorizationServerUrl;
229
+ }
230
+ deactivate() {
231
+ this.active = false;
232
+ this.invalidatedAccessToken = undefined;
233
+ this.invalidatedClientId = undefined;
234
+ this.staleRedirectClientId = undefined;
235
+ this.lastObservedClientId = undefined;
236
+ this.lastSavedAccessToken = undefined;
237
+ this.pendingAuthAccessToken = undefined;
238
+ }
239
+ assertStoredIssuerBindings(entry, issuer) {
240
+ if (this.flowIssuerMismatch) {
241
+ throw new Error(`OAuth authorization server issuer changed for ${this.serverName}; clear credentials before authenticating again`);
242
+ }
243
+ if (!entry || !issuer)
244
+ return;
245
+ const storedIssuers = [entry.clientInfo?.issuer, entry.tokens?.issuer]
246
+ .filter((storedIssuer) => storedIssuer !== undefined);
247
+ if (storedIssuers.some(storedIssuer => !issuersMatch(storedIssuer, issuer))) {
248
+ this.flowIssuerMismatch = true;
249
+ throw new Error(`OAuth authorization server issuer changed for ${this.serverName}; clear credentials before authenticating again`);
250
+ }
251
+ }
252
+ throwIfInactive() {
253
+ if (!this.active)
254
+ throw new Error("OAuth flow is no longer active");
255
+ this.assertAuthority();
256
+ this.runtimeSignal?.throwIfAborted();
257
+ // The SDK can swallow refresh fetch errors and attempt browser authorization.
258
+ // A failed service credential must stop that fallback and token persistence.
259
+ this.authFetch.throwIfHeaderResolutionFailed();
260
+ }
261
+ /**
262
+ * The redirect URL for OAuth callbacks.
263
+ * This must match the redirect_uri in client metadata.
264
+ */
265
+ get redirectUrl() {
266
+ return this.redirectUrlSnapshot;
267
+ }
268
+ /** Configured homepage, else the historical default on stock pi, else nothing. */
269
+ get clientUri() {
270
+ return this.config.clientUri ?? defaultClientUri();
271
+ }
272
+ /**
273
+ * Client metadata for dynamic registration.
274
+ * Describes this client to the OAuth authorization server.
275
+ */
276
+ get clientMetadata() {
277
+ if (this.usesClientCredentials) {
278
+ return {
279
+ client_name: this.config.clientName ?? defaultClientName(),
280
+ ...(this.clientUri !== undefined ? { client_uri: this.clientUri } : {}),
281
+ ...(this.config.logoUri !== undefined ? { logo_uri: this.config.logoUri } : {}),
282
+ redirect_uris: [],
283
+ grant_types: ["client_credentials"],
284
+ token_endpoint_auth_method: this.config.clientSecret ? "client_secret_post" : "none",
285
+ };
286
+ }
287
+ const redirectUrl = this.redirectUrl;
288
+ if (!redirectUrl) {
289
+ throw new Error("redirectUrl is required for authorization_code flow");
290
+ }
291
+ return {
292
+ redirect_uris: [redirectUrl],
293
+ client_name: this.config.clientName ?? defaultClientName(),
294
+ ...(this.clientUri !== undefined ? { client_uri: this.clientUri } : {}),
295
+ ...(this.config.logoUri !== undefined ? { logo_uri: this.config.logoUri } : {}),
296
+ grant_types: ["authorization_code", "refresh_token"],
297
+ response_types: ["code"],
298
+ token_endpoint_auth_method: this.config.clientSecret ? "client_secret_post" : "none",
299
+ ...(this.config.scope !== undefined ? { scope: this.config.scope } : {}),
300
+ };
301
+ }
302
+ /**
303
+ * Get client information (for pre-registered or dynamically registered clients).
304
+ * Returns undefined if no client info exists or if the server URL has changed.
305
+ */
306
+ async clientInformation() {
307
+ this.throwIfInactive();
308
+ if (this.invalidatedClientId !== undefined) {
309
+ invalidateAuthEntryCache(this.serverName);
310
+ }
311
+ const issuer = this.discoveredIssuer;
312
+ const stored = await getAuthForUrl(this.serverName, this.serverUrl, this.storageOptions);
313
+ this.throwIfInactive();
314
+ this.assertStoredIssuerBindings(stored, issuer);
315
+ // Check config first (pre-registered client). Store only its issuer binding.
316
+ // The configured secret stays in config and never enters the credential store.
317
+ if (this.config.clientId) {
318
+ const storedClient = stored?.clientInfo?.clientId === this.config.clientId
319
+ ? stored.clientInfo
320
+ : undefined;
321
+ if (issuer && (storedClient?.issuer !== issuer || storedClient.configPreRegistered !== true)) {
322
+ this.throwIfInactive();
323
+ updateClientInfo(this.serverName, { clientId: this.config.clientId, issuer, configPreRegistered: true }, this.serverUrl, this.storageOptions);
324
+ }
325
+ const clientSecret = this.config.clientSecret?.startsWith("!")
326
+ ? resolveCommandSecret(this.config.clientSecret, `MCP server "${this.serverName}" OAuth clientSecret`)
327
+ : this.config.clientSecret;
328
+ return {
329
+ client_id: this.config.clientId,
330
+ client_secret: clientSecret,
331
+ ...(issuer !== undefined ? { issuer } : {}),
332
+ };
333
+ }
334
+ // Keep client registration associated with this in-flight flow even if
335
+ // another runtime writes the shared persistent entry for the same name.
336
+ const clientInfo = this.flowClientInfo ?? stored?.clientInfo;
337
+ if (clientInfo?.clientId === this.invalidatedClientId)
338
+ return undefined;
339
+ const clientMetadataUrl = this.clientMetadataUrl;
340
+ const supportsClientMetadataDocument = this.flowDiscoveryState
341
+ ?.authorizationServerMetadata?.client_id_metadata_document_supported;
342
+ if (clientMetadataUrl !== undefined && supportsClientMetadataDocument !== undefined) {
343
+ if (supportsClientMetadataDocument === true
344
+ && clientInfo?.clientId !== clientMetadataUrl
345
+ && (stored?.tokens?.refreshToken === undefined || this.invalidatedAccessToken !== undefined)) {
346
+ // With no DCR refresh pair to preserve, let the SDK select CIMD now.
347
+ return undefined;
348
+ }
349
+ if (supportsClientMetadataDocument !== true && clientInfo?.clientId === clientMetadataUrl) {
350
+ return undefined;
351
+ }
352
+ }
353
+ if (clientInfo) {
354
+ this.invalidatedClientId = undefined;
355
+ // A stored SEP-2352 issuer stub for a config-pre-registered client
356
+ // (identified by the explicit marker, or by the legacy stub shape of
357
+ // {clientId, issuer} with no registration metadata) is only meaningful
358
+ // when the config supplies the matching client secret. Since we reach
359
+ // this branch only when config.clientId is absent, serving the stub
360
+ // would let a token refresh go out with a client_id but no secret,
361
+ // causing invalid_client and credential invalidation. Return undefined
362
+ // so callers treat this as "no client info".
363
+ const isConfiguredCimd = clientMetadataUrl !== undefined
364
+ && clientInfo.clientId === clientMetadataUrl;
365
+ const isConfigStub = clientInfo.configPreRegistered === true
366
+ || (clientInfo.clientSecret === undefined
367
+ && clientInfo.clientIdIssuedAt === undefined
368
+ && clientInfo.clientSecretExpiresAt === undefined
369
+ && clientInfo.redirectUris === undefined);
370
+ if (isConfigStub && !isConfiguredCimd) {
371
+ return undefined;
372
+ }
373
+ // Check if client secret has expired
374
+ if (clientInfo.clientSecretExpiresAt && clientInfo.clientSecretExpiresAt < Date.now() / 1000) {
375
+ return undefined;
376
+ }
377
+ if (issuer && clientInfo.issuer && !issuersMatch(clientInfo.issuer, issuer)) {
378
+ return undefined;
379
+ }
380
+ if (issuer && clientInfo.issuer === undefined) {
381
+ clientInfo.issuer = issuer;
382
+ this.flowClientInfo = clientInfo;
383
+ this.throwIfInactive();
384
+ updateClientInfo(this.serverName, clientInfo, this.serverUrl, this.storageOptions);
385
+ }
386
+ // Keep a stale dynamic registration available for its refresh attempt,
387
+ // but suppress it if that attempt invalidates the token and auth falls
388
+ // back to an interactive flow. The next clientInformation() call then
389
+ // makes the SDK register the current callback URI.
390
+ const redirectUriIsStale = this.redirectUrl !== undefined
391
+ && (!Array.isArray(clientInfo.redirectUris) || !clientInfo.redirectUris.includes(this.redirectUrl));
392
+ this.staleRedirectClientId = redirectUriIsStale ? clientInfo.clientId : undefined;
393
+ // Return all registration metadata and the local issuer extension.
394
+ // This keeps the SDK OAuth view and the stored issuer binding consistent.
395
+ this.lastObservedClientId = clientInfo.clientId;
396
+ return {
397
+ client_id: clientInfo.clientId,
398
+ client_secret: clientInfo.clientSecret,
399
+ ...(clientInfo.clientIdIssuedAt !== undefined
400
+ ? { client_id_issued_at: clientInfo.clientIdIssuedAt }
401
+ : {}),
402
+ ...(clientInfo.clientSecretExpiresAt !== undefined
403
+ ? { client_secret_expires_at: clientInfo.clientSecretExpiresAt }
404
+ : {}),
405
+ ...(clientInfo.redirectUris !== undefined
406
+ ? { redirect_uris: clientInfo.redirectUris }
407
+ : {}),
408
+ ...(clientInfo.issuer !== undefined ? { issuer: clientInfo.issuer } : {}),
409
+ };
410
+ }
411
+ // No client info or URL changed - will trigger dynamic registration
412
+ return undefined;
413
+ }
414
+ /**
415
+ * Save client information from dynamic registration.
416
+ */
417
+ async saveClientInformation(info) {
418
+ this.throwIfInactive();
419
+ const issuer = this.discoveredIssuer ?? info.issuer;
420
+ if (this.config.clientId && info.client_id === this.config.clientId) {
421
+ updateClientInfo(this.serverName, {
422
+ clientId: info.client_id,
423
+ ...(issuer !== undefined ? { issuer } : {}),
424
+ configPreRegistered: true,
425
+ }, this.serverUrl, this.storageOptions);
426
+ return;
427
+ }
428
+ const redirectUris = ("redirect_uris" in info ? info.redirect_uris : undefined)
429
+ ?? (this.redirectUrl ? [this.redirectUrl] : undefined);
430
+ const clientInfo = {
431
+ clientId: info.client_id,
432
+ ...(info.client_secret !== undefined ? { clientSecret: info.client_secret } : {}),
433
+ ...(info.client_id_issued_at !== undefined ? { clientIdIssuedAt: info.client_id_issued_at } : {}),
434
+ ...(info.client_secret_expires_at !== undefined ? { clientSecretExpiresAt: info.client_secret_expires_at } : {}),
435
+ ...(redirectUris !== undefined ? { redirectUris } : {}),
436
+ ...(issuer !== undefined ? { issuer } : {}),
437
+ };
438
+ this.flowClientInfo = clientInfo;
439
+ this.invalidatedClientId = undefined;
440
+ this.lastObservedClientId = clientInfo.clientId;
441
+ updateClientInfo(this.serverName, clientInfo, this.serverUrl, this.storageOptions);
442
+ }
443
+ /**
444
+ * Get stored OAuth tokens.
445
+ * Returns undefined if no tokens exist or if the server URL has changed.
446
+ */
447
+ async tokens(ctx) {
448
+ this.throwIfInactive();
449
+ // Once this provider rejects a token, bypass its process-local cache until
450
+ // another process replaces that token in shared secure storage.
451
+ if (this.invalidatedAccessToken !== undefined) {
452
+ invalidateAuthEntryCache(this.serverName);
453
+ }
454
+ // Use getAuthForUrl to validate tokens are for the current server URL.
455
+ const entry = await getAuthForUrl(this.serverName, this.serverUrl, this.storageOptions);
456
+ this.throwIfInactive();
457
+ if (!entry?.tokens || entry.tokens.accessToken === this.invalidatedAccessToken)
458
+ return undefined;
459
+ this.invalidatedAccessToken = undefined;
460
+ const issuer = this.discoveredIssuer;
461
+ this.assertStoredIssuerBindings(entry, issuer);
462
+ if (issuer && entry.tokens.issuer === undefined) {
463
+ entry.tokens.issuer = issuer;
464
+ this.throwIfInactive();
465
+ updateTokens(this.serverName, entry.tokens, this.serverUrl, this.storageOptions);
466
+ }
467
+ if (ctx !== undefined) {
468
+ this.pendingAuthAccessToken = entry.tokens.accessToken;
469
+ }
470
+ return toOAuthTokens(entry.tokens);
471
+ }
472
+ /**
473
+ * Save OAuth tokens.
474
+ */
475
+ async saveTokens(tokens) {
476
+ const issuer = this.discoveredIssuer ?? tokens.issuer;
477
+ const storedTokens = {
478
+ accessToken: tokens.access_token,
479
+ ...(tokens.refresh_token !== undefined ? { refreshToken: tokens.refresh_token } : {}),
480
+ // Preserve expiry even when expires_in is 0 (e.g. the SDK re-saving an
481
+ // already-expired token) so expired tokens stay expired instead of
482
+ // being persisted as never-expiring.
483
+ ...(tokens.expires_in !== undefined ? { expiresAt: Date.now() / 1000 + tokens.expires_in } : {}),
484
+ ...(tokens.scope !== undefined ? { scope: tokens.scope } : {}),
485
+ ...(issuer !== undefined ? { issuer } : {}),
486
+ };
487
+ this.throwIfInactive();
488
+ updateTokens(this.serverName, storedTokens, this.serverUrl, this.storageOptions);
489
+ this.invalidatedAccessToken = undefined;
490
+ this.lastSavedAccessToken = storedTokens.accessToken;
491
+ // Discovery must survive the browser redirect so the callback can verify
492
+ // the authorization server that minted the code. Once token issuance
493
+ // succeeds, clear it so a later 401 re-reads PRM and can observe an
494
+ // authorization-server migration.
495
+ this.flowDiscoveryState = undefined;
496
+ }
497
+ /**
498
+ * Redirect the user to the authorization URL.
499
+ * This opens the browser for the user to authenticate.
500
+ *
501
+ * Throws UnauthorizedError when called outside of a user-initiated flow
502
+ * (no oauthState saved by startAuth). That path is reached when the SDK
503
+ * falls through from a failed refresh into a fresh authorization_code
504
+ * flow, which library hosts cannot complete in-process.
505
+ */
506
+ async redirectToAuthorization(authorizationUrl) {
507
+ if (this.usesClientCredentials) {
508
+ throw new Error("redirectToAuthorization is not used for client_credentials flow");
509
+ }
510
+ // No flow-local state means we're on the post-refresh authorize fallback.
511
+ this.throwIfInactive();
512
+ if (!this.flowState) {
513
+ throw new UnauthorizedError(`Re-authentication required for MCP server: ${this.serverName}`);
514
+ }
515
+ // URL is passed to callback, not logged (may contain sensitive params)
516
+ await this.callbacks.onRedirect(addAuthorizationParams(authorizationUrl, this.config.authorizationParams));
517
+ }
518
+ /**
519
+ * Save the PKCE code verifier.
520
+ */
521
+ async saveCodeVerifier(codeVerifier) {
522
+ this.throwIfInactive();
523
+ this.flowCodeVerifier = codeVerifier;
524
+ }
525
+ /**
526
+ * Get the stored PKCE code verifier.
527
+ * @throws Error if no code verifier is stored
528
+ */
529
+ async codeVerifier() {
530
+ if (this.usesClientCredentials) {
531
+ throw new Error("codeVerifier is not used for client_credentials flow");
532
+ }
533
+ this.throwIfInactive();
534
+ if (!this.flowCodeVerifier) {
535
+ throw new Error(`No code verifier saved for MCP server: ${this.serverName}`);
536
+ }
537
+ return this.flowCodeVerifier;
538
+ }
539
+ /**
540
+ * Keep discovery with the in-flight PKCE verifier. The callback leg uses it
541
+ * to validate the authorization response issuer before token exchange.
542
+ */
543
+ async saveDiscoveryState(state) {
544
+ this.throwIfInactive();
545
+ this.flowDiscoveryState = structuredClone(state);
546
+ }
547
+ async discoveryState() {
548
+ this.throwIfInactive();
549
+ if (!this.flowDiscoveryState && this.config.authServerMetadataUrl !== undefined) {
550
+ const discoveryState = await loadConfiguredDiscoveryState(this.config.authServerMetadataUrl, this.serverUrl, this.config.skipIssuerMetadataValidation === true, this.authFetch);
551
+ this.throwIfInactive();
552
+ this.flowDiscoveryState = discoveryState;
553
+ }
554
+ this.throwIfInactive();
555
+ return this.flowDiscoveryState ? structuredClone(this.flowDiscoveryState) : undefined;
556
+ }
557
+ /** Internal connection-attempt identity check for manager cleanup. */
558
+ /**
559
+ * Save the OAuth state parameter for CSRF protection.
560
+ */
561
+ async saveState(state) {
562
+ this.throwIfInactive();
563
+ this.flowState = state;
564
+ }
565
+ /**
566
+ * Get the stored OAuth state parameter.
567
+ * @throws UnauthorizedError if no flow is in progress (see redirectToAuthorization)
568
+ */
569
+ async state() {
570
+ if (this.usesClientCredentials) {
571
+ throw new Error("state is not used for client_credentials flow");
572
+ }
573
+ this.throwIfInactive();
574
+ if (!this.flowState) {
575
+ throw new UnauthorizedError(`Re-authentication required for MCP server: ${this.serverName}`);
576
+ }
577
+ return this.flowState;
578
+ }
579
+ /**
580
+ * Invalidate credentials when authentication fails.
581
+ * Clears tokens, client info, or all credentials based on the type.
582
+ */
583
+ async invalidateCredentials(type) {
584
+ this.throwIfInactive();
585
+ switch (type) {
586
+ case "all":
587
+ this.flowClientInfo = undefined;
588
+ this.flowCodeVerifier = undefined;
589
+ this.flowDiscoveryState = undefined;
590
+ this.flowIssuerMismatch = false;
591
+ this.flowState = undefined;
592
+ this.invalidatedAccessToken = undefined;
593
+ this.invalidatedClientId = undefined;
594
+ this.staleRedirectClientId = undefined;
595
+ this.lastObservedClientId = undefined;
596
+ this.lastSavedAccessToken = undefined;
597
+ this.pendingAuthAccessToken = undefined;
598
+ clearAllCredentials(this.serverName, this.storageOptions);
599
+ break;
600
+ case "client":
601
+ // Dynamic client registrations share the same credential-store entry as
602
+ // tokens. Keep SDK invalidation local so a stale process cannot rewrite
603
+ // that entry over credentials another process just authorized.
604
+ this.invalidatedClientId = this.lastObservedClientId;
605
+ this.lastObservedClientId = undefined;
606
+ this.flowClientInfo = undefined;
607
+ invalidateAuthEntryCache(this.serverName);
608
+ break;
609
+ case "tokens":
610
+ // Invalidation is provider-local. Persistently deleting a shared token
611
+ // here lets a process refreshing stale cached credentials erase a token
612
+ // that another process just authorized. A later tokens() call bypasses
613
+ // the local cache and adopts a replacement token when one exists.
614
+ this.invalidatedAccessToken = this.pendingAuthAccessToken ?? this.lastSavedAccessToken;
615
+ this.lastSavedAccessToken = undefined;
616
+ this.pendingAuthAccessToken = undefined;
617
+ if (this.staleRedirectClientId !== undefined) {
618
+ this.invalidatedClientId = this.staleRedirectClientId;
619
+ }
620
+ invalidateAuthEntryCache(this.serverName);
621
+ break;
622
+ case "verifier":
623
+ clearCodeVerifier(this.serverName, this.storageOptions);
624
+ break;
625
+ case "discovery":
626
+ this.flowDiscoveryState = undefined;
627
+ break;
628
+ }
629
+ }
630
+ /**
631
+ * Adds configured authorization-code scope without replacing the SDK's
632
+ * default token endpoint authentication behavior.
633
+ */
634
+ addClientAuthentication = async (headers, params, _url, metadata) => {
635
+ this.throwIfInactive();
636
+ if (params.get("grant_type") === "authorization_code" && !params.has("scope") && this.config.scope) {
637
+ params.set("scope", this.config.scope);
638
+ }
639
+ const clientInfo = await this.clientInformation();
640
+ this.throwIfInactive();
641
+ if (!clientInfo) {
642
+ return;
643
+ }
644
+ const supportedMethods = metadata?.token_endpoint_auth_methods_supported ?? [];
645
+ const hasClientSecret = clientInfo.client_secret !== undefined;
646
+ let authMethod;
647
+ if (supportedMethods.length === 0) {
648
+ authMethod = hasClientSecret ? "client_secret_post" : "none";
649
+ }
650
+ else if (hasClientSecret && supportedMethods.includes("client_secret_basic")) {
651
+ authMethod = "client_secret_basic";
652
+ }
653
+ else if (hasClientSecret && supportedMethods.includes("client_secret_post")) {
654
+ authMethod = "client_secret_post";
655
+ }
656
+ else if (supportedMethods.includes("none")) {
657
+ authMethod = "none";
658
+ }
659
+ else {
660
+ authMethod = hasClientSecret ? "client_secret_post" : "none";
661
+ }
662
+ if (authMethod === "client_secret_basic") {
663
+ if (!clientInfo.client_secret) {
664
+ throw new Error("client_secret_basic authentication requires a client_secret");
665
+ }
666
+ headers.set("Authorization", `Basic ${Buffer.from(`${clientInfo.client_id}:${clientInfo.client_secret}`).toString("base64")}`);
667
+ return;
668
+ }
669
+ if (!params.has("client_id")) {
670
+ params.set("client_id", clientInfo.client_id);
671
+ }
672
+ if (authMethod === "client_secret_post" && clientInfo.client_secret && !params.has("client_secret")) {
673
+ params.set("client_secret", clientInfo.client_secret);
674
+ }
675
+ };
676
+ prepareTokenRequest(scope) {
677
+ if (!this.usesClientCredentials) {
678
+ return undefined;
679
+ }
680
+ const params = new URLSearchParams({ grant_type: "client_credentials" });
681
+ const requestedScope = scope ?? this.config.scope;
682
+ if (requestedScope) {
683
+ params.set("scope", requestedScope);
684
+ }
685
+ return params;
686
+ }
687
+ }
688
+ export { DEFAULT_OAUTH_CALLBACK_PORT, DEFAULT_OAUTH_CALLBACK_PATH };
689
+ //# sourceMappingURL=mcp-oauth-provider.js.map