8000 Add opt-in Agents Schema context to run_query results by felipempleite · Pull Request #231 · ClickHouse/mcp-clickhouse · GitHub
[go: up one dir, main page]

Skip to content

Add opt-in Agents Schema context to run_query results - #231

Closed
felipempleite wants to merge 7 commits into
ClickHouse:mainfrom
felipempleite:agents-schema-discovery
Closed

felipempleite wants to merge 7 commits into
ClickHouse:mainfrom
felipempleite:agents-schema-discovery

Conversation

@felipempleite
@felipempleite felipempleite commented Aug 30, 2026 •
Copy link
Copy Markdown
Contributor

Summary

Adds opt-in reference context to successful run_query results: governed model descriptions from canonical AGENTS.DBT_MODEL, an AGENTS.ROOT discovery hint, and conditional engine guidance for ReplacingMergeTree and CollapsingMergeTree families, including Shared and Replicated variants.

Enable with CLICKHOUSE_MCP_AGENTS_SCHEMA_DISCOVERY=true before startup. Disabled servers retain the upstream response shape and tool description; server-wide MCP instructions are unchanged.

ClickHouse publishing is merged in dbt-labs/agents_schema#40. This consumer uses the standard's case-sensitive uppercase AGENTS.* names.

Why

A successful query can still produce misleading analysis if an agent misses the model's business definitions.

Returning relevant Agents Schema descriptions and engine warnings alongside query results helps agents interpret the data and recognize when a query needs refinement, without relying on them to discover metadata separately. The feature is opt-in, preserving existing behavior for deployments that do not need it.

Behavior and compatibility

  • Enrichment starts after the base result is complete and serialized. At most two enrichment jobs can be in flight per server, including jobs whose callers have timed out or cancelled. Busy servers return the base result immediately; otherwise callers wait up to three additional seconds. An already-started lookup can continue until its execution or network timeout.
  • All lookups use the caller's resolved ClickHouse configuration, including request-scoped roles and settings. Discovery, model descriptions, and engine checks fail independently without losing successful query rows.
  • Context queries request a two-second execution limit when permitted, preserving read-only timeout settings and stricter existing limits. Caller-wait and admission bounds also apply when the server-side timeout cannot be changed.
  • Discovery, current-database, and engine caches are server-owned, bounded, scoped to the complete configuration, and expire after five minutes. Uncacheable configurations bypass metadata caches. Descriptions are truncated to 300 Unicode characters in SQL before transfer.
  • Matching uses exact (database, table) pairs; bare names require a known current database. Clients with a stateful HTTP session skip all enrichment, including qualified references, so an optional lookup cannot occupy the session after the caller's wait ends and break a subsequent query. This also avoids temporary-table shadowing. Sessions are never removed or replaced to obtain metadata.
  • Canonical AGENTS references are not enriched; 8000 system metadata references are excluded from matching. Engine advice is conditional, so a query already accounting for row versions, deletion markers, or collapsed rows is not told unconditionally to add FINAL. Explicit deduplication for ReplacingMergeTree with is_deleted must exclude deleted rows after selecting the latest version.
  • Context is labeled as reference data, not instructions. Query arguments, parameter binding, row serialization, and base-query cancellation are unchanged.

Limitations

  • Conservative table matching is not a full SQL parser. It ignores comments and literals, supports simple quoted identifiers, and distinguishes explicit aliases and qualified identifiers from clause keywords. Queries with WITH, nested comments, more than 65,536 characters, or more than 32 distinct references are skipped, as are table functions and unsupported references. Ambiguous keyword expressions or references (such as ON join BETWEEN ...) skip enrichment entirely; quoting or qualifying keyword-named columns avoids that ambiguity, and operator-like table names should be quoted or qualified.
  • dbt descriptions match schema_name.name; physical aliases remain an upstream limitation tracked in agents_schema#41.

