Datagrunt 5.7.0: Self-Hostable MCP Server for Deterministic Agent Tools
Datagrunt 5.7.0 is now available! This minor release introduces an optional, self-hostable Model Context Protocol (MCP) server (datagrunt[mcp], datagrunt-mcp) that exposes deterministic CSV, TSV, Excel, Parquet, and PDF tools to AI agents over local stdio and remote Streamable HTTP transports (PR #526, PR #527).
Highlights in Datagrunt 5.7.0
- Optional
datagrunt[mcp]Extra &datagrunt-mcpCLI — Built on the official Python MCP SDK v2 (mcp>=2.0.0), with PEP 562 lazy loading indatagrunt.mcpsoimport datagruntandimport datagrunt.mcpnever eagerly importmcp,starlette,uvicorn,duckdb, orpolars. - Nine Deterministic Agent Tools + Server Resource — Exposes read-only-by-default
list_files,inspect_file,read_sample,query_file,pdf_to_markdown,pdf_extract_elements, andpdf_inspect_corpus(plusdatagrunt://server/info), alongside opt-in write-gatedconvert_fileandpdf_export. - Symlink-Safe Root Sandboxing & Uncompressed-Size Guards — Confines every read, discovery scan, and write to canonical configured roots via
PathSandbox, blocks dot-prefixed output segments and in-place source overwrites, and rejects Parquet RLE/dictionary and XLSX zip bombs before materialization. - Hardened Single-Statement Read-Only DuckDB SQL — Combines lexical tokenization with DuckDB’s own
conn.extract_statements()parser, locks down every session (enable_external_access=false,temp_directory='',lock_configuration=true), enforces per-query CPU timeouts viaconn.interrupt(), and preservesDecimaland non-finite float distinctness in JSON. - Fail-Closed Self-Hosted Streamable HTTP — Refuses non-loopback HTTP bindings without a Bearer token (
>= 16chars via env var), enforces constant-time Bearer auth, sliding-window per-client rate limiting, HTTP method allowlists, hardened security headers,/healthzprobing, and loopback DNS-rebinding protection.
1. Optional [mcp] Extra, Lazy Loading & datagrunt-mcp CLI
Install the MCP server alone for tabular tools, or pair it with [pdf] to enable deterministic PDF Markdown rendering, structured element extraction, and PDF export:
# Tabular MCP server only
uv pip install "datagrunt[mcp]"
# Tabular + PDF MCP server
uv pip install "datagrunt[mcp,pdf]"In pyproject.toml, datagrunt registers the datagrunt-mcp console script (datagrunt.mcp.cli:main) and also supports python -m datagrunt.mcp:
# Local stdio transport for Claude Desktop, Cursor, or local agents
datagrunt-mcp --root /path/to/dataTrue to Datagrunt’s lazy-import architecture, "mcp" is registered in datagrunt’s _SUBPACKAGES table and datagrunt.mcp._extra defers importing mcp.server.mcpserver, starlette, and uvicorn until create_server(), create_streamable_http_app(), or run_server() is actually called. Config, exception, and PathSandbox types remain importable even when [mcp] is not installed:
from pathlib import Path
from datagrunt.mcp import MCPServerConfig, PathSandbox
# Pure config and sandbox types work with zero optional extras
config = MCPServerConfig(roots=(Path("."),), max_rows=100)
sandbox = PathSandbox(config)
print(sandbox.roots)2. Deterministic Agent Tools & Server Resource
create_server(config) registers seven read-only tools and one JSON resource by default, keeping write tools completely hidden unless allow_writes=True (--allow-writes):
- Resource
datagrunt://server/info— Reports server version,root_count,allow_writes,has_dedicated_output_dir,pdf_enabled,pdf_extra_installed,pdf_sandbox, activelimits, andsupported_formats. - Discovery & Tabular Tools:
list_files(directory=None, recursive=False, glob=None, limit=100)— Lists CSV, TSV, Excel, Parquet, PDF, and verified v5 PDF bundles (manifest.jsondirectories) in deterministic sorted order.inspect_file(path, sheet=None, lenient=False, pdf_ocr="auto")— Returns CSV dialect and normalized column metadata, Excel sheet names and dtypes, Parquet schema and row groups, or PDF/bundle page summaries and element counts, plusdb_tableandsql_alias="data".read_sample(path, n_rows=20, offset=0, sheet=None, columns=None, normalize_columns=False, lenient=False)— Returns a bounded, paginated slice of rows from CSV, TSV, Excel, or Parquet files.query_file(path, sql, sheet=None, normalize_columns=False, lenient=False, max_rows=None, pdf_ocr="auto")— Runs validated read-only DuckDB SQL over CSV, TSV, Excel, Parquet, or PDF element frames registered asdataanddb_table.
- PDF Tools (hidden when
--disable-pdfis passed):pdf_to_markdown(path, page_start=None, page_end=None, include_hidden=False, ocr="auto", max_chars=None)— Renders deterministic Markdown, optionally sliced by 1-indexed page range and bounded bymax_chars(default100,000).pdf_extract_elements(path, kind=None, page_start=None, page_end=None, include_hidden=False, offset=0, limit=100, ocr="auto")— Extracts paginatedheading,paragraph,key_value,table,list, andfigureelements with bounding boxes,scope_path,hidden_reasons, androute.pdf_inspect_corpus(corpus_dir)— Summarizes a verified v5 corpus (corpus_manifest.json) without requiring the[pdf]extra.
- Opt-In Write Tools (registered only when
--allow-writes/allow_writes=True):convert_file(...)— Converts CSV, TSV, Excel, or Parquet tocsv,excel,json,jsonl, orparquet(supportingall_sheets=True).pdf_export(...)— Exports a PDF or bundle tojson,jsonl,markdown,parquet,csv, or a checksummed v5bundledirectory.
All tool invocations run off the asyncio event loop via anyio.to_thread.run_sync bounded by anyio.CapacityLimiter(config.max_concurrent_tools) (default 8), and unexpected internal errors surface safely as Internal tool execution error (<TypeName>) without leaking host paths or tracebacks.
from pathlib import Path
from datagrunt.mcp import MCPServerConfig, create_server
# Read-only MCP server over a sandboxed data directory
config = MCPServerConfig(
roots=(Path("/data"),),
allow_writes=False,
max_rows=200,
)
server = create_server(config)3. Symlink-Safe Path Sandboxing & Uncompressed-Size Guards
PathSandbox enforces strict canonical containment before any reader or writer touches disk:
- Canonical read & discovery containment: Every read path is canonicalized with
resolve(strict=True)and checked againstconfig.roots. Traversal (..), symlink escapes outside configured roots, broken symlinks, NUL bytes, and non-regular special files raisePathAccessError. - Write-root isolation (
--output-dir): Whenallow_writes=True, writes are confined tooutput_dirif configured (orrootsotherwise).resolve_write()refuses symlinked targets or symlinked parent directories, blocks dot-prefixed segments (such as.envrcor.github), enforces format-appropriate file suffixes, defaults tooverwrite=False, forbids overwriting the source input file, and validates every per-sheet output path beforeconvert_file(..., all_sheets=True)writes anything. - Bomb & memory-exhaustion guards:
max_file_bytes(default250 MiB) caps full file reads and SQL inputs, and_check_uncompressed_budget()inspects Parquet row-group/dictionary materialized size estimates and XLSX zip entry sizes before full materialization.
4. Hardened Read-Only DuckDB SQL Execution
datagrunt.mcp.sql_guard protects query_file with layered pre-execution and engine-level controls:
- Lexical SQL inspection (
validate_readonly_sql): Tokenizes--line comments, nested/* ... */block comments, single-quoted strings, DuckDBE'...'escape strings, dollar-quoted$tag$...$tag$strings, and double-quoted identifiers so quoted calls like"duckdb_settings"()cannot evadeFORBIDDEN_FUNCTIONS. Rejects multi-statement queries, queries exceeding32,768characters, mutating keywords, and external-scan or introspection functions (READ_CSV,READ_PARQUET,READ_XLSX,GLOB,CURRENT_SETTING,DUCKDB_SETTINGS,DUCKDB_SECRETS,GETENV, and more). - Locked-down DuckDB session (
execute_readonly_sql): Creates a fresh:memory:connection, registerstable_nameanddata, executes 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, then parses authoritatively withconn.extract_statements()to ensure a singleSELECTorEXPLAINstatement. - Timeout & lossless JSON serialization: A
threading.Timercallsconn.interrupt()aftersql_timeout_s(default30.0s), whilejson_safe_value()serializesDecimalvalues andNaN/Infinity/-Infinityfloats as strings so precision andNULLdistinctness are preserved.
5. Self-Hosted Streamable HTTP & ASGI Security
For shared or containerized deployments, datagrunt-mcp --transport streamable-http exposes /mcp alongside an unauthenticated GET/HEAD /healthz endpoint (returning {"status": "ok"} with no version disclosure):
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"You can also embed the hardened ASGI application directly in Python with create_streamable_http_app():
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)Key HTTP security defaults in HTTPSettings and wrap_http_security:
- Fail-closed non-loopback binding: Binding to a non-loopback address without
DATAGRUNT_MCP_AUTH_TOKEN(minimum16characters, read strictly from an environment variable rather than CLI flags) raisesConfigurationErrorunless--allow-insecure-no-authis explicitly passed. - Constant-time Bearer authentication (
BearerAuthMiddleware): Validates HTTPAuthorization: Bearer ...headers and WebSocket upgrades withhmac.compare_digest(never accepting tokens in URL query strings). - Per-client sliding-window rate limiting (
RateLimitMiddleware): Caps requests at120RPM per client by default (--rate-limit-rpm,0disables) using a bounded4,096-client LRUOrderedDictand/64IPv6 grouping. - Method allowlisting & security headers (
SecurityHeadersMiddleware): Restricts methods toGET,POST,DELETE,OPTIONS, andHEAD(405otherwise) and attachesnosniff,X-Frame-Options: DENY,Cache-Control: no-store,Content-Security-Policy, andPermissions-Policyheaders on every response. - DNS rebinding protection: Covers all loopback aliases (
127.0.0.1:*,localhost:*,[::1]:*, plus the configured loopback host) when bound locally, and derives matching host/origin patterns when only--allowed-hostor--allowed-originis provided.
6. CI & Packaging Updates
- Optional dependency & script entrypoint:
pyproject.tomladdsmcp = ["mcp>=2.0.0"]under[project.optional-dependencies]anddatagrunt-mcp = "datagrunt.mcp.cli:main"under[project.scripts]. - Full CI & audit coverage:
.github/workflows/ci.ymlinstalls.[dev,pdf,rationalize,mcp]across the Rust/Python test jobs and.[pdf,rationalize,mcp]inpip-audit, enforced bytests/test_workflows.pyalongside the new test suite undertests/mcp_tests/.
Getting Started with Datagrunt 5.7.0
Install or upgrade with uv:
uv pip install --upgrade "datagrunt[mcp,pdf]"Or with pip:
pip install --upgrade "datagrunt[mcp,pdf]"Explore the new MCP Server Guide and Installation Docs for the full CLI flag matrix, environment variables, and tool reference.