Skip to content

chore(api): steer MCP agents to builder tools over raw SQL - #3853

Open
brandon-pereira wants to merge 1 commit into
mainfrom
agent/mcp-builder-tool-steering
Open

brandon-pereira wants to merge 1 commit into
mainfrom
agent/mcp-builder-tool-steering

Conversation

@brandon-pereira

@brandon-pereira brandon-pereira commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Agents were reaching for clickstack_sql for work the builder tools already handle. The SQL fallback list named CTEs and subqueries broadly, so an agent could write a CTE for an aggregation and then cite that list as the reason for SQL. In a 14-day aggregate review of request intent across 212 teams, about 18% cited HAVING and about 37% said the builders could not extract JSON or regex.

The server instructions, clickstack_sql, and the shared builder-tool nudge now draw a sharper line. SQL is reserved for joins across sources or tables, window functions or per-row ordering, aggregation over an already-aggregated result, unregistered tables, and summary metrics. A shared "not reasons" list maps the common needs to the tool that covers them: HAVING, JSON/regex and derived fields, conditional counts and two-window comparisons, one trace with logs, and child-span time breakdowns. clickstack_table and clickstack_timeseries state their having, expression-valued groupBy/valueExpression, and per-item where support up front. Descriptions stay under the 2048-byte client limit.

No tool parameters or query behavior changed.

How to reproduce

Starting point: an MCP client connected to a ClickStack instance.

On main:

  1. Ask an agent to filter grouped results with HAVING, extract a JSON field, or compare counts across two windows. The generic CTE/subquery fallback wording invites raw SQL, while the builder descriptions only document HAVING and expression support in individual field schemas.

On this branch:

  1. Run the same prompts. The server instructions and tool descriptions name the builder tool for each need and reserve SQL for cases builders cannot express.

How to test on Vercel preview

N/A — non-UI change.

References

  • Aggregate review: 18% of 212 teams cited HAVING; 37% said builders could not extract JSON or regex (14-day window).

Note

Low Risk
Documentation and test-only changes to MCP tool descriptions and server instructions; no query execution or API parameter behavior changes.

Overview
Sharpens MCP copy only so agents default to builder query tools instead of clickstack_sql. Shared builderCatalog text now narrows when SQL is allowed (e.g. joins, window/per-row ordering, re-aggregation, unregistered tables, summary metrics) and drops vague CTE/subquery wording that justified SQL for simple aggregations.

Adds NOT_REASONS_TO_USE_SQL, surfaced in server instructions and the SQL tool description, mapping common needs (HAVING, JSON/expressions, per-item where, trace tools) to the right builder. clickstack_table and clickstack_timeseries descriptions now lead with having, expression groupBy/valueExpression, and per-select where before the “prefer builder over SQL” nudge.

Tests in toolDescriptions.test.ts lock metadata under the 2048-byte limit, assert the new SQL guidance (no “CTEs”), and check capability text ordering.

Reviewed by Cursor Bugbot for commit 4a3c76d. Bugbot is set up for automated code reviews on this repo. Configure here.

@brandon-pereira
brandon-pereira requested a review from a team as a code owner November 27, 2026 17:21
@vercel

vercel Bot commented Nov 27, 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 27, 2026 5:24pm UTC
hyperdx-storybook Ready Ready Preview Nov 27, 2026 5:24pm UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 27, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 4a3c76d

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 github-actions Bot added the review/tier-2 Low risk — AI review + quick human skim label Nov 27, 2026
@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: 74 (+ 73 in test files, excluded from tier calculation)
  • Branch: agent/mcp-builder-tool-steering
  • Author: brandon-pereira

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

Duplicate code analysis

No new duplicate code introduced by this PR.


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.10%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

@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.

2 finding(s): 🔴 0 P0/P1 · 🟡 1 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/prompts/dashboards/content.ts:85 — The create_dashboard prompt still tells agents to use raw SQL for "JOINs, sub-queries, CTEs, or expressions the builder does not generate" → This prompt is the one the server instructions tell agents to fetch. It still uses the broad wording this PR removes elsewhere. builderCatalog.ts says its shared strings exist so this guidance "can't drift apart", but this copy was never wired to them. Fix: build the line from SQL_FALLBACK_CRITERIA / NOT_REASONS_TO_USE_SQL (dashboard tiles support having and expression-valued groupBy too). Alternatively, add this prompt to the not.toContain('CTEs') check in toolDescriptions.test.ts.
🔵 1 P3 — no action needed before merge
  • 🔵 P3 packages/api/src/mcp/__tests__/toolDescriptions.test.ts:57 — The new SQL-guidance test mostly compares constants to their own literal text, and its CTE check is too narrow → The expect(SQL_FALLBACK_CRITERIA).toContain(...) and expect(NOT_REASONS_TO_USE_SQL).toContain(...) lines only repeat the constant's text, so any wording edit breaks them while a real regression still passes. not.toContain('CTEs') misses 'CTE', 'sub-queries' and the create_dashboard prompt (content.ts:85). Fix: drop the self-referential assertions. Instead, check each tool that NOT_REASONS_TO_USE_SQL names is actually registered with that parameter (e.g. clickstack_trace_waterfall has includeLogs, clickstack_table has having), and match a case-insensitive /\bCTEs?\b|sub-?quer/i across the instructions and every description and prompt.

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 issues found. This is a prose-only change to MCP tool descriptions and server instructions (plus tests); all factual capability claims in the new steering text were verified accurate against the live schemas (having, per-item where → <aggFn>If(...), includeLogs, clickstack_trace_top_time_consuming_ops, metricTables.summary). The items below are recommendations and nits.

