mcp-bd-service
# MCP_BD_Service
<!-- mcp-name: io.github.jtesotelo/mcp-bd-service -->
A **generic, read-only MCP server for SQL databases**. It knows nothing about your data in advance: it discovers tables, columns and relationships at runtime, so any MCP-capable LLM client (Claude, GitHub Copilot, Cursor, the OpenAI API, local models via Ollama...) can explore the database and answer questions about it.
Works with any database SQLAlchemy supports: SQLite, PostgreSQL, MySQL/MariaDB, SQL Server, and others.
## Architecture
```text
MCP clients: Claude Desktop · VS Code Copilot · Cursor · OpenAI API · mcp-bd-service chat
│ MCP: stdio (local) or Streamable HTTP (remote)
│ HTTP: /health · bearer token · rate limit · CORS
┌───────────────────────▼────────────────────────────────────┐
│ server.py (FastMCP) │
│ tools: list_tables · describe_table · get_relationships │
│ search_schema · sample_rows · profile_column │
│ run_query resource: schema://overview │
└──────┬──────────────────┬──────────────────┬───────────────┘
┌──────▼───────┐ ┌───────▼────────┐ ┌──────▼──────────────┐
│ db/introspect│ │ db/query_guard │ │ catalog (YAML) │
│ tables, FKs, │ │ sqlglot: one │ │ descriptions, │
│ types │ │ SELECT only, │ │ synonyms │
│ │ │ table rules │ │ │
└──────┬───────┘ └───────┬────────┘ └─────────────────────┘
└──────────┬───────┘
┌──────▼──────────────┐
│ db/engine.py │ read-only connection,
│ db/executor.py │ timeouts, row limit, masking
└──────┬──────────────┘
SQLite · PostgreSQL · MySQL · SQL Server · ...
```
The LLM follows a progressive workflow instead of receiving the whole schema at once: `list_tables` / `search_schema` → `describe_table` / `profile_column` → `run_query`.
## Install
```bash
pip install mcp-bd-service # SQLite included
pip install "mcp-bd-service[postgres]" # or [mysql], [mssql], [chat]
```
Or run it without installing, using [uv](https://docs.astral.sh/uv/):
```bash
uvx mcp-bd-service --db-url "sqlite:////absolute/path/data.db"
```
Try it with a synthetic demo database:
```bash
mcp-bd-service sample-db # creates ./database/sample.db and an example catalog
```
## Use it from an MCP client (local, stdio)
Claude Desktop (`claude_desktop_config.json`); VS Code, Cursor and Claude Code use the same `command` / `args` / `env` fields:
```json
{
"mcpServers": {
"database": {
"command": "uvx",
"args": ["mcp-bd-service"],
"env": { "DATABASE_URL": "sqlite:////absolute/path/data.db" }
}
}
}
```
For PostgreSQL: `"args": ["--from", "mcp-bd-service[postgres]", "mcp-bd-service"]` and `"DATABASE_URL": "postgresql+psycopg://readonly:password@host/db"`. Use absolute paths for SQLite.
## Remote access (Streamable HTTP)
```bash
export MCP_AUTH_TOKENS=$(python -c "import secrets; print(secrets.token_urlsafe(32))")
mcp-bd-service --transport http --host 0.0.0.0 --port 8000
```
- Endpoint: `http://HOST:8000/mcp` (Streamable HTTP, stateless). Health check: `GET /health`.
- Every request needs `Authorization: Bearer <token>`. Several comma-separated tokens are accepted, so you can rotate them.
- The server refuses to bind a non-local address without a token (override with `MCP_ALLOW_NO_AUTH=true` only behind your own auth proxy).
- Rate limit per client (`MCP_RATE_LIMIT_PER_MINUTE`), DNS-rebinding protection (`MCP_ALLOWED_HOSTS`), optional CORS (`MCP_CORS_ORIGINS`).
- Always serve it behind HTTPS (cloud platforms provide it).
Client examples:
```jsonc
// VS Code (.vscode/mcp.json)
{ "servers": { "database": { "type": "http", "url": "https://your-host/mcp",
"headers": { "Authorization": "Bearer ${input:mcp-token}" } } },
"inputs": [{ "id": "mcp-token", "type": "promptString", "password": true,
"description": "MCP token" }] }
```
```python
# OpenAI Responses API
tools = [{"type": "mcp", "server_label": "database",
"server_url": "https://your-host/mcp",
"headers": {"Authorization": f"Bearer {token}"},
"require_approval": "never"}]
```
ChatGPT connectors and claude.ai custom connectors expect OAuth; bearer tokens work with VS Code, Cursor, Claude Code, the OpenAI and Anthropic APIs and the console client. OAuth support is on the roadmap.
## Docker and deployment
```bash
export MCP_AUTH_TOKENS=$(python -c "import secrets; print(secrets.token_urlsafe(32))")
docker compose up --build # http://localhost:8000/mcp, synthetic demo database
```
A multi-arch image is published to `ghcr.io/jtesotelo/mcp-bd-service`, and [render.yaml](render.yaml) deploys a free demo on Render in a few clicks. See [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) for Render, Cloud Run, Hugging Face Spaces, your own PostgreSQL, and a production checklist.
## Console chat with a local model (Ollama)
```bash
pip install "mcp-bd-service[chat]"
mcp-bd-service chat
```
A conversational chat that keeps history (`/reset` clears it, `/salir` exits). Set `OLLAMA_MODEL` in `.env`. By default it starts the server locally; set `MCP_SERVER_URL` (and `MCP_CLIENT_TOKEN`) to chat with a remote server. Check that `→ Consultando herramienta MCP: run_query` appears in the console: a model writing SQL in its answer does not mean it ran it.
Inspect the tools visually: `npx @modelcontextprotocol/inspector mcp-bd-service`
## Tools
| Tool | Purpose |
|---|---|
| `list_tables` | Tables and views with row counts and descriptions |
| `describe_table` | Columns, keys, foreign keys, referencing tables, sample rows |
| `get_relationships` | All foreign keys (how to join tables) |
| `search_schema` | Find tables/columns by keyword (accent-insensitive, fuzzy, uses catalog synonyms) |
| `sample_rows` | First rows of a table |
| `profile_column` | Nulls, distinct values, min/max/avg and most frequent values |
| `run_query` | One read-only SQL query, with row and time limits |
## Semantic catalog (optional, recommended)
Descriptions and synonyms help LLMs — especially small local models — map business language to tables ("pedidos" → `orders`).
```bash
mcp-bd-service catalog init # writes a skeleton to CATALOG_PATH (default: metadata/catalog.yaml)
```
Fill in the descriptions and synonyms; `mcp-bd-service sample-db` writes a complete example. Your `metadata/catalog.yaml` is git-ignored.
## Security
Several independent layers:
1. **Read-only connection**: SQLite opened with `mode=ro` + `query_only`; PostgreSQL/MySQL sessions set to read-only.
2. **Query validation** with `sqlglot`: exactly one `SELECT`/`WITH` statement; no DML/DDL, `PRAGMA`, `ATTACH`, `SELECT INTO`, locking clauses, dangerous functions (`load_extension`, `pg_read_file`, `pg_sleep`...) or system tables; only visible tables.
3. **Limits**: `MAX_ROWS`, `QUERY_TIMEOUT_SECONDS`.
4. **Access control**: `ALLOWED_TABLES`, `DENIED_TABLES`, `MASKED_COLUMNS`.
In production, also connect with a database user that only has `SELECT` grants. Do not expose the server to a network without authentication.
## Configuration
All settings are environment variables (a `.env` in the working directory is loaded); see [.env.example](.env.example).
## Development
```bash
pip install -e ".[dev]"
pytest
```
The suite builds a synthetic database and covers the query guard, every tool through an MCP client, masking, limits, timeouts, HTTP authentication and rate limiting, the CLI, and real stdio and HTTP servers. CI runs it on Python 3.10–3.13.
### Releasing
Pushing a tag `vX.Y.Z` runs [.github/workflows/release.yml](.github/workflows/release.yml): tests → build → PyPI (trusted publishing) → MCP Registry (GitHub OIDC). Bump the version in `src/mcp_bd_service/__init__.py` and `server.json` first (CI checks they match). One-time setup is described at the top of the workflow.
## Project structure
```text
src/mcp_bd_service/
├── cli.py # `mcp-bd-service` command
├── config.py # settings from environment / .env
├── server.py # MCP tools, resource, prompt
├── http_app.py # Streamable HTTP: auth, rate limit, CORS
├── llm_client.py # `mcp-bd-service chat` (Ollama)
├── sample_data.py # `mcp-bd-service sample-db`
├── db/ # engine, introspection, query guard, executor
├── catalog/ # semantic catalog + `catalog init`
└── analytics/profile.py # column statistics
server.json # MCP Registry metadata
CHANGELOG.md, CONTRIBUTING.md, SECURITY.md
Dockerfile, docker-compose.yml, render.yaml
docs/DEPLOYMENT.md
tests/
```
## Contributing
Contributions are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md). Report vulnerabilities privately as described in [SECURITY.md](SECURITY.md). Changes are listed in [CHANGELOG.md](CHANGELOG.md).
## Roadmap
- OAuth 2.1 (for ChatGPT connectors and claude.ai)
- Audit log of queries
## License
MIT, see [LICENSE](LICENSE).
TDQS
Scored across 7 tools
Each tool has a clearly distinct role in the discovery-to-query workflow. Minor overlap: describe_table returns example rows, which duplicates sample_rows, and profile_column vs sample_rows both touch per-column/per-table data inspection.
All tools follow a consistent snake_case verb_noun pattern (list_tables, describe_table, profile_column, run_query). No mixing of conventions.
Seven tools is well-scoped for a read-only database exploration service, with each tool earning its place across discovery, understanding, and querying.
Strong coverage of the read-only lifecycle: discovery (list/search), understanding (describe, relationships, profile, sample), and execution (run_query). Minor gaps like schema-level listing or query explanation are easy workarounds; write operations are reasonably out of scope.