Datagrunt 5.8.1: Lower Latency Across Agent, MCP Server, and CLI

December 3, 2026by Martin Graham

Datagrunt 5.8.1 is now available! This patch release targets end-to-end latency across datagrunt agent, the self-hosted MCP server (datagrunt-mcp), and the unified datagrunt CLI — eliminating redundant model turns, repeated file parses, serialized remote read barriers, and heavy startup imports.


Highlights in Datagrunt 5.8.1

  1. CSV VARCHAR Schema & TRY_CAST Guidance — inspect_file (CSV), the query_file tool description, MCP server instructions, and the standalone agent system prompt (SYSTEM_PROMPT_VERSION = "1.1.0") now explicitly report CSV columns as VARCHAR and guide TRY_CAST(...) on the first SQL query, cutting wasted read_sample and type-error retry turns.
  2. Provider-Agnostic thinking_level (--thinking-level) — Tunes reasoning effort (low, medium, high, xhigh) across Gemini (thinkingLevel / thinkingBudget), OpenAI reasoning models (reasoning_effort), and Anthropic (thinking.budget_tokens) via AgentConfig, --thinking-level, or DATAGRUNT_AGENT_THINKING_LEVEL.
  3. Bounded, Stat-Validated LRU Read Caches & --no-pdf-sandbox — Caches Arrow tables (64 MiB / 16-table cap) and extracted PDF documents (32 MiB / 8-doc cap) across MCP tool calls with stat fingerprinting, recursive non-symlink PDF bundle checks, and post-load TOCTOU validation, plus --no-pdf-sandbox for trusted local PDFs on datagrunt agent.
  4. Parallel Remote Built-In Read Execution — --allow-remote-reads (allow_remote_builtin_reads=True) promotes verified remote built-in read tools into the session-pinned allowlist at session start so multi-tool read turns run concurrently in read_batch groups, with inter-batch tools/list_changed re-planning.
  5. Lazy DuckDB, PyArrow, and Polars Imports on datagrunt inspect — PEP 562 lazy re-exports in datagrunt.core.csv_io and deferred imports in datagrunt.mcp.tools keep duckdb, pyarrow, and polars completely unloaded during CSV inspection.

1. CSV VARCHAR Schema & First-Try TRY_CAST SQL

Datagrunt intentionally preserves raw CSV values by loading CSV columns as VARCHAR in DuckDB (preserve, not transform). Previously, an AI agent inspecting a CSV file received column names without explicit SQL types, often triggering extra read_sample calls or failed SUM(amount) queries followed by a retry turn.

In Datagrunt 5.8.1:

  • inspect_file on CSV files now returns "dtypes": {col: "VARCHAR", ...} alongside a sql_note explaining TRY_CAST(col AS DOUBLE/BIGINT/DATE).
  • Both the MCP server instructions and the query_file tool description document the CSV VARCHAR contract and TRY_CAST(...) pattern.
  • datagrunt.agent.prompts bumps SYSTEM_PROMPT_VERSION from "1.0.0" to "1.1.0", instructing the agent to wrap numeric or date CSV columns in TRY_CAST(...) on its first query and to batch independent read-only tool calls in parallel.
# Inspect CSV dialect, column list, VARCHAR dtypes, and SQL guidance in JSON
datagrunt inspect sales.csv --json

2. Provider-Agnostic --thinking-level Controls

Reasoning models can spend significant wall-clock time on extended thinking for straightforward tabular or metadata queries. Datagrunt 5.8.1 adds a provider-agnostic ThinkingLevel ("low", "medium", "high", "xhigh") across the CLI (--thinking-level / DATAGRUNT_AGENT_THINKING_LEVEL), AgentConfig, and ModelRequest:

# Lower reasoning effort and disable subprocess PDF sandboxing for trusted local files
datagrunt agent \
  --model gemini:gemini-4-hydrogen \
  --vertex-project my-gcp-proj \
  --vertex-location global \
  --thinking-level low \
  --no-pdf-sandbox \
  --root ./data \
  "Summarize sales.csv"

Each provider adapter maps thinking_level to its native wire format while enforcing provider constraints:

  • Gemini (GeminiAgentModel): Sets generationConfig.thinkingConfig.thinkingLevel (LOW, MEDIUM, HIGH, XHIGH) on Gemini 3+/4+ models, and automatically maps to thinkingBudget (1024, 4096, 8192, 16384) on Gemini 2.0 / 2.5 models.
  • OpenAI (OpenAICompatibleAgentModel): Sets reasoning_effort for OpenAI reasoning models (o1, o3, o4, gpt-5, excluding o1-mini and o1-preview), clamping xhigh to high. Unsupported models (such as gpt-4o or local Ollama models) log a warning and omit reasoning_effort.
  • Anthropic (AnthropicAgentModel): Enables thinking: {"type": "enabled", "budget_tokens": ...} (1024, 4096, 8192, 16384), requires any explicit max_output_tokens to exceed budget_tokens (raising ValueError rather than silently overriding), downgrades forced tool_choice to {"type": "auto"}, and omits temperature.

You can configure thinking_level directly in Python using AgentConfig and THINKING_LEVELS:

from pathlib import Path
from datagrunt.agent import THINKING_LEVELS, AgentConfig, DatagruntAgent, InProcessMCPTarget
from datagrunt.mcp import MCPServerConfig

