Skip to main content
Glama
mcp-bd-service

mcp-bd-service

by 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

 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.

Related MCP server: mcp-sql

Install

pip install mcp-bd-service                 # SQLite included
pip install "mcp-bd-service[postgres]"     # or [mysql], [mssql], [chat]

Or run it without installing, using uv:

uvx mcp-bd-service --db-url "sqlite:////absolute/path/data.db"

Try it with a synthetic demo database:

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:

{
  "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)

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:

// 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" }] }
# 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

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 deploys a free demo on Render in a few clicks. See docs/DEPLOYMENT.md for Render, Cloud Run, Hugging Face Spaces, your own PostgreSQL, and a production checklist.

Console chat with a local model (Ollama)

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

Descriptions and synonyms help LLMs — especially small local models — map business language to tables ("pedidos" → orders).

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.

Development

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: 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

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. Report vulnerabilities privately as described in SECURITY.md. Changes are listed in CHANGELOG.md.

Roadmap

  • OAuth 2.1 (for ChatGPT connectors and claude.ai)

  • Audit log of queries

License

MIT, see LICENSE.

Available Tools

7 tools
describe_tableC
Read-onlyIdempotent

Columns (type, nullability, keys, description), foreign keys, tables that reference it, synonyms and a few example rows of one table.

Inputs: table (required), sample_rows. Returns: object

get_relationshipsA
Read-onlyIdempotent

All foreign-key relationships between tables (how to JOIN them).

Inputs: no named parameters. Returns: object

list_tablesB
Read-onlyIdempotent

List all tables and views with their description, column count and row count.

Inputs: no named parameters. Returns: object

profile_columnB
Read-onlyIdempotent

Statistics of a column: nulls, distinct values, min/max/avg and the most frequent values. Use it to learn valid filter values.

Inputs: table (required), column (required), top. Returns: object

run_queryA
Read-onlyIdempotent

Run ONE read-only SQL query (SELECT or WITH ... SELECT) in the database's SQL dialect. Results are limited in rows and execution time.

Inputs: sql (required). Returns: object

sample_rowsB
Read-onlyIdempotent

Return the first rows of a table to see what the data looks like.

Inputs: table (required), limit. Returns: object

search_schemaA
Read-onlyIdempotent

Find tables and columns whose name, description or synonyms match a keyword (accent-insensitive, any language used in the catalog).

Inputs: keyword (required). Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.5/5.0

    Scored across 7 tools

    Disambiguation4/5

    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.

    Naming Consistency5/5

    All tools follow a consistent snake_case verb_noun pattern (list_tables, describe_table, profile_column, run_query). No mixing of conventions.

    Tool Count5/5

    Seven tools is well-scoped for a read-only database exploration service, with each tool earning its place across discovery, understanding, and querying.

    Completeness4/5

    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.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables SQL agents to connect to any SQLAlchemy-supported database via MCP, providing read-only SQL querying, automatic table summarization, and column content search.
      4
      Apache 2.0
    • A
      license
      Not graded
      quality
      Not graded
      maintenance
      An extensible read-only MCP server for SQL databases, enabling schema exploration and safe SELECT queries via tools like list_schemas, list_tables, describe_table, and execute_query.
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to read-only query a SQLite database, inspect schema and table summaries, and execute SELECT queries with pagination through MCP.
      MIT
    • F
      license
      Not graded
      quality
      A
      maintenance
      Enables MCP clients and LLMs to interact with a DuckDB database through SQL query execution, table creation, and schema inspection, with optional read-only operation.
      -