ChunkTuner
Summary: ChunkTuner's MCP server lets you benchmark and tune document chunking strategies on a local corpus directly from an MCP host like Claude Desktop.
List strategies (
list_strategies) — see registered chunking strategies, optionally filtered by content type.Preview chunking (
preview_chunks) — split inline text with a chosen strategy and params, with no embedding calls.Evaluate chunking (
evaluate_chunking) — run a dry-run cost/token estimate or a full evaluation over local files (underCHUNK_TUNER_BASE_DIR), with optional strategy/content-type filters, dataset file or LLM-generated dataset, embedding model, retrieval scope (document/corpus), caching, and doc limits.Recommend a config (
recommend_config) — run the tuner and get a ranked recommendation of the best chunking setup, with warnings (e.g., placeholder dataset).Cost control — dummy embeddings by default; dry-run estimates before paid LLM dataset generation; embedding cache supported.
Retrieval metrics only — recall/MRR/NDCG-style scoring; generation metrics are not exposed via MCP.
Integrates with OpenAI's embedding models to evaluate and score chunking strategies.
chunktuner
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/>local files / directories"] --> Ingest
MCP["MCP server<br/>local files under CHUNK_TUNER_BASE_DIR"] --> 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 optional and available only through the Python API (Evaluator(..., enable_generation_metrics=True) with the ragas extra); the CLI and MCP server report retrieval metrics only.
The CLI and MCP server ingest local files and directories. URL and repository ingestion (URLIngestor, RepoIngestor) are available from the Python API.
Related MCP server: LLM Evaluation Harness MCP Server
Interfaces
Python library — programmatic integration into your pipeline
CLI (
chunk-tune) — human-driven tuning from the terminalMCP 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_qaEvaluation 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 aquerieslist (question,document_id,answer_spans, optionalreference_answer).document_idcan be the file path relative to the corpus path, an absolute path, or the file name.--generate-dataset: generate questions with the configuredllm_model. Runchunk-tune estimate ./my_docs --generate-datasetfirst to see the cost. The command asks for confirmation unless you pass--yes, and caches the dataset undercache_dirso re-runs reuse it.
Other evaluation flags:
--retrieval-scope document|corpus: which ranking feeds the score's rank metrics. The default isdocument.--retrieval-mode dense|bm25|hybrid: first-stage retrieval.dense(default) ranks by embeddings,bm25ranks lexically and makes no embedding calls,hybridfuses both with reciprocal rank fusion.bm25andhybridneed thebm25extra.--reranker <spec>: optional second stage that reorders the top 20 first-stage chunks per query.dummy(free, for tests),localorlocal:<hf-model-id>(local cross-encoder; needs thelateextra 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).--no-cache: turn off the embedding cache, which is on by default for real embedding models.--top-khas 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 2Supported strategies
Strategy | Best for |
| Baseline; uniform token windows |
| General prose and documentation |
| Prose with clear paragraphs; groups of whole paragraphs |
| Token-budget recursive splits (semchunk; no embeddings) |
| Structured Markdown docs |
| PDFs with layout regions and tables |
| PDF/DOCX with mixed layout and text |
| Fixed-token fallback; true late chunking not implemented (explicit only) |
| High-value narrative documents (explicit only; LLM cost) |
| Code repos (Python; other languages fall back to line windows) |
| Code baseline (sliding window) |
MCP server (Claude Desktop)
Python FastMCP (chunk-tune-mcp, stdio). No Node.js build. See docs/mcp_setup.md.
Add to your .mcp.json:
{
"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 and use_cache fields, and their responses include a warnings list. See docs/mcp_setup.md.
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 cacheInstallation 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 support
uv add "chunktuner[docling]" # PDF/DOCX support
uv add "chunktuner[ragas]" # generation metrics (Python API only)
uv add "chunktuner[semantic]" # semantic chunking
uv add "chunktuner[code]" # AST code chunking
uv add "chunktuner[bm25]" # BM25 / hybrid retrieval
uv add "chunktuner[late]" # local cross-encoder reranker
uv add "chunktuner[all]" # everythingContributing
See CONTRIBUTING.md.
Author
Shantanu Deshmukh — full stack developer building E2E AI applications.
Available Tools
4 toolsevaluate_chunkingC
Dry-run cost estimate or full evaluation (DummyEmbeddingFunction if no model).
content_type restricts strategies to those supporting it. The response includes a
warnings list (e.g. when the trivial placeholder dataset is used).
Inputs: path (required), top_k, dry_run, max_docs, +8 more.
list_strategiesB
List registered chunking strategies, optionally filtered by content type.
Inputs: content_type. Returns: result
preview_chunksC
Chunk inline text with one strategy + params (no embeddings).
Inputs: text (required), strategy_name (required), config, content_type. Returns: result
recommend_configC
Run tuner and return ranked Recommendation (uses dummy embeddings by default).
The response adds a warnings list (e.g. when the trivial placeholder dataset is used).
Inputs: path (required), top_k, max_docs, use_case, +7 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 4 tools
Each tool targets a different stage of the workflow: listing strategies, previewing chunks, evaluating cost/quality, and recommending a configuration. The only mild overlap is between evaluate_chunking and recommend_config, since both can run evaluations, but the descriptions distinguish a direct evaluation from a ranked tuner recommendation.
All four tools follow a clear snake_case verb_noun pattern: list_strategies, preview_chunks, evaluate_chunking, recommend_config. The noun forms vary naturally with the action and remain predictable.
Four tools is a focused, coherent surface for a chunking tuning server, covering discovery, preview, evaluation, and recommendation. It is slightly thin but not problematically so, since each tool has a clear role.
The surface covers the main workflow: inspect available strategies, preview chunk output, evaluate configurations, and get recommendations. Minor gaps remain around saving/applying a recommended configuration or inspecting detailed strategy metadata, but core workflows are covered.
Maintenance
Related MCP Connectors
Pageshuck: PDF, Word and PowerPoint files to clean text and Markdown, tables kept, RAG chunks.
Ingest, manage, and retrieve documents for RAG-powered AI applications
LLM evaluation: compare models on cost and quality, score outputs, run benchmarks, analyse agents.
Count tokens (o200k/cl100k), truncate to a budget, chunk text for RAG and estimate LLM cost.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables version-controlled golden dataset management and semantic evaluation for RAG/LLM pipelines using TF-IDF cosine similarity, without requiring an LLM API key.923 PyPIMIT
- AlicenseNot gradedqualityDmaintenanceEvaluates RAG outputs on faithfulness, answer relevancy, and context precision using an LLM-as-a-Judge backend. Exposes tools for running evaluations, scoring individual samples, and checking thresholds, enabling CI gating and on-demand assessment via MCP.MIT
- AlicenseNot gradedqualityDmaintenanceEnables benchmarking of local LLM models (performance and quality) and sharing results to a public leaderboard via MCP tools.41 npm8Apache 2.0
- FlicenseNot gradedqualityDmaintenanceEnables document Q&A and knowledge retrieval through hybrid semantic and keyword search, with tools for document ingestion, chunking, summarization, PII redaction, and RAGAS-based evaluation.-