Skip to content

refactor(api): resolve MCP sources through one helper - #3771

Merged
kodiakhq[bot] merged 2 commits into
mainfrom
claude/mcp-source-lookup-helper
Nov 23, 2026
Merged

kodiakhq[bot] merged 2 commits into
mainfrom
claude/mcp-source-lookup-helper

Conversation

@brandon-pereira

Copy link
Copy Markdown
Member

Summary

MCP tools and prompts each looked up sources themselves, calling getSource / getSources directly at about 16 places. A few of them also applied isHiddenSource on their own. So no single place decided which sources an MCP caller can see, and any visibility rule had to be copied into each tool.

Every MCP source lookup now goes through packages/api/src/mcp/utils/sources.ts. This makes it the single extension point for source resolution in the MCP server, the same way #3752 did for ClickHouse clients.

Helper Wraps Used where
getMcpSource(context, id) getSource(context.teamId, id) tools that never hid sources
getMcpSources(context) getSources(context.teamId) tools that never hid sources
getVisibleMcpSources(context) getMcpSources + isHiddenSource filter listSources, create_dashboard prompt
getVisibleMcpSource(context, id) getMcpSource, null when hidden describeSource, deleteSource

Places that hid sources before still hide them, and places that didn't still don't. Return values, null-on-not-found, error messages and tool output are unchanged.

A few internal functions (createSourceLookup, loadHealthSource, getReferenceTargets, validateCorrelatedSourceIds, the metric describe/list implementations) now take McpContext instead of teamId, so they can call the helpers. teamId variables left unused by that change are removed.

One small difference: clickstack_delete_source now returns "Source not found" for a missing source before calling deleteSource, rather than after deleteSource returns null. The output is the same.

No changeset, since this is an internal refactor with no user-facing change.

How to test

  • mcpSources.test.ts covers the helpers: team scoping, null on not found, and which sources get hidden while PromQL is off or on.
  • make ci-lint passes.
  • cd packages/api && yarn ci:unit: 1643 tests passed.
  • make dev-int FILE=src/mcp/__tests__: 23 test files, 636 tests passed.

References

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

vercel Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

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

2 Skipped Deployments
Project Deployment Actions Updated
hyperdx-oss Ignored Ignored Preview Nov 23, 2026 6:29pm UTC
hyperdx-storybook Ignored Ignored Preview Nov 23, 2026 6:29pm UTC

Request Review

@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: ed059ce

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 23, 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: 23
  • Production lines changed: 178 (+ 83 in test files, excluded from tier calculation)
  • Branch: claude/mcp-source-lookup-helper
  • 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

1 new clone introduced by this PR.

  • packages/api/src/mcp/tools/trace/breakdown.ts:76-92 ↔ packages/api/src/mcp/tools/trace/waterfall.ts:343-358 — 17 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 107 in total (1.12%).
Run yarn dupes locally to reproduce, or yarn dupes:all for the full picture.

@github-actions

Copy link
Copy Markdown
Contributor

PR Review

✅ No issues found.

@github-actions

Copy link
Copy Markdown
Contributor

Deep Review

✅ No critical issues found.

This is a behavior-preserving internal refactor. McpContext.teamId is typed string and getSource/getSources take a string, so every former teamId.toString() call site passed the same value context.teamId now carries — the substitution is type-safe with no value change. The clickstack_delete_source and describeSource rewrites were checked case-by-case (missing / hidden / visible source) and produce identical outcomes and error strings. getVisibleMcpSource's source && !isHiddenSource(...) ? source : null handles the null-source case correctly. All internal callers of the signature-changed functions (createSourceLookup, loadHealthSource, getReferenceTargets, validateCorrelatedSourceIds) were updated in-diff, and the one out-of-diff test (queryTilesHandler.test.ts) mocks getReferenceTargets argument-agnostically, so the signature change does not break it. Per-call-site hiding behavior matches pre-diff: listSources/describeSource/deleteSource/create-dashboard prompt filter hidden sources, the others preserve their prior non-filtering.

🟡 P2 -- recommended

  • packages/api/src/mcp/__tests__/mcpSources.test.ts:1 -- the new unit tests cover the four helpers in isolation, but nothing asserts which helper each of the ~16 converted call sites uses, and that per-site choice is exactly what this PR changes; a future swap of getMcpSource for getVisibleMcpSource (or vice versa) on an agent-reachable path would silently change source visibility with no failing test.
    • Fix: add a focused test per visibility-sensitive tool path (listSources, describeSource, deleteSource, the create-dashboard prompt) asserting a hidden PromQL source is excluded while PromQL is off.
