Skip to main content
Glama
mcp-sql-server-kit

mcp-sql-server-kit

by khoinh-work

mcp-sql-server-kit

A remote Model Context Protocol (MCP) server that gives Claude, ChatGPT or your own AI agent safe, read-only access to a SQL database, protected by OAuth 2.1.

  • Remote, not just local: Streamable HTTP transport, stateless, runs behind any load balancer. A stdio entry point is included for Claude Desktop.

  • OAuth 2.1 out of the box: discovery metadata (RFC 9728 + RFC 8414), dynamic client registration, authorization code + PKCE, refresh token rotation, revocation. Or plug in your own identity provider (Auth0, Keycloak, Entra ID, Okta) with JWT validation.

  • Five generic tools + a knowledge file instead of one tool per business question (see Why five tools).

  • Read-only in two layers: a SQL guard that gives the model a clear error, and engine-level enforcement (read-only SQLite handle; Postgres READ ONLY transaction + statement_timeout).

  • SQLite and PostgreSQL, a synthetic demo dataset, Docker, CI, 31 tests including the full OAuth flow and engine-level write rejection on a real Postgres.

Quick start

npm install
npm run seed                      # builds data/demo.sqlite (synthetic retail data)
AUTH_USERS=demo:change-me npm run dev

The MCP endpoint is http://localhost:3000/mcp. Try it with the MCP Inspector:

npx @modelcontextprotocol/inspector

Choose Streamable HTTP, enter http://localhost:3000/mcp, click Connect: the Inspector runs the OAuth flow, you sign in as demo / change-me, and the five tools appear.

Connect Claude

  • Claude (web, desktop, mobile): deploy the server somewhere with HTTPS, set PUBLIC_URL to that address, then add https://your-host/mcp as a custom connector. Claude handles the OAuth sign-in.

  • Claude Desktop, local only: npm run build, then add to claude_desktop_config.json:

    {
      "mcpServers": {
        "sql": {
          "command": "node",
          "args": ["/absolute/path/to/mcp-sql-server-kit/dist/stdio.js"],
          "env": { "DATABASE_URL": "sqlite:/absolute/path/to/data/demo.sqlite" }
        }
      }
    }

Docker

docker compose up --build

Related MCP server: Governor SQL MCP

Tools

Tool

What it does

search_knowledge

Metric definitions with reference SQL, glossary terms and data rules from knowledge/knowledge.yaml

list_tables

Tables with (approximate) row counts

describe_table

Columns, types, primary keys, foreign keys

sample_rows

A few real rows, so the model sees actual values and formats

run_query

One SELECT / WITH ... SELECT, capped at MAX_ROWS, with a clear note when truncated

All five carry readOnlyHint: true.

A typical exchange for "Which region had the highest net revenue?": search_knowledge("net revenue") returns the definition (completed orders only, after discount) and its SQL, describe_table("stores") shows where region lives, and one run_query returns three rows.

Why five tools

The obvious way to build a data MCP server is one tool per business question: get_revenue_by_region, get_top_products, get_return_rate, ... It works for the first demo and then gets worse with every tool you add.

I learned this on a production agent platform where one MCP server had grown to 20 hand-built business tools, each with a long description so the model would use it correctly. Measured on real traffic:

Hand-built tools (before)

This design

Tool descriptions per model call

73,689 characters (~81% of each call's input)

2,511 characters

Time the model spent just choosing a tool

53-81 s

not yet measured on the same workload

Questions outside the predefined tools

wrong tool or many retries

answered with SQL

Tool definitions are sent to the model on every step of an agent loop, not once. Twenty long descriptions make every step slower and more expensive, and the model still fails on the twenty-first question because there is no tool for it.

The fix is to separate two things that the "one tool per question" design mixes up:

  1. Capabilities (what the agent can do) stay small and generic: explore the schema, run a read-only query.

  2. Domain knowledge (what revenue or region means here) moves to a curated file the agent searches when it needs it. Adding a metric is a YAML edit, not a new tool, and it costs nothing on calls that don't need it.

Security model

Layer

SQLite

PostgreSQL

OAuth bearer token with scope sql:read, bound to this resource

yes

yes

SQL guard: one statement, SELECT/WITH only, no DDL/DML/INTO/dangerous functions, comments and literals stripped before checking

yes

yes

Engine refuses writes

read-only file handle + query_only

BEGIN READ ONLY

Row cap

streamed, stops at MAX_ROWS

LIMIT MAX_ROWS + 1

Time limit

best effort (see below)

statement_timeout

Recommendations for real deployments:

  • Connect with a database role that only has SELECT on the tables you want to expose. The read-only transaction is a second line of defence, not a replacement for grants.

  • Use AUTH_MODE=jwt with your identity provider. The built-in authorization server keeps state in memory (a restart signs everyone out) and stores passwords from an environment variable; it is meant for demos and small internal teams.

  • Put the server behind HTTPS. OAuth metadata is built from PUBLIC_URL.

Known limitation: better-sqlite3 has no per-statement timeout, so a pathological SQLite query can run long even though row reading stops at the cap. Use Postgres for untrusted users at scale.

Configuration

Variable

Default

PUBLIC_URL

http://localhost:$PORT

Address clients use; must be HTTPS in production

PORT / HOST

3000 / 0.0.0.0

DATABASE_URL

sqlite:data/demo.sqlite

sqlite:<file> or postgres://...

KNOWLEDGE_PATH

knowledge/knowledge.yaml

MAX_ROWS

200

Rows returned per query

QUERY_TIMEOUT_MS

5000

AUTH_MODE

builtin

builtin, jwt or none (localhost only)

AUTH_USERS

builtin: user:password,user2:password2

OAUTH_SCOPE

sql:read

Scope required on every token

OAUTH_ISSUER, OAUTH_JWKS_URL, OAUTH_AUDIENCE

jwt mode

Use your own database

  1. Point DATABASE_URL at it (ideally a read-only role).

  2. Replace knowledge/knowledge.yaml with your metrics, glossary and rules. Start with the five questions people ask most; write the SQL you would trust, and the rules a new analyst would need to hear on day one.

  3. Run the tests and ask your agent a question that is not in the knowledge file: it should still get there through describe_table and run_query.

Development

npm test             # unit + tool + full OAuth flow tests
npm run typecheck

# Postgres tests (optional): load the demo data, then
npx tsx scripts/sqlite-to-postgres.ts | psql "$TEST_POSTGRES_URL"
TEST_POSTGRES_URL=postgres://... npm test
src/
  index.ts          HTTP entry point
  stdio.ts          stdio entry point (Claude Desktop)
  http.ts           Express app: OAuth routes, bearer auth, Streamable HTTP
  server.ts         the five MCP tools
  sqlGuard.ts       read-only SQL guard
  knowledge.ts      YAML knowledge library + search
  auth/builtin.ts   built-in OAuth 2.1 authorization server
  auth/jwt.ts       JWT verification for external identity providers
  db/               SQLite and PostgreSQL adapters
knowledge/          business knowledge for the demo dataset
scripts/            demo data generator, SQLite -> Postgres export
test/               vitest suites

License

MIT

Tool Schema Changelog

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

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to safely query and explore SQLite databases through read-only, guard-protected tools that block writes, sensitive table access, and runaway queries.
      1
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI agents to safely query SQL databases through read-only tools for describing entities, reading records, and aggregating records, with view-based access and fail-closed per-user row-level security.
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables AI agents to inspect database schemas and run strictly read-only SQL queries with guardrails against destructive statements, multi-statement chaining, and unbounded scans. Supports SQLite natively and PostgreSQL optionally.
      4
      53 PyPI
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to safely explore and query SQLite or PostgreSQL databases through read-only, guarded SELECT queries with column masking, row limits, timeouts, and audit logging.
      MIT