@ttoss/http-server-mcp 0.14.0 → 0.16.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.
package/dist/index.d.cts CHANGED
@@ -665,8 +665,325 @@ declare namespace Application {
665
665
  const HttpError: typeof HttpErrors.HttpError;
666
666
  }
667
667
  //#endregion
668
- //#region src/index.d.ts
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
+ }
681
+ /**
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.
686
+ */
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[];
708
+ /**
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.
712
+ */
713
+ 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
+ */
719
+ 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
669
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
+ }
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;
670
987
  /**
671
988
  * Options for a single `apiCall` request.
672
989
  */
@@ -758,58 +1075,6 @@ declare const getIdentity: () => unknown;
758
1075
  * ```
759
1076
  */
760
1077
  declare const checkScopes: (required: string[]) => void;
761
- /** Amazon Cognito user pool configuration for JWT verification. */
762
- interface CognitoUserPoolConfig {
763
- /** The Cognito User Pool ID (e.g. `us-east-1_abc123`). */
764
- userPoolId: string;
765
- /**
766
- * Which token type to verify.
767
- * @default 'access'
768
- */
769
- tokenUse?: 'access' | 'id';
770
- /** The app client ID registered in the User Pool. */
771
- clientId: string;
772
- }
773
- /**
774
- * Authentication options for the MCP router.
775
- *
776
- * Supply either `cognitoUserPool` (uses `CognitoJwtVerifier` from
777
- * `@ttoss/auth-core`) or a custom `verifyToken` function — not both.
778
- */
779
- interface McpAuthOptions {
780
- /**
781
- * Amazon Cognito user pool config. When provided, the router creates a
782
- * `CognitoJwtVerifier` and validates every incoming Bearer token against it.
783
- */
784
- cognitoUserPool?: CognitoUserPoolConfig;
785
- /**
786
- * Custom token verifier for non-Cognito providers (Auth0, Keycloak, …).
787
- * Receives the raw Bearer token string. Should resolve with the verified
788
- * payload or reject/throw on failure.
789
- */
790
- verifyToken?: (token: string) => Promise<unknown>;
791
- /**
792
- * Router-level scope guard. All listed scopes must be present on the token
793
- * for any MCP request to be allowed. Returns 403 if any scope is missing.
794
- *
795
- * Cognito encodes scopes as a space-separated string in `payload.scope`.
796
- *
797
- * @example ['mcp:access']
798
- */
799
- requiredScopes?: string[];
800
- /**
801
- * URL of this MCP server, used in the OAuth Protected Resource Metadata
802
- * response (`/.well-known/oauth-protected-resource`). Both this field and
803
- * `authorizationServerUrl` must be provided to enable the endpoint.
804
- */
805
- resourceServerUrl?: string;
806
- /**
807
- * URL of the OAuth Authorization Server that issues tokens for this resource.
808
- * Enables `/.well-known/oauth-protected-resource` for MCP client auto-discovery
809
- * (RFC 9728) when combined with `resourceServerUrl`.
810
- */
811
- authorizationServerUrl?: string;
812
- }
813
1078
  /**
814
1079
  * Options for configuring the MCP router
815
1080
  */
@@ -858,14 +1123,17 @@ interface McpRouterOptions {
858
1123
  * getApiHeaders: () => ({ 'x-internal-key': process.env.INTERNAL_API_KEY! })
859
1124
  * ```
860
1125
  */
861
- getApiHeaders?: (ctx: Context$1) => Record<string, string>;
1126
+ getApiHeaders?: (ctx: Context$2) => Record<string, string>;
862
1127
  /**
863
1128
  * OAuth / JWT authentication configuration for the MCP endpoint.
864
1129
  *
865
- * When set, every incoming MCP request must include a valid Bearer token in
866
- * the `Authorization` header. Invalid or missing tokens receive a `401`
867
- * response with `WWW-Authenticate: Bearer`. Tokens that fail a
868
- * `requiredScopes` check receive `403`.
1130
+ * When set, incoming MCP requests must include a valid Bearer token in the
1131
+ * `Authorization` header except for `publicMethods` (by default
1132
+ * `initialize` and `tools/list`), which bypass verification so clients can
1133
+ * discover the server before authenticating. Invalid or missing tokens
1134
+ * receive a `401` response with `WWW-Authenticate: Bearer` (or
1135
+ * `Bearer resource_metadata="..."` when `resourceMetadataUrl` is set, per
1136
+ * RFC 9728). Tokens that fail a `requiredScopes` check receive `403`.
869
1137
  *
870
1138
  * The verified token payload is accessible inside tool handlers via
871
1139
  * {@link getIdentity}. Fine-grained per-tool scope checks can be done with
@@ -1066,4 +1334,4 @@ declare const createProtectedResourceMetadataMiddleware: (args: {
1066
1334
  authorizationServers: string[];
1067
1335
  }) => Application.Middleware;
1068
1336
  //#endregion
1069
- export { ApiCallOptions, CognitoUserPoolConfig, JsonObjectSchema, McpAuthOptions, McpRouterOptions, McpServer, RegisterToolFromSchemaParams, apiCall, checkScopes, createMcpRouter, createProtectedResourceMetadataMiddleware, getIdentity, getWwwAuthenticateHeader, registerToolFromSchema, z };
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 };