@ny4n/mcp 0.0.0-stage → 1.0.1

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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/LICENSES/modelcontextprotocol-typescript-sdk.txt +21 -0
  3. package/README.md +135 -2
  4. package/dist/auth-provider.d.ts +19 -0
  5. package/dist/auth-provider.d.ts.map +1 -0
  6. package/dist/auth-provider.js +2 -0
  7. package/dist/auth-provider.js.map +1 -0
  8. package/dist/client.d.ts +89 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +457 -0
  11. package/dist/client.js.map +1 -0
  12. package/dist/index.d.ts +9 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +7 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/oauth/callback.d.ts +48 -0
  17. package/dist/oauth/callback.d.ts.map +1 -0
  18. package/dist/oauth/callback.js +115 -0
  19. package/dist/oauth/callback.js.map +1 -0
  20. package/dist/oauth/discovery.d.ts +30 -0
  21. package/dist/oauth/discovery.d.ts.map +1 -0
  22. package/dist/oauth/discovery.js +156 -0
  23. package/dist/oauth/discovery.js.map +1 -0
  24. package/dist/oauth/errors.d.ts +25 -0
  25. package/dist/oauth/errors.d.ts.map +1 -0
  26. package/dist/oauth/errors.js +48 -0
  27. package/dist/oauth/errors.js.map +1 -0
  28. package/dist/oauth/flow.d.ts +102 -0
  29. package/dist/oauth/flow.d.ts.map +1 -0
  30. package/dist/oauth/flow.js +334 -0
  31. package/dist/oauth/flow.js.map +1 -0
  32. package/dist/oauth/index.d.ts +7 -0
  33. package/dist/oauth/index.d.ts.map +1 -0
  34. package/dist/oauth/index.js +6 -0
  35. package/dist/oauth/index.js.map +1 -0
  36. package/dist/oauth/provider.d.ts +62 -0
  37. package/dist/oauth/provider.d.ts.map +1 -0
  38. package/dist/oauth/provider.js +118 -0
  39. package/dist/oauth/provider.js.map +1 -0
  40. package/dist/oauth/types.d.ts +82 -0
  41. package/dist/oauth/types.d.ts.map +1 -0
  42. package/dist/oauth/types.js +109 -0
  43. package/dist/oauth/types.js.map +1 -0
  44. package/dist/protocol/content.d.ts +82 -0
  45. package/dist/protocol/content.d.ts.map +1 -0
  46. package/dist/protocol/content.js +41 -0
  47. package/dist/protocol/content.js.map +1 -0
  48. package/dist/protocol/jsonrpc.d.ts +59 -0
  49. package/dist/protocol/jsonrpc.d.ts.map +1 -0
  50. package/dist/protocol/jsonrpc.js +67 -0
  51. package/dist/protocol/jsonrpc.js.map +1 -0
  52. package/dist/protocol/types.d.ts +123 -0
  53. package/dist/protocol/types.d.ts.map +1 -0
  54. package/dist/protocol/types.js +7 -0
  55. package/dist/protocol/types.js.map +1 -0
  56. package/dist/testing/index.d.ts +2 -0
  57. package/dist/testing/index.d.ts.map +1 -0
  58. package/dist/testing/index.js +2 -0
  59. package/dist/testing/index.js.map +1 -0
  60. package/dist/transports/in-memory.d.ts +19 -0
  61. package/dist/transports/in-memory.d.ts.map +1 -0
  62. package/dist/transports/in-memory.js +50 -0
  63. package/dist/transports/in-memory.js.map +1 -0
  64. package/dist/transports/stdio.d.ts +32 -0
  65. package/dist/transports/stdio.d.ts.map +1 -0
  66. package/dist/transports/stdio.js +201 -0
  67. package/dist/transports/stdio.js.map +1 -0
  68. package/dist/transports/streamable-http.d.ts +99 -0
  69. package/dist/transports/streamable-http.d.ts.map +1 -0
  70. package/dist/transports/streamable-http.js +459 -0
  71. package/dist/transports/streamable-http.js.map +1 -0
  72. package/dist/transports/transport.d.ts +28 -0
  73. package/dist/transports/transport.d.ts.map +1 -0
  74. package/dist/transports/transport.js +38 -0
  75. package/dist/transports/transport.js.map +1 -0
  76. package/package.json +59 -5