🟡 P2 — recommended

  • packages/api/src/mcp/__tests__/toolDescriptions.test.ts:66 — PREFER_BUILDER_OVER_SQL_NUDGE is injected into six builder tools but ordering/presence is only asserted for clickstack_table and clickstack_timeseries, leaving the PR's central behavior untested on clickstack_search, clickstack_event_patterns, clickstack_event_deltas, and clickstack_service_health.
    • Fix: Add a data-driven assertion that every nudge-bearing tool's description contains PREFER THIS over clickstack_sql.
  • .changeset/ — no changeset accompanies this behavior-affecting @hyperdx/api change, which AGENTS.md item 7 requires for user-facing/behavior changes to a published package (precedent: .changeset/mcp-strict-tool-arguments.md).
    • Fix: Add a @hyperdx/api: patch changeset, or confirm with a maintainer that MCP steering text falls under the docs/tooling carve-out.
🔵 P3 nitpicks (6)
  • packages/api/src/mcp/mcpServer.ts:36 — the header NOT reasons to use SQL — builders cover these needs: is hand-written verbatim in both mcpServer.ts:36 and sql.ts:112 while only the bullet body is shared, so it can drift despite the module comment claiming these strings cannot.
    • Fix: Source the header from a shared constant alongside NOT_REASONS_TO_USE_SQL.
  • packages/api/src/mcp/tools/query/sql.ts:107 — the "Default to builder tools…" lead-in is duplicated against mcpServer.ts:27 and has already drifted (builder tools vs builder query tools).
    • Fix: Extract a shared preamble constant for the reliability/chart-ready claim.
    • maintainability, testing
  • packages/api/src/mcp/tools/query/builderCatalog.ts:28 — NOT_REASONS_TO_USE_SQL maps HAVING only to clickstack_table, but clickstack_timeseries exposes no having, so an agent needing per-bucket HAVING over time is steered away from SQL with no builder that covers it.
    • Fix: Scope the mapping to aggregate tables or note that HAVING combined with a time bucket is a legitimate SQL fallback.
  • packages/api/src/mcp/__tests__/toolDescriptions.test.ts:57 — assertions on lines 57–63 check that each shared constant contains substrings of its own literal definition, restating the source rather than verifying wiring already covered by the toContain(SQL_FALLBACK_CRITERIA) checks.
    • Fix: Drop the self-referential substring checks or keep only as an explicit change-detector.
  • packages/api/src/mcp/__tests__/toolDescriptions.test.ts:90 — the ordering test matches exact phrases like "having" filters aggregated groups, so benign rewording breaks it even though the capabilities-before-nudge intent is unchanged.
    • Fix: Match on shorter stable tokens (e.g. "having", valueExpression) to track ordering rather than prose.
  • packages/api/src/mcp/__tests__/toolDescriptions.test.ts:27 — the 2048-byte limit test never builds the PromQL-enabled instructions variant (isPromqlEnabled is off under test), so the largest client-visible string, which this PR grows, is unmeasured.
    • Fix: Add a case with PromQL enabled asserting the combined instructions stay within CLAUDE_CODE_METADATA_LIMIT.

Reviewers (4): correctness, testing, maintainability, project-standards.

Testing gaps:

  • No test cross-checks that the tools/params named in NOT_REASONS_TO_USE_SQL still exist in the registered schema, so a future rename would silently make the steering prose inaccurate.
  • No test verifies BUILDER_TOOLS_LIST bullets correspond to actually-registered tool names.

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

@github-actions

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 480 passed • 1 skipped • 1069s

Status Count
✅ Passed 480
❌ Failed 0
⚠️ Flaky 11
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

This branch was successfully deployed

2 active deployments
Preview – hyperdx-oss — 4a3c76df Deployed Nov 27, 2026 by vercel[bot]
Preview – hyperdx-storybook — 4a3c76df Deployed Nov 27, 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