@openconductor/mcp-sdk 0.2.0 → 1.0.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/README.md +106 -106
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.mjs.map +1 -1
- package/dist/telemetry/index.js +1 -1
- package/dist/telemetry/index.js.map +1 -1
- package/dist/telemetry/index.mjs +1 -1
- package/dist/telemetry/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,19 +1,27 @@
|
|
|
1
1
|
# @openconductor/mcp-sdk
|
|
2
2
|
|
|
3
|
-
The standard SDK for building production-ready MCP servers
|
|
3
|
+
**The standard SDK for building production-ready MCP servers.**
|
|
4
|
+
|
|
5
|
+
Stop copy-pasting boilerplate. Get error handling, validation, logging, and telemetry out of the box.
|
|
4
6
|
|
|
5
7
|
[](https://www.npmjs.com/package/@openconductor/mcp-sdk)
|
|
8
|
+
[](https://www.npmjs.com/package/@openconductor/mcp-sdk)
|
|
6
9
|
[](https://opensource.org/licenses/MIT)
|
|
10
|
+
[](https://www.typescriptlang.org/)
|
|
7
11
|
|
|
8
|
-
## Why?
|
|
12
|
+
## Why This SDK?
|
|
9
13
|
|
|
10
14
|
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
15
|
|
|
16
|
-
|
|
16
|
+
| Feature | Without SDK | With SDK |
|
|
17
|
+
|---------|-------------|----------|
|
|
18
|
+
| **Error Handling** | 50+ lines of JSON-RPC formatting | Built-in, spec-compliant |
|
|
19
|
+
| **Input Validation** | Manual checks, type-unsafe | Zod schemas, fully typed |
|
|
20
|
+
| **Logging** | console.log chaos | Structured JSON, log-aggregator ready |
|
|
21
|
+
| **Telemetry** | Flying blind | One-line setup, real dashboards |
|
|
22
|
+
| **Timeouts** | None (hung requests) | Automatic with configurable limits |
|
|
23
|
+
|
|
24
|
+
All in **~15kb**, zero config required.
|
|
17
25
|
|
|
18
26
|
## Install
|
|
19
27
|
|
|
@@ -21,6 +29,8 @@ This SDK gives you all of that in ~15kb, with zero config required.
|
|
|
21
29
|
npm install @openconductor/mcp-sdk
|
|
22
30
|
```
|
|
23
31
|
|
|
32
|
+
**Requirements:** Node.js 18+
|
|
33
|
+
|
|
24
34
|
## Quick Start
|
|
25
35
|
|
|
26
36
|
```typescript
|
|
@@ -29,14 +39,13 @@ import {
|
|
|
29
39
|
validateInput,
|
|
30
40
|
z,
|
|
31
41
|
createLogger,
|
|
32
|
-
createHealthCheck,
|
|
33
42
|
initTelemetry
|
|
34
43
|
} from '@openconductor/mcp-sdk'
|
|
35
44
|
|
|
36
|
-
// Optional: Enable
|
|
45
|
+
// Optional: Enable observability
|
|
37
46
|
initTelemetry({
|
|
38
|
-
apiKey: 'oc_xxx',
|
|
39
|
-
serverName: 'my-
|
|
47
|
+
apiKey: 'oc_xxx', // Get free key at openconductor.dev
|
|
48
|
+
serverName: 'my-server',
|
|
40
49
|
serverVersion: '1.0.0'
|
|
41
50
|
})
|
|
42
51
|
|
|
@@ -48,165 +57,117 @@ const searchTool = wrapTool(
|
|
|
48
57
|
limit: z.number().int().positive().default(10)
|
|
49
58
|
}),
|
|
50
59
|
async (input) => {
|
|
51
|
-
//
|
|
52
|
-
return { results:
|
|
60
|
+
// input is typed: { query: string, limit: number }
|
|
61
|
+
return { results: await db.search(input.query, input.limit) }
|
|
53
62
|
}
|
|
54
63
|
),
|
|
55
64
|
{ name: 'search', timeout: 5000 }
|
|
56
65
|
)
|
|
57
66
|
|
|
58
|
-
// Automatic error handling, logging, and telemetry
|
|
67
|
+
// Automatic error handling, logging, and telemetry
|
|
59
68
|
const result = await searchTool({ query: 'hello', limit: 5 })
|
|
60
69
|
```
|
|
61
70
|
|
|
62
71
|
## Features
|
|
63
72
|
|
|
64
|
-
### Error Handling
|
|
73
|
+
### 🛡️ Error Handling
|
|
65
74
|
|
|
66
|
-
|
|
75
|
+
JSON-RPC 2.0 compliant errors with rich context:
|
|
67
76
|
|
|
68
77
|
```typescript
|
|
69
|
-
import { ValidationError,
|
|
78
|
+
import { ValidationError, ToolExecutionError } from '@openconductor/mcp-sdk/errors'
|
|
70
79
|
|
|
71
|
-
|
|
72
|
-
|
|
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
|
+
throw new ValidationError('amount', 'Must be positive', -5)
|
|
81
|
+
// → { code: -32602, message: "Validation failed...", data: { field, reason, value } }
|
|
80
82
|
```
|
|
81
83
|
|
|
82
|
-
**
|
|
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
|
|
84
|
+
**10 error types included:** ValidationError, ToolNotFoundError, ToolExecutionError, ResourceNotFoundError, AuthenticationError, AuthorizationError, RateLimitError, TimeoutError, DependencyError, ConfigurationError
|
|
93
85
|
|
|
94
|
-
|
|
86
|
+
[→ Error Handling Guide](./docs/errors.md)
|
|
95
87
|
|
|
96
|
-
|
|
88
|
+
### ✅ Validation
|
|
97
89
|
|
|
90
|
+
Zod-powered with MCP-specific helpers:
|
|
98
91
|
|
|
99
92
|
```typescript
|
|
100
|
-
import {
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
-
})
|
|
93
|
+
import { validateInput, z, schemas } from '@openconductor/mcp-sdk'
|
|
94
|
+
|
|
95
|
+
const handler = validateInput(
|
|
96
|
+
z.object({
|
|
97
|
+
query: schemas.nonEmptyString,
|
|
98
|
+
limit: schemas.limit, // 1-100, default 10
|
|
99
|
+
email: schemas.email,
|
|
100
|
+
url: schemas.url,
|
|
101
|
+
}),
|
|
102
|
+
async (input) => doSomething(input) // Fully typed!
|
|
103
|
+
)
|
|
119
104
|
```
|
|
120
105
|
|
|
121
|
-
|
|
106
|
+
[→ Validation Guide](./docs/validation.md)
|
|
122
107
|
|
|
123
|
-
|
|
108
|
+
### 📝 Logging
|
|
109
|
+
|
|
110
|
+
Structured JSON that works with any log aggregator:
|
|
124
111
|
|
|
125
112
|
```typescript
|
|
126
113
|
import { createLogger } from '@openconductor/mcp-sdk/logger'
|
|
127
114
|
|
|
128
|
-
const log = createLogger('my-server', {
|
|
129
|
-
level: 'info', // 'debug' | 'info' | 'warn' | 'error'
|
|
130
|
-
pretty: true // Pretty print for local dev
|
|
131
|
-
})
|
|
115
|
+
const log = createLogger('my-server', { level: 'info', pretty: true })
|
|
132
116
|
|
|
133
117
|
log.info('Tool invoked', { tool: 'search', userId: 'abc' })
|
|
134
|
-
// {"timestamp":"
|
|
118
|
+
// {"timestamp":"...","level":"info","service":"my-server","message":"Tool invoked","tool":"search","userId":"abc"}
|
|
135
119
|
|
|
136
|
-
|
|
137
|
-
const toolLog = log.child({ tool: 'search', requestId: 'req_123' })
|
|
138
|
-
toolLog.info('Processing query')
|
|
139
|
-
// All logs include tool and requestId automatically
|
|
120
|
+
const toolLog = log.child({ requestId: 'req_123' }) // Scoped context
|
|
140
121
|
```
|
|
141
122
|
|
|
142
|
-
### Server Utilities
|
|
123
|
+
### 🔧 Server Utilities
|
|
143
124
|
|
|
144
125
|
Health checks and tool wrappers:
|
|
145
126
|
|
|
146
127
|
```typescript
|
|
147
128
|
import { createHealthCheck, wrapTool } from '@openconductor/mcp-sdk/server'
|
|
148
129
|
|
|
149
|
-
// Standard health
|
|
130
|
+
// Standard health endpoint
|
|
150
131
|
const healthCheck = createHealthCheck({
|
|
151
|
-
name: 'my-
|
|
132
|
+
name: 'my-server',
|
|
152
133
|
version: '1.0.0',
|
|
153
|
-
uptime: () => process.uptime(),
|
|
154
134
|
checks: {
|
|
155
135
|
database: async () => db.ping(),
|
|
156
136
|
redis: async () => redis.ping(),
|
|
157
137
|
}
|
|
158
138
|
})
|
|
139
|
+
// → { status: 'healthy', checks: { database: true, redis: true }, ... }
|
|
159
140
|
|
|
160
|
-
//
|
|
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
|
|
141
|
+
// Wrap any handler with production features
|
|
171
142
|
const safeTool = wrapTool(myHandler, {
|
|
172
143
|
name: 'my-tool',
|
|
173
|
-
timeout: 5000, // Auto-timeout
|
|
144
|
+
timeout: 5000, // Auto-timeout
|
|
174
145
|
})
|
|
175
146
|
```
|
|
176
147
|
|
|
177
|
-
### Telemetry
|
|
148
|
+
### 📊 Telemetry
|
|
178
149
|
|
|
179
|
-
Optional observability for
|
|
150
|
+
Optional observability for production:
|
|
180
151
|
|
|
181
152
|
```typescript
|
|
182
153
|
import { initTelemetry } from '@openconductor/mcp-sdk/telemetry'
|
|
183
154
|
|
|
184
|
-
// Initialize once at startup
|
|
185
155
|
initTelemetry({
|
|
186
|
-
apiKey: 'oc_xxx', //
|
|
156
|
+
apiKey: 'oc_xxx', // Free tier at openconductor.dev
|
|
187
157
|
serverName: 'my-server',
|
|
188
158
|
serverVersion: '1.0.0',
|
|
189
|
-
debug: true // Log telemetry events locally
|
|
190
159
|
})
|
|
191
160
|
|
|
192
|
-
//
|
|
193
|
-
//
|
|
194
|
-
//
|
|
195
|
-
//
|
|
196
|
-
//
|
|
161
|
+
// All wrapped tools automatically report:
|
|
162
|
+
// ✓ Invocation counts
|
|
163
|
+
// ✓ Success/failure rates
|
|
164
|
+
// ✓ Latency percentiles (p50, p95, p99)
|
|
165
|
+
// ✓ Error messages
|
|
197
166
|
```
|
|
198
167
|
|
|
199
|
-
**
|
|
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
|
|
168
|
+
**Privacy:** Only tool names, durations, and errors are sent. Never inputs, outputs, or user data.
|
|
205
169
|
|
|
206
|
-
|
|
207
|
-
- Tool inputs or outputs
|
|
208
|
-
- User data
|
|
209
|
-
- Request/response bodies
|
|
170
|
+
[→ Telemetry Guide](./docs/telemetry.md)
|
|
210
171
|
|
|
211
172
|
## Tree-Shakeable Imports
|
|
212
173
|
|
|
@@ -216,7 +177,7 @@ Import only what you need:
|
|
|
216
177
|
// Full SDK
|
|
217
178
|
import { z, validate, wrapTool, createLogger } from '@openconductor/mcp-sdk'
|
|
218
179
|
|
|
219
|
-
// Or specific modules
|
|
180
|
+
// Or specific modules (smaller bundles)
|
|
220
181
|
import { ValidationError } from '@openconductor/mcp-sdk/errors'
|
|
221
182
|
import { z, validate } from '@openconductor/mcp-sdk/validate'
|
|
222
183
|
import { createLogger } from '@openconductor/mcp-sdk/logger'
|
|
@@ -224,6 +185,45 @@ import { wrapTool } from '@openconductor/mcp-sdk/server'
|
|
|
224
185
|
import { initTelemetry } from '@openconductor/mcp-sdk/telemetry'
|
|
225
186
|
```
|
|
226
187
|
|
|
188
|
+
## Documentation
|
|
189
|
+
|
|
190
|
+
- **[Getting Started](./docs/getting-started.md)** — Build your first server
|
|
191
|
+
- **[Error Handling](./docs/errors.md)** — All error types and usage
|
|
192
|
+
- **[Validation](./docs/validation.md)** — Schema patterns and helpers
|
|
193
|
+
- **[Telemetry](./docs/telemetry.md)** — Observability setup
|
|
194
|
+
- **[API Reference](./docs/api-reference.md)** — Complete API docs
|
|
195
|
+
|
|
196
|
+
## Examples
|
|
197
|
+
|
|
198
|
+
### Full MCP Server
|
|
199
|
+
|
|
200
|
+
See [examples/full-server](./examples/full-server) for a complete implementation.
|
|
201
|
+
|
|
202
|
+
### FastMCP Integration
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
import FastMCP from 'fastmcp'
|
|
206
|
+
import { wrapTool, validateInput, z } from '@openconductor/mcp-sdk'
|
|
207
|
+
|
|
208
|
+
const server = new FastMCP({ name: 'my-server' })
|
|
209
|
+
|
|
210
|
+
server.addTool({
|
|
211
|
+
name: 'greet',
|
|
212
|
+
description: 'Generate a greeting',
|
|
213
|
+
parameters: z.object({ name: z.string() }),
|
|
214
|
+
execute: wrapTool(
|
|
215
|
+
validateInput(z.object({ name: z.string() }), async ({ name }) => {
|
|
216
|
+
return `Hello, ${name}!`
|
|
217
|
+
}),
|
|
218
|
+
{ name: 'greet', timeout: 5000 }
|
|
219
|
+
)
|
|
220
|
+
})
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
## Contributing
|
|
224
|
+
|
|
225
|
+
Contributions welcome! See [CONTRIBUTING.md](./CONTRIBUTING.md).
|
|
226
|
+
|
|
227
227
|
## License
|
|
228
228
|
|
|
229
229
|
MIT © [OpenConductor](https://openconductor.dev)
|
package/dist/index.js
CHANGED
|
@@ -272,7 +272,7 @@ function createLogger(service, options = {}) {
|
|
|
272
272
|
}
|
|
273
273
|
|
|
274
274
|
// src/telemetry/index.ts
|
|
275
|
-
var SDK_VERSION = "0.
|
|
275
|
+
var SDK_VERSION = "1.0.0";
|
|
276
276
|
var DEFAULT_ENDPOINT = "https://api.openconductor.ai/functions/v1/telemetry";
|
|
277
277
|
var globalTelemetry = null;
|
|
278
278
|
function initTelemetry(config) {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors/codes.ts","../src/errors/index.ts","../src/validate/index.ts","../src/logger/index.ts","../src/telemetry/index.ts","../src/server/index.ts"],"names":["z"],"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,UA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.0 Standard Error Codes\n * https://www.jsonrpc.org/specification#error_object\n */\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","import { z, ZodError, type ZodSchema, type ZodTypeDef, type SafeParseReturnType } from 'zod'\nimport { ValidationError } from '../errors'\n\n// Re-export zod for convenience\nexport { z, ZodError, type ZodSchema }\nexport type { ZodTypeDef }\n\n/**\n * Options for input validation\n */\nexport interface ValidateOptions {\n /** Strip unknown keys from objects (default: true) */\n stripUnknown?: boolean\n /** Custom error formatter */\n formatError?: (error: ZodError) => string\n}\n\n/**\n * Validates input against a Zod schema\n * Throws ValidationError on failure with detailed field info\n */\nexport function validate<T>(\n schema: ZodSchema<T>,\n input: unknown,\n options: ValidateOptions = {}\n): T {\n const { stripUnknown = true } = options\n\n const result = (\n stripUnknown\n ? schema.safeParse(input)\n : schema instanceof z.ZodObject\n ? schema.strict().safeParse(input)\n : schema.safeParse(input)\n ) as SafeParseReturnType<unknown, T>\n\n if (!result.success) {\n const firstError = result.error.errors[0]\n const field = firstError.path.join('.') || 'input'\n const reason = firstError.message\n throw new ValidationError(field, reason, firstError.path.length > 0 \n ? getNestedValue(input, firstError.path) \n : input\n )\n }\n\n return result.data\n}\n\n/**\n * Creates a validated tool handler\n * Wraps your handler function with automatic input validation\n */\nexport function validateInput<TInput, TOutput>(\n schema: ZodSchema<TInput>,\n handler: (input: TInput) => TOutput | Promise<TOutput>,\n options: ValidateOptions = {}\n): (input: unknown) => Promise<TOutput> {\n return async (input: unknown) => {\n const validated = validate(schema, input, options)\n return handler(validated)\n }\n}\n\n\n/**\n * Helper to extract nested value from object by path\n */\nfunction getNestedValue(obj: unknown, path: (string | number)[]): unknown {\n let current = obj\n for (const key of path) {\n if (current === null || current === undefined) return undefined\n current = (current as Record<string | number, unknown>)[key]\n }\n return current\n}\n\n/**\n * Common schema patterns for MCP tools\n */\nexport const schemas = {\n /** Non-empty string */\n nonEmptyString: z.string().min(1, 'Cannot be empty'),\n \n /** Positive integer */\n positiveInt: z.number().int().positive(),\n \n /** Pagination limit (1-100, default 10) */\n limit: z.number().int().min(1).max(100).default(10),\n \n /** Pagination offset (>= 0, default 0) */\n offset: z.number().int().min(0).default(0),\n \n /** URL string */\n url: z.string().url(),\n \n /** Email string */\n email: z.string().email(),\n \n /** UUID string */\n uuid: z.string().uuid(),\n \n /** ISO date string */\n isoDate: z.string().datetime(),\n \n /** Boolean with string coercion ('true'/'false' -> boolean) */\n booleanish: z.union([\n z.boolean(),\n z.enum(['true', 'false']).transform(v => v === 'true'),\n ]),\n}\n\n/**\n * Type helper to infer schema type\n */\nexport type Infer<T extends ZodSchema> = z.infer<T>\n","export type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport interface LogEntry {\n timestamp?: string\n level: LogLevel\n service: string\n message: string\n [key: string]: unknown\n}\n\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info') */\n level?: LogLevel\n /** Custom output function (default: console methods) */\n output?: (entry: LogEntry) => void\n /** Include timestamps (default: true) */\n timestamps?: boolean\n /** Pretty print JSON (default: false, use true for local dev) */\n pretty?: boolean\n}\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Creates a structured logger for MCP servers\n */\nexport function createLogger(service: string, options: LoggerOptions = {}) {\n const {\n level: minLevel = 'info',\n timestamps = true,\n pretty = false,\n } = options\n\n const shouldLog = (level: LogLevel): boolean => {\n return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[minLevel]\n }\n\n const formatEntry = (entry: LogEntry): string => {\n return pretty ? JSON.stringify(entry, null, 2) : JSON.stringify(entry)\n }\n\n const log = (level: LogLevel, message: string, data?: Record<string, unknown>) => {\n if (!shouldLog(level)) return\n\n const entry: LogEntry = {\n ...(timestamps && { timestamp: new Date().toISOString() }),\n level,\n service,\n message,\n ...data,\n }\n\n if (options.output) {\n options.output(entry)\n } else {\n const formatted = formatEntry(entry)\n switch (level) {\n case 'debug':\n console.debug(formatted)\n break\n case 'info':\n console.info(formatted)\n break\n case 'warn':\n console.warn(formatted)\n break\n case 'error':\n console.error(formatted)\n break\n }\n }\n\n return entry\n }\n\n return {\n debug: (message: string, data?: Record<string, unknown>) => log('debug', message, data),\n info: (message: string, data?: Record<string, unknown>) => log('info', message, data),\n warn: (message: string, data?: Record<string, unknown>) => log('warn', message, data),\n error: (message: string, data?: Record<string, unknown>) => log('error', message, data),\n \n /**\n * Create a child logger with additional context\n */\n child: (context: Record<string, unknown>) => {\n return createLogger(service, {\n ...options,\n output: (entry) => {\n const merged = { ...entry, ...context }\n if (options.output) {\n options.output(merged)\n } else {\n const formatted = pretty ? JSON.stringify(merged, null, 2) : JSON.stringify(merged)\n console[entry.level](formatted)\n }\n },\n })\n },\n }\n}\n\nexport type Logger = ReturnType<typeof createLogger>\n","export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '0.2.0'\nconst DEFAULT_ENDPOINT = 'https://api.openconductor.ai/functions/v1/telemetry'\n\nlet globalTelemetry: Telemetry | null = null\n\n/**\n * Initialize telemetry for your MCP server\n * Call this once at startup with your OpenConductor API key\n */\nexport function initTelemetry(config: TelemetryConfig): Telemetry {\n globalTelemetry = new Telemetry(config)\n return globalTelemetry\n}\n\n/**\n * Get the global telemetry instance (if initialized)\n */\nexport function getTelemetry(): Telemetry | null {\n return globalTelemetry\n}\n\n\nexport class Telemetry {\n private config: Required<Omit<TelemetryConfig, 'serverVersion'>> & Pick<TelemetryConfig, 'serverVersion'>\n private buffer: ToolMetric[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(config: TelemetryConfig) {\n this.config = {\n apiKey: config.apiKey,\n serverName: config.serverName,\n serverVersion: config.serverVersion,\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n batchSize: config.batchSize ?? 10,\n flushInterval: config.flushInterval ?? 30000,\n debug: config.debug ?? false,\n }\n\n // Start periodic flush\n this.flushTimer = setInterval(() => {\n this.flush().catch(this.handleError.bind(this))\n }, this.config.flushInterval)\n\n // Flush on process exit\n if (typeof process !== 'undefined') {\n process.on('beforeExit', () => this.flush())\n process.on('SIGINT', () => {\n this.flush().finally(() => process.exit(0))\n })\n process.on('SIGTERM', () => {\n this.flush().finally(() => process.exit(0))\n })\n }\n\n this.log('Telemetry initialized', { serverName: config.serverName })\n }\n\n /**\n * Track a tool invocation\n */\n trackToolCall(\n tool: string,\n duration: number,\n success: boolean,\n error?: string\n ): void {\n const metric: ToolMetric = {\n tool,\n duration,\n success,\n ...(error && { error }),\n timestamp: new Date().toISOString(),\n }\n\n this.buffer.push(metric)\n this.log('Metric tracked', { ...metric })\n\n // Auto-flush if buffer is full\n if (this.buffer.length >= this.config.batchSize) {\n this.flush().catch(this.handleError.bind(this))\n }\n }\n\n /**\n * Flush buffered metrics to OpenConductor\n */\n async flush(): Promise<void> {\n if (this.buffer.length === 0) return\n\n const metrics = [...this.buffer]\n this.buffer = []\n\n const batch: TelemetryBatch = {\n serverName: this.config.serverName,\n serverVersion: this.config.serverVersion,\n metrics,\n meta: {\n sdkVersion: SDK_VERSION,\n nodeVersion: typeof process !== 'undefined' ? process.version : 'unknown',\n platform: typeof process !== 'undefined' ? process.platform : 'unknown',\n },\n }\n\n this.log('Flushing metrics', { count: metrics.length })\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'X-OpenConductor-SDK': SDK_VERSION,\n },\n body: JSON.stringify(batch),\n })\n\n if (!response.ok) {\n throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`)\n }\n\n this.log('Metrics flushed successfully', { count: metrics.length })\n } catch (error) {\n // Put metrics back in buffer on failure\n this.buffer.unshift(...metrics)\n throw error\n }\n }\n\n /**\n * Stop telemetry collection\n */\n shutdown(): void {\n if (this.flushTimer) {\n clearInterval(this.flushTimer)\n this.flushTimer = null\n }\n this.flush().catch(this.handleError.bind(this))\n this.log('Telemetry shutdown')\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n console.debug(JSON.stringify({\n timestamp: new Date().toISOString(),\n level: 'debug',\n service: 'openconductor-telemetry',\n message,\n ...data,\n }))\n }\n }\n\n private handleError(error: unknown): void {\n if (this.config.debug) {\n console.error('[OpenConductor Telemetry Error]', error)\n }\n }\n}\n","import { MCPError, ToolExecutionError, TimeoutError } from '../errors'\nimport { createLogger, type Logger } from '../logger'\nimport { getTelemetry } from '../telemetry'\n\nexport interface HealthCheckInfo {\n name: string\n version: string\n description?: string\n uptime?: () => number\n checks?: Record<string, () => Promise<boolean> | boolean>\n}\n\nexport interface HealthCheckResponse {\n status: 'healthy' | 'degraded' | 'unhealthy'\n name: string\n version: string\n description?: string\n uptime?: number\n timestamp: string\n checks?: Record<string, boolean>\n}\n\n/**\n * Creates a standard health check response for MCP servers\n */\nexport function createHealthCheck(info: HealthCheckInfo) {\n return async (): Promise<HealthCheckResponse> => {\n const checks: Record<string, boolean> = {}\n let allHealthy = true\n\n if (info.checks) {\n for (const [name, check] of Object.entries(info.checks)) {\n try {\n checks[name] = await check()\n if (!checks[name]) allHealthy = false\n } catch {\n checks[name] = false\n allHealthy = false\n }\n }\n }\n\n return {\n status: allHealthy ? 'healthy' : 'degraded',\n name: info.name,\n version: info.version,\n ...(info.description && { description: info.description }),\n ...(info.uptime && { uptime: info.uptime() }),\n timestamp: new Date().toISOString(),\n ...(Object.keys(checks).length > 0 && { checks }),\n }\n }\n}\n\n\nexport interface WrapToolOptions {\n /** Tool name for logging and telemetry */\n name: string\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number\n /** Custom logger instance */\n logger?: Logger\n /** Enable telemetry reporting (default: true if telemetry initialized) */\n telemetry?: boolean\n}\n\nexport interface ToolContext {\n /** Unique ID for this tool call */\n callId: string\n /** Tool name */\n name: string\n /** Start time of execution */\n startTime: number\n /** Logger scoped to this call */\n log: Logger\n}\n\n/**\n * Wraps a tool handler with automatic error handling, logging, timeouts, and telemetry\n */\nexport function wrapTool<TInput, TOutput>(\n handler: (input: TInput, ctx: ToolContext) => TOutput | Promise<TOutput>,\n options: WrapToolOptions\n): (input: TInput) => Promise<TOutput> {\n const {\n name,\n timeout = 30000,\n telemetry: enableTelemetry = true,\n } = options\n\n const baseLogger = options.logger ?? createLogger(name)\n\n return async (input: TInput): Promise<TOutput> => {\n const callId = generateCallId()\n const startTime = Date.now()\n const log = baseLogger.child({ callId })\n\n const ctx: ToolContext = { callId, name, startTime, log }\n\n log.info('Tool invoked', { tool: name, input: sanitizeInput(input) })\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError(name, timeout))\n }, timeout)\n })\n\n // Race handler against timeout\n const result = await Promise.race([\n Promise.resolve(handler(input, ctx)),\n timeoutPromise,\n ])\n\n const duration = Date.now() - startTime\n log.info('Tool completed', { tool: name, duration })\n\n // Report success to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, true)\n }\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n log.error('Tool failed', { \n tool: name, \n duration, \n error: errorMessage,\n stack: error instanceof Error ? error.stack : undefined,\n })\n\n // Report failure to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, false, errorMessage)\n }\n\n // Re-throw MCPErrors as-is, wrap others\n if (error instanceof MCPError) {\n throw error\n }\n\n throw new ToolExecutionError(\n name,\n errorMessage,\n error instanceof Error ? error : undefined\n )\n }\n }\n}\n\n/**\n * Generates a unique call ID\n */\nfunction generateCallId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n}\n\n/**\n * Sanitizes input for logging (removes sensitive fields)\n */\nfunction sanitizeInput(input: unknown): unknown {\n if (typeof input !== 'object' || input === null) return input\n\n const sensitiveKeys = ['password', 'token', 'secret', 'key', 'auth', 'credential']\n const sanitized: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (sensitiveKeys.some(k => key.toLowerCase().includes(k))) {\n sanitized[key] = '[REDACTED]'\n } else {\n sanitized[key] = value\n }\n }\n\n return sanitized\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors/codes.ts","../src/errors/index.ts","../src/validate/index.ts","../src/logger/index.ts","../src/telemetry/index.ts","../src/server/index.ts"],"names":["z"],"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,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A,EAAY,SAAS,QAAA,EAAU,KAAA,EAAO,QAAQ,YAAY,CAAA;AACjF,EAAA,MAAM,YAAqC,EAAC;AAE5C,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAgC,CAAA,EAAG;AAC3E,IAAA,IAAI,aAAA,CAAc,KAAK,CAAA,CAAA,KAAK,GAAA,CAAI,aAAY,CAAE,QAAA,CAAS,CAAC,CAAC,CAAA,EAAG;AAC1D,MAAA,SAAA,CAAU,GAAG,CAAA,GAAI,YAAA;AAAA,IACnB,CAAA,MAAO;AACL,MAAA,SAAA,CAAU,GAAG,CAAA,GAAI,KAAA;AAAA,IACnB;AAAA,EACF;AAEA,EAAA,OAAO,SAAA;AACT","file":"index.js","sourcesContent":["/**\n * JSON-RPC 2.0 Standard Error Codes\n * https://www.jsonrpc.org/specification#error_object\n */\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","import { z, ZodError, type ZodSchema, type ZodTypeDef, type SafeParseReturnType } from 'zod'\nimport { ValidationError } from '../errors'\n\n// Re-export zod for convenience\nexport { z, ZodError, type ZodSchema }\nexport type { ZodTypeDef }\n\n/**\n * Options for input validation\n */\nexport interface ValidateOptions {\n /** Strip unknown keys from objects (default: true) */\n stripUnknown?: boolean\n /** Custom error formatter */\n formatError?: (error: ZodError) => string\n}\n\n/**\n * Validates input against a Zod schema\n * Throws ValidationError on failure with detailed field info\n */\nexport function validate<T>(\n schema: ZodSchema<T>,\n input: unknown,\n options: ValidateOptions = {}\n): T {\n const { stripUnknown = true } = options\n\n const result = (\n stripUnknown\n ? schema.safeParse(input)\n : schema instanceof z.ZodObject\n ? schema.strict().safeParse(input)\n : schema.safeParse(input)\n ) as SafeParseReturnType<unknown, T>\n\n if (!result.success) {\n const firstError = result.error.errors[0]\n const field = firstError.path.join('.') || 'input'\n const reason = firstError.message\n throw new ValidationError(field, reason, firstError.path.length > 0 \n ? getNestedValue(input, firstError.path) \n : input\n )\n }\n\n return result.data\n}\n\n/**\n * Creates a validated tool handler\n * Wraps your handler function with automatic input validation\n */\nexport function validateInput<TInput, TOutput>(\n schema: ZodSchema<TInput>,\n handler: (input: TInput) => TOutput | Promise<TOutput>,\n options: ValidateOptions = {}\n): (input: unknown) => Promise<TOutput> {\n return async (input: unknown) => {\n const validated = validate(schema, input, options)\n return handler(validated)\n }\n}\n\n\n/**\n * Helper to extract nested value from object by path\n */\nfunction getNestedValue(obj: unknown, path: (string | number)[]): unknown {\n let current = obj\n for (const key of path) {\n if (current === null || current === undefined) return undefined\n current = (current as Record<string | number, unknown>)[key]\n }\n return current\n}\n\n/**\n * Common schema patterns for MCP tools\n */\nexport const schemas = {\n /** Non-empty string */\n nonEmptyString: z.string().min(1, 'Cannot be empty'),\n \n /** Positive integer */\n positiveInt: z.number().int().positive(),\n \n /** Pagination limit (1-100, default 10) */\n limit: z.number().int().min(1).max(100).default(10),\n \n /** Pagination offset (>= 0, default 0) */\n offset: z.number().int().min(0).default(0),\n \n /** URL string */\n url: z.string().url(),\n \n /** Email string */\n email: z.string().email(),\n \n /** UUID string */\n uuid: z.string().uuid(),\n \n /** ISO date string */\n isoDate: z.string().datetime(),\n \n /** Boolean with string coercion ('true'/'false' -> boolean) */\n booleanish: z.union([\n z.boolean(),\n z.enum(['true', 'false']).transform(v => v === 'true'),\n ]),\n}\n\n/**\n * Type helper to infer schema type\n */\nexport type Infer<T extends ZodSchema> = z.infer<T>\n","export type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport interface LogEntry {\n timestamp?: string\n level: LogLevel\n service: string\n message: string\n [key: string]: unknown\n}\n\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info') */\n level?: LogLevel\n /** Custom output function (default: console methods) */\n output?: (entry: LogEntry) => void\n /** Include timestamps (default: true) */\n timestamps?: boolean\n /** Pretty print JSON (default: false, use true for local dev) */\n pretty?: boolean\n}\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Creates a structured logger for MCP servers\n */\nexport function createLogger(service: string, options: LoggerOptions = {}) {\n const {\n level: minLevel = 'info',\n timestamps = true,\n pretty = false,\n } = options\n\n const shouldLog = (level: LogLevel): boolean => {\n return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[minLevel]\n }\n\n const formatEntry = (entry: LogEntry): string => {\n return pretty ? JSON.stringify(entry, null, 2) : JSON.stringify(entry)\n }\n\n const log = (level: LogLevel, message: string, data?: Record<string, unknown>) => {\n if (!shouldLog(level)) return\n\n const entry: LogEntry = {\n ...(timestamps && { timestamp: new Date().toISOString() }),\n level,\n service,\n message,\n ...data,\n }\n\n if (options.output) {\n options.output(entry)\n } else {\n const formatted = formatEntry(entry)\n switch (level) {\n case 'debug':\n console.debug(formatted)\n break\n case 'info':\n console.info(formatted)\n break\n case 'warn':\n console.warn(formatted)\n break\n case 'error':\n console.error(formatted)\n break\n }\n }\n\n return entry\n }\n\n return {\n debug: (message: string, data?: Record<string, unknown>) => log('debug', message, data),\n info: (message: string, data?: Record<string, unknown>) => log('info', message, data),\n warn: (message: string, data?: Record<string, unknown>) => log('warn', message, data),\n error: (message: string, data?: Record<string, unknown>) => log('error', message, data),\n \n /**\n * Create a child logger with additional context\n */\n child: (context: Record<string, unknown>) => {\n return createLogger(service, {\n ...options,\n output: (entry) => {\n const merged = { ...entry, ...context }\n if (options.output) {\n options.output(merged)\n } else {\n const formatted = pretty ? JSON.stringify(merged, null, 2) : JSON.stringify(merged)\n console[entry.level](formatted)\n }\n },\n })\n },\n }\n}\n\nexport type Logger = ReturnType<typeof createLogger>\n","export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '1.0.0'\nconst DEFAULT_ENDPOINT = 'https://api.openconductor.ai/functions/v1/telemetry'\n\nlet globalTelemetry: Telemetry | null = null\n\n/**\n * Initialize telemetry for your MCP server\n * Call this once at startup with your OpenConductor API key\n */\nexport function initTelemetry(config: TelemetryConfig): Telemetry {\n globalTelemetry = new Telemetry(config)\n return globalTelemetry\n}\n\n/**\n * Get the global telemetry instance (if initialized)\n */\nexport function getTelemetry(): Telemetry | null {\n return globalTelemetry\n}\n\n\nexport class Telemetry {\n private config: Required<Omit<TelemetryConfig, 'serverVersion'>> & Pick<TelemetryConfig, 'serverVersion'>\n private buffer: ToolMetric[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(config: TelemetryConfig) {\n this.config = {\n apiKey: config.apiKey,\n serverName: config.serverName,\n serverVersion: config.serverVersion,\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n batchSize: config.batchSize ?? 10,\n flushInterval: config.flushInterval ?? 30000,\n debug: config.debug ?? false,\n }\n\n // Start periodic flush\n this.flushTimer = setInterval(() => {\n this.flush().catch(this.handleError.bind(this))\n }, this.config.flushInterval)\n\n // Flush on process exit\n if (typeof process !== 'undefined') {\n process.on('beforeExit', () => this.flush())\n process.on('SIGINT', () => {\n this.flush().finally(() => process.exit(0))\n })\n process.on('SIGTERM', () => {\n this.flush().finally(() => process.exit(0))\n })\n }\n\n this.log('Telemetry initialized', { serverName: config.serverName })\n }\n\n /**\n * Track a tool invocation\n */\n trackToolCall(\n tool: string,\n duration: number,\n success: boolean,\n error?: string\n ): void {\n const metric: ToolMetric = {\n tool,\n duration,\n success,\n ...(error && { error }),\n timestamp: new Date().toISOString(),\n }\n\n this.buffer.push(metric)\n this.log('Metric tracked', { ...metric })\n\n // Auto-flush if buffer is full\n if (this.buffer.length >= this.config.batchSize) {\n this.flush().catch(this.handleError.bind(this))\n }\n }\n\n /**\n * Flush buffered metrics to OpenConductor\n */\n async flush(): Promise<void> {\n if (this.buffer.length === 0) return\n\n const metrics = [...this.buffer]\n this.buffer = []\n\n const batch: TelemetryBatch = {\n serverName: this.config.serverName,\n serverVersion: this.config.serverVersion,\n metrics,\n meta: {\n sdkVersion: SDK_VERSION,\n nodeVersion: typeof process !== 'undefined' ? process.version : 'unknown',\n platform: typeof process !== 'undefined' ? process.platform : 'unknown',\n },\n }\n\n this.log('Flushing metrics', { count: metrics.length })\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'X-OpenConductor-SDK': SDK_VERSION,\n },\n body: JSON.stringify(batch),\n })\n\n if (!response.ok) {\n throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`)\n }\n\n this.log('Metrics flushed successfully', { count: metrics.length })\n } catch (error) {\n // Put metrics back in buffer on failure\n this.buffer.unshift(...metrics)\n throw error\n }\n }\n\n /**\n * Stop telemetry collection\n */\n shutdown(): void {\n if (this.flushTimer) {\n clearInterval(this.flushTimer)\n this.flushTimer = null\n }\n this.flush().catch(this.handleError.bind(this))\n this.log('Telemetry shutdown')\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n console.debug(JSON.stringify({\n timestamp: new Date().toISOString(),\n level: 'debug',\n service: 'openconductor-telemetry',\n message,\n ...data,\n }))\n }\n }\n\n private handleError(error: unknown): void {\n if (this.config.debug) {\n console.error('[OpenConductor Telemetry Error]', error)\n }\n }\n}\n","import { MCPError, ToolExecutionError, TimeoutError } from '../errors'\nimport { createLogger, type Logger } from '../logger'\nimport { getTelemetry } from '../telemetry'\n\nexport interface HealthCheckInfo {\n name: string\n version: string\n description?: string\n uptime?: () => number\n checks?: Record<string, () => Promise<boolean> | boolean>\n}\n\nexport interface HealthCheckResponse {\n status: 'healthy' | 'degraded' | 'unhealthy'\n name: string\n version: string\n description?: string\n uptime?: number\n timestamp: string\n checks?: Record<string, boolean>\n}\n\n/**\n * Creates a standard health check response for MCP servers\n */\nexport function createHealthCheck(info: HealthCheckInfo) {\n return async (): Promise<HealthCheckResponse> => {\n const checks: Record<string, boolean> = {}\n let allHealthy = true\n\n if (info.checks) {\n for (const [name, check] of Object.entries(info.checks)) {\n try {\n checks[name] = await check()\n if (!checks[name]) allHealthy = false\n } catch {\n checks[name] = false\n allHealthy = false\n }\n }\n }\n\n return {\n status: allHealthy ? 'healthy' : 'degraded',\n name: info.name,\n version: info.version,\n ...(info.description && { description: info.description }),\n ...(info.uptime && { uptime: info.uptime() }),\n timestamp: new Date().toISOString(),\n ...(Object.keys(checks).length > 0 && { checks }),\n }\n }\n}\n\n\nexport interface WrapToolOptions {\n /** Tool name for logging and telemetry */\n name: string\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number\n /** Custom logger instance */\n logger?: Logger\n /** Enable telemetry reporting (default: true if telemetry initialized) */\n telemetry?: boolean\n}\n\nexport interface ToolContext {\n /** Unique ID for this tool call */\n callId: string\n /** Tool name */\n name: string\n /** Start time of execution */\n startTime: number\n /** Logger scoped to this call */\n log: Logger\n}\n\n/**\n * Wraps a tool handler with automatic error handling, logging, timeouts, and telemetry\n */\nexport function wrapTool<TInput, TOutput>(\n handler: (input: TInput, ctx: ToolContext) => TOutput | Promise<TOutput>,\n options: WrapToolOptions\n): (input: TInput) => Promise<TOutput> {\n const {\n name,\n timeout = 30000,\n telemetry: enableTelemetry = true,\n } = options\n\n const baseLogger = options.logger ?? createLogger(name)\n\n return async (input: TInput): Promise<TOutput> => {\n const callId = generateCallId()\n const startTime = Date.now()\n const log = baseLogger.child({ callId })\n\n const ctx: ToolContext = { callId, name, startTime, log }\n\n log.info('Tool invoked', { tool: name, input: sanitizeInput(input) })\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError(name, timeout))\n }, timeout)\n })\n\n // Race handler against timeout\n const result = await Promise.race([\n Promise.resolve(handler(input, ctx)),\n timeoutPromise,\n ])\n\n const duration = Date.now() - startTime\n log.info('Tool completed', { tool: name, duration })\n\n // Report success to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, true)\n }\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n log.error('Tool failed', { \n tool: name, \n duration, \n error: errorMessage,\n stack: error instanceof Error ? error.stack : undefined,\n })\n\n // Report failure to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, false, errorMessage)\n }\n\n // Re-throw MCPErrors as-is, wrap others\n if (error instanceof MCPError) {\n throw error\n }\n\n throw new ToolExecutionError(\n name,\n errorMessage,\n error instanceof Error ? error : undefined\n )\n }\n }\n}\n\n/**\n * Generates a unique call ID\n */\nfunction generateCallId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n}\n\n/**\n * Sanitizes input for logging (removes sensitive fields)\n */\nfunction sanitizeInput(input: unknown): unknown {\n if (typeof input !== 'object' || input === null) return input\n\n const sensitiveKeys = ['password', 'token', 'secret', 'key', 'auth', 'credential']\n const sanitized: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (sensitiveKeys.some(k => key.toLowerCase().includes(k))) {\n sanitized[key] = '[REDACTED]'\n } else {\n sanitized[key] = value\n }\n }\n\n return sanitized\n}\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -271,7 +271,7 @@ function createLogger(service, options = {}) {
|
|
|
271
271
|
}
|
|
272
272
|
|
|
273
273
|
// src/telemetry/index.ts
|
|
274
|
-
var SDK_VERSION = "0.
|
|
274
|
+
var SDK_VERSION = "1.0.0";
|
|
275
275
|
var DEFAULT_ENDPOINT = "https://api.openconductor.ai/functions/v1/telemetry";
|
|
276
276
|
var globalTelemetry = null;
|
|
277
277
|
function initTelemetry(config) {
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors/codes.ts","../src/errors/index.ts","../src/validate/index.ts","../src/logger/index.ts","../src/telemetry/index.ts","../src/server/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;A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AAU,GAAG,CAAA,GAAI,KAAA;AAAA,IACnB;AAAA,EACF;AAEA,EAAA,OAAO,SAAA;AACT","file":"index.mjs","sourcesContent":["/**\n * JSON-RPC 2.0 Standard Error Codes\n * https://www.jsonrpc.org/specification#error_object\n */\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","import { z, ZodError, type ZodSchema, type ZodTypeDef, type SafeParseReturnType } from 'zod'\nimport { ValidationError } from '../errors'\n\n// Re-export zod for convenience\nexport { z, ZodError, type ZodSchema }\nexport type { ZodTypeDef }\n\n/**\n * Options for input validation\n */\nexport interface ValidateOptions {\n /** Strip unknown keys from objects (default: true) */\n stripUnknown?: boolean\n /** Custom error formatter */\n formatError?: (error: ZodError) => string\n}\n\n/**\n * Validates input against a Zod schema\n * Throws ValidationError on failure with detailed field info\n */\nexport function validate<T>(\n schema: ZodSchema<T>,\n input: unknown,\n options: ValidateOptions = {}\n): T {\n const { stripUnknown = true } = options\n\n const result = (\n stripUnknown\n ? schema.safeParse(input)\n : schema instanceof z.ZodObject\n ? schema.strict().safeParse(input)\n : schema.safeParse(input)\n ) as SafeParseReturnType<unknown, T>\n\n if (!result.success) {\n const firstError = result.error.errors[0]\n const field = firstError.path.join('.') || 'input'\n const reason = firstError.message\n throw new ValidationError(field, reason, firstError.path.length > 0 \n ? getNestedValue(input, firstError.path) \n : input\n )\n }\n\n return result.data\n}\n\n/**\n * Creates a validated tool handler\n * Wraps your handler function with automatic input validation\n */\nexport function validateInput<TInput, TOutput>(\n schema: ZodSchema<TInput>,\n handler: (input: TInput) => TOutput | Promise<TOutput>,\n options: ValidateOptions = {}\n): (input: unknown) => Promise<TOutput> {\n return async (input: unknown) => {\n const validated = validate(schema, input, options)\n return handler(validated)\n }\n}\n\n\n/**\n * Helper to extract nested value from object by path\n */\nfunction getNestedValue(obj: unknown, path: (string | number)[]): unknown {\n let current = obj\n for (const key of path) {\n if (current === null || current === undefined) return undefined\n current = (current as Record<string | number, unknown>)[key]\n }\n return current\n}\n\n/**\n * Common schema patterns for MCP tools\n */\nexport const schemas = {\n /** Non-empty string */\n nonEmptyString: z.string().min(1, 'Cannot be empty'),\n \n /** Positive integer */\n positiveInt: z.number().int().positive(),\n \n /** Pagination limit (1-100, default 10) */\n limit: z.number().int().min(1).max(100).default(10),\n \n /** Pagination offset (>= 0, default 0) */\n offset: z.number().int().min(0).default(0),\n \n /** URL string */\n url: z.string().url(),\n \n /** Email string */\n email: z.string().email(),\n \n /** UUID string */\n uuid: z.string().uuid(),\n \n /** ISO date string */\n isoDate: z.string().datetime(),\n \n /** Boolean with string coercion ('true'/'false' -> boolean) */\n booleanish: z.union([\n z.boolean(),\n z.enum(['true', 'false']).transform(v => v === 'true'),\n ]),\n}\n\n/**\n * Type helper to infer schema type\n */\nexport type Infer<T extends ZodSchema> = z.infer<T>\n","export type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport interface LogEntry {\n timestamp?: string\n level: LogLevel\n service: string\n message: string\n [key: string]: unknown\n}\n\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info') */\n level?: LogLevel\n /** Custom output function (default: console methods) */\n output?: (entry: LogEntry) => void\n /** Include timestamps (default: true) */\n timestamps?: boolean\n /** Pretty print JSON (default: false, use true for local dev) */\n pretty?: boolean\n}\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Creates a structured logger for MCP servers\n */\nexport function createLogger(service: string, options: LoggerOptions = {}) {\n const {\n level: minLevel = 'info',\n timestamps = true,\n pretty = false,\n } = options\n\n const shouldLog = (level: LogLevel): boolean => {\n return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[minLevel]\n }\n\n const formatEntry = (entry: LogEntry): string => {\n return pretty ? JSON.stringify(entry, null, 2) : JSON.stringify(entry)\n }\n\n const log = (level: LogLevel, message: string, data?: Record<string, unknown>) => {\n if (!shouldLog(level)) return\n\n const entry: LogEntry = {\n ...(timestamps && { timestamp: new Date().toISOString() }),\n level,\n service,\n message,\n ...data,\n }\n\n if (options.output) {\n options.output(entry)\n } else {\n const formatted = formatEntry(entry)\n switch (level) {\n case 'debug':\n console.debug(formatted)\n break\n case 'info':\n console.info(formatted)\n break\n case 'warn':\n console.warn(formatted)\n break\n case 'error':\n console.error(formatted)\n break\n }\n }\n\n return entry\n }\n\n return {\n debug: (message: string, data?: Record<string, unknown>) => log('debug', message, data),\n info: (message: string, data?: Record<string, unknown>) => log('info', message, data),\n warn: (message: string, data?: Record<string, unknown>) => log('warn', message, data),\n error: (message: string, data?: Record<string, unknown>) => log('error', message, data),\n \n /**\n * Create a child logger with additional context\n */\n child: (context: Record<string, unknown>) => {\n return createLogger(service, {\n ...options,\n output: (entry) => {\n const merged = { ...entry, ...context }\n if (options.output) {\n options.output(merged)\n } else {\n const formatted = pretty ? JSON.stringify(merged, null, 2) : JSON.stringify(merged)\n console[entry.level](formatted)\n }\n },\n })\n },\n }\n}\n\nexport type Logger = ReturnType<typeof createLogger>\n","export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '0.2.0'\nconst DEFAULT_ENDPOINT = 'https://api.openconductor.ai/functions/v1/telemetry'\n\nlet globalTelemetry: Telemetry | null = null\n\n/**\n * Initialize telemetry for your MCP server\n * Call this once at startup with your OpenConductor API key\n */\nexport function initTelemetry(config: TelemetryConfig): Telemetry {\n globalTelemetry = new Telemetry(config)\n return globalTelemetry\n}\n\n/**\n * Get the global telemetry instance (if initialized)\n */\nexport function getTelemetry(): Telemetry | null {\n return globalTelemetry\n}\n\n\nexport class Telemetry {\n private config: Required<Omit<TelemetryConfig, 'serverVersion'>> & Pick<TelemetryConfig, 'serverVersion'>\n private buffer: ToolMetric[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(config: TelemetryConfig) {\n this.config = {\n apiKey: config.apiKey,\n serverName: config.serverName,\n serverVersion: config.serverVersion,\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n batchSize: config.batchSize ?? 10,\n flushInterval: config.flushInterval ?? 30000,\n debug: config.debug ?? false,\n }\n\n // Start periodic flush\n this.flushTimer = setInterval(() => {\n this.flush().catch(this.handleError.bind(this))\n }, this.config.flushInterval)\n\n // Flush on process exit\n if (typeof process !== 'undefined') {\n process.on('beforeExit', () => this.flush())\n process.on('SIGINT', () => {\n this.flush().finally(() => process.exit(0))\n })\n process.on('SIGTERM', () => {\n this.flush().finally(() => process.exit(0))\n })\n }\n\n this.log('Telemetry initialized', { serverName: config.serverName })\n }\n\n /**\n * Track a tool invocation\n */\n trackToolCall(\n tool: string,\n duration: number,\n success: boolean,\n error?: string\n ): void {\n const metric: ToolMetric = {\n tool,\n duration,\n success,\n ...(error && { error }),\n timestamp: new Date().toISOString(),\n }\n\n this.buffer.push(metric)\n this.log('Metric tracked', { ...metric })\n\n // Auto-flush if buffer is full\n if (this.buffer.length >= this.config.batchSize) {\n this.flush().catch(this.handleError.bind(this))\n }\n }\n\n /**\n * Flush buffered metrics to OpenConductor\n */\n async flush(): Promise<void> {\n if (this.buffer.length === 0) return\n\n const metrics = [...this.buffer]\n this.buffer = []\n\n const batch: TelemetryBatch = {\n serverName: this.config.serverName,\n serverVersion: this.config.serverVersion,\n metrics,\n meta: {\n sdkVersion: SDK_VERSION,\n nodeVersion: typeof process !== 'undefined' ? process.version : 'unknown',\n platform: typeof process !== 'undefined' ? process.platform : 'unknown',\n },\n }\n\n this.log('Flushing metrics', { count: metrics.length })\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'X-OpenConductor-SDK': SDK_VERSION,\n },\n body: JSON.stringify(batch),\n })\n\n if (!response.ok) {\n throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`)\n }\n\n this.log('Metrics flushed successfully', { count: metrics.length })\n } catch (error) {\n // Put metrics back in buffer on failure\n this.buffer.unshift(...metrics)\n throw error\n }\n }\n\n /**\n * Stop telemetry collection\n */\n shutdown(): void {\n if (this.flushTimer) {\n clearInterval(this.flushTimer)\n this.flushTimer = null\n }\n this.flush().catch(this.handleError.bind(this))\n this.log('Telemetry shutdown')\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n console.debug(JSON.stringify({\n timestamp: new Date().toISOString(),\n level: 'debug',\n service: 'openconductor-telemetry',\n message,\n ...data,\n }))\n }\n }\n\n private handleError(error: unknown): void {\n if (this.config.debug) {\n console.error('[OpenConductor Telemetry Error]', error)\n }\n }\n}\n","import { MCPError, ToolExecutionError, TimeoutError } from '../errors'\nimport { createLogger, type Logger } from '../logger'\nimport { getTelemetry } from '../telemetry'\n\nexport interface HealthCheckInfo {\n name: string\n version: string\n description?: string\n uptime?: () => number\n checks?: Record<string, () => Promise<boolean> | boolean>\n}\n\nexport interface HealthCheckResponse {\n status: 'healthy' | 'degraded' | 'unhealthy'\n name: string\n version: string\n description?: string\n uptime?: number\n timestamp: string\n checks?: Record<string, boolean>\n}\n\n/**\n * Creates a standard health check response for MCP servers\n */\nexport function createHealthCheck(info: HealthCheckInfo) {\n return async (): Promise<HealthCheckResponse> => {\n const checks: Record<string, boolean> = {}\n let allHealthy = true\n\n if (info.checks) {\n for (const [name, check] of Object.entries(info.checks)) {\n try {\n checks[name] = await check()\n if (!checks[name]) allHealthy = false\n } catch {\n checks[name] = false\n allHealthy = false\n }\n }\n }\n\n return {\n status: allHealthy ? 'healthy' : 'degraded',\n name: info.name,\n version: info.version,\n ...(info.description && { description: info.description }),\n ...(info.uptime && { uptime: info.uptime() }),\n timestamp: new Date().toISOString(),\n ...(Object.keys(checks).length > 0 && { checks }),\n }\n }\n}\n\n\nexport interface WrapToolOptions {\n /** Tool name for logging and telemetry */\n name: string\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number\n /** Custom logger instance */\n logger?: Logger\n /** Enable telemetry reporting (default: true if telemetry initialized) */\n telemetry?: boolean\n}\n\nexport interface ToolContext {\n /** Unique ID for this tool call */\n callId: string\n /** Tool name */\n name: string\n /** Start time of execution */\n startTime: number\n /** Logger scoped to this call */\n log: Logger\n}\n\n/**\n * Wraps a tool handler with automatic error handling, logging, timeouts, and telemetry\n */\nexport function wrapTool<TInput, TOutput>(\n handler: (input: TInput, ctx: ToolContext) => TOutput | Promise<TOutput>,\n options: WrapToolOptions\n): (input: TInput) => Promise<TOutput> {\n const {\n name,\n timeout = 30000,\n telemetry: enableTelemetry = true,\n } = options\n\n const baseLogger = options.logger ?? createLogger(name)\n\n return async (input: TInput): Promise<TOutput> => {\n const callId = generateCallId()\n const startTime = Date.now()\n const log = baseLogger.child({ callId })\n\n const ctx: ToolContext = { callId, name, startTime, log }\n\n log.info('Tool invoked', { tool: name, input: sanitizeInput(input) })\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError(name, timeout))\n }, timeout)\n })\n\n // Race handler against timeout\n const result = await Promise.race([\n Promise.resolve(handler(input, ctx)),\n timeoutPromise,\n ])\n\n const duration = Date.now() - startTime\n log.info('Tool completed', { tool: name, duration })\n\n // Report success to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, true)\n }\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n log.error('Tool failed', { \n tool: name, \n duration, \n error: errorMessage,\n stack: error instanceof Error ? error.stack : undefined,\n })\n\n // Report failure to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, false, errorMessage)\n }\n\n // Re-throw MCPErrors as-is, wrap others\n if (error instanceof MCPError) {\n throw error\n }\n\n throw new ToolExecutionError(\n name,\n errorMessage,\n error instanceof Error ? error : undefined\n )\n }\n }\n}\n\n/**\n * Generates a unique call ID\n */\nfunction generateCallId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n}\n\n/**\n * Sanitizes input for logging (removes sensitive fields)\n */\nfunction sanitizeInput(input: unknown): unknown {\n if (typeof input !== 'object' || input === null) return input\n\n const sensitiveKeys = ['password', 'token', 'secret', 'key', 'auth', 'credential']\n const sanitized: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (sensitiveKeys.some(k => key.toLowerCase().includes(k))) {\n sanitized[key] = '[REDACTED]'\n } else {\n sanitized[key] = value\n }\n }\n\n return sanitized\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors/codes.ts","../src/errors/index.ts","../src/validate/index.ts","../src/logger/index.ts","../src/telemetry/index.ts","../src/server/index.ts"],"names":[],"mappings":";;;;AAIO,IAAM,UAAA,GAAa;AAAA;AAAA,EAExB,WAAA,EAAa,MAAA;AAAA,EACb,eAAA,EAAiB,MAAA;AAAA,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IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,MAAM,OAAO,KAAA;AAExD,EAAA,MAAM,gBAAgB,CAAC,UAAA,EAAY,SAAS,QAAA,EAAU,KAAA,EAAO,QAAQ,YAAY,CAAA;AACjF,EAAA,MAAM,YAAqC,EAAC;AAE5C,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAgC,CAAA,EAAG;AAC3E,IAAA,IAAI,aAAA,CAAc,KAAK,CAAA,CAAA,KAAK,GAAA,CAAI,aAAY,CAAE,QAAA,CAAS,CAAC,CAAC,CAAA,EAAG;AAC1D,MAAA,SAAA,CAAU,GAAG,CAAA,GAAI,YAAA;AAAA,IACnB,CAAA,MAAO;AACL,MAAA,SAAA,CAAU,GAAG,CAAA,GAAI,KAAA;AAAA,IACnB;AAAA,EACF;AAEA,EAAA,OAAO,SAAA;AACT","file":"index.mjs","sourcesContent":["/**\n * JSON-RPC 2.0 Standard Error Codes\n * https://www.jsonrpc.org/specification#error_object\n */\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","import { z, ZodError, type ZodSchema, type ZodTypeDef, type SafeParseReturnType } from 'zod'\nimport { ValidationError } from '../errors'\n\n// Re-export zod for convenience\nexport { z, ZodError, type ZodSchema }\nexport type { ZodTypeDef }\n\n/**\n * Options for input validation\n */\nexport interface ValidateOptions {\n /** Strip unknown keys from objects (default: true) */\n stripUnknown?: boolean\n /** Custom error formatter */\n formatError?: (error: ZodError) => string\n}\n\n/**\n * Validates input against a Zod schema\n * Throws ValidationError on failure with detailed field info\n */\nexport function validate<T>(\n schema: ZodSchema<T>,\n input: unknown,\n options: ValidateOptions = {}\n): T {\n const { stripUnknown = true } = options\n\n const result = (\n stripUnknown\n ? schema.safeParse(input)\n : schema instanceof z.ZodObject\n ? schema.strict().safeParse(input)\n : schema.safeParse(input)\n ) as SafeParseReturnType<unknown, T>\n\n if (!result.success) {\n const firstError = result.error.errors[0]\n const field = firstError.path.join('.') || 'input'\n const reason = firstError.message\n throw new ValidationError(field, reason, firstError.path.length > 0 \n ? getNestedValue(input, firstError.path) \n : input\n )\n }\n\n return result.data\n}\n\n/**\n * Creates a validated tool handler\n * Wraps your handler function with automatic input validation\n */\nexport function validateInput<TInput, TOutput>(\n schema: ZodSchema<TInput>,\n handler: (input: TInput) => TOutput | Promise<TOutput>,\n options: ValidateOptions = {}\n): (input: unknown) => Promise<TOutput> {\n return async (input: unknown) => {\n const validated = validate(schema, input, options)\n return handler(validated)\n }\n}\n\n\n/**\n * Helper to extract nested value from object by path\n */\nfunction getNestedValue(obj: unknown, path: (string | number)[]): unknown {\n let current = obj\n for (const key of path) {\n if (current === null || current === undefined) return undefined\n current = (current as Record<string | number, unknown>)[key]\n }\n return current\n}\n\n/**\n * Common schema patterns for MCP tools\n */\nexport const schemas = {\n /** Non-empty string */\n nonEmptyString: z.string().min(1, 'Cannot be empty'),\n \n /** Positive integer */\n positiveInt: z.number().int().positive(),\n \n /** Pagination limit (1-100, default 10) */\n limit: z.number().int().min(1).max(100).default(10),\n \n /** Pagination offset (>= 0, default 0) */\n offset: z.number().int().min(0).default(0),\n \n /** URL string */\n url: z.string().url(),\n \n /** Email string */\n email: z.string().email(),\n \n /** UUID string */\n uuid: z.string().uuid(),\n \n /** ISO date string */\n isoDate: z.string().datetime(),\n \n /** Boolean with string coercion ('true'/'false' -> boolean) */\n booleanish: z.union([\n z.boolean(),\n z.enum(['true', 'false']).transform(v => v === 'true'),\n ]),\n}\n\n/**\n * Type helper to infer schema type\n */\nexport type Infer<T extends ZodSchema> = z.infer<T>\n","export type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport interface LogEntry {\n timestamp?: string\n level: LogLevel\n service: string\n message: string\n [key: string]: unknown\n}\n\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info') */\n level?: LogLevel\n /** Custom output function (default: console methods) */\n output?: (entry: LogEntry) => void\n /** Include timestamps (default: true) */\n timestamps?: boolean\n /** Pretty print JSON (default: false, use true for local dev) */\n pretty?: boolean\n}\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Creates a structured logger for MCP servers\n */\nexport function createLogger(service: string, options: LoggerOptions = {}) {\n const {\n level: minLevel = 'info',\n timestamps = true,\n pretty = false,\n } = options\n\n const shouldLog = (level: LogLevel): boolean => {\n return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[minLevel]\n }\n\n const formatEntry = (entry: LogEntry): string => {\n return pretty ? JSON.stringify(entry, null, 2) : JSON.stringify(entry)\n }\n\n const log = (level: LogLevel, message: string, data?: Record<string, unknown>) => {\n if (!shouldLog(level)) return\n\n const entry: LogEntry = {\n ...(timestamps && { timestamp: new Date().toISOString() }),\n level,\n service,\n message,\n ...data,\n }\n\n if (options.output) {\n options.output(entry)\n } else {\n const formatted = formatEntry(entry)\n switch (level) {\n case 'debug':\n console.debug(formatted)\n break\n case 'info':\n console.info(formatted)\n break\n case 'warn':\n console.warn(formatted)\n break\n case 'error':\n console.error(formatted)\n break\n }\n }\n\n return entry\n }\n\n return {\n debug: (message: string, data?: Record<string, unknown>) => log('debug', message, data),\n info: (message: string, data?: Record<string, unknown>) => log('info', message, data),\n warn: (message: string, data?: Record<string, unknown>) => log('warn', message, data),\n error: (message: string, data?: Record<string, unknown>) => log('error', message, data),\n \n /**\n * Create a child logger with additional context\n */\n child: (context: Record<string, unknown>) => {\n return createLogger(service, {\n ...options,\n output: (entry) => {\n const merged = { ...entry, ...context }\n if (options.output) {\n options.output(merged)\n } else {\n const formatted = pretty ? JSON.stringify(merged, null, 2) : JSON.stringify(merged)\n console[entry.level](formatted)\n }\n },\n })\n },\n }\n}\n\nexport type Logger = ReturnType<typeof createLogger>\n","export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '1.0.0'\nconst DEFAULT_ENDPOINT = 'https://api.openconductor.ai/functions/v1/telemetry'\n\nlet globalTelemetry: Telemetry | null = null\n\n/**\n * Initialize telemetry for your MCP server\n * Call this once at startup with your OpenConductor API key\n */\nexport function initTelemetry(config: TelemetryConfig): Telemetry {\n globalTelemetry = new Telemetry(config)\n return globalTelemetry\n}\n\n/**\n * Get the global telemetry instance (if initialized)\n */\nexport function getTelemetry(): Telemetry | null {\n return globalTelemetry\n}\n\n\nexport class Telemetry {\n private config: Required<Omit<TelemetryConfig, 'serverVersion'>> & Pick<TelemetryConfig, 'serverVersion'>\n private buffer: ToolMetric[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(config: TelemetryConfig) {\n this.config = {\n apiKey: config.apiKey,\n serverName: config.serverName,\n serverVersion: config.serverVersion,\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n batchSize: config.batchSize ?? 10,\n flushInterval: config.flushInterval ?? 30000,\n debug: config.debug ?? false,\n }\n\n // Start periodic flush\n this.flushTimer = setInterval(() => {\n this.flush().catch(this.handleError.bind(this))\n }, this.config.flushInterval)\n\n // Flush on process exit\n if (typeof process !== 'undefined') {\n process.on('beforeExit', () => this.flush())\n process.on('SIGINT', () => {\n this.flush().finally(() => process.exit(0))\n })\n process.on('SIGTERM', () => {\n this.flush().finally(() => process.exit(0))\n })\n }\n\n this.log('Telemetry initialized', { serverName: config.serverName })\n }\n\n /**\n * Track a tool invocation\n */\n trackToolCall(\n tool: string,\n duration: number,\n success: boolean,\n error?: string\n ): void {\n const metric: ToolMetric = {\n tool,\n duration,\n success,\n ...(error && { error }),\n timestamp: new Date().toISOString(),\n }\n\n this.buffer.push(metric)\n this.log('Metric tracked', { ...metric })\n\n // Auto-flush if buffer is full\n if (this.buffer.length >= this.config.batchSize) {\n this.flush().catch(this.handleError.bind(this))\n }\n }\n\n /**\n * Flush buffered metrics to OpenConductor\n */\n async flush(): Promise<void> {\n if (this.buffer.length === 0) return\n\n const metrics = [...this.buffer]\n this.buffer = []\n\n const batch: TelemetryBatch = {\n serverName: this.config.serverName,\n serverVersion: this.config.serverVersion,\n metrics,\n meta: {\n sdkVersion: SDK_VERSION,\n nodeVersion: typeof process !== 'undefined' ? process.version : 'unknown',\n platform: typeof process !== 'undefined' ? process.platform : 'unknown',\n },\n }\n\n this.log('Flushing metrics', { count: metrics.length })\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'X-OpenConductor-SDK': SDK_VERSION,\n },\n body: JSON.stringify(batch),\n })\n\n if (!response.ok) {\n throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`)\n }\n\n this.log('Metrics flushed successfully', { count: metrics.length })\n } catch (error) {\n // Put metrics back in buffer on failure\n this.buffer.unshift(...metrics)\n throw error\n }\n }\n\n /**\n * Stop telemetry collection\n */\n shutdown(): void {\n if (this.flushTimer) {\n clearInterval(this.flushTimer)\n this.flushTimer = null\n }\n this.flush().catch(this.handleError.bind(this))\n this.log('Telemetry shutdown')\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n console.debug(JSON.stringify({\n timestamp: new Date().toISOString(),\n level: 'debug',\n service: 'openconductor-telemetry',\n message,\n ...data,\n }))\n }\n }\n\n private handleError(error: unknown): void {\n if (this.config.debug) {\n console.error('[OpenConductor Telemetry Error]', error)\n }\n }\n}\n","import { MCPError, ToolExecutionError, TimeoutError } from '../errors'\nimport { createLogger, type Logger } from '../logger'\nimport { getTelemetry } from '../telemetry'\n\nexport interface HealthCheckInfo {\n name: string\n version: string\n description?: string\n uptime?: () => number\n checks?: Record<string, () => Promise<boolean> | boolean>\n}\n\nexport interface HealthCheckResponse {\n status: 'healthy' | 'degraded' | 'unhealthy'\n name: string\n version: string\n description?: string\n uptime?: number\n timestamp: string\n checks?: Record<string, boolean>\n}\n\n/**\n * Creates a standard health check response for MCP servers\n */\nexport function createHealthCheck(info: HealthCheckInfo) {\n return async (): Promise<HealthCheckResponse> => {\n const checks: Record<string, boolean> = {}\n let allHealthy = true\n\n if (info.checks) {\n for (const [name, check] of Object.entries(info.checks)) {\n try {\n checks[name] = await check()\n if (!checks[name]) allHealthy = false\n } catch {\n checks[name] = false\n allHealthy = false\n }\n }\n }\n\n return {\n status: allHealthy ? 'healthy' : 'degraded',\n name: info.name,\n version: info.version,\n ...(info.description && { description: info.description }),\n ...(info.uptime && { uptime: info.uptime() }),\n timestamp: new Date().toISOString(),\n ...(Object.keys(checks).length > 0 && { checks }),\n }\n }\n}\n\n\nexport interface WrapToolOptions {\n /** Tool name for logging and telemetry */\n name: string\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number\n /** Custom logger instance */\n logger?: Logger\n /** Enable telemetry reporting (default: true if telemetry initialized) */\n telemetry?: boolean\n}\n\nexport interface ToolContext {\n /** Unique ID for this tool call */\n callId: string\n /** Tool name */\n name: string\n /** Start time of execution */\n startTime: number\n /** Logger scoped to this call */\n log: Logger\n}\n\n/**\n * Wraps a tool handler with automatic error handling, logging, timeouts, and telemetry\n */\nexport function wrapTool<TInput, TOutput>(\n handler: (input: TInput, ctx: ToolContext) => TOutput | Promise<TOutput>,\n options: WrapToolOptions\n): (input: TInput) => Promise<TOutput> {\n const {\n name,\n timeout = 30000,\n telemetry: enableTelemetry = true,\n } = options\n\n const baseLogger = options.logger ?? createLogger(name)\n\n return async (input: TInput): Promise<TOutput> => {\n const callId = generateCallId()\n const startTime = Date.now()\n const log = baseLogger.child({ callId })\n\n const ctx: ToolContext = { callId, name, startTime, log }\n\n log.info('Tool invoked', { tool: name, input: sanitizeInput(input) })\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError(name, timeout))\n }, timeout)\n })\n\n // Race handler against timeout\n const result = await Promise.race([\n Promise.resolve(handler(input, ctx)),\n timeoutPromise,\n ])\n\n const duration = Date.now() - startTime\n log.info('Tool completed', { tool: name, duration })\n\n // Report success to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, true)\n }\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n log.error('Tool failed', { \n tool: name, \n duration, \n error: errorMessage,\n stack: error instanceof Error ? error.stack : undefined,\n })\n\n // Report failure to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, false, errorMessage)\n }\n\n // Re-throw MCPErrors as-is, wrap others\n if (error instanceof MCPError) {\n throw error\n }\n\n throw new ToolExecutionError(\n name,\n errorMessage,\n error instanceof Error ? error : undefined\n )\n }\n }\n}\n\n/**\n * Generates a unique call ID\n */\nfunction generateCallId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n}\n\n/**\n * Sanitizes input for logging (removes sensitive fields)\n */\nfunction sanitizeInput(input: unknown): unknown {\n if (typeof input !== 'object' || input === null) return input\n\n const sensitiveKeys = ['password', 'token', 'secret', 'key', 'auth', 'credential']\n const sanitized: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (sensitiveKeys.some(k => key.toLowerCase().includes(k))) {\n sanitized[key] = '[REDACTED]'\n } else {\n sanitized[key] = value\n }\n }\n\n return sanitized\n}\n"]}
|
package/dist/server/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors/codes.ts","../../src/errors/index.ts","../../src/logger/index.ts","../../src/telemetry/index.ts","../../src/server/index.ts"],"names":[],"mappings":";;;AAIO,IAAM,UAAA,GAAa;AAAA,EAUxB,oBAAA,EAAsB,MAAA;AAAA,EAKtB,aAAA,EAAe,MAIjB,CAAA;;;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,iBAAA,CAAkB,IAAA,EAAM,IAAA,CAAK,WAAW,CAAA;AAAA,IAChD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAA,GAAS;AACP,IAAA,OAAO;AAAA,MACL,MAAM,IAAA,CAAK,IAAA;AAAA,MACX,SAAS,IAAA,CAAK,OAAA;AAAA,MACd,GAAI,IAAA,CAAK,IAAA,IAAQ,EAAE,IAAA,EAAM,KAAK,IAAA;AAAK,KACrC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,UAAA,CA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AA,OAAO,SAAA;AACT","file":"index.js","sourcesContent":["/**\n * JSON-RPC 2.0 Standard Error Codes\n * https://www.jsonrpc.org/specification#error_object\n */\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","export type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport interface LogEntry {\n timestamp?: string\n level: LogLevel\n service: string\n message: string\n [key: string]: unknown\n}\n\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info') */\n level?: LogLevel\n /** Custom output function (default: console methods) */\n output?: (entry: LogEntry) => void\n /** Include timestamps (default: true) */\n timestamps?: boolean\n /** Pretty print JSON (default: false, use true for local dev) */\n pretty?: boolean\n}\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Creates a structured logger for MCP servers\n */\nexport function createLogger(service: string, options: LoggerOptions = {}) {\n const {\n level: minLevel = 'info',\n timestamps = true,\n pretty = false,\n } = options\n\n const shouldLog = (level: LogLevel): boolean => {\n return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[minLevel]\n }\n\n const formatEntry = (entry: LogEntry): string => {\n return pretty ? JSON.stringify(entry, null, 2) : JSON.stringify(entry)\n }\n\n const log = (level: LogLevel, message: string, data?: Record<string, unknown>) => {\n if (!shouldLog(level)) return\n\n const entry: LogEntry = {\n ...(timestamps && { timestamp: new Date().toISOString() }),\n level,\n service,\n message,\n ...data,\n }\n\n if (options.output) {\n options.output(entry)\n } else {\n const formatted = formatEntry(entry)\n switch (level) {\n case 'debug':\n console.debug(formatted)\n break\n case 'info':\n console.info(formatted)\n break\n case 'warn':\n console.warn(formatted)\n break\n case 'error':\n console.error(formatted)\n break\n }\n }\n\n return entry\n }\n\n return {\n debug: (message: string, data?: Record<string, unknown>) => log('debug', message, data),\n info: (message: string, data?: Record<string, unknown>) => log('info', message, data),\n warn: (message: string, data?: Record<string, unknown>) => log('warn', message, data),\n error: (message: string, data?: Record<string, unknown>) => log('error', message, data),\n \n /**\n * Create a child logger with additional context\n */\n child: (context: Record<string, unknown>) => {\n return createLogger(service, {\n ...options,\n output: (entry) => {\n const merged = { ...entry, ...context }\n if (options.output) {\n options.output(merged)\n } else {\n const formatted = pretty ? JSON.stringify(merged, null, 2) : JSON.stringify(merged)\n console[entry.level](formatted)\n }\n },\n })\n },\n }\n}\n\nexport type Logger = ReturnType<typeof createLogger>\n","export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '0.2.0'\nconst DEFAULT_ENDPOINT = 'https://api.openconductor.ai/functions/v1/telemetry'\n\nlet globalTelemetry: Telemetry | null = null\n\n/**\n * Initialize telemetry for your MCP server\n * Call this once at startup with your OpenConductor API key\n */\nexport function initTelemetry(config: TelemetryConfig): Telemetry {\n globalTelemetry = new Telemetry(config)\n return globalTelemetry\n}\n\n/**\n * Get the global telemetry instance (if initialized)\n */\nexport function getTelemetry(): Telemetry | null {\n return globalTelemetry\n}\n\n\nexport class Telemetry {\n private config: Required<Omit<TelemetryConfig, 'serverVersion'>> & Pick<TelemetryConfig, 'serverVersion'>\n private buffer: ToolMetric[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(config: TelemetryConfig) {\n this.config = {\n apiKey: config.apiKey,\n serverName: config.serverName,\n serverVersion: config.serverVersion,\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n batchSize: config.batchSize ?? 10,\n flushInterval: config.flushInterval ?? 30000,\n debug: config.debug ?? false,\n }\n\n // Start periodic flush\n this.flushTimer = setInterval(() => {\n this.flush().catch(this.handleError.bind(this))\n }, this.config.flushInterval)\n\n // Flush on process exit\n if (typeof process !== 'undefined') {\n process.on('beforeExit', () => this.flush())\n process.on('SIGINT', () => {\n this.flush().finally(() => process.exit(0))\n })\n process.on('SIGTERM', () => {\n this.flush().finally(() => process.exit(0))\n })\n }\n\n this.log('Telemetry initialized', { serverName: config.serverName })\n }\n\n /**\n * Track a tool invocation\n */\n trackToolCall(\n tool: string,\n duration: number,\n success: boolean,\n error?: string\n ): void {\n const metric: ToolMetric = {\n tool,\n duration,\n success,\n ...(error && { error }),\n timestamp: new Date().toISOString(),\n }\n\n this.buffer.push(metric)\n this.log('Metric tracked', { ...metric })\n\n // Auto-flush if buffer is full\n if (this.buffer.length >= this.config.batchSize) {\n this.flush().catch(this.handleError.bind(this))\n }\n }\n\n /**\n * Flush buffered metrics to OpenConductor\n */\n async flush(): Promise<void> {\n if (this.buffer.length === 0) return\n\n const metrics = [...this.buffer]\n this.buffer = []\n\n const batch: TelemetryBatch = {\n serverName: this.config.serverName,\n serverVersion: this.config.serverVersion,\n metrics,\n meta: {\n sdkVersion: SDK_VERSION,\n nodeVersion: typeof process !== 'undefined' ? process.version : 'unknown',\n platform: typeof process !== 'undefined' ? process.platform : 'unknown',\n },\n }\n\n this.log('Flushing metrics', { count: metrics.length })\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'X-OpenConductor-SDK': SDK_VERSION,\n },\n body: JSON.stringify(batch),\n })\n\n if (!response.ok) {\n throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`)\n }\n\n this.log('Metrics flushed successfully', { count: metrics.length })\n } catch (error) {\n // Put metrics back in buffer on failure\n this.buffer.unshift(...metrics)\n throw error\n }\n }\n\n /**\n * Stop telemetry collection\n */\n shutdown(): void {\n if (this.flushTimer) {\n clearInterval(this.flushTimer)\n this.flushTimer = null\n }\n this.flush().catch(this.handleError.bind(this))\n this.log('Telemetry shutdown')\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n console.debug(JSON.stringify({\n timestamp: new Date().toISOString(),\n level: 'debug',\n service: 'openconductor-telemetry',\n message,\n ...data,\n }))\n }\n }\n\n private handleError(error: unknown): void {\n if (this.config.debug) {\n console.error('[OpenConductor Telemetry Error]', error)\n }\n }\n}\n","import { MCPError, ToolExecutionError, TimeoutError } from '../errors'\nimport { createLogger, type Logger } from '../logger'\nimport { getTelemetry } from '../telemetry'\n\nexport interface HealthCheckInfo {\n name: string\n version: string\n description?: string\n uptime?: () => number\n checks?: Record<string, () => Promise<boolean> | boolean>\n}\n\nexport interface HealthCheckResponse {\n status: 'healthy' | 'degraded' | 'unhealthy'\n name: string\n version: string\n description?: string\n uptime?: number\n timestamp: string\n checks?: Record<string, boolean>\n}\n\n/**\n * Creates a standard health check response for MCP servers\n */\nexport function createHealthCheck(info: HealthCheckInfo) {\n return async (): Promise<HealthCheckResponse> => {\n const checks: Record<string, boolean> = {}\n let allHealthy = true\n\n if (info.checks) {\n for (const [name, check] of Object.entries(info.checks)) {\n try {\n checks[name] = await check()\n if (!checks[name]) allHealthy = false\n } catch {\n checks[name] = false\n allHealthy = false\n }\n }\n }\n\n return {\n status: allHealthy ? 'healthy' : 'degraded',\n name: info.name,\n version: info.version,\n ...(info.description && { description: info.description }),\n ...(info.uptime && { uptime: info.uptime() }),\n timestamp: new Date().toISOString(),\n ...(Object.keys(checks).length > 0 && { checks }),\n }\n }\n}\n\n\nexport interface WrapToolOptions {\n /** Tool name for logging and telemetry */\n name: string\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number\n /** Custom logger instance */\n logger?: Logger\n /** Enable telemetry reporting (default: true if telemetry initialized) */\n telemetry?: boolean\n}\n\nexport interface ToolContext {\n /** Unique ID for this tool call */\n callId: string\n /** Tool name */\n name: string\n /** Start time of execution */\n startTime: number\n /** Logger scoped to this call */\n log: Logger\n}\n\n/**\n * Wraps a tool handler with automatic error handling, logging, timeouts, and telemetry\n */\nexport function wrapTool<TInput, TOutput>(\n handler: (input: TInput, ctx: ToolContext) => TOutput | Promise<TOutput>,\n options: WrapToolOptions\n): (input: TInput) => Promise<TOutput> {\n const {\n name,\n timeout = 30000,\n telemetry: enableTelemetry = true,\n } = options\n\n const baseLogger = options.logger ?? createLogger(name)\n\n return async (input: TInput): Promise<TOutput> => {\n const callId = generateCallId()\n const startTime = Date.now()\n const log = baseLogger.child({ callId })\n\n const ctx: ToolContext = { callId, name, startTime, log }\n\n log.info('Tool invoked', { tool: name, input: sanitizeInput(input) })\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError(name, timeout))\n }, timeout)\n })\n\n // Race handler against timeout\n const result = await Promise.race([\n Promise.resolve(handler(input, ctx)),\n timeoutPromise,\n ])\n\n const duration = Date.now() - startTime\n log.info('Tool completed', { tool: name, duration })\n\n // Report success to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, true)\n }\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n log.error('Tool failed', { \n tool: name, \n duration, \n error: errorMessage,\n stack: error instanceof Error ? error.stack : undefined,\n })\n\n // Report failure to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, false, errorMessage)\n }\n\n // Re-throw MCPErrors as-is, wrap others\n if (error instanceof MCPError) {\n throw error\n }\n\n throw new ToolExecutionError(\n name,\n errorMessage,\n error instanceof Error ? error : undefined\n )\n }\n }\n}\n\n/**\n * Generates a unique call ID\n */\nfunction generateCallId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n}\n\n/**\n * Sanitizes input for logging (removes sensitive fields)\n */\nfunction sanitizeInput(input: unknown): unknown {\n if (typeof input !== 'object' || input === null) return input\n\n const sensitiveKeys = ['password', 'token', 'secret', 'key', 'auth', 'credential']\n const sanitized: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (sensitiveKeys.some(k => key.toLowerCase().includes(k))) {\n sanitized[key] = '[REDACTED]'\n } else {\n sanitized[key] = value\n }\n }\n\n return sanitized\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/errors/codes.ts","../../src/errors/index.ts","../../src/logger/index.ts","../../src/telemetry/index.ts","../../src/server/index.ts"],"names":[],"mappings":";;;AAIO,IAAM,UAAA,GAAa;AAAA,EAUxB,oBAAA,EAAsB,MAAA;AAAA,EAKtB,aAAA,EAAe,MAIjB,CAAA;;;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,iBAAA,CAAkB,I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K,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAgC,CAAA,EAAG;AAC3E,IAAA,IAAI,aAAA,CAAc,KAAK,CAAA,CAAA,KAAK,GAAA,CAAI,aAAY,CAAE,QAAA,CAAS,CAAC,CAAC,CAAA,EAAG;AAC1D,MAAA,SAAA,CAAU,GAAG,CAAA,GAAI,YAAA;AAAA,IACnB,CAAA,MAAO;AACL,MAAA,SAAA,CAAU,GAAG,CAAA,GAAI,KAAA;AAAA,IACnB;AAAA,EACF;AAEA,EAAA,OAAO,SAAA;AACT","file":"index.js","sourcesContent":["/**\n * JSON-RPC 2.0 Standard Error Codes\n * https://www.jsonrpc.org/specification#error_object\n */\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","export type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport interface LogEntry {\n timestamp?: string\n level: LogLevel\n service: string\n message: string\n [key: string]: unknown\n}\n\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info') */\n level?: LogLevel\n /** Custom output function (default: console methods) */\n output?: (entry: LogEntry) => void\n /** Include timestamps (default: true) */\n timestamps?: boolean\n /** Pretty print JSON (default: false, use true for local dev) */\n pretty?: boolean\n}\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Creates a structured logger for MCP servers\n */\nexport function createLogger(service: string, options: LoggerOptions = {}) {\n const {\n level: minLevel = 'info',\n timestamps = true,\n pretty = false,\n } = options\n\n const shouldLog = (level: LogLevel): boolean => {\n return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[minLevel]\n }\n\n const formatEntry = (entry: LogEntry): string => {\n return pretty ? JSON.stringify(entry, null, 2) : JSON.stringify(entry)\n }\n\n const log = (level: LogLevel, message: string, data?: Record<string, unknown>) => {\n if (!shouldLog(level)) return\n\n const entry: LogEntry = {\n ...(timestamps && { timestamp: new Date().toISOString() }),\n level,\n service,\n message,\n ...data,\n }\n\n if (options.output) {\n options.output(entry)\n } else {\n const formatted = formatEntry(entry)\n switch (level) {\n case 'debug':\n console.debug(formatted)\n break\n case 'info':\n console.info(formatted)\n break\n case 'warn':\n console.warn(formatted)\n break\n case 'error':\n console.error(formatted)\n break\n }\n }\n\n return entry\n }\n\n return {\n debug: (message: string, data?: Record<string, unknown>) => log('debug', message, data),\n info: (message: string, data?: Record<string, unknown>) => log('info', message, data),\n warn: (message: string, data?: Record<string, unknown>) => log('warn', message, data),\n error: (message: string, data?: Record<string, unknown>) => log('error', message, data),\n \n /**\n * Create a child logger with additional context\n */\n child: (context: Record<string, unknown>) => {\n return createLogger(service, {\n ...options,\n output: (entry) => {\n const merged = { ...entry, ...context }\n if (options.output) {\n options.output(merged)\n } else {\n const formatted = pretty ? JSON.stringify(merged, null, 2) : JSON.stringify(merged)\n console[entry.level](formatted)\n }\n },\n })\n },\n }\n}\n\nexport type Logger = ReturnType<typeof createLogger>\n","export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '1.0.0'\nconst DEFAULT_ENDPOINT = 'https://api.openconductor.ai/functions/v1/telemetry'\n\nlet globalTelemetry: Telemetry | null = null\n\n/**\n * Initialize telemetry for your MCP server\n * Call this once at startup with your OpenConductor API key\n */\nexport function initTelemetry(config: TelemetryConfig): Telemetry {\n globalTelemetry = new Telemetry(config)\n return globalTelemetry\n}\n\n/**\n * Get the global telemetry instance (if initialized)\n */\nexport function getTelemetry(): Telemetry | null {\n return globalTelemetry\n}\n\n\nexport class Telemetry {\n private config: Required<Omit<TelemetryConfig, 'serverVersion'>> & Pick<TelemetryConfig, 'serverVersion'>\n private buffer: ToolMetric[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(config: TelemetryConfig) {\n this.config = {\n apiKey: config.apiKey,\n serverName: config.serverName,\n serverVersion: config.serverVersion,\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n batchSize: config.batchSize ?? 10,\n flushInterval: config.flushInterval ?? 30000,\n debug: config.debug ?? false,\n }\n\n // Start periodic flush\n this.flushTimer = setInterval(() => {\n this.flush().catch(this.handleError.bind(this))\n }, this.config.flushInterval)\n\n // Flush on process exit\n if (typeof process !== 'undefined') {\n process.on('beforeExit', () => this.flush())\n process.on('SIGINT', () => {\n this.flush().finally(() => process.exit(0))\n })\n process.on('SIGTERM', () => {\n this.flush().finally(() => process.exit(0))\n })\n }\n\n this.log('Telemetry initialized', { serverName: config.serverName })\n }\n\n /**\n * Track a tool invocation\n */\n trackToolCall(\n tool: string,\n duration: number,\n success: boolean,\n error?: string\n ): void {\n const metric: ToolMetric = {\n tool,\n duration,\n success,\n ...(error && { error }),\n timestamp: new Date().toISOString(),\n }\n\n this.buffer.push(metric)\n this.log('Metric tracked', { ...metric })\n\n // Auto-flush if buffer is full\n if (this.buffer.length >= this.config.batchSize) {\n this.flush().catch(this.handleError.bind(this))\n }\n }\n\n /**\n * Flush buffered metrics to OpenConductor\n */\n async flush(): Promise<void> {\n if (this.buffer.length === 0) return\n\n const metrics = [...this.buffer]\n this.buffer = []\n\n const batch: TelemetryBatch = {\n serverName: this.config.serverName,\n serverVersion: this.config.serverVersion,\n metrics,\n meta: {\n sdkVersion: SDK_VERSION,\n nodeVersion: typeof process !== 'undefined' ? process.version : 'unknown',\n platform: typeof process !== 'undefined' ? process.platform : 'unknown',\n },\n }\n\n this.log('Flushing metrics', { count: metrics.length })\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'X-OpenConductor-SDK': SDK_VERSION,\n },\n body: JSON.stringify(batch),\n })\n\n if (!response.ok) {\n throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`)\n }\n\n this.log('Metrics flushed successfully', { count: metrics.length })\n } catch (error) {\n // Put metrics back in buffer on failure\n this.buffer.unshift(...metrics)\n throw error\n }\n }\n\n /**\n * Stop telemetry collection\n */\n shutdown(): void {\n if (this.flushTimer) {\n clearInterval(this.flushTimer)\n this.flushTimer = null\n }\n this.flush().catch(this.handleError.bind(this))\n this.log('Telemetry shutdown')\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n console.debug(JSON.stringify({\n timestamp: new Date().toISOString(),\n level: 'debug',\n service: 'openconductor-telemetry',\n message,\n ...data,\n }))\n }\n }\n\n private handleError(error: unknown): void {\n if (this.config.debug) {\n console.error('[OpenConductor Telemetry Error]', error)\n }\n }\n}\n","import { MCPError, ToolExecutionError, TimeoutError } from '../errors'\nimport { createLogger, type Logger } from '../logger'\nimport { getTelemetry } from '../telemetry'\n\nexport interface HealthCheckInfo {\n name: string\n version: string\n description?: string\n uptime?: () => number\n checks?: Record<string, () => Promise<boolean> | boolean>\n}\n\nexport interface HealthCheckResponse {\n status: 'healthy' | 'degraded' | 'unhealthy'\n name: string\n version: string\n description?: string\n uptime?: number\n timestamp: string\n checks?: Record<string, boolean>\n}\n\n/**\n * Creates a standard health check response for MCP servers\n */\nexport function createHealthCheck(info: HealthCheckInfo) {\n return async (): Promise<HealthCheckResponse> => {\n const checks: Record<string, boolean> = {}\n let allHealthy = true\n\n if (info.checks) {\n for (const [name, check] of Object.entries(info.checks)) {\n try {\n checks[name] = await check()\n if (!checks[name]) allHealthy = false\n } catch {\n checks[name] = false\n allHealthy = false\n }\n }\n }\n\n return {\n status: allHealthy ? 'healthy' : 'degraded',\n name: info.name,\n version: info.version,\n ...(info.description && { description: info.description }),\n ...(info.uptime && { uptime: info.uptime() }),\n timestamp: new Date().toISOString(),\n ...(Object.keys(checks).length > 0 && { checks }),\n }\n }\n}\n\n\nexport interface WrapToolOptions {\n /** Tool name for logging and telemetry */\n name: string\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number\n /** Custom logger instance */\n logger?: Logger\n /** Enable telemetry reporting (default: true if telemetry initialized) */\n telemetry?: boolean\n}\n\nexport interface ToolContext {\n /** Unique ID for this tool call */\n callId: string\n /** Tool name */\n name: string\n /** Start time of execution */\n startTime: number\n /** Logger scoped to this call */\n log: Logger\n}\n\n/**\n * Wraps a tool handler with automatic error handling, logging, timeouts, and telemetry\n */\nexport function wrapTool<TInput, TOutput>(\n handler: (input: TInput, ctx: ToolContext) => TOutput | Promise<TOutput>,\n options: WrapToolOptions\n): (input: TInput) => Promise<TOutput> {\n const {\n name,\n timeout = 30000,\n telemetry: enableTelemetry = true,\n } = options\n\n const baseLogger = options.logger ?? createLogger(name)\n\n return async (input: TInput): Promise<TOutput> => {\n const callId = generateCallId()\n const startTime = Date.now()\n const log = baseLogger.child({ callId })\n\n const ctx: ToolContext = { callId, name, startTime, log }\n\n log.info('Tool invoked', { tool: name, input: sanitizeInput(input) })\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError(name, timeout))\n }, timeout)\n })\n\n // Race handler against timeout\n const result = await Promise.race([\n Promise.resolve(handler(input, ctx)),\n timeoutPromise,\n ])\n\n const duration = Date.now() - startTime\n log.info('Tool completed', { tool: name, duration })\n\n // Report success to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, true)\n }\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n log.error('Tool failed', { \n tool: name, \n duration, \n error: errorMessage,\n stack: error instanceof Error ? error.stack : undefined,\n })\n\n // Report failure to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, false, errorMessage)\n }\n\n // Re-throw MCPErrors as-is, wrap others\n if (error instanceof MCPError) {\n throw error\n }\n\n throw new ToolExecutionError(\n name,\n errorMessage,\n error instanceof Error ? error : undefined\n )\n }\n }\n}\n\n/**\n * Generates a unique call ID\n */\nfunction generateCallId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n}\n\n/**\n * Sanitizes input for logging (removes sensitive fields)\n */\nfunction sanitizeInput(input: unknown): unknown {\n if (typeof input !== 'object' || input === null) return input\n\n const sensitiveKeys = ['password', 'token', 'secret', 'key', 'auth', 'credential']\n const sanitized: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (sensitiveKeys.some(k => key.toLowerCase().includes(k))) {\n sanitized[key] = '[REDACTED]'\n } else {\n sanitized[key] = value\n }\n }\n\n return sanitized\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors/codes.ts","../../src/errors/index.ts","../../src/logger/index.ts","../../src/telemetry/index.ts","../../src/server/index.ts"],"names":[],"mappings":";AAIO,IAAM,UAAA,GAAa;AAAA,EAUxB,oBAAA,EAAsB,MAAA;AAAA,EAKtB,aAAA,EAAe,MAIjB,CAAA;;;ACfO,IAAM,QAAA,GAAN,cAAuB,KAAA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,KAAA,CAAM,CAAA,EAAG,CAAC,CAAC,CAAA,CAAA;AAC7E;AAKA,SAAS,cAAc,KAAA,EAAyB;AAC9C,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,MAAM,OAAO,KAAA;AAExD,EAAA,MAAM,gBAAgB,CAAC,UAAA,EAAY,SAAS,QAAA,EAAU,KAAA,EAAO,QAAQ,YAAY,CAAA;AACjF,EAAA,MAAM,YAAqC,EAAC;AAE5C,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAgC,CAAA,EAAG;AAC3E,IAAA,IAAI,aAAA,CAAc,KAAK,CAAA,CAAA,KAAK,GAAA,CAAI,aAAY,CAAE,QAAA,CAAS,CAAC,CAAC,CAAA,EAAG;AAC1D,MAAA,SAAA,CAAU,GAAG,CAAA,GAAI,YAAA;AAAA,IACnB,CAAA,MAAO;AACL,MAAA,SAAA,CAAU,GAAG,CAAA,GAAI,KAAA;AAAA,IACnB;AAAA,EACF;AAEA,EAAA,OAAO,SAAA;AACT","file":"index.mjs","sourcesContent":["/**\n * JSON-RPC 2.0 Standard Error Codes\n * https://www.jsonrpc.org/specification#error_object\n */\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","export type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport interface LogEntry {\n timestamp?: string\n level: LogLevel\n service: string\n message: string\n [key: string]: unknown\n}\n\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info') */\n level?: LogLevel\n /** Custom output function (default: console methods) */\n output?: (entry: LogEntry) => void\n /** Include timestamps (default: true) */\n timestamps?: boolean\n /** Pretty print JSON (default: false, use true for local dev) */\n pretty?: boolean\n}\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Creates a structured logger for MCP servers\n */\nexport function createLogger(service: string, options: LoggerOptions = {}) {\n const {\n level: minLevel = 'info',\n timestamps = true,\n pretty = false,\n } = options\n\n const shouldLog = (level: LogLevel): boolean => {\n return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[minLevel]\n }\n\n const formatEntry = (entry: LogEntry): string => {\n return pretty ? JSON.stringify(entry, null, 2) : JSON.stringify(entry)\n }\n\n const log = (level: LogLevel, message: string, data?: Record<string, unknown>) => {\n if (!shouldLog(level)) return\n\n const entry: LogEntry = {\n ...(timestamps && { timestamp: new Date().toISOString() }),\n level,\n service,\n message,\n ...data,\n }\n\n if (options.output) {\n options.output(entry)\n } else {\n const formatted = formatEntry(entry)\n switch (level) {\n case 'debug':\n console.debug(formatted)\n break\n case 'info':\n console.info(formatted)\n break\n case 'warn':\n console.warn(formatted)\n break\n case 'error':\n console.error(formatted)\n break\n }\n }\n\n return entry\n }\n\n return {\n debug: (message: string, data?: Record<string, unknown>) => log('debug', message, data),\n info: (message: string, data?: Record<string, unknown>) => log('info', message, data),\n warn: (message: string, data?: Record<string, unknown>) => log('warn', message, data),\n error: (message: string, data?: Record<string, unknown>) => log('error', message, data),\n \n /**\n * Create a child logger with additional context\n */\n child: (context: Record<string, unknown>) => {\n return createLogger(service, {\n ...options,\n output: (entry) => {\n const merged = { ...entry, ...context }\n if (options.output) {\n options.output(merged)\n } else {\n const formatted = pretty ? JSON.stringify(merged, null, 2) : JSON.stringify(merged)\n console[entry.level](formatted)\n }\n },\n })\n },\n }\n}\n\nexport type Logger = ReturnType<typeof createLogger>\n","export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '0.2.0'\nconst DEFAULT_ENDPOINT = 'https://api.openconductor.ai/functions/v1/telemetry'\n\nlet globalTelemetry: Telemetry | null = null\n\n/**\n * Initialize telemetry for your MCP server\n * Call this once at startup with your OpenConductor API key\n */\nexport function initTelemetry(config: TelemetryConfig): Telemetry {\n globalTelemetry = new Telemetry(config)\n return globalTelemetry\n}\n\n/**\n * Get the global telemetry instance (if initialized)\n */\nexport function getTelemetry(): Telemetry | null {\n return globalTelemetry\n}\n\n\nexport class Telemetry {\n private config: Required<Omit<TelemetryConfig, 'serverVersion'>> & Pick<TelemetryConfig, 'serverVersion'>\n private buffer: ToolMetric[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(config: TelemetryConfig) {\n this.config = {\n apiKey: config.apiKey,\n serverName: config.serverName,\n serverVersion: config.serverVersion,\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n batchSize: config.batchSize ?? 10,\n flushInterval: config.flushInterval ?? 30000,\n debug: config.debug ?? false,\n }\n\n // Start periodic flush\n this.flushTimer = setInterval(() => {\n this.flush().catch(this.handleError.bind(this))\n }, this.config.flushInterval)\n\n // Flush on process exit\n if (typeof process !== 'undefined') {\n process.on('beforeExit', () => this.flush())\n process.on('SIGINT', () => {\n this.flush().finally(() => process.exit(0))\n })\n process.on('SIGTERM', () => {\n this.flush().finally(() => process.exit(0))\n })\n }\n\n this.log('Telemetry initialized', { serverName: config.serverName })\n }\n\n /**\n * Track a tool invocation\n */\n trackToolCall(\n tool: string,\n duration: number,\n success: boolean,\n error?: string\n ): void {\n const metric: ToolMetric = {\n tool,\n duration,\n success,\n ...(error && { error }),\n timestamp: new Date().toISOString(),\n }\n\n this.buffer.push(metric)\n this.log('Metric tracked', { ...metric })\n\n // Auto-flush if buffer is full\n if (this.buffer.length >= this.config.batchSize) {\n this.flush().catch(this.handleError.bind(this))\n }\n }\n\n /**\n * Flush buffered metrics to OpenConductor\n */\n async flush(): Promise<void> {\n if (this.buffer.length === 0) return\n\n const metrics = [...this.buffer]\n this.buffer = []\n\n const batch: TelemetryBatch = {\n serverName: this.config.serverName,\n serverVersion: this.config.serverVersion,\n metrics,\n meta: {\n sdkVersion: SDK_VERSION,\n nodeVersion: typeof process !== 'undefined' ? process.version : 'unknown',\n platform: typeof process !== 'undefined' ? process.platform : 'unknown',\n },\n }\n\n this.log('Flushing metrics', { count: metrics.length })\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'X-OpenConductor-SDK': SDK_VERSION,\n },\n body: JSON.stringify(batch),\n })\n\n if (!response.ok) {\n throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`)\n }\n\n this.log('Metrics flushed successfully', { count: metrics.length })\n } catch (error) {\n // Put metrics back in buffer on failure\n this.buffer.unshift(...metrics)\n throw error\n }\n }\n\n /**\n * Stop telemetry collection\n */\n shutdown(): void {\n if (this.flushTimer) {\n clearInterval(this.flushTimer)\n this.flushTimer = null\n }\n this.flush().catch(this.handleError.bind(this))\n this.log('Telemetry shutdown')\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n console.debug(JSON.stringify({\n timestamp: new Date().toISOString(),\n level: 'debug',\n service: 'openconductor-telemetry',\n message,\n ...data,\n }))\n }\n }\n\n private handleError(error: unknown): void {\n if (this.config.debug) {\n console.error('[OpenConductor Telemetry Error]', error)\n }\n }\n}\n","import { MCPError, ToolExecutionError, TimeoutError } from '../errors'\nimport { createLogger, type Logger } from '../logger'\nimport { getTelemetry } from '../telemetry'\n\nexport interface HealthCheckInfo {\n name: string\n version: string\n description?: string\n uptime?: () => number\n checks?: Record<string, () => Promise<boolean> | boolean>\n}\n\nexport interface HealthCheckResponse {\n status: 'healthy' | 'degraded' | 'unhealthy'\n name: string\n version: string\n description?: string\n uptime?: number\n timestamp: string\n checks?: Record<string, boolean>\n}\n\n/**\n * Creates a standard health check response for MCP servers\n */\nexport function createHealthCheck(info: HealthCheckInfo) {\n return async (): Promise<HealthCheckResponse> => {\n const checks: Record<string, boolean> = {}\n let allHealthy = true\n\n if (info.checks) {\n for (const [name, check] of Object.entries(info.checks)) {\n try {\n checks[name] = await check()\n if (!checks[name]) allHealthy = false\n } catch {\n checks[name] = false\n allHealthy = false\n }\n }\n }\n\n return {\n status: allHealthy ? 'healthy' : 'degraded',\n name: info.name,\n version: info.version,\n ...(info.description && { description: info.description }),\n ...(info.uptime && { uptime: info.uptime() }),\n timestamp: new Date().toISOString(),\n ...(Object.keys(checks).length > 0 && { checks }),\n }\n }\n}\n\n\nexport interface WrapToolOptions {\n /** Tool name for logging and telemetry */\n name: string\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number\n /** Custom logger instance */\n logger?: Logger\n /** Enable telemetry reporting (default: true if telemetry initialized) */\n telemetry?: boolean\n}\n\nexport interface ToolContext {\n /** Unique ID for this tool call */\n callId: string\n /** Tool name */\n name: string\n /** Start time of execution */\n startTime: number\n /** Logger scoped to this call */\n log: Logger\n}\n\n/**\n * Wraps a tool handler with automatic error handling, logging, timeouts, and telemetry\n */\nexport function wrapTool<TInput, TOutput>(\n handler: (input: TInput, ctx: ToolContext) => TOutput | Promise<TOutput>,\n options: WrapToolOptions\n): (input: TInput) => Promise<TOutput> {\n const {\n name,\n timeout = 30000,\n telemetry: enableTelemetry = true,\n } = options\n\n const baseLogger = options.logger ?? createLogger(name)\n\n return async (input: TInput): Promise<TOutput> => {\n const callId = generateCallId()\n const startTime = Date.now()\n const log = baseLogger.child({ callId })\n\n const ctx: ToolContext = { callId, name, startTime, log }\n\n log.info('Tool invoked', { tool: name, input: sanitizeInput(input) })\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError(name, timeout))\n }, timeout)\n })\n\n // Race handler against timeout\n const result = await Promise.race([\n Promise.resolve(handler(input, ctx)),\n timeoutPromise,\n ])\n\n const duration = Date.now() - startTime\n log.info('Tool completed', { tool: name, duration })\n\n // Report success to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, true)\n }\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n log.error('Tool failed', { \n tool: name, \n duration, \n error: errorMessage,\n stack: error instanceof Error ? error.stack : undefined,\n })\n\n // Report failure to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, false, errorMessage)\n }\n\n // Re-throw MCPErrors as-is, wrap others\n if (error instanceof MCPError) {\n throw error\n }\n\n throw new ToolExecutionError(\n name,\n errorMessage,\n error instanceof Error ? error : undefined\n )\n }\n }\n}\n\n/**\n * Generates a unique call ID\n */\nfunction generateCallId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n}\n\n/**\n * Sanitizes input for logging (removes sensitive fields)\n */\nfunction sanitizeInput(input: unknown): unknown {\n if (typeof input !== 'object' || input === null) return input\n\n const sensitiveKeys = ['password', 'token', 'secret', 'key', 'auth', 'credential']\n const sanitized: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (sensitiveKeys.some(k => key.toLowerCase().includes(k))) {\n sanitized[key] = '[REDACTED]'\n } else {\n sanitized[key] = value\n }\n }\n\n return sanitized\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/errors/codes.ts","../../src/errors/index.ts","../../src/logger/index.ts","../../src/telemetry/index.ts","../../src/server/index.ts"],"names":[],"mappings":";AAIO,IAAM,UAAA,GAAa;AAAA,EAUxB,oBAAA,EAAsB,MAAA;AAAA,EAKtB,aAAA,EAAe,MAIjB,CAAA;;;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,iBAAA,CAAkB,IAAA,EAAM,IAAA,CAAK,WAAW,CAAA;AAAA,IAChD;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,MAAA,GAAS;AACP,IAAA,OAAO;AAAA,MACL,MAAM,IAAA,CAAK,IAAA;AAAA,MACX,SAAS,IAAA,CAAK,OAAA;AAAA,MACd,GAAI,IAAA,CAAK,IAAA,IAAQ,EAAE,IAAA,EAAM,KAAK,IAAA;AAAK,KACrC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,UAAA,CAAW,KAA6B,IAAA,EAAM;AAC5C,IAAA,OAAO;AAAA,MACL,OAAA,EAAS,KAAA;AAAA,MACT,EAAA;AAAA,MACA,KAAA,EAAO,KAAK,MAAA;AAAO,KACrB;AAAA,EACF;AACF,CAAA;AA+BO,IAAM,kBAAA,GAAN,cAAiC,QAAA,CAAS;AAAA,EAC/C,WAAA,CAAY,QAAA,EAAkB,MAAA,EAAgB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EA,MAAA,MAAM,IAAI,kBAAA;AAAA,QACR,IAAA;AAAA,QACA,YAAA;AAAA,QACA,KAAA,YAAiB,QAAQ,KAAA,GAAQ;AAAA,OACnC;AAAA,IACF;AAAA,EACF,CAAA;AACF;AAKA,SAAS,cAAA,GAAyB;AAChC,EAAA,OAAO,GAAG,IAAA,CAAK,GAAA,EAAI,CAAE,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA,EAAI,IAAA,CAAK,MAAA,GAAS,QAAA,CAAS,EAAE,EAAE,KAAA,CAAM,CAAA,EAAG,CAAC,CAAC,CAAA,CAAA;AAC7E;AAKA,SAAS,cAAc,KAAA,EAAyB;AAC9C,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,MAAM,OAAO,KAAA;AAExD,EAAA,MAAM,gBAAgB,CAAC,UAAA,EAAY,SAAS,QAAA,EAAU,KAAA,EAAO,QAAQ,YAAY,CAAA;AACjF,EAAA,MAAM,YAAqC,EAAC;AAE5C,EAAA,KAAA,MAAW,CAAC,GAAA,EAAK,KAAK,KAAK,MAAA,CAAO,OAAA,CAAQ,KAAgC,CAAA,EAAG;AAC3E,IAAA,IAAI,aAAA,CAAc,KAAK,CAAA,CAAA,KAAK,GAAA,CAAI,aAAY,CAAE,QAAA,CAAS,CAAC,CAAC,CAAA,EAAG;AAC1D,MAAA,SAAA,CAAU,GAAG,CAAA,GAAI,YAAA;AAAA,IACnB,CAAA,MAAO;AACL,MAAA,SAAA,CAAU,GAAG,CAAA,GAAI,KAAA;AAAA,IACnB;AAAA,EACF;AAEA,EAAA,OAAO,SAAA;AACT","file":"index.mjs","sourcesContent":["/**\n * JSON-RPC 2.0 Standard Error Codes\n * https://www.jsonrpc.org/specification#error_object\n */\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","export type LogLevel = 'debug' | 'info' | 'warn' | 'error'\n\nexport interface LogEntry {\n timestamp?: string\n level: LogLevel\n service: string\n message: string\n [key: string]: unknown\n}\n\nexport interface LoggerOptions {\n /** Minimum log level to output (default: 'info') */\n level?: LogLevel\n /** Custom output function (default: console methods) */\n output?: (entry: LogEntry) => void\n /** Include timestamps (default: true) */\n timestamps?: boolean\n /** Pretty print JSON (default: false, use true for local dev) */\n pretty?: boolean\n}\n\nconst LEVEL_PRIORITY: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n}\n\n/**\n * Creates a structured logger for MCP servers\n */\nexport function createLogger(service: string, options: LoggerOptions = {}) {\n const {\n level: minLevel = 'info',\n timestamps = true,\n pretty = false,\n } = options\n\n const shouldLog = (level: LogLevel): boolean => {\n return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[minLevel]\n }\n\n const formatEntry = (entry: LogEntry): string => {\n return pretty ? JSON.stringify(entry, null, 2) : JSON.stringify(entry)\n }\n\n const log = (level: LogLevel, message: string, data?: Record<string, unknown>) => {\n if (!shouldLog(level)) return\n\n const entry: LogEntry = {\n ...(timestamps && { timestamp: new Date().toISOString() }),\n level,\n service,\n message,\n ...data,\n }\n\n if (options.output) {\n options.output(entry)\n } else {\n const formatted = formatEntry(entry)\n switch (level) {\n case 'debug':\n console.debug(formatted)\n break\n case 'info':\n console.info(formatted)\n break\n case 'warn':\n console.warn(formatted)\n break\n case 'error':\n console.error(formatted)\n break\n }\n }\n\n return entry\n }\n\n return {\n debug: (message: string, data?: Record<string, unknown>) => log('debug', message, data),\n info: (message: string, data?: Record<string, unknown>) => log('info', message, data),\n warn: (message: string, data?: Record<string, unknown>) => log('warn', message, data),\n error: (message: string, data?: Record<string, unknown>) => log('error', message, data),\n \n /**\n * Create a child logger with additional context\n */\n child: (context: Record<string, unknown>) => {\n return createLogger(service, {\n ...options,\n output: (entry) => {\n const merged = { ...entry, ...context }\n if (options.output) {\n options.output(merged)\n } else {\n const formatted = pretty ? JSON.stringify(merged, null, 2) : JSON.stringify(merged)\n console[entry.level](formatted)\n }\n },\n })\n },\n }\n}\n\nexport type Logger = ReturnType<typeof createLogger>\n","export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '1.0.0'\nconst DEFAULT_ENDPOINT = 'https://api.openconductor.ai/functions/v1/telemetry'\n\nlet globalTelemetry: Telemetry | null = null\n\n/**\n * Initialize telemetry for your MCP server\n * Call this once at startup with your OpenConductor API key\n */\nexport function initTelemetry(config: TelemetryConfig): Telemetry {\n globalTelemetry = new Telemetry(config)\n return globalTelemetry\n}\n\n/**\n * Get the global telemetry instance (if initialized)\n */\nexport function getTelemetry(): Telemetry | null {\n return globalTelemetry\n}\n\n\nexport class Telemetry {\n private config: Required<Omit<TelemetryConfig, 'serverVersion'>> & Pick<TelemetryConfig, 'serverVersion'>\n private buffer: ToolMetric[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(config: TelemetryConfig) {\n this.config = {\n apiKey: config.apiKey,\n serverName: config.serverName,\n serverVersion: config.serverVersion,\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n batchSize: config.batchSize ?? 10,\n flushInterval: config.flushInterval ?? 30000,\n debug: config.debug ?? false,\n }\n\n // Start periodic flush\n this.flushTimer = setInterval(() => {\n this.flush().catch(this.handleError.bind(this))\n }, this.config.flushInterval)\n\n // Flush on process exit\n if (typeof process !== 'undefined') {\n process.on('beforeExit', () => this.flush())\n process.on('SIGINT', () => {\n this.flush().finally(() => process.exit(0))\n })\n process.on('SIGTERM', () => {\n this.flush().finally(() => process.exit(0))\n })\n }\n\n this.log('Telemetry initialized', { serverName: config.serverName })\n }\n\n /**\n * Track a tool invocation\n */\n trackToolCall(\n tool: string,\n duration: number,\n success: boolean,\n error?: string\n ): void {\n const metric: ToolMetric = {\n tool,\n duration,\n success,\n ...(error && { error }),\n timestamp: new Date().toISOString(),\n }\n\n this.buffer.push(metric)\n this.log('Metric tracked', { ...metric })\n\n // Auto-flush if buffer is full\n if (this.buffer.length >= this.config.batchSize) {\n this.flush().catch(this.handleError.bind(this))\n }\n }\n\n /**\n * Flush buffered metrics to OpenConductor\n */\n async flush(): Promise<void> {\n if (this.buffer.length === 0) return\n\n const metrics = [...this.buffer]\n this.buffer = []\n\n const batch: TelemetryBatch = {\n serverName: this.config.serverName,\n serverVersion: this.config.serverVersion,\n metrics,\n meta: {\n sdkVersion: SDK_VERSION,\n nodeVersion: typeof process !== 'undefined' ? process.version : 'unknown',\n platform: typeof process !== 'undefined' ? process.platform : 'unknown',\n },\n }\n\n this.log('Flushing metrics', { count: metrics.length })\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'X-OpenConductor-SDK': SDK_VERSION,\n },\n body: JSON.stringify(batch),\n })\n\n if (!response.ok) {\n throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`)\n }\n\n this.log('Metrics flushed successfully', { count: metrics.length })\n } catch (error) {\n // Put metrics back in buffer on failure\n this.buffer.unshift(...metrics)\n throw error\n }\n }\n\n /**\n * Stop telemetry collection\n */\n shutdown(): void {\n if (this.flushTimer) {\n clearInterval(this.flushTimer)\n this.flushTimer = null\n }\n this.flush().catch(this.handleError.bind(this))\n this.log('Telemetry shutdown')\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n console.debug(JSON.stringify({\n timestamp: new Date().toISOString(),\n level: 'debug',\n service: 'openconductor-telemetry',\n message,\n ...data,\n }))\n }\n }\n\n private handleError(error: unknown): void {\n if (this.config.debug) {\n console.error('[OpenConductor Telemetry Error]', error)\n }\n }\n}\n","import { MCPError, ToolExecutionError, TimeoutError } from '../errors'\nimport { createLogger, type Logger } from '../logger'\nimport { getTelemetry } from '../telemetry'\n\nexport interface HealthCheckInfo {\n name: string\n version: string\n description?: string\n uptime?: () => number\n checks?: Record<string, () => Promise<boolean> | boolean>\n}\n\nexport interface HealthCheckResponse {\n status: 'healthy' | 'degraded' | 'unhealthy'\n name: string\n version: string\n description?: string\n uptime?: number\n timestamp: string\n checks?: Record<string, boolean>\n}\n\n/**\n * Creates a standard health check response for MCP servers\n */\nexport function createHealthCheck(info: HealthCheckInfo) {\n return async (): Promise<HealthCheckResponse> => {\n const checks: Record<string, boolean> = {}\n let allHealthy = true\n\n if (info.checks) {\n for (const [name, check] of Object.entries(info.checks)) {\n try {\n checks[name] = await check()\n if (!checks[name]) allHealthy = false\n } catch {\n checks[name] = false\n allHealthy = false\n }\n }\n }\n\n return {\n status: allHealthy ? 'healthy' : 'degraded',\n name: info.name,\n version: info.version,\n ...(info.description && { description: info.description }),\n ...(info.uptime && { uptime: info.uptime() }),\n timestamp: new Date().toISOString(),\n ...(Object.keys(checks).length > 0 && { checks }),\n }\n }\n}\n\n\nexport interface WrapToolOptions {\n /** Tool name for logging and telemetry */\n name: string\n /** Timeout in milliseconds (default: 30000) */\n timeout?: number\n /** Custom logger instance */\n logger?: Logger\n /** Enable telemetry reporting (default: true if telemetry initialized) */\n telemetry?: boolean\n}\n\nexport interface ToolContext {\n /** Unique ID for this tool call */\n callId: string\n /** Tool name */\n name: string\n /** Start time of execution */\n startTime: number\n /** Logger scoped to this call */\n log: Logger\n}\n\n/**\n * Wraps a tool handler with automatic error handling, logging, timeouts, and telemetry\n */\nexport function wrapTool<TInput, TOutput>(\n handler: (input: TInput, ctx: ToolContext) => TOutput | Promise<TOutput>,\n options: WrapToolOptions\n): (input: TInput) => Promise<TOutput> {\n const {\n name,\n timeout = 30000,\n telemetry: enableTelemetry = true,\n } = options\n\n const baseLogger = options.logger ?? createLogger(name)\n\n return async (input: TInput): Promise<TOutput> => {\n const callId = generateCallId()\n const startTime = Date.now()\n const log = baseLogger.child({ callId })\n\n const ctx: ToolContext = { callId, name, startTime, log }\n\n log.info('Tool invoked', { tool: name, input: sanitizeInput(input) })\n\n try {\n // Create timeout promise\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(new TimeoutError(name, timeout))\n }, timeout)\n })\n\n // Race handler against timeout\n const result = await Promise.race([\n Promise.resolve(handler(input, ctx)),\n timeoutPromise,\n ])\n\n const duration = Date.now() - startTime\n log.info('Tool completed', { tool: name, duration })\n\n // Report success to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, true)\n }\n\n return result\n } catch (error) {\n const duration = Date.now() - startTime\n const errorMessage = error instanceof Error ? error.message : String(error)\n\n log.error('Tool failed', { \n tool: name, \n duration, \n error: errorMessage,\n stack: error instanceof Error ? error.stack : undefined,\n })\n\n // Report failure to telemetry\n if (enableTelemetry) {\n const tel = getTelemetry()\n tel?.trackToolCall(name, duration, false, errorMessage)\n }\n\n // Re-throw MCPErrors as-is, wrap others\n if (error instanceof MCPError) {\n throw error\n }\n\n throw new ToolExecutionError(\n name,\n errorMessage,\n error instanceof Error ? error : undefined\n )\n }\n }\n}\n\n/**\n * Generates a unique call ID\n */\nfunction generateCallId(): string {\n return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`\n}\n\n/**\n * Sanitizes input for logging (removes sensitive fields)\n */\nfunction sanitizeInput(input: unknown): unknown {\n if (typeof input !== 'object' || input === null) return input\n\n const sensitiveKeys = ['password', 'token', 'secret', 'key', 'auth', 'credential']\n const sanitized: Record<string, unknown> = {}\n\n for (const [key, value] of Object.entries(input as Record<string, unknown>)) {\n if (sensitiveKeys.some(k => key.toLowerCase().includes(k))) {\n sanitized[key] = '[REDACTED]'\n } else {\n sanitized[key] = value\n }\n }\n\n return sanitized\n}\n"]}
|
package/dist/telemetry/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/telemetry/index.ts"],"names":[],"mappings":";;;AAoCA,IAAM,WAAA,GAAc,OAAA;AACpB,IAAM,gBAAA,GAAmB,qDAAA;AAEzB,IAAI,eAAA,GAAoC,IAAA;AAMjC,SAAS,cAAc,MAAA,EAAoC;AAChE,EAAA,eAAA,GAAkB,IAAI,UAAU,MAAM,CAAA;AACtC,EAAA,OAAO,eAAA;AACT;AAKO,SAAS,YAAA,GAAiC;AAC/C,EAAA,OAAO,eAAA;AACT;AAGO,IAAM,YAAN,MAAgB;AAAA,EACb,MAAA;AAAA,EACA,SAAuB,EAAC;AAAA,EACxB,UAAA,GAAoD,IAAA;AAAA,EAE5D,YAAY,MAAA,EAAyB;AACnC,IAAA,IAAA,CAAK,MAAA,GAAS;AAAA,MACZ,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,YAAY,MAAA,CAAO,UAAA;AAAA,MACnB,eAAe,MAAA,CAAO,aAAA;AAAA,MACtB,QAAA,EAAU,OAAO,QAAA,IAAY,gBAAA;AAAA,MAC7B,SAAA,EAAW,OAAO,SAAA,IAAa,EAAA;AAAA,MAC/B,aAAA,EAAe,OAAO,aAAA,IAAiB,GAAA;AAAA,MACvC,KAAA,EAAO,OAAO,KAAA,IAAS;AAAA,K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AAK,CAAA;AAAA,IACxD;AAAA,EACF;AACF","file":"index.js","sourcesContent":["export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '0.
|
|
1
|
+
{"version":3,"sources":["../../src/telemetry/index.ts"],"names":[],"mappings":";;;AAoCA,IAAM,WAAA,GAAc,OAAA;AACpB,IAAM,gBAAA,GAAmB,qDAAA;AAEzB,IAAI,eAAA,GAAoC,IAAA;AAMjC,SAAS,cAAc,MAAA,EAAoC;AAChE,EAAA,eAAA,GAAkB,IAAI,UAAU,MAAM,CAAA;AACtC,EAAA,OAAO,eAAA;AACT;AAKO,SAAS,YAAA,GAAiC;AAC/C,EAAA,OAAO,eAAA;AACT;AAGO,IAAM,YAAN,MAAgB;AAAA,EACb,MAAA;AAAA,EACA,SAAuB,EAAC;AAAA,EACxB,UAAA,GAAoD,IAAA;AAAA,EAE5D,YAAY,MAAA,EAAyB;AACnC,IAAA,IAAA,CAAK,MAAA,GAAS;AAAA,MACZ,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,YAAY,MAAA,CAAO,UAAA;AAAA,MACnB,eAAe,MAAA,CAAO,aAAA;AAAA,MACtB,QAAA,EAAU,OAAO,QAAA,IAAY,gBAAA;AAAA,MAC7B,SAAA,EAAW,OAAO,SAAA,IAAa,EAAA;AAAA,MAC/B,aAAA,EAAe,OAAO,aAAA,IAAiB,GAAA;AAAA,MACvC,K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,OAAA,CAAQ,KAAA,CAAM,mCAAmC,KAAK,CAAA;AAAA,IACxD;AAAA,EACF;AACF","file":"index.js","sourcesContent":["export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '1.0.0'\nconst DEFAULT_ENDPOINT = 'https://api.openconductor.ai/functions/v1/telemetry'\n\nlet globalTelemetry: Telemetry | null = null\n\n/**\n * Initialize telemetry for your MCP server\n * Call this once at startup with your OpenConductor API key\n */\nexport function initTelemetry(config: TelemetryConfig): Telemetry {\n globalTelemetry = new Telemetry(config)\n return globalTelemetry\n}\n\n/**\n * Get the global telemetry instance (if initialized)\n */\nexport function getTelemetry(): Telemetry | null {\n return globalTelemetry\n}\n\n\nexport class Telemetry {\n private config: Required<Omit<TelemetryConfig, 'serverVersion'>> & Pick<TelemetryConfig, 'serverVersion'>\n private buffer: ToolMetric[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(config: TelemetryConfig) {\n this.config = {\n apiKey: config.apiKey,\n serverName: config.serverName,\n serverVersion: config.serverVersion,\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n batchSize: config.batchSize ?? 10,\n flushInterval: config.flushInterval ?? 30000,\n debug: config.debug ?? false,\n }\n\n // Start periodic flush\n this.flushTimer = setInterval(() => {\n this.flush().catch(this.handleError.bind(this))\n }, this.config.flushInterval)\n\n // Flush on process exit\n if (typeof process !== 'undefined') {\n process.on('beforeExit', () => this.flush())\n process.on('SIGINT', () => {\n this.flush().finally(() => process.exit(0))\n })\n process.on('SIGTERM', () => {\n this.flush().finally(() => process.exit(0))\n })\n }\n\n this.log('Telemetry initialized', { serverName: config.serverName })\n }\n\n /**\n * Track a tool invocation\n */\n trackToolCall(\n tool: string,\n duration: number,\n success: boolean,\n error?: string\n ): void {\n const metric: ToolMetric = {\n tool,\n duration,\n success,\n ...(error && { error }),\n timestamp: new Date().toISOString(),\n }\n\n this.buffer.push(metric)\n this.log('Metric tracked', { ...metric })\n\n // Auto-flush if buffer is full\n if (this.buffer.length >= this.config.batchSize) {\n this.flush().catch(this.handleError.bind(this))\n }\n }\n\n /**\n * Flush buffered metrics to OpenConductor\n */\n async flush(): Promise<void> {\n if (this.buffer.length === 0) return\n\n const metrics = [...this.buffer]\n this.buffer = []\n\n const batch: TelemetryBatch = {\n serverName: this.config.serverName,\n serverVersion: this.config.serverVersion,\n metrics,\n meta: {\n sdkVersion: SDK_VERSION,\n nodeVersion: typeof process !== 'undefined' ? process.version : 'unknown',\n platform: typeof process !== 'undefined' ? process.platform : 'unknown',\n },\n }\n\n this.log('Flushing metrics', { count: metrics.length })\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'X-OpenConductor-SDK': SDK_VERSION,\n },\n body: JSON.stringify(batch),\n })\n\n if (!response.ok) {\n throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`)\n }\n\n this.log('Metrics flushed successfully', { count: metrics.length })\n } catch (error) {\n // Put metrics back in buffer on failure\n this.buffer.unshift(...metrics)\n throw error\n }\n }\n\n /**\n * Stop telemetry collection\n */\n shutdown(): void {\n if (this.flushTimer) {\n clearInterval(this.flushTimer)\n this.flushTimer = null\n }\n this.flush().catch(this.handleError.bind(this))\n this.log('Telemetry shutdown')\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n console.debug(JSON.stringify({\n timestamp: new Date().toISOString(),\n level: 'debug',\n service: 'openconductor-telemetry',\n message,\n ...data,\n }))\n }\n }\n\n private handleError(error: unknown): void {\n if (this.config.debug) {\n console.error('[OpenConductor Telemetry Error]', error)\n }\n }\n}\n"]}
|
package/dist/telemetry/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/telemetry/index.ts"],"names":[],"mappings":";AAoCA,IAAM,WAAA,GAAc,OAAA;AACpB,IAAM,gBAAA,GAAmB,qDAAA;AAEzB,IAAI,eAAA,GAAoC,IAAA;AAMjC,SAAS,cAAc,MAAA,EAAoC;AAChE,EAAA,eAAA,GAAkB,IAAI,UAAU,MAAM,CAAA;AACtC,EAAA,OAAO,eAAA;AACT;AAKO,SAAS,YAAA,GAAiC;AAC/C,EAAA,OAAO,eAAA;AACT;AAGO,IAAM,YAAN,MAAgB;AAAA,EACb,MAAA;AAAA,EACA,SAAuB,EAAC;AAAA,EACxB,UAAA,GAAoD,IAAA;AAAA,EAE5D,YAAY,MAAA,EAAyB;AACnC,IAAA,IAAA,CAAK,MAAA,GAAS;AAAA,MACZ,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,YAAY,MAAA,CAAO,UAAA;AAAA,MACnB,eAAe,MAAA,CAAO,aAAA;AAAA,MACtB,QAAA,EAAU,OAAO,QAAA,IAAY,gBAAA;AAAA,MAC7B,SAAA,EAAW,OAAO,SAAA,IAAa,EAAA;AAAA,MAC/B,aAAA,EAAe,OAAO,aAAA,IAAiB,GAAA;AAAA,MACvC,KAAA,EAAO,OAAO,KAAA,IAAS;AAAA,KACzB;AAGA,IAAA,IAAA,CAAK,UAAA,GAAa,YAAY,MAAM;AAClC,MAAA,IAAA,CAAK,OAAM,CAAE,KAAA,CAAM,KAAK,WAAA,CAAY,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,IAChD,CAAA,EAAG,IAAA,CAAK,MAAA,CAAO,aAAa,CAAA;AAG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8BAAA,EAAgC,EAAE,KAAA,EAAO,OAAA,CAAQ,QAAQ,CAAA;AAAA,IACpE,SAAS,KAAA,EAAO;AAEd,MAAA,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,GAAG,OAAO,CAAA;AAC9B,MAAA,MAAM,KAAA;AAAA,IACR;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,QAAA,GAAiB;AACf,IAAA,IAAI,KAAK,UAAA,EAAY;AACnB,MAAA,aAAA,CAAc,KAAK,UAAU,CAAA;AAC7B,MAAA,IAAA,CAAK,UAAA,GAAa,IAAA;AAAA,IACpB;AACA,IAAA,IAAA,CAAK,OAAM,CAAE,KAAA,CAAM,KAAK,WAAA,CAAY,IAAA,CAAK,IAAI,CAAC,CAAA;AAC9C,IAAA,IAAA,CAAK,IAAI,oBAAoB,CAAA;AAAA,EAC/B;AAAA,EAEQ,GAAA,CAAI,SAAiB,IAAA,EAAsC;AACjE,IAAA,IAAI,IAAA,CAAK,OAAO,KAAA,EAAO;AACrB,MAAA,OAAA,CAAQ,KAAA,CAAM,KAAK,SAAA,CAAU;AAAA,QAC3B,SAAA,EAAA,iBAAW,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAAA,QAClC,KAAA,EAAO,OAAA;AAAA,QACP,OAAA,EAAS,yBAAA;AAAA,QACT,OAAA;AAAA,QACA,GAAG;AAAA,OACJ,CAAC,CAAA;AAAA,IACJ;AAAA,EACF;AAAA,EAEQ,YAAY,KAAA,EAAsB;AACxC,IAAA,IAAI,IAAA,CAAK,OAAO,KAAA,EAAO;AACrB,MAAA,OAAA,CAAQ,KAAA,CAAM,mCAAmC,KAAK,CAAA;AAAA,IACxD;AAAA,EACF;AACF","file":"index.mjs","sourcesContent":["export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '0.
|
|
1
|
+
{"version":3,"sources":["../../src/telemetry/index.ts"],"names":[],"mappings":";AAoCA,IAAM,WAAA,GAAc,OAAA;AACpB,IAAM,gBAAA,GAAmB,qDAAA;AAEzB,IAAI,eAAA,GAAoC,IAAA;AAMjC,SAAS,cAAc,MAAA,EAAoC;AAChE,EAAA,eAAA,GAAkB,IAAI,UAAU,MAAM,CAAA;AACtC,EAAA,OAAO,eAAA;AACT;AAKO,SAAS,YAAA,GAAiC;AAC/C,EAAA,OAAO,eAAA;AACT;AAGO,IAAM,YAAN,MAAgB;AAAA,EACb,MAAA;AAAA,EACA,SAAuB,EAAC;AAAA,EACxB,UAAA,GAAoD,IAAA;AAAA,EAE5D,YAAY,MAAA,EAAyB;AACnC,IAAA,IAAA,CAAK,MAAA,GAAS;AAAA,MACZ,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,YAAY,MAAA,CAAO,UAAA;AAAA,MACnB,eAAe,MAAA,CAAO,aAAA;AAAA,MACtB,QAAA,EAAU,OAAO,QAAA,IAAY,gBAAA;AAAA,MAC7B,SAAA,EAAW,OAAO,SAAA,IAAa,EAAA;AAAA,MAC/B,aAAA,EAAe,OAAO,aAAA,IAAiB,GAAA;AAAA,MACvC,KAAA,EAAO,OAAO,KAAA,IAAS;AAAA,KACzB;AAGA,IAAA,IAAA,CAAK,UAAA,GAAa,YAAY,MAAM;AAClC,MAAA,IAAA,CAAK,OAAM,CAAE,KAAA,CAAM,KAAK,WAAA,CAAY,IAAA,CAAK,IAAI,CAAC,CAAA;AAAA,IAChD,CAAA,EAAG,IAA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MACrF;AAEA,MAAA,IAAA,CAAK,IAAI,8BAAA,EAAgC,EAAE,KAAA,EAAO,OAAA,CAAQ,QAAQ,CAAA;AAAA,IACpE,SAAS,KAAA,EAAO;AAEd,MAAA,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,GAAG,OAAO,CAAA;AAC9B,MAAA,MAAM,KAAA;AAAA,IACR;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,QAAA,GAAiB;AACf,IAAA,IAAI,KAAK,UAAA,EAAY;AACnB,MAAA,aAAA,CAAc,KAAK,UAAU,CAAA;AAC7B,MAAA,IAAA,CAAK,UAAA,GAAa,IAAA;AAAA,IACpB;AACA,IAAA,IAAA,CAAK,OAAM,CAAE,KAAA,CAAM,KAAK,WAAA,CAAY,IAAA,CAAK,IAAI,CAAC,CAAA;AAC9C,IAAA,IAAA,CAAK,IAAI,oBAAoB,CAAA;AAAA,EAC/B;AAAA,EAEQ,GAAA,CAAI,SAAiB,IAAA,EAAsC;AACjE,IAAA,IAAI,IAAA,CAAK,OAAO,KAAA,EAAO;AACrB,MAAA,OAAA,CAAQ,KAAA,CAAM,KAAK,SAAA,CAAU;AAAA,QAC3B,SAAA,EAAA,iBAAW,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAAA,QAClC,KAAA,EAAO,OAAA;AAAA,QACP,OAAA,EAAS,yBAAA;AAAA,QACT,OAAA;AAAA,QACA,GAAG;AAAA,OACJ,CAAC,CAAA;AAAA,IACJ;AAAA,EACF;AAAA,EAEQ,YAAY,KAAA,EAAsB;AACxC,IAAA,IAAI,IAAA,CAAK,OAAO,KAAA,EAAO;AACrB,MAAA,OAAA,CAAQ,KAAA,CAAM,mCAAmC,KAAK,CAAA;AAAA,IACxD;AAAA,EACF;AACF","file":"index.mjs","sourcesContent":["export interface TelemetryConfig {\n /** Your OpenConductor API key */\n apiKey: string\n /** Server name for identification */\n serverName: string\n /** Server version */\n serverVersion?: string\n /** Custom endpoint (default: OpenConductor production) */\n endpoint?: string\n /** Batch size before flushing (default: 10) */\n batchSize?: number\n /** Flush interval in ms (default: 30000) */\n flushInterval?: number\n /** Enable debug logging (default: false) */\n debug?: boolean\n}\n\nexport interface ToolMetric {\n tool: string\n duration: number\n success: boolean\n error?: string\n timestamp: string\n}\n\nexport interface TelemetryBatch {\n serverName: string\n serverVersion?: string\n metrics: ToolMetric[]\n meta: {\n sdkVersion: string\n nodeVersion: string\n platform: string\n }\n}\n\nconst SDK_VERSION = '1.0.0'\nconst DEFAULT_ENDPOINT = 'https://api.openconductor.ai/functions/v1/telemetry'\n\nlet globalTelemetry: Telemetry | null = null\n\n/**\n * Initialize telemetry for your MCP server\n * Call this once at startup with your OpenConductor API key\n */\nexport function initTelemetry(config: TelemetryConfig): Telemetry {\n globalTelemetry = new Telemetry(config)\n return globalTelemetry\n}\n\n/**\n * Get the global telemetry instance (if initialized)\n */\nexport function getTelemetry(): Telemetry | null {\n return globalTelemetry\n}\n\n\nexport class Telemetry {\n private config: Required<Omit<TelemetryConfig, 'serverVersion'>> & Pick<TelemetryConfig, 'serverVersion'>\n private buffer: ToolMetric[] = []\n private flushTimer: ReturnType<typeof setInterval> | null = null\n\n constructor(config: TelemetryConfig) {\n this.config = {\n apiKey: config.apiKey,\n serverName: config.serverName,\n serverVersion: config.serverVersion,\n endpoint: config.endpoint ?? DEFAULT_ENDPOINT,\n batchSize: config.batchSize ?? 10,\n flushInterval: config.flushInterval ?? 30000,\n debug: config.debug ?? false,\n }\n\n // Start periodic flush\n this.flushTimer = setInterval(() => {\n this.flush().catch(this.handleError.bind(this))\n }, this.config.flushInterval)\n\n // Flush on process exit\n if (typeof process !== 'undefined') {\n process.on('beforeExit', () => this.flush())\n process.on('SIGINT', () => {\n this.flush().finally(() => process.exit(0))\n })\n process.on('SIGTERM', () => {\n this.flush().finally(() => process.exit(0))\n })\n }\n\n this.log('Telemetry initialized', { serverName: config.serverName })\n }\n\n /**\n * Track a tool invocation\n */\n trackToolCall(\n tool: string,\n duration: number,\n success: boolean,\n error?: string\n ): void {\n const metric: ToolMetric = {\n tool,\n duration,\n success,\n ...(error && { error }),\n timestamp: new Date().toISOString(),\n }\n\n this.buffer.push(metric)\n this.log('Metric tracked', { ...metric })\n\n // Auto-flush if buffer is full\n if (this.buffer.length >= this.config.batchSize) {\n this.flush().catch(this.handleError.bind(this))\n }\n }\n\n /**\n * Flush buffered metrics to OpenConductor\n */\n async flush(): Promise<void> {\n if (this.buffer.length === 0) return\n\n const metrics = [...this.buffer]\n this.buffer = []\n\n const batch: TelemetryBatch = {\n serverName: this.config.serverName,\n serverVersion: this.config.serverVersion,\n metrics,\n meta: {\n sdkVersion: SDK_VERSION,\n nodeVersion: typeof process !== 'undefined' ? process.version : 'unknown',\n platform: typeof process !== 'undefined' ? process.platform : 'unknown',\n },\n }\n\n this.log('Flushing metrics', { count: metrics.length })\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n 'X-OpenConductor-SDK': SDK_VERSION,\n },\n body: JSON.stringify(batch),\n })\n\n if (!response.ok) {\n throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`)\n }\n\n this.log('Metrics flushed successfully', { count: metrics.length })\n } catch (error) {\n // Put metrics back in buffer on failure\n this.buffer.unshift(...metrics)\n throw error\n }\n }\n\n /**\n * Stop telemetry collection\n */\n shutdown(): void {\n if (this.flushTimer) {\n clearInterval(this.flushTimer)\n this.flushTimer = null\n }\n this.flush().catch(this.handleError.bind(this))\n this.log('Telemetry shutdown')\n }\n\n private log(message: string, data?: Record<string, unknown>): void {\n if (this.config.debug) {\n console.debug(JSON.stringify({\n timestamp: new Date().toISOString(),\n level: 'debug',\n service: 'openconductor-telemetry',\n message,\n ...data,\n }))\n }\n }\n\n private handleError(error: unknown): void {\n if (this.config.debug) {\n console.error('[OpenConductor Telemetry Error]', error)\n }\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openconductor/mcp-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "The standard SDK for building MCP servers — error handling, validation, logging, and telemetry out of the box",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|