@ttoss/http-server-mcp 0.16.0 → 0.16.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.
package/dist/index.d.cts CHANGED
@@ -3,6 +3,7 @@
3
3
  import { McpServer, McpServer as McpServer$1 } from "@modelcontextprotocol/sdk/server/mcp.js";
4
4
  import { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
5
5
  import { Router } from "@ttoss/http-server";
6
+ import { OAuthVerifyOptions } from "@ttoss/http-server-oauth";
6
7
  import accepts from "accepts";
7
8
  import { AsyncLocalStorage } from "async_hooks";
8
9
  import Cookies from "cookies";
@@ -665,325 +666,23 @@ declare namespace Application {
665
666
  const HttpError: typeof HttpErrors.HttpError;
666
667
  }
667
668
  //#endregion
668
- //#region src/auth.d.ts
669
- /** Amazon Cognito user pool configuration for JWT verification. */
670
- interface CognitoUserPoolConfig {
671
- /** The Cognito User Pool ID (e.g. `us-east-1_abc123`). */
672
- userPoolId: string;
673
- /**
674
- * Which token type to verify.
675
- * @default 'access'
676
- */
677
- tokenUse?: 'access' | 'id';
678
- /** The app client ID registered in the User Pool. */
679
- clientId: string;
680
- }
669
+ //#region src/index.d.ts
670
+ type Context$1 = Application.Context;
681
671
  /**
682
- * Authentication options for the MCP router.
683
- *
684
- * Supply either `cognitoUserPool` (uses `CognitoJwtVerifier` from
685
- * `@ttoss/auth-core`) or a custom `verifyToken` function — not both.
672
+ * Authentication options for the MCP endpoint. Extends the `@ttoss/http-server`
673
+ * OAuth verification options with the optional protected-resource metadata
674
+ * endpoint that MCP clients fetch for discovery.
686
675
  */
687
- interface McpAuthOptions {
688
- /**
689
- * Amazon Cognito user pool config. When provided, the router creates a
690
- * `CognitoJwtVerifier` and validates every incoming Bearer token against it.
691
- */
692
- cognitoUserPool?: CognitoUserPoolConfig;
693
- /**
694
- * Custom token verifier for non-Cognito providers (Auth0, Keycloak, …).
695
- * Receives the raw Bearer token string. Should resolve with the verified
696
- * payload or reject/throw on failure.
697
- */
698
- verifyToken?: (token: string) => Promise<unknown>;
699
- /**
700
- * Router-level scope guard. All listed scopes must be present on the token
701
- * for any MCP request to be allowed. Returns 403 if any scope is missing.
702
- *
703
- * Cognito encodes scopes as a space-separated string in `payload.scope`.
704
- *
705
- * @example ['mcp:access']
706
- */
707
- requiredScopes?: string[];
676
+ interface McpAuthOptions extends OAuthVerifyOptions {
708
677
  /**
709
- * URL of this MCP server, used in the OAuth Protected Resource Metadata
710
- * response (`/.well-known/oauth-protected-resource`). Both this field and
711
- * `authorizationServerUrl` must be provided to enable the endpoint.
678
+ * URL of this MCP server, surfaced in the OAuth Protected Resource Metadata
679
+ * response. Both this and `authorizationServerUrl` must be set to serve
680
+ * `/.well-known/oauth-protected-resource`.
712
681
  */
713
682
  resourceServerUrl?: string;
714
- /**
715
- * URL of the OAuth Authorization Server that issues tokens for this resource.
716
- * Enables `/.well-known/oauth-protected-resource` for MCP client auto-discovery
717
- * (RFC 9728) when combined with `resourceServerUrl`.
718
- */
683
+ /** URL of the OAuth Authorization Server that issues tokens for this resource. */
719
684
  authorizationServerUrl?: string;
720
- /**
721
- * JSON-RPC methods (read from `body.method`) that bypass token verification,
722
- * so MCP clients can discover the server before authenticating. Set to an
723
- * empty array to require a token for every method.
724
- *
725
- * @default ['initialize', 'tools/list']
726
- */
727
- publicMethods?: string[];
728
- /**
729
- * When set, a `401` from verification responds with
730
- * `WWW-Authenticate: Bearer resource_metadata="<resourceMetadataUrl>"`
731
- * (RFC 9728) so MCP clients can auto-discover the authorization server.
732
- * When omitted, the header falls back to a bare `Bearer`.
733
- *
734
- * @example 'https://mcp.example.com/.well-known/oauth-protected-resource'
735
- */
736
- resourceMetadataUrl?: string;
737
- }
738
- //#endregion
739
- //#region src/authServerTypes.d.ts
740
- type Context$1 = Application.Context;
741
- /**
742
- * OAuth 2.0 client metadata as supplied by a client during Dynamic Client
743
- * Registration (RFC 7591). Apps may persist additional fields verbatim.
744
- */
745
- interface OAuthClientMetadata {
746
- /** Allowed redirect URIs. At least one is required for the auth-code flow. */
747
- redirect_uris: string[];
748
- /** Human-readable client name shown on consent screens. */
749
- client_name?: string;
750
- /** OAuth grant types the client will use. Defaults to auth-code + refresh. */
751
- grant_types?: string[];
752
- /** OAuth response types the client will use. Defaults to `['code']`. */
753
- response_types?: string[];
754
- /**
755
- * Client authentication method at the token endpoint. `'none'` registers a
756
- * public client (no secret issued); anything else registers a confidential
757
- * client and a `client_secret` is generated.
758
- */
759
- token_endpoint_auth_method?: string;
760
- /** Space-separated scopes the client may request. */
761
- scope?: string;
762
- [key: string]: unknown;
763
- }
764
- /**
765
- * A registered OAuth client as persisted by the app's {@link ClientStore}.
766
- */
767
- interface OAuthClient extends OAuthClientMetadata {
768
- /** Unique client identifier issued by the authorization server. */
769
- client_id: string;
770
- /** Client secret for confidential clients. Absent for public clients. */
771
- client_secret?: string;
772
- /** Unix timestamp (seconds) when the client was registered. */
773
- client_id_issued_at?: number;
774
- }
775
- /**
776
- * App-provided store for OAuth clients. ttoss owns protocol mechanics; the app
777
- * owns persistence (DynamoDB, Postgres, in-memory, …).
778
- */
779
- interface ClientStore {
780
- /** Look up a client by its `client_id`. Return `undefined` if unknown. */
781
- get: (clientId: string) => Promise<OAuthClient | undefined> | OAuthClient | undefined;
782
- /** Persist a newly registered client. */
783
- register: (client: OAuthClient) => Promise<void> | void;
784
- }
785
- /**
786
- * A short-lived authorization code with its bound PKCE challenge and the
787
- * details needed to issue tokens when the code is later exchanged.
788
- */
789
- interface StoredAuthorizationCode {
790
- /** The opaque authorization code value. */
791
- code: string;
792
- /** The `client_id` the code was issued to. */
793
- clientId: string;
794
- /** The redirect URI the code was issued for (must match on exchange). */
795
- redirectUri: string;
796
- /** The PKCE `code_challenge` (S256) bound to this code. */
797
- codeChallenge: string;
798
- /** The scopes granted to this code. */
799
- scopes: string[];
800
- /** The authenticated end-user subject identifier. */
801
- subject: string;
802
- /** Unix timestamp (milliseconds) after which the code is invalid. */
803
- expiresAt: number;
804
- }
805
- /**
806
- * App-provided store for authorization codes. Codes are single-use and
807
- * short-lived; the app decides where to persist them.
808
- */
809
- interface AuthCodeStore {
810
- /** Persist an authorization code. */
811
- save: (code: StoredAuthorizationCode) => Promise<void> | void;
812
- /** Look up an authorization code by its value. */
813
- get: (code: string) => Promise<StoredAuthorizationCode | undefined> | StoredAuthorizationCode | undefined;
814
- /** Remove an authorization code (called on exchange to enforce single use). */
815
- delete: (code: string) => Promise<void> | void;
816
- }
817
- /** Tokens returned by the app's {@link McpAuthServerOptions.issueTokens} hook. */
818
- interface IssuedTokens {
819
- /** The access token string (JWT, opaque, …). */
820
- accessToken: string;
821
- /** Optional refresh token enabling the `refresh_token` grant. */
822
- refreshToken?: string;
823
- /** Access token lifetime in seconds, surfaced as `expires_in`. */
824
- expiresIn?: number;
825
- /** Granted scopes as a space-separated string. Defaults to the bound scopes. */
826
- scope?: string;
827
- }
828
- /** Arguments passed to {@link McpAuthServerOptions.issueTokens}. */
829
- interface IssueTokensArgs {
830
- /** The authenticated end-user subject identifier. */
831
- subject: string;
832
- /** The scopes granted to the token. */
833
- scopes: string[];
834
- /** The client the tokens are being issued to. */
835
- client: OAuthClient;
836
- }
837
- /** The validated authorization request passed to the consent/login hook. */
838
- interface AuthorizeRequest {
839
- /** The requesting `client_id`. */
840
- clientId: string;
841
- /** The validated redirect URI. */
842
- redirectUri: string;
843
- /** The requested scopes. */
844
- scopes: string[];
845
- /** Opaque CSRF/state value to echo back on redirect. */
846
- state?: string;
847
- /** The PKCE `code_challenge`. */
848
- codeChallenge: string;
849
- /** The PKCE challenge method (always `'S256'`). */
850
- codeChallengeMethod: string;
851
- }
852
- /** Arguments passed to {@link McpAuthServerOptions.onAuthorize}. */
853
- interface OnAuthorizeArgs {
854
- /** The Koa context, so the app can read cookies/session or write a response. */
855
- ctx: Context$1;
856
- /** The resolved client making the request. */
857
- client: OAuthClient;
858
- /** The validated authorization request. */
859
- request: AuthorizeRequest;
860
- }
861
- /**
862
- * Result of the app's consent/login hook.
863
- *
864
- * `approved: true` means the end-user is authenticated and has consented — the
865
- * authorization server issues a code and redirects. `approved: false` means the
866
- * app has taken over the response (e.g. redirected to its own login/consent
867
- * page); the authorization server does nothing further.
868
- */
869
- type OnAuthorizeResult = {
870
- approved: true;
871
- subject: string;
872
- scopes?: string[];
873
- } | {
874
- approved: false;
875
- };
876
- /** Arguments passed to {@link McpAuthServerOptions.onRefreshToken}. */
877
- interface OnRefreshTokenArgs {
878
- /** The refresh token presented by the client. */
879
- refreshToken: string;
880
- /** The authenticated client. */
881
- client: OAuthClient;
882
- /** Scopes requested in the refresh request (may be empty). */
883
- scopes: string[];
884
- }
885
- /**
886
- * Result of validating a refresh token. Return `undefined` to reject the token.
887
- */
888
- type OnRefreshTokenResult = {
889
- subject: string;
890
- scopes: string[];
891
- } | undefined;
892
- /** Configuration for {@link createMcpAuthServer}. */
893
- interface McpAuthServerOptions {
894
- /** The authorization server's issuer identifier (its base URL). */
895
- issuer: string;
896
- /** App-provided store for dynamic clients. */
897
- clientStore: ClientStore;
898
- /** App-provided store for short-lived authorization codes. */
899
- authCodeStore: AuthCodeStore;
900
- /**
901
- * App-owned token minting. ttoss never sees the user model or signing keys —
902
- * it hands you the subject/scopes/client and you return the tokens.
903
- */
904
- issueTokens: (args: IssueTokensArgs) => Promise<IssuedTokens> | IssuedTokens;
905
- /**
906
- * App-owned login/consent. Called on every `/authorize` request; return the
907
- * authenticated subject to approve, or take over the response to show your
908
- * own login/consent UI and return `{ approved: false }`.
909
- */
910
- onAuthorize: (args: OnAuthorizeArgs) => Promise<OnAuthorizeResult> | OnAuthorizeResult;
911
- /**
912
- * App-owned refresh-token validation. Required to support the `refresh_token`
913
- * grant; when omitted, refresh requests get `unsupported_grant_type`.
914
- */
915
- onRefreshToken?: (args: OnRefreshTokenArgs) => Promise<OnRefreshTokenResult> | OnRefreshTokenResult;
916
- /** Scopes advertised in discovery metadata (`scopes_supported`). */
917
- scopesSupported?: string[];
918
- /**
919
- * When set, also serves `/.well-known/oauth-protected-resource` (RFC 9728)
920
- * pairing this resource URL with the issuer as its authorization server.
921
- */
922
- resource?: string;
923
- /**
924
- * Authorization code lifetime in seconds.
925
- * @default 600
926
- */
927
- authorizationCodeTtl?: number;
928
- /** Override the default endpoint paths. */
929
- endpoints?: {
930
- /** @default '/authorize' */authorize?: string; /** @default '/token' */
931
- token?: string; /** @default '/register' */
932
- register?: string;
933
- };
934
685
  }
935
- //#endregion
936
- //#region src/authServer.d.ts
937
- /**
938
- * Creates transport-agnostic OAuth 2.1 Authorization Server primitives for MCP.
939
- *
940
- * Mounts the authorization endpoint (`/authorize`, PKCE S256 required), token
941
- * endpoint (`/token`, `authorization_code` + `refresh_token` grants), Dynamic
942
- * Client Registration (`/register`, RFC 7591), and AS metadata discovery
943
- * (`/.well-known/oauth-authorization-server`, RFC 8414). When `resource` is
944
- * set, it also serves the protected-resource metadata (RFC 9728).
945
- *
946
- * ttoss owns only the protocol mechanics — the app supplies its own stores,
947
- * token signing/verification, and login/consent UI through the option hooks, so
948
- * the user model, JWT/IAM, and authentication never leave the consuming app.
949
- *
950
- * @param options - Authorization server configuration and pluggable hooks.
951
- * @returns A Koa `Router` exposing `routes()` / `allowedMethods()`.
952
- *
953
- * @example
954
- * ```typescript
955
- * import { App, bodyParser } from '@ttoss/http-server';
956
- * import { createMcpAuthServer } from '@ttoss/http-server-mcp';
957
- *
958
- * const authServer = createMcpAuthServer({
959
- * issuer: 'https://api.soat.dev',
960
- * clientStore,
961
- * authCodeStore,
962
- * issueTokens: async ({ subject, scopes }) => ({
963
- * accessToken: signJwt({ sub: subject, scope: scopes.join(' ') }),
964
- * refreshToken: createRefreshToken(subject),
965
- * expiresIn: 3600,
966
- * }),
967
- * onAuthorize: async ({ ctx }) => {
968
- * const session = await getSession(ctx);
969
- * if (!session) {
970
- * ctx.redirect('/login');
971
- * return { approved: false };
972
- * }
973
- * return { approved: true, subject: session.userId };
974
- * },
975
- * scopesSupported: ['mcp:access'],
976
- * });
977
- *
978
- * const app = new App();
979
- * app.use(bodyParser());
980
- * app.use(authServer.routes());
981
- * ```
982
- */
983
- declare const createMcpAuthServer: (options: McpAuthServerOptions) => Router;
984
- //#endregion
985
- //#region src/index.d.ts
986
- type Context$2 = Application.Context;
987
686
  /**
988
687
  * Options for a single `apiCall` request.
989
688
  */
@@ -1123,7 +822,7 @@ interface McpRouterOptions {
1123
822
  * getApiHeaders: () => ({ 'x-internal-key': process.env.INTERNAL_API_KEY! })
1124
823
  * ```
1125
824
  */
1126
- getApiHeaders?: (ctx: Context$2) => Record<string, string>;
825
+ getApiHeaders?: (ctx: Context$1) => Record<string, string>;
1127
826
  /**
1128
827
  * OAuth / JWT authentication configuration for the MCP endpoint.
1129
828
  *
@@ -1274,64 +973,5 @@ interface RegisterToolFromSchemaParams {
1274
973
  * ```
1275
974
  */
1276
975
  declare const registerToolFromSchema: (server: McpServer$1, params: RegisterToolFromSchemaParams) => void;
1277
- /**
1278
- * Returns the `WWW-Authenticate` header value for a 401 response on a
1279
- * protected resource, following the MCP auth spec requirement that
1280
- * unauthorized responses advertise the resource metadata URL so MCP
1281
- * clients can bootstrap OAuth discovery.
1282
- *
1283
- * Use this in your own auth middleware when you are not using the built-in
1284
- * `auth` option on `createMcpRouter`.
1285
- *
1286
- * @example
1287
- * ```typescript
1288
- * import { getWwwAuthenticateHeader } from '@ttoss/http-server-mcp';
1289
- *
1290
- * // Inside a Koa middleware
1291
- * ctx.status = 401;
1292
- * ctx.set('WWW-Authenticate', getWwwAuthenticateHeader({ resource: 'https://mcp.example.com' }));
1293
- * ```
1294
- */
1295
- declare const getWwwAuthenticateHeader: (args: {
1296
- /**
1297
- * The resource server URL. The metadata URL is derived as
1298
- * `<resource>/.well-known/oauth-protected-resource` per RFC 9728.
1299
- */
1300
- resource: string;
1301
- }) => string;
1302
- /**
1303
- * Creates a standalone Koa middleware that serves
1304
- * `GET /.well-known/oauth-protected-resource` (RFC 9728) without requiring
1305
- * the built-in `auth` option on `createMcpRouter`.
1306
- *
1307
- * Mount this **before** your own auth middleware so the discovery endpoint
1308
- * remains unauthenticated (MCP clients fetch it before they have a token).
1309
- *
1310
- * @example
1311
- * ```typescript
1312
- * import Koa from 'koa';
1313
- * import { createProtectedResourceMetadataMiddleware } from '@ttoss/http-server-mcp';
1314
- *
1315
- * const app = new Koa();
1316
- * app.use(
1317
- * createProtectedResourceMetadataMiddleware({
1318
- * resource: 'https://mcp.example.com',
1319
- * authorizationServers: ['https://api.example.com'],
1320
- * })
1321
- * );
1322
- * app.use(myOwnAuthMiddleware);
1323
- * ```
1324
- */
1325
- declare const createProtectedResourceMetadataMiddleware: (args: {
1326
- /**
1327
- * The protected resource's identifier URI (the MCP server URL).
1328
- */
1329
- resource: string;
1330
- /**
1331
- * List of authorization server issuer URIs that issue tokens for this
1332
- * resource.
1333
- */
1334
- authorizationServers: string[];
1335
- }) => Application.Middleware;
1336
976
  //#endregion
1337
- export { ApiCallOptions, AuthCodeStore, AuthorizeRequest, ClientStore, type CognitoUserPoolConfig, Context$1 as Context, IssueTokensArgs, IssuedTokens, JsonObjectSchema, type McpAuthOptions, McpAuthServerOptions, McpRouterOptions, McpServer, OAuthClient, OAuthClientMetadata, OnAuthorizeArgs, OnAuthorizeResult, OnRefreshTokenArgs, OnRefreshTokenResult, RegisterToolFromSchemaParams, StoredAuthorizationCode, apiCall, checkScopes, createMcpAuthServer, createMcpRouter, createProtectedResourceMetadataMiddleware, getIdentity, getWwwAuthenticateHeader, registerToolFromSchema, z };
977
+ export { ApiCallOptions, JsonObjectSchema, McpAuthOptions, McpRouterOptions, McpServer, RegisterToolFromSchemaParams, apiCall, checkScopes, createMcpRouter, getIdentity, registerToolFromSchema, z };