Repository navigation
feat(mcp): add clickstack_service_health tool #3411
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
4250e5c
feat(mcp): add clickstack_service_health tool
brandon-pereira 51c4003
fix(mcp): fit service health description in the 2048-byte limit and d…
brandon-pereira b0c5527
fix(mcp): find novel errors beyond the top N and stop double-counting…
brandon-pereira 304c0fa
chore: update service health changeset
brandon-pereira 40cb7cb
fix(mcp): flag incomplete novelty checks and keep service health lint…
brandon-pereira 80b488a
perf(mcp): build each result row's column map once (deep-review P3)
brandon-pereira 5001c46
test(mcp): cover service health comparison fallback and new-operation…
brandon-pereira e73937d
test(mcp): build a typed context instead of an eslint-disable cast (r…
brandon-pereira a2e368a
fix(mcp): match error groups across windows by hash and reuse the sha…
brandon-pereira 65514af
refactor(mcp): move the error-group query out of queries.ts to stay u…
brandon-pereira 9767585
test(mcp): cover the table-name sourceId hint; reuse SERVICE_ALIAS (r…
brandon-pereira 94c88d9
fix(mcp): zero the score of low-volume services; only name a source w…
brandon-pereira 9114430
fix(mcp): call a long error trickle intermittent instead of a transie…
brandon-pereira 18c6c82
fix(mcp): describe spread-out errors by what was observed (greptile P2)
brandon-pereira f0b1f96
refactor(mcp): drop materialized-view support from service health
brandon-pereira b11c5c3
Merge branch 'main' into brandon/brandon-mcp-service-health-tool
kodiakhq[bot] a8783c7
Merge branch 'main' into brandon/brandon-mcp-service-health-tool
kodiakhq[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| '@hyperdx/api': minor | ||
| '@hyperdx/common-utils': patch | ||
| '@hyperdx/app': patch | ||
| --- | ||
|
|
||
| feat(mcp): add `clickstack_service_health`, a one-call per-service health report for a trace source (throughput, error rate, p50/p95/p99, top error groups), compared with yesterday and ranked worst first |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
295 changes: 295 additions & 0 deletions
295
packages/api/src/mcp/__tests__/serviceHealthTool.int.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,295 @@ | ||
| import { SourceKind } from '@hyperdx/common-utils/dist/types'; | ||
| import { Client } from '@modelcontextprotocol/sdk/client/index.js'; | ||
|
|
||
| import * as config from '@/config'; | ||
| import { | ||
| bulkInsertData, | ||
| DEFAULT_DATABASE, | ||
| DEFAULT_LOGS_TABLE, | ||
| DEFAULT_TRACES_TABLE, | ||
| getLoggedInAgent, | ||
| getServer, | ||
| } from '@/fixtures'; | ||
| import { McpContext } from '@/mcp/tools/types'; | ||
| import Connection from '@/models/connection'; | ||
| import { Source, type SourceDocument } from '@/models/source'; | ||
|
|
||
| import { callTool, createTestClient, getFirstText } from './mcpTestUtils'; | ||
|
|
||
| const TOOL = 'clickstack_service_health'; | ||
| const HOUR = 60 * 60 * 1000; | ||
| // ClickHouse is shared across tests and files, so scope every query to this | ||
| // run's services. | ||
| const RUN = `sh${Date.now()}`; | ||
| const svc = (name: string) => `${RUN}-${name}`; | ||
|
|
||
| type Span = { | ||
| ServiceName: string; | ||
| SpanKind?: string; | ||
| durationMs?: number; | ||
| error?: string; | ||
| }; | ||
|
|
||
| type ServiceReport = { | ||
| service: string; | ||
| status: string; | ||
| flags: string[]; | ||
| current: { | ||
| requests: number; | ||
| errors: number; | ||
| errorRate: number; | ||
| p95Ms: number; | ||
| }; | ||
| comparison?: { requests: number; errors: number } | null; | ||
| topErrors: { | ||
| group: Record<string, string>; | ||
| count: number; | ||
| comparisonCount?: number; | ||
| status?: string; | ||
| }[]; | ||
| }; | ||
|
|
||
| describe('MCP Service Health Tool', () => { | ||
| const server = getServer(); | ||
| let client: Client; | ||
| let traceSource: SourceDocument; | ||
| let logSource: SourceDocument; | ||
| const now = Date.now(); | ||
|
|
||
| async function insertSpans(windowStart: number, spans: Span[]) { | ||
| await bulkInsertData( | ||
| `${DEFAULT_DATABASE}.${DEFAULT_TRACES_TABLE}`, | ||
| spans.map((s, i) => ({ | ||
| // Spread across the first 50 minutes of the window. | ||
| Timestamp: new Date(windowStart + ((i * 30_000) % (50 * 60_000))), | ||
| TraceId: `trace-${windowStart}-${i}`, | ||
| SpanId: `span-${windowStart}-${i}`, | ||
| ParentSpanId: '', | ||
| SpanName: 'GET /api', | ||
| SpanKind: s.SpanKind ?? (i % 2 ? 'Server' : 'SPAN_KIND_SERVER'), | ||
| ServiceName: s.ServiceName, | ||
| Duration: (s.durationMs ?? 100) * 1e6, | ||
| // Both error spellings must count. | ||
| StatusCode: s.error ? (i % 2 ? 'Error' : 'STATUS_CODE_ERROR') : 'Ok', | ||
| StatusMessage: s.error ?? '', | ||
| SpanAttributes: {}, | ||
| ResourceAttributes: {}, | ||
| })), | ||
| ); | ||
| } | ||
|
|
||
| const repeat = (n: number, s: Span): Span[] => | ||
| Array.from({ length: n }, () => s); | ||
|
|
||
| beforeAll(async () => { | ||
| await server.start(); | ||
| }); | ||
|
|
||
| beforeEach(async () => { | ||
| const { team, user } = await getLoggedInAgent(server); | ||
| const connection = await Connection.create({ | ||
| team: team._id, | ||
| name: 'Default', | ||
| host: config.CLICKHOUSE_HOST, | ||
| username: config.CLICKHOUSE_USER, | ||
| password: config.CLICKHOUSE_PASSWORD, | ||
| }); | ||
| logSource = await Source.create({ | ||
| kind: SourceKind.Log, | ||
| team: team._id, | ||
| from: { databaseName: DEFAULT_DATABASE, tableName: DEFAULT_LOGS_TABLE }, | ||
| timestampValueExpression: 'Timestamp', | ||
| connection: connection._id, | ||
| name: 'Logs', | ||
| }); | ||
| traceSource = await Source.create({ | ||
| kind: SourceKind.Trace, | ||
| team: team._id, | ||
| from: { databaseName: DEFAULT_DATABASE, tableName: DEFAULT_TRACES_TABLE }, | ||
| timestampValueExpression: 'Timestamp', | ||
| connection: connection._id, | ||
| name: 'Traces', | ||
| traceIdExpression: 'TraceId', | ||
| spanIdExpression: 'SpanId', | ||
| parentSpanIdExpression: 'ParentSpanId', | ||
| spanNameExpression: 'SpanName', | ||
| spanKindExpression: 'SpanKind', | ||
| durationExpression: 'Duration', | ||
| durationPrecision: 9, | ||
| serviceNameExpression: 'ServiceName', | ||
| statusCodeExpression: 'StatusCode', | ||
| statusMessageExpression: 'StatusMessage', | ||
| }); | ||
| const context: McpContext = { | ||
| teamId: team._id.toString(), | ||
| userId: user._id.toString(), | ||
| }; | ||
| client = await createTestClient(context); | ||
| }); | ||
|
|
||
| afterEach(async () => { | ||
| await client.close(); | ||
| await server.clearDBs(); | ||
| }); | ||
|
|
||
| afterAll(async () => { | ||
| await server.stop(); | ||
| }); | ||
|
|
||
| const call = (args: Record<string, unknown> = {}) => | ||
| callTool(client, TOOL, { | ||
| sourceId: traceSource._id.toString(), | ||
| startTime: new Date(now - HOUR).toISOString(), | ||
| endTime: new Date(now).toISOString(), | ||
| where: `startsWith(ServiceName, '${RUN}')`, | ||
| whereLanguage: 'sql', | ||
| ...args, | ||
| }); | ||
|
|
||
| const parse = (result: Awaited<ReturnType<typeof call>>) => { | ||
| expect(result.isError).toBeFalsy(); | ||
| const body: { | ||
| summary: Record<string, unknown>; | ||
| services: ServiceReport[]; | ||
| } = JSON.parse(getFirstText(result)); | ||
| return body; | ||
| }; | ||
|
|
||
| it('is listed with its input schema', async () => { | ||
| const { tools } = await client.listTools(); | ||
| const tool = tools.find(t => t.name === TOOL); | ||
| expect(tool?.inputSchema.required).toEqual(['sourceId']); | ||
| expect(Object.keys(tool?.inputSchema.properties ?? {})).toEqual( | ||
| expect.arrayContaining([ | ||
| 'comparison', | ||
| 'spanKind', | ||
| 'errorGroupBy', | ||
| 'topN', | ||
| ]), | ||
| ); | ||
| }); | ||
|
|
||
| it('rejects non-trace sources', async () => { | ||
| const result = await call({ sourceId: logSource._id.toString() }); | ||
| expect(result.isError).toBe(true); | ||
| expect(getFirstText(result)).toContain('kind="trace"'); | ||
| }); | ||
|
|
||
| it('points a table name passed as sourceId at the right source ID', async () => { | ||
| const result = await call({ sourceId: DEFAULT_TRACES_TABLE }); | ||
| expect(result.isError).toBe(true); | ||
| expect(getFirstText(result)).toContain( | ||
| `sourceId:"${traceSource._id.toString()}"`, | ||
| ); | ||
| }); | ||
|
|
||
| it('rejects a window longer than the comparison shift', async () => { | ||
| const result = await call({ | ||
| startTime: new Date(now - 30 * HOUR).toISOString(), | ||
| }); | ||
| expect(result.isError).toBe(true); | ||
| expect(getFirstText(result)).toMatch(/overlap/); | ||
| }); | ||
|
|
||
| describe('with data in both windows', () => { | ||
| beforeAll(async () => { | ||
| const currentStart = now - HOUR; | ||
| const yesterdayStart = currentStart - 24 * HOUR; | ||
| await insertSpans(currentStart, [ | ||
| ...repeat(99, { ServiceName: svc('steady') }), | ||
| ...repeat(1, { ServiceName: svc('steady'), error: 'flaky' }), | ||
| // Internal error spans must not count with the default spanKind. | ||
| ...repeat(100, { | ||
| ServiceName: svc('steady'), | ||
| SpanKind: 'Internal', | ||
| error: 'internal', | ||
| }), | ||
| ...repeat(80, { ServiceName: svc('erroring') }), | ||
| ...repeat(15, { ServiceName: svc('erroring'), error: 'db timeout' }), | ||
| ...repeat(5, { ServiceName: svc('erroring'), error: 'auth failed' }), | ||
| ...repeat(100, { ServiceName: svc('slow'), durationMs: 600 }), | ||
| ]); | ||
| await insertSpans(yesterdayStart, [ | ||
| ...repeat(99, { ServiceName: svc('steady') }), | ||
| ...repeat(1, { ServiceName: svc('steady'), error: 'flaky' }), | ||
| ...repeat(99, { ServiceName: svc('erroring') }), | ||
| ...repeat(1, { ServiceName: svc('erroring'), error: 'db timeout' }), | ||
| ...repeat(100, { ServiceName: svc('slow'), durationMs: 100 }), | ||
| ]); | ||
| }); | ||
|
|
||
| it('ranks regressions first and leaves steady services healthy', async () => { | ||
| const { summary, services } = parse(await call()); | ||
| expect(services.map(s => [s.service, s.status])).toEqual([ | ||
| [svc('erroring'), 'critical'], | ||
| [svc('slow'), 'degraded'], | ||
| [svc('steady'), 'healthy'], | ||
| ]); | ||
| expect(services[0].flags).toEqual( | ||
| expect.arrayContaining(['error_rate_up', 'high_error_rate']), | ||
| ); | ||
| expect(services[1].flags).toContain('latency_up'); | ||
| expect(services[1].current.p95Ms).toBeCloseTo(600, -1); | ||
| expect(summary.statusCounts).toEqual({ | ||
| critical: 1, | ||
| degraded: 1, | ||
| healthy: 1, | ||
| }); | ||
| }); | ||
|
|
||
| it('counts server spans only by default', async () => { | ||
| const { services } = parse(await call()); | ||
| const steady = services.find(s => s.service === svc('steady')); | ||
| expect(steady?.current.requests).toBe(100); | ||
| expect(steady?.current.errors).toBe(1); | ||
|
|
||
| const all = parse(await call({ spanKind: 'all' })); | ||
| expect( | ||
| all.services.find(s => s.service === svc('steady'))?.current.requests, | ||
| ).toBe(200); | ||
| }); | ||
|
|
||
| it('tags error groups as new or growing against the comparison', async () => { | ||
| const { services } = parse(await call()); | ||
| expect(services[0].topErrors).toEqual([ | ||
| expect.objectContaining({ | ||
| group: { SpanName: 'GET /api', StatusMessage: 'db timeout' }, | ||
| count: 15, | ||
| comparisonCount: 1, | ||
| status: 'growing', | ||
| }), | ||
| expect.objectContaining({ | ||
| group: { SpanName: 'GET /api', StatusMessage: 'auth failed' }, | ||
| count: 5, | ||
| comparisonCount: 0, | ||
| status: 'new', | ||
| }), | ||
| ]); | ||
| // Spans are spread over the first 50 minutes, so nothing is ongoing. | ||
| const first = services[0].topErrors[0] as Record<string, unknown>; | ||
| expect(Date.parse(String(first.firstSeen))).toBeLessThan( | ||
| Date.parse(String(first.lastSeen)), | ||
| ); | ||
| expect(first.ongoing).toBe(false); | ||
| }); | ||
|
|
||
| it('accepts a custom errorGroupBy', async () => { | ||
| const { services } = parse(await call({ errorGroupBy: 'StatusMessage' })); | ||
| expect(services[0].topErrors[0].group).toEqual({ | ||
| StatusMessage: 'db timeout', | ||
| }); | ||
| }); | ||
|
|
||
| it('omits comparisons with comparison:none', async () => { | ||
| const { summary, services } = parse(await call({ comparison: 'none' })); | ||
| expect(summary.comparisonWindow).toBeNull(); | ||
| expect(services[0].comparison).toBeUndefined(); | ||
| expect(services[0].topErrors[0].status).toBeUndefined(); | ||
| }); | ||
|
|
||
| it('filters to the requested services', async () => { | ||
| const { services } = parse(await call({ services: [svc('slow')] })); | ||
| expect(services.map(s => s.service)).toEqual([svc('slow')]); | ||
| }); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔵 minor — Integration test never runs the comparison fallback, new-operation detection, or the novelty lift against real ClickHouse
Every seeded span is named 'GET /api' and both windows have data, so
findNewOperationsalways returns empty andresolveComparisonalways returns the requested window. A regression that broke the operations SQL, or made the fallback never fire, would still pass. The unit tests stub these inputs (newOperations: new Map()). Fix: add an int case that seeds a span name present only in the current window and checksnewOperationsplusstatus:'new_operation'. Add another case with no yesterday data that checkssummary.comparison === 'previous_period'andcomparisonNote.Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond