duckdb-mcp
A minimal MCP server that provides a persistent DuckDB SQL engine to AI assistants, enabling natural-language querying of CSVs, Parquet, and cloud data with 12 tools and optional read-only mode.
README
<div align="center">
🦆 DuckDB MCP Server
Give your AI assistant a blazing-fast, persistent SQL engine.
A minimal Model Context Protocol server that plugs DuckDB straight into Claude — query CSVs, Parquet, and cloud data in plain language, at in-process speed.
⚡ ~10 ms / query · 🪶 2 runtime deps · 🧰 12 tools · 🔒 read-only & secret-safe
</div>
✨ Why this one?
| ⚡ Fast | One persistent connection for the whole session — no subprocess spawn, no reconnect. ~10 ms per query. |
| 🪶 Tiny | A focused src/ package, just two runtime dependencies (duckdb, mcp). No bloat, no magic. |
| 🧰 Complete | 12 tools covering query, write, CSV/Parquet loading, and full catalog/schema/table introspection. |
| 🔒 Safe by default | Engine-enforced --read-only mode, plus a list_environments tool that masks every secret (****). |
| ☁️ Cloud-ready | Query s3:// Parquet directly, with ${VAR} interpolation to keep credentials out of config files. |
| 🧩 Extensible | Opt-in unsigned/community extensions (e.g. TA-Lib) via a single flag or env var. |
| 🔌 Local or remote | Run over stdio (Claude Desktop) or streamable HTTP — one --transport flag. |
| 🔑 Token auth | Protect the HTTP transport with a bearer token from a single env var. |
| ✅ Trustworthy | Fully typed, linted, and tested — CI runs black + ruff + mypy + pytest on Python 3.12 & 3.13. |
🚀 Quick start
1. Run it — no install needed (via uv):
uvx --from git+https://github.com/wuqunfei/duckdb-mcp-mini duckdb-mcp --db :memory:
2. Point Claude Desktop at it — add this to claude_desktop_config.json and restart Claude:
{
"mcpServers": {
"duckdb": {
"command": "uvx",
"args": ["--from", "git+https://github.com/wuqunfei/duckdb-mcp-mini", "duckdb-mcp", "--db", ":memory:"]
}
}
}
3. Ask away 💬
"Load
~/data/sales.csvand show me total revenue by region."
That's it. Tools are available immediately. 🎉
📦 Install
pip install . # from a clone, into the current environment
pip install -e ".[dev]" # for development (editable + dev tools)
Or run straight from Git without installing:
uvx --from git+https://github.com/wuqunfei/duckdb-mcp-mini duckdb-mcp --db :memory:
ℹ️ This package is not published to PyPI — install from source or run from Git as shown above.
Requirements: 🐍 Python 3.11–3.14 · 🦆 DuckDB 1.5.2 (pinned in pyproject.toml, easy to change) · 🔌 MCP SDK 2.0.0+
🏃 Run
The installed console script is duckdb-mcp. It speaks MCP over stdio, so you'll normally launch it from an MCP client — but you can start it directly too:
duckdb-mcp # in-memory, read-write
duckdb-mcp --db /path/to/analytics.duckdb --schema main
duckdb-mcp --db analytics.duckdb --init-sql init.sql
duckdb-mcp --db analytics.duckdb --read-only
python -m duckdb_mcp.cli --db :memory: # module form
uv run duckdb-mcp --db :memory: # via uv, no install
CLI arguments
| Flag | Description |
|---|---|
--db, --database |
Database path (:memory: or /path/to/db.duckdb). Default: :memory: |
--schema |
Default schema. Default: main |
--init-sql |
Path to a SQL file executed once on startup |
--read-only |
Open the database read-only (default: read-write) |
--allow-unsigned-extensions |
Allow unsigned/community extensions (default: off; env: ALLOW_UNSIGNED_EXTENSIONS) |
--transport |
stdio (default) or http (streamable HTTP) |
--host |
Bind host for the http transport (default: 127.0.0.1) |
--port |
Bind port for the http transport (default: 8000) |
--log-level |
Log level to stderr: DEBUG/INFO/WARNING/ERROR/CRITICAL (default: WARNING; env: LOG_LEVEL). DEBUG logs every tool request |
🐛 Debugging: run with
--log-level DEBUG(orLOG_LEVEL=DEBUG) to log every incoming tool request — name and arguments — to stderr, so you can see exactly what a client sends:DEBUG duckdb_mcp: tool request: query args={'sql': 'SELECT 42 AS answer'}Logs always go to stderr (never stdout, which is the protocol channel in stdio mode).
🔒 Read-only mode
--read-only opens the connection via DuckDB's own read-only flag, so writes are blocked at the engine level (not by inspecting SQL):
- ✅
SELECTworks normally - 🚫
INSERT/UPDATE/DELETE/CREATE/DROPare rejected by DuckDB - 💡 Perfect for shared analytics/reporting databases where accidental writes must be impossible
🔌 Transports
The server speaks two MCP transports — pick with --transport:
| Transport | Flag | Use it for |
|---|---|---|
| stdio (default) | --transport stdio |
Local clients that launch the process, e.g. Claude Desktop |
| streamable HTTP | --transport http |
Remote / networked clients — the current MCP HTTP transport (single /mcp endpoint) |
# stdio (default) — the process talks over stdin/stdout
duckdb-mcp --db analytics.duckdb
🌐 Run an HTTP server
Configuration splits cleanly in two: args set the database and network binding, environment variables carry secrets and toggles (so they stay out of ps and shell history).
# 1) Environment — secrets & toggles
export MCP_AUTH_TOKEN="a-long-random-secret" # require Bearer auth (recommended)
export ALLOW_UNSIGNED_EXTENSIONS=true # optional: allow community extensions
export AWS_ACCESS_KEY_ID="${AWS_ACCESS_KEY_ID}" # optional: for s3:// queries
export AWS_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY}"
# 2) Args — database + network binding
duckdb-mcp \
--transport http \
--host 0.0.0.0 \
--port 8000 \
--db /data/analytics.duckdb \
--init-sql /data/init.sql \
--read-only
# → serving at http://0.0.0.0:8000/mcp
--init-sql runs a SQL file once, when the connection opens. Combined with --read-only it must be read-only-safe (loading extensions or setting options is fine — creating tables is not):
-- /data/init.sql
INSTALL httpfs; LOAD httpfs; -- read remote/S3 data
SET memory_limit = '4GB';
Drop
--read-onlyif your init script needs to create tables or views.
No install? Run the same thing straight from Git:
MCP_AUTH_TOKEN="a-long-random-secret" \
uvx --from git+https://github.com/wuqunfei/duckdb-mcp-mini duckdb-mcp \
--transport http --host 0.0.0.0 --port 8000 --db :memory:
| Setting | Kind | Notes |
|---|---|---|
--transport http |
arg | Required to serve over HTTP |
--host / --port |
arg | Bind address (default 127.0.0.1:8000) |
--db / --schema / --init-sql / --read-only |
arg | Same as stdio mode |
MCP_AUTH_TOKEN |
env | Require Authorization: Bearer <token> (env-only, no flag) |
ALLOW_UNSIGNED_EXTENSIONS |
env | Community extensions (or the --allow-unsigned-extensions flag) |
AWS_*, any ${VAR} |
env | Cloud credentials for s3:// reads (see the Environment variables & cloud data section) |
--log-level / LOG_LEVEL |
both | DEBUG logs every tool request to stderr |
Verify it's up (with MCP_AUTH_TOKEN set, a missing/wrong token returns 401):
curl -s -o /dev/null -w '%{http_code}\n' \
-X POST http://127.0.0.1:8000/mcp \
-H 'Authorization: Bearer a-long-random-secret' \
-H 'Accept: application/json, text/event-stream' \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","id":1,"method":"ping"}'
# 401 = missing/invalid token · 400 = reached the server (a real client does the full MCP handshake)
🔑 Bearer token
Setting MCP_AUTH_TOKEN turns on auth for the HTTP transport:
- 🌱 Environment only — read from
MCP_AUTH_TOKEN, never a CLI flag, so it stays out ofpsand shell history. - 🔌 HTTP only — ignored for
stdio(the client owns the process); setting it there prints a warning. - ⚠️ Access control, not identity — every caller with the token gets full database access. Pair it with
--read-onlyand network controls; it is not per-user auth.
🔒
--hostdefaults to127.0.0.1(localhost only). Bind to0.0.0.0only on a trusted network, and always withMCP_AUTH_TOKENset.
🔗 Connect a client
MCP client config (Claude Desktop or any client that supports an HTTP URL) — omit headers if you didn't set a token:
{
"mcpServers": {
"duckdb": {
"url": "http://127.0.0.1:8000/mcp",
"headers": { "Authorization": "Bearer a-long-random-secret" }
}
}
}
From Python (the mcp client libraries ship httpx2):
import asyncio
import httpx2
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
URL = "http://127.0.0.1:8000/mcp"
HEADERS = {"Authorization": "Bearer a-long-random-secret"} # omit if no MCP_AUTH_TOKEN
async def main():
async with httpx2.AsyncClient(headers=HEADERS) as http:
async with streamable_http_client(URL, http_client=http) as streams:
read, write = streams[0], streams[1]
async with ClientSession(read, write) as session:
await session.initialize()
tools = await session.list_tools()
print("tools:", [t.name for t in tools.tools])
result = await session.call_tool("query", {"sql": "SELECT 42 AS answer"})
print(result.content[0].text)
asyncio.run(main())
🖥️ Configure Claude Desktop
Add one of the following to your claude_desktop_config.json, then restart Claude.
Run from Git (no install):
{
"mcpServers": {
"duckdb": {
"command": "uvx",
"args": ["--from", "git+https://github.com/wuqunfei/duckdb-mcp-mini", "duckdb-mcp", "--db", ":memory:"]
}
}
}
Run from a local clone:
{
"mcpServers": {
"duckdb": {
"command": "uv",
"args": ["run", "--directory", "/absolute/path/to/duckdb-mcp-mini", "duckdb-mcp", "--db", "/home/user/analytics.duckdb", "--schema", "main"]
}
}
}
After pip install . (command on PATH):
{
"mcpServers": {
"duckdb": {
"command": "duckdb-mcp",
"args": ["--db", "/home/user/analytics.duckdb", "--read-only"]
}
}
}
📍 Config file locations
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Linux:
~/.config/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
🔁 Multiple servers
Add more entries under mcpServers with distinct names (e.g. duckdb-dev, duckdb-prod), each with its own --db/--schema.
☁️ Environment variables & cloud data
Any variables set in the client's env block are available to DuckDB during connection (handy for S3/cloud credentials). Values support ${VAR_NAME} interpolation, so you can reference the system environment instead of hardcoding secrets into the config file:
{
"mcpServers": {
"duckdb": {
"command": "uvx",
"args": ["--from", "git+https://github.com/wuqunfei/duckdb-mcp-mini", "duckdb-mcp", "--db", ":memory:"],
"env": {
"AWS_ACCESS_KEY_ID": "${AWS_ACCESS_KEY_ID}",
"AWS_SECRET_ACCESS_KEY": "${AWS_SECRET_ACCESS_KEY}",
"AWS_REGION": "${AWS_REGION}",
"S3_BUCKET": "my-data-bucket"
}
}
}
}
Set the referenced variables in your shell first:
export AWS_ACCESS_KEY_ID="your-key"
export AWS_SECRET_ACCESS_KEY="your-secret"
export AWS_REGION="us-east-1"
Then query cloud data directly:
SELECT * FROM read_parquet('s3://my-data-bucket/data.parquet')
🔐 Interpolation happens before the DuckDB connection is opened, so credentials are ready in time for connection setup and any
--init-sql. Use thelist_environmentstool to confirm what's set — values are always masked.
🧩 Community & unsigned extensions
DuckDB only loads signed extensions by default. To use community or self-hosted extensions, enable unsigned extensions with the --allow-unsigned-extensions flag or the ALLOW_UNSIGNED_EXTENSIONS environment variable (default: off):
duckdb-mcp --db :memory: --allow-unsigned-extensions
# or
ALLOW_UNSIGNED_EXTENSIONS=true duckdb-mcp --db :memory:
In a Claude Desktop config:
{
"mcpServers": {
"duckdb": {
"command": "uvx",
"args": ["--from", "git+https://github.com/wuqunfei/duckdb-mcp-mini", "duckdb-mcp", "--db", ":memory:", "--allow-unsigned-extensions"]
}
}
}
The flag is applied as a connection-time setting, so it's already on — just INSTALL and LOAD through the execute tool. For example, neuesql/atm_talib (TA-Lib for DuckDB):
INSTALL talib FROM 'https://neuesql.github.io/atm_talib';
LOAD talib;
⚠️ Unsigned extensions run native code with full trust. Only enable this for extensions from sources you trust.
🧰 Tools (12)
| Category | Tool | Purpose |
|---|---|---|
| 🔎 Core | query |
Run a SELECT and return the result as a text table |
| ✍️ Core | execute |
Run a write statement (INSERT/UPDATE/DELETE/CREATE/DROP); returns a status message |
| 📥 File I/O | read_csv |
Load a CSV file into a table (table_name defaults to data) |
| 📥 File I/O | read_parquet |
Load a Parquet file into a table (table_name defaults to data) |
| 📚 Introspection | list_catalogs |
List catalogs |
| 📚 Introspection | list_databases |
List databases |
| 📚 Introspection | list_schemas |
List schemas |
| 📚 Introspection | list_tables |
List tables in the current schema |
| 📚 Introspection | list_columns |
Describe a table's columns |
| 📚 Introspection | list_extensions |
List loaded extensions |
| 🔐 Introspection | list_environments |
List environment variables as key: value, with values masked (****, or empty when unset) |
| 🏷️ Introspection | check_version |
Report the DuckDB version |
query vs execute — query is for reads (fetches rows, formats a table); execute is for writes/DDL (runs the statement, returns "Executed successfully").
🏗️ Architecture
launch (cli.main)
↓
DuckDBSession(...) # src/duckdb_mcp/session.py
├─ interpolate ${VAR} across os.environ ← runs BEFORE connecting
├─ duckdb.connect(db, read_only=...) ← one persistent connection
└─ run --init-sql (if provided) ← falls back to :memory: on error
↓
create_server(session) # src/duckdb_mcp/server.py
└─ registers 12 tools on an mcp MCPServer; each calls dispatch_tool()
↓
_serve(session, transport=...) # src/duckdb_mcp/cli.py
└─ run_stdio_async() | run_streamable_http_async()
- 🧩
session.pyholdsDuckDBSessionwith no MCP imports, so the connection/formatting logic is unit-testable with onlyduckdb. - 🗂️
server.pyholds the_HANDLERSregistry (single source of truth for the tool set) plusdispatch_tool()and the thin typed MCP registrations. - 🎛️
cli.pyparses args, builds the session, and serves.
Good to know:
- 🛟 If connecting to
--db(or running--init-sql) fails, the session degrades to an in-memory read-write connection rather than crashing. - ⚠️ SQL is f-string interpolated (table names, filepaths). This is intentional for a local single-user tool — inputs are not sanitized.
🛠️ Development
pip install -e ".[dev]" # or: uv sync --extra dev
black --check src tests # format (drop --check to apply)
ruff check src tests # lint
mypy src # type check
pytest # tests
pytest tests/test_server.py::test_dispatch_query # run a single test
📁 Project layout
duckdb-mcp-mini/
├── src/duckdb_mcp/
│ ├── __init__.py # package version + DuckDBSession export
│ ├── session.py # persistent DuckDB session (no MCP deps)
│ ├── server.py # tool registry + dispatch + MCP server wiring
│ └── cli.py # argument parsing + entrypoint
├── tests/ # pytest suite
├── .github/workflows/
│ ├── ci.yml # lint + type + test on py3.11–3.14
│ └── release.yml # build on tag (PyPI publish disabled)
├── pyproject.toml
├── LICENSE
└── README.md
🔄 CI / CD
- CI (
.github/workflows/ci.yml) runs black, ruff, mypy, and pytest on Python 3.11, 3.12, 3.13, and 3.14 for every push/PR tomain, and checks thatduckdb-mcp --helpworks. - CD (
.github/workflows/release.yml) builds the sdist/wheel on av*tag and attaches them to the GitHub Release. PyPI publishing is intentionally disabled — thepublish-pypijob is gated behindif: false; see the comments in that file to enable it later.
🤝 Contributing
Issues and PRs are welcome! Please keep the footprint small (the minimalism is a feature 🪶), and make sure black / ruff / mypy / pytest all pass before opening a PR.
<div align="center">
Built with 🦆 + 🔌 · Licensed under MIT
</div>
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。