@dev-crowagent/pigeon-mcp 0.0.0-stage → 1.7.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 (136) hide show
  1. package/CHANGELOG.md +143 -0
  2. package/README.md +256 -2
  3. package/THIRD_PARTY_NOTICES/modelcontextprotocol-typescript-sdk.txt +21 -0
  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 +193 -0
  9. package/dist/client.d.ts.map +1 -0
  10. package/dist/client.js +747 -0
  11. package/dist/client.js.map +1 -0
  12. package/dist/config-schema.d.ts +105 -0
  13. package/dist/config-schema.d.ts.map +1 -0
  14. package/dist/config-schema.js +101 -0
  15. package/dist/config-schema.js.map +1 -0
  16. package/dist/config.d.ts +57 -0
  17. package/dist/config.d.ts.map +1 -0
  18. package/dist/config.js +160 -0
  19. package/dist/config.js.map +1 -0
  20. package/dist/index.d.ts +16 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +14 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/input-schema.d.ts +7 -0
  25. package/dist/input-schema.d.ts.map +1 -0
  26. package/dist/input-schema.js +13 -0
  27. package/dist/input-schema.js.map +1 -0
  28. package/dist/model-content.d.ts +19 -0
  29. package/dist/model-content.d.ts.map +1 -0
  30. package/dist/model-content.js +67 -0
  31. package/dist/model-content.js.map +1 -0
  32. package/dist/naming.d.ts +23 -0
  33. package/dist/naming.d.ts.map +1 -0
  34. package/dist/naming.js +37 -0
  35. package/dist/naming.js.map +1 -0
  36. package/dist/oauth/auth-provider.d.ts +52 -0
  37. package/dist/oauth/auth-provider.d.ts.map +1 -0
  38. package/dist/oauth/auth-provider.js +97 -0
  39. package/dist/oauth/auth-provider.js.map +1 -0
  40. package/dist/oauth/callback.d.ts +48 -0
  41. package/dist/oauth/callback.d.ts.map +1 -0
  42. package/dist/oauth/callback.js +121 -0
  43. package/dist/oauth/callback.js.map +1 -0
  44. package/dist/oauth/client-settings.d.ts +107 -0
  45. package/dist/oauth/client-settings.d.ts.map +1 -0
  46. package/dist/oauth/client-settings.js +114 -0
  47. package/dist/oauth/client-settings.js.map +1 -0
  48. package/dist/oauth/discovery.d.ts +30 -0
  49. package/dist/oauth/discovery.d.ts.map +1 -0
  50. package/dist/oauth/discovery.js +156 -0
  51. package/dist/oauth/discovery.js.map +1 -0
  52. package/dist/oauth/errors.d.ts +32 -0
  53. package/dist/oauth/errors.d.ts.map +1 -0
  54. package/dist/oauth/errors.js +58 -0
  55. package/dist/oauth/errors.js.map +1 -0
  56. package/dist/oauth/flow.d.ts +112 -0
  57. package/dist/oauth/flow.d.ts.map +1 -0
  58. package/dist/oauth/flow.js +360 -0
  59. package/dist/oauth/flow.js.map +1 -0
  60. package/dist/oauth/index.d.ts +11 -0
  61. package/dist/oauth/index.d.ts.map +1 -0
  62. package/dist/oauth/index.js +9 -0
  63. package/dist/oauth/index.js.map +1 -0
  64. package/dist/oauth/loopback.d.ts +51 -0
  65. package/dist/oauth/loopback.d.ts.map +1 -0
  66. package/dist/oauth/loopback.js +98 -0
  67. package/dist/oauth/loopback.js.map +1 -0
  68. package/dist/oauth/provider.d.ts +62 -0
  69. package/dist/oauth/provider.d.ts.map +1 -0
  70. package/dist/oauth/provider.js +118 -0
  71. package/dist/oauth/provider.js.map +1 -0
  72. package/dist/oauth/sign-in.d.ts +73 -0
  73. package/dist/oauth/sign-in.d.ts.map +1 -0
  74. package/dist/oauth/sign-in.js +182 -0
  75. package/dist/oauth/sign-in.js.map +1 -0
  76. package/dist/oauth/types.d.ts +83 -0
  77. package/dist/oauth/types.d.ts.map +1 -0
  78. package/dist/oauth/types.js +113 -0
  79. package/dist/oauth/types.js.map +1 -0
  80. package/dist/output-limit.d.ts +24 -0
  81. package/dist/output-limit.d.ts.map +1 -0
  82. package/dist/output-limit.js +58 -0
  83. package/dist/output-limit.js.map +1 -0
  84. package/dist/protocol/content.d.ts +83 -0
  85. package/dist/protocol/content.d.ts.map +1 -0
  86. package/dist/protocol/content.js +41 -0
  87. package/dist/protocol/content.js.map +1 -0
  88. package/dist/protocol/http-headers.d.ts +31 -0
  89. package/dist/protocol/http-headers.d.ts.map +1 -0
  90. package/dist/protocol/http-headers.js +129 -0
  91. package/dist/protocol/http-headers.js.map +1 -0
  92. package/dist/protocol/jsonrpc.d.ts +64 -0
  93. package/dist/protocol/jsonrpc.d.ts.map +1 -0
  94. package/dist/protocol/jsonrpc.js +74 -0
  95. package/dist/protocol/jsonrpc.js.map +1 -0
  96. package/dist/protocol/stateless.d.ts +47 -0
  97. package/dist/protocol/stateless.d.ts.map +1 -0
  98. package/dist/protocol/stateless.js +102 -0
  99. package/dist/protocol/stateless.js.map +1 -0
  100. package/dist/protocol/types.d.ts +156 -0
  101. package/dist/protocol/types.d.ts.map +1 -0
  102. package/dist/protocol/types.js +12 -0
  103. package/dist/protocol/types.js.map +1 -0
  104. package/dist/result-schema.d.ts +10 -0
  105. package/dist/result-schema.d.ts.map +1 -0
  106. package/dist/result-schema.js +78 -0
  107. package/dist/result-schema.js.map +1 -0
  108. package/dist/testing/index.d.ts +2 -0
  109. package/dist/testing/index.d.ts.map +1 -0
  110. package/dist/testing/index.js +2 -0
  111. package/dist/testing/index.js.map +1 -0
  112. package/dist/transports/in-memory.d.ts +19 -0
  113. package/dist/transports/in-memory.d.ts.map +1 -0
  114. package/dist/transports/in-memory.js +50 -0
  115. package/dist/transports/in-memory.js.map +1 -0
  116. package/dist/transports/lines.d.ts +34 -0
  117. package/dist/transports/lines.d.ts.map +1 -0
  118. package/dist/transports/lines.js +85 -0
  119. package/dist/transports/lines.js.map +1 -0
  120. package/dist/transports/pipe.d.ts +49 -0
  121. package/dist/transports/pipe.d.ts.map +1 -0
  122. package/dist/transports/pipe.js +96 -0
  123. package/dist/transports/pipe.js.map +1 -0
  124. package/dist/transports/stdio.d.ts +29 -0
  125. package/dist/transports/stdio.d.ts.map +1 -0
  126. package/dist/transports/stdio.js +170 -0
  127. package/dist/transports/stdio.js.map +1 -0
  128. package/dist/transports/streamable-http.d.ts +113 -0
  129. package/dist/transports/streamable-http.d.ts.map +1 -0
  130. package/dist/transports/streamable-http.js +586 -0
  131. package/dist/transports/streamable-http.js.map +1 -0
  132. package/dist/transports/transport.d.ts +48 -0
  133. package/dist/transports/transport.d.ts.map +1 -0
  134. package/dist/transports/transport.js +38 -0
  135. package/dist/transports/transport.js.map +1 -0
  136. package/package.json +65 -5