🔵 P3 nitpicks (2)
  • packages/api/src/mcp/prompts/dashboards/index.ts:124 -- the two dashboard prompts deliberately call different helpers (getVisibleMcpSources for create-dashboard, getMcpSources for the query guide) with no inline note explaining why one hides PromQL sources and the other does not, inviting a future reader to "fix" the asymmetry.
    • Fix: add a one-line comment on the getMcpSources call stating the query-guide prompt intentionally includes hidden sources.
  • packages/api/src/mcp/__tests__/mcpSources.test.ts:64 -- getVisibleMcpSources/getVisibleMcpSource are never asserted to scope the lookup to context.teamId (only getMcpSource/getMcpSources are), so a regression dropping team scoping in the visible-variant path would go uncaught.
    • Fix: add a toHaveBeenCalledWith('team-1') assertion in the getVisibleMcpSources test.

Reviewers (6): correctness, maintainability, testing, kieran-typescript, api-contract, project-standards.

Testing gaps: No regression coverage tying each converted call site to its intended visibility helper; getVisible* team-scoping not directly asserted.

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

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

E2E Test Results

✅ All tests passed • 473 passed • 1 skipped • 1110s

Status Count
✅ Passed 473
❌ Failed 0
⚠️ Flaky 12
⏭️ Skipped 1

Tests ran across 4 shards in parallel.

View full report →

@kodiakhq
kodiakhq Bot merged commit 8eb4641 into main Nov 23, 2026
28 checks passed
@kodiakhq
kodiakhq Bot deleted the claude/mcp-source-lookup-helper branch November 23, 2026 18:36
kodiakhq Bot pushed a commit that referenced this pull request Nov 23, 2026
## Summary

MCP tools and prompts called the connection controller directly (`getConnectionsByTeam`, `getConnectionById`, `validateConnectionId`) from five places. This adds `mcp/utils/connections.ts` with three helpers that take the full `McpContext`:

- `getMcpConnections(context)`
- `getMcpConnection(context, connectionId, { selectPassword }?)`
- `validateMcpConnectionId(context, connectionId)`

Every MCP call site now uses them, including `getMcpClickhouseClient`. The rules about which connections an MCP caller can use now live in one place, matching how `mcp/utils/clickhouse.ts` and `mcp/utils/sources.ts` already work.

No behavior change: same return values, null when a connection is not found, and the same validation messages and tool output.

No changeset: internal refactor with no user-facing change.

### How to reproduce

**Starting point:** N/A, internal refactor with no user-visible change.

**Testing:**

1. `cd packages/api && yarn ci:unit` runs the new `src/mcp/__tests__/mcpConnections.test.ts` and the existing MCP unit tests, including the dashboard prompt tests.
2. `make dev-int FILE=src/mcp/__tests__` runs the MCP integration suites (sources, dashboards, saved searches and more): 23 suites, 636 tests pass.

### How to test on Vercel preview

N/A, non-UI change.

### References

- Related PRs: #3771 (same pattern for source lookups)
kodiakhq Bot pushed a commit that referenced this pull request Nov 24, 2026
…lper (#3777)

## Summary

Follow-up to #3776.

#3776 routed MCP connection lookups through `mcp/utils/connections.ts`. Two PromQL paths still skipped it, because they get their connection inside the shared `controllers/promql.ts`:

- PromQL tiles (`runPromqlTile`, via `resolvePromqlTarget`)
- PromQL `describe_source` (`describePromqlSource`, via `getPromqlLabelCatalog`)

This PR gives both controller functions an optional `getConnection` lookup. It defaults to the existing team-scoped `getConnectionById`, so the REST `/prometheus` router is unchanged. The MCP paths now take the full `McpContext` and pass `getMcpConnection`, so every MCP connection lookup goes through the helper. The comment in `connections.ts` drops the PromQL exception that #3776 added.

No behavior change: the same connection is found, the password is selected the same way, and the "Connection not found" errors are unchanged.

No changeset: internal refactor with no user-facing change.

### How to reproduce

**Starting point:** N/A, internal refactor with no user-visible change.

**Testing:**

1. `cd packages/api && yarn ci:unit` runs the new `controllers/__tests__/promqlConnectionLookup.test.ts` (default lookup, custom lookup, and not-found handling) and a new `describeSourceTimeout.test.ts` case that checks PromQL `describe_source` looks up connections through the MCP helper.
2. `make dev-int FILE="promql prometheus"` covers the MCP PromQL tools and tiles plus the REST `/prometheus` router: 5 suites, 189 tests pass. The full MCP integration suite (`make dev-int FILE=src/mcp/__tests__`) also passes: 23 suites, 636 tests.

### How to test on Vercel preview

N/A, non-UI change.

### References

- Related PRs: #3776, #3771 (same pattern for source lookups)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants