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
@@ -1,8 +1,5 @@
1
- /**
2
- * Exports all utility functions and classes
3
- */
4
- export * from './errors.js';
5
- export * from './logging.js';
6
- export * from './rate-limiting.js';
7
- export * from './tokenization.js';
8
- export * from './validation.js';
1
+ export * from "./internal/index.js";
2
+ export * from "./parsing/index.js";
3
+ export * from "./security/index.js";
4
+ export * from "./metrics/index.js";
5
+ export * from "./obsidian/index.js";
@@ -1,9 +1,13 @@
1
- /**
2
- * Exports all utility functions and classes
3
- */
4
- export * from './errors.js';
5
- export * from './logging.js';
6
- export * from './rate-limiting.js';
7
- export * from './tokenization.js';
8
- export * from './validation.js';
9
- //# sourceMappingURL=index.js.map
1
+ // Re-export all utilities from their categorized subdirectories
2
+ export * from "./internal/index.js";
3
+ export * from "./parsing/index.js";
4
+ export * from "./security/index.js";
5
+ export * from "./metrics/index.js";
6
+ export * from "./obsidian/index.js"; // Added export for obsidian utils
7
+ // It's good practice to have index.ts files in each subdirectory
8
+ // that export the contents of that directory.
9
+ // Assuming those will be created or already exist.
10
+ // If not, this might need adjustment to export specific files, e.g.:
11
+ // export * from './internal/errorHandler.js';
12
+ // export * from './internal/logger.js';
13
+ // ... etc.
@@ -0,0 +1,54 @@
1
+ import { RequestContext } from "./requestContext.js";
2
+ /**
3
+ * Configuration for the {@link retryWithDelay} function, defining how retries are handled.
4
+ */
5
+ export interface RetryConfig<T> {
6
+ /**
7
+ * A descriptive name for the operation being retried. Used in logging.
8
+ * Example: "FetchUserData", "ProcessPayment".
9
+ */
10
+ operationName: string;
11
+ /**
12
+ * The request context associated with the operation, for logging and tracing.
13
+ */
14
+ context: RequestContext;
15
+ /**
16
+ * The maximum number of retry attempts before failing.
17
+ */
18
+ maxRetries: number;
19
+ /**
20
+ * The delay in milliseconds between retry attempts.
21
+ */
22
+ delayMs: number;
23
+ /**
24
+ * An optional function to determine if a retry should be attempted based on the error.
25
+ * If not provided, retries will be attempted for any error.
26
+ * @param error - The error that occurred during the operation.
27
+ * @returns `true` if a retry should be attempted, `false` otherwise.
28
+ */
29
+ shouldRetry?: (error: unknown) => boolean;
30
+ /**
31
+ * An optional function to execute before each retry attempt.
32
+ * Useful for custom logging or cleanup actions.
33
+ * @param attempt - The current retry attempt number.
34
+ * @param error - The error that triggered the retry.
35
+ */
36
+ onRetry?: (attempt: number, error: unknown) => void;
37
+ }
38
+ /**
39
+ * Executes an asynchronous operation with a configurable retry mechanism.
40
+ * This function will attempt the operation up to `maxRetries` times, with a specified
41
+ * `delayMs` between attempts. It allows for custom logic to decide if an error
42
+ * warrants a retry and for actions to be taken before each retry.
43
+ *
44
+ * @template T The expected return type of the asynchronous operation.
45
+ * @param {() => Promise<T>} operation - The asynchronous function to execute.
46
+ * This function should return a Promise resolving to type `T`.
47
+ * @param {RetryConfig<T>} config - Configuration options for the retry behavior,
48
+ * including operation name, context, retry limits, delay, and custom handlers.
49
+ * @returns {Promise<T>} A promise that resolves with the result of the operation if successful.
50
+ * @throws {McpError} Throws an `McpError` if the operation fails after all retry attempts,
51
+ * or if an unexpected error occurs during the retry logic. The error will contain details
52
+ * about the operation name, context, and the last encountered error.
53
+ */
54
+ export declare function retryWithDelay<T>(operation: () => Promise<T>, config: RetryConfig<T>): Promise<T>;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * @fileoverview Provides utilities for handling asynchronous operations,
3
+ * such as retrying operations with delays.
4
+ * @module src/utils/internal/asyncUtils
5
+ */
6
+ import { McpError, BaseErrorCode } from "../../types-global/errors.js";
7
+ import { logger } from "./logger.js";
8
+ /**
9
+ * Executes an asynchronous operation with a configurable retry mechanism.
10
+ * This function will attempt the operation up to `maxRetries` times, with a specified
11
+ * `delayMs` between attempts. It allows for custom logic to decide if an error
12
+ * warrants a retry and for actions to be taken before each retry.
13
+ *
14
+ * @template T The expected return type of the asynchronous operation.
15
+ * @param {() => Promise<T>} operation - The asynchronous function to execute.
16
+ * This function should return a Promise resolving to type `T`.
17
+ * @param {RetryConfig<T>} config - Configuration options for the retry behavior,
18
+ * including operation name, context, retry limits, delay, and custom handlers.
19
+ * @returns {Promise<T>} A promise that resolves with the result of the operation if successful.
20
+ * @throws {McpError} Throws an `McpError` if the operation fails after all retry attempts,
21
+ * or if an unexpected error occurs during the retry logic. The error will contain details
22
+ * about the operation name, context, and the last encountered error.
23
+ */
24
+ export async function retryWithDelay(operation, config) {
25
+ const { operationName, context, maxRetries, delayMs, shouldRetry = () => true, // Default: retry on any error
26
+ onRetry, } = config;
27
+ let lastError;
28
+ for (let attempt = 1; attempt <= maxRetries; attempt++) {
29
+ try {
30
+ return await operation();
31
+ }
32
+ catch (error) {
33
+ lastError = error;
34
+ // Ensure the context for logging includes attempt details
35
+ const retryAttemptContext = {
36
+ ...context, // Spread existing context
37
+ operation: operationName, // Ensure operationName is part of the context for logger
38
+ attempt,
39
+ maxRetries,
40
+ lastError: error instanceof Error ? error.message : String(error),
41
+ };
42
+ if (attempt < maxRetries && shouldRetry(error)) {
43
+ if (onRetry) {
44
+ onRetry(attempt, error); // Custom onRetry logic
45
+ }
46
+ else {
47
+ // Default logging for retry attempt
48
+ logger.warning(`Operation '${operationName}' failed on attempt ${attempt} of ${maxRetries}. Retrying in ${delayMs}ms...`, retryAttemptContext);
49
+ }
50
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
51
+ }
52
+ else {
53
+ // Max retries reached or shouldRetry returned false
54
+ const finalErrorMsg = `Operation '${operationName}' failed definitively after ${attempt} attempt(s).`;
55
+ // Log the final failure with the enriched context
56
+ logger.error(finalErrorMsg, error instanceof Error ? error : undefined, retryAttemptContext);
57
+ if (error instanceof McpError) {
58
+ // If the last error was already an McpError, re-throw it but ensure its details are preserved/updated.
59
+ error.details = {
60
+ ...(typeof error.details === "object" && error.details !== null
61
+ ? error.details
62
+ : {}),
63
+ ...retryAttemptContext, // Add retry context to existing details
64
+ finalAttempt: true,
65
+ };
66
+ throw error;
67
+ }
68
+ // For other errors, wrap in a new McpError
69
+ throw new McpError(BaseErrorCode.SERVICE_UNAVAILABLE, // Default to SERVICE_UNAVAILABLE, consider making this configurable or smarter
70
+ `${finalErrorMsg} Last error: ${error instanceof Error ? error.message : String(error)}`, {
71
+ ...retryAttemptContext, // Include all retry context
72
+ originalErrorName: error instanceof Error ? error.name : typeof error,
73
+ originalErrorStack: error instanceof Error ? error.stack : undefined,
74
+ finalAttempt: true,
75
+ });
76
+ }
77
+ }
78
+ }
79
+ // Fallback: This part should ideally not be reached if the loop logic is correct.
80
+ // If it is, it implies an issue with the loop or maxRetries logic.
81
+ const fallbackErrorContext = {
82
+ ...context,
83
+ operation: operationName,
84
+ maxRetries,
85
+ reason: "Fallback_Error_Path_Reached_In_Retry_Logic",
86
+ };
87
+ logger.crit(
88
+ // Log as critical because this path indicates a logic flaw
89
+ `Operation '${operationName}' failed unexpectedly after all retries (fallback path). This may indicate a logic error in retryWithDelay.`, lastError instanceof Error ? lastError : undefined, fallbackErrorContext);
90
+ throw new McpError(BaseErrorCode.INTERNAL_ERROR, // Indicates an issue with the retry utility itself
91
+ `Operation '${operationName}' failed unexpectedly after all retries (fallback path). Last error: ${lastError instanceof Error ? lastError.message : String(lastError)}`, {
92
+ ...fallbackErrorContext,
93
+ originalError: lastError instanceof Error
94
+ ? {
95
+ message: lastError.message,
96
+ name: lastError.name,
97
+ stack: lastError.stack,
98
+ }
99
+ : String(lastError),
100
+ });
101
+ }
@@ -0,0 +1,176 @@
1
+ /**
2
+ * @fileoverview This module provides utilities for robust error handling.
3
+ * It defines structures for error context, options for handling errors,
4
+ * and mappings for classifying errors. The main `ErrorHandler` class
5
+ * offers static methods for consistent error processing, logging, and transformation.
6
+ * @module src/utils/internal/errorHandler
7
+ */
8
+ import { BaseErrorCode } from "../../types-global/errors.js";
9
+ /**
10
+ * Defines a generic structure for providing context with errors.
11
+ * This context can include identifiers like `requestId` or any other relevant
12
+ * key-value pairs that aid in debugging or understanding the error's circumstances.
13
+ */
14
+ export interface ErrorContext {
15
+ /**
16
+ * A unique identifier for the request or operation during which the error occurred.
17
+ * Useful for tracing errors through logs and distributed systems.
18
+ */
19
+ requestId?: string;
20
+ /**
21
+ * Allows for arbitrary additional context information.
22
+ * Keys are strings, and values can be of any type.
23
+ */
24
+ [key: string]: unknown;
25
+ }
26
+ /**
27
+ * Configuration options for the `ErrorHandler.handleError` method.
28
+ * These options control how an error is processed, logged, and whether it's rethrown.
29
+ */
30
+ export interface ErrorHandlerOptions {
31
+ /**
32
+ * The context of the operation that caused the error.
33
+ * This can include `requestId` and other relevant debugging information.
34
+ */
35
+ context?: ErrorContext;
36
+ /**
37
+ * A descriptive name of the operation being performed when the error occurred.
38
+ * This helps in identifying the source or nature of the error in logs.
39
+ * Example: "UserLogin", "ProcessPayment", "FetchUserProfile".
40
+ */
41
+ operation: string;
42
+ /**
43
+ * The input data or parameters that were being processed when the error occurred.
44
+ * This input will be sanitized before logging to prevent sensitive data exposure.
45
+ */
46
+ input?: unknown;
47
+ /**
48
+ * If true, the (potentially transformed) error will be rethrown after handling.
49
+ * Defaults to `false`.
50
+ */
51
+ rethrow?: boolean;
52
+ /**
53
+ * A specific `BaseErrorCode` to assign to the error, overriding any
54
+ * automatically determined error code.
55
+ */
56
+ errorCode?: BaseErrorCode;
57
+ /**
58
+ * A custom function to map or transform the original error into a new `Error` instance.
59
+ * If provided, this function is used instead of the default `McpError` creation.
60
+ * @param error - The original error that occurred.
61
+ * @returns The transformed error.
62
+ */
63
+ errorMapper?: (error: unknown) => Error;
64
+ /**
65
+ * If true, stack traces will be included in the logs.
66
+ * Defaults to `true`.
67
+ */
68
+ includeStack?: boolean;
69
+ /**
70
+ * If true, indicates that the error is critical and might require immediate attention
71
+ * or could lead to system instability. This is primarily for logging and alerting.
72
+ * Defaults to `false`.
73
+ */
74
+ critical?: boolean;
75
+ }
76
+ /**
77
+ * Defines a basic rule for mapping errors based on patterns.
78
+ * Used internally by `COMMON_ERROR_PATTERNS` and as a base for `ErrorMapping`.
79
+ */
80
+ export interface BaseErrorMapping {
81
+ /**
82
+ * A string or regular expression to match against the error message.
83
+ * If a string is provided, it's typically used for substring matching (case-insensitive).
84
+ */
85
+ pattern: string | RegExp;
86
+ /**
87
+ * The `BaseErrorCode` to assign if the pattern matches.
88
+ */
89
+ errorCode: BaseErrorCode;
90
+ /**
91
+ * An optional custom message template for the mapped error.
92
+ * (Note: This property is defined but not directly used by `ErrorHandler.determineErrorCode`
93
+ * which focuses on `errorCode`. It's more relevant for custom mapping logic.)
94
+ */
95
+ messageTemplate?: string;
96
+ }
97
+ /**
98
+ * Extends `BaseErrorMapping` to include a factory function for creating
99
+ * specific error instances and additional context for the mapping.
100
+ * Used by `ErrorHandler.mapError`.
101
+ * @template T The type of `Error` this mapping will produce, defaults to `Error`.
102
+ */
103
+ export interface ErrorMapping<T extends Error = Error> extends BaseErrorMapping {
104
+ /**
105
+ * A factory function that creates and returns an instance of the mapped error type `T`.
106
+ * @param error - The original error that occurred.
107
+ * @param context - Optional additional context provided in the mapping rule.
108
+ * @returns The newly created error instance.
109
+ */
110
+ factory: (error: unknown, context?: Record<string, unknown>) => T;
111
+ /**
112
+ * Additional static context to be merged or passed to the `factory` function
113
+ * when this mapping rule is applied.
114
+ */
115
+ additionalContext?: Record<string, unknown>;
116
+ }
117
+ /**
118
+ * A utility class providing static methods for comprehensive error handling.
119
+ */
120
+ export declare class ErrorHandler {
121
+ /**
122
+ * Determines an appropriate `BaseErrorCode` for a given error.
123
+ * Checks `McpError` instances, `ERROR_TYPE_MAPPINGS`, and `COMMON_ERROR_PATTERNS`.
124
+ * Defaults to `BaseErrorCode.INTERNAL_ERROR`.
125
+ * @param error - The error instance or value to classify.
126
+ * @returns The determined error code.
127
+ */
128
+ static determineErrorCode(error: unknown): BaseErrorCode;
129
+ /**
130
+ * Handles an error with consistent logging and optional transformation.
131
+ * Sanitizes input, determines error code, logs details, and can rethrow.
132
+ * @param error - The error instance or value that occurred.
133
+ * @param options - Configuration for handling the error.
134
+ * @returns The handled (and potentially transformed) error instance.
135
+ */
136
+ static handleError(error: unknown, options: ErrorHandlerOptions): Error;
137
+ /**
138
+ * Maps an error to a specific error type `T` based on `ErrorMapping` rules.
139
+ * Returns original/default error if no mapping matches.
140
+ * @template T The target error type, extending `Error`.
141
+ * @param error - The error instance or value to map.
142
+ * @param mappings - An array of mapping rules to apply.
143
+ * @param defaultFactory - Optional factory for a default error if no mapping matches.
144
+ * @returns The mapped error of type `T`, or the original/defaulted error.
145
+ */
146
+ static mapError<T extends Error>(error: unknown, mappings: ReadonlyArray<ErrorMapping<T>>, defaultFactory?: (error: unknown, context?: Record<string, unknown>) => T): T | Error;
147
+ /**
148
+ * Formats an error into a consistent object structure for API responses or structured logging.
149
+ * @param error - The error instance or value to format.
150
+ * @returns A structured representation of the error.
151
+ */
152
+ static formatError(error: unknown): Record<string, unknown>;
153
+ /**
154
+ * Safely executes a function (sync or async) and handles errors using `ErrorHandler.handleError`.
155
+ * The error is always rethrown by default by `handleError` when `rethrow` is true.
156
+ * @template T The expected return type of the function `fn`.
157
+ * @param fn - The function to execute.
158
+ * @param options - Error handling options (excluding `rethrow`, as it's forced to true).
159
+ * @returns A promise resolving with the result of `fn` if successful.
160
+ * @throws {McpError | Error} The error processed by `ErrorHandler.handleError`.
161
+ * @example
162
+ * ```typescript
163
+ * async function fetchData(userId: string, context: RequestContext) {
164
+ * return ErrorHandler.tryCatch(
165
+ * async () => {
166
+ * const response = await fetch(`/api/users/${userId}`);
167
+ * if (!response.ok) throw new Error(`Failed to fetch user: ${response.status}`);
168
+ * return response.json();
169
+ * },
170
+ * { operation: 'fetchUserData', context, input: { userId } } // rethrow is implicitly true
171
+ * );
172
+ * }
173
+ * ```
174
+ */
175
+ static tryCatch<T>(fn: () => Promise<T> | T, options: Omit<ErrorHandlerOptions, "rethrow">): Promise<T>;
176
+ }