assert "low" in THINKING_LEVELS

config = AgentConfig(
    model="openai:o3-mini",
    mcp_target=InProcessMCPTarget(MCPServerConfig(roots=(Path("./data"),))),
    thinking_level="low",
    max_steps=10,
)
with DatagruntAgent(config) as agent:
    result = agent.run("Compute total revenue by region from sales.csv")
    print(result.text)

3. Bounded, Stat-Validated LRU Read Caches & --no-pdf-sandbox

Interactive agent sessions frequently issue multiple query_file queries against the same CSV/Excel/Parquet file or mix inspect_file, pdf_to_markdown, pdf_extract_elements, and query_file against the same PDF or PDF bundle. Datagrunt 5.8.1 introduces a thread-safe, bounded LRU cache module (datagrunt.mcp._cache) that reuses parsed Arrow tables and PDFDocument objects without sacrificing freshness or sandbox guarantees:

  • Bounded Arrow cache (query_file): Caches up to 16 Arrow tables / 64 MiB total (32 MiB single-table cap).
  • Bounded PDF cache (inspect_file, pdf_to_markdown, pdf_extract_elements, query_file): Caches up to 8 PDF documents / 32 MiB estimated memory (16 MiB single-document cap).
  • Stat fingerprinting & bundle integrity: Cache keys include (st_mtime_ns, st_size, st_ino) for regular files and a recursive, non-symlink directory walk (up to 512 entries) for PDF bundles so edits to nested artifacts (json/document.json, markdown/document.md, images/*) immediately invalidate the cache. Symlinks inside directories fail closed by bypassing the cache, and fingerprints are re-checked after loading to prevent TOCTOU races.
  • Policy isolation: Keys also isolate sheet, normalize_columns, lenient, ocr, and pdf_sandbox, ensuring unsandboxed extractions are never served under a sandboxed configuration.

For trusted local PDFs where subprocess worker startup overhead dominates short queries, datagrunt agent now exposes --no-pdf-sandbox (or DATAGRUNT_AGENT_PDF_SANDBOX=false) to run in-process MCP PDF extraction without spawning per-call worker subprocesses (--pdf-sandbox remains enabled by default).


4. Parallel Remote Built-In Reads with Inter-Batch Re-Planning

In 5.8.0, --allow-remote-reads auto-approved Datagrunt’s 6 built-in read-only tools (list_files, inspect_file, read_sample, query_file, pdf_extract_elements, pdf_to_markdown) inside the approval callback, which meant multi-tool read turns against a remote MCP server still executed sequentially behind per-call write_barrier checks.

In 5.8.1, enabling --allow-remote-reads (or AgentConfig(..., allow_remote_builtin_reads=True)) promotes verified built-in read tools discovered at session start (those whose remote annotations confirm readOnlyHint=True and destructiveHint is not True) into the session-pinned AllowlistEntry set:

from datagrunt.agent import AgentConfig, DatagruntAgent, StreamableHTTPMCPTarget

config = AgentConfig(
    model="anthropic:claude-sonnet-4-5",
    mcp_target=StreamableHTTPMCPTarget(
        url="https://mcp.example.com/mcp",
        headers={"Authorization": "Bearer ..."},
    ),
    allow_remote_builtin_reads=True,
    thinking_level="low",
)
with DatagruntAgent(config) as agent:
    result = agent.run("Inspect all Q4 CSVs in parallel and summarize totals")
    print(result.text)

Security invariants remain strict:

  • Session-pinned definition_sha256: Only the 6 built-in read tools present and verified at session start are promoted.
  • Inter-batch tools/list_changed re-planning: When a turn mixes read and write calls, DatagruntAgent plans and dispatches one barrier batch at a time and checks tools_dirty before each batch. If tools/list_changed arrives mid-turn (for instance while awaiting interactive write approval), tools are refreshed and any mutated or newly added tool immediately drops back to write classification.

5. Lazy DuckDB, PyArrow, and Polars Imports on inspect

To keep datagrunt inspect and pure metadata calls fast, 5.8.1 converts datagrunt.core.csv_io to PEP 562 lazy re-exports, defers polars imports inside CSVStringSample and CSVColumns methods, extracts database_table_name_for_path() into datagrunt.core.file_io, moves json_safe_value() into pure-stdlib datagrunt.mcp._json, and defers duckdb/pyarrow imports in datagrunt.mcp.tools until query_file runs:

import io
import json
from datagrunt.cli import main

out = io.StringIO()
exit_code = main(["inspect", "sales.csv", "--json"], stdout=out, stderr=io.StringIO())
info = json.loads(out.getvalue())
print(exit_code, info["dtypes"], info["sql_note"])

Running datagrunt inspect on a CSV file now completes without importing duckdb or pyarrow.


Upgrading to Datagrunt 5.8.1

Upgrade with uv or pip:

# Core library + unified tabular CLI
uv pip install --upgrade datagrunt

# With optional extras for PDF, MCP server, or standalone agent
uv pip install --upgrade "datagrunt[pdf]"
uv pip install --upgrade "datagrunt[mcp,pdf]"
uv pip install --upgrade "datagrunt[agent,pdf]"

See the updated Unified CLI & Standalone Agent Guide and MCP Server Guide for complete flag references, caching caps, and provider tuning options.