@cyanheads/git-mcp-server 2.1.3 → 2.1.4

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![TypeScript](https://img.shields.io/badge/TypeScript-^5.8.3-blue.svg)](https://www.typescriptlang.org/)
4
4
  [![Model Context Protocol](https://img.shields.io/badge/MCP%20SDK-^1.13.0-green.svg)](https://modelcontextprotocol.io/)
5
- [![Version](https://img.shields.io/badge/Version-2.1.3-blue.svg)](./CHANGELOG.md)
5
+ [![Version](https://img.shields.io/badge/Version-2.1.4-blue.svg)](./CHANGELOG.md)
6
6
  [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
7
7
  [![Status](https://img.shields.io/badge/Status-Stable-green.svg)](https://github.com/cyanheads/git-mcp-server/issues)
8
8
  [![GitHub](https://img.shields.io/github/stars/cyanheads/git-mcp-server?style=social)](https://github.com/cyanheads/git-mcp-server)
@@ -29,10 +29,9 @@ This server equips your AI with a comprehensive suite of tools to interact with
29
29
 
30
30
  ## Table of Contents
31
31
 
32
- | [Overview](#overview) | [Features](#features) | [Installation](#installation) |
33
- | :------------------------------ | :-------------------------------------- | :---------------------------- | ------------------- |
32
+ | [Overview](#overview) | [Features](#features) | [Installation](#installation) |
34
33
  | [Configuration](#configuration) | [Project Structure](#project-structure) |
35
- | [Tools](#tools) | [Resources](#resources) | [Development](#development) | [License](#license) |
34
+ | [Tools](#tools) | [Resources](#resources) | [Development](#development) | [License](#license) |
36
35
 
37
36
  ## Overview
38
37
 
@@ -61,7 +60,7 @@ Leverages the robust utilities provided by the `mcp-ts-template`:
61
60
  - **Input Validation/Sanitization**: Uses `zod` for schema validation and custom sanitization logic (crucial for paths).
62
61
  - **Request Context**: Tracking and correlation of operations via unique request IDs using `AsyncLocalStorage`.
63
62
  - **Type Safety**: Strong typing enforced by TypeScript and Zod schemas.
64
- - **HTTP Transport**: High-performance HTTP server using **Hono**, featuring session management with garbage collection, CORS, and IP-based rate limiting.
63
+ - **HTTP Transport**: High-performance HTTP server using **Hono**, featuring session management, CORS, and authentication support.
65
64
  - **Deployment**: Multi-stage `Dockerfile` for creating small, secure production images with native dependency support.
66
65
 
67
66
  ### Git Integration
@@ -100,7 +99,7 @@ Add the following to your MCP client's configuration file (e.g., `cline_mcp_sett
100
99
  }
101
100
  ```
102
101
 
103
- ### If running manually (not via MCP client for development or testing)
102
+ ### If running manually (not via MCP client) for development or testing
104
103
 
105
104
  #### Install via npm
106
105
 
@@ -143,7 +142,10 @@ Configure the server using environment variables. These environmental variables
143
142
  | `MCP_ALLOWED_ORIGINS` | Comma-separated list of allowed origins for CORS (if `MCP_TRANSPORT_TYPE=http`). | (none) |
144
143
  | `MCP_LOG_LEVEL` | Logging level (`debug`, `info`, `notice`, `warning`, `error`, `crit`, `alert`, `emerg`). Inherited from template. | `info` |
145
144
  | `GIT_SIGN_COMMITS` | Set to `"true"` to enable signing attempts for commits made by the `git_commit` tool. Requires server-side Git/key setup (see below). | `false` |
146
- | `MCP_AUTH_SECRET_KEY` | Secret key for signing/verifying authentication tokens (required if auth is enabled in the future). | `''` |
145
+ | `MCP_AUTH_MODE` | Authentication mode: `jwt`, `oauth`, or `none`. | `none` |
146
+ | `MCP_AUTH_SECRET_KEY` | Secret key for JWT validation (if `MCP_AUTH_MODE=jwt`). | `''` |
147
+ | `OAUTH_ISSUER_URL` | OIDC issuer URL for OAuth validation (if `MCP_AUTH_MODE=oauth`). | `''` |
148
+ | `OAUTH_AUDIENCE` | Audience claim for OAuth validation (if `MCP_AUTH_MODE=oauth`). | `''` |
147
149
 
148
150
  ## Project Structure
149
151
 
@@ -201,7 +203,7 @@ _Note: The `path` parameter for most tools defaults to the session's working dir
201
203
 
202
204
  ## Resources
203
205
 
204
- **MCP Resources are not implemented in this version (v2.1.2).**
206
+ **MCP Resources are not implemented in this version (v2.1.4).**
205
207
 
206
208
  This version focuses on the refactored Git tools implementation based on the latest `mcp-ts-template` and MCP SDK v1.13.0. Resource capabilities, previously available, have been temporarily removed during this major update.
207
209
 
@@ -40,14 +40,22 @@ export const config = {
40
40
  mcpAllowedOrigins: process.env.MCP_ALLOWED_ORIGINS?.split(",") || [],
41
41
  /** Flag to enable GPG signing for commits made by the git_commit tool. Requires server-side GPG setup. */
42
42
  gitSignCommits: process.env.GIT_SIGN_COMMITS === "true",
43
+ /** The authentication mode ('jwt', 'oauth', or 'none'). Defaults to 'none'. */
44
+ mcpAuthMode: process.env.MCP_AUTH_MODE || "none",
45
+ /** Secret key for signing/verifying JWTs. Required if mcpAuthMode is 'jwt'. */
46
+ mcpAuthSecretKey: process.env.MCP_AUTH_SECRET_KEY,
47
+ /** The OIDC issuer URL for OAuth token validation. Required if mcpAuthMode is 'oauth'. */
48
+ oauthIssuerUrl: process.env.OAUTH_ISSUER_URL,
49
+ /** The audience claim for OAuth token validation. Required if mcpAuthMode is 'oauth'. */
50
+ oauthAudience: process.env.OAUTH_AUDIENCE,
51
+ /** The JWKS URI for fetching public keys for OAuth. Optional, can be derived from issuer URL. */
52
+ oauthJwksUri: process.env.OAUTH_JWKS_URI,
43
53
  /** Security-related configurations. */
44
54
  security: {
45
55
  // Placeholder for security settings
46
56
  // Example: authRequired: process.env.AUTH_REQUIRED === 'true'
47
57
  /** Indicates if authentication is required for server operations. */
48
58
  authRequired: false,
49
- /** Secret key for signing/verifying authentication tokens (required if authRequired is true). */
50
- mcpAuthSecretKey: process.env.MCP_AUTH_SECRET_KEY || "", // Default to empty string, validation should happen elsewhere
51
59
  },
52
60
  // Note: mcpClient configuration is now loaded separately from mcp-config.json
53
61
  };
@@ -43,9 +43,9 @@ import { initializeGitStatusStateAccessors, registerGitStatusTool, } from "./too
43
43
  import { initializeGitTagStateAccessors, registerGitTagTool, } from "./tools/gitTag/index.js";
44
44
  import { initializeGitWorktreeStateAccessors, registerGitWorktreeTool, } from "./tools/gitWorktree/index.js";
45
45
  import { initializeGitWrapupInstructionsStateAccessors, registerGitWrapupInstructionsTool, } from "./tools/gitWrapupInstructions/index.js";
46
- // Import transport setup functions AND state accessors
47
- import { getHttpSessionWorkingDirectory, setHttpSessionWorkingDirectory, startHttpTransport, } from "./transports/httpTransport.js";
48
- import { connectStdioTransport, getStdioWorkingDirectory, setStdioWorkingDirectory, } from "./transports/stdioTransport.js";
46
+ // Import transport setup functions
47
+ import { startHttpTransport } from "./transports/httpTransport.js";
48
+ import { connectStdioTransport } from "./transports/stdioTransport.js";
49
49
  /**
50
50
  * Creates and configures a new instance of the McpServer.
51
51
  *
@@ -79,7 +79,9 @@ import { connectStdioTransport, getStdioWorkingDirectory, setStdioWorkingDirecto
79
79
  */
80
80
  // Removed sessionId parameter, it will be retrieved from context within tool handlers
81
81
  async function createMcpServerInstance() {
82
- const context = { operation: "createMcpServerInstance" };
82
+ const context = requestContextService.createRequestContext({
83
+ operation: "createMcpServerInstance",
84
+ });
83
85
  logger.info("Initializing MCP server instance", context);
84
86
  // Configure the request context service (used for correlating logs/errors).
85
87
  requestContextService.configure({
@@ -110,6 +112,9 @@ async function createMcpServerInstance() {
110
112
  tools: { listChanged: true },
111
113
  },
112
114
  });
115
+ // Each server instance is isolated per session. This variable will hold the
116
+ // working directory for the duration of this session.
117
+ let sessionWorkingDirectory = undefined;
113
118
  // --- Define Unified State Accessor Functions ---
114
119
  // These functions abstract away the transport type to get/set session state.
115
120
  /** Gets the session ID from the tool's execution context. */
@@ -117,34 +122,21 @@ async function createMcpServerInstance() {
117
122
  // The RequestContext created by the tool registration wrapper should contain the sessionId.
118
123
  return toolContext?.sessionId;
119
124
  };
120
- /** Gets the working directory based on transport type and session ID. */
125
+ /** Gets the working directory for the current session. */
121
126
  const getWorkingDirectory = (sessionId) => {
122
- if (config.mcpTransportType === "http") {
123
- if (!sessionId) {
124
- logger.warning("Attempted to get HTTP working directory without session ID", { ...context, caller: "getWorkingDirectory" });
125
- return undefined;
126
- }
127
- return getHttpSessionWorkingDirectory(sessionId);
128
- }
129
- else {
130
- // For stdio, there's only one implicit session, ID is not needed.
131
- return getStdioWorkingDirectory();
132
- }
127
+ // The working directory is now stored in a variable scoped to this server instance.
128
+ // The sessionId is kept for potential logging or more complex future state management.
129
+ return sessionWorkingDirectory;
133
130
  };
134
- /** Sets the working directory based on transport type and session ID. */
131
+ /** Sets the working directory for the current session. */
135
132
  const setWorkingDirectory = (sessionId, dir) => {
136
- if (config.mcpTransportType === "http") {
137
- if (!sessionId) {
138
- logger.error("Attempted to set HTTP working directory without session ID", { ...context, caller: "setWorkingDirectory", dir });
139
- // Optionally throw an error or just log
140
- return;
141
- }
142
- setHttpSessionWorkingDirectory(sessionId, dir);
143
- }
144
- else {
145
- // For stdio, set the single session's directory.
146
- setStdioWorkingDirectory(dir);
147
- }
133
+ // The working directory is now stored in a variable scoped to this server instance.
134
+ logger.debug("Setting session working directory", {
135
+ ...context,
136
+ sessionId,
137
+ newDirectory: dir,
138
+ });
139
+ sessionWorkingDirectory = dir;
148
140
  };
149
141
  // --- Initialize Tool State Accessors BEFORE Registration ---
150
142
  // Pass the defined unified accessor functions to the initializers.
@@ -254,7 +246,10 @@ async function createMcpServerInstance() {
254
246
  async function startTransport() {
255
247
  // Determine the transport type from the validated configuration.
256
248
  const transportType = config.mcpTransportType;
257
- const context = { operation: "startTransport", transport: transportType };
249
+ const context = requestContextService.createRequestContext({
250
+ operation: "startTransport",
251
+ transport: transportType,
252
+ });
258
253
  logger.info(`Starting transport: ${transportType}`, context);
259
254
  // --- HTTP Transport Setup ---
260
255
  if (transportType === "http") {
@@ -294,7 +289,9 @@ async function startTransport() {
294
289
  * @returns {Promise<void | McpServer>} Resolves upon successful startup (void for http, McpServer for stdio). Rejects on critical failure.
295
290
  */
296
291
  export async function initializeAndStartServer() {
297
- const context = { operation: "initializeAndStartServer" };
292
+ const context = requestContextService.createRequestContext({
293
+ operation: "initializeAndStartServer",
294
+ });
298
295
  logger.info("MCP Server initialization sequence started.", context);
299
296
  try {
300
297
  // Initiate the transport setup based on configuration.
@@ -310,7 +307,11 @@ export async function initializeAndStartServer() {
310
307
  stack: err instanceof Error ? err.stack : undefined,
311
308
  });
312
309
  // Use the centralized error handler for consistent critical error reporting.
313
- ErrorHandler.handleError(err, { ...context, critical: true });
310
+ ErrorHandler.handleError(err, {
311
+ ...context,
312
+ operation: "initializeAndStartServer_Catch",
313
+ critical: true,
314
+ });
314
315
  // Exit the process with a non-zero code to indicate failure.
315
316
  logger.info("Exiting process due to critical initialization error.", context);
316
317
  process.exit(1);
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @fileoverview Defines the AsyncLocalStorage context for authentication information.
3
+ * This module provides a mechanism to store and retrieve authentication details
4
+ * (like scopes and client ID) across asynchronous operations, making it available
5
+ * from the middleware layer down to the tool and resource handlers without
6
+ * drilling props.
7
+ *
8
+ * @module src/mcp-server/transports/auth/core/authContext
9
+ */
10
+ import { AsyncLocalStorage } from "async_hooks";
11
+ /**
12
+ * An instance of AsyncLocalStorage to hold the authentication context (`AuthStore`).
13
+ * This allows `authInfo` to be accessible throughout the async call chain of a request
14
+ * after being set in the authentication middleware.
15
+ *
16
+ * @example
17
+ * // In middleware:
18
+ * await authContext.run({ authInfo }, next);
19
+ *
20
+ * // In a deeper handler:
21
+ * const store = authContext.getStore();
22
+ * const scopes = store?.authInfo.scopes;
23
+ */
24
+ export const authContext = new AsyncLocalStorage();
@@ -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,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,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,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,127 @@
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 { ErrorHandler } from "../../../../../utils/internal/errorHandler.js";
14
+ import { logger, requestContextService } from "../../../../../utils/index.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.", {
47
+ error: error,
48
+ context: requestContextService.createRequestContext({
49
+ operation: "oauthMiddlewareSetup",
50
+ }),
51
+ });
52
+ // Prevent server from starting if JWKS setup fails in oauth mode
53
+ process.exit(1);
54
+ }
55
+ }
56
+ /**
57
+ * Hono middleware for verifying OAuth 2.1 JWT Bearer tokens.
58
+ * It validates the token and uses AsyncLocalStorage to pass auth info.
59
+ * @param c - The Hono context object.
60
+ * @param next - The function to call to proceed to the next middleware.
61
+ */
62
+ export async function oauthMiddleware(c, next) {
63
+ // If OAuth is not the configured auth mode, skip this middleware.
64
+ if (config.mcpAuthMode !== "oauth") {
65
+ return await next();
66
+ }
67
+ const context = requestContextService.createRequestContext({
68
+ operation: "oauthMiddleware",
69
+ httpMethod: c.req.method,
70
+ httpPath: c.req.path,
71
+ });
72
+ if (!jwks) {
73
+ // This should not happen if startup validation is correct, but it's a safeguard.
74
+ // This should not happen if startup validation is correct, but it's a safeguard.
75
+ throw new McpError(BaseErrorCode.CONFIGURATION_ERROR, "OAuth middleware is active, but JWKS client is not initialized.", context);
76
+ }
77
+ const authHeader = c.req.header("Authorization");
78
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
79
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, "Missing or invalid token format.");
80
+ }
81
+ const token = authHeader.substring(7);
82
+ try {
83
+ const { payload } = await jwtVerify(token, jwks, {
84
+ issuer: config.oauthIssuerUrl,
85
+ audience: config.oauthAudience,
86
+ });
87
+ // The 'scope' claim is typically a space-delimited string in OAuth 2.1.
88
+ const scopes = typeof payload.scope === "string" ? payload.scope.split(" ") : [];
89
+ if (scopes.length === 0) {
90
+ logger.warning("Authentication failed: Token contains no scopes, but scopes are required.", { ...context, jwtPayloadKeys: Object.keys(payload) });
91
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, "Token must contain valid, non-empty scopes.");
92
+ }
93
+ const clientId = typeof payload.client_id === "string" ? payload.client_id : undefined;
94
+ if (!clientId) {
95
+ logger.warning("Authentication failed: OAuth token 'client_id' claim is missing or not a string.", { ...context, jwtPayloadKeys: Object.keys(payload) });
96
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, "Invalid token, missing client identifier.");
97
+ }
98
+ const authInfo = {
99
+ token,
100
+ clientId,
101
+ scopes,
102
+ subject: typeof payload.sub === "string" ? payload.sub : undefined,
103
+ };
104
+ // Attach to the raw request for potential legacy compatibility and
105
+ // store in AsyncLocalStorage for modern, safe access in handlers.
106
+ c.env.incoming.auth = authInfo;
107
+ await authContext.run({ authInfo }, next);
108
+ }
109
+ catch (error) {
110
+ if (error instanceof Error && error.name === "JWTExpired") {
111
+ logger.warning("Authentication failed: OAuth token expired.", context);
112
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, "Token expired.");
113
+ }
114
+ const handledError = ErrorHandler.handleError(error, {
115
+ operation: "oauthMiddleware",
116
+ context,
117
+ rethrow: false, // We will throw a new McpError below
118
+ });
119
+ // Ensure we always throw an McpError for consistency
120
+ if (handledError instanceof McpError) {
121
+ throw handledError;
122
+ }
123
+ else {
124
+ throw new McpError(BaseErrorCode.UNAUTHORIZED, `Unauthorized: ${handledError.message || "Invalid token"}`, { originalError: handledError.name });
125
+ }
126
+ }
127
+ }
@@ -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
+ };