Text-to-SQL Agent para BigQuery
sarinravishanker/text-to-sql-agent
Perguntas em português → SQL automático no BigQuery com aprovação
Ver no GitHubAgente de conversação que transforma perguntas em linguagem natural em consultas SQL executáveis no BigQuery, com interface Streamlit para revisão antes da execução e suporte MCP para Claude Desktop. Inclui guardrails de custo e estimativas de scan antes de rodar queries.
Instalação
npx convez-ai sarinravishanker/text-to-sql-agent1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.
Métricas
Casos de uso
- Análise de dados sem escrever SQL manualmente
- Business intelligence conversacional sobre BigQuery
- Relatórios sob demanda via interface web ou Claude Desktop
- Exploração segura de schemas com controle de custo
Veredito

Solução madura que democratiza acesso ao BigQuery via linguagem natural. O suporte dual (Streamlit + MCP) é prático, e os guardrails de custo antes de executar queries salvam da surpresa cara — recomendado para times com BigQuery mas sem especialistas SQL tempo integral.
README
A tradução para o português deste README ainda está na fila.
Text-to-SQL Analytics Agent
A conversational analytics agent that takes a plain-English business question, explores your BigQuery schema, writes the SQL, and returns a clear answer.
Built with the Anthropic SDK, Google BigQuery, FastMCP, and Streamlit.
Two interfaces, one tool layer
Both interfaces share the same BigQuery tool functions in agent/tools.py, including the same cost guardrails.
| Streamlit UI | Claude Code / Desktop (MCP) | |
|---|---|---|
| Agent loop | Written in code (agent/agent.py) | Claude reasons natively |
| SQL review | Yes — you see and approve SQL before it runs | No — Claude executes directly |
| Dry-run estimate | Shown before Run button | Enforced inside the tool |
| Conversation memory | No — each question is independent | Yes — Claude remembers the session |
| Token cost | Flat per question | Grows with conversation length |
| Shareable | Yes | Local only |
Architecture
Streamlit UI
Question → agent/agent.py (Anthropic SDK)
→ list_datasets / list_tables / get_table_schema ──► BigQuery (schema)
→ Generate SQL (no execution)
→ Dry-run estimate
→ User clicks ▶ Run Query
→ execute_sql ──► BigQuery ──► Results table
FastMCP (Claude Code / Desktop)
Question → Claude (reasons natively)
→ mcp_server/server.py (FastMCP)
→ agent/tools.py ──► BigQuery
→ Claude interprets and responds
Prerequisites
- Python 3.11+
- Google Cloud project with BigQuery enabled
gcloudCLI installed- Anthropic API key
- Claude Code or Claude Desktop (MCP interface only)
Setup
1. Clone and install
git clone <your-repo-url>
cd text-to-sql-agent
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txt
2. Authenticate with Google Cloud
gcloud auth application-default login
3. Configure environment variables
cp .env.example .env
Fill in ANTHROPIC_API_KEY, GOOGLE_CLOUD_PROJECT, and adjust limits as needed. See .env.example for all options.
4. Verify access
# BigQuery
python -c "from google.cloud import bigquery; print([d.dataset_id for d in bigquery.Client().list_datasets()])"
# Anthropic
python -c "import anthropic; anthropic.Anthropic(); print('OK')"
Streamlit UI
streamlit run ui/app.py
Open http://localhost:8501.
- Type a question in plain English
- The agent explores your schema and writes SQL — nothing executes yet
- A scan cost estimate appears (green < 100 MB / yellow < 1 GB / red = blocked)
- Click ▶ Run Query — results appear as a table
- For ambiguous questions the agent asks for clarification before generating SQL
FastMCP (Claude Code / Claude Desktop)
Connect to Claude Code
claude mcp add bigquery-agent \
/absolute/path/to/venv/bin/python \
/absolute/path/to/mcp_server/server.py
Use absolute paths — relative paths will fail if Claude Code runs from a different directory.
Connect to Claude Desktop
Add to ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"bigquery-agent": {
"command": "/absolute/path/to/venv/bin/python",
"args": ["/absolute/path/to/mcp_server/server.py"],
"env": {
"GOOGLE_CLOUD_PROJECT": "your-project-id",
"MAX_BYTES_SCANNED": "1000000000"
}
}
}
}
Restart Claude Desktop — a hammer icon (🔨) confirms tools are active.
Note on guardrails: Cost guardrails (dry-run byte limit, read-only SQL enforcement, dataset blocklist) are enforced inside the tool layer and apply in Claude Desktop exactly as they do in the Streamlit UI. However, Claude Desktop has no system prompt restricting it to BigQuery topics — it will answer off-topic questions from its own knowledge without using the MCP tools. It also executes SQL autonomously without a human review step. For a controlled, review-before-execute experience, use the Streamlit UI.
Tools exposed
| Tool | What it does |
|---|---|
bq_list_datasets | Lists all datasets in the GCP project |
bq_list_tables | Lists tables in a dataset |
bq_get_table_schema | Returns columns, types, and descriptions |
bq_get_sample_rows | Returns up to 10 sample rows |
bq_get_table_stats | Returns row count, partition info, last modified |
bq_execute_sql | Runs a SELECT query with dry-run and byte limit enforced |
CLI
python scripts/run_local.py "your question here"
Tests
pytest tests/ -v
Uses mocked BigQuery and Anthropic clients — no real API calls.
Project structure
text-to-sql-agent/
├── agent/
│ ├── agent.py # Agent loop (Streamlit interface)
│ ├── tools.py # BigQuery tools + dry-run (shared by both interfaces)
│ ├── prompts.py # System prompts
│ └── schema_cache.py # TTL in-memory schema cache
├── mcp_server/
│ └── server.py # FastMCP server (Claude Code / Desktop interface)
├── ui/
│ └── app.py # Streamlit chat UI
├── scripts/
│ └── run_local.py # CLI test runner
├── tests/
├── .env.example
└── requirements.txt
Cost guardrails
BigQuery charges per bytes scanned, not rows returned. MAX_BYTES_SCANNED is the only setting that prevents BigQuery spend — all others affect app behaviour or Anthropic token cost only.
| Guardrail | Protects | Default |
|---|---|---|
MAX_BYTES_SCANNED | BigQuery cost — blocks query before execution | 1 GB |
MAX_ROWS_RETURNED | App memory — no effect on BQ cost | 500 rows |
SCHEMA_CACHE_TTL_SECONDS | Anthropic tokens — avoids re-fetching schemas | 5 min |
| Max iterations (Streamlit) | Anthropic tokens — stops runaway agent loops | 10 |
| Prompt caching (Streamlit) | Anthropic tokens — system prompt cached after first call | enabled |
Tech stack
| Layer | Tool |
|---|---|
| LLM | Claude (Anthropic SDK) |
| Data warehouse | Google BigQuery |
| MCP server | FastMCP |
| UI | Streamlit |
| Language | Python 3.11+ |