@openconductor/mcp-sdk 0.2.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 OpenConductor
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,229 @@
1
+ # @openconductor/mcp-sdk
2
+
3
+ The standard SDK for building production-ready MCP servers. Stop copy-pasting boilerplate — get error handling, validation, logging, and telemetry out of the box.
4
+
5
+ [![npm version](https://badge.fury.io/js/%40openconductor%2Fmcp-sdk.svg)](https://www.npmjs.com/package/@openconductor/mcp-sdk)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ## Why?
9
+
10
+ Every MCP server needs the same things:
11
+ - **Error handling** that follows JSON-RPC 2.0 spec
12
+ - **Input validation** that doesn't suck
13
+ - **Structured logging** for debugging and observability
14
+ - **Telemetry** to know what's actually happening in production
15
+
16
+ This SDK gives you all of that in ~15kb, with zero config required.
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install @openconductor/mcp-sdk
22
+ ```
23
+
24
+ ## Quick Start
25
+
26
+ ```typescript
27
+ import {
28
+ wrapTool,
29
+ validateInput,
30
+ z,
31
+ createLogger,
32
+ createHealthCheck,
33
+ initTelemetry
34
+ } from '@openconductor/mcp-sdk'
35
+
36
+ // Optional: Enable telemetry (free tier available)
37
+ initTelemetry({
38
+ apiKey: 'oc_xxx',
39
+ serverName: 'my-mcp-server',
40
+ serverVersion: '1.0.0'
41
+ })
42
+
43
+ // Create a validated, wrapped tool in seconds
44
+ const searchTool = wrapTool(
45
+ validateInput(
46
+ z.object({
47
+ query: z.string().min(1),
48
+ limit: z.number().int().positive().default(10)
49
+ }),
50
+ async (input) => {
51
+ // Your logic here — input is typed and validated
52
+ return { results: [] }
53
+ }
54
+ ),
55
+ { name: 'search', timeout: 5000 }
56
+ )
57
+
58
+ // Automatic error handling, logging, and telemetry!
59
+ const result = await searchTool({ query: 'hello', limit: 5 })
60
+ ```
61
+
62
+ ## Features
63
+
64
+ ### Error Handling
65
+
66
+ Clean, JSON-RPC 2.0 compliant errors with detailed context:
67
+
68
+ ```typescript
69
+ import { ValidationError, ToolNotFoundError, MCPError } from '@openconductor/mcp-sdk/errors'
70
+
71
+ // Throw structured errors
72
+ throw new ValidationError('amount', 'Must be a positive integer', -5)
73
+
74
+ // Automatically formatted as JSON-RPC error:
75
+ // {
76
+ // code: -32602,
77
+ // message: "Validation failed for 'amount': Must be a positive integer",
78
+ // data: { field: "amount", reason: "Must be a positive integer", value: -5 }
79
+ // }
80
+ ```
81
+
82
+ **Available Errors:**
83
+ - `ValidationError` — Invalid input parameters
84
+ - `ToolNotFoundError` — Requested tool doesn't exist
85
+ - `ToolExecutionError` — Tool failed during execution
86
+ - `ResourceNotFoundError` — Resource URI not found
87
+ - `AuthenticationError` — Auth required or failed
88
+ - `AuthorizationError` — Not permitted
89
+ - `RateLimitError` — Too many requests
90
+ - `TimeoutError` — Operation timed out
91
+ - `DependencyError` — External dependency unavailable
92
+ - `ConfigurationError` — Invalid server config
93
+
94
+ ### Validation
95
+
96
+ Zod-powered validation with MCP-specific helpers:
97
+
98
+
99
+ ```typescript
100
+ import { validate, validateInput, z, schemas } from '@openconductor/mcp-sdk/validate'
101
+
102
+ // Use built-in schemas for common patterns
103
+ const schema = z.object({
104
+ query: schemas.nonEmptyString,
105
+ limit: schemas.limit, // 1-100, defaults to 10
106
+ offset: schemas.offset, // >= 0, defaults to 0
107
+ email: schemas.email,
108
+ url: schemas.url,
109
+ })
110
+
111
+ // Validate manually
112
+ const data = validate(schema, userInput)
113
+
114
+ // Or wrap your handler for automatic validation
115
+ const handler = validateInput(schema, async (input) => {
116
+ // input is fully typed!
117
+ return doSomething(input)
118
+ })
119
+ ```
120
+
121
+ ### Logging
122
+
123
+ Structured JSON logging that works with any log aggregator:
124
+
125
+ ```typescript
126
+ import { createLogger } from '@openconductor/mcp-sdk/logger'
127
+
128
+ const log = createLogger('my-server', {
129
+ level: 'info', // 'debug' | 'info' | 'warn' | 'error'
130
+ pretty: true // Pretty print for local dev
131
+ })
132
+
133
+ log.info('Tool invoked', { tool: 'search', userId: 'abc' })
134
+ // {"timestamp":"2025-01-19T...","level":"info","service":"my-server","message":"Tool invoked","tool":"search","userId":"abc"}
135
+
136
+ // Create scoped child loggers
137
+ const toolLog = log.child({ tool: 'search', requestId: 'req_123' })
138
+ toolLog.info('Processing query')
139
+ // All logs include tool and requestId automatically
140
+ ```
141
+
142
+ ### Server Utilities
143
+
144
+ Health checks and tool wrappers:
145
+
146
+ ```typescript
147
+ import { createHealthCheck, wrapTool } from '@openconductor/mcp-sdk/server'
148
+
149
+ // Standard health check endpoint
150
+ const healthCheck = createHealthCheck({
151
+ name: 'my-mcp-server',
152
+ version: '1.0.0',
153
+ uptime: () => process.uptime(),
154
+ checks: {
155
+ database: async () => db.ping(),
156
+ redis: async () => redis.ping(),
157
+ }
158
+ })
159
+
160
+ // Returns:
161
+ // {
162
+ // status: 'healthy',
163
+ // name: 'my-mcp-server',
164
+ // version: '1.0.0',
165
+ // uptime: 3600,
166
+ // timestamp: '2025-01-19T...',
167
+ // checks: { database: true, redis: true }
168
+ // }
169
+
170
+ // Wrap tools with automatic error handling, logging, timeouts, and telemetry
171
+ const safeTool = wrapTool(myHandler, {
172
+ name: 'my-tool',
173
+ timeout: 5000, // Auto-timeout after 5s
174
+ })
175
+ ```
176
+
177
+ ### Telemetry
178
+
179
+ Optional observability for your MCP servers:
180
+
181
+ ```typescript
182
+ import { initTelemetry } from '@openconductor/mcp-sdk/telemetry'
183
+
184
+ // Initialize once at startup
185
+ initTelemetry({
186
+ apiKey: 'oc_xxx', // Get free key at openconductor.dev
187
+ serverName: 'my-server',
188
+ serverVersion: '1.0.0',
189
+ debug: true // Log telemetry events locally
190
+ })
191
+
192
+ // That's it! All wrapped tools automatically report:
193
+ // - Invocation counts
194
+ // - Success/failure rates
195
+ // - Latency percentiles (p50, p95, p99)
196
+ // - Error messages
197
+ ```
198
+
199
+ **What gets sent:**
200
+ - Tool names and call counts
201
+ - Execution duration
202
+ - Success/failure status
203
+ - Error messages (not stack traces)
204
+ - SDK and Node.js version
205
+
206
+ **What never gets sent:**
207
+ - Tool inputs or outputs
208
+ - User data
209
+ - Request/response bodies
210
+
211
+ ## Tree-Shakeable Imports
212
+
213
+ Import only what you need:
214
+
215
+ ```typescript
216
+ // Full SDK
217
+ import { z, validate, wrapTool, createLogger } from '@openconductor/mcp-sdk'
218
+
219
+ // Or specific modules
220
+ import { ValidationError } from '@openconductor/mcp-sdk/errors'
221
+ import { z, validate } from '@openconductor/mcp-sdk/validate'
222
+ import { createLogger } from '@openconductor/mcp-sdk/logger'
223
+ import { wrapTool } from '@openconductor/mcp-sdk/server'
224
+ import { initTelemetry } from '@openconductor/mcp-sdk/telemetry'
225
+ ```
226
+
227
+ ## License
228
+
229
+ MIT © [OpenConductor](https://openconductor.dev)
@@ -0,0 +1,114 @@
1
+ /**
2
+ * JSON-RPC 2.0 Standard Error Codes
3
+ * https://www.jsonrpc.org/specification#error_object
4
+ */
5
+ declare const ErrorCodes: {
6
+ readonly PARSE_ERROR: -32700;
7
+ readonly INVALID_REQUEST: -32600;
8
+ readonly METHOD_NOT_FOUND: -32601;
9
+ readonly INVALID_PARAMS: -32602;
10
+ readonly INTERNAL_ERROR: -32603;
11
+ readonly TOOL_NOT_FOUND: -32001;
12
+ readonly TOOL_EXECUTION_ERROR: -32002;
13
+ readonly RESOURCE_NOT_FOUND: -32003;
14
+ readonly AUTHENTICATION_ERROR: -32004;
15
+ readonly AUTHORIZATION_ERROR: -32005;
16
+ readonly RATE_LIMIT_ERROR: -32006;
17
+ readonly TIMEOUT_ERROR: -32007;
18
+ readonly VALIDATION_ERROR: -32008;
19
+ readonly DEPENDENCY_ERROR: -32009;
20
+ readonly CONFIGURATION_ERROR: -32010;
21
+ };
22
+ type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
23
+
24
+ /**
25
+ * Base error class for MCP servers
26
+ * Formats errors according to JSON-RPC 2.0 specification
27
+ */
28
+ declare class MCPError extends Error {
29
+ readonly code: ErrorCode;
30
+ readonly data?: Record<string, unknown>;
31
+ constructor(code: ErrorCode, message: string, data?: Record<string, unknown>);
32
+ /**
33
+ * Returns JSON-RPC 2.0 formatted error object
34
+ */
35
+ toJSON(): {
36
+ data?: Record<string, unknown> | undefined;
37
+ code: ErrorCode;
38
+ message: string;
39
+ };
40
+ /**
41
+ * Create error response for JSON-RPC
42
+ */
43
+ toResponse(id?: string | number | null): {
44
+ jsonrpc: "2.0";
45
+ id: string | number | null;
46
+ error: {
47
+ data?: Record<string, unknown> | undefined;
48
+ code: ErrorCode;
49
+ message: string;
50
+ };
51
+ };
52
+ }
53
+ /**
54
+ * Thrown when tool input validation fails
55
+ */
56
+ declare class ValidationError extends MCPError {
57
+ constructor(field: string, reason: string, value?: unknown);
58
+ }
59
+ /**
60
+ * Thrown when a requested tool doesn't exist
61
+ */
62
+ declare class ToolNotFoundError extends MCPError {
63
+ constructor(toolName: string);
64
+ }
65
+ /**
66
+ * Thrown when tool execution fails
67
+ */
68
+ declare class ToolExecutionError extends MCPError {
69
+ constructor(toolName: string, reason: string, cause?: Error);
70
+ }
71
+ /**
72
+ * Thrown when a requested resource doesn't exist
73
+ */
74
+ declare class ResourceNotFoundError extends MCPError {
75
+ constructor(resourceUri: string);
76
+ }
77
+ /**
78
+ * Thrown when authentication fails
79
+ */
80
+ declare class AuthenticationError extends MCPError {
81
+ constructor(reason?: string);
82
+ }
83
+ /**
84
+ * Thrown when authorization fails (authenticated but not permitted)
85
+ */
86
+ declare class AuthorizationError extends MCPError {
87
+ constructor(action: string, resource?: string);
88
+ }
89
+ /**
90
+ * Thrown when rate limits are exceeded
91
+ */
92
+ declare class RateLimitError extends MCPError {
93
+ constructor(retryAfterMs?: number);
94
+ }
95
+ /**
96
+ * Thrown when an operation times out
97
+ */
98
+ declare class TimeoutError extends MCPError {
99
+ constructor(operation: string, timeoutMs: number);
100
+ }
101
+ /**
102
+ * Thrown when a required dependency is unavailable
103
+ */
104
+ declare class DependencyError extends MCPError {
105
+ constructor(dependency: string, reason: string);
106
+ }
107
+ /**
108
+ * Thrown when server configuration is invalid
109
+ */
110
+ declare class ConfigurationError extends MCPError {
111
+ constructor(setting: string, reason: string);
112
+ }
113
+
114
+ export { AuthenticationError, AuthorizationError, ConfigurationError, DependencyError, type ErrorCode, ErrorCodes, MCPError, RateLimitError, ResourceNotFoundError, TimeoutError, ToolExecutionError, ToolNotFoundError, ValidationError };
@@ -0,0 +1,114 @@
1
+ /**
2
+ * JSON-RPC 2.0 Standard Error Codes
3
+ * https://www.jsonrpc.org/specification#error_object
4
+ */
5
+ declare const ErrorCodes: {
6
+ readonly PARSE_ERROR: -32700;
7
+ readonly INVALID_REQUEST: -32600;
8
+ readonly METHOD_NOT_FOUND: -32601;
9
+ readonly INVALID_PARAMS: -32602;
10
+ readonly INTERNAL_ERROR: -32603;
11
+ readonly TOOL_NOT_FOUND: -32001;
12
+ readonly TOOL_EXECUTION_ERROR: -32002;
13
+ readonly RESOURCE_NOT_FOUND: -32003;
14
+ readonly AUTHENTICATION_ERROR: -32004;
15
+ readonly AUTHORIZATION_ERROR: -32005;
16
+ readonly RATE_LIMIT_ERROR: -32006;
17
+ readonly TIMEOUT_ERROR: -32007;
18
+ readonly VALIDATION_ERROR: -32008;
19
+ readonly DEPENDENCY_ERROR: -32009;
20
+ readonly CONFIGURATION_ERROR: -32010;
21
+ };
22
+ type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];
23
+
24
+ /**
25
+ * Base error class for MCP servers
26
+ * Formats errors according to JSON-RPC 2.0 specification
27
+ */
28
+ declare class MCPError extends Error {
29
+ readonly code: ErrorCode;
30
+ readonly data?: Record<string, unknown>;
31
+ constructor(code: ErrorCode, message: string, data?: Record<string, unknown>);
32
+ /**
33
+ * Returns JSON-RPC 2.0 formatted error object
34
+ */
35
+ toJSON(): {
36
+ data?: Record<string, unknown> | undefined;
37
+ code: ErrorCode;
38
+ message: string;
39
+ };
40
+ /**
41
+ * Create error response for JSON-RPC
42
+ */
43
+ toResponse(id?: string | number | null): {
44
+ jsonrpc: "2.0";
45
+ id: string | number | null;
46
+ error: {
47
+ data?: Record<string, unknown> | undefined;
48
+ code: ErrorCode;
49
+ message: string;
50
+ };
51
+ };
52
+ }
53
+ /**
54
+ * Thrown when tool input validation fails
55
+ */
56
+ declare class ValidationError extends MCPError {
57
+ constructor(field: string, reason: string, value?: unknown);
58
+ }
59
+ /**
60
+ * Thrown when a requested tool doesn't exist
61
+ */
62
+ declare class ToolNotFoundError extends MCPError {
63
+ constructor(toolName: string);
64
+ }
65
+ /**
66
+ * Thrown when tool execution fails
67
+ */
68
+ declare class ToolExecutionError extends MCPError {
69
+ constructor(toolName: string, reason: string, cause?: Error);
70
+ }
71
+ /**
72
+ * Thrown when a requested resource doesn't exist
73
+ */
74
+ declare class ResourceNotFoundError extends MCPError {
75
+ constructor(resourceUri: string);
76
+ }
77
+ /**
78
+ * Thrown when authentication fails
79
+ */
80
+ declare class AuthenticationError extends MCPError {
81
+ constructor(reason?: string);
82
+ }
83
+ /**
84
+ * Thrown when authorization fails (authenticated but not permitted)
85
+ */
86
+ declare class AuthorizationError extends MCPError {
87
+ constructor(action: string, resource?: string);
88
+ }
89
+ /**
90
+ * Thrown when rate limits are exceeded
91
+ */
92
+ declare class RateLimitError extends MCPError {
93
+ constructor(retryAfterMs?: number);
94
+ }
95
+ /**
96
+ * Thrown when an operation times out
97
+ */
98
+ declare class TimeoutError extends MCPError {
99
+ constructor(operation: string, timeoutMs: number);
100
+ }
101
+ /**
102
+ * Thrown when a required dependency is unavailable
103
+ */
104
+ declare class DependencyError extends MCPError {
105
+ constructor(dependency: string, reason: string);
106
+ }
107
+ /**
108
+ * Thrown when server configuration is invalid
109
+ */
110
+ declare class ConfigurationError extends MCPError {
111
+ constructor(setting: string, reason: string);
112
+ }
113
+
114
+ export { AuthenticationError, AuthorizationError, ConfigurationError, DependencyError, type ErrorCode, ErrorCodes, MCPError, RateLimitError, ResourceNotFoundError, TimeoutError, ToolExecutionError, ToolNotFoundError, ValidationError };
@@ -0,0 +1,159 @@
1
+ 'use strict';
2
+
3
+ // src/errors/codes.ts
4
+ var ErrorCodes = {
5
+ // JSON-RPC 2.0 Standard Errors
6
+ PARSE_ERROR: -32700,
7
+ INVALID_REQUEST: -32600,
8
+ METHOD_NOT_FOUND: -32601,
9
+ INVALID_PARAMS: -32602,
10
+ INTERNAL_ERROR: -32603,
11
+ // MCP-Specific Errors (-32000 to -32099 reserved for implementation)
12
+ TOOL_NOT_FOUND: -32001,
13
+ TOOL_EXECUTION_ERROR: -32002,
14
+ RESOURCE_NOT_FOUND: -32003,
15
+ AUTHENTICATION_ERROR: -32004,
16
+ AUTHORIZATION_ERROR: -32005,
17
+ RATE_LIMIT_ERROR: -32006,
18
+ TIMEOUT_ERROR: -32007,
19
+ VALIDATION_ERROR: -32008,
20
+ DEPENDENCY_ERROR: -32009,
21
+ CONFIGURATION_ERROR: -32010
22
+ };
23
+
24
+ // src/errors/index.ts
25
+ var MCPError = class extends Error {
26
+ code;
27
+ data;
28
+ constructor(code, message, data) {
29
+ super(message);
30
+ this.name = "MCPError";
31
+ this.code = code;
32
+ this.data = data;
33
+ if (Error.captureStackTrace) {
34
+ Error.captureStackTrace(this, this.constructor);
35
+ }
36
+ }
37
+ /**
38
+ * Returns JSON-RPC 2.0 formatted error object
39
+ */
40
+ toJSON() {
41
+ return {
42
+ code: this.code,
43
+ message: this.message,
44
+ ...this.data && { data: this.data }
45
+ };
46
+ }
47
+ /**
48
+ * Create error response for JSON-RPC
49
+ */
50
+ toResponse(id = null) {
51
+ return {
52
+ jsonrpc: "2.0",
53
+ id,
54
+ error: this.toJSON()
55
+ };
56
+ }
57
+ };
58
+ var ValidationError = class extends MCPError {
59
+ constructor(field, reason, value) {
60
+ super(ErrorCodes.INVALID_PARAMS, `Validation failed for '${field}': ${reason}`, {
61
+ field,
62
+ reason,
63
+ ...value !== void 0 && { value }
64
+ });
65
+ this.name = "ValidationError";
66
+ }
67
+ };
68
+ var ToolNotFoundError = class extends MCPError {
69
+ constructor(toolName) {
70
+ super(ErrorCodes.TOOL_NOT_FOUND, `Tool '${toolName}' not found`, {
71
+ tool: toolName
72
+ });
73
+ this.name = "ToolNotFoundError";
74
+ }
75
+ };
76
+ var ToolExecutionError = class extends MCPError {
77
+ constructor(toolName, reason, cause) {
78
+ super(ErrorCodes.TOOL_EXECUTION_ERROR, `Tool '${toolName}' failed: ${reason}`, {
79
+ tool: toolName,
80
+ reason,
81
+ ...cause && { cause: cause.message }
82
+ });
83
+ this.name = "ToolExecutionError";
84
+ }
85
+ };
86
+ var ResourceNotFoundError = class extends MCPError {
87
+ constructor(resourceUri) {
88
+ super(ErrorCodes.RESOURCE_NOT_FOUND, `Resource '${resourceUri}' not found`, {
89
+ uri: resourceUri
90
+ });
91
+ this.name = "ResourceNotFoundError";
92
+ }
93
+ };
94
+ var AuthenticationError = class extends MCPError {
95
+ constructor(reason = "Authentication required") {
96
+ super(ErrorCodes.AUTHENTICATION_ERROR, reason);
97
+ this.name = "AuthenticationError";
98
+ }
99
+ };
100
+ var AuthorizationError = class extends MCPError {
101
+ constructor(action, resource) {
102
+ const msg = resource ? `Not authorized to ${action} on '${resource}'` : `Not authorized to ${action}`;
103
+ super(ErrorCodes.AUTHORIZATION_ERROR, msg, {
104
+ action,
105
+ ...resource && { resource }
106
+ });
107
+ this.name = "AuthorizationError";
108
+ }
109
+ };
110
+ var RateLimitError = class extends MCPError {
111
+ constructor(retryAfterMs) {
112
+ super(ErrorCodes.RATE_LIMIT_ERROR, "Rate limit exceeded", {
113
+ ...retryAfterMs && { retryAfterMs }
114
+ });
115
+ this.name = "RateLimitError";
116
+ }
117
+ };
118
+ var TimeoutError = class extends MCPError {
119
+ constructor(operation, timeoutMs) {
120
+ super(ErrorCodes.TIMEOUT_ERROR, `Operation '${operation}' timed out after ${timeoutMs}ms`, {
121
+ operation,
122
+ timeoutMs
123
+ });
124
+ this.name = "TimeoutError";
125
+ }
126
+ };
127
+ var DependencyError = class extends MCPError {
128
+ constructor(dependency, reason) {
129
+ super(ErrorCodes.DEPENDENCY_ERROR, `Dependency '${dependency}' unavailable: ${reason}`, {
130
+ dependency,
131
+ reason
132
+ });
133
+ this.name = "DependencyError";
134
+ }
135
+ };
136
+ var ConfigurationError = class extends MCPError {
137
+ constructor(setting, reason) {
138
+ super(ErrorCodes.CONFIGURATION_ERROR, `Invalid configuration '${setting}': ${reason}`, {
139
+ setting,
140
+ reason
141
+ });
142
+ this.name = "ConfigurationError";
143
+ }
144
+ };
145
+
146
+ exports.AuthenticationError = AuthenticationError;
147
+ exports.AuthorizationError = AuthorizationError;
148
+ exports.ConfigurationError = ConfigurationError;
149
+ exports.DependencyError = DependencyError;
150
+ exports.ErrorCodes = ErrorCodes;
151
+ exports.MCPError = MCPError;
152
+ exports.RateLimitError = RateLimitError;
153
+ exports.ResourceNotFoundError = ResourceNotFoundError;
154
+ exports.TimeoutError = TimeoutError;
155
+ exports.ToolExecutionError = ToolExecutionError;
156
+ exports.ToolNotFoundError = ToolNotFoundError;
157
+ exports.ValidationError = ValidationError;
158
+ //# sourceMappingURL=index.js.map
159
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/errors/codes.ts","../../src/errors/index.ts"],"names":[],"mappings":";;;AAIO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,WAAA,EAAa,MAAA;AAAA,EACb,eAAA,EAAiB,MAAA;AAAA,EACjB,gBAAA,EAAkB,MAAA;AAAA,EAClB,cAAA,EAAgB,MAAA;AAAA,EAChB,cAAA,EAAgB,MAAA;AAAA;AAAA,EAGhB,cAAA,EAAgB,MAAA;AAAA,EAChB,oBAAA,EAAsB,MAAA;AAAA,EACtB,kBAAA,EAAoB,MAAA;AAAA,EACpB,oBAAA,EAAsB,MAAA;AAAA,EACtB,mBAAA,EAAqB,MAAA;AAAA,EACrB,gBAAA,EAAkB,MAAA;AAAA,EAClB,aAAA,EAAe,MAAA;AAAA,EACf,gBAAA,EAAkB,MAAA;AAAA,EAClB,gBAAA,EAAkB,MAAA;AAAA,EAClB,mBAAA,EAAqB;AACvB;;;ACfO,IAAM,QAAA,GAAN,cAAuB,KAAA,CAAM;AAAA,EAClB,IAAA;AAAA,EACA,IAAA;AAAA,EAEhB,WAAA,CACE,IAAA,EACA,OAAA,EACA,IAAA,EACA;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,UAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAGZ,IAAA,IAAI,MAAM,iBAAA,EAAmB;AAC3B,MAAA,KAAA,CAAM,iBA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*/\nexport const ErrorCodes = {\n // JSON-RPC 2.0 Standard Errors\n PARSE_ERROR: -32700,\n INVALID_REQUEST: -32600,\n METHOD_NOT_FOUND: -32601,\n INVALID_PARAMS: -32602,\n INTERNAL_ERROR: -32603,\n\n // MCP-Specific Errors (-32000 to -32099 reserved for implementation)\n TOOL_NOT_FOUND: -32001,\n TOOL_EXECUTION_ERROR: -32002,\n RESOURCE_NOT_FOUND: -32003,\n AUTHENTICATION_ERROR: -32004,\n AUTHORIZATION_ERROR: -32005,\n RATE_LIMIT_ERROR: -32006,\n TIMEOUT_ERROR: -32007,\n VALIDATION_ERROR: -32008,\n DEPENDENCY_ERROR: -32009,\n CONFIGURATION_ERROR: -32010,\n} as const\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes]\n","import { ErrorCodes, type ErrorCode } from './codes'\n\nexport { ErrorCodes, type ErrorCode } from './codes'\n\n/**\n * Base error class for MCP servers\n * Formats errors according to JSON-RPC 2.0 specification\n */\nexport class MCPError extends Error {\n public readonly code: ErrorCode\n public readonly data?: Record<string, unknown>\n\n constructor(\n code: ErrorCode,\n message: string,\n data?: Record<string, unknown>\n ) {\n super(message)\n this.name = 'MCPError'\n this.code = code\n this.data = data\n\n // Maintains proper stack trace in V8 environments\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n }\n\n /**\n * Returns JSON-RPC 2.0 formatted error object\n */\n toJSON() {\n return {\n code: this.code,\n message: this.message,\n ...(this.data && { data: this.data }),\n }\n }\n\n /**\n * Create error response for JSON-RPC\n */\n toResponse(id: string | number | null = null) {\n return {\n jsonrpc: '2.0' as const,\n id,\n error: this.toJSON(),\n }\n }\n}\n\n/**\n * Thrown when tool input validation fails\n */\nexport class ValidationError extends MCPError {\n constructor(field: string, reason: string, value?: unknown) {\n super(ErrorCodes.INVALID_PARAMS, `Validation failed for '${field}': ${reason}`, {\n field,\n reason,\n ...(value !== undefined && { value }),\n })\n this.name = 'ValidationError'\n }\n}\n\n/**\n * Thrown when a requested tool doesn't exist\n */\nexport class ToolNotFoundError extends MCPError {\n constructor(toolName: string) {\n super(ErrorCodes.TOOL_NOT_FOUND, `Tool '${toolName}' not found`, {\n tool: toolName,\n })\n this.name = 'ToolNotFoundError'\n }\n}\n\n/**\n * Thrown when tool execution fails\n */\nexport class ToolExecutionError extends MCPError {\n constructor(toolName: string, reason: string, cause?: Error) {\n super(ErrorCodes.TOOL_EXECUTION_ERROR, `Tool '${toolName}' failed: ${reason}`, {\n tool: toolName,\n reason,\n ...(cause && { cause: cause.message }),\n })\n this.name = 'ToolExecutionError'\n }\n}\n\n/**\n * Thrown when a requested resource doesn't exist\n */\nexport class ResourceNotFoundError extends MCPError {\n constructor(resourceUri: string) {\n super(ErrorCodes.RESOURCE_NOT_FOUND, `Resource '${resourceUri}' not found`, {\n uri: resourceUri,\n })\n this.name = 'ResourceNotFoundError'\n }\n}\n\n/**\n * Thrown when authentication fails\n */\nexport class AuthenticationError extends MCPError {\n constructor(reason: string = 'Authentication required') {\n super(ErrorCodes.AUTHENTICATION_ERROR, reason)\n this.name = 'AuthenticationError'\n }\n}\n\n/**\n * Thrown when authorization fails (authenticated but not permitted)\n */\nexport class AuthorizationError extends MCPError {\n constructor(action: string, resource?: string) {\n const msg = resource\n ? `Not authorized to ${action} on '${resource}'`\n : `Not authorized to ${action}`\n super(ErrorCodes.AUTHORIZATION_ERROR, msg, {\n action,\n ...(resource && { resource }),\n })\n this.name = 'AuthorizationError'\n }\n}\n\n/**\n * Thrown when rate limits are exceeded\n */\nexport class RateLimitError extends MCPError {\n constructor(retryAfterMs?: number) {\n super(ErrorCodes.RATE_LIMIT_ERROR, 'Rate limit exceeded', {\n ...(retryAfterMs && { retryAfterMs }),\n })\n this.name = 'RateLimitError'\n }\n}\n\n/**\n * Thrown when an operation times out\n */\nexport class TimeoutError extends MCPError {\n constructor(operation: string, timeoutMs: number) {\n super(ErrorCodes.TIMEOUT_ERROR, `Operation '${operation}' timed out after ${timeoutMs}ms`, {\n operation,\n timeoutMs,\n })\n this.name = 'TimeoutError'\n }\n}\n\n/**\n * Thrown when a required dependency is unavailable\n */\nexport class DependencyError extends MCPError {\n constructor(dependency: string, reason: string) {\n super(ErrorCodes.DEPENDENCY_ERROR, `Dependency '${dependency}' unavailable: ${reason}`, {\n dependency,\n reason,\n })\n this.name = 'DependencyError'\n }\n}\n\n/**\n * Thrown when server configuration is invalid\n */\nexport class ConfigurationError extends MCPError {\n constructor(setting: string, reason: string) {\n super(ErrorCodes.CONFIGURATION_ERROR, `Invalid configuration '${setting}': ${reason}`, {\n setting,\n reason,\n })\n this.name = 'ConfigurationError'\n }\n}\n"]}