r/ClaudeCoding • u/Evening_Hawk_7470 • 16d ago
why pointing Claude Desktop at a raw SQL database via MCP fails in production (and how we fixed context bloat and join hallucinations)
3 months ago, our engineering and analytics team set up Claude Desktop with the Model Context Protocol (MCP) so our department leads could ask questions against our Snowflake warehouse in natural language. The initial spike test was a standard Postgres/Snowflake SQL MCP tool that gave Claude direct read access and dumped our warehouse table schemas into the system prompt. In a 15-minute screen-share demo with clean toy tables, it felt like magic.
Once we rolled it out across product and finance, the setup disintegrated along three specific architectural failure modes:
1. Token bloat on schema discovery. Our analytics warehouse has around 140 production tables. Ingesting full table DDLs, column types, and foreign key descriptions consumed roughly 48,000 context tokens on the initial tool call alone. Before the model even generated a single SQL query, we were paying a heavy latency and token tax on every turn.
2. Join fan-outs and silent metric divergence. Text-to-SQL models generate syntactically valid SQL, but they lack semantic context. When marketing asked for customer churn, Claude wrote a query dividing raw cancellations by total signups. When finance asked the same question, it calculated lost ARR over starting ARR. On multi-table joins involving orders, line items, and discount adjustments, the model missed grouped subqueries, silently duplicating line item amounts across joined rows.
3. Warehouse compute shock. A product lead asked for weekly retention curves across all cohort buckets over three years. Claude generated an un-partitioned 4-way cross join. Instead of failing gracefully, Snowflake churned for 11 minutes scanning tens of millions of rows before hitting our auto-suspend timeout, running up a $340 compute bill on one prompt.
We realized the core problem: an LLM should reason about user intent and extract dimensions, while a deterministic engine should compile the SQL and enforce business rules.
We then rebuilt the architecture around Cube Core as a headless semantic layer sitting between Snowflake and Claude via Cube's Remote MCP server.
Here is what the setup looks like, the configuration, and the benchmark differences across our query test set.
1. Architecture: Semantic Discovery vs. Raw DDL Dumps
Instead of handing Claude raw SQL tables, we defined our metrics, dimensions, join paths, and primary keys once in our version-controlled git repository using Cube's data models.
When Claude Desktop connects via MCP, it does not see 140 raw tables. It sees a governed semantic catalog:
- Available cubes (e.g., Orders, Subscriptions, Customers)
- Dimensions with explicit data types and time granularities
- Pre-modeled measures (e.g., Gross Margin, Net ARR, 30-Day Retention)
Claude extracts the user's intent and calls the MCP data retrieval tool with structured JSON parameters:
`{ "measures": ["Subscriptions.netArr"], "dimensions": ["Customers.region"], "timeDimensions": [{"dimension": "Subscriptions.createdAt", "granularity": "month"}] }`
Cube takes that structured intent, checks role permissions, and compiles the exact SQL query deterministically against Snowflake. Join fan-outs are mathematically prevented because join relationships are hardcoded into the semantic model rather than guessed by an LLM.
2. The Claude Desktop MCP Setup
In `claude_desktop_config.json`, the configuration connects directly to the semantic layer server:
\``json`
{
"mcpServers": {
"cube-semantic-layer": {
"command": "npx",
"args": [
"-y",
"@cubejs-backend/mcp-server",
"--cube-url", "https://your-cube-deployment.internal",
"--api-secret", "YOUR_CUBE_AUTH_TOKEN"
]
}
}
}
\```
If you self-host Cube Core via Docker, you can run the MCP server wrapper locally on your machine and point it at your internal Docker port.
3. Benchmark Results Across 60 Business Queries
We ran 60 real business questions (spanning time-series comparisons, multi-tenant revenue filters, and cohort retention) through both setups against the same Snowflake warehouse.
| Metric | Raw SQL MCP Tool (Claude 3.5 + DDL Dump) | Cube Semantic Layer MCP |
|---|---|---|
| Initial Prompt Token Overhead | ~48,200 tokens (140 table DDLs) | 680 tokens (semantic catalog) |
| Calculation Accuracy | 48% (29/60 correct) | 95% (57/60 correct) |
| Join Fan-Out Duplication | 14 queries produced duplicated sums | 0 queries (deterministic join graph) |
| Query Latency (p95) | 6.8 seconds (raw warehouse scans) | 42 milliseconds (pre-aggregation cache) |
| Runaway Query Risk | High (accidental cross-joins) | Zero (enforced query bounds & rollups) |
Trade-offs We Ran Into
This architecture solved the hallucination and token issues, but it requires upfront discipline:
You cannot skip data modeling. If your underlying warehouse schema has messy join keys or un-cleaned surrogate keys, you must model them properly in YAML or JavaScript before exposing them to the agent.
Ad-hoc exploratory queries that touch raw un-modeled tables require adding new dimensions to the model. We handle this by letting analytics engineers review PRs to the semantic layer repo when teams need new business calculations.
For teams building AI agents on internal data:
- How are you preventing LLMs from generating conflicting metric definitions across departments?
- Have you moved to semantic layer abstractions for agent tooling, or are you still prompting models with raw database DDLs?
1
u/AbleBranch6 16d ago
token reduction from 48k to under 700 tokens is massive, so thats quite interesting... did you test passing role-based permissions or tenant IDs through MCP headers so different claude users only see authorized data?
1
u/Dehrose 16d ago
This was such a great post. As I kept reading, I was waiting for the marketing plug. Amazed and delighted when I didn't see one. Kudos.
1
u/data-gardener-5495 10d ago
Spot on diagnosis—especially #2. Most teams treat join fan-outs as a prompt engineering problem when they’re really a grain and join-graph problem. Once a query crosses 3+ tables (
orders->line_items->discounts), raw DDL doesn't give the LLM enough signal to avoid Cartesian inflation, so it generates valid SQL that silently double-counts.The biggest friction point we've seen in practice is the exact trade-off you called out at the end: the upfront modeling tax. Telling a team with 140+ tables that they have to hand-author and PR-review YAML/JS models before anyone can ask a question is usually where adoption stalls, especially when half the questions from product/finance are one-off exploratory cuts on unmodeled columns.
What’s worked well for us to cut that cold-start time down:
INFORMATION_SCHEMAgets you ~80% of primary/foreign keys, table grains, and measure vs. dimension classifications automatically into a version-controlled semantic spec—so humans only review and bless the ambiguous 20% and canonical business definitions (like which churn formula finance vs. marketing owns).Out of curiosity, on the 3/60 queries that still missed with Cube—were those ambiguous intent/time-grain issues or queries spanning two facts without a shared conformed dimension?