MCP Server (Self-Hostable Agent Tools)
Datagrunt 5.7.0 introduces an optional, self-hostable Model Context Protocol (MCP) server (datagrunt-mcp) that gives AI agents deterministic, read-only-by-default access to CSV, TSV, Excel, Parquet, PDF, and verified v5 PDF bundle/corpus files without writing ad-hoc code or leaking host paths.
Every tool delegates directly to Datagrunt’s deterministic readers, writers, and locked-down DuckDB SQL engine—there are zero LLM calls inside the server, and data values are preserved rather than silently transformed.
Installation & Lazy Loading
Install the mcp extra (official Python MCP SDK v2, mcp>=2.0.0), optionally alongside pdf to enable deterministic PDF tools:
# Tabular MCP tools (CSV, TSV, Excel, Parquet)
uv pip install "datagrunt[mcp]"
# Tabular + deterministic PDF tools
uv pip install "datagrunt[mcp,pdf]"import datagrunt and import datagrunt.mcp never eagerly import mcp, starlette, uvicorn, duckdb, or polars. Configuration, exception, and PathSandbox classes load with zero extra dependencies, while create_server(), create_streamable_http_app(), and run_server() load lazily via PEP 562 __getattr__ and raise an ImportError with an install hint if [mcp] is missing.
Running the Server
Start the server via the datagrunt-mcp console script or python -m datagrunt.mcp.
Local stdio Transport
For Claude Desktop, Cursor, or local agent clients, stdio is the default transport. All logs are written strictly to stderr so stdout JSON-RPC framing stays intact:
datagrunt-mcp --root /path/to/dataRepeat --root (or set DATAGRUNT_MCP_ROOTS delimited by os.pathsep) to expose multiple allowed root directories. If omitted, the server defaults to the current working directory.
Self-Hosted Streamable HTTP Transport
Bind locally on 127.0.0.1:8000 at /mcp (with an unauthenticated GET/HEAD /healthz probe returning {"status": "ok"}):
datagrunt-mcp --transport streamable-http --root /path/to/dataFor remote, Docker, or horizontally scaled deployments, provide a Bearer token (minimum 16 characters, always via an environment variable—never on the CLI) and enable --stateless-http:
export DATAGRUNT_MCP_AUTH_TOKEN="$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')"
datagrunt-mcp \
--transport streamable-http \
--host 0.0.0.0 \
--port 8000 \
--root /data \
--stateless-http \
--allowed-host "mcp.example.com"Mounting the ASGI App in Python
Use create_streamable_http_app() or create_server() to embed the MCP server inside an existing Starlette/Uvicorn/Gunicorn service:
from pathlib import Path
from datagrunt.mcp import HTTPSettings, MCPServerConfig, create_streamable_http_app
config = MCPServerConfig(
roots=(Path("/data"),),
allow_writes=True,
output_dir=Path("/exports"),
http=HTTPSettings(
host="127.0.0.1",
port=8000,
stateless_http=True,
json_response=True,
),
)
app = create_streamable_http_app(config)Deterministic Tools & Resource Catalog
All tools return bounded, JSON-serializable structured payloads and execute synchronously off the event loop via anyio.to_thread.run_sync with an anyio.CapacityLimiter (default 8 concurrent executions).
Server Capabilities Resource
datagrunt://server/info(application/json) — Returns server name, version,root_count,allow_writes,has_dedicated_output_dir,pdf_enabled,pdf_extra_installed,pdf_sandbox, configuredlimits(max_rows,max_chars,max_file_bytes,max_sql_memory), andsupported_formats.
Read-Only Tabular & Discovery Tools
| Tool | Purpose | Key Options |
|---|---|---|
list_files |
Discover supported CSV, TSV, Excel, Parquet, PDF, and verified PDF bundle directories inside configured roots | directory, recursive=False, glob, limit=100 (max 1000) |
inspect_file |
Return structural metadata: CSV dialect/columns/rows, Excel sheets/dtypes, Parquet schema/row groups, or PDF/bundle page & element summaries, plus db_table and sql_alias="data" |
path, sheet, lenient=False, pdf_ocr="auto" |
read_sample |
Read a bounded, paginated row slice from CSV, TSV, Excel, or Parquet files | path, n_rows=20, offset=0, sheet, columns, normalize_columns=False, lenient=False |
query_file |
Execute a validated single-statement read-only DuckDB SQL query against table data (or db_table) |
path, sql, sheet, normalize_columns=False, lenient=False, max_rows, pdf_ocr="auto" |
Read-Only PDF Tools
Registered when enable_pdf=True (disabled by --disable-pdf). pdf_inspect_corpus works without the [pdf] extra; pdf_to_markdown and pdf_extract_elements require [pdf].
| Tool | Purpose | Key Options |
|---|---|---|
pdf_to_markdown |
Render deterministic Markdown from a PDF or verified v5 bundle, optionally sliced by 1-indexed page range | path, page_start, page_end, include_hidden=False, ocr="auto", max_chars |
pdf_extract_elements |
Extract paginated structured elements (heading, paragraph, key_value, table, list, figure) with element_id, bbox, scope_path, hidden_reasons, and route |
path, kind, page_start, page_end, include_hidden=False, offset=0, limit=100, ocr="auto" |
pdf_inspect_corpus |
Load and summarize a verified v5 PDF corpus directory (corpus_manifest.json) |
corpus_dir |
Opt-In Write & Export Tools
convert_file and pdf_export are hidden and disabled by default. Pass --allow-writes (and optionally --output-dir <dir>) to register them:
| Tool | Purpose | Supported output_format Values |
|---|---|---|
convert_file |
Convert CSV, TSV, Excel, or Parquet inside configured write roots; supports sheet, all_sheets=True, normalize_columns, lenient, overwrite=False |
csv, excel, json, jsonl, parquet |
pdf_export |
Export a PDF or verified bundle inside configured write roots (include_hidden=False, overwrite=False, ocr="auto") |
json, jsonl, markdown, parquet, csv, bundle |
Security & Resource Isolation
Symlink-Safe Path Sandboxing (PathSandbox)
- Canonical read containment: Every read path is resolved with
resolve(strict=True)and verified to sit inside configuredroots. Symlink escapes, traversal (..), NUL bytes, and non-regular special files are rejected withPathAccessError. - Dedicated write confinement: When
allow_writes=True, writes are confined to(output_dir,)if--output-diris configured (orrootsotherwise).PathSandbox.resolve_write()blocks writing through existing symlinks or symlinked parent directories, rejects dot-prefixed path segments (such as.envrcor.github), enforces format-appropriate file suffixes, defaults tooverwrite=False, refuses in-place overwrites of the source input file, and pre-validates every per-sheet output path whenconvert_file(..., all_sheets=True)runs. - Uncompressed-size & file-size budgets:
max_file_bytes(default250 MiB) caps full loads and SQL queries, and pre-checks guard against Parquet RLE/dictionary materialized-memory bombs and XLSX uncompressed zip bombs before materialization.
Hardened Read-Only DuckDB SQL (sql_guard)
query_file validates and executes SQL in two independent layers:
- Pre-execution SQL guard (
validate_readonly_sql): Tokenizes SQL (handling--comments, nested/* ... */comments, single-quoted strings, DuckDBE'...'escape strings, dollar-quoted$tag$...$tag$strings, and double-quoted identifiers so quoted calls like"duckdb_settings"()are still caught), rejects multi-statement queries and queries over32,768characters, restricts leading keywords toSELECT,WITH,EXPLAIN,DESCRIBE,SUMMARIZE,SHOW, andVALUES, and blocks mutating keywords as well as external-scan and introspection functions (READ_CSV,READ_PARQUET,READ_XLSX,GLOB,CURRENT_SETTING,DUCKDB_SETTINGS,DUCKDB_SECRETS,GETENV, etc.). - Locked-down DuckDB session (
execute_readonly_sql): Opens a fresh:memory:connection, registers the file asdataanddb_table, applies and verifiesSET temp_directory='',SET autoinstall_known_extensions=false,SET autoload_known_extensions=false,SET enable_external_access=false,SET max_memory=...,SET threads=1, andSET lock_configuration=true, parses authoritatively withconn.extract_statements()(accepting only singleSELECTorEXPLAINstatements), and enforcessql_timeout_s(default30.0s) viaconn.interrupt(). - Precision-preserving JSON output:
Decimalvalues serialize as strings andNaN/Infinity/-Infinityserialize as explicit strings so they remain distinct from SQLNULL(None).
Fail-Closed Streamable HTTP Hosting
- No accidental unauthenticated exposure:
HTTPSettings.validate_for_hosting()refuses to bind Streamable HTTP to any non-loopback host without a Bearer token (>= 16characters) unless--allow-insecure-no-authis explicitly passed (for example, behind an authenticating reverse proxy). - Middleware defense-in-depth (
wrap_http_security):SecurityHeadersMiddleware: enforcesGET,POST,DELETE,OPTIONS,HEAD(405otherwise) and setsx-content-type-options: nosniff,x-frame-options: DENY,cache-control: no-store,content-security-policy: default-src 'none'; frame-ancestors 'none', andpermissions-policy: camera=(), microphone=(), geolocation=().RateLimitMiddleware: bounded-memory (4096tracked clients LRU) per-client sliding-window limiter (rate_limit_rpm, default120; IPv6 grouped by/64), returning429withRetry-After.BearerAuthMiddleware: constant-timehmac.compare_digestBearer check for HTTP and WebSocket (query-string tokens are never accepted), exemptingGET/HEAD /healthz.
- DNS rebinding protection: Automatically allows all loopback aliases (
127.0.0.1:*,localhost:*,[::1]:*, plus the configured loopback bind host) when binding locally, and derives matching host/origin pairs when only--allowed-hostor--allowed-originis specified.
CLI Flags & Environment Variables
| CLI Flag | Environment Variable | Default | Description |
|---|---|---|---|
--transport |
DATAGRUNT_MCP_TRANSPORT |
stdio |
Transport mode (stdio or streamable-http) |
--root DIR |
DATAGRUNT_MCP_ROOTS |
Current working dir | Allowed read root (os.pathsep-delimited in env; repeatable CLI flag) |
--allow-writes |
DATAGRUNT_MCP_ALLOW_WRITES |
false |
Enable convert_file and pdf_export |
--output-dir DIR |
DATAGRUNT_MCP_OUTPUT_DIR |
None | Dedicated write root confining all outputs when writes are enabled |
--max-rows |
DATAGRUNT_MCP_MAX_ROWS |
200 |
Maximum rows returned per tool call (1–10000) |
--max-chars |
DATAGRUNT_MCP_MAX_CHARS |
100000 |
Maximum characters returned by pdf_to_markdown (1000–1000000) |
--max-file-bytes |
DATAGRUNT_MCP_MAX_FILE_BYTES |
262144000 (250 MiB) |
Maximum file size (and uncompressed Parquet/XLSX budget) |
--max-sql-memory |
DATAGRUNT_MCP_MAX_SQL_MEMORY |
512MB |
DuckDB memory cap per query (KB/MB/GB) |
--sql-timeout-s |
DATAGRUNT_MCP_SQL_TIMEOUT_S |
30.0 |
Per-query DuckDB CPU timeout in seconds (0.1–300.0) |
--max-concurrent-tools |
DATAGRUNT_MCP_MAX_CONCURRENT_TOOLS |
8 |
Maximum concurrent in-flight tool executions (1–64) |
--disable-pdf |
DATAGRUNT_MCP_DISABLE_PDF |
false |
Hide and disable all PDF tools |
--no-pdf-sandbox |
DATAGRUNT_MCP_NO_PDF_SANDBOX |
false |
Run PDFium in-process instead of memory-capped worker subprocesses |
--pdf-workers |
DATAGRUNT_MCP_PDF_WORKERS |
1 |
Worker count for PDF extraction (1–16) |
--host |
DATAGRUNT_MCP_HOST |
127.0.0.1 |
Bind host for streamable-http |
--port |
DATAGRUNT_MCP_PORT |
8000 |
Bind port for streamable-http |
--path |
DATAGRUNT_MCP_PATH |
/mcp |
Endpoint path for streamable-http |
--auth-token-env |
— | DATAGRUNT_MCP_AUTH_TOKEN |
Name of env var holding the HTTP Bearer token (>=16 chars) |
--allow-insecure-no-auth |
DATAGRUNT_MCP_ALLOW_INSECURE_NO_AUTH |
false |
Allow non-loopback HTTP binding without Bearer auth |
--stateless-http |
DATAGRUNT_MCP_STATELESS_HTTP |
false |
Run Streamable HTTP in stateless mode |
--json-response |
DATAGRUNT_MCP_JSON_RESPONSE |
false |
Return JSON responses instead of SSE streams |
--allowed-host |
DATAGRUNT_MCP_ALLOWED_HOSTS |
Loopback aliases | Allowed Host headers (comma-separated in env; repeatable CLI flag) |
--allowed-origin |
DATAGRUNT_MCP_ALLOWED_ORIGINS |
Loopback aliases | Allowed Origin headers (comma-separated in env; repeatable CLI flag) |
--rate-limit-rpm |
DATAGRUNT_MCP_RATE_LIMIT_RPM |
120 |
Per-client HTTP requests per minute (0 disables) |
--log-level |
DATAGRUNT_MCP_LOG_LEVEL |
WARNING |
stderr logging level (DEBUG, INFO, WARNING, ERROR) |