|
| 1 | +import { createLogger } from '@sim/logger' |
| 2 | +import type { McpExecutionContext, McpMiddleware, McpMiddlewareNext } from './types' |
| 3 | +import type { McpToolResult } from '@/lib/mcp/types' |
| 4 | + |
| 5 | +const logger = createLogger('mcp:telemetry') |
| 6 | + |
| 7 | +export class TelemetryMiddleware implements McpMiddleware { |
| 8 | + async execute( |
| 9 | + context: McpExecutionContext, |
| 10 | + next: McpMiddlewareNext |
| 11 | + ): Promise<McpToolResult> { |
| 12 | + const startTime = performance.now() |
| 13 | + |
| 14 | + try { |
| 15 | + const result = await next(context) |
| 16 | + |
| 17 | + const latency_ms = Math.round(performance.now() - startTime) |
| 18 | + const isError = result.isError === true |
| 19 | + |
| 20 | + logger.info('MCP Tool Execution Completed', { |
| 21 | + toolName: context.toolCall.name, |
| 22 | + serverId: context.serverId, |
| 23 | + workspaceId: context.workspaceId, |
| 24 | + latency_ms, |
| 25 | + success: !isError, |
| 26 | + ...(isError && { failure_reason: 'TOOL_ERROR' }) |
| 27 | + }) |
| 28 | + |
| 29 | + return result |
| 30 | + } catch (error) { |
| 31 | + const latency_ms = Math.round(performance.now() - startTime) |
| 32 | + |
| 33 | + // Attempt to determine failure reason based on error |
| 34 | + let failure_reason = 'API_500' // General failure fallback |
| 35 | + if (error instanceof Error) { |
| 36 | + const lowerMsg = error.message.toLowerCase() |
| 37 | + if (error.name === 'TimeoutError' || lowerMsg.includes('timeout')) { |
| 38 | + failure_reason = 'TIMEOUT' |
| 39 | + } else if (lowerMsg.includes('validation') || error.name === 'ZodError') { |
| 40 | + failure_reason = 'VALIDATION_ERROR' |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + logger.error('MCP Tool Execution Failed', { |
| 45 | + toolName: context.toolCall.name, |
| 46 | + serverId: context.serverId, |
| 47 | + workspaceId: context.workspaceId, |
| 48 | + latency_ms, |
| 49 | + failure_reason, |
| 50 | + err: error instanceof Error ? error.message : String(error) |
| 51 | + }) |
| 52 | + |
| 53 | + throw error // Re-throw to allow upstream handling (e.g. circuit breaker) |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments