Back to Browse

Chunktuner MCP Server

Developer ToolsModerate5.3MCP RegistryLocal
Free

Server data from the Official MCP Registry

Benchmark chunking strategies on your corpus and recommend the best RAG chunking config.

About

Benchmark chunking strategies on your corpus and recommend the best RAG chunking config.

Security Report

5.3
Moderate5.3Moderate Risk

The chunktuner MCP server shows solid security design: local paths are confined to CHUNK_TUNER_BASE_DIR, URL fetching is opt-in via CHUNK_TUNER_ALLOW_URLS=1 with an SSRF guard, and API keys are read from environment variables rather than hardcoded. The main points for users are that document content is sent to the configured LLM provider when dataset generation or generation metrics are enabled, and that the tools.py file was truncated so its remaining registrations were not reviewed. Supply chain analysis found 8 known vulnerabilities in dependencies (1 critical, 1 high severity). Package verification found 1 issue.

9 files analyzed · 13 issues found

Security scores are indicators to help you make informed decisions, not guarantees. Always review permissions before connecting any MCP server.

Permissions Required

This plugin requests these system permissions. Most are normal for its category.

File System Read

Reads files on your machine. Normal for tools that analyze or process local data.

File System Write

Writes or modifies files on your machine. Check that this is expected for the tool.

HTTP Network Access

Connects to external APIs or services over the internet.

env_vars

Check that this permission is expected for this type of plugin.

What You'll Need

Set these up before or after installing:

Absolute corpus root; every local path a tool receives must be under it.Optional

Environment variable: CHUNK_TUNER_BASE_DIR

Set to 1 to let tools fetch public http(s) URLs (SSRF-guarded). Off when unset.Optional

Environment variable: CHUNK_TUNER_ALLOW_URLS

LiteLLM model id for dataset generation, generation metrics and agentic.Optional

Environment variable: CHUNKTUNER_LLM_MODEL

Optional OpenAI-compatible endpoint for LiteLLM (e.g. a local server).Optional

Environment variable: CHUNKTUNER_API_BASE

Optional API key for CHUNKTUNER_API_BASE.Required

Environment variable: CHUNKTUNER_API_KEY

How to Install

Add this to your MCP configuration file:

{
  "mcpServers": {
    "chunktuner": {
      "command": "uvx",
      "args": [
        "chunktuner==0.3.0"
      ],
      "env": {
        "CHUNKTUNER_API_KEY": "your-chunktuner-api-key-here",
        "CHUNKTUNER_API_BASE": "your-chunktuner-api-base-here",
        "CHUNKTUNER_LLM_MODEL": "your-chunktuner-llm-model-here",
        "CHUNK_TUNER_BASE_DIR": "your-chunk-tuner-base-dir-here",
        "CHUNK_TUNER_ALLOW_URLS": "your-chunk-tuner-allow-urls-here"
      }
    }
  }
}

Some servers take additional arguments. See the repository for details.

Documentation

View on GitHub

From the project's GitHub README.

chunktuner

PyPI version Python versions License: MIT CI Docs

Auto chunking tuner and MCP server for RAG pipelines.

Give it your documents. It tries multiple chunking strategies, measures which setup supports retrieval best, and recommends a configuration for your corpus and use case. Zero API cost to start — run estimate for a dry-run before any paid calls.

Full documentation: shantanu-deshmukh.github.io/chunktuner

flowchart TD
    Lib["Python library<br/>files, URLs, repos"] --> Ingest
    CLI["CLI (chunk-tune)<br/>files, directories, URLs, repos"] --> Ingest
    MCP["MCP server<br/>files and repos under CHUNK_TUNER_BASE_DIR<br/>URLs opt-in (CHUNK_TUNER_ALLOW_URLS=1)"] --> Ingest

    Ingest["Ingest your documents"] --> Tune

    subgraph Tune ["AutoTuner: for every strategy and param set"]
        direction LR
        Chunk["Chunk document"] --> Embed["Embed chunks<br/>and queries"] --> Score["Score retrieval<br/>recall, MRR, NDCG"]
    end

    Tune --> Rank["Rank all configs<br/>against baseline"] --> Best(["Recommended config<br/>printed"])

What it does

When building a RAG pipeline, how you split documents into chunks directly impacts retrieval quality. chunktuner automates the process of finding the optimal chunking strategy for your specific corpus, embedding model, and use case.

It benchmarks strategies like fixed-token windows, recursive character splitting, semantic splitting, PDF structural chunking, and AST-based code chunking — then scores each one against retrieval metrics (token recall, MRR, NDCG) over an evaluation dataset (your own question file, LLM-generated questions, or a built-in placeholder dataset). Generation metrics (RAGAS faithfulness, answer relevancy) are opt-in (--generation-metrics with the ragas extra and a real dataset); they are reported next to the retrieval metrics but are not part of the default scores.

The CLI ingests local files and directories, a single http(s) URL (HTML, plain text, markdown or PDF) and, with --repo, a local code repository (vendor and build directories skipped). The MCP server and HTTP API take files and repositories under CHUNK_TUNER_BASE_DIR, and URLs only when CHUNK_TUNER_ALLOW_URLS=1. URL fetching always refuses private, loopback, link-local and reserved addresses, on every redirect hop.


Interfaces

  • Python library — programmatic integration into your pipeline
  • CLI (chunk-tune) — human-driven tuning from the terminal
  • MCP server — use directly from Claude Desktop or any MCP host

Quickstart

# Install (pick one)
uv tool install chunktuner
pip install chunktuner

# Initialize workspace (embedding_model defaults to null — no API calls)
chunk-tune init

# See cost estimate before running anything
chunk-tune estimate ./my_docs --use-case rag_qa

# Get a recommendation (dummy embeddings by default; add --embedding-model for real ones)
chunk-tune recommend ./my_docs --use-case rag_qa

Evaluation datasets. Without a dataset flag, evaluate / compare / recommend use a placeholder dataset (one query per document, whose answer is the document's first 200 characters) and print a warning. For meaningful scores, use one of:

  • --dataset questions.yaml: your own JSON/YAML file with a queries list (question, document_id, answer_spans, optional reference_answer). document_id can be the file path relative to the corpus path, an absolute path, or the file name.
  • --generate-dataset: generate questions with the configured llm_model. Run chunk-tune estimate ./my_docs --generate-dataset first to see the cost. The command asks for confirmation unless you pass --yes, and caches the dataset under cache_dir so re-runs reuse it.

Other evaluation flags:

  • --retrieval-scope document|corpus: which ranking feeds the score's rank metrics. The default is document.
  • --retrieval-mode dense|bm25|hybrid: first-stage retrieval. dense (default) ranks by embeddings, bm25 ranks lexically and makes no embedding calls, hybrid fuses both with reciprocal rank fusion. bm25 and hybrid need the bm25 extra.
  • --reranker <spec>: optional second stage that reorders the top 20 first-stage chunks per query. dummy (free, for tests), local or local:<hf-model-id> (local cross-encoder; needs the late extra and downloads the model), or any other string as a LiteLLM rerank model, e.g. cohere/rerank-english-v3.0 (paid API; the command asks for confirmation unless you pass --yes).
  • --embedding-mode independent|contextualized: how chunks are embedded. independent (default) embeds each chunk on its own; contextualized embeds each chunk with its whole document: late chunking for local:<hf-model-id> models, otherwise a contextualized LiteLLM model such as voyage/voyage-context-4. Not allowed with --retrieval-mode bm25 (exits 2).
  • --embedding-model local:<hf-model-id>: run a sentence-transformers embedding model on your machine (needs the late extra and downloads the model; no API cost, so no confirmation prompt).
  • --no-cache: turn off the embedding cache, which is on by default for real embedding models.
  • --generation-metrics: also compute RAGAS faithfulness and answer_relevancy (needs the ragas extra and --dataset or --generate-dataset). The configured llm_model answers each eval query from the retrieved chunks and judges the answers (about 6 LLM calls per query per config; answer_relevancy also needs a real embedding model). Report-only: not part of the default scores. Run chunk-tune estimate ./my_docs --generation-metrics first to see the cost. The command asks for confirmation unless you pass --yes.
  • --top-k has no effect on metrics. Retrieval depth is a 2000-token context budget divided by the average chunk size.

Python API:

from pathlib import Path
from chunktuner import FileIngestor, DummyEmbeddingFunction, LiteLLMEmbeddingFunction, AutoTuner
from chunktuner import default_registry, Evaluator, ScoreCalculator

docs = FileIngestor().ingest_dir(Path("./my_docs"))

# Free/offline: use dummy embeddings for quick strategy comparison.
# Swap in LiteLLMEmbeddingFunction for real embeddings with any provider:
#   LiteLLMEmbeddingFunction("text-embedding-3-small")          # OpenAI
#   LiteLLMEmbeddingFunction("gemini/gemini-embedding-001")     # Google
#   LiteLLMEmbeddingFunction("openai/<id>", api_base="http://localhost:1234/v1")  # local
embedding_fn = DummyEmbeddingFunction()

tuner = AutoTuner(
    strategies=default_registry,
    evaluator=Evaluator(embedding_fn),
    scorer=ScoreCalculator(use_case="rag_qa"),
)
result = tuner.recommend(
    docs, use_case="rag_qa", strategies=["fixed_tokens", "recursive_character"]
)
print(result.best.config)

Example output

The financial example benchmark prints a ranked table with the winning config and how much it beats the baseline (chunk-tune recommend prints the best configuration):

  Rank   Strategy              Params                  Score   Recall   MRR    IOU   AvgTok
 ────────────────────────────────────────────────────────────────────────────────────────
   1 ★   recursive_character   1024 chr / 154 ov        0.821    0.950  0.880  0.062      212
     2   fixed_tokens          512 tok / 51 ov           0.764    0.920  0.840  0.059      444
   ...
  Baseline  fixed_tokens  512 tok / 0 ov  →  score 0.682
  Winner beats baseline by +0.139  (+20.4%)

Real-world example

See examples/financial_analysis for a full benchmark on S&P 500 earnings call transcripts — a corpus where separator choice and chunk size make a measurable difference in retrieval quality.

Run it offline with zero API cost:

cd examples/financial_analysis
uv sync
uv run python run_benchmark.py --fixture --num-transcripts 2

Supported strategies

StrategyBest for
fixed_tokensBaseline; uniform token windows
recursive_characterGeneral prose and documentation
paragraph_groupProse with clear paragraphs; groups of whole paragraphs
semanticToken-budget recursive splits (semchunk; no embeddings)
markdown_semanticStructured Markdown docs
pdf_structuralPDFs with layout regions and tables
structural_semanticPDF/DOCX/PPTX with mixed layout and text
late_chunkingFixed-token fallback (explicit only); for true late chunking use --embedding-mode contextualized with a local:<hf-model-id> model
agenticHigh-value narrative documents (explicit only; LLM cost)
code_astCode repos (Python, JS/TS/TSX, Go, Java, Rust, C, C++; others fall back to line windows)
code_windowCode baseline (sliding window)

MCP server (Claude Desktop)

A pure-Python stdio server (chunk-tune-mcp) built on the MCP Python SDK v2 (mcp>=2.3,<3, MCPServer). No Node.js build. See MCP setup.

Add to your MCP host config (claude_desktop_config.json for Claude Desktop, .mcp.json for Claude Code):

{
  "mcpServers": {
    "chunktuner": {
      "command": "uvx",
      "args": ["--from", "chunktuner[mcp]", "chunk-tune-mcp"],
      "env": {
        "CHUNK_TUNER_BASE_DIR": "/path/to/your/corpus"
      }
    }
  }
}

Tools available: list_strategies, preview_chunks, evaluate_chunking, recommend_config.

  • evaluate_chunking and recommend_config accept optional dataset_path, generate_dataset, retrieval_scope, retrieval_mode, reranker, embedding_mode, use_cache, generation_metrics and repo fields.
  • Their responses include a warnings list.
  • Every tool returns structured content (structuredContent) with an output schema, alongside the JSON text.
  • Both tools send progress notifications per evaluated config when the client asks for progress.

See MCP setup. The repository also has MCP Registry metadata (server.json) and a uv-type .mcpb bundle (packaging/mcpb/).


CLI reference

chunk-tune init       Bootstrap workspace config
chunk-tune analyze    Quick structural scan (no API cost)
chunk-tune estimate   Dry-run cost/token estimate
chunk-tune evaluate   Full evaluation across strategies
chunk-tune recommend  Evaluation + best config recommendation
chunk-tune compare    Side-by-side comparison of specific strategies
chunk-tune preview    Inspect how a strategy splits a document
chunk-tune cache      Manage embedding and chunk cache

Installation options

pip install chunktuner                 # CLI + library
uv add chunktuner                      # library
uv tool install chunktuner             # global CLI
uvx --from chunktuner chunk-tune …     # ephemeral CLI (no install)

# With optional extras
pip install "chunktuner[docling]"      # PDF/DOCX/PPTX support
uv add "chunktuner[docling]"           # PDF/DOCX/PPTX support
uv add "chunktuner[ragas]"             # generation metrics (--generation-metrics)
uv add "chunktuner[semantic]"          # semantic and markdown_semantic chunking
uv add "chunktuner[code]"              # AST code chunking
uv add "chunktuner[bm25]"              # BM25 / hybrid retrieval
uv add "chunktuner[late]"              # local embeddings, late chunking, cross-encoder reranker
uv add "chunktuner[all]"               # everything

Contributing

See CONTRIBUTING.md.


Author

Shantanu Deshmukh — full stack developer building E2E AI applications.

LinkedIn / Twitter

Reviews

No reviews yet

Be the first to review this server!