@@ -0,0 +1,32 @@
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
+ /**
26
+ * Thrown by `McpOAuthServerStore.withRefreshLock()` when another process holds the refresh lock for the
27
+ * whole wait. `startMcpSignIn()` then skips the refresh and goes to the browser step.
28
+ */
29
+ export declare class McpRefreshLockBusyError extends Error {
30
+ constructor();
31
+ }
32
+ //# 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;AAED;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,KAAK;IACjD,cAGC;CACD"}
@@ -0,0 +1,58 @@
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
+ /**
49
+ * Thrown by `McpOAuthServerStore.withRefreshLock()` when another process holds the refresh lock for the
50
+ * whole wait. `startMcpSignIn()` then skips the refresh and goes to the browser step.
51
+ */
52
+ export class McpRefreshLockBusyError extends Error {
53
+ constructor() {
54
+ super("Another process is refreshing the MCP server's tokens");
55
+ this.name = "McpRefreshLockBusyError";
56
+ }
57
+ }
58
+ //# 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,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;C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GAAG,oCAAoC,CAAC;IAClD,CAAC;CACD;AAED;;;GAGG;AACH,MAAM,OAAO,uBAAwB,SAAQ,KAAK;IACjD;QACC,KAAK,CAAC,uDAAuD,CAAC,CAAC;QAC/D,IAAI,CAAC,IAAI,GAAG,yBAAyB,CAAC;IACvC,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\n/**\n * Thrown by `McpOAuthServerStore.withRefreshLock()` when another process holds the refresh lock for the\n * whole wait. `startMcpSignIn()` then skips the refresh and goes to the browser step.\n */\nexport class McpRefreshLockBusyError extends Error {\n\tconstructor() {\n\t\tsuper(\"Another process is refreshing the MCP server's tokens\");\n\t\tthis.name = \"McpRefreshLockBusyError\";\n\t}\n}\n"]}
@@ -0,0 +1,112 @@
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
+ * Only refresh the stored tokens: return `REDIRECT` instead of registering a client or preparing an
54
+ * authorization request, so a pending authorization (its `state` and PKCE verifier) stays usable.
55
+ */
56
+ refreshOnly?: boolean;
57
+ /**
58
+ * With `authorizationCode`: the redirect URI the authorization request used. The exchange fails before
59
+ * sending the code when the flow would send another one (RFC 6749 section 4.1.3 requires the same).
60
+ */
61
+ authorizationRedirectUrl?: string;
62
+ }
63
+ export type OAuthFlowResult = "AUTHORIZED" | "REDIRECT";
64
+ export interface TokenRequestOptions {
65
+ metadata?: AuthorizationServerMetadata;
66
+ clientInformation: OAuthClientInformationMixed;
67
+ resource?: string;
68
+ addClientAuthentication?: AddClientAuthentication;
69
+ fetch?: McpFetch;
70
+ signal?: AbortSignal;
71
+ }
72
+ export declare function startAuthorization(authorizationServerUrl: string | URL, options: {
73
+ metadata?: AuthorizationServerMetadata;
74
+ clientInformation: OAuthClientInformationMixed;
75
+ redirectUrl: string | URL;
76
+ scope?: string;
77
+ state?: string;
78
+ resource?: string;
79
+ }): Promise<{
80
+ authorizationUrl: URL;
81
+ codeVerifier: string;
82
+ }>;
83
+ export declare function registerClient(authorizationServerUrl: string | URL, options: {
84
+ metadata?: AuthorizationServerMetadata;
85
+ clientMetadata: OAuthClientMetadata;
86
+ scope?: string;
87
+ fetch?: McpFetch;
88
+ signal?: AbortSignal;
89
+ }): Promise<OAuthClientInformationFull>;
90
+ export declare function exchangeAuthorizationCode(authorizationServerUrl: string | URL, options: TokenRequestOptions & {
91
+ code: string;
92
+ codeVerifier: string;
93
+ redirectUrl: string | URL;
94
+ }): Promise<OAuthTokens>;
95
+ export declare function refreshAuthorization(authorizationServerUrl: string | URL, options: TokenRequestOptions & {
96
+ refreshToken: string;
97
+ }): Promise<OAuthTokens>;
98
+ /**
99
+ * Scopes for a step-up authorization: the challenged scopes plus the ones granted so far, since a
100
+ * challenge may list only the missing scopes and a token with just those would lose access the old
101
+ * one had (SEP-2350). Without challenged scopes, `undefined` lets the flow pick its default.
102
+ */
103
+ export declare function stepUpScope(granted: string | undefined, challenged: string | undefined): string | undefined;
104
+ export declare function authorizeMcp(provider: OAuthClientProvider, options: OAuthFlowOptions): Promise<OAuthFlowResult>;
105
+ /**
106
+ * Auth provider for `StreamableHttpTransport`. After a 401 it refreshes the tokens, or throws
107
+ * `McpOAuthAuthorizationRequiredError` when the user has to authorize (again). Concurrent 401s share
108
+ * one refresh, and a request whose token was already replaced is just retried: with rotating refresh
109
+ * tokens, a second refresh with the old refresh token would fail and discard the new grant.
110
+ */
111
+ export declare function adaptOAuthProvider(provider: OAuthClientProvider): AuthProvider;
112
+ //# 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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EAAE,mBAAmB,GAAG;IAAE,YAAY,EAAE,MAAM,CAAA;CAAE,GACrD,OAAO,CAAC,WAAW,CAAC,CAOtB;AAMD;;;;GAIG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,EAAE,UAAU,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAI3G;AAyID,wBAAsB,YAAY,CAAC,QAAQ,EAAE,mBAAmB,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,eAAe,CAAC,CAwBrH;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,mBAAmB,GAAG,YAAY,CA8B9E"}
@@ -0,0 +1,360 @@
1
+ /*
2
+ * Adapted from modelcontextprotocol/typescript-sdk v1.29.0 src/client/auth.ts.
3
+ * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see THIRD_PARTY_NOTICES/.
4
+ * Modified to remove SDK/Zod dependencies and use WebCrypto for PKCE.
5
+ */
6
+ import { isObject } from "../protocol/jsonrpc.js";
7
+ import { discoverAuthorizationServerMetadata, discoverOAuthServerInfo, parseWwwAuthenticate, selectResource, } from "./discovery.js";
8
+ import { McpOAuthAuthorizationRequiredError, OAuthError, OAuthInsecureEndpointError, OAuthIssuerMismatchError, OAuthRegistrationError, } from "./errors.js";
9
+ import { isHttpUrl, parseClientInformation, parseOAuthTokens, } from "./types.js";
10
+ function loopback(hostname) {
11
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
12
+ }
13
+ /**
14
+ * The OpenID Connect `application_type` for `redirect_uris` (MCP SEP-837). Without one, OpenID Connect servers
15
+ * assume `web`, which rejects http loopback redirect URIs. Loopback hosts and custom schemes are native (RFC 8252).
16
+ */
17
+ function applicationType(redirectUris) {
18
+ const native = redirectUris.some((uri) => {
19
+ if (!URL.canParse(uri))
20
+ return false;
21
+ const url = new URL(uri);
22
+ return (url.protocol !== "http:" && url.protocol !== "https:") || loopback(url.hostname);
23
+ });
24
+ return native ? "native" : "web";
25
+ }
26
+ function secureEndpoint(value) {
27
+ const url = new URL(value);
28
+ if (url.protocol !== "https:" && !loopback(url.hostname))
29
+ throw new OAuthInsecureEndpointError(url.href);
30
+ return url;
31
+ }
32
+ function selectClientAuthMethod(information, supported) {
33
+ const hinted = "token_endpoint_auth_method" in information ? information.token_endpoint_auth_method : undefined;
34
+ if (hinted &&
35
+ ["client_secret_basic", "client_secret_post", "none"].includes(hinted) &&
36
+ (supported.length === 0 || supported.includes(hinted))) {
37
+ return hinted;
38
+ }
39
+ if (supported.length === 0)
40
+ return information.client_secret ? "client_secret_basic" : "none";
41
+ if (information.client_secret && supported.includes("client_secret_basic"))
42
+ return "client_secret_basic";
43
+ if (information.client_secret && supported.includes("client_secret_post"))
44
+ return "client_secret_post";
45
+ if (supported.includes("none"))
46
+ return "none";
47
+ return information.client_secret ? "client_secret_post" : "none";
48
+ }
49
+ function applyClientAuthentication(method, information, headers, params) {
50
+ if (method === "client_secret_basic") {
51
+ if (!information.client_secret)
52
+ throw new Error("client_secret_basic requires a client secret");
53
+ headers.set("Authorization", `Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`);
54
+ }
55
+ else {
56
+ params.set("client_id", information.client_id);
57
+ if (method === "client_secret_post" && information.client_secret)
58
+ params.set("client_secret", information.client_secret);
59
+ }
60
+ }
61
+ async function pkce() {
62
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
63
+ const verifier = Buffer.from(bytes).toString("base64url");
64
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
65
+ return { verifier, challenge: Buffer.from(digest).toString("base64url") };
66
+ }
67
+ export async function startAuthorization(authorizationServerUrl, options) {
68
+ const metadata = options.metadata;
69
+ if (metadata && !metadata.response_types_supported.includes("code")) {
70
+ throw new Error("Authorization server does not support authorization codes");
71
+ }
72
+ if (metadata?.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes("S256")) {
73
+ throw new Error("Authorization server does not support PKCE S256");
74
+ }
75
+ const url = new URL(metadata?.authorization_endpoint ?? new URL("/authorize", authorizationServerUrl));
76
+ // Callers open this URL with the platform URL handler, which also launches files and custom protocols.
77
+ if (!isHttpUrl(url))
78
+ throw new Error(`Invalid authorization endpoint ${url.href}`);
79
+ const { verifier, challenge } = await pkce();
80
+ url.searchParams.set("response_type", "code");
81
+ url.searchParams.set("client_id", options.clientInformation.client_id);
82
+ url.searchParams.set("code_challenge", challenge);
83
+ url.searchParams.set("code_challenge_method", "S256");
84
+ url.searchParams.set("redirect_uri", String(options.redirectUrl));
85
+ if (options.state)
86
+ url.searchParams.set("state", options.state);
87
+ if (options.scope)
88
+ url.searchParams.set("scope", options.scope);
89
+ if (options.scope?.split(/\s+/).includes("offline_access"))
90
+ url.searchParams.set("prompt", "consent");
91
+ if (options.resource)
92
+ url.searchParams.set("resource", options.resource);
93
+ return { authorizationUrl: url, codeVerifier: verifier };
94
+ }
95
+ async function tokenRequest(authorizationServerUrl, options, params) {
96
+ const url = secureEndpoint(options.metadata?.token_endpoint ?? new URL("/token", authorizationServerUrl));
97
+ const headers = new Headers({ Accept: "application/json", "content-type": "application/x-www-form-urlencoded" });
98
+ if (options.resource)
99
+ params.set("resource", options.resource);
100
+ if (options.addClientAuthentication) {
101
+ await options.addClientAuthentication(headers, params, url, options.metadata);
102
+ }
103
+ else {
104
+ applyClientAuthentication(selectClientAuthMethod(options.clientInformation, options.metadata?.token_endpoint_auth_methods_supported ?? []), options.clientInformation, headers, params);
105
+ }
106
+ const response = await (options.fetch ?? globalThis.fetch)(url, {
107
+ method: "POST",
108
+ headers,
109
+ body: params,
110
+ signal: options.signal,
111
+ });
112
+ const text = await response.text();
113
+ let value;
114
+ try {
115
+ value = JSON.parse(text);
116
+ }
117
+ catch { }
118
+ // Servers may report OAuth errors with any status, so check the body before the status.
119
+ if (isObject(value) && typeof value.error === "string") {
120
+ throw new OAuthError(value.error, typeof value.error_description === "string" ? value.error_description : value.error, typeof value.error_uri === "string" ? value.error_uri : undefined);
121
+ }
122
+ if (!response.ok)
123
+ throw new OAuthError("server_error", `HTTP ${response.status}: ${text}`);
124
+ return parseOAuthTokens(value);
125
+ }
126
+ export async function registerClient(authorizationServerUrl, options) {
127
+ const endpoint = options.metadata?.registration_endpoint;
128
+ if (options.metadata && !endpoint)
129
+ throw new Error("Authorization server does not support dynamic client registration");
130
+ const response = await (options.fetch ?? globalThis.fetch)(new URL(endpoint ?? new URL("/register", authorizationServerUrl)), {
131
+ method: "POST",
132
+ headers: { Accept: "application/json", "content-type": "application/json" },
133
+ body: JSON.stringify({
134
+ ...options.clientMetadata,
135
+ application_type: options.clientMetadata.application_type ?? applicationType(options.clientMetadata.redirect_uris),
136
+ ...(options.scope ? { scope: options.scope } : {}),
137
+ }),
138
+ signal: options.signal,
139
+ });
140
+ if (!response.ok)
141
+ throw new OAuthRegistrationError(response.status, await response.text());
142
+ return parseClientInformation(await response.json());
143
+ }
144
+ export async function exchangeAuthorizationCode(authorizationServerUrl, options) {
145
+ return tokenRequest(authorizationServerUrl, options, new URLSearchParams({
146
+ grant_type: "authorization_code",
147
+ code: options.code,
148
+ code_verifier: options.codeVerifier,
149
+ redirect_uri: String(options.redirectUrl),
150
+ }));
151
+ }
152
+ export async function refreshAuthorization(authorizationServerUrl, options) {
153
+ const tokens = await tokenRequest(authorizationServerUrl, options, new URLSearchParams({ grant_type: "refresh_token", refresh_token: options.refreshToken }));
154
+ return { refresh_token: options.refreshToken, ...tokens };
155
+ }
156
+ function withScope(tokens, scope) {
157
+ return tokens.scope === undefined && scope ? { ...tokens, scope } : tokens;
158
+ }
159
+ /**
160
+ * Scopes for a step-up authorization: the challenged scopes plus the ones granted so far, since a
161
+ * challenge may list only the missing scopes and a token with just those would lose access the old
162
+ * one had (SEP-2350). Without challenged scopes, `undefined` lets the flow pick its default.
163
+ */
164
+ export function stepUpScope(granted, challenged) {
165
+ if (!challenged)
166
+ return undefined;
167
+ const scopes = [granted, challenged].flatMap((scope) => scope?.split(/\s+/).filter(Boolean) ?? []);
168
+ return [...new Set(scopes)].join(" ");
169
+ }
170
+ async function runFlow(provider, options, use = {}) {
171
+ const metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);
172
+ // With a configured metadata URL, discovery is not cached, so changing the URL applies at once.
173
+ const cached = metadataUrl ? undefined : await provider.discoveryState?.();
174
+ const discovered = cached?.authorizationServerUrl
175
+ ? {
176
+ authorizationServerUrl: cached.authorizationServerUrl,
177
+ authorizationServerMetadata: cached.authorizationServerMetadata ??
178
+ (await discoverAuthorizationServerMetadata(cached.authorizationServerUrl, {
179
+ fetch: options.fetch,
180
+ skipIssuerValidation: options.skipIssuerValidation,
181
+ signal: options.signal,
182
+ })),
183
+ resourceMetadata: cached.resourceMetadata,
184
+ }
185
+ : await discoverOAuthServerInfo(options.serverUrl, {
186
+ resourceMetadataUrl: options.resourceMetadataUrl,
187
+ authorizationServerMetadataUrl: metadataUrl,
188
+ fetch: options.fetch,
189
+ skipIssuerValidation: options.skipIssuerValidation,
190
+ signal: options.signal,
191
+ });
192
+ if (!metadataUrl) {
193
+ await provider.saveDiscoveryState?.({
194
+ ...discovered,
195
+ ...(options.resourceMetadataUrl ? { resourceMetadataUrl: options.resourceMetadataUrl.href } : {}),
196
+ });
197
+ }
198
+ const metadata = discovered.authorizationServerMetadata;
199
+ const resource = selectResource(options.serverUrl, discovered.resourceMetadata);
200
+ // `||`, not `??`: an empty scope (for example from `scopes_supported: []`) falls through to the next source.
201
+ const scope = options.scope || discovered.resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
202
+ const stored = await provider.clientInformation();
203
+ use.storedClientId = stored?.client_id;
204
+ const clientDocument = stored ? undefined : provider.clientMetadataDocument?.(metadata);
205
+ if (clientDocument) {
206
+ const url = new URL(clientDocument.url);
207
+ if (url.protocol !== "https:" || url.pathname === "/")
208
+ throw new Error("Invalid OAuth client metadata URL");
209
+ }
210
+ // The document's redirect URI may differ from the provider's, for example by a server-specific path.
211
+ const redirectUrl = clientDocument?.redirectUrl ?? String(provider.redirectUrl);
212
+ // Checked first: another redirect URI also explains a client that is missing for the exchange.
213
+ if (options.authorizationCode && options.authorizationRedirectUrl !== undefined) {
214
+ if (redirectUrl !== options.authorizationRedirectUrl) {
215
+ throw new Error(`The code exchange would use the redirect URI ${redirectUrl}, but the authorization request used ${options.authorizationRedirectUrl}`);
216
+ }
217
+ }
218
+ let client = stored ?? (clientDocument && { client_id: clientDocument.url });
219
+ if (!client) {
220
+ if (options.refreshOnly)
221
+ return "REDIRECT";
222
+ if (options.authorizationCode) {
223
+ throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");
224
+ }
225
+ if (!provider.saveClientInformation)
226
+ throw new Error("OAuth client information cannot be persisted");
227
+ client = await registerClient(discovered.authorizationServerUrl, {
228
+ metadata,
229
+ clientMetadata: provider.clientMetadata,
230
+ scope,
231
+ fetch: options.fetch,
232
+ signal: options.signal,
233
+ });
234
+ await provider.saveClientInformation(client);
235
+ }
236
+ const tokenOptions = {
237
+ metadata,
238
+ clientInformation: client,
239
+ resource,
240
+ addClientAuthentication: provider.addClientAuthentication,
241
+ fetch: options.fetch,
242
+ signal: options.signal,
243
+ };
244
+ if (options.authorizationCode) {
245
+ // RFC 9207: never send a code from another authorization server to this one. Without metadata there
246
+ // is no issuer to compare with, so any `iss` is rejected.
247
+ const iss = options.iss;
248
+ if (iss !== undefined || metadata?.authorization_response_iss_parameter_supported) {
249
+ if (iss !== metadata?.issuer)
250
+ throw new OAuthIssuerMismatchError(metadata?.issuer, iss);
251
+ }
252
+ const tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {
253
+ ...tokenOptions,
254
+ code: options.authorizationCode,
255
+ codeVerifier: await provider.codeVerifier(),
256
+ redirectUrl,
257
+ });
258
+ // A response without `scope` grants the requested scope (RFC 6749 §5.1). Recorded so a step-up can
259
+ // keep it. Callers pass the options of the authorization request, so `scope` is what was requested.
260
+ await provider.saveTokens(withScope(tokens, scope));
261
+ return "AUTHORIZED";
262
+ }
263
+ const existing = options.skipRefresh ? undefined : await provider.tokens();
264
+ if (existing?.refresh_token) {
265
+ try {
266
+ const tokens = await refreshAuthorization(discovered.authorizationServerUrl, {
267
+ ...tokenOptions,
268
+ refreshToken: existing.refresh_token,
269
+ });
270
+ // A refresh without `scope` keeps the scope of the grant (RFC 6749 §6).
271
+ await provider.saveTokens(withScope(tokens, existing.scope));
272
+ return "AUTHORIZED";
273
+ }
274
+ catch (error) {
275
+ if (options.signal?.aborted || error instanceof OAuthInsecureEndpointError)
276
+ throw error;
277
+ if (error instanceof OAuthError && error.code !== "server_error")
278
+ throw error;
279
+ }
280
+ }
281
+ if (options.refreshOnly)
282
+ return "REDIRECT";
283
+ const state = await provider.state?.();
284
+ const authorization = await startAuthorization(discovered.authorizationServerUrl, {
285
+ metadata,
286
+ clientInformation: client,
287
+ redirectUrl,
288
+ scope,
289
+ state,
290
+ resource,
291
+ });
292
+ await provider.saveCodeVerifier(authorization.codeVerifier);
293
+ await provider.redirectToAuthorization(authorization.authorizationUrl);
294
+ return "REDIRECT";
295
+ }
296
+ export async function authorizeMcp(provider, options) {
297
+ const use = {};
298
+ try {
299
+ return await runFlow(provider, options, use);
300
+ }
301
+ catch (error) {
302
+ if (error instanceof OAuthError && ["invalid_client", "unauthorized_client"].includes(error.code)) {
303
+ // A refresh keeps a pending authorization's `state` and verifier: they are the user's sign-in. A client
304
+ // stored meanwhile (by a sign-in that completed) is not the one the server rejected, so it stays.
305
+ if (options.refreshOnly) {
306
+ if ((await provider.clientInformation())?.client_id === use.storedClientId) {
307
+ for (const kind of ["client", "tokens", "discovery"])
308
+ await provider.invalidateCredentials?.(kind);
309
+ }
310
+ }
311
+ else {
312
+ await provider.invalidateCredentials?.("all");
313
+ }
314
+ return runFlow(provider, options);
315
+ }
316
+ if (error instanceof OAuthError && error.code === "invalid_grant") {
317
+ await provider.invalidateCredentials?.("tokens");
318
+ return runFlow(provider, options);
319
+ }
320
+ throw error;
321
+ }
322
+ }
323
+ /**
324
+ * Auth provider for `StreamableHttpTransport`. After a 401 it refreshes the tokens, or throws
325
+ * `McpOAuthAuthorizationRequiredError` when the user has to authorize (again). Concurrent 401s share
326
+ * one refresh, and a request whose token was already replaced is just retried: with rotating refresh
327
+ * tokens, a second refresh with the old refresh token would fail and discard the new grant.
328
+ */
329
+ export function adaptOAuthProvider(provider) {
330
+ let inFlight;
331
+ return {
332
+ token: async () => (await provider.tokens())?.access_token,
333
+ onUnauthorized: async (context) => {
334
+ const challenge = parseWwwAuthenticate(context.response.headers.get("www-authenticate"));
335
+ const insufficientScope = challenge.error === "insufficient_scope";
336
+ if (!insufficientScope && !inFlight && context.token !== undefined) {
337
+ const current = (await provider.tokens())?.access_token;
338
+ if (current !== undefined && current !== context.token)
339
+ return;
340
+ }
341
+ inFlight ??= Promise.resolve(insufficientScope ? provider.tokens() : undefined)
342
+ .then((granted) => authorizeMcp(provider, {
343
+ serverUrl: context.serverUrl,
344
+ resourceMetadataUrl: challenge.resourceMetadataUrl,
345
+ scope: insufficientScope ? stepUpScope(granted?.scope, challenge.scope) : challenge.scope,
346
+ fetch: context.fetch,
347
+ skipRefresh: insufficientScope,
348
+ }))
349
+ .then((result) => {
350
+ if (result === "REDIRECT")
351
+ throw new McpOAuthAuthorizationRequiredError();
352
+ })
353
+ .finally(() => {
354
+ inFlight = undefined;
355
+ });
356
+ await inFlight;
357
+ },
358
+ };
359
+ }
360
+ //# sourceMappingURL=flow.js.map