obsidian-mcp-server 1.5.8 → 2.0.2

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 (221) hide show
  1. package/README.md +248 -104
  2. package/dist/config/index.d.ts +41 -0
  3. package/dist/config/index.js +191 -0
  4. package/dist/index.d.ts +1 -5
  5. package/dist/index.js +296 -18
  6. package/dist/mcp-server/server.d.ts +33 -0
  7. package/dist/mcp-server/server.js +211 -0
  8. package/dist/mcp-server/tools/obsidianDeleteFileTool/index.d.ts +12 -0
  9. package/dist/mcp-server/tools/obsidianDeleteFileTool/index.js +12 -0
  10. package/dist/mcp-server/tools/obsidianDeleteFileTool/logic.d.ts +51 -0
  11. package/dist/mcp-server/tools/obsidianDeleteFileTool/logic.js +168 -0
  12. package/dist/mcp-server/tools/obsidianDeleteFileTool/registration.d.ts +19 -0
  13. package/dist/mcp-server/tools/obsidianDeleteFileTool/registration.js +91 -0
  14. package/dist/mcp-server/tools/obsidianGlobalSearchTool/index.d.ts +12 -0
  15. package/dist/mcp-server/tools/obsidianGlobalSearchTool/index.js +12 -0
  16. package/dist/mcp-server/tools/obsidianGlobalSearchTool/logic.d.ts +77 -0
  17. package/dist/mcp-server/tools/obsidianGlobalSearchTool/logic.js +341 -0
  18. package/dist/mcp-server/tools/obsidianGlobalSearchTool/registration.d.ts +18 -0
  19. package/dist/mcp-server/tools/obsidianGlobalSearchTool/registration.js +69 -0
  20. package/dist/mcp-server/tools/obsidianListFilesTool/index.d.ts +12 -0
  21. package/dist/mcp-server/tools/obsidianListFilesTool/index.js +12 -0
  22. package/dist/mcp-server/tools/obsidianListFilesTool/logic.d.ts +64 -0
  23. package/dist/mcp-server/tools/obsidianListFilesTool/logic.js +179 -0
  24. package/dist/mcp-server/tools/obsidianListFilesTool/registration.d.ts +19 -0
  25. package/dist/mcp-server/tools/obsidianListFilesTool/registration.js +96 -0
  26. package/dist/mcp-server/tools/obsidianManageFrontmatterTool/index.d.ts +3 -0
  27. package/dist/mcp-server/tools/obsidianManageFrontmatterTool/index.js +2 -0
  28. package/dist/mcp-server/tools/obsidianManageFrontmatterTool/logic.d.ts +42 -0
  29. package/dist/mcp-server/tools/obsidianManageFrontmatterTool/logic.js +152 -0
  30. package/dist/mcp-server/tools/obsidianManageFrontmatterTool/registration.d.ts +3 -0
  31. package/dist/mcp-server/tools/obsidianManageFrontmatterTool/registration.js +52 -0
  32. package/dist/mcp-server/tools/obsidianManageTagsTool/index.d.ts +3 -0
  33. package/dist/mcp-server/tools/obsidianManageTagsTool/index.js +2 -0
  34. package/dist/mcp-server/tools/obsidianManageTagsTool/logic.d.ts +28 -0
  35. package/dist/mcp-server/tools/obsidianManageTagsTool/logic.js +161 -0
  36. package/dist/mcp-server/tools/obsidianManageTagsTool/registration.d.ts +3 -0
  37. package/dist/mcp-server/tools/obsidianManageTagsTool/registration.js +52 -0
  38. package/dist/mcp-server/tools/obsidianReadFileTool/index.d.ts +12 -0
  39. package/dist/mcp-server/tools/obsidianReadFileTool/index.js +12 -0
  40. package/dist/mcp-server/tools/obsidianReadFileTool/logic.d.ts +87 -0
  41. package/dist/mcp-server/tools/obsidianReadFileTool/logic.js +216 -0
  42. package/dist/mcp-server/tools/obsidianReadFileTool/registration.d.ts +20 -0
  43. package/dist/mcp-server/tools/obsidianReadFileTool/registration.js +101 -0
  44. package/dist/mcp-server/tools/obsidianSearchReplaceTool/index.d.ts +12 -0
  45. package/dist/mcp-server/tools/obsidianSearchReplaceTool/index.js +12 -0
  46. package/dist/mcp-server/tools/obsidianSearchReplaceTool/logic.d.ts +255 -0
  47. package/dist/mcp-server/tools/obsidianSearchReplaceTool/logic.js +583 -0
  48. package/dist/mcp-server/tools/obsidianSearchReplaceTool/registration.d.ts +22 -0
  49. package/dist/mcp-server/tools/obsidianSearchReplaceTool/registration.js +111 -0
  50. package/dist/mcp-server/tools/obsidianUpdateFileTool/index.d.ts +12 -0
  51. package/dist/mcp-server/tools/obsidianUpdateFileTool/index.js +12 -0
  52. package/dist/mcp-server/tools/obsidianUpdateFileTool/logic.d.ts +183 -0
  53. package/dist/mcp-server/tools/obsidianUpdateFileTool/logic.js +490 -0
  54. package/dist/mcp-server/tools/obsidianUpdateFileTool/registration.d.ts +21 -0
  55. package/dist/mcp-server/tools/obsidianUpdateFileTool/registration.js +108 -0
  56. package/dist/mcp-server/transports/authentication/authContext.d.ts +33 -0
  57. package/dist/mcp-server/transports/authentication/authContext.js +24 -0
  58. package/dist/mcp-server/transports/authentication/authMiddleware.d.ts +30 -0
  59. package/dist/mcp-server/transports/authentication/authMiddleware.js +145 -0
  60. package/dist/mcp-server/transports/authentication/authUtils.d.ts +18 -0
  61. package/dist/mcp-server/transports/authentication/authUtils.js +45 -0
  62. package/dist/mcp-server/transports/authentication/oauthMiddleware.d.ts +24 -0
  63. package/dist/mcp-server/transports/authentication/oauthMiddleware.js +109 -0
  64. package/dist/mcp-server/transports/authentication/types.d.ts +17 -0
  65. package/dist/mcp-server/transports/authentication/types.js +5 -0
  66. package/dist/mcp-server/transports/httpTransport.d.ts +24 -0
  67. package/dist/mcp-server/transports/httpTransport.js +496 -0
  68. package/dist/mcp-server/transports/stdioTransport.d.ts +42 -0
  69. package/dist/mcp-server/transports/stdioTransport.js +63 -0
  70. package/dist/services/obsidianRestAPI/index.d.ts +15 -0
  71. package/dist/services/obsidianRestAPI/index.js +17 -0
  72. package/dist/services/obsidianRestAPI/methods/activeFileMethods.d.ts +38 -0
  73. package/dist/services/obsidianRestAPI/methods/activeFileMethods.js +62 -0
  74. package/dist/services/obsidianRestAPI/methods/commandMethods.d.ts +22 -0
  75. package/dist/services/obsidianRestAPI/methods/commandMethods.js +31 -0
  76. package/dist/services/obsidianRestAPI/methods/openMethods.d.ts +16 -0
  77. package/dist/services/obsidianRestAPI/methods/openMethods.js +21 -0
  78. package/dist/services/obsidianRestAPI/methods/patchMethods.d.ts +37 -0
  79. package/dist/services/obsidianRestAPI/methods/patchMethods.js +94 -0
  80. package/dist/services/obsidianRestAPI/methods/periodicNoteMethods.d.ts +42 -0
  81. package/dist/services/obsidianRestAPI/methods/periodicNoteMethods.js +66 -0
  82. package/dist/services/obsidianRestAPI/methods/searchMethods.d.ts +25 -0
  83. package/dist/services/obsidianRestAPI/methods/searchMethods.js +36 -0
  84. package/dist/services/obsidianRestAPI/methods/vaultMethods.d.ts +58 -0
  85. package/dist/services/obsidianRestAPI/methods/vaultMethods.js +144 -0
  86. package/dist/services/obsidianRestAPI/service.d.ts +195 -0
  87. package/dist/services/obsidianRestAPI/service.js +379 -0
  88. package/dist/services/obsidianRestAPI/types.d.ts +127 -0
  89. package/dist/services/obsidianRestAPI/types.js +7 -0
  90. package/dist/services/obsidianRestAPI/vaultCache/index.d.ts +4 -0
  91. package/dist/services/obsidianRestAPI/vaultCache/index.js +4 -0
  92. package/dist/services/obsidianRestAPI/vaultCache/service.d.ts +88 -0
  93. package/dist/services/obsidianRestAPI/vaultCache/service.js +299 -0
  94. package/dist/types-global/errors.d.ts +73 -0
  95. package/dist/types-global/errors.js +71 -0
  96. package/dist/utils/index.d.ts +5 -8
  97. package/dist/utils/index.js +13 -9
  98. package/dist/utils/internal/asyncUtils.d.ts +54 -0
  99. package/dist/utils/internal/asyncUtils.js +101 -0
  100. package/dist/utils/internal/errorHandler.d.ts +176 -0
  101. package/dist/utils/internal/errorHandler.js +351 -0
  102. package/dist/utils/internal/index.d.ts +4 -0
  103. package/dist/utils/internal/index.js +4 -0
  104. package/dist/utils/internal/logger.d.ts +141 -0
  105. package/dist/utils/internal/logger.js +406 -0
  106. package/dist/utils/internal/requestContext.d.ts +83 -0
  107. package/dist/utils/internal/requestContext.js +72 -0
  108. package/dist/utils/metrics/index.d.ts +1 -0
  109. package/dist/utils/metrics/index.js +1 -0
  110. package/dist/utils/metrics/tokenCounter.d.ts +27 -0
  111. package/dist/utils/metrics/tokenCounter.js +128 -0
  112. package/dist/utils/obsidian/index.d.ts +5 -0
  113. package/dist/utils/obsidian/index.js +5 -0
  114. package/dist/utils/obsidian/obsidianApiUtils.d.ts +14 -0
  115. package/dist/utils/obsidian/obsidianApiUtils.js +29 -0
  116. package/dist/utils/obsidian/obsidianStatUtils.d.ts +68 -0
  117. package/dist/utils/obsidian/obsidianStatUtils.js +143 -0
  118. package/dist/utils/parsing/dateParser.d.ts +56 -0
  119. package/dist/utils/parsing/dateParser.js +104 -0
  120. package/dist/utils/parsing/index.d.ts +2 -0
  121. package/dist/utils/parsing/index.js +3 -0
  122. package/dist/utils/parsing/jsonParser.d.ts +80 -0
  123. package/dist/utils/parsing/jsonParser.js +133 -0
  124. package/dist/utils/security/idGenerator.d.ts +140 -0
  125. package/dist/utils/security/idGenerator.js +194 -0
  126. package/dist/utils/security/index.d.ts +3 -0
  127. package/dist/utils/security/index.js +3 -0
  128. package/dist/utils/security/rateLimiter.d.ts +156 -0
  129. package/dist/utils/security/rateLimiter.js +235 -0
  130. package/dist/utils/security/sanitization.d.ts +244 -0
  131. package/dist/utils/security/sanitization.js +599 -0
  132. package/package.json +58 -37
  133. package/dist/index.js.map +0 -1
  134. package/dist/mcp/handlers.d.ts +0 -29
  135. package/dist/mcp/handlers.js +0 -305
  136. package/dist/mcp/handlers.js.map +0 -1
  137. package/dist/mcp/index.d.ts +0 -6
  138. package/dist/mcp/index.js +0 -7
  139. package/dist/mcp/index.js.map +0 -1
  140. package/dist/mcp/server.d.ts +0 -18
  141. package/dist/mcp/server.js +0 -240
  142. package/dist/mcp/server.js.map +0 -1
  143. package/dist/mcp/types.d.ts +0 -70
  144. package/dist/mcp/types.js +0 -49
  145. package/dist/mcp/types.js.map +0 -1
  146. package/dist/obsidian/client.d.ts +0 -109
  147. package/dist/obsidian/client.js +0 -403
  148. package/dist/obsidian/client.js.map +0 -1
  149. package/dist/obsidian/errors.d.ts +0 -28
  150. package/dist/obsidian/errors.js +0 -75
  151. package/dist/obsidian/errors.js.map +0 -1
  152. package/dist/obsidian/index.d.ts +0 -6
  153. package/dist/obsidian/index.js +0 -7
  154. package/dist/obsidian/index.js.map +0 -1
  155. package/dist/obsidian/types.d.ts +0 -107
  156. package/dist/obsidian/types.js +0 -12
  157. package/dist/obsidian/types.js.map +0 -1
  158. package/dist/resources/index.d.ts +0 -13
  159. package/dist/resources/index.js +0 -15
  160. package/dist/resources/index.js.map +0 -1
  161. package/dist/resources/tags.d.ts +0 -39
  162. package/dist/resources/tags.js +0 -257
  163. package/dist/resources/tags.js.map +0 -1
  164. package/dist/resources/types.d.ts +0 -27
  165. package/dist/resources/types.js +0 -5
  166. package/dist/resources/types.js.map +0 -1
  167. package/dist/tools/base.d.ts +0 -46
  168. package/dist/tools/base.js +0 -88
  169. package/dist/tools/base.js.map +0 -1
  170. package/dist/tools/files/content.d.ts +0 -58
  171. package/dist/tools/files/content.js +0 -171
  172. package/dist/tools/files/content.js.map +0 -1
  173. package/dist/tools/files/index.d.ts +0 -14
  174. package/dist/tools/files/index.js +0 -22
  175. package/dist/tools/files/index.js.map +0 -1
  176. package/dist/tools/files/list.d.ts +0 -35
  177. package/dist/tools/files/list.js +0 -133
  178. package/dist/tools/files/list.js.map +0 -1
  179. package/dist/tools/index.d.ts +0 -21
  180. package/dist/tools/index.js +0 -31
  181. package/dist/tools/index.js.map +0 -1
  182. package/dist/tools/properties/index.d.ts +0 -14
  183. package/dist/tools/properties/index.js +0 -19
  184. package/dist/tools/properties/index.js.map +0 -1
  185. package/dist/tools/properties/manager.d.ts +0 -62
  186. package/dist/tools/properties/manager.js +0 -302
  187. package/dist/tools/properties/manager.js.map +0 -1
  188. package/dist/tools/properties/tools.d.ts +0 -47
  189. package/dist/tools/properties/tools.js +0 -239
  190. package/dist/tools/properties/tools.js.map +0 -1
  191. package/dist/tools/properties/types.d.ts +0 -141
  192. package/dist/tools/properties/types.js +0 -70
  193. package/dist/tools/properties/types.js.map +0 -1
  194. package/dist/tools/search/complex.d.ts +0 -38
  195. package/dist/tools/search/complex.js +0 -270
  196. package/dist/tools/search/complex.js.map +0 -1
  197. package/dist/tools/search/index.d.ts +0 -14
  198. package/dist/tools/search/index.js +0 -20
  199. package/dist/tools/search/index.js.map +0 -1
  200. package/dist/tools/search/simple.d.ts +0 -25
  201. package/dist/tools/search/simple.js +0 -127
  202. package/dist/tools/search/simple.js.map +0 -1
  203. package/dist/utils/errors.d.ts +0 -24
  204. package/dist/utils/errors.js +0 -59
  205. package/dist/utils/errors.js.map +0 -1
  206. package/dist/utils/idGenerator.d.ts +0 -15
  207. package/dist/utils/idGenerator.js +0 -21
  208. package/dist/utils/idGenerator.js.map +0 -1
  209. package/dist/utils/index.js.map +0 -1
  210. package/dist/utils/logging.d.ts +0 -245
  211. package/dist/utils/logging.js +0 -417
  212. package/dist/utils/logging.js.map +0 -1
  213. package/dist/utils/rate-limiting.d.ts +0 -50
  214. package/dist/utils/rate-limiting.js +0 -94
  215. package/dist/utils/rate-limiting.js.map +0 -1
  216. package/dist/utils/tokenization.d.ts +0 -28
  217. package/dist/utils/tokenization.js +0 -75
  218. package/dist/utils/tokenization.js.map +0 -1
  219. package/dist/utils/validation.d.ts +0 -22
  220. package/dist/utils/validation.js +0 -92
  221. package/dist/utils/validation.js.map +0 -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/authentication/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,30 @@
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 returns an HTTP 401 Unauthorized response.
14
+ *
15
+ * @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/authentication/authMiddleware
17
+ */
18
+ import { HttpBindings } from "@hono/node-server";
19
+ import { Context, Next } from "hono";
20
+ /**
21
+ * Hono middleware for verifying JWT Bearer token authentication.
22
+ * It attaches authentication info to `c.env.incoming.auth` for SDK compatibility with the node server.
23
+ */
24
+ export declare function mcpAuthMiddleware(c: Context<{
25
+ Bindings: HttpBindings;
26
+ }>, next: Next): Promise<void | (Response & import("hono").TypedResponse<{
27
+ error: string;
28
+ }, 500, "json">) | (Response & import("hono").TypedResponse<{
29
+ error: string;
30
+ }, 401, "json">)>;
@@ -0,0 +1,145 @@
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 returns an HTTP 401 Unauthorized response.
14
+ *
15
+ * @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/authentication/authMiddleware
17
+ */
18
+ import jwt from "jsonwebtoken";
19
+ import { config, environment } from "../../../config/index.js";
20
+ import { logger, requestContextService } from "../../../utils/index.js";
21
+ import { authContext } from "./authContext.js";
22
+ // Startup Validation: Validate secret key presence on module load.
23
+ if (environment === "production" && !config.mcpAuthSecretKey) {
24
+ logger.fatal("CRITICAL: MCP_AUTH_SECRET_KEY is not set in production environment. Authentication cannot proceed securely.");
25
+ throw new Error("MCP_AUTH_SECRET_KEY must be set in production environment for JWT authentication.");
26
+ }
27
+ else if (!config.mcpAuthSecretKey) {
28
+ logger.warning("MCP_AUTH_SECRET_KEY is not set. Authentication middleware will bypass checks (DEVELOPMENT ONLY). This is insecure for production.");
29
+ }
30
+ /**
31
+ * Hono middleware for verifying JWT Bearer token authentication.
32
+ * It attaches authentication info to `c.env.incoming.auth` for SDK compatibility with the node server.
33
+ */
34
+ export async function mcpAuthMiddleware(c, next) {
35
+ const context = requestContextService.createRequestContext({
36
+ operation: "mcpAuthMiddleware",
37
+ method: c.req.method,
38
+ path: c.req.path,
39
+ });
40
+ logger.debug("Running MCP Authentication Middleware (Bearer Token Validation)...", context);
41
+ const reqWithAuth = c.env.incoming;
42
+ // Development Mode Bypass
43
+ if (!config.mcpAuthSecretKey) {
44
+ if (environment !== "production") {
45
+ logger.warning("Bypassing JWT authentication: MCP_AUTH_SECRET_KEY is not set (DEVELOPMENT ONLY).", context);
46
+ reqWithAuth.auth = {
47
+ token: "dev-mode-placeholder-token",
48
+ clientId: "dev-client-id",
49
+ scopes: ["dev-scope"],
50
+ };
51
+ const authInfo = reqWithAuth.auth;
52
+ logger.debug("Dev mode auth object created.", {
53
+ ...context,
54
+ authDetails: authInfo,
55
+ });
56
+ return await authContext.run({ authInfo }, next);
57
+ }
58
+ else {
59
+ logger.error("FATAL: MCP_AUTH_SECRET_KEY is missing in production. Cannot bypass auth.", context);
60
+ return c.json({ error: "Server configuration error: Authentication key missing." }, 500);
61
+ }
62
+ }
63
+ const authHeader = c.req.header("Authorization");
64
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
65
+ logger.warning("Authentication failed: Missing or malformed Authorization header (Bearer scheme required).", context);
66
+ return c.json({
67
+ error: "Unauthorized: Missing or invalid authentication token format.",
68
+ }, 401);
69
+ }
70
+ const tokenParts = authHeader.split(" ");
71
+ if (tokenParts.length !== 2 || tokenParts[0] !== "Bearer" || !tokenParts[1]) {
72
+ logger.warning("Authentication failed: Malformed Bearer token.", context);
73
+ return c.json({ error: "Unauthorized: Malformed authentication token." }, 401);
74
+ }
75
+ const rawToken = tokenParts[1];
76
+ try {
77
+ const decoded = jwt.verify(rawToken, config.mcpAuthSecretKey);
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
+ }
82
+ const clientIdFromToken = typeof decoded.cid === "string"
83
+ ? decoded.cid
84
+ : typeof decoded.client_id === "string"
85
+ ? decoded.client_id
86
+ : undefined;
87
+ if (!clientIdFromToken) {
88
+ logger.warning("Authentication failed: JWT 'cid' or 'client_id' claim is missing or not a string.", { ...context, jwtPayloadKeys: Object.keys(decoded) });
89
+ return c.json({ error: "Unauthorized: Invalid token, missing client identifier." }, 401);
90
+ }
91
+ let scopesFromToken = [];
92
+ if (Array.isArray(decoded.scp) &&
93
+ decoded.scp.every((s) => typeof s === "string")) {
94
+ scopesFromToken = decoded.scp;
95
+ }
96
+ else if (typeof decoded.scope === "string" &&
97
+ decoded.scope.trim() !== "") {
98
+ scopesFromToken = decoded.scope.split(" ").filter((s) => s);
99
+ if (scopesFromToken.length === 0 && decoded.scope.trim() !== "") {
100
+ scopesFromToken = [decoded.scope.trim()];
101
+ }
102
+ }
103
+ if (scopesFromToken.length === 0) {
104
+ logger.warning("Authentication failed: Token resulted in an empty scope array, and scopes are required.", { ...context, jwtPayloadKeys: Object.keys(decoded) });
105
+ return c.json({ error: "Unauthorized: Token must contain valid, non-empty scopes." }, 401);
106
+ }
107
+ reqWithAuth.auth = {
108
+ token: rawToken,
109
+ clientId: clientIdFromToken,
110
+ scopes: scopesFromToken,
111
+ };
112
+ const subClaimForLogging = typeof decoded.sub === "string" ? decoded.sub : undefined;
113
+ const authInfo = reqWithAuth.auth;
114
+ logger.debug("JWT verified successfully. AuthInfo attached to request.", {
115
+ ...context,
116
+ mcpSessionIdContext: subClaimForLogging,
117
+ clientId: authInfo.clientId,
118
+ scopes: authInfo.scopes,
119
+ });
120
+ await authContext.run({ authInfo }, next);
121
+ }
122
+ catch (error) {
123
+ let errorMessage = "Invalid token";
124
+ if (error instanceof jwt.TokenExpiredError) {
125
+ errorMessage = "Token expired";
126
+ logger.warning("Authentication failed: Token expired.", {
127
+ ...context,
128
+ expiredAt: error.expiredAt,
129
+ });
130
+ }
131
+ else if (error instanceof jwt.JsonWebTokenError) {
132
+ errorMessage = `Invalid token: ${error.message}`;
133
+ logger.warning(`Authentication failed: ${errorMessage}`, { ...context });
134
+ }
135
+ else if (error instanceof Error) {
136
+ errorMessage = `Verification error: ${error.message}`;
137
+ logger.error("Authentication failed: Unexpected error during token verification.", { ...context, error: error.message });
138
+ }
139
+ else {
140
+ errorMessage = "Unknown verification error";
141
+ logger.error("Authentication failed: Unexpected non-error exception during token verification.", { ...context, error });
142
+ }
143
+ return c.json({ error: `Unauthorized: ${errorMessage}.` }, 401);
144
+ }
145
+ }
@@ -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/authentication/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/authentication/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,24 @@
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/authentication/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<(Response & import("hono").TypedResponse<{
21
+ error: string;
22
+ }, 500, "json">) | (Response & import("hono").TypedResponse<{
23
+ error: string;
24
+ }, 401, "json">) | undefined>;
@@ -0,0 +1,109 @@
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/authentication/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 "./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
+ const context = requestContextService.createRequestContext({
61
+ operation: "oauthMiddleware",
62
+ httpMethod: c.req.method,
63
+ httpPath: c.req.path,
64
+ });
65
+ if (!jwks) {
66
+ // This should not happen if startup validation is correct, but it's a safeguard.
67
+ const error = new McpError(BaseErrorCode.CONFIGURATION_ERROR, "OAuth middleware is active, but JWKS client is not initialized.", context);
68
+ ErrorHandler.handleError(error, { operation: "oauthMiddleware", context });
69
+ return c.json({ error: "Server configuration error." }, 500);
70
+ }
71
+ const authHeader = c.req.header("Authorization");
72
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
73
+ return c.json({ error: "Unauthorized: Missing or invalid token format." }, 401);
74
+ }
75
+ const token = authHeader.substring(7);
76
+ try {
77
+ const { payload } = await jwtVerify(token, jwks, {
78
+ issuer: config.oauthIssuerUrl,
79
+ audience: config.oauthAudience,
80
+ });
81
+ // The 'scope' claim is typically a space-delimited string in OAuth 2.1.
82
+ const scopes = typeof payload.scope === "string" ? payload.scope.split(" ") : [];
83
+ const clientId = typeof payload.client_id === "string" ? payload.client_id : undefined;
84
+ if (!clientId) {
85
+ logger.warning("Authentication failed: OAuth token 'client_id' claim is missing or not a string.", { ...context, jwtPayloadKeys: Object.keys(payload) });
86
+ return c.json({ error: "Unauthorized: Invalid token, missing client identifier." }, 401);
87
+ }
88
+ const authInfo = {
89
+ token,
90
+ clientId,
91
+ scopes,
92
+ subject: typeof payload.sub === "string" ? payload.sub : undefined,
93
+ };
94
+ // Attach to the raw request for potential legacy compatibility and
95
+ // store in AsyncLocalStorage for modern, safe access in handlers.
96
+ c.env.incoming.auth = authInfo;
97
+ await authContext.run({ authInfo }, next);
98
+ }
99
+ catch (error) {
100
+ logger.warning("OAuth token validation failed", {
101
+ ...context,
102
+ errorName: error.name,
103
+ errorMessage: error.message,
104
+ });
105
+ // The `jose` library provides specific error codes like 'ERR_JWT_EXPIRED' or 'ERR_JWS_INVALID'
106
+ const message = `Unauthorized: ${error.message || "Invalid token"}`;
107
+ return c.json({ error: message }, 401);
108
+ }
109
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @fileoverview Shared types for authentication middleware.
3
+ * @module src/mcp-server/transports/authentication/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/authentication/types
4
+ */
5
+ export {};
@@ -0,0 +1,24 @@
1
+ /**
2
+ * @fileoverview Handles the setup and management of the Streamable HTTP MCP transport using Hono.
3
+ * Implements the MCP Specification 2025-03-26 for Streamable HTTP.
4
+ * This includes creating a Hono server, configuring middleware (CORS, Authentication),
5
+ * defining request routing for the single MCP endpoint (POST/GET/DELETE),
6
+ * managing server-side sessions, handling Server-Sent Events (SSE) for streaming,
7
+ * and binding to a network port with retry logic for port conflicts.
8
+ *
9
+ * Specification Reference:
10
+ * https://github.com/modelcontextprotocol/modelcontextprotocol/blob/main/docs/specification/2025-03-26/basic/transports.mdx#streamable-http
11
+ * @module src/mcp-server/transports/httpTransport
12
+ */
13
+ import { ServerType } from "@hono/node-server";
14
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
15
+ 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
+ export declare function startHttpTransport(createServerInstanceFn: () => Promise<McpServer>, parentContext: RequestContext): Promise<ServerType>;