@openconductor/mcp-sdk 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +229 -0
- package/dist/errors/index.d.mts +114 -0
- package/dist/errors/index.d.ts +114 -0
- package/dist/errors/index.js +159 -0
- package/dist/errors/index.js.map +1 -0
- package/dist/errors/index.mjs +146 -0
- package/dist/errors/index.mjs.map +1 -0
- package/dist/index.d.mts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +524 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +495 -0
- package/dist/index.mjs.map +1 -0
- package/dist/logger/index.d.mts +34 -0
- package/dist/logger/index.d.ts +34 -0
- package/dist/logger/index.js +79 -0
- package/dist/logger/index.js.map +1 -0
- package/dist/logger/index.mjs +77 -0
- package/dist/logger/index.mjs.map +1 -0
- package/dist/server/index.d.mts +48 -0
- package/dist/server/index.d.ts +48 -0
- package/dist/server/index.js +239 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/index.mjs +236 -0
- package/dist/server/index.mjs.map +1 -0
- package/dist/telemetry/index.d.mts +64 -0
- package/dist/telemetry/index.d.ts +64 -0
- package/dist/telemetry/index.js +129 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/telemetry/index.mjs +125 -0
- package/dist/telemetry/index.mjs.map +1 -0
- package/dist/validate/index.d.mts +51 -0
- package/dist/validate/index.d.ts +51 -0
- package/dist/validate/index.js +122 -0
- package/dist/validate/index.js.map +1 -0
- package/dist/validate/index.mjs +111 -0
- package/dist/validate/index.mjs.map +1 -0
- package/package.json +85 -0
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
// src/errors/codes.ts
|
|
2
|
+
var ErrorCodes = {
|
|
3
|
+
TOOL_EXECUTION_ERROR: -32002,
|
|
4
|
+
TIMEOUT_ERROR: -32007};
|
|
5
|
+
|
|
6
|
+
// src/errors/index.ts
|
|
7
|
+
var MCPError = class extends Error {
|
|
8
|
+
code;
|
|
9
|
+
data;
|
|
10
|
+
constructor(code, message, data) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = "MCPError";
|
|
13
|
+
this.code = code;
|
|
14
|
+
this.data = data;
|
|
15
|
+
if (Error.captureStackTrace) {
|
|
16
|
+
Error.captureStackTrace(this, this.constructor);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Returns JSON-RPC 2.0 formatted error object
|
|
21
|
+
*/
|
|
22
|
+
toJSON() {
|
|
23
|
+
return {
|
|
24
|
+
code: this.code,
|
|
25
|
+
message: this.message,
|
|
26
|
+
...this.data && { data: this.data }
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Create error response for JSON-RPC
|
|
31
|
+
*/
|
|
32
|
+
toResponse(id = null) {
|
|
33
|
+
return {
|
|
34
|
+
jsonrpc: "2.0",
|
|
35
|
+
id,
|
|
36
|
+
error: this.toJSON()
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
var ToolExecutionError = class extends MCPError {
|
|
41
|
+
constructor(toolName, reason, cause) {
|
|
42
|
+
super(ErrorCodes.TOOL_EXECUTION_ERROR, `Tool '${toolName}' failed: ${reason}`, {
|
|
43
|
+
tool: toolName,
|
|
44
|
+
reason,
|
|
45
|
+
...cause && { cause: cause.message }
|
|
46
|
+
});
|
|
47
|
+
this.name = "ToolExecutionError";
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
var TimeoutError = class extends MCPError {
|
|
51
|
+
constructor(operation, timeoutMs) {
|
|
52
|
+
super(ErrorCodes.TIMEOUT_ERROR, `Operation '${operation}' timed out after ${timeoutMs}ms`, {
|
|
53
|
+
operation,
|
|
54
|
+
timeoutMs
|
|
55
|
+
});
|
|
56
|
+
this.name = "TimeoutError";
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// src/logger/index.ts
|
|
61
|
+
var LEVEL_PRIORITY = {
|
|
62
|
+
debug: 0,
|
|
63
|
+
info: 1,
|
|
64
|
+
warn: 2,
|
|
65
|
+
error: 3
|
|
66
|
+
};
|
|
67
|
+
function createLogger(service, options = {}) {
|
|
68
|
+
const {
|
|
69
|
+
level: minLevel = "info",
|
|
70
|
+
timestamps = true,
|
|
71
|
+
pretty = false
|
|
72
|
+
} = options;
|
|
73
|
+
const shouldLog = (level) => {
|
|
74
|
+
return LEVEL_PRIORITY[level] >= LEVEL_PRIORITY[minLevel];
|
|
75
|
+
};
|
|
76
|
+
const formatEntry = (entry) => {
|
|
77
|
+
return pretty ? JSON.stringify(entry, null, 2) : JSON.stringify(entry);
|
|
78
|
+
};
|
|
79
|
+
const log = (level, message, data) => {
|
|
80
|
+
if (!shouldLog(level)) return;
|
|
81
|
+
const entry = {
|
|
82
|
+
...timestamps && { timestamp: (/* @__PURE__ */ new Date()).toISOString() },
|
|
83
|
+
level,
|
|
84
|
+
service,
|
|
85
|
+
message,
|
|
86
|
+
...data
|
|
87
|
+
};
|
|
88
|
+
if (options.output) {
|
|
89
|
+
options.output(entry);
|
|
90
|
+
} else {
|
|
91
|
+
const formatted = formatEntry(entry);
|
|
92
|
+
switch (level) {
|
|
93
|
+
case "debug":
|
|
94
|
+
console.debug(formatted);
|
|
95
|
+
break;
|
|
96
|
+
case "info":
|
|
97
|
+
console.info(formatted);
|
|
98
|
+
break;
|
|
99
|
+
case "warn":
|
|
100
|
+
console.warn(formatted);
|
|
101
|
+
break;
|
|
102
|
+
case "error":
|
|
103
|
+
console.error(formatted);
|
|
104
|
+
break;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return entry;
|
|
108
|
+
};
|
|
109
|
+
return {
|
|
110
|
+
debug: (message, data) => log("debug", message, data),
|
|
111
|
+
info: (message, data) => log("info", message, data),
|
|
112
|
+
warn: (message, data) => log("warn", message, data),
|
|
113
|
+
error: (message, data) => log("error", message, data),
|
|
114
|
+
/**
|
|
115
|
+
* Create a child logger with additional context
|
|
116
|
+
*/
|
|
117
|
+
child: (context) => {
|
|
118
|
+
return createLogger(service, {
|
|
119
|
+
...options,
|
|
120
|
+
output: (entry) => {
|
|
121
|
+
const merged = { ...entry, ...context };
|
|
122
|
+
if (options.output) {
|
|
123
|
+
options.output(merged);
|
|
124
|
+
} else {
|
|
125
|
+
const formatted = pretty ? JSON.stringify(merged, null, 2) : JSON.stringify(merged);
|
|
126
|
+
console[entry.level](formatted);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// src/telemetry/index.ts
|
|
135
|
+
var globalTelemetry = null;
|
|
136
|
+
function getTelemetry() {
|
|
137
|
+
return globalTelemetry;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// src/server/index.ts
|
|
141
|
+
function createHealthCheck(info) {
|
|
142
|
+
return async () => {
|
|
143
|
+
const checks = {};
|
|
144
|
+
let allHealthy = true;
|
|
145
|
+
if (info.checks) {
|
|
146
|
+
for (const [name, check] of Object.entries(info.checks)) {
|
|
147
|
+
try {
|
|
148
|
+
checks[name] = await check();
|
|
149
|
+
if (!checks[name]) allHealthy = false;
|
|
150
|
+
} catch {
|
|
151
|
+
checks[name] = false;
|
|
152
|
+
allHealthy = false;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
status: allHealthy ? "healthy" : "degraded",
|
|
158
|
+
name: info.name,
|
|
159
|
+
version: info.version,
|
|
160
|
+
...info.description && { description: info.description },
|
|
161
|
+
...info.uptime && { uptime: info.uptime() },
|
|
162
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
163
|
+
...Object.keys(checks).length > 0 && { checks }
|
|
164
|
+
};
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function wrapTool(handler, options) {
|
|
168
|
+
const {
|
|
169
|
+
name,
|
|
170
|
+
timeout = 3e4,
|
|
171
|
+
telemetry: enableTelemetry = true
|
|
172
|
+
} = options;
|
|
173
|
+
const baseLogger = options.logger ?? createLogger(name);
|
|
174
|
+
return async (input) => {
|
|
175
|
+
const callId = generateCallId();
|
|
176
|
+
const startTime = Date.now();
|
|
177
|
+
const log = baseLogger.child({ callId });
|
|
178
|
+
const ctx = { callId, name, startTime, log };
|
|
179
|
+
log.info("Tool invoked", { tool: name, input: sanitizeInput(input) });
|
|
180
|
+
try {
|
|
181
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
182
|
+
setTimeout(() => {
|
|
183
|
+
reject(new TimeoutError(name, timeout));
|
|
184
|
+
}, timeout);
|
|
185
|
+
});
|
|
186
|
+
const result = await Promise.race([
|
|
187
|
+
Promise.resolve(handler(input, ctx)),
|
|
188
|
+
timeoutPromise
|
|
189
|
+
]);
|
|
190
|
+
const duration = Date.now() - startTime;
|
|
191
|
+
log.info("Tool completed", { tool: name, duration });
|
|
192
|
+
if (enableTelemetry) {
|
|
193
|
+
const tel = getTelemetry();
|
|
194
|
+
tel?.trackToolCall(name, duration, true);
|
|
195
|
+
}
|
|
196
|
+
return result;
|
|
197
|
+
} catch (error) {
|
|
198
|
+
const duration = Date.now() - startTime;
|
|
199
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
200
|
+
log.error("Tool failed", {
|
|
201
|
+
tool: name,
|
|
202
|
+
duration,
|
|
203
|
+
error: errorMessage,
|
|
204
|
+
stack: error instanceof Error ? error.stack : void 0
|
|
205
|
+
});
|
|
206
|
+
if (error instanceof MCPError) {
|
|
207
|
+
throw error;
|
|
208
|
+
}
|
|
209
|
+
throw new ToolExecutionError(
|
|
210
|
+
name,
|
|
211
|
+
errorMessage,
|
|
212
|
+
error instanceof Error ? error : void 0
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
function generateCallId() {
|
|
218
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
219
|
+
}
|
|
220
|
+
function sanitizeInput(input) {
|
|
221
|
+
if (typeof input !== "object" || input === null) return input;
|
|
222
|
+
const sensitiveKeys = ["password", "token", "secret", "key", "auth", "credential"];
|
|
223
|
+
const sanitized = {};
|
|
224
|
+
for (const [key, value] of Object.entries(input)) {
|
|
225
|
+
if (sensitiveKeys.some((k) => key.toLowerCase().includes(k))) {
|
|
226
|
+
sanitized[key] = "[REDACTED]";
|
|
227
|
+
} else {
|
|
228
|
+
sanitized[key] = value;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return sanitized;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export { createHealthCheck, wrapTool };
|
|
235
|
+
//# sourceMappingURL=index.mjs.map
|
|
236
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +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,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AY,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"]}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
interface TelemetryConfig {
|
|
2
|
+
/** Your OpenConductor API key */
|
|
3
|
+
apiKey: string;
|
|
4
|
+
/** Server name for identification */
|
|
5
|
+
serverName: string;
|
|
6
|
+
/** Server version */
|
|
7
|
+
serverVersion?: string;
|
|
8
|
+
/** Custom endpoint (default: OpenConductor production) */
|
|
9
|
+
endpoint?: string;
|
|
10
|
+
/** Batch size before flushing (default: 10) */
|
|
11
|
+
batchSize?: number;
|
|
12
|
+
/** Flush interval in ms (default: 30000) */
|
|
13
|
+
flushInterval?: number;
|
|
14
|
+
/** Enable debug logging (default: false) */
|
|
15
|
+
debug?: boolean;
|
|
16
|
+
}
|
|
17
|
+
interface ToolMetric {
|
|
18
|
+
tool: string;
|
|
19
|
+
duration: number;
|
|
20
|
+
success: boolean;
|
|
21
|
+
error?: string;
|
|
22
|
+
timestamp: string;
|
|
23
|
+
}
|
|
24
|
+
interface TelemetryBatch {
|
|
25
|
+
serverName: string;
|
|
26
|
+
serverVersion?: string;
|
|
27
|
+
metrics: ToolMetric[];
|
|
28
|
+
meta: {
|
|
29
|
+
sdkVersion: string;
|
|
30
|
+
nodeVersion: string;
|
|
31
|
+
platform: string;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Initialize telemetry for your MCP server
|
|
36
|
+
* Call this once at startup with your OpenConductor API key
|
|
37
|
+
*/
|
|
38
|
+
declare function initTelemetry(config: TelemetryConfig): Telemetry;
|
|
39
|
+
/**
|
|
40
|
+
* Get the global telemetry instance (if initialized)
|
|
41
|
+
*/
|
|
42
|
+
declare function getTelemetry(): Telemetry | null;
|
|
43
|
+
declare class Telemetry {
|
|
44
|
+
private config;
|
|
45
|
+
private buffer;
|
|
46
|
+
private flushTimer;
|
|
47
|
+
constructor(config: TelemetryConfig);
|
|
48
|
+
/**
|
|
49
|
+
* Track a tool invocation
|
|
50
|
+
*/
|
|
51
|
+
trackToolCall(tool: string, duration: number, success: boolean, error?: string): void;
|
|
52
|
+
/**
|
|
53
|
+
* Flush buffered metrics to OpenConductor
|
|
54
|
+
*/
|
|
55
|
+
flush(): Promise<void>;
|
|
56
|
+
/**
|
|
57
|
+
* Stop telemetry collection
|
|
58
|
+
*/
|
|
59
|
+
shutdown(): void;
|
|
60
|
+
private log;
|
|
61
|
+
private handleError;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export { Telemetry, type TelemetryBatch, type TelemetryConfig, type ToolMetric, getTelemetry, initTelemetry };
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
interface TelemetryConfig {
|
|
2
|
+
/** Your OpenConductor API key */
|
|
3
|
+
apiKey: string;
|
|
4
|
+
/** Server name for identification */
|
|
5
|
+
serverName: string;
|
|
6
|
+
/** Server version */
|
|
7
|
+
serverVersion?: string;
|
|
8
|
+
/** Custom endpoint (default: OpenConductor production) */
|
|
9
|
+
endpoint?: string;
|
|
10
|
+
/** Batch size before flushing (default: 10) */
|
|
11
|
+
batchSize?: number;
|
|
12
|
+
/** Flush interval in ms (default: 30000) */
|
|
13
|
+
flushInterval?: number;
|
|
14
|
+
/** Enable debug logging (default: false) */
|
|
15
|
+
debug?: boolean;
|
|
16
|
+
}
|
|
17
|
+
interface ToolMetric {
|
|
18
|
+
tool: string;
|
|
19
|
+
duration: number;
|
|
20
|
+
success: boolean;
|
|
21
|
+
error?: string;
|
|
22
|
+
timestamp: string;
|
|
23
|
+
}
|
|
24
|
+
interface TelemetryBatch {
|
|
25
|
+
serverName: string;
|
|
26
|
+
serverVersion?: string;
|
|
27
|
+
metrics: ToolMetric[];
|
|
28
|
+
meta: {
|
|
29
|
+
sdkVersion: string;
|
|
30
|
+
nodeVersion: string;
|
|
31
|
+
platform: string;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Initialize telemetry for your MCP server
|
|
36
|
+
* Call this once at startup with your OpenConductor API key
|
|
37
|
+
*/
|
|
38
|
+
declare function initTelemetry(config: TelemetryConfig): Telemetry;
|
|
39
|
+
/**
|
|
40
|
+
* Get the global telemetry instance (if initialized)
|
|
41
|
+
*/
|
|
42
|
+
declare function getTelemetry(): Telemetry | null;
|
|
43
|
+
declare class Telemetry {
|
|
44
|
+
private config;
|
|
45
|
+
private buffer;
|
|
46
|
+
private flushTimer;
|
|
47
|
+
constructor(config: TelemetryConfig);
|
|
48
|
+
/**
|
|
49
|
+
* Track a tool invocation
|
|
50
|
+
*/
|
|
51
|
+
trackToolCall(tool: string, duration: number, success: boolean, error?: string): void;
|
|
52
|
+
/**
|
|
53
|
+
* Flush buffered metrics to OpenConductor
|
|
54
|
+
*/
|
|
55
|
+
flush(): Promise<void>;
|
|
56
|
+
/**
|
|
57
|
+
* Stop telemetry collection
|
|
58
|
+
*/
|
|
59
|
+
shutdown(): void;
|
|
60
|
+
private log;
|
|
61
|
+
private handleError;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export { Telemetry, type TelemetryBatch, type TelemetryConfig, type ToolMetric, getTelemetry, initTelemetry };
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/telemetry/index.ts
|
|
4
|
+
var SDK_VERSION = "0.2.0";
|
|
5
|
+
var DEFAULT_ENDPOINT = "https://api.openconductor.ai/functions/v1/telemetry";
|
|
6
|
+
var globalTelemetry = null;
|
|
7
|
+
function initTelemetry(config) {
|
|
8
|
+
globalTelemetry = new Telemetry(config);
|
|
9
|
+
return globalTelemetry;
|
|
10
|
+
}
|
|
11
|
+
function getTelemetry() {
|
|
12
|
+
return globalTelemetry;
|
|
13
|
+
}
|
|
14
|
+
var Telemetry = class {
|
|
15
|
+
config;
|
|
16
|
+
buffer = [];
|
|
17
|
+
flushTimer = null;
|
|
18
|
+
constructor(config) {
|
|
19
|
+
this.config = {
|
|
20
|
+
apiKey: config.apiKey,
|
|
21
|
+
serverName: config.serverName,
|
|
22
|
+
serverVersion: config.serverVersion,
|
|
23
|
+
endpoint: config.endpoint ?? DEFAULT_ENDPOINT,
|
|
24
|
+
batchSize: config.batchSize ?? 10,
|
|
25
|
+
flushInterval: config.flushInterval ?? 3e4,
|
|
26
|
+
debug: config.debug ?? false
|
|
27
|
+
};
|
|
28
|
+
this.flushTimer = setInterval(() => {
|
|
29
|
+
this.flush().catch(this.handleError.bind(this));
|
|
30
|
+
}, this.config.flushInterval);
|
|
31
|
+
if (typeof process !== "undefined") {
|
|
32
|
+
process.on("beforeExit", () => this.flush());
|
|
33
|
+
process.on("SIGINT", () => {
|
|
34
|
+
this.flush().finally(() => process.exit(0));
|
|
35
|
+
});
|
|
36
|
+
process.on("SIGTERM", () => {
|
|
37
|
+
this.flush().finally(() => process.exit(0));
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
this.log("Telemetry initialized", { serverName: config.serverName });
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Track a tool invocation
|
|
44
|
+
*/
|
|
45
|
+
trackToolCall(tool, duration, success, error) {
|
|
46
|
+
const metric = {
|
|
47
|
+
tool,
|
|
48
|
+
duration,
|
|
49
|
+
success,
|
|
50
|
+
...error && { error },
|
|
51
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
52
|
+
};
|
|
53
|
+
this.buffer.push(metric);
|
|
54
|
+
this.log("Metric tracked", { ...metric });
|
|
55
|
+
if (this.buffer.length >= this.config.batchSize) {
|
|
56
|
+
this.flush().catch(this.handleError.bind(this));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Flush buffered metrics to OpenConductor
|
|
61
|
+
*/
|
|
62
|
+
async flush() {
|
|
63
|
+
if (this.buffer.length === 0) return;
|
|
64
|
+
const metrics = [...this.buffer];
|
|
65
|
+
this.buffer = [];
|
|
66
|
+
const batch = {
|
|
67
|
+
serverName: this.config.serverName,
|
|
68
|
+
serverVersion: this.config.serverVersion,
|
|
69
|
+
metrics,
|
|
70
|
+
meta: {
|
|
71
|
+
sdkVersion: SDK_VERSION,
|
|
72
|
+
nodeVersion: typeof process !== "undefined" ? process.version : "unknown",
|
|
73
|
+
platform: typeof process !== "undefined" ? process.platform : "unknown"
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
this.log("Flushing metrics", { count: metrics.length });
|
|
77
|
+
try {
|
|
78
|
+
const response = await fetch(this.config.endpoint, {
|
|
79
|
+
method: "POST",
|
|
80
|
+
headers: {
|
|
81
|
+
"Content-Type": "application/json",
|
|
82
|
+
"Authorization": `Bearer ${this.config.apiKey}`,
|
|
83
|
+
"X-OpenConductor-SDK": SDK_VERSION
|
|
84
|
+
},
|
|
85
|
+
body: JSON.stringify(batch)
|
|
86
|
+
});
|
|
87
|
+
if (!response.ok) {
|
|
88
|
+
throw new Error(`Telemetry flush failed: ${response.status} ${response.statusText}`);
|
|
89
|
+
}
|
|
90
|
+
this.log("Metrics flushed successfully", { count: metrics.length });
|
|
91
|
+
} catch (error) {
|
|
92
|
+
this.buffer.unshift(...metrics);
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Stop telemetry collection
|
|
98
|
+
*/
|
|
99
|
+
shutdown() {
|
|
100
|
+
if (this.flushTimer) {
|
|
101
|
+
clearInterval(this.flushTimer);
|
|
102
|
+
this.flushTimer = null;
|
|
103
|
+
}
|
|
104
|
+
this.flush().catch(this.handleError.bind(this));
|
|
105
|
+
this.log("Telemetry shutdown");
|
|
106
|
+
}
|
|
107
|
+
log(message, data) {
|
|
108
|
+
if (this.config.debug) {
|
|
109
|
+
console.debug(JSON.stringify({
|
|
110
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
111
|
+
level: "debug",
|
|
112
|
+
service: "openconductor-telemetry",
|
|
113
|
+
message,
|
|
114
|
+
...data
|
|
115
|
+
}));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
handleError(error) {
|
|
119
|
+
if (this.config.debug) {
|
|
120
|
+
console.error("[OpenConductor Telemetry Error]", error);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
exports.Telemetry = Telemetry;
|
|
126
|
+
exports.getTelemetry = getTelemetry;
|
|
127
|
+
exports.initTelemetry = initTelemetry;
|
|
128
|
+
//# sourceMappingURL=index.js.map
|
|
129
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/telemetry/index.ts"],"names":[],"mappings":";;;AAoCA,IAAM,WAAA,GAAc,OAAA;AACpB,IAAM,gBAAA,GAA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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.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.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"]}
|