import { McpServerFactory } from "@modelcontextprotocol/server"; import { z } from "zod"; //#region src/cli-args.d.ts interface ParsedArgs { /** Environment-shaped overrides, highest precedence. */ overrides: Record; help: boolean; version: boolean; /** Fatal: a flag of ours used wrongly. */ errors: string[]; /** Non-fatal: flags we do not know about. */ warnings: string[]; } //#endregion //#region src/config.d.ts declare const configSchema: z.ZodObject<{ backend: z.ZodDefault>; transport: z.ZodDefault>; port: z.ZodDefault>; host: z.ZodDefault; allowedHosts: z.ZodPipe, z.ZodTransform>; allowedOrigins: z.ZodPipe, z.ZodTransform>; collectorPort: z.ZodDefault>; persist: z.ZodOptional; retentionMs: z.ZodOptional>; maxTraces: z.ZodDefault>; jaegerBaseUrl: z.ZodDefault; devtoolsBaseUrl: z.ZodDefault; tempoBaseUrl: z.ZodDefault; prometheusBaseUrl: z.ZodDefault; lokiBaseUrl: z.ZodDefault; grafanaCloudToken: z.ZodDefault; grafanaUrl: z.ZodDefault; grafanaTempoDatasource: z.ZodDefault; tempoUsername: z.ZodDefault; prometheusUsername: z.ZodDefault; lokiUsername: z.ZodDefault; toolsets: z.ZodPipe, z.ZodTransform>; omitTools: z.ZodPipe, z.ZodTransform>; fixturePath: z.ZodDefault; logfireBaseUrl: z.ZodDefault; logfireReadToken: z.ZodDefault; datadogSite: z.ZodDefault; datadogApiKey: z.ZodDefault; datadogAppKey: z.ZodDefault; signozBaseUrl: z.ZodDefault; signozApiKey: z.ZodDefault; cloudflareAccountId: z.ZodDefault; cloudflareApiToken: z.ZodDefault; }, z.core.$strip>; type AppConfig = z.infer; type Env = Record; /** * Resolves configuration from flags, then the environment, then defaults. * * `argv` and `env` are parameters rather than globals so the precedence rules * can be tested without mutating the process. * * `argv` defaults to empty rather than `process.argv`. A library embedding this * server has its own command line, and inheriting it would turn that caller's * unrelated flags into "unknown option" errors. The CLI passes argv in. */ export declare function loadConfig(argv?: readonly string[], env?: Env): AppConfig; /** * The same resolution from an already-parsed command line, so a caller that * needs `--help`, `--version` or the error list does not parse argv a second * time and reach a different verdict about it. */ export declare function resolveConfig(parsed: ParsedArgs, env?: Env): AppConfig; //#endregion //#region src/types.d.ts type SignalSupport = 'available' | 'unsupported'; type SpanStatusCode = 'OK' | 'ERROR' | 'UNSET'; type TagValue = string | number | boolean; /** * A span's attributes. The keys are whatever the instrumentation emitted, so * this is an open dictionary on purpose: naming it once says that, rather than * each signature re-deciding it. */ type Tags = Record; type FilterOperator = 'equals' | 'not_equals' | 'contains' | 'not_contains' | 'starts_with' | 'ends_with' | 'in' | 'not_in' | 'gt' | 'lt' | 'gte' | 'lte' | 'between' | 'exists' | 'not_exists'; type FilterValueType = 'string' | 'number' | 'boolean'; interface QueryFilter { field: string; operator: FilterOperator; value?: TagValue | TagValue[]; valueType?: FilterValueType; } interface SpanRecord { traceId: string; spanId: string; parentSpanId: string | null; operationName: string; serviceName: string; startTimeUnixMs: number; durationMs: number; statusCode: SpanStatusCode; tags: Record; hasError: boolean; } interface TraceRecord { traceId: string; spans: SpanRecord[]; /** The backend capped the span page, so this trace is missing spans. */ truncated?: boolean; } interface TraceSearchQuery { service?: string; operation?: string; tags?: Record; minDurationMs?: number; maxDurationMs?: number; startTimeUnixMs?: number; endTimeUnixMs?: number; limit?: number; statusCode?: SpanStatusCode; hasError?: boolean; filters?: QueryFilter[]; } interface SpanSearchQuery extends TraceSearchQuery { spanMinDurationMs?: number; spanMaxDurationMs?: number; } interface MetricSearchQuery { metricName?: string; serviceName?: string; lookbackMinutes?: number; limit?: number; } interface MetricSeriesQuery { startTimeUnixMs?: number; endTimeUnixMs?: number; serviceName?: string; limit?: number; /** * Attributes the series must keep apart, for a counter read as counts. * A backend that aggregates at query time (Datadog) sums within this grouping * and answers with `temporality: 'delta'`. Others return every series anyway. */ groupBy?: string[]; } interface LogSearchQuery { serviceName?: string; traceId?: string; spanId?: string; severityText?: string; text?: string; attributes?: Record; startTimeUnixMs?: number; endTimeUnixMs?: number; limit?: number; } interface MetricPoint { timestampUnixMs: number; value: number; /** When a cumulative series began counting, where the backend keeps it. */ startTimeUnixMs?: number; } interface MetricSeries { metricName: string; unit?: string; points: MetricPoint[]; attributes?: Record; /** * For a counter: whether each point is an increment (`delta`) or a running * total (`cumulative`). Absent means not known, and is read as cumulative, * the OTLP default. */ temporality?: 'delta' | 'cumulative'; } interface LogRecord { timestampUnixMs: number; severityText: string; body: string; serviceName?: string; traceId?: string; spanId?: string; attributes?: Record; } interface SearchResult { items: T[]; cursor?: string; totalCount: number; unsupported?: boolean; detail?: string; /** * The backend's page filled before local filtering, so more matches may * exist. Absent means the caller judges by `items.length` against its limit. */ truncated?: boolean; } type TraceSearchResult = SearchResult; type SpanSearchResult = SearchResult; type MetricSearchResult = SearchResult; type LogSearchResult = SearchResult; interface BackendHealth { healthy: boolean; message?: string; } interface BackendCapabilities { traces: SignalSupport; metrics: SignalSupport; logs: SignalSupport; } interface ServiceListResult { services: string[]; } interface OperationListResult { operations: string[]; } interface ServiceQuery { limit?: number; } interface CorrelatedSignals { trace: TraceRecord | null; metrics: MetricSeries[]; logs: LogRecord[]; } interface ServiceMapNode { service: string; traces: number; spans: number; errors: number; inboundCalls: number; outboundCalls: number; avgDurationMs: number; errorRate: number; } interface ServiceMapEdge { source: string; target: string; calls: number; errors: number; avgDurationMs: number; p95DurationMs: number; } interface ServiceMap { nodes: ServiceMapNode[]; edges: ServiceMapEdge[]; } interface TraceSummary { traceId: string; serviceName: string; durationMs: number; statusCode: SpanStatusCode; spanCount: number; llmSpanCount: number; errorSpanCount: number; totalTokens: number; modelsUsed: string[]; serviceCount: number; topOperations: Array<{ operation: string; count: number; }>; /** Counts cover only the spans the backend returned. */ truncated?: boolean; } interface InstrumentationScore { score: number; grade: string; suggestions: string[]; } //#endregion //#region ../autotel-devtools/dist/index-DLvpQKEC.d.ts /** * - `exception`: a span failed (status ERROR) — thrown, or an invocation failure. * - `handled_exception`: an exception was recorded on a span that still * succeeded, e.g. `console.error(err)` before a fallback response. * - `http_5xx`: a server response in the 5xx range with no exception behind it. * - `error_log`: an error-level log outside any trace. * - `log_flood` / `runaway_alarm`: autotel's own detectors, reported as * `autotel.LogFlood` / `autotel.RunawayAlarm` exceptions. */ type IssueSource = 'exception' | 'handled_exception' | 'http_5xx' | 'error_log' | 'log_flood' | 'runaway_alarm'; //#endregion //#region src/issues/group.d.ts type IssueStatus = 'active' | 'resolved' | 'ignored'; interface Issue { fingerprint: string; service: string; source: IssueSource; title: string; type?: string; message: string; culprit?: string; operation?: string; status: IssueStatus; count: number; firstSeen: number; lastSeen: number; /** Occurrences per equal-width bucket across the window, oldest first. */ trend: number[]; /** Came back after a gap of `quietMs` or more between two occurrences. */ regression: boolean; versions: string[]; affected: { users: number; accounts: number; sessions: number; }; /** Newest first. */ sampleTraceIds: string[]; latestStack?: string; } //#endregion //#region src/modules/span-aggregate.d.ts /** * Aggregation over spans and logs the backend already returned: what an agent * would otherwise do by reading raw traces into its context and counting. * Pure, so every backend gets it; a backend that can aggregate server-side * answers with exact numbers instead (`TelemetryBackend.aggregateSpans`). */ interface LatencyStats { count: number; errorCount: number; errorRate: number; avgMs: number; p50Ms: number; p95Ms: number; p99Ms: number; maxMs: number; } interface SpanAggregateRow extends LatencyStats { group: Record; /** Absent when the backend aggregated server-side. */ firstSeenUnixMs?: number; lastSeenUnixMs?: number; buckets?: Array<{ startUnixMs: number; } & LatencyStats>; } //#endregion //#region src/backends/telemetry.d.ts interface TelemetryBackend { readonly kind: string; healthCheck(): Promise; capabilities(): BackendCapabilities; listServices(query?: ServiceQuery): Promise; listOperations(service: string): Promise; searchTraces(query: TraceSearchQuery): Promise; searchSpans(query: SpanSearchQuery): Promise; getTrace(traceId: string): Promise; serviceMap(lookbackMinutes?: number, limit?: number): Promise; summarizeTrace(traceId: string): Promise; listMetrics(query?: MetricSearchQuery): Promise; getMetricSeries(name: string, query?: MetricSeriesQuery): Promise; searchLogs(query?: LogSearchQuery): Promise; getCorrelatedSignals(traceId: string): Promise; /** * Where a human opens this trace in the backend's own UI, so an agent's * claim can be checked in one click. `undefined` when there is no UI. */ traceUrl?(traceId: string): string | undefined; /** * Aggregates computed by the backend over every matching span, not a * sample. Rows carry no first/last seen. Absent, or `undefined` for a query * the backend cannot honour in full, means the caller samples spans and * aggregates them itself. */ aggregateSpans?(query: SpanAggregateQuery): Promise; /** * Stored issues, with status, for backends that keep issue state (devtools). * `undefined` means "not supported here": callers group issues themselves. */ listIssues?(query: IssueListQuery): Promise; /** * Coding-agent token and cost usage (devtools, from Claude Code / Codex / * opencode telemetry). `undefined` means this backend does not keep it. */ agentUsage?(query: AgentUsageQuery): Promise; /** * Received telemetry checked against upstream semantic conventions (devtools, * through `weaver`). `run` starts a fresh check; otherwise the latest result. * `undefined` means this backend does not validate. */ semconvValidation?(run: boolean): Promise; } interface SpanAggregateQuery extends SpanSearchQuery { groupBy?: string[]; /** Counts only: skip the latency measures and the error request. */ countOnly?: boolean; } interface AgentUsageQuery { session?: string; prompt?: string; repository?: string; agent?: string; latest?: 'session' | 'prompt'; } interface IssueListQuery { service?: string; start: number; end: number; quietMs: number; } //#endregion //#region src/app.d.ts interface App { config: AppConfig; backend: TelemetryBackend; /** The MCP revision this build speaks. */ protocolVersion: string; /** The newest 2025-era revision the SDK's legacy path still answers. */ legacyProtocolVersion: string; /** * Builds a server instance. Protocol 2026-07-28 has no handshake and no * session, so an instance holds nothing worth keeping between requests and * the HTTP entry calls this per request; stdio calls it per connection. */ createServer: McpServerFactory; start(): Promise; stop(): Promise; } interface CreateAppOptions { /** * Command-line flags to apply over the environment. The CLI passes * `process.argv.slice(2)`; embedders leave this empty and configure through * the environment, or pass `config` directly. */ argv?: readonly string[]; env?: Env; /** Skips resolution entirely when you already have a config. */ config?: AppConfig; } export declare function createApp(options?: CreateAppOptions): Promise; //#endregion //#region src/backends/factory.d.ts interface BackendHandle { backend: TelemetryBackend; start: () => Promise; stop: () => Promise; } export declare function createBackend(config: AppConfig): Promise; //#endregion //#region src/tools/shared.d.ts declare const traceQuerySchema: z.ZodObject<{ from: z.ZodOptional; to: z.ZodOptional; serviceName: z.ZodOptional; operationName: z.ZodOptional; lookbackMinutes: z.ZodOptional>; limit: z.ZodOptional>; errorOnly: z.ZodOptional; statusCode: z.ZodOptional>; minDurationMs: z.ZodOptional>; maxDurationMs: z.ZodOptional>; genAiSystem: z.ZodOptional; genAiRequestModel: z.ZodOptional; genAiResponseModel: z.ZodOptional; tags: z.ZodOptional>>; filters: z.ZodOptional; valueType: z.ZodEnum<{ boolean: "boolean"; number: "number"; string: "string"; }>; value: z.ZodOptional>; values: z.ZodOptional>>; }, z.core.$strip>>>; }, z.core.$strip>; type TraceQueryInput = z.infer; type SpanQueryInput = TraceQueryInput & { minDurationMs?: number; maxDurationMs?: number; }; type MetricsQueryInput = { metricName?: string; serviceName?: string; lookbackMinutes?: number; from?: string; to?: string; limit?: number; }; type LogsQueryInput = { serviceName?: string; traceId?: string; spanId?: string; severityText?: string; text?: string; lookbackMinutes?: number; from?: string; to?: string; limit?: number; attributes?: Record; }; export declare function toTraceSearchQuery(input: TraceQueryInput): TraceSearchQuery; export declare function toSpanSearchQuery(input: SpanQueryInput): SpanSearchQuery; export declare function toMetricSearchQuery(input: MetricsQueryInput): MetricSearchQuery; export declare function toLogSearchQuery(input: LogsQueryInput): LogSearchQuery; //#endregion //#region src/modules/discovery.d.ts interface FieldDiscovery { totalFields: number; fieldsByType: FieldsByType; searchableFields: string[]; fieldDetails: Array<{ name: string; type: 'string' | 'number' | 'boolean'; occurrences: number; examples: Array; }>; } interface ServiceDiscoveryItem { name: string; signals: { traces: boolean; logs: boolean; metrics: boolean; }; stats: { traces: number; spans: number; errorSpans: number; logs: number; metrics: number; }; operations: string[]; metricNames: string[]; logSeverities: string[]; languages: string[]; } /** Discovered field names, grouped by the tag kind they carry. */ interface FieldsByType { string: string[]; number: string[]; boolean: string[]; } export declare function discoverTraceFields(traces: TraceRecord[], search?: string): FieldDiscovery; export declare function discoverLogFields(logs: LogRecord[], search?: string): FieldDiscovery; export declare function discoverServices(params: { services: string[]; traces: TraceRecord[]; logs: LogRecord[]; metrics: MetricSeries[]; }): ServiceDiscoveryItem[]; //#endregion //#region src/modules/anomaly.d.ts interface AnomalyQuery { service?: string; operation?: string; } interface AnomalyResult { type: 'latency_spike' | 'error_rate_spike' | 'traffic_drop'; service: string; description: string; severity: 'low' | 'medium' | 'high'; evidence: { current: number; baseline: number; threshold: number; }; affectedTraceIds: string[]; } export declare function detectAnomalies(traces: TraceRecord[], query: AnomalyQuery): AnomalyResult[]; //#endregion //#region src/modules/estimate.d.ts /** * Bad input, named so callers can map it to their own error surface — the CLI * turns it into an `AUTOTEL_E_INVALID_INPUT` envelope, the MCP tool into a * tool error. This module stays free of either. */ export declare class EstimateInputError extends Error { readonly field: string; readonly expected: string; constructor(field: string, expected: string, message: string); } interface EstimateBytes { /** One scattered log line, serialized with its envelope. */ logLine?: number; /** One canonical log line: the whole request as a single wide event. */ canonicalLine?: number; /** One exported span. */ span?: number; } interface EstimateInput { /** Requests the application serves per month. */ requestsPerMonth: number; /** Log lines written per request today, before canonical log lines. */ logLinesPerRequest?: number; /** Spans exported per request after instrumenting. */ spansPerRequest?: number; /** Traffic kept after sampling, 1–100. Applied to both shapes. */ keepPercent?: number; /** USD per gigabyte ingested. Required — this tool does not invent rates. */ perGb: number; /** USD per million events indexed. Zero for providers that only meter bytes. */ perMillionEvents?: number; /** Override the measured byte sizes with your own. */ bytes?: EstimateBytes; } interface EstimateTotals { events: number; gb: number; cost: number; } interface EstimateResult { currency: 'USD'; before: EstimateTotals; after: EstimateTotals; saved: number; savedPercent: number; basis: { logLineBytes: number; canonicalLineBytes: number; spanBytes: number; /** `measured` when the defaults were used, `caller` when overridden. */ bytesFrom: 'measured' | 'caller'; perGb: number; perMillionEvents: number; keepPercent: number; bytesPerGb: number; }; } export declare function estimateCost(input: EstimateInput): EstimateResult; //#endregion //#region src/modules/correlator.d.ts interface RootCauseResult { bottleneck: SpanRecord; reason: string; percentOfTrace: number; path: string[]; /** The bottleneck's own time, not spent waiting on child spans. */ selfTimeMs: number; /** Where the trace's time actually went, largest self time first. */ topSelfTime: Array<{ service: string; operation: string; spanId: string; selfTimeMs: number; }>; } export declare function findRootCause(trace: TraceRecord): RootCauseResult; //#endregion //#region src/modules/llm-analytics.d.ts interface UsageReport { totalRequests: number; totalPromptTokens: number; totalCompletionTokens: number; totalTokens: number; /** * Sum of priced requests only. Requests using a model absent from the * pricing catalog don't contribute; check `unpricedRequests` to spot * coverage gaps (typical cause: a new model name — add it to * AUTOTEL_LLM_PRICES_JSON). */ totalCostUsd: number; unpricedRequests: number; byModel: Record; byService: Record; } interface LlmModelSummary { model: string; provider: string | undefined; requestCount: number; firstSeenUnixMs: number; lastSeenUnixMs: number; } interface LlmModelStats { model: string; requestCount: number; successCount: number; errorCount: number; successRate: number; errorRate: number; durationMs: PercentileStats; tokens: { prompt: PercentileStats; completion: PercentileStats; total: PercentileStats; }; /** Total USD spend across priced requests. Zero if model is unpriced. */ costUsd: number; /** Published list prices per million tokens, or null if uncatalogued. */ inputPricePerMtok: number | null; outputPricePerMtok: number | null; finishReasons: Record | null; } interface PercentileStats { mean: number; median: number; p50: number; p95: number; p99: number; } interface LlmToolUsage { toolName: string; usageCount: number; services: string[]; firstSeenUnixMs: number; lastSeenUnixMs: number; } interface RankedTraceSummary { traceId: string; serviceName: string; operationName: string; startTimeUnixMs: number; durationMs: number; models: string[]; tokens: { prompt: number; completion: number; total: number; }; /** Priced spans only — unpriced spans don't contribute. */ costUsd: number; /** True if any LLM span in the trace couldn't be priced. */ hasUnpricedSpans: boolean; status: string; hasErrors: boolean; llmSpanCount: number; } export declare function collectUsage(traces: TraceRecord[]): UsageReport; export declare function listModels(traces: TraceRecord[]): LlmModelSummary[]; export declare function getModelStats(traces: TraceRecord[], modelName: string): LlmModelStats | null; export declare function rankExpensiveTraces(traces: TraceRecord[]): RankedTraceSummary[]; export declare function rankSlowTraces(traces: TraceRecord[]): RankedTraceSummary[]; export declare function listToolUsage(traces: TraceRecord[]): LlmToolUsage[]; //#endregion //#region src/modules/semantic-conventions.d.ts interface SemanticConvention { id: string; brief?: string; note?: string; } interface SemanticConventionFile { namespace: string; version: string; conventions: SemanticConvention[]; } export declare function listSemanticConventionNamespaces(forceRefresh?: boolean): Promise; export declare function getSemanticConventionNamespace(namespace: string): Promise; export declare function clearSemanticConventionCache(): void; //#endregion //#region src/modules/instrumentation.d.ts interface InstrumentationScore$1 { score: number; grade: 'A' | 'B' | 'C' | 'D' | 'F'; findings: string[]; } export declare function scoreSpan(span: Pick): InstrumentationScore$1; export declare function suggestInstrumentationFixes(span: Pick): string[]; //#endregion //#region src/modules/collector-config.d.ts type OtelCollectorValidationResult = { valid: true; summary: string; } | { valid: false; summary: string; issues: string[]; }; export declare function validateOtlpReceiverConfig(input: unknown): OtelCollectorValidationResult; export declare function suggestCollectorConfig(): string; //#endregion //#region src/modules/collector-catalog.d.ts type CollectorComponentKind = 'receiver' | 'processor' | 'exporter' | 'connector' | 'extension'; interface CollectorValidationResult { valid: boolean; summary: string; issues?: string[]; } export declare function listCollectorVersions(forceRefresh?: boolean): Promise; export declare function resolveCollectorVersion(version?: string): Promise; export declare function listCollectorComponents(version?: string, forceRefresh?: boolean): Promise>; export declare function getCollectorComponentSchema(kind: CollectorComponentKind, name: string, version?: string): Promise; export declare function getCollectorComponentReadme(kind: CollectorComponentKind, name: string, version?: string): Promise; export declare function validateCollectorComponentConfig(params: { kind: CollectorComponentKind; name: string; version?: string; config: unknown; }): Promise; export declare function refreshCollectorCatalog(): Promise<{ versions: number; latestVersion: string | null; components: Record; }>; //#endregion //#region src/modules/docs.d.ts export declare function buildCollectorGuide(): string; export declare function buildInstrumentationGuide(): string; export declare function buildCapabilitiesText(serverName: string): string; //#endregion //#region src/tools/diagnosis.d.ts /** * Extract the most informative error message from span tags. OTel * semantic conventions prefer `exception.message`, but real-world spans * carry errors under `error.message`, `otel.status_description`, or * domain-specific keys like `validation.error`. Exported so tests can * pin the precedence without spinning up an MCP server. */ export declare function pickErrorMessage(tags: Record): string | undefined; //#endregion export type { App, AppConfig, BackendCapabilities, BackendHandle, BackendHealth, CorrelatedSignals, EstimateBytes, EstimateInput, EstimateResult, EstimateTotals, FilterOperator, FilterValueType, InstrumentationScore, LogRecord, LogSearchQuery, LogSearchResult, LogsQueryInput, MetricPoint, MetricSearchQuery, MetricSearchResult, MetricSeries, MetricSeriesQuery, MetricsQueryInput, OperationListResult, QueryFilter, SearchResult, ServiceListResult, ServiceMap, ServiceMapEdge, ServiceMapNode, ServiceQuery, SignalSupport, SpanQueryInput, SpanRecord, SpanSearchQuery, SpanSearchResult, SpanStatusCode, TagValue, Tags, TelemetryBackend, TraceQueryInput, TraceRecord, TraceSearchQuery, TraceSearchResult, TraceSummary };