obsidian-mcp-server 2.0.4 → 2.0.5
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/CHANGELOG.md +9 -0
- package/README.md +80 -88
- package/dist/mcp-server/server.js +2 -2
- package/dist/mcp-server/tools/obsidianListFilesTool/logic.js +5 -4
- package/dist/mcp-server/tools/{obsidianUpdateFileTool → obsidianUpdateNoteTool}/index.d.ts +4 -4
- package/dist/mcp-server/tools/{obsidianUpdateFileTool → obsidianUpdateNoteTool}/index.js +4 -4
- package/dist/mcp-server/tools/{obsidianUpdateFileTool → obsidianUpdateNoteTool}/logic.d.ts +8 -8
- package/dist/mcp-server/tools/{obsidianUpdateFileTool → obsidianUpdateNoteTool}/logic.js +7 -7
- package/dist/mcp-server/tools/{obsidianUpdateFileTool → obsidianUpdateNoteTool}/registration.d.ts +2 -2
- package/dist/mcp-server/tools/{obsidianUpdateFileTool → obsidianUpdateNoteTool}/registration.js +13 -13
- package/dist/mcp-server/transports/{authentication → auth/core}/authContext.d.ts +2 -2
- package/dist/mcp-server/transports/{authentication → auth/core}/authContext.js +1 -1
- package/dist/mcp-server/transports/{authentication/types.d.ts → auth/core/authTypes.d.ts} +1 -1
- package/dist/mcp-server/transports/{authentication/types.js → auth/core/authTypes.js} +1 -1
- package/dist/mcp-server/transports/{authentication → auth/core}/authUtils.d.ts +1 -1
- package/dist/mcp-server/transports/{authentication → auth/core}/authUtils.js +3 -3
- package/dist/mcp-server/transports/auth/index.d.ts +10 -0
- package/dist/mcp-server/transports/auth/index.js +9 -0
- package/dist/mcp-server/transports/{authentication/authMiddleware.d.ts → auth/strategies/jwt/jwtMiddleware.d.ts} +4 -7
- package/dist/mcp-server/transports/{authentication/authMiddleware.js → auth/strategies/jwt/jwtMiddleware.js} +40 -36
- package/dist/mcp-server/transports/{authentication → auth/strategies/oauth}/oauthMiddleware.d.ts +2 -6
- package/dist/mcp-server/transports/{authentication → auth/strategies/oauth}/oauthMiddleware.js +33 -18
- package/dist/mcp-server/transports/httpErrorHandler.d.ts +26 -0
- package/dist/mcp-server/transports/httpErrorHandler.js +73 -0
- package/dist/mcp-server/transports/httpTransport.d.ts +11 -14
- package/dist/mcp-server/transports/httpTransport.js +91 -379
- package/package.json +11 -16
|
@@ -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";
|
|
@@ -10,10 +10,11 @@
|
|
|
10
10
|
* is attached to `c.env.incoming.auth`. This direct attachment to the raw Node.js
|
|
11
11
|
* request object is for compatibility with the underlying SDK transport, which is
|
|
12
12
|
* not Hono-context-aware.
|
|
13
|
-
* If the token is missing, invalid, or expired, it
|
|
13
|
+
* If the token is missing, invalid, or expired, it throws an `McpError`, which is
|
|
14
|
+
* then handled by the centralized `httpErrorHandler`.
|
|
14
15
|
*
|
|
15
16
|
* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2025-03-26/basic/authorization.mdx | MCP Authorization Specification}
|
|
16
|
-
* @module src/mcp-server/transports/
|
|
17
|
+
* @module src/mcp-server/transports/auth/strategies/jwt/jwtMiddleware
|
|
17
18
|
*/
|
|
18
19
|
import { HttpBindings } from "@hono/node-server";
|
|
19
20
|
import { Context, Next } from "hono";
|
|
@@ -23,8 +24,4 @@ import { Context, Next } from "hono";
|
|
|
23
24
|
*/
|
|
24
25
|
export declare function mcpAuthMiddleware(c: Context<{
|
|
25
26
|
Bindings: HttpBindings;
|
|
26
|
-
}>, next: Next): Promise<void
|
|
27
|
-
error: string;
|
|
28
|
-
}, 500, "json">) | (Response & import("hono").TypedResponse<{
|
|
29
|
-
error: string;
|
|
30
|
-
}, 401, "json">)>;
|
|
27
|
+
}>, next: Next): Promise<void>;
|
|
@@ -10,22 +10,26 @@
|
|
|
10
10
|
* is attached to `c.env.incoming.auth`. This direct attachment to the raw Node.js
|
|
11
11
|
* request object is for compatibility with the underlying SDK transport, which is
|
|
12
12
|
* not Hono-context-aware.
|
|
13
|
-
* If the token is missing, invalid, or expired, it
|
|
13
|
+
* If the token is missing, invalid, or expired, it throws an `McpError`, which is
|
|
14
|
+
* then handled by the centralized `httpErrorHandler`.
|
|
14
15
|
*
|
|
15
16
|
* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2025-03-26/basic/authorization.mdx | MCP Authorization Specification}
|
|
16
|
-
* @module src/mcp-server/transports/
|
|
17
|
+
* @module src/mcp-server/transports/auth/strategies/jwt/jwtMiddleware
|
|
17
18
|
*/
|
|
18
|
-
import
|
|
19
|
-
import { config, environment } from "
|
|
20
|
-
import { logger, requestContextService } from "
|
|
21
|
-
import {
|
|
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";
|
|
22
24
|
// Startup Validation: Validate secret key presence on module load.
|
|
23
|
-
if (
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
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
|
+
}
|
|
29
33
|
}
|
|
30
34
|
/**
|
|
31
35
|
* Hono middleware for verifying JWT Bearer token authentication.
|
|
@@ -39,6 +43,10 @@ export async function mcpAuthMiddleware(c, next) {
|
|
|
39
43
|
});
|
|
40
44
|
logger.debug("Running MCP Authentication Middleware (Bearer Token Validation)...", context);
|
|
41
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
|
+
}
|
|
42
50
|
// Development Mode Bypass
|
|
43
51
|
if (!config.mcpAuthSecretKey) {
|
|
44
52
|
if (environment !== "production") {
|
|
@@ -57,28 +65,23 @@ export async function mcpAuthMiddleware(c, next) {
|
|
|
57
65
|
}
|
|
58
66
|
else {
|
|
59
67
|
logger.error("FATAL: MCP_AUTH_SECRET_KEY is missing in production. Cannot bypass auth.", context);
|
|
60
|
-
|
|
68
|
+
throw new McpError(BaseErrorCode.INTERNAL_ERROR, "Server configuration error: Authentication key missing.");
|
|
61
69
|
}
|
|
62
70
|
}
|
|
71
|
+
const secretKey = new TextEncoder().encode(config.mcpAuthSecretKey);
|
|
63
72
|
const authHeader = c.req.header("Authorization");
|
|
64
73
|
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
|
65
74
|
logger.warning("Authentication failed: Missing or malformed Authorization header (Bearer scheme required).", context);
|
|
66
|
-
|
|
67
|
-
error: "Unauthorized: Missing or invalid authentication token format.",
|
|
68
|
-
}, 401);
|
|
75
|
+
throw new McpError(BaseErrorCode.UNAUTHORIZED, "Missing or invalid authentication token format.");
|
|
69
76
|
}
|
|
70
77
|
const tokenParts = authHeader.split(" ");
|
|
71
78
|
if (tokenParts.length !== 2 || tokenParts[0] !== "Bearer" || !tokenParts[1]) {
|
|
72
79
|
logger.warning("Authentication failed: Malformed Bearer token.", context);
|
|
73
|
-
|
|
80
|
+
throw new McpError(BaseErrorCode.UNAUTHORIZED, "Malformed authentication token.");
|
|
74
81
|
}
|
|
75
82
|
const rawToken = tokenParts[1];
|
|
76
83
|
try {
|
|
77
|
-
const decoded =
|
|
78
|
-
if (typeof decoded === "string") {
|
|
79
|
-
logger.warning("Authentication failed: JWT decoded to a string, expected an object payload.", context);
|
|
80
|
-
return c.json({ error: "Unauthorized: Invalid token payload format." }, 401);
|
|
81
|
-
}
|
|
84
|
+
const { payload: decoded } = await jwtVerify(rawToken, secretKey);
|
|
82
85
|
const clientIdFromToken = typeof decoded.cid === "string"
|
|
83
86
|
? decoded.cid
|
|
84
87
|
: typeof decoded.client_id === "string"
|
|
@@ -86,7 +89,7 @@ export async function mcpAuthMiddleware(c, next) {
|
|
|
86
89
|
: undefined;
|
|
87
90
|
if (!clientIdFromToken) {
|
|
88
91
|
logger.warning("Authentication failed: JWT 'cid' or 'client_id' claim is missing or not a string.", { ...context, jwtPayloadKeys: Object.keys(decoded) });
|
|
89
|
-
|
|
92
|
+
throw new McpError(BaseErrorCode.UNAUTHORIZED, "Invalid token, missing client identifier.");
|
|
90
93
|
}
|
|
91
94
|
let scopesFromToken = [];
|
|
92
95
|
if (Array.isArray(decoded.scp) &&
|
|
@@ -102,7 +105,7 @@ export async function mcpAuthMiddleware(c, next) {
|
|
|
102
105
|
}
|
|
103
106
|
if (scopesFromToken.length === 0) {
|
|
104
107
|
logger.warning("Authentication failed: Token resulted in an empty scope array, and scopes are required.", { ...context, jwtPayloadKeys: Object.keys(decoded) });
|
|
105
|
-
|
|
108
|
+
throw new McpError(BaseErrorCode.UNAUTHORIZED, "Token must contain valid, non-empty scopes.");
|
|
106
109
|
}
|
|
107
110
|
reqWithAuth.auth = {
|
|
108
111
|
token: rawToken,
|
|
@@ -120,26 +123,27 @@ export async function mcpAuthMiddleware(c, next) {
|
|
|
120
123
|
await authContext.run({ authInfo }, next);
|
|
121
124
|
}
|
|
122
125
|
catch (error) {
|
|
123
|
-
let errorMessage = "Invalid token";
|
|
124
|
-
|
|
125
|
-
|
|
126
|
+
let errorMessage = "Invalid token.";
|
|
127
|
+
let errorCode = BaseErrorCode.UNAUTHORIZED;
|
|
128
|
+
if (error instanceof Error && error.name === "JWTExpired") {
|
|
129
|
+
errorMessage = "Token expired.";
|
|
126
130
|
logger.warning("Authentication failed: Token expired.", {
|
|
127
131
|
...context,
|
|
128
|
-
|
|
132
|
+
errorName: error.name,
|
|
129
133
|
});
|
|
130
134
|
}
|
|
131
|
-
else if (error instanceof jwt.JsonWebTokenError) {
|
|
132
|
-
errorMessage = `Invalid token: ${error.message}`;
|
|
133
|
-
logger.warning(`Authentication failed: ${errorMessage}`, { ...context });
|
|
134
|
-
}
|
|
135
135
|
else if (error instanceof Error) {
|
|
136
|
-
errorMessage = `
|
|
137
|
-
logger.
|
|
136
|
+
errorMessage = `Invalid token: ${error.message}`;
|
|
137
|
+
logger.warning(`Authentication failed: ${errorMessage}`, {
|
|
138
|
+
...context,
|
|
139
|
+
errorName: error.name,
|
|
140
|
+
});
|
|
138
141
|
}
|
|
139
142
|
else {
|
|
140
|
-
errorMessage = "Unknown verification error";
|
|
143
|
+
errorMessage = "Unknown verification error.";
|
|
144
|
+
errorCode = BaseErrorCode.INTERNAL_ERROR;
|
|
141
145
|
logger.error("Authentication failed: Unexpected non-error exception during token verification.", { ...context, error });
|
|
142
146
|
}
|
|
143
|
-
|
|
147
|
+
throw new McpError(errorCode, errorMessage);
|
|
144
148
|
}
|
|
145
149
|
}
|
package/dist/mcp-server/transports/{authentication → auth/strategies/oauth}/oauthMiddleware.d.ts
RENAMED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* On success, it populates an AuthInfo object and stores it in an AsyncLocalStorage
|
|
6
6
|
* context for use in downstream handlers.
|
|
7
7
|
*
|
|
8
|
-
* @module src/mcp-server/transports/
|
|
8
|
+
* @module src/mcp-server/transports/auth/strategies/oauth/oauthMiddleware
|
|
9
9
|
*/
|
|
10
10
|
import { HttpBindings } from "@hono/node-server";
|
|
11
11
|
import { Context, Next } from "hono";
|
|
@@ -17,8 +17,4 @@ import { Context, Next } from "hono";
|
|
|
17
17
|
*/
|
|
18
18
|
export declare function oauthMiddleware(c: Context<{
|
|
19
19
|
Bindings: HttpBindings;
|
|
20
|
-
}>, next: Next): Promise<
|
|
21
|
-
error: string;
|
|
22
|
-
}, 500, "json">) | (Response & import("hono").TypedResponse<{
|
|
23
|
-
error: string;
|
|
24
|
-
}, 401, "json">) | undefined>;
|
|
20
|
+
}>, next: Next): Promise<void>;
|
package/dist/mcp-server/transports/{authentication → auth/strategies/oauth}/oauthMiddleware.js
RENAMED
|
@@ -5,14 +5,14 @@
|
|
|
5
5
|
* On success, it populates an AuthInfo object and stores it in an AsyncLocalStorage
|
|
6
6
|
* context for use in downstream handlers.
|
|
7
7
|
*
|
|
8
|
-
* @module src/mcp-server/transports/
|
|
8
|
+
* @module src/mcp-server/transports/auth/strategies/oauth/oauthMiddleware
|
|
9
9
|
*/
|
|
10
10
|
import { createRemoteJWKSet, jwtVerify } from "jose";
|
|
11
|
-
import { config } from "
|
|
12
|
-
import { BaseErrorCode, McpError } from "
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import { authContext } from "
|
|
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
16
|
// --- Startup Validation ---
|
|
17
17
|
// Ensures that necessary OAuth configuration is present when the mode is 'oauth'.
|
|
18
18
|
if (config.mcpAuthMode === "oauth") {
|
|
@@ -57,6 +57,10 @@ if (config.mcpAuthMode === "oauth" && config.oauthIssuerUrl) {
|
|
|
57
57
|
* @param next - The function to call to proceed to the next middleware.
|
|
58
58
|
*/
|
|
59
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
|
+
}
|
|
60
64
|
const context = requestContextService.createRequestContext({
|
|
61
65
|
operation: "oauthMiddleware",
|
|
62
66
|
httpMethod: c.req.method,
|
|
@@ -64,13 +68,12 @@ export async function oauthMiddleware(c, next) {
|
|
|
64
68
|
});
|
|
65
69
|
if (!jwks) {
|
|
66
70
|
// This should not happen if startup validation is correct, but it's a safeguard.
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
return c.json({ error: "Server configuration error." }, 500);
|
|
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);
|
|
70
73
|
}
|
|
71
74
|
const authHeader = c.req.header("Authorization");
|
|
72
75
|
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
|
73
|
-
|
|
76
|
+
throw new McpError(BaseErrorCode.UNAUTHORIZED, "Missing or invalid token format.");
|
|
74
77
|
}
|
|
75
78
|
const token = authHeader.substring(7);
|
|
76
79
|
try {
|
|
@@ -80,10 +83,14 @@ export async function oauthMiddleware(c, next) {
|
|
|
80
83
|
});
|
|
81
84
|
// The 'scope' claim is typically a space-delimited string in OAuth 2.1.
|
|
82
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
|
+
}
|
|
83
90
|
const clientId = typeof payload.client_id === "string" ? payload.client_id : undefined;
|
|
84
91
|
if (!clientId) {
|
|
85
92
|
logger.warning("Authentication failed: OAuth token 'client_id' claim is missing or not a string.", { ...context, jwtPayloadKeys: Object.keys(payload) });
|
|
86
|
-
|
|
93
|
+
throw new McpError(BaseErrorCode.UNAUTHORIZED, "Invalid token, missing client identifier.");
|
|
87
94
|
}
|
|
88
95
|
const authInfo = {
|
|
89
96
|
token,
|
|
@@ -97,13 +104,21 @@ export async function oauthMiddleware(c, next) {
|
|
|
97
104
|
await authContext.run({ authInfo }, next);
|
|
98
105
|
}
|
|
99
106
|
catch (error) {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
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
|
|
104
115
|
});
|
|
105
|
-
//
|
|
106
|
-
|
|
107
|
-
|
|
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
|
+
}
|
|
108
123
|
}
|
|
109
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
|
+
};
|
|
@@ -1,10 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @fileoverview
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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.
|
|
8
13
|
*
|
|
9
14
|
* Specification Reference:
|
|
10
15
|
* https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2025-03-26/basic/transports.mdx#streamable-http
|
|
@@ -13,12 +18,4 @@
|
|
|
13
18
|
import { ServerType } from "@hono/node-server";
|
|
14
19
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
15
20
|
import { RequestContext } from "../../utils/index.js";
|
|
16
|
-
/**
|
|
17
|
-
* Sets up and starts the Streamable HTTP transport layer for the MCP server.
|
|
18
|
-
*
|
|
19
|
-
* @param createServerInstanceFn - An asynchronous factory function that returns a new `McpServer` instance.
|
|
20
|
-
* @param parentContext - Logging context from the main server startup process.
|
|
21
|
-
* @returns A promise that resolves with the Node.js `http.Server` instance when the HTTP server is successfully listening.
|
|
22
|
-
* @throws {Error} If the server fails to start after all port retries.
|
|
23
|
-
*/
|
|
24
21
|
export declare function startHttpTransport(createServerInstanceFn: () => Promise<McpServer>, parentContext: RequestContext): Promise<ServerType>;
|