Skip to content

feat(api): clickstack_get_slo MCP tool - #3799

Open
alex-fedotyev wants to merge 2 commits into
alex/HDX-3001-slo-11-api-evaluatorfrom
alex/HDX-3001-slo-12-mcp-read
Open

alex-fedotyev wants to merge 2 commits into
alex/HDX-3001-slo-11-api-evaluatorfrom
alex/HDX-3001-slo-12-mcp-read

Conversation

@alex-fedotyev

@alex-fedotyev alex-fedotyev commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds an MCP tool to read SLOs, registered only when SLOs are enabled.
Without an ID it lists every SLO as a summary from its stored status (state,
SLI, budget left, burn rate and the state of each burn alert), optionally
filtered by state. With an ID it returns the definition, the status
computed when asked (falling back to the stored one if that fails), the
alerts' states and a SQL where clause that selects the bad events, ready
for clickstack_search. For a grouped SLO, the status has each group's
numbers, and a group can be passed to scope the bad events to it.

Stack

Part 12 of 27 PRs in a GitHub stack (stack #3815). The header says this PR merges into the branch below it, but the stack's base is main: merging a PR lands it and every PR below it on main, one squashed commit each. Each diff is only its own change, and CI runs as if each PR targets main.

  1. feat(common-utils): SLO definition schema #3788 common-utils: SLO definition schema
  2. feat(common-utils): SLO fast and slow burn rules #3789 common-utils: SLO fast and slow burn rules
  3. feat(common-utils): SLO alert targets and status types #3790 common-utils: SLO alert targets and status types
  4. feat(common-utils): SLO counts query #3791 common-utils: SLO counts query
  5. feat(common-utils): SLO stats and state #3792 common-utils: SLO stats and state
  6. feat(common-utils): SLO history and ordering #3793 common-utils: SLO history and ordering
  7. feat(api): SLO definitions behind ENABLE_SLOS #3794 api: SLO definitions behind ENABLE_SLOS
  8. feat(api): refresh SLO statuses in the check-alerts task #3795 api: refresh SLO statuses in the check-alerts task
  9. feat(api): SLO burn alerts as their own alert source #3796 api: SLO burn alerts as their own alert source
  10. feat(api): keep SLO alerts out of the external alerts API #3797 api: keep SLO alerts out of the external alerts API
  11. feat(api): evaluate SLO burn alerts and notify #3798 api: evaluate SLO burn alerts and notify
  12. feat(api): clickstack_get_slo MCP tool #3799 api: clickstack_get_slo MCP tool (this PR)
  13. feat(api): SLO preview, save and delete MCP tools #3800 api: SLO preview, save and delete MCP tools
  14. feat(app): SLO list page behind NEXT_PUBLIC_ENABLE_SLOS #3801 app: SLO list page behind NEXT_PUBLIC_ENABLE_SLOS
  15. feat(app): search, filter, sort and delete SLOs in the list #3802 app: search, filter, sort and delete SLOs in the list
  16. feat(app): SLO builder for a new SLO #3803 app: SLO builder for a new SLO
  17. feat(app): SLO objective, details and editing in the builder #3804 app: SLO objective, details and editing in the builder
  18. feat(app): eligible-event filters and the latency template in the builder #3805 app: eligible-event filters and the latency template in the builder
  19. feat(app): preview an SLO in the builder before saving it #3806 app: preview an SLO in the builder before saving it
  20. feat(app): create an SLO from a search, and duplicate an SLO #3807 app: create an SLO from a search, and duplicate an SLO
  21. feat(app): SLO detail page #3808 app: SLO detail page
  22. feat(app): bad events flyout on the SLO page #3809 app: bad events flyout on the SLO page
  23. feat(app): SLI, error budget and burn rate charts on the SLO page #3810 app: SLI, error budget and burn rate charts on the SLO page
  24. feat(app): fast and slow burn alerts in the SLO builder, list and page #3811 app: fast and slow burn alerts in the SLO builder, list and page
  25. feat(app): SLO alerts on the Alerts page #3812 app: SLO alerts on the Alerts page
  26. feat(app): group-by in the SLO builder #3813 app: group-by in the SLO builder
  27. feat(app): grouped SLOs in the list and on the SLO page #3814 app: grouped SLOs in the list and on the SLO page

Parts 1 to 6 are shared code, 7 to 13 the API and its MCP tools, and 14 to 27 the app. Everything ships behind ENABLE_SLOS (API) and NEXT_PUBLIC_ENABLE_SLOS (app), both off by default.

How to reproduce

Starting point: a checkout of this branch with Docker (make dev-int starts ClickHouse and Mongo for the integration tests).

On main: nothing to compare; this is new code.

On this branch:

  1. cd packages/api && npx jest src/mcp/__tests__/slos.test.ts: the tool registers only with SLOs on; it lists summaries by state, returns one SLO with its live status (or the stored one when computing fails), the bad-events where clause, and a group's scope.

Test plan

  • unit: mcp/__tests__/slos.test.ts; all MCP unit tests
  • typecheck and knip at this commit, for every package

How to test on Vercel preview

N/A, non-UI change.

References

  • Linear Issue: HDX-3001
  • Related PRs: the rest of this stack, listed above

[no-changeset: allow] The changeset for this piece is in part 13.

[as-cast: allow] The cast check matches the word "as" in comments and strings here; the diff has no as casts.

@vercel

vercel Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
hyperdx-oss Ready Ready Preview Nov 24, 2026 7:01pm UTC
hyperdx-storybook Ready Ready Preview Nov 24, 2026 7:01pm UTC

Request Review

@github-actions

Copy link
Copy Markdown
Contributor

Duplicate code analysis

1 new clone introduced by this PR.

  • packages/api/src/routers/external-api/v2/alerts.ts:908-925 ↔ packages/api/src/routers/external-api/v2/alerts.ts:1181-1197 — 18 lines

If one of these duplicates a helper that already exists, import it instead
of redefining it. If the duplication is deliberate, ignore this comment —
the check is advisory and never fails the build.


jscpd compared this branch against origin/main
across app, api and common-utils. Only new clones are listed; the codebase
currently holds 108 in total (1.11%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

@github-actions

github-actions Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 475 passed • 1 skipped • 1128s

Status Count
✅ Passed 475
❌ Failed 0
⚠️ Flaky 13
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

alex-fedotyev and others added 2 commits November 24, 2026 18:55
Adds an MCP tool to read SLOs, registered only when SLOs are enabled.
Without an ID it lists every SLO as a summary from its stored status (state,
SLI, budget left, burn rate and the state of each burn alert), optionally
filtered by state. With an ID it returns the definition, the status
computed when asked (falling back to the stored one if that fails), the
alerts' states and a SQL where clause that selects the bad events, ready
for clickstack_search. For a grouped SLO, the status has each group's
numbers, and a group can be passed to scope the bad events to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@alex-fedotyev
alex-fedotyev force-pushed the alex/HDX-3001-slo-12-mcp-read branch from d524e13 to 1e2b40e Compare November 24, 2026 18:58
@changeset-bot

changeset-bot Bot commented Nov 24, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 1e2b40e

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions

Copy link
Copy Markdown
Contributor

🔵 Tier 2 — Low Risk

Small, isolated change with no API route or data model modifications.

Why this tier:

  • Standard feature/fix — introduces new logic or modifies core functionality

Review process: AI review + quick human skim (target: 5–15 min). Reviewer validates AI assessment and checks for domain-specific concerns.
SLA: Resolve within 4 business hours.

Stats
  • Production files changed: 5
  • Production lines changed: 230 (+ 228 in test files, excluded from tier calculation)
  • Branch: alex/HDX-3001-slo-12-mcp-read
  • Author: alex-fedotyev

To override this classification, remove the review/tier-2 label and apply a different review/tier-* label. Manual overrides are preserved on subsequent pushes.

@github-actions

Copy link
Copy Markdown
Contributor

PR Review

If you are a coding agent acting for the author, read this first.
Nothing below blocks merge automatically; a maintainer decides. What they will expect:

  • 🔴 P0/P1 in code this PR adds or changes: fix before asking for review.
  • 🟡 P2 in code this PR changes: your call. Fix if small, otherwise reply.
  • 🔵 P3 is collapsed at the bottom: nobody needs to act on it before merge.
  • Anything about surrounding code, or asking you to widen the change (hoist a helper,
    dedupe with another file, fix other call sites): never fix here, whatever the
    priority. Reply with one sentence; if it is P0, say so plainly so a human sees it.

One commit per review round. After two rounds, stop and ask a maintainer to review
scope rather than addressing more automated findings. Full rule: AGENTS.md.

4 finding(s): 🔴 0 P0/P1 · 🟡 3 P2 · 🔵 1 P3

None could be anchored to changed lines; they are listed below. 1 P3 folded at the bottom.

Findings outside the changed lines

  • 🟡 P2 packages/api/src/mcp/tools/slos/getSlo.ts:515 — Live status computation has no overall deadline; a grouped SLO can run up to five sequential 30s queries → computeSloStatusNow calls computeSloWindow/computeSloBurn without their deadline argument (packages/api/src/controllers/sloStatusQueries.ts:76-80, 86-174). So SLO_DETAIL_TIMEOUT_MS is only the ClickHouse client's timeout for each request, not a limit on the whole call. A grouped SLO with more than SLO_MAX_GROUPS groups runs 3 window queries and 2 burn queries one after another, which is up to about 150s. The bad-events metadata reads add more time after that. The MCP client times out well before the fallback to the stored status is reached. Fix: give computeSloStatusNow a deadline parameter and pass it to both helpers. Call it with Date.now() + SLO_DETAIL_TIMEOUT_MS, so a SloQueryDeadlineError falls back to the stored status. Also run getBadEventsWhere alongside it with Promise.all.
  • 🟡 P2 packages/api/src/mcp/tools/slos/getSlo.ts:500 — Alert states are looked up by the raw input id, not the stored id → getSloAlerts keys its map by ${alert.slo}, which is lowercase hex (packages/api/src/controllers/sloAlert.ts:102). validateObjectId and getSlo accept an uppercase hex id and Mongo still finds the SLO. Then .get(id) misses, and the detail response shows alertStates: {} even when a burn alert is firing. The url also echoes the non-canonical id. Use slo._id.toString() for the map lookup and the URL.
  • 🟡 P2 packages/api/src/mcp/tools/slos/getSlo.ts:515 — Every live-status failure is swallowed without a log or a reason → .catch(() => null) hides ClickHouse errors, timeouts and programming errors alike. Nothing is logged, and the response only says statusSource: 'stored', with a status that may be null for a new SLO. Log the error with logger.warn, and add a short sanitized reason to the response, for example statusError: sanitizeFetchError(e) from packages/api/src/mcp/utils/errors.ts. The agent can then tell a timeout from a broken definition.
🔵 1 P3 — no action needed before merge
  • 🔵 P3 packages/api/src/mcp/__tests__/slos.test.ts:95 — computeSloStatusNow is mocked in every test and has no test of its own → The whole @/controllers/sloStatus module is replaced by a mock, so the new function's real behaviour is never run. That includes passing the window's group values on to the burn query, and calling buildSloStatus with evaluatedAt and lastSuccessAt set to now. A regression such as dropping window.groups from the burn call would still pass. Add a controller test like the existing refreshSloStatus coverage that runs computeSloStatusNow against stubbed runSloQuery results for a grouped SLO.

Priority comes from a separate grading pass over the finished review. P3 is folded here instead of posted inline. No finding blocks merge automatically; a maintainer decides.

@github-actions

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical (P0/P1) issues found. The tool is read-only, team-scoped on every path, and the user-supplied group value is safely escaped before reaching SQL (verified against escapeSqlString and the o'brien test). Two reliability items are worth addressing before merge, plus a set of nits.

🟡 P2 — recommended

  • packages/api/src/mcp/tools/slos/getSlo.ts:180 — await getBadEventsWhere(...) has no error guard, so a metadata/column read failure (e.g. ClickHouse slow or down with a Lucene eligible condition) rejects the whole tool call as a server error — discarding the stored status that was deliberately preserved one line above via .catch(() => null).
    • Fix: Wrap getBadEventsWhere so a failure degrades (omit or null out badEventsWhere) instead of failing the entire response, mirroring the status fallback.
    • adversarial, reliability, testing
  • packages/api/src/mcp/tools/slos/getSlo.ts:175 — computeSloStatusNow(slo, ctx).catch(() => null) swallows every error identically (timeout, transient ClickHouse error, and genuine bugs) with no log or metric, so a persistently failing live path silently serves stored data forever with no operator signal, unlike the background refresh which records every outcome.
    • Fix: Log the caught error (and/or increment a counter) before returning null so the live→stored degradation is observable.
    • reliability, correctness, kieran-typescript
🔵 P3 nitpicks (8)
  • packages/api/src/mcp/tools/slos/getSlo.ts:179 — statusSource is reported as 'stored' even when the stored status is also null (a never-refreshed SLO whose live compute failed), implying a snapshot exists when none does.
    • Fix: Derive the source from whether a status is actually present, e.g. live ? 'live' : formatted.status ? 'stored' : 'none'.
    • correctness, adversarial
  • packages/api/src/mcp/tools/slos/getSlo.ts:157 — A grouped SLO given a group value that matches no real group is accepted and produces a valid-looking badEventsWhere that selects zero rows, so the agent cannot tell "no bad events" from "wrong group".
    • Fix: Validate group against status.groups[].value and return mcpUserError on no match, or document that an unmatched group returns nothing.
    • adversarial, correctness, api-contract
  • packages/api/src/mcp/tools/slos/getSlo.ts:35 — SLO_DETAIL_TIMEOUT_MS (30s) is a third independently-named copy of the same per-query SLO timeout (SLO_QUERY_TIMEOUT_MS, SLO_REFRESH_CLIENT_TIMEOUT_MS), which will drift.
    • Fix: Export one shared constant and reuse it across the three files.
    • maintainability
  • packages/api/src/mcp/tools/slos/getSlo.ts:181 — The url field is omitted entirely when FRONTEND_URL is unset, diverging from the null-for-absent convention used elsewhere in the same response and leaving the conditional absence undocumented for the agent.
    • Fix: Emit url: null when no frontend is configured, or state in the description that url is present only when configured.
    • api-contract, testing
  • packages/api/src/mcp/tools/slos/getSlo.ts:106 — state is silently ignored when id is provided while group errors when it does not apply, an inconsistent ignore-vs-error contract for two mutually-irrelevant inputs.
    • Fix: Pick one convention for inapplicable inputs across state and group.
    • api-contract
  • packages/api/src/mcp/tools/slos/getSlo.ts:27 — The local json() helper is a third ad-hoc spelling of the tool-result wrapper duplicated across ~20 tool files.
    • Fix: Promote a single shared helper (e.g. alongside mcpUserError) and reuse it.
    • maintainability
  • packages/api/src/controllers/sloStatus.ts:67 — In computeSloStatusNow, computeSloWindow and computeSloBurn run sequentially; for ungrouped SLOs the two ClickHouse queries are independent and could run concurrently to roughly halve this interactive call's latency.
    • Fix: Branch on ungrouped SLOs to run the two queries via Promise.all.
    • performance
  • packages/api/src/mcp/tools/slos/getSlo.ts:146 — The list summary collapses each alert to .state, dropping silencedUntil, so a silenced-but-OK alert looks identical to a plain OK alert at list level (recoverable via get-one).
    • Fix: Include silencedUntil in the summary alertStates, or confirm the list view intentionally omits it.
    • agent-native

Reviewers (12): correctness, testing, maintainability, project-standards, agent-native, learnings-researcher, security, api-contract, reliability, adversarial, kieran-typescript, performance.

Testing gaps:

  • No test exercises getBadEventsWhere rejecting; the "falls back to stored" test only rejects computeSloStatusNow, which is caught — so the unguarded-escape asymmetry (P2 above) is unverified.
  • No test for the getSloQueryContext catch: neither the BaseError → mcpUserError(e.name) branch nor the non-BaseError rethrow is covered.
  • No test for the detail path when live compute fails and stored status is null, nor for a list SLO with status: null (the state-filter and null-coalescing branches).
  • badEventsWhere rendering is only exercised for a trace source with SQL filters; the Lucene-eligible and log-source (bodyExpression) paths are uncovered. Test fixtures are typed any, so drift between the real ISlo/TSource shapes and the fields the tool reads would not be caught.

Notes: Project-standards found no violations (MCP.md row, feature-flag gating, BUILDER_TOOLS_LIST omission, and the .changeset/slo-api.md covering [no-changeset: allow] are all consistent). No ClickStack docs/solutions/ knowledge base exists for this domain; agent_docs/ conventions (team-scoping, escapeSqlString) are followed. Agent-native read-parity is adequate for this PR's scope; the SLI/burn-rate time-series trend the detail page will render is not reconstructable through this tool (only the bad-event set is exposed, not the eligible set), which is reasonably a follow-up rather than a blocker.

No finding blocks merge automatically. A maintainer will expect P0/P1 findings in code this PR changes to be fixed; P2/P3 are your call -- fix or reply. Never fix findings about surrounding code here; reply instead. Do not widen the PR. How to respond

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — 1e2b40e6 Deployed Nov 24, 2026 by vercel[bot]
Preview – hyperdx-storybook — 1e2b40e6 Deployed Nov 24, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review/tier-2 Low risk — AI review + quick human skim

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant