Datagrunt 5.7.0: Self-Hostable MCP Server for Deterministic Agent Tools

November 30, 2026by Martin Graham

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

  1. Optional datagrunt[mcp] Extra & datagrunt-mcp CLI — Built on the official Python MCP SDK v2 (mcp>=2.0.0), with PEP 562 lazy loading in datagrunt.mcp so import datagrunt and import datagrunt.mcp never eagerly import mcp, starlette, uvicorn, duckdb, or polars.
  2. 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, and pdf_inspect_corpus (plus datagrunt://server/info), alongside opt-in write-gated convert_file and pdf_export.
  3. 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.
  4. 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 via conn.interrupt(), and preserves Decimal and non-finite float distinctness in JSON.
  5. Fail-Closed Self-Hosted Streamable HTTP — Refuses non-loopback HTTP bindings without a Bearer token (>= 16 chars via env var), enforces constant-time Bearer auth, sliding-window per-client rate limiting, HTTP method allowlists, hardened security headers, /healthz probing, 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/data

True 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, active limits, and supported_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.json directories) 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, plus db_table and sql_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 as data and db_table.
  • PDF Tools (hidden when --disable-pdf is 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 by max_chars (default 100,000).
    • pdf_extract_elements(path, kind=None, page_start=None, page_end=None, include_hidden=False, offset=0, limit=100, ocr="auto") — Extracts paginated heading, paragraph, key_value, table, list, and figure elements with bounding boxes, scope_path, hidden_reasons, and route.
    • 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 to csv, excel, json, jsonl, or parquet (supporting all_sheets=True).
    • pdf_export(...) — Exports a PDF or bundle to json, jsonl, markdown, parquet, csv, or a checksummed v5 bundle directory.

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 against config.roots. Traversal (..), symlink escapes outside configured roots, broken symlinks, NUL bytes, and non-regular special files raise PathAccessError.
  • Write-root isolation (--output-dir): When allow_writes=True, writes are confined to output_dir if configured (or roots otherwise). resolve_write() refuses symlinked targets or symlinked parent directories, blocks dot-prefixed segments (such as .envrc or .github), enforces format-appropriate file suffixes, defaults to overwrite=False, forbids overwriting the source input file, and validates every per-sheet output path before convert_file(..., all_sheets=True) writes anything.
  • Bomb & memory-exhaustion guards: max_file_bytes (default 250 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:

  1. Lexical SQL inspection (validate_readonly_sql): Tokenizes -- line comments, nested /* ... */ block comments, single-quoted strings, DuckDB E'...' escape strings, dollar-quoted $tag$...$tag$ strings, and double-quoted identifiers so quoted calls like "duckdb_settings"() cannot evade FORBIDDEN_FUNCTIONS. Rejects multi-statement queries, queries exceeding 32,768 characters, mutating keywords, and external-scan or introspection functions (READ_CSV, READ_PARQUET, READ_XLSX, GLOB, CURRENT_SETTING, DUCKDB_SETTINGS, DUCKDB_SECRETS, GETENV, and more).
  2. Locked-down DuckDB session (execute_readonly_sql): Creates a fresh :memory: connection, registers table_name and data, executes and verifies SET temp_directory='', SET autoinstall_known_extensions=false, SET autoload_known_extensions=false, SET enable_external_access=false, SET max_memory=..., SET threads=1, and SET lock_configuration=true, then parses authoritatively with conn.extract_statements() to ensure a single SELECT or EXPLAIN statement.
  3. Timeout & lossless JSON serialization: A threading.Timer calls conn.interrupt() after sql_timeout_s (default 30.0 s), while json_safe_value() serializes Decimal values and NaN / Infinity / -Infinity floats as strings so precision and NULL distinctness 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 (minimum 16 characters, read strictly from an environment variable rather than CLI flags) raises ConfigurationError unless --allow-insecure-no-auth is explicitly passed.
  • Constant-time Bearer authentication (BearerAuthMiddleware): Validates HTTP Authorization: Bearer ... headers and WebSocket upgrades with hmac.compare_digest (never accepting tokens in URL query strings).
  • Per-client sliding-window rate limiting (RateLimitMiddleware): Caps requests at 120 RPM per client by default (--rate-limit-rpm, 0 disables) using a bounded 4,096-client LRU OrderedDict and /64 IPv6 grouping.
  • Method allowlisting & security headers (SecurityHeadersMiddleware): Restricts methods to GET, POST, DELETE, OPTIONS, and HEAD (405 otherwise) and attaches nosniff, X-Frame-Options: DENY, Cache-Control: no-store, Content-Security-Policy, and Permissions-Policy headers 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-host or --allowed-origin is provided.

6. CI & Packaging Updates

  • Optional dependency & script entrypoint: pyproject.toml adds mcp = ["mcp>=2.0.0"] under [project.optional-dependencies] and datagrunt-mcp = "datagrunt.mcp.cli:main" under [project.scripts].
  • Full CI & audit coverage: .github/workflows/ci.yml installs .[dev,pdf,rationalize,mcp] across the Rust/Python test jobs and .[pdf,rationalize,mcp] in pip-audit, enforced by tests/test_workflows.py alongside the new test suite under tests/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.