@@ -0,0 +1,115 @@
1
+ import { createServer } from "node:http";
2
+ function plainText(page) {
3
+ if (page.ok)
4
+ return "Authorization complete. You may close this window.";
5
+ return page.details ? `${page.message}\n\n${page.details}` : page.message;
6
+ }
7
+ export class OAuthCallbackServer {
8
+ redirectUrl;
9
+ server;
10
+ paths;
11
+ timeoutMs;
12
+ renderPage;
13
+ pending = new Map();
14
+ constructor(server, redirectUrl, paths, timeoutMs, renderPage) {
15
+ this.server = server;
16
+ this.redirectUrl = redirectUrl;
17
+ this.paths = paths;
18
+ this.timeoutMs = timeoutMs;
19
+ this.renderPage = renderPage;
20
+ }
21
+ static async listen(options = {}) {
22
+ const host = options.host ?? "127.0.0.1";
23
+ const redirectHost = options.redirectHost ?? host;
24
+ const path = options.path ?? "/callback";
25
+ let instance;
26
+ const server = createServer((request, response) => instance?.handle(request.url ?? "/", response));
27
+ await new Promise((resolve, reject) => {
28
+ server.once("error", reject);
29
+ server.listen(options.port ?? 0, host, () => {
30
+ server.off("error", reject);
31
+ resolve();
32
+ });
33
+ });
34
+ const address = server.address();
35
+ if (!address || typeof address === "string")
36
+ throw new Error("OAuth callback server did not bind to TCP");
37
+ instance = new OAuthCallbackServer(server, `http://${redirectHost.includes(":") ? `[${redirectHost}]` : redirectHost}:${address.port}${path}`, [path, ...(options.extraPaths ?? [])], options.timeoutMs ?? 5 * 60_000, options.renderPage);
38
+ return instance;
39
+ }
40
+ /**
41
+ * Wait for the authorization response with `state`. With `path`, a response on another path fails, so
42
+ * a server-specific redirect URI can tell authorization servers apart (RFC 9700 section 4.4.2.2).
43
+ */
44
+ waitForCallback(state, path) {
45
+ if (this.pending.has(state))
46
+ throw new Error("OAuth state is already pending");
47
+ return new Promise((resolve, reject) => {
48
+ const timer = setTimeout(() => {
49
+ this.pending.delete(state);
50
+ reject(new Error("OAuth callback timed out"));
51
+ }, this.timeoutMs);
52
+ this.pending.set(state, { resolve, reject, timer, path });
53
+ });
54
+ }
55
+ async close() {
56
+ for (const pending of this.pending.values()) {
57
+ clearTimeout(pending.timer);
58
+ pending.reject(new Error("OAuth callback server closed"));
59
+ }
60
+ this.pending.clear();
61
+ await new Promise((resolve, reject) => {
62
+ this.server.close((error) => (error ? reject(error) : resolve()));
63
+ });
64
+ }
65
+ reply(response, status, page) {
66
+ if (this.renderPage) {
67
+ response.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
68
+ response.end(this.renderPage(page));
69
+ }
70
+ else {
71
+ response.writeHead(status, { "content-type": "text/plain; charset=utf-8" }).end(plainText(page));
72
+ }
73
+ }
74
+ handle(rawUrl, response) {
75
+ const url = new URL(rawUrl, this.redirectUrl);
76
+ if (!this.paths.includes(url.pathname)) {
77
+ this.reply(response, 404, { ok: false, message: "Not found" });
78
+ return;
79
+ }
80
+ const state = url.searchParams.get("state");
81
+ const pending = state ? this.pending.get(state) : undefined;
82
+ if (!state || !pending) {
83
+ this.reply(response, 400, { ok: false, message: "Invalid or expired OAuth state" });
84
+ return;
85
+ }
86
+ clearTimeout(pending.timer);
87
+ this.pending.delete(state);
88
+ if (pending.path !== undefined && url.pathname !== pending.path) {
89
+ pending.reject(new Error("The authorization response arrived on another redirect URI"));
90
+ this.reply(response, 400, { ok: false, message: "Unexpected redirect URI" });
91
+ return;
92
+ }
93
+ const error = url.searchParams.get("error");
94
+ if (error) {
95
+ const description = url.searchParams.get("error_description") ?? error;
96
+ pending.reject(new Error(description));
97
+ this.reply(response, 200, {
98
+ ok: false,
99
+ message: "Authorization failed. You may close this window.",
100
+ details: description,
101
+ });
102
+ return;
103
+ }
104
+ const code = url.searchParams.get("code");
105
+ if (!code) {
106
+ pending.reject(new Error("OAuth callback did not include an authorization code"));
107
+ this.reply(response, 400, { ok: false, message: "Missing authorization code" });
108
+ return;
109
+ }
110
+ const iss = url.searchParams.get("iss");
111
+ pending.resolve({ code, state, ...(iss ? { iss } : {}) });
112
+ this.reply(response, 200, { ok: true });
113
+ }
114
+ }
115
+ //# sourceMappingURL=callback.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"callback.js","sourceRoot":"","sources":["../../src/oauth/callback.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAoC,MAAM,WAAW,CAAC;AA4B3E,SAAS,SAAS,CAAC,IAAuB;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CAAC;QAC5C,IAAI,KAAK,EAAE,CAAC;YACX,MAAM,WAAW,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,mBAAmB,CAAC,IAAI,KAAK,CAAC;YACvE,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC;YACvC,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE;gBACzB,EAAE,EAAE,KAAK;gBACT,OAAO,EAAE,kDAAkD;gBAC3D,OAAO,EAAE,WAAW;aACpB,CAAC,CAAC;YACH,OAAO;QACR,CAAC;QACD,MAAM,IAAI,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC1C,IAAI,CAAC,IAAI,EAAE,CAAC;YACX,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC,CAAC;YAClF,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,4BAA4B,EAAE,CAAC,CAAC;YAChF,OAAO;QACR,CAAC;QACD,MAAM,GAAG,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACxC,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;QAC1D,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,GAAG,EAAE,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC;IACzC,CAAC;CACD","sourcesContent":["import { createServer, type Server, type ServerResponse } from \"node:http\";\n\nexport interface OAuthCallback {\n\tcode: string;\n\tstate: string;\n\tiss?: string;\n}\n\n/** Outcome shown on the browser page after the redirect. */\nexport type OAuthCallbackPage = { ok: true } | { ok: false; message: string; details?: string };\n\nexport interface OAuthCallbackServerOptions {\n\t/** Address to listen on. Default: `127.0.0.1`. */\n\thost?: string;\n\t/**\n\t * Host name in `redirectUrl`, for example `localhost` for a client registered with it while\n\t * listening on `127.0.0.1`. Default: `host`.\n\t */\n\tredirectHost?: string;\n\tport?: number;\n\tpath?: string;\n\t/** More paths that receive the callback, for example a server-specific path of a redirect URI. */\n\textraPaths?: string[];\n\ttimeoutMs?: number;\n\t/** Render the browser page as HTML. Default: a plain-text message. */\n\trenderPage?: (page: OAuthCallbackPage) => string;\n}\n\nfunction plainText(page: OAuthCallbackPage): string {\n\tif (page.ok) return \"Authorization complete. You may close this window.\";\n\treturn page.details ? `${page.message}\\n\\n${page.details}` : page.message;\n}\n\nexport class OAuthCallbackServer {\n\treadonly redirectUrl: string;\n\tprivate server: Server;\n\tprivate paths: string[];\n\tprivate timeoutMs: number;\n\tprivate renderPage: ((page: OAuthCallbackPage) => string) | undefined;\n\tprivate pending = new Map<\n\t\tstring,\n\t\t{\n\t\t\tresolve: (callback: OAuthCallback) => void;\n\t\t\treject: (error: Error) => void;\n\t\t\ttimer: ReturnType<typeof setTimeout>;\n\t\t\tpath: string | undefined;\n\t\t}\n\t>();\n\n\tprivate constructor(\n\t\tserver: Server,\n\t\tredirectUrl: string,\n\t\tpaths: string[],\n\t\ttimeoutMs: number,\n\t\trenderPage: ((page: OAuthCallbackPage) => string) | undefined,\n\t) {\n\t\tthis.server = server;\n\t\tthis.redirectUrl = redirectUrl;\n\t\tthis.paths = paths;\n\t\tthis.timeoutMs = timeoutMs;\n\t\tthis.renderPage = renderPage;\n\t}\n\n\tstatic async listen(options: OAuthCallbackServerOptions = {}): Promise<OAuthCallbackServer> {\n\t\tconst host = options.host ?? \"127.0.0.1\";\n\t\tconst redirectHost = options.redirectHost ?? host;\n\t\tconst path = options.path ?? \"/callback\";\n\t\tlet instance: OAuthCallbackServer | undefined;\n\t\tconst server = createServer((request, response) => instance?.handle(request.url ?? \"/\", response));\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tserver.once(\"error\", reject);\n\t\t\tserver.listen(options.port ?? 0, host, () => {\n\t\t\t\tserver.off(\"error\", reject);\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t\tconst address = server.address();\n\t\tif (!address || typeof address === \"string\") throw new Error(\"OAuth callback server did not bind to TCP\");\n\t\tinstance = new OAuthCallbackServer(\n\t\t\tserver,\n\t\t\t`http://${redirectHost.includes(\":\") ? `[${redirectHost}]` : redirectHost}:${address.port}${path}`,\n\t\t\t[path, ...(options.extraPaths ?? [])],\n\t\t\toptions.timeoutMs ?? 5 * 60_000,\n\t\t\toptions.renderPage,\n\t\t);\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Wait for the authorization response with `state`. With `path`, a response on another path fails, so\n\t * a server-specific redirect URI can tell authorization servers apart (RFC 9700 section 4.4.2.2).\n\t */\n\twaitForCallback(state: string, path?: string): Promise<OAuthCallback> {\n\t\tif (this.pending.has(state)) throw new Error(\"OAuth state is already pending\");\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer = setTimeout(() => {\n\t\t\t\tthis.pending.delete(state);\n\t\t\t\treject(new Error(\"OAuth callback timed out\"));\n\t\t\t}, this.timeoutMs);\n\t\t\tthis.pending.set(state, { resolve, reject, timer, path });\n\t\t});\n\t}\n\n\tasync close(): Promise<void> {\n\t\tfor (const pending of this.pending.values()) {\n\t\t\tclearTimeout(pending.timer);\n\t\t\tpending.reject(new Error(\"OAuth callback server closed\"));\n\t\t}\n\t\tthis.pending.clear();\n\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\tthis.server.close((error) => (error ? reject(error) : resolve()));\n\t\t});\n\t}\n\n\tprivate reply(response: ServerResponse, status: number, page: OAuthCallbackPage): void {\n\t\tif (this.renderPage) {\n\t\t\tresponse.writeHead(status, { \"content-type\": \"text/html; charset=utf-8\", \"cache-control\": \"no-store\" });\n\t\t\tresponse.end(this.renderPage(page));\n\t\t} else {\n\t\t\tresponse.writeHead(status, { \"content-type\": \"text/plain; charset=utf-8\" }).end(plainText(page));\n\t\t}\n\t}\n\n\tprivate handle(rawUrl: string, response: ServerResponse): void {\n\t\tconst url = new URL(rawUrl, this.redirectUrl);\n\t\tif (!this.paths.includes(url.pathname)) {\n\t\t\tthis.reply(response, 404, { ok: false, message: \"Not found\" });\n\t\t\treturn;\n\t\t}\n\t\tconst state = url.searchParams.get(\"state\");\n\t\tconst pending = state ? this.pending.get(state) : undefined;\n\t\tif (!state || !pending) {\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Invalid or expired OAuth state\" });\n\t\t\treturn;\n\t\t}\n\t\tclearTimeout(pending.timer);\n\t\tthis.pending.delete(state);\n\t\tif (pending.path !== undefined && url.pathname !== pending.path) {\n\t\t\tpending.reject(new Error(\"The authorization response arrived on another redirect URI\"));\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Unexpected redirect URI\" });\n\t\t\treturn;\n\t\t}\n\t\tconst error = url.searchParams.get(\"error\");\n\t\tif (error) {\n\t\t\tconst description = url.searchParams.get(\"error_description\") ?? error;\n\t\t\tpending.reject(new Error(description));\n\t\t\tthis.reply(response, 200, {\n\t\t\t\tok: false,\n\t\t\t\tmessage: \"Authorization failed. You may close this window.\",\n\t\t\t\tdetails: description,\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tif (!code) {\n\t\t\tpending.reject(new Error(\"OAuth callback did not include an authorization code\"));\n\t\t\tthis.reply(response, 400, { ok: false, message: \"Missing authorization code\" });\n\t\t\treturn;\n\t\t}\n\t\tconst iss = url.searchParams.get(\"iss\");\n\t\tpending.resolve({ code, state, ...(iss ? { iss } : {}) });\n\t\tthis.reply(response, 200, { ok: true });\n\t}\n}\n"]}
@@ -0,0 +1,30 @@
1
+ import type { McpFetch } from "../auth-provider.ts";
2
+ import { type AuthorizationServerMetadata, type OAuthChallenge, type OAuthProtectedResourceMetadata, type OAuthServerInfo } from "./types.ts";
3
+ export declare function parseWwwAuthenticate(header: string | null): OAuthChallenge;
4
+ export declare function discoverProtectedResourceMetadata(serverUrl: string | URL, options?: {
5
+ resourceMetadataUrl?: string | URL;
6
+ protocolVersion?: string;
7
+ fetch?: McpFetch;
8
+ signal?: AbortSignal;
9
+ }): Promise<OAuthProtectedResourceMetadata>;
10
+ export declare function buildAuthorizationServerDiscoveryUrls(authorizationServerUrl: string | URL): {
11
+ url: URL;
12
+ type: "oauth" | "oidc";
13
+ }[];
14
+ export declare function discoverAuthorizationServerMetadata(authorizationServerUrl: string | URL, options?: {
15
+ fetch?: McpFetch;
16
+ protocolVersion?: string;
17
+ skipIssuerValidation?: boolean;
18
+ signal?: AbortSignal;
19
+ }): Promise<AuthorizationServerMetadata | undefined>;
20
+ export declare function discoverOAuthServerInfo(serverUrl: string | URL, options?: {
21
+ resourceMetadataUrl?: URL;
22
+ /** Metadata document to use instead of discovery. It is trusted as configured, so its issuer is not checked. */
23
+ authorizationServerMetadataUrl?: URL;
24
+ fetch?: McpFetch;
25
+ skipIssuerValidation?: boolean;
26
+ signal?: AbortSignal;
27
+ }): Promise<OAuthServerInfo>;
28
+ export declare function resourceUrlFromServerUrl(value: string | URL): URL;
29
+ export declare function selectResource(serverUrl: string | URL, metadata?: OAuthProtectedResourceMetadata): string | undefined;
30
+ //# sourceMappingURL=discovery.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discovery.d.ts","sourceRoot":"","sources":["../../src/oauth/discovery.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EACN,KAAK,2BAA2B,EAChC,KAAK,cAAc,EACnB,KAAK,8BAA8B,EACnC,KAAK,eAAe,EAGpB,MAAM,YAAY,CAAC;AAsBpB,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,cAAc,CAiB1E;AAcD,wBAAsB,iCAAiC,CACtD,SAAS,EAAE,MAAM,GAAG,GAAG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elcontextprotocol/typescript-sdk v1.29.0 src/client/auth.ts.
3
+ * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see LICENSES/.
4
+ * Modified to remove Zod/CORS shims and enforce authorization-server issuer validation.
5
+ */
6
+ import { LATEST_PROTOCOL_VERSION } from "../protocol/types.js";
7
+ import { OAuthIssuerMismatchError } from "./errors.js";
8
+ import { parseAuthorizationServerMetadata, parseProtectedResourceMetadata, } from "./types.js";
9
+ function discard(response) {
10
+ void response?.body?.cancel().catch(() => { });
11
+ }
12
+ /** 4xx and 502 mean "not here", so discovery tries the next candidate URL. */
13
+ function isDiscoveryMiss(status) {
14
+ return (status >= 400 && status < 500) || status === 502;
15
+ }
16
+ /** Path suffix for `/.well-known/<kind><path>`; empty for the root path. */
17
+ function pathSuffix(pathname) {
18
+ return pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
19
+ }
20
+ function field(header, name) {
21
+ const match = header.match(new RegExp(String.raw `(?:^|[,\s])${name}=(?:"([^"]*)"|([^\s,]+))`, "i"));
22
+ // An empty value (`scope=""`) carries no information, so it counts as absent.
23
+ return match?.[1] || match?.[2] || undefined;
24
+ }
25
+ export function parseWwwAuthenticate(header) {
26
+ if (!header)
27
+ return {};
28
+ const scheme = header.trimStart().split(/\s+/, 1)[0]?.toLowerCase();
29
+ if (scheme !== "bearer" && scheme !== "dpop")
30
+ return {};
31
+ const resourceMetadata = field(header, "resource_metadata");
32
+ let resourceMetadataUrl;
33
+ if (resourceMetadata) {
34
+ try {
35
+ resourceMetadataUrl = new URL(resourceMetadata);
36
+ }
37
+ catch { }
38
+ }
39
+ return {
40
+ resourceMetadataUrl,
41
+ scope: field(header, "scope"),
42
+ error: field(header, "error"),
43
+ errorDescription: field(header, "error_description"),
44
+ };
45
+ }
46
+ async function fetchMetadata(url, fetch, protocolVersion, signal) {
47
+ return fetch(url, {
48
+ headers: { Accept: "application/json", "MCP-Protocol-Version": protocolVersion },
49
+ signal,
50
+ });
51
+ }
52
+ export async function discoverProtectedResourceMetadata(serverUrl, options = {}) {
53
+ const server = new URL(serverUrl);
54
+ const fetch = options.fetch ?? globalThis.fetch;
55
+ const version = options.protocolVersion ?? LATEST_PROTOCOL_VERSION;
56
+ let response = await fetchMetadata(options.resourceMetadataUrl
57
+ ? new URL(options.resourceMetadataUrl)
58
+ : new URL(`/.well-known/oauth-protected-resource${pathSuffix(server.pathname)}`, server.origin), fetch, version, options.signal);
59
+ if (!options.resourceMetadataUrl && server.pathname !== "/" && isDiscoveryMiss(response.status)) {
60
+ discard(response);
61
+ response = await fetchMetadata(new URL("/.well-known/oauth-protected-resource", server.origin), fetch, version, options.signal);
62
+ }
63
+ if (!response.ok) {
64
+ discard(response);
65
+ throw new Error(`HTTP ${response.status} loading OAuth protected resource metadata`);
66
+ }
67
+ return parseProtectedResourceMetadata(await response.json());
68
+ }
69
+ export function buildAuthorizationServerDiscoveryUrls(authorizationServerUrl) {
70
+ const issuer = new URL(authorizationServerUrl);
71
+ const path = pathSuffix(issuer.pathname);
72
+ const urls = [
73
+ { url: new URL(`/.well-known/oauth-authorization-server${path}`, issuer.origin), type: "oauth" },
74
+ { url: new URL(`/.well-known/openid-configuration${path}`, issuer.origin), type: "oidc" },
75
+ ];
76
+ if (path)
77
+ urls.push({ url: new URL(`${path}/.well-known/openid-configuration`, issuer.origin), type: "oidc" });
78
+ return urls;
79
+ }
80
+ export async function discoverAuthorizationServerMetadata(authorizationServerUrl, options = {}) {
81
+ const fetch = options.fetch ?? globalThis.fetch;
82
+ for (const { url } of buildAuthorizationServerDiscoveryUrls(authorizationServerUrl)) {
83
+ const response = await fetchMetadata(url, fetch, options.protocolVersion ?? LATEST_PROTOCOL_VERSION, options.signal);
84
+ if (!response.ok) {
85
+ discard(response);
86
+ if (isDiscoveryMiss(response.status))
87
+ continue;
88
+ throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);
89
+ }
90
+ const metadata = parseAuthorizationServerMetadata(await response.json());
91
+ if (!options.skipIssuerValidation) {
92
+ const expected = String(authorizationServerUrl);
93
+ // URL parsing adds a trailing slash to bare origins, so compare without one on either side.
94
+ const trim = (value) => (value.endsWith("/") ? value.slice(0, -1) : value);
95
+ if (trim(metadata.issuer) !== trim(expected))
96
+ throw new OAuthIssuerMismatchError(expected, metadata.issuer);
97
+ }
98
+ return metadata;
99
+ }
100
+ return undefined;
101
+ }
102
+ export async function discoverOAuthServerInfo(serverUrl, options = {}) {
103
+ let resourceMetadata;
104
+ try {
105
+ resourceMetadata = await discoverProtectedResourceMetadata(serverUrl, {
106
+ resourceMetadataUrl: options.resourceMetadataUrl,
107
+ fetch: options.fetch,
108
+ signal: options.signal,
109
+ });
110
+ }
111
+ catch (error) {
112
+ if (error instanceof TypeError)
113
+ throw error;
114
+ }
115
+ if (options.authorizationServerMetadataUrl) {
116
+ const url = options.authorizationServerMetadataUrl;
117
+ const response = await fetchMetadata(url, options.fetch ?? globalThis.fetch, LATEST_PROTOCOL_VERSION, options.signal);
118
+ if (!response.ok) {
119
+ discard(response);
120
+ throw new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);
121
+ }
122
+ const metadata = parseAuthorizationServerMetadata(await response.json());
123
+ return { authorizationServerUrl: metadata.issuer, authorizationServerMetadata: metadata, resourceMetadata };
124
+ }
125
+ const authorizationServerUrl = resourceMetadata?.authorization_servers?.[0] ?? String(new URL("/", serverUrl));
126
+ return {
127
+ authorizationServerUrl,
128
+ authorizationServerMetadata: await discoverAuthorizationServerMetadata(authorizationServerUrl, {
129
+ fetch: options.fetch,
130
+ skipIssuerValidation: options.skipIssuerValidation,
131
+ signal: options.signal,
132
+ }),
133
+ resourceMetadata,
134
+ };
135
+ }
136
+ export function resourceUrlFromServerUrl(value) {
137
+ const url = new URL(value);
138
+ url.hash = "";
139
+ return url;
140
+ }
141
+ export function selectResource(serverUrl, metadata) {
142
+ if (!metadata)
143
+ return undefined;
144
+ const requested = resourceUrlFromServerUrl(serverUrl);
145
+ const configured = new URL(metadata.resource);
146
+ if (requested.origin !== configured.origin) {
147
+ throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);
148
+ }
149
+ const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : `${requested.pathname}/`;
150
+ const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : `${configured.pathname}/`;
151
+ if (!requestedPath.startsWith(configuredPath)) {
152
+ throw new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);
153
+ }
154
+ return metadata.resource;
155
+ }
156
+ //# sourceMappingURL=discovery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discovery.js","sourceRoot":"","sources":["../../src/oauth/discovery.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AAC/D,OAAO,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AACvD,OAAO,EAKN,gCAAgC,EAChC,8BAA8B,GAC9B,MAAM,YAAY,CAAC;AAEpB,SAAS,OAAO,CAAC,QAA8B;IAC9C,KAAK,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;AAC/C,CAAC;AAED,8EAA8E;AAC9E,SAAS,eAAe,CAAC,MAAc;IACtC,OAAO,CAAC,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC,IAAI,MAAM,KAAK,GAAG,CAAC;AAC1D,CAAC;AAED,4EAA4E;AAC5E,SAAS,UAAU,CAAC,QAAgB;IACnC,OAAO,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC;AAClE,CAAC;AAED,SAAS,KAAK,CAAC,MAAc,EAAE,IAAY;IAC1C,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,MAAM,CAAC,MAAM,CAAC,GAAG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UAAU,CAAC,MAAM,EAAE,CAAC;QAC5C,MAAM,IAAI,KAAK,CAAC,sBAAsB,QAAQ,CAAC,QAAQ,8BAA8B,SAAS,EAAE,CAAC,CAAC;IACnG,CAAC;IACD,MAAM,aAAa,GAAG,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,SAAS,CAAC,QAAQ,GAAG,CAAC;IACvG,MAAM,cAAc,GAAG,UAAU,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,CAAC,GAAG,UAAU,CAAC,QAAQ,GAAG,CAAC;IAC3G,IAAI,CAAC,aAAa,CAAC,UAAU,CAAC,cAAc,CAAC,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CAAC,sBAAsB,QAAQ,CAAC,QAAQ,8BAA8B,SAAS,EAAE,CAAC,CAAC;IACnG,CAAC;IACD,OAAO,QAAQ,CAAC,QAAQ,CAAC;AAC1B,CAAC","sourcesContent":["/*\n * Adapted from modelcontextprotocol/typescript-sdk v1.29.0 src/client/auth.ts.\n * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see LICENSES/.\n * Modified to remove Zod/CORS shims and enforce authorization-server issuer validation.\n */\n\nimport type { McpFetch } from \"../auth-provider.ts\";\nimport { LATEST_PROTOCOL_VERSION } from \"../protocol/types.ts\";\nimport { OAuthIssuerMismatchError } from \"./errors.ts\";\nimport {\n\ttype AuthorizationServerMetadata,\n\ttype OAuthChallenge,\n\ttype OAuthProtectedResourceMetadata,\n\ttype OAuthServerInfo,\n\tparseAuthorizationServerMetadata,\n\tparseProtectedResourceMetadata,\n} from \"./types.ts\";\n\nfunction discard(response: Response | undefined): void {\n\tvoid response?.body?.cancel().catch(() => {});\n}\n\n/** 4xx and 502 mean \"not here\", so discovery tries the next candidate URL. */\nfunction isDiscoveryMiss(status: number): boolean {\n\treturn (status >= 400 && status < 500) || status === 502;\n}\n\n/** Path suffix for `/.well-known/<kind><path>`; empty for the root path. */\nfunction pathSuffix(pathname: string): string {\n\treturn pathname.endsWith(\"/\") ? pathname.slice(0, -1) : pathname;\n}\n\nfunction field(header: string, name: string): string | undefined {\n\tconst match = header.match(new RegExp(String.raw`(?:^|[,\\s])${name}=(?:\"([^\"]*)\"|([^\\s,]+))`, \"i\"));\n\t// An empty value (`scope=\"\"`) carries no information, so it counts as absent.\n\treturn match?.[1] || match?.[2] || undefined;\n}\n\nexport function parseWwwAuthenticate(header: string | null): OAuthChallenge {\n\tif (!header) return {};\n\tconst scheme = header.trimStart().split(/\\s+/, 1)[0]?.toLowerCase();\n\tif (scheme !== \"bearer\" && scheme !== \"dpop\") return {};\n\tconst resourceMetadata = field(header, \"resource_metadata\");\n\tlet resourceMetadataUrl: URL | undefined;\n\tif (resourceMetadata) {\n\t\ttry {\n\t\t\tresourceMetadataUrl = new URL(resourceMetadata);\n\t\t} catch {}\n\t}\n\treturn {\n\t\tresourceMetadataUrl,\n\t\tscope: field(header, \"scope\"),\n\t\terror: field(header, \"error\"),\n\t\terrorDescription: field(header, \"error_description\"),\n\t};\n}\n\nasync function fetchMetadata(\n\turl: URL,\n\tfetch: McpFetch,\n\tprotocolVersion: string,\n\tsignal: AbortSignal | undefined,\n): Promise<Response> {\n\treturn fetch(url, {\n\t\theaders: { Accept: \"application/json\", \"MCP-Protocol-Version\": protocolVersion },\n\t\tsignal,\n\t});\n}\n\nexport async function discoverProtectedResourceMetadata(\n\tserverUrl: string | URL,\n\toptions: {\n\t\tresourceMetadataUrl?: string | URL;\n\t\tprotocolVersion?: string;\n\t\tfetch?: McpFetch;\n\t\tsignal?: AbortSignal;\n\t} = {},\n): Promise<OAuthProtectedResourceMetadata> {\n\tconst server = new URL(serverUrl);\n\tconst fetch = options.fetch ?? globalThis.fetch;\n\tconst version = options.protocolVersion ?? LATEST_PROTOCOL_VERSION;\n\tlet response = await fetchMetadata(\n\t\toptions.resourceMetadataUrl\n\t\t\t? new URL(options.resourceMetadataUrl)\n\t\t\t: new URL(`/.well-known/oauth-protected-resource${pathSuffix(server.pathname)}`, server.origin),\n\t\tfetch,\n\t\tversion,\n\t\toptions.signal,\n\t);\n\tif (!options.resourceMetadataUrl && server.pathname !== \"/\" && isDiscoveryMiss(response.status)) {\n\t\tdiscard(response);\n\t\tresponse = await fetchMetadata(\n\t\t\tnew URL(\"/.well-known/oauth-protected-resource\", server.origin),\n\t\t\tfetch,\n\t\t\tversion,\n\t\t\toptions.signal,\n\t\t);\n\t}\n\tif (!response.ok) {\n\t\tdiscard(response);\n\t\tthrow new Error(`HTTP ${response.status} loading OAuth protected resource metadata`);\n\t}\n\treturn parseProtectedResourceMetadata(await response.json());\n}\n\nexport function buildAuthorizationServerDiscoveryUrls(\n\tauthorizationServerUrl: string | URL,\n): { url: URL; type: \"oauth\" | \"oidc\" }[] {\n\tconst issuer = new URL(authorizationServerUrl);\n\tconst path = pathSuffix(issuer.pathname);\n\tconst urls: { url: URL; type: \"oauth\" | \"oidc\" }[] = [\n\t\t{ url: new URL(`/.well-known/oauth-authorization-server${path}`, issuer.origin), type: \"oauth\" },\n\t\t{ url: new URL(`/.well-known/openid-configuration${path}`, issuer.origin), type: \"oidc\" },\n\t];\n\tif (path) urls.push({ url: new URL(`${path}/.well-known/openid-configuration`, issuer.origin), type: \"oidc\" });\n\treturn urls;\n}\n\nexport async function discoverAuthorizationServerMetadata(\n\tauthorizationServerUrl: string | URL,\n\toptions: { fetch?: McpFetch; protocolVersion?: string; skipIssuerValidation?: boolean; signal?: AbortSignal } = {},\n): Promise<AuthorizationServerMetadata | undefined> {\n\tconst fetch = options.fetch ?? globalThis.fetch;\n\tfor (const { url } of buildAuthorizationServerDiscoveryUrls(authorizationServerUrl)) {\n\t\tconst response = await fetchMetadata(\n\t\t\turl,\n\t\t\tfetch,\n\t\t\toptions.protocolVersion ?? LATEST_PROTOCOL_VERSION,\n\t\t\toptions.signal,\n\t\t);\n\t\tif (!response.ok) {\n\t\t\tdiscard(response);\n\t\t\tif (isDiscoveryMiss(response.status)) continue;\n\t\t\tthrow new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);\n\t\t}\n\t\tconst metadata = parseAuthorizationServerMetadata(await response.json());\n\t\tif (!options.skipIssuerValidation) {\n\t\t\tconst expected = String(authorizationServerUrl);\n\t\t\t// URL parsing adds a trailing slash to bare origins, so compare without one on either side.\n\t\t\tconst trim = (value: string) => (value.endsWith(\"/\") ? value.slice(0, -1) : value);\n\t\t\tif (trim(metadata.issuer) !== trim(expected)) throw new OAuthIssuerMismatchError(expected, metadata.issuer);\n\t\t}\n\t\treturn metadata;\n\t}\n\treturn undefined;\n}\n\nexport async function discoverOAuthServerInfo(\n\tserverUrl: string | URL,\n\toptions: {\n\t\tresourceMetadataUrl?: URL;\n\t\t/** Metadata document to use instead of discovery. It is trusted as configured, so its issuer is not checked. */\n\t\tauthorizationServerMetadataUrl?: URL;\n\t\tfetch?: McpFetch;\n\t\tskipIssuerValidation?: boolean;\n\t\tsignal?: AbortSignal;\n\t} = {},\n): Promise<OAuthServerInfo> {\n\tlet resourceMetadata: OAuthProtectedResourceMetadata | undefined;\n\ttry {\n\t\tresourceMetadata = await discoverProtectedResourceMetadata(serverUrl, {\n\t\t\tresourceMetadataUrl: options.resourceMetadataUrl,\n\t\t\tfetch: options.fetch,\n\t\t\tsignal: options.signal,\n\t\t});\n\t} catch (error) {\n\t\tif (error instanceof TypeError) throw error;\n\t}\n\tif (options.authorizationServerMetadataUrl) {\n\t\tconst url = options.authorizationServerMetadataUrl;\n\t\tconst response = await fetchMetadata(\n\t\t\turl,\n\t\t\toptions.fetch ?? globalThis.fetch,\n\t\t\tLATEST_PROTOCOL_VERSION,\n\t\t\toptions.signal,\n\t\t);\n\t\tif (!response.ok) {\n\t\t\tdiscard(response);\n\t\t\tthrow new Error(`HTTP ${response.status} loading authorization server metadata from ${url}`);\n\t\t}\n\t\tconst metadata = parseAuthorizationServerMetadata(await response.json());\n\t\treturn { authorizationServerUrl: metadata.issuer, authorizationServerMetadata: metadata, resourceMetadata };\n\t}\n\tconst authorizationServerUrl = resourceMetadata?.authorization_servers?.[0] ?? String(new URL(\"/\", serverUrl));\n\treturn {\n\t\tauthorizationServerUrl,\n\t\tauthorizationServerMetadata: await discoverAuthorizationServerMetadata(authorizationServerUrl, {\n\t\t\tfetch: options.fetch,\n\t\t\tskipIssuerValidation: options.skipIssuerValidation,\n\t\t\tsignal: options.signal,\n\t\t}),\n\t\tresourceMetadata,\n\t};\n}\n\nexport function resourceUrlFromServerUrl(value: string | URL): URL {\n\tconst url = new URL(value);\n\turl.hash = \"\";\n\treturn url;\n}\n\nexport function selectResource(serverUrl: string | URL, metadata?: OAuthProtectedResourceMetadata): string | undefined {\n\tif (!metadata) return undefined;\n\tconst requested = resourceUrlFromServerUrl(serverUrl);\n\tconst configured = new URL(metadata.resource);\n\tif (requested.origin !== configured.origin) {\n\t\tthrow new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);\n\t}\n\tconst requestedPath = requested.pathname.endsWith(\"/\") ? requested.pathname : `${requested.pathname}/`;\n\tconst configuredPath = configured.pathname.endsWith(\"/\") ? configured.pathname : `${configured.pathname}/`;\n\tif (!requestedPath.startsWith(configuredPath)) {\n\t\tthrow new Error(`Protected resource ${metadata.resource} does not match MCP server ${requested}`);\n\t}\n\treturn metadata.resource;\n}\n"]}
@@ -0,0 +1,25 @@
1
+ export declare class OAuthError extends Error {
2
+ readonly code: string;
3
+ readonly errorUri: string | undefined;
4
+ constructor(code: string, message: string, errorUri?: string);
5
+ }
6
+ export declare class OAuthIssuerMismatchError extends Error {
7
+ /** `undefined` when no authorization server metadata was discovered. */
8
+ readonly expected: string | undefined;
9
+ /** `undefined` when an authorization response lacks the `iss` parameter its server promised (RFC 9207). */
10
+ readonly received: string | undefined;
11
+ constructor(expected: string | undefined, received: string | undefined);
12
+ }
13
+ export declare class OAuthInsecureEndpointError extends Error {
14
+ readonly endpoint: string;
15
+ constructor(endpoint: string);
16
+ }
17
+ export declare class OAuthRegistrationError extends Error {
18
+ readonly status: number;
19
+ readonly body: string;
20
+ constructor(status: number, body: string);
21
+ }
22
+ export declare class McpOAuthAuthorizationRequiredError extends Error {
23
+ constructor();
24
+ }
25
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../../src/oauth/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,UAAW,SAAQ,KAAK;IACpC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAEtC,YAAY,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,EAK3D;CACD;AAED,qBAAa,wBAAyB,SAAQ,KAAK;IAClD,wEAAwE;IACxE,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IACtC,2GAA2G;IAC3G,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAEtC,YAAY,QAAQ,EAAE,MAAM,GAAG,SAAS,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,EAMrE;CACD;AAED,qBAAa,0BAA2B,SAAQ,KAAK;IACpD,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B,YAAY,QAAQ,EAAE,MAAM,EAI3B;CACD;AAED,qBAAa,sBAAuB,SAAQ,KAAK;IAChD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,YAAY,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAKvC;CACD;AAED,qBAAa,kCAAmC,SAAQ,KAAK;IAC5D,cAGC;CACD"}
@@ -0,0 +1,48 @@
1
+ export class OAuthError extends Error {
2
+ code;
3
+ errorUri;
4
+ constructor(code, message, errorUri) {
5
+ super(message || code);
6
+ this.name = "OAuthError";
7
+ this.code = code;
8
+ this.errorUri = errorUri;
9
+ }
10
+ }
11
+ export class OAuthIssuerMismatchError extends Error {
12
+ /** `undefined` when no authorization server metadata was discovered. */
13
+ expected;
14
+ /** `undefined` when an authorization response lacks the `iss` parameter its server promised (RFC 9207). */
15
+ received;
16
+ constructor(expected, received) {
17
+ const format = (issuer) => (issuer === undefined ? "none" : JSON.stringify(issuer));
18
+ super(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`);
19
+ this.name = "OAuthIssuerMismatchError";
20
+ this.expected = expected;
21
+ this.received = received;
22
+ }
23
+ }
24
+ export class OAuthInsecureEndpointError extends Error {
25
+ endpoint;
26
+ constructor(endpoint) {
27
+ super(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`);
28
+ this.name = "OAuthInsecureEndpointError";
29
+ this.endpoint = endpoint;
30
+ }
31
+ }
32
+ export class OAuthRegistrationError extends Error {
33
+ status;
34
+ body;
35
+ constructor(status, body) {
36
+ super(`OAuth dynamic client registration failed with status ${status}: ${body}`);
37
+ this.name = "OAuthRegistrationError";
38
+ this.status = status;
39
+ this.body = body;
40
+ }
41
+ }
42
+ export class McpOAuthAuthorizationRequiredError extends Error {
43
+ constructor() {
44
+ super("MCP OAuth authorization requires user interaction");
45
+ this.name = "McpOAuthAuthorizationRequiredError";
46
+ }
47
+ }
48
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../../src/oauth/errors.ts"],"names":[],"mappings":"AAAA,MAAM,OAAO,UAAW,SAAQ,KAAK;IAC3B,IAAI,CAAS;IACb,QAAQ,CAAqB;IAEtC,YAAY,IAAY,EAAE,OAAe,EAAE,QAAiB;QAC3D,KAAK,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,YAAY,CAAC;QACzB,IAAI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CAAmC,SAAQ,KAAK;IAC5D;QACC,KAAK,CAAC,mDAAmD,CAAC,CAAC;QAC3D,IAAI,CAAC,IAAI,GAAG,oCAAoC,CAAC;IAClD,CAAC;CACD","sourcesContent":["export class OAuthError extends Error {\n\treadonly code: string;\n\treadonly errorUri: string | undefined;\n\n\tconstructor(code: string, message: string, errorUri?: string) {\n\t\tsuper(message || code);\n\t\tthis.name = \"OAuthError\";\n\t\tthis.code = code;\n\t\tthis.errorUri = errorUri;\n\t}\n}\n\nexport class OAuthIssuerMismatchError extends Error {\n\t/** `undefined` when no authorization server metadata was discovered. */\n\treadonly expected: string | undefined;\n\t/** `undefined` when an authorization response lacks the `iss` parameter its server promised (RFC 9207). */\n\treadonly received: string | undefined;\n\n\tconstructor(expected: string | undefined, received: string | undefined) {\n\t\tconst format = (issuer: string | undefined) => (issuer === undefined ? \"none\" : JSON.stringify(issuer));\n\t\tsuper(`OAuth issuer mismatch: expected ${format(expected)}, received ${format(received)}`);\n\t\tthis.name = \"OAuthIssuerMismatchError\";\n\t\tthis.expected = expected;\n\t\tthis.received = received;\n\t}\n}\n\nexport class OAuthInsecureEndpointError extends Error {\n\treadonly endpoint: string;\n\n\tconstructor(endpoint: string) {\n\t\tsuper(`Refusing to send OAuth credentials to non-HTTPS endpoint ${endpoint}`);\n\t\tthis.name = \"OAuthInsecureEndpointError\";\n\t\tthis.endpoint = endpoint;\n\t}\n}\n\nexport class OAuthRegistrationError extends Error {\n\treadonly status: number;\n\treadonly body: string;\n\n\tconstructor(status: number, body: string) {\n\t\tsuper(`OAuth dynamic client registration failed with status ${status}: ${body}`);\n\t\tthis.name = \"OAuthRegistrationError\";\n\t\tthis.status = status;\n\t\tthis.body = body;\n\t}\n}\n\nexport class McpOAuthAuthorizationRequiredError extends Error {\n\tconstructor() {\n\t\tsuper(\"MCP OAuth authorization requires user interaction\");\n\t\tthis.name = \"McpOAuthAuthorizationRequiredError\";\n\t}\n}\n"]}
@@ -0,0 +1,102 @@
1
+ import type { AuthProvider, McpFetch } from "../auth-provider.ts";
2
+ import { type AuthorizationServerMetadata, type OAuthClientInformationFull, type OAuthClientInformationMixed, type OAuthClientMetadata, type OAuthDiscoveryState, type OAuthTokens } from "./types.ts";
3
+ export type AddClientAuthentication = (headers: Headers, params: URLSearchParams, url: string | URL, metadata?: AuthorizationServerMetadata) => void | Promise<void>;
4
+ /** A Client ID Metadata Document: an https URL used as `client_id`, and a redirect URI it lists. */
5
+ export interface OAuthClientMetadataDocument {
6
+ url: string;
7
+ redirectUrl: string;
8
+ }
9
+ export interface OAuthClientProvider {
10
+ readonly redirectUrl: string | URL;
11
+ readonly clientMetadata: OAuthClientMetadata;
12
+ /**
13
+ * Client ID Metadata Document to identify as instead of registering dynamically, or `undefined` to
14
+ * register. Called when no client information is stored; the document is not stored. `metadata` is
15
+ * `undefined` when the authorization server has none; check `client_id_metadata_document_supported`.
16
+ */
17
+ clientMetadataDocument?(metadata: AuthorizationServerMetadata | undefined): OAuthClientMetadataDocument | undefined;
18
+ state?(): string | Promise<string>;
19
+ clientInformation(): OAuthClientInformationMixed | undefined | Promise<OAuthClientInformationMixed | undefined>;
20
+ saveClientInformation?(information: OAuthClientInformationMixed): void | Promise<void>;
21
+ tokens(): OAuthTokens | undefined | Promise<OAuthTokens | undefined>;
22
+ saveTokens(tokens: OAuthTokens): void | Promise<void>;
23
+ redirectToAuthorization(url: URL): void | Promise<void>;
24
+ saveCodeVerifier(verifier: string): void | Promise<void>;
25
+ codeVerifier(): string | Promise<string>;
26
+ addClientAuthentication?: AddClientAuthentication;
27
+ invalidateCredentials?(kind: "all" | "client" | "tokens" | "verifier" | "discovery"): void | Promise<void>;
28
+ saveDiscoveryState?(state: OAuthDiscoveryState): void | Promise<void>;
29
+ discoveryState?(): OAuthDiscoveryState | undefined | Promise<OAuthDiscoveryState | undefined>;
30
+ }
31
+ export interface OAuthFlowOptions {
32
+ serverUrl: string | URL;
33
+ authorizationCode?: string;
34
+ /** `iss` parameter of the authorization response that delivered `authorizationCode` (RFC 9207). */
35
+ iss?: string;
36
+ scope?: string;
37
+ resourceMetadataUrl?: URL;
38
+ /**
39
+ * Authorization server metadata document to use instead of discovery, for servers that advertise a
40
+ * wrong authorization server or none. It is trusted as configured. Must use https, except on loopback.
41
+ */
42
+ authorizationServerMetadataUrl?: URL;
43
+ fetch?: McpFetch;
44
+ /** Aborts every request of the flow. Requests have no time limit of their own; combine with a timeout as needed. */
45
+ signal?: AbortSignal;
46
+ skipIssuerValidation?: boolean;
47
+ /**
48
+ * Go straight to the authorization redirect instead of refreshing stored tokens, for example when the
49
+ * server asks for scopes the current grant lacks (a refresh keeps the old scope).
50
+ */
51
+ skipRefresh?: boolean;
52
+ }
53
+ export type OAuthFlowResult = "AUTHORIZED" | "REDIRECT";
54
+ export interface TokenRequestOptions {
55
+ metadata?: AuthorizationServerMetadata;
56
+ clientInformation: OAuthClientInformationMixed;
57
+ resource?: string;
58
+ addClientAuthentication?: AddClientAuthentication;
59
+ fetch?: McpFetch;
60
+ signal?: AbortSignal;
61
+ }
62
+ export declare function startAuthorization(authorizationServerUrl: string | URL, options: {
63
+ metadata?: AuthorizationServerMetadata;
64
+ clientInformation: OAuthClientInformationMixed;
65
+ redirectUrl: string | URL;
66
+ scope?: string;
67
+ state?: string;
68
+ resource?: string;
69
+ }): Promise<{
70
+ authorizationUrl: URL;
71
+ codeVerifier: string;
72
+ }>;
73
+ export declare function registerClient(authorizationServerUrl: string | URL, options: {
74
+ metadata?: AuthorizationServerMetadata;
75
+ clientMetadata: OAuthClientMetadata;
76
+ scope?: string;
77
+ fetch?: McpFetch;
78
+ signal?: AbortSignal;
79
+ }): Promise<OAuthClientInformationFull>;
80
+ export declare function exchangeAuthorizationCode(authorizationServerUrl: string | URL, options: TokenRequestOptions & {
81
+ code: string;
82
+ codeVerifier: string;
83
+ redirectUrl: string | URL;
84
+ }): Promise<OAuthTokens>;
85
+ export declare function refreshAuthorization(authorizationServerUrl: string | URL, options: TokenRequestOptions & {
86
+ refreshToken: string;
87
+ }): Promise<OAuthTokens>;
88
+ /**
89
+ * Scopes for a step-up authorization: the challenged scopes plus the ones granted so far, since a
90
+ * challenge may list only the missing scopes and a token with just those would lose access the old
91
+ * one had (SEP-2350). Without challenged scopes, `undefined` lets the flow pick its default.
92
+ */
93
+ export declare function stepUpScope(granted: string | undefined, challenged: string | undefined): string | undefined;
94
+ export declare function authorizeMcp(provider: OAuthClientProvider, options: OAuthFlowOptions): Promise<OAuthFlowResult>;
95
+ /**
96
+ * Auth provider for `StreamableHttpTransport`. After a 401 it refreshes the tokens, or throws
97
+ * `McpOAuthAuthorizationRequiredError` when the user has to authorize (again). Concurrent 401s share
98
+ * one refresh, and a request whose token was already replaced is just retried: with rotating refresh
99
+ * tokens, a second refresh with the old refresh token would fail and discard the new grant.
100
+ */
101
+ export declare function adaptOAuthProvider(provider: OAuthClientProvider): AuthProvider;
102
+ //# sourceMappingURL=flow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flow.d.ts","sourceRoot":"","sources":["../../src/oauth/flow.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAuB,MAAM,qBAAqB,CAAC;AAevF,OAAO,EACN,KAAK,2BAA2B,EAEhC,KAAK,0BAA0B,EAC/B,KAAK,2BAA2B,EAChC,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,WAAW,EAGhB,MAAM,YAAY,CAAC;AAEpB,MAAM,MAAM,uBAAuB,GAAG,CACrC,OAAO,EAAE,OAAO,EAChB,MAAM,EAAE,eAAe,EACvB,GAAG,EAAE,MAAM,GAAG,GAAG,EACjB,QAAQ,CAAC,EAAE,2BAA2B,KAClC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;AAE1B,oGAAoG;AACpG,MAAM,WAAW,2BAA2B;IAC3C,GAAG,EAAE,MAAM,CAAC;IACZ,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,mBAAmB;IACnC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