Validation

  • Python 3.12, locked dependencies with all extras, ClickHouse 26.3.41.4: 1,052 passed, 1 expected failure, 0 skipped.
  • Feature/integration/startup tests: 218 passed on each of Python 3.10 with minimum clickhouse-connect 1.0.0, and Python 3.11, 3.13, and 3.14 with locked dependencies.
  • Unit and real FastMCP/ClickHouse regressions cover keyword aliases, qualified keyword columns, operator/CASE expressions, and keyword-named tables, including decoy tables that must not contribute context.
  • An additional review-time comparison against ClickHouse's EXPLAIN AST covered 614 parser-accepted SQL cases, with no spurious table references from the scanner.
  • New regressions reproduced temporary-table misattribution and missing enrichment for server-enforced readonly=1 accounts before the fixes, then passed afterward.
  • Real FastMCP/ClickHouse tests cover temporary-table shadowing and qualified references via constructor, settings, and generic-argument session configuration; read-only users with and without metadata grants; and cache isolation after a privileged caller warms the caches. Test-only user provisioning is enabled in the local and CI ClickHouse services.
  • New regressions fail before these fixes and pass afterward: a five-second metadata view cannot break the next sequential query in an explicit session, and deletion-marker guidance covers the difference between deduplication alone and FINAL.
  • Fresh-process startup tests cover unset, disabled, enabled, and .env-enabled discovery with modern and legacy MCP clients.
  • Repository-wide Ruff, changed-file formatting, whitespace checks, test-service configuration validation, and wheel/sdist builds pass.

GitHub Actions may still require maintainer approval for this fork; the results above are local validation.

@CLAassistant
CLAassistant commented Aug 30, 2026 •
Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@felipempleite
felipempleite force-pushed the agents-schema-discovery branch 2 times, most recently from 6367c54 to e85ad0e Compare August 30, 2026 19:31
@felipempleite
felipempleite force-pushed the agents-schema-discovery branch from 653e100 to 6eeba99 Compare September 26, 2026 19:44
@felipempleite
felipempleite force-pushed the agents-schema-discovery branch from 6eeba99 to 974f41b Compare October 5, 2026 11:33
@felipempleite felipempleite changed the title Prefetch Agents Schema context into run_query results Add opt-in Agents Schema context to run_query results Oct 5, 2026
@felipempleite
felipempleite marked this pull request as ready for review October 5, 2026 11:34
@felipempleite
felipempleite marked this pull request as draft October 5, 2026 11:42
@felipempleite
felipempleite marked this pull request as ready for review October 5, 2026 15:57
@felipempleite
Copy link
Copy Markdown
Contributor Author

Hi @joe-clickhouse! Would you or someone else on the team be able to review this? It adds opt-in Agents Schema context to query results, with existing behavior unchanged by default. Local tests are passing; validation and limitations are in the description. Could you also approve the CI runs? Thanks!

@joe-clickhouse
Copy link
Copy Markdown
Collaborator

Hi @felipempleite yes thanks. I'll take a look today.

@joe-clickhouse
Copy link
Copy Markdown
Collaborator

Hey @felipempleite thanks for the work and thorough tests. I really appreciate the work here. However, I'm going to pass on this PR because I think the approach isn't quite right, even if the remaining bugs were fixed.

I think context should be exposed through discovery or semantic tools. That's how this server works and almost every one one as well. Agents Schema's own consumer starts at AGENTS.ROOT, which agents can already query through run_query. Adding SQL parsing, another thread pool, and caches to query execution is more machinery than we need for simple discovery.

Also, this implementation specifically, I did some testing on a live ClickHouse server and as it stand its showed a few limitations:

  • Valid SQL can make the scanner block the event loop for several seconds
  • Enrichment skips CTEs, WITH TOTALS, and WITH FILL, and misses later tables in comma joins
  • Metadata arrives after execution, so it's not able tp help with the first query
  • Engine guidance is separate from Agents Schema, and list_tables already exposes the engine

I think our first attempt here should be much smaller in scope and complexity. Let's start with a sentence in the server instructions telling agents to read AGENTS.ROOT when discovery shows an AGENTS database. If model descriptions prove useful, we could consider exposing them through list_tables, where table identity is explicit.

Help to discuss further if you want to create an issue for it or even open up another PR trying the simple approach first. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

0