@cyanheads/pubchem-mcp-server 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 (127) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +236 -0
  3. package/dist/config/index.d.ts +98 -0
  4. package/dist/config/index.js +326 -0
  5. package/dist/index.d.ts +24 -0
  6. package/dist/index.js +214 -0
  7. package/dist/mcp-server/server.d.ts +21 -0
  8. package/dist/mcp-server/server.js +124 -0
  9. package/dist/mcp-server/tools/fetchAssaySummary/index.d.ts +7 -0
  10. package/dist/mcp-server/tools/fetchAssaySummary/index.js +7 -0
  11. package/dist/mcp-server/tools/fetchAssaySummary/logic.d.ts +71 -0
  12. package/dist/mcp-server/tools/fetchAssaySummary/logic.js +96 -0
  13. package/dist/mcp-server/tools/fetchAssaySummary/registration.d.ts +12 -0
  14. package/dist/mcp-server/tools/fetchAssaySummary/registration.js +68 -0
  15. package/dist/mcp-server/tools/fetchCompoundProperties/index.d.ts +7 -0
  16. package/dist/mcp-server/tools/fetchCompoundProperties/index.js +7 -0
  17. package/dist/mcp-server/tools/fetchCompoundProperties/logic.d.ts +131 -0
  18. package/dist/mcp-server/tools/fetchCompoundProperties/logic.js +100 -0
  19. package/dist/mcp-server/tools/fetchCompoundProperties/registration.d.ts +13 -0
  20. package/dist/mcp-server/tools/fetchCompoundProperties/registration.js +52 -0
  21. package/dist/mcp-server/tools/fetchCompoundXrefs/index.d.ts +7 -0
  22. package/dist/mcp-server/tools/fetchCompoundXrefs/index.js +7 -0
  23. package/dist/mcp-server/tools/fetchCompoundXrefs/logic.d.ts +89 -0
  24. package/dist/mcp-server/tools/fetchCompoundXrefs/logic.js +145 -0
  25. package/dist/mcp-server/tools/fetchCompoundXrefs/registration.d.ts +13 -0
  26. package/dist/mcp-server/tools/fetchCompoundXrefs/registration.js +52 -0
  27. package/dist/mcp-server/tools/fetchSubstanceDetails/index.d.ts +7 -0
  28. package/dist/mcp-server/tools/fetchSubstanceDetails/index.js +7 -0
  29. package/dist/mcp-server/tools/fetchSubstanceDetails/logic.d.ts +69 -0
  30. package/dist/mcp-server/tools/fetchSubstanceDetails/logic.js +97 -0
  31. package/dist/mcp-server/tools/fetchSubstanceDetails/registration.d.ts +13 -0
  32. package/dist/mcp-server/tools/fetchSubstanceDetails/registration.js +79 -0
  33. package/dist/mcp-server/tools/getCompoundImage/index.d.ts +7 -0
  34. package/dist/mcp-server/tools/getCompoundImage/index.js +7 -0
  35. package/dist/mcp-server/tools/getCompoundImage/logic.d.ts +42 -0
  36. package/dist/mcp-server/tools/getCompoundImage/logic.js +68 -0
  37. package/dist/mcp-server/tools/getCompoundImage/registration.d.ts +12 -0
  38. package/dist/mcp-server/tools/getCompoundImage/registration.js +57 -0
  39. package/dist/mcp-server/tools/searchAssaysByTarget/index.d.ts +7 -0
  40. package/dist/mcp-server/tools/searchAssaysByTarget/index.js +7 -0
  41. package/dist/mcp-server/tools/searchAssaysByTarget/logic.d.ts +35 -0
  42. package/dist/mcp-server/tools/searchAssaysByTarget/logic.js +64 -0
  43. package/dist/mcp-server/tools/searchAssaysByTarget/registration.d.ts +12 -0
  44. package/dist/mcp-server/tools/searchAssaysByTarget/registration.js +62 -0
  45. package/dist/mcp-server/tools/searchCompoundByIdentifier/index.d.ts +7 -0
  46. package/dist/mcp-server/tools/searchCompoundByIdentifier/index.js +7 -0
  47. package/dist/mcp-server/tools/searchCompoundByIdentifier/logic.d.ts +35 -0
  48. package/dist/mcp-server/tools/searchCompoundByIdentifier/logic.js +59 -0
  49. package/dist/mcp-server/tools/searchCompoundByIdentifier/registration.d.ts +12 -0
  50. package/dist/mcp-server/tools/searchCompoundByIdentifier/registration.js +51 -0
  51. package/dist/mcp-server/tools/searchCompoundsByFormula/index.d.ts +7 -0
  52. package/dist/mcp-server/tools/searchCompoundsByFormula/index.js +7 -0
  53. package/dist/mcp-server/tools/searchCompoundsByFormula/logic.d.ts +38 -0
  54. package/dist/mcp-server/tools/searchCompoundsByFormula/logic.js +75 -0
  55. package/dist/mcp-server/tools/searchCompoundsByFormula/registration.d.ts +12 -0
  56. package/dist/mcp-server/tools/searchCompoundsByFormula/registration.js +62 -0
  57. package/dist/mcp-server/tools/searchCompoundsBySimilarity/index.d.ts +7 -0
  58. package/dist/mcp-server/tools/searchCompoundsBySimilarity/index.js +7 -0
  59. package/dist/mcp-server/tools/searchCompoundsBySimilarity/logic.d.ts +41 -0
  60. package/dist/mcp-server/tools/searchCompoundsBySimilarity/logic.js +82 -0
  61. package/dist/mcp-server/tools/searchCompoundsBySimilarity/registration.d.ts +12 -0
  62. package/dist/mcp-server/tools/searchCompoundsBySimilarity/registration.js +62 -0
  63. package/dist/mcp-server/tools/searchCompoundsByStructure/index.d.ts +7 -0
  64. package/dist/mcp-server/tools/searchCompoundsByStructure/index.js +7 -0
  65. package/dist/mcp-server/tools/searchCompoundsByStructure/logic.d.ts +41 -0
  66. package/dist/mcp-server/tools/searchCompoundsByStructure/logic.js +78 -0
  67. package/dist/mcp-server/tools/searchCompoundsByStructure/registration.d.ts +13 -0
  68. package/dist/mcp-server/tools/searchCompoundsByStructure/registration.js +63 -0
  69. package/dist/mcp-server/transports/auth/core/authContext.d.ts +33 -0
  70. package/dist/mcp-server/transports/auth/core/authContext.js +24 -0
  71. package/dist/mcp-server/transports/auth/core/authTypes.d.ts +17 -0
  72. package/dist/mcp-server/transports/auth/core/authTypes.js +5 -0
  73. package/dist/mcp-server/transports/auth/core/authUtils.d.ts +18 -0
  74. package/dist/mcp-server/transports/auth/core/authUtils.js +45 -0
  75. package/dist/mcp-server/transports/auth/index.d.ts +10 -0
  76. package/dist/mcp-server/transports/auth/index.js +9 -0
  77. package/dist/mcp-server/transports/auth/strategies/jwt/jwtMiddleware.d.ts +27 -0
  78. package/dist/mcp-server/transports/auth/strategies/jwt/jwtMiddleware.js +149 -0
  79. package/dist/mcp-server/transports/auth/strategies/oauth/oauthMiddleware.d.ts +20 -0
  80. package/dist/mcp-server/transports/auth/strategies/oauth/oauthMiddleware.js +124 -0
  81. package/dist/mcp-server/transports/httpErrorHandler.d.ts +26 -0
  82. package/dist/mcp-server/transports/httpErrorHandler.js +73 -0
  83. package/dist/mcp-server/transports/httpTransport.d.ts +21 -0
  84. package/dist/mcp-server/transports/httpTransport.js +208 -0
  85. package/dist/mcp-server/transports/stdioTransport.d.ts +42 -0
  86. package/dist/mcp-server/transports/stdioTransport.js +63 -0
  87. package/dist/services/pubchem/pubchemApiClient.d.ts +52 -0
  88. package/dist/services/pubchem/pubchemApiClient.js +120 -0
  89. package/dist/types-global/errors.d.ts +127 -0
  90. package/dist/types-global/errors.js +126 -0
  91. package/dist/utils/index.d.ts +12 -0
  92. package/dist/utils/index.js +20 -0
  93. package/dist/utils/internal/errorHandler.d.ts +176 -0
  94. package/dist/utils/internal/errorHandler.js +335 -0
  95. package/dist/utils/internal/index.d.ts +9 -0
  96. package/dist/utils/internal/index.js +9 -0
  97. package/dist/utils/internal/logger.d.ts +148 -0
  98. package/dist/utils/internal/logger.js +430 -0
  99. package/dist/utils/internal/requestContext.d.ts +83 -0
  100. package/dist/utils/internal/requestContext.js +72 -0
  101. package/dist/utils/metrics/index.d.ts +7 -0
  102. package/dist/utils/metrics/index.js +7 -0
  103. package/dist/utils/metrics/tokenCounter.d.ts +35 -0
  104. package/dist/utils/metrics/tokenCounter.js +110 -0
  105. package/dist/utils/network/fetchWithTimeout.d.ts +21 -0
  106. package/dist/utils/network/fetchWithTimeout.js +59 -0
  107. package/dist/utils/network/index.d.ts +6 -0
  108. package/dist/utils/network/index.js +5 -0
  109. package/dist/utils/parsing/dateParser.d.ts +73 -0
  110. package/dist/utils/parsing/dateParser.js +107 -0
  111. package/dist/utils/parsing/index.d.ts +8 -0
  112. package/dist/utils/parsing/index.js +8 -0
  113. package/dist/utils/parsing/jsonParser.d.ts +82 -0
  114. package/dist/utils/parsing/jsonParser.js +126 -0
  115. package/dist/utils/scheduling/index.d.ts +6 -0
  116. package/dist/utils/scheduling/index.js +6 -0
  117. package/dist/utils/scheduling/scheduler.d.ts +72 -0
  118. package/dist/utils/scheduling/scheduler.js +152 -0
  119. package/dist/utils/security/idGenerator.d.ts +137 -0
  120. package/dist/utils/security/idGenerator.js +215 -0
  121. package/dist/utils/security/index.d.ts +9 -0
  122. package/dist/utils/security/index.js +9 -0
  123. package/dist/utils/security/rateLimiter.d.ts +108 -0
  124. package/dist/utils/security/rateLimiter.js +179 -0
  125. package/dist/utils/security/sanitization.d.ts +184 -0
  126. package/dist/utils/security/sanitization.js +453 -0
  127. package/package.json +108 -0
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @fileoverview Shared types for authentication middleware.
3
+ * @module src/mcp-server/transports/auth/core/auth.types
4
+ */
5
+ import type { AuthInfo as SdkAuthInfo } from "@modelcontextprotocol/sdk/server/auth/types.js";
6
+ /**
7
+ * Defines the structure for authentication information derived from a token.
8
+ * It extends the base SDK type to include common optional claims.
9
+ */
10
+ export type AuthInfo = SdkAuthInfo & {
11
+ subject?: string;
12
+ };
13
+ declare module "http" {
14
+ interface IncomingMessage {
15
+ auth?: AuthInfo;
16
+ }
17
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @fileoverview Shared types for authentication middleware.
3
+ * @module src/mcp-server/transports/auth/core/auth.types
4
+ */
5
+ export {};
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @fileoverview Provides utility functions for authorization, specifically for
3
+ * checking token scopes against required permissions for a given operation.
4
+ * @module src/mcp-server/transports/auth/core/authUtils
5
+ */
6
+ /**
7
+ * Checks if the current authentication context contains all the specified scopes.
8
+ * This function is designed to be called within tool or resource handlers to
9
+ * enforce scope-based access control. It retrieves the authentication information
10
+ * from `authContext` (AsyncLocalStorage).
11
+ *
12
+ * @param requiredScopes - An array of scope strings that are mandatory for the operation.
13
+ * @throws {McpError} Throws an error with `BaseErrorCode.INTERNAL_ERROR` if the
14
+ * authentication context is missing, which indicates a server configuration issue.
15
+ * @throws {McpError} Throws an error with `BaseErrorCode.FORBIDDEN` if one or
16
+ * more required scopes are not present in the validated token.
17
+ */
18
+ export declare function withRequiredScopes(requiredScopes: string[]): void;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * @fileoverview Provides utility functions for authorization, specifically for
3
+ * checking token scopes against required permissions for a given operation.
4
+ * @module src/mcp-server/transports/auth/core/authUtils
5
+ */
6
+ import { BaseErrorCode, McpError } from "../../../../types-global/errors.js";
7
+ import { logger, requestContextService } from "../../../../utils/index.js";
8
+ import { authContext } from "./authContext.js";
9
+ /**
10
+ * Checks if the current authentication context contains all the specified scopes.
11
+ * This function is designed to be called within tool or resource handlers to
12
+ * enforce scope-based access control. It retrieves the authentication information
13
+ * from `authContext` (AsyncLocalStorage).
14
+ *
15
+ * @param requiredScopes - An array of scope strings that are mandatory for the operation.
16
+ * @throws {McpError} Throws an error with `BaseErrorCode.INTERNAL_ERROR` if the
17
+ * authentication context is missing, which indicates a server configuration issue.
18
+ * @throws {McpError} Throws an error with `BaseErrorCode.FORBIDDEN` if one or
19
+ * more required scopes are not present in the validated token.
20
+ */
21
+ export function withRequiredScopes(requiredScopes) {
22
+ const store = authContext.getStore();
23
+ if (!store || !store.authInfo) {
24
+ // This is a server-side logic error; the auth middleware should always populate this.
25
+ throw new McpError(BaseErrorCode.INTERNAL_ERROR, "Authentication context is missing. This indicates a server configuration error.", requestContextService.createRequestContext({
26
+ operation: "withRequiredScopesCheck",
27
+ error: "AuthStore not found in AsyncLocalStorage.",
28
+ }));
29
+ }
30
+ const { scopes: grantedScopes, clientId } = store.authInfo;
31
+ const grantedScopeSet = new Set(grantedScopes);
32
+ const missingScopes = requiredScopes.filter((scope) => !grantedScopeSet.has(scope));
33
+ if (missingScopes.length > 0) {
34
+ const context = requestContextService.createRequestContext({
35
+ operation: "withRequiredScopesCheck",
36
+ required: requiredScopes,
37
+ granted: grantedScopes,
38
+ missing: missingScopes,
39
+ clientId: clientId,
40
+ subject: store.authInfo.subject,
41
+ });
42
+ logger.warning("Authorization failed: Missing required scopes.", context);
43
+ throw new McpError(BaseErrorCode.FORBIDDEN, `Insufficient permissions. Missing required scopes: ${missingScopes.join(", ")}`, { requiredScopes, missingScopes });
44
+ }
45
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @fileoverview Barrel file for the auth module.
3
+ * Exports core utilities and middleware strategies for easier imports.
4
+ * @module src/mcp-server/transports/auth/index
5
+ */
6
+ export { authContext } from "./core/authContext.js";
7
+ export { withRequiredScopes } from "./core/authUtils.js";
8
+ export type { AuthInfo } from "./core/authTypes.js";
9
+ export { mcpAuthMiddleware as jwtAuthMiddleware } from "./strategies/jwt/jwtMiddleware.js";
10
+ export { oauthMiddleware } from "./strategies/oauth/oauthMiddleware.js";
@@ -0,0 +1,9 @@
1
+ /**
2
+ * @fileoverview Barrel file for the auth module.
3
+ * Exports core utilities and middleware strategies for easier imports.
4
+ * @module src/mcp-server/transports/auth/index
5
+ */
6
+ export { authContext } from "./core/authContext.js";
7
+ export { withRequiredScopes } from "./core/authUtils.js";
8
+ export { mcpAuthMiddleware as jwtAuthMiddleware } from "./strategies/jwt/jwtMiddleware.js";
9
+ export { oauthMiddleware } from "./strategies/oauth/oauthMiddleware.js";
@@ -0,0 +1,27 @@
1
+ /**
2
+ * @fileoverview MCP Authentication Middleware for Bearer Token Validation (JWT) for Hono.
3
+ *
4
+ * This middleware validates JSON Web Tokens (JWT) passed via the 'Authorization' header
5
+ * using the 'Bearer' scheme (e.g., "Authorization: Bearer <your_token>").
6
+ * It verifies the token's signature and expiration using the secret key defined
7
+ * in the configuration (`config.mcpAuthSecretKey`).
8
+ *
9
+ * If the token is valid, an object conforming to the MCP SDK's `AuthInfo` type
10
+ * is attached to `c.env.incoming.auth`. This direct attachment to the raw Node.js
11
+ * request object is for compatibility with the underlying SDK transport, which is
12
+ * not Hono-context-aware.
13
+ * If the token is missing, invalid, or expired, it throws an `McpError`, which is
14
+ * then handled by the centralized `httpErrorHandler`.
15
+ *
16
+ * @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2025-03-26/basic/authorization.mdx | MCP Authorization Specification}
17
+ * @module src/mcp-server/transports/auth/strategies/jwt/jwtMiddleware
18
+ */
19
+ import { HttpBindings } from "@hono/node-server";
20
+ import { Context, Next } from "hono";
21
+ /**
22
+ * Hono middleware for verifying JWT Bearer token authentication.
23
+ * It attaches authentication info to `c.env.incoming.auth` for SDK compatibility with the node server.
24
+ */
25
+ export declare function mcpAuthMiddleware(c: Context<{
26
+ Bindings: HttpBindings;
27
+ }>, next: Next): Promise<void>;
@@ -0,0 +1,149 @@
1
+ /**
2
+ * @fileoverview MCP Authentication Middleware for Bearer Token Validation (JWT) for Hono.
3
+ *
4
+ * This middleware validates JSON Web Tokens (JWT) passed via the 'Authorization' header
5
+ * using the 'Bearer' scheme (e.g., "Authorization: Bearer <your_token>").
6
+ * It verifies the token's signature and expiration using the secret key defined
7
+ * in the configuration (`config.mcpAuthSecretKey`).
8
+ *
9
+ * If the token is valid, an object conforming to the MCP SDK's `AuthInfo` type
10
+ * is attached to `c.env.incoming.auth`. This direct attachment to the raw Node.js
11
+ * request object is for compatibility with the underlying SDK transport, which is
12
+ * not Hono-context-aware.
13
+ * If the token is missing, invalid, or expired, it throws an `McpError`, which is
14
+ * then handled by the centralized `httpErrorHandler`.
15
+ *
16
+ * @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2025-03-26/basic/authorization.mdx | MCP Authorization Specification}
17
+ * @module src/mcp-server/transports/auth/strategies/jwt/jwtMiddleware
18
+ */
19
+ import { jwtVerify } from "jose";
20
+ import { config, environment } from "../../../../../config/index.js";
21
+ import { logger, requestContextService } from "../../../../../utils/index.js";
22
+ import { BaseErrorCode, McpError } from "../../../../../types-global/errors.js";
23
+ import { authContext } from "../../core/authContext.js";
24
+ // Startup Validation: Validate secret key presence on module load.
25
+ if (config.mcpAuthMode === "jwt") {
26
+ if (environment === "production" && !config.mcpAuthSecretKey) {
27
+ logger.fatal("CRITICAL: MCP_AUTH_SECRET_KEY is not set in production environment for JWT auth. Authentication cannot proceed securely.");
28
+ throw new Error("MCP_AUTH_SECRET_KEY must be set in production environment for JWT authentication.");
29
+ }
30
+ else if (!config.mcpAuthSecretKey) {
31
+ logger.warning("MCP_AUTH_SECRET_KEY is not set. JWT auth middleware will bypass checks (DEVELOPMENT ONLY). This is insecure for production.");
32
+ }
33
+ }
34
+ /**
35
+ * Hono middleware for verifying JWT Bearer token authentication.
36
+ * It attaches authentication info to `c.env.incoming.auth` for SDK compatibility with the node server.
37
+ */
38
+ export async function mcpAuthMiddleware(c, next) {
39
+ const context = requestContextService.createRequestContext({
40
+ operation: "mcpAuthMiddleware",
41
+ method: c.req.method,
42
+ path: c.req.path,
43
+ });
44
+ logger.debug("Running MCP Authentication Middleware (Bearer Token Validation)...", context);
45
+ const reqWithAuth = c.env.incoming;
46
+ // If JWT auth is not enabled, skip the middleware.
47
+ if (config.mcpAuthMode !== "jwt") {
48
+ return await next();
49
+ }
50
+ // Development Mode Bypass
51
+ if (!config.mcpAuthSecretKey) {
52
+ if (environment !== "production") {
53
+ logger.warning("Bypassing JWT authentication: MCP_AUTH_SECRET_KEY is not set (DEVELOPMENT ONLY).", context);
54
+ reqWithAuth.auth = {
55
+ token: "dev-mode-placeholder-token",
56
+ clientId: "dev-client-id",
57
+ scopes: ["dev-scope"],
58
+ };
59
+ const authInfo = reqWithAuth.auth;
60
+ logger.debug("Dev mode auth object created.", {
61
+ ...context,
62
+ authDetails: authInfo,
63
+ });
64
+ return await authContext.run({ authInfo }, next);
65
+ }
66
+ else {
67
+ logger.error("FATAL: MCP_AUTH_SECRET_KEY is missing in production. Cannot bypass auth.", context);
68
+ throw new McpError(BaseErrorCode.INTERNAL_ERROR, "Server configuration error: Authentication key missing.");
69
+ }
70
+ }
71
+ const secretKey = new TextEncoder().encode(config.mcpAuthSecretKey);
72
+ const authHeader = c.req.header("Authorization");
73
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
74
+ logger.warning("Authentication failed: Missing or malformed Authorization header (Bearer scheme required).", context);
75
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, "Missing or invalid authentication token format.");
76
+ }
77
+ const tokenParts = authHeader.split(" ");
78
+ if (tokenParts.length !== 2 || tokenParts[0] !== "Bearer" || !tokenParts[1]) {
79
+ logger.warning("Authentication failed: Malformed Bearer token.", context);
80
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, "Malformed authentication token.");
81
+ }
82
+ const rawToken = tokenParts[1];
83
+ try {
84
+ const { payload: decoded } = await jwtVerify(rawToken, secretKey);
85
+ const clientIdFromToken = typeof decoded.cid === "string"
86
+ ? decoded.cid
87
+ : typeof decoded.client_id === "string"
88
+ ? decoded.client_id
89
+ : undefined;
90
+ if (!clientIdFromToken) {
91
+ logger.warning("Authentication failed: JWT 'cid' or 'client_id' claim is missing or not a string.", { ...context, jwtPayloadKeys: Object.keys(decoded) });
92
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, "Invalid token, missing client identifier.");
93
+ }
94
+ let scopesFromToken = [];
95
+ if (Array.isArray(decoded.scp) &&
96
+ decoded.scp.every((s) => typeof s === "string")) {
97
+ scopesFromToken = decoded.scp;
98
+ }
99
+ else if (typeof decoded.scope === "string" &&
100
+ decoded.scope.trim() !== "") {
101
+ scopesFromToken = decoded.scope.split(" ").filter((s) => s);
102
+ if (scopesFromToken.length === 0 && decoded.scope.trim() !== "") {
103
+ scopesFromToken = [decoded.scope.trim()];
104
+ }
105
+ }
106
+ if (scopesFromToken.length === 0) {
107
+ logger.warning("Authentication failed: Token resulted in an empty scope array, and scopes are required.", { ...context, jwtPayloadKeys: Object.keys(decoded) });
108
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, "Token must contain valid, non-empty scopes.");
109
+ }
110
+ reqWithAuth.auth = {
111
+ token: rawToken,
112
+ clientId: clientIdFromToken,
113
+ scopes: scopesFromToken,
114
+ };
115
+ const subClaimForLogging = typeof decoded.sub === "string" ? decoded.sub : undefined;
116
+ const authInfo = reqWithAuth.auth;
117
+ logger.debug("JWT verified successfully. AuthInfo attached to request.", {
118
+ ...context,
119
+ mcpSessionIdContext: subClaimForLogging,
120
+ clientId: authInfo.clientId,
121
+ scopes: authInfo.scopes,
122
+ });
123
+ await authContext.run({ authInfo }, next);
124
+ }
125
+ catch (error) {
126
+ let errorMessage = "Invalid token.";
127
+ let errorCode = BaseErrorCode.UNAUTHORIZED;
128
+ if (error instanceof Error && error.name === "JWTExpired") {
129
+ errorMessage = "Token expired.";
130
+ logger.warning("Authentication failed: Token expired.", {
131
+ ...context,
132
+ errorName: error.name,
133
+ });
134
+ }
135
+ else if (error instanceof Error) {
136
+ errorMessage = `Invalid token: ${error.message}`;
137
+ logger.warning(`Authentication failed: ${errorMessage}`, {
138
+ ...context,
139
+ errorName: error.name,
140
+ });
141
+ }
142
+ else {
143
+ errorMessage = "Unknown verification error.";
144
+ errorCode = BaseErrorCode.INTERNAL_ERROR;
145
+ logger.error("Authentication failed: Unexpected non-error exception during token verification.", { ...context, error });
146
+ }
147
+ throw new McpError(errorCode, errorMessage);
148
+ }
149
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @fileoverview Hono middleware for OAuth 2.1 Bearer Token validation.
3
+ * This middleware extracts a JWT from the Authorization header, validates it against
4
+ * a remote JWKS (JSON Web Key Set), and checks its issuer and audience claims.
5
+ * On success, it populates an AuthInfo object and stores it in an AsyncLocalStorage
6
+ * context for use in downstream handlers.
7
+ *
8
+ * @module src/mcp-server/transports/auth/strategies/oauth/oauthMiddleware
9
+ */
10
+ import { HttpBindings } from "@hono/node-server";
11
+ import { Context, Next } from "hono";
12
+ /**
13
+ * Hono middleware for verifying OAuth 2.1 JWT Bearer tokens.
14
+ * It validates the token and uses AsyncLocalStorage to pass auth info.
15
+ * @param c - The Hono context object.
16
+ * @param next - The function to call to proceed to the next middleware.
17
+ */
18
+ export declare function oauthMiddleware(c: Context<{
19
+ Bindings: HttpBindings;
20
+ }>, next: Next): Promise<void>;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * @fileoverview Hono middleware for OAuth 2.1 Bearer Token validation.
3
+ * This middleware extracts a JWT from the Authorization header, validates it against
4
+ * a remote JWKS (JSON Web Key Set), and checks its issuer and audience claims.
5
+ * On success, it populates an AuthInfo object and stores it in an AsyncLocalStorage
6
+ * context for use in downstream handlers.
7
+ *
8
+ * @module src/mcp-server/transports/auth/strategies/oauth/oauthMiddleware
9
+ */
10
+ import { createRemoteJWKSet, jwtVerify } from "jose";
11
+ import { config } from "../../../../../config/index.js";
12
+ import { BaseErrorCode, McpError } from "../../../../../types-global/errors.js";
13
+ import { logger, requestContextService } from "../../../../../utils/index.js";
14
+ import { ErrorHandler } from "../../../../../utils/internal/errorHandler.js";
15
+ import { authContext } from "../../core/authContext.js";
16
+ // --- Startup Validation ---
17
+ // Ensures that necessary OAuth configuration is present when the mode is 'oauth'.
18
+ if (config.mcpAuthMode === "oauth") {
19
+ if (!config.oauthIssuerUrl) {
20
+ throw new Error("OAUTH_ISSUER_URL must be set when MCP_AUTH_MODE is 'oauth'");
21
+ }
22
+ if (!config.oauthAudience) {
23
+ throw new Error("OAUTH_AUDIENCE must be set when MCP_AUTH_MODE is 'oauth'");
24
+ }
25
+ logger.info("OAuth 2.1 mode enabled. Verifying tokens against issuer.", requestContextService.createRequestContext({
26
+ issuer: config.oauthIssuerUrl,
27
+ audience: config.oauthAudience,
28
+ }));
29
+ }
30
+ // --- JWKS Client Initialization ---
31
+ // The remote JWK set is fetched and cached to avoid network calls on every request.
32
+ let jwks;
33
+ if (config.mcpAuthMode === "oauth" && config.oauthIssuerUrl) {
34
+ try {
35
+ const jwksUrl = new URL(config.oauthJwksUri ||
36
+ `${config.oauthIssuerUrl.replace(/\/$/, "")}/.well-known/jwks.json`);
37
+ jwks = createRemoteJWKSet(jwksUrl, {
38
+ cooldownDuration: 300000, // 5 minutes
39
+ timeoutDuration: 5000, // 5 seconds
40
+ });
41
+ logger.info(`JWKS client initialized for URL: ${jwksUrl.href}`, requestContextService.createRequestContext({
42
+ operation: "oauthMiddlewareSetup",
43
+ }));
44
+ }
45
+ catch (error) {
46
+ logger.fatal("Failed to initialize JWKS client.", error, requestContextService.createRequestContext({
47
+ operation: "oauthMiddlewareSetup",
48
+ }));
49
+ // Prevent server from starting if JWKS setup fails in oauth mode
50
+ process.exit(1);
51
+ }
52
+ }
53
+ /**
54
+ * Hono middleware for verifying OAuth 2.1 JWT Bearer tokens.
55
+ * It validates the token and uses AsyncLocalStorage to pass auth info.
56
+ * @param c - The Hono context object.
57
+ * @param next - The function to call to proceed to the next middleware.
58
+ */
59
+ export async function oauthMiddleware(c, next) {
60
+ // If OAuth is not the configured auth mode, skip this middleware.
61
+ if (config.mcpAuthMode !== "oauth") {
62
+ return await next();
63
+ }
64
+ const context = requestContextService.createRequestContext({
65
+ operation: "oauthMiddleware",
66
+ httpMethod: c.req.method,
67
+ httpPath: c.req.path,
68
+ });
69
+ if (!jwks) {
70
+ // This should not happen if startup validation is correct, but it's a safeguard.
71
+ // This should not happen if startup validation is correct, but it's a safeguard.
72
+ throw new McpError(BaseErrorCode.CONFIGURATION_ERROR, "OAuth middleware is active, but JWKS client is not initialized.", context);
73
+ }
74
+ const authHeader = c.req.header("Authorization");
75
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
76
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, "Missing or invalid token format.");
77
+ }
78
+ const token = authHeader.substring(7);
79
+ try {
80
+ const { payload } = await jwtVerify(token, jwks, {
81
+ issuer: config.oauthIssuerUrl,
82
+ audience: config.oauthAudience,
83
+ });
84
+ // The 'scope' claim is typically a space-delimited string in OAuth 2.1.
85
+ const scopes = typeof payload.scope === "string" ? payload.scope.split(" ") : [];
86
+ if (scopes.length === 0) {
87
+ logger.warning("Authentication failed: Token contains no scopes, but scopes are required.", { ...context, jwtPayloadKeys: Object.keys(payload) });
88
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, "Token must contain valid, non-empty scopes.");
89
+ }
90
+ const clientId = typeof payload.client_id === "string" ? payload.client_id : undefined;
91
+ if (!clientId) {
92
+ logger.warning("Authentication failed: OAuth token 'client_id' claim is missing or not a string.", { ...context, jwtPayloadKeys: Object.keys(payload) });
93
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, "Invalid token, missing client identifier.");
94
+ }
95
+ const authInfo = {
96
+ token,
97
+ clientId,
98
+ scopes,
99
+ subject: typeof payload.sub === "string" ? payload.sub : undefined,
100
+ };
101
+ // Attach to the raw request for potential legacy compatibility and
102
+ // store in AsyncLocalStorage for modern, safe access in handlers.
103
+ c.env.incoming.auth = authInfo;
104
+ await authContext.run({ authInfo }, next);
105
+ }
106
+ catch (error) {
107
+ if (error instanceof Error && error.name === "JWTExpired") {
108
+ logger.warning("Authentication failed: OAuth token expired.", context);
109
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, "Token expired.");
110
+ }
111
+ const handledError = ErrorHandler.handleError(error, {
112
+ operation: "oauthMiddleware",
113
+ context,
114
+ rethrow: false, // We will throw a new McpError below
115
+ });
116
+ // Ensure we always throw an McpError for consistency
117
+ if (handledError instanceof McpError) {
118
+ throw handledError;
119
+ }
120
+ else {
121
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, `Unauthorized: ${handledError.message || "Invalid token"}`, { originalError: handledError.name });
122
+ }
123
+ }
124
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * @fileoverview Centralized error handler for the Hono HTTP transport.
3
+ * This middleware intercepts errors that occur during request processing,
4
+ * standardizes them using the application's ErrorHandler utility, and
5
+ * formats them into a consistent JSON-RPC error response.
6
+ * @module src/mcp-server/transports/httpErrorHandler
7
+ */
8
+ import { Context } from "hono";
9
+ import { BaseErrorCode } from "../../types-global/errors.js";
10
+ /**
11
+ * A centralized error handling middleware for Hono.
12
+ * This function is registered with `app.onError()` and will catch any errors
13
+ * thrown from preceding middleware or route handlers.
14
+ *
15
+ * @param err - The error that was thrown.
16
+ * @param c - The Hono context object for the request.
17
+ * @returns A Response object containing the formatted JSON-RPC error.
18
+ */
19
+ export declare const httpErrorHandler: (err: Error, c: Context) => Promise<Response & import("hono").TypedResponse<{
20
+ jsonrpc: string;
21
+ error: {
22
+ code: number | BaseErrorCode;
23
+ message: string;
24
+ };
25
+ id: string | number | null;
26
+ }, import("hono/utils/http-status").ContentfulStatusCode, "json">>;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * @fileoverview Centralized error handler for the Hono HTTP transport.
3
+ * This middleware intercepts errors that occur during request processing,
4
+ * standardizes them using the application's ErrorHandler utility, and
5
+ * formats them into a consistent JSON-RPC error response.
6
+ * @module src/mcp-server/transports/httpErrorHandler
7
+ */
8
+ import { BaseErrorCode, McpError } from "../../types-global/errors.js";
9
+ import { ErrorHandler, requestContextService } from "../../utils/index.js";
10
+ /**
11
+ * A centralized error handling middleware for Hono.
12
+ * This function is registered with `app.onError()` and will catch any errors
13
+ * thrown from preceding middleware or route handlers.
14
+ *
15
+ * @param err - The error that was thrown.
16
+ * @param c - The Hono context object for the request.
17
+ * @returns A Response object containing the formatted JSON-RPC error.
18
+ */
19
+ export const httpErrorHandler = async (err, c) => {
20
+ const context = requestContextService.createRequestContext({
21
+ operation: "httpErrorHandler",
22
+ path: c.req.path,
23
+ method: c.req.method,
24
+ });
25
+ const handledError = ErrorHandler.handleError(err, {
26
+ operation: "httpTransport",
27
+ context,
28
+ });
29
+ let status = 500;
30
+ if (handledError instanceof McpError) {
31
+ switch (handledError.code) {
32
+ case BaseErrorCode.NOT_FOUND:
33
+ status = 404;
34
+ break;
35
+ case BaseErrorCode.UNAUTHORIZED:
36
+ status = 401;
37
+ break;
38
+ case BaseErrorCode.FORBIDDEN:
39
+ status = 403;
40
+ break;
41
+ case BaseErrorCode.VALIDATION_ERROR:
42
+ status = 400;
43
+ break;
44
+ case BaseErrorCode.CONFLICT:
45
+ status = 409;
46
+ break;
47
+ case BaseErrorCode.RATE_LIMITED:
48
+ status = 429;
49
+ break;
50
+ default:
51
+ status = 500;
52
+ }
53
+ }
54
+ // Attempt to get the request ID from the body, but don't fail if it's not there or unreadable.
55
+ let requestId = null;
56
+ try {
57
+ const body = await c.req.json();
58
+ requestId = body?.id || null;
59
+ }
60
+ catch {
61
+ // Ignore parsing errors, requestId will remain null
62
+ }
63
+ const errorCode = handledError instanceof McpError ? handledError.code : -32603;
64
+ c.status(status);
65
+ return c.json({
66
+ jsonrpc: "2.0",
67
+ error: {
68
+ code: errorCode,
69
+ message: handledError.message,
70
+ },
71
+ id: requestId,
72
+ });
73
+ };
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @fileoverview Configures and starts the Streamable HTTP MCP transport using Hono.
3
+ * This module integrates the `@modelcontextprotocol/sdk`'s `StreamableHTTPServerTransport`
4
+ * into a Hono web server. Its responsibilities include:
5
+ * - Creating a Hono server instance.
6
+ * - Applying and configuring middleware for CORS, rate limiting, and authentication (JWT/OAuth).
7
+ * - Defining the routes (`/mcp` endpoint for POST, GET, DELETE) to handle the MCP lifecycle.
8
+ * - Orchestrating session management by mapping session IDs to SDK transport instances.
9
+ * - Implementing port-binding logic with automatic retry on conflicts.
10
+ *
11
+ * The underlying implementation of the MCP Streamable HTTP specification, including
12
+ * Server-Sent Events (SSE) for streaming, is handled by the SDK's transport class.
13
+ *
14
+ * Specification Reference:
15
+ * https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2025-03-26/basic/transports.mdx#streamable-http
16
+ * @module src/mcp-server/transports/httpTransport
17
+ */
18
+ import { ServerType } from "@hono/node-server";
19
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
20
+ import { RequestContext } from "../../utils/index.js";
21
+ export declare function startHttpTransport(createServerInstanceFn: () => Promise<McpServer>, parentContext: RequestContext): Promise<ServerType>;