Model-Shunt
This server lets you delegate token-heavy file reading and boilerplate code generation to fast, economical worker models, and discover optimal models for each task.
Bulk read: Analyze multiple or large files by asking a targeted question; returns concise structured bullet points with exact line citations, saving up to ~90% primary agent tokens.
Code write: Generate boilerplate code (tests, mocks, stubs, configs) matching a reference file's conventions; optionally write directly to disk without consuming frontier output tokens.
Model discovery: Query available provider models and get recommendations for the best reader (high context, low cost) and writer (code intelligence) models.
Flexible routing: Override provider or model per call, supporting Gemini, Groq, OpenAI, DeepSeek, Anthropic, Ollama, and OpenRouter.
Safe MCP server: Runs locally over stdio, enforces workspace path restrictions, and returns structured errors without disrupting subsequent calls.
Allows Google Gemini models to be used as fast, economical worker models for bulk file analysis and boilerplate code generation.
Allows local Ollama models to serve as private, offline worker models for reading and code-writing tasks.
Allows OpenAI models to be used as worker models for delegated reading and code generation workloads.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Model-Shunt Use a worker model to summarize src/processor.py"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Model-Shunt π
A decoupled, zero-dependency, universal implementation of the Shunt model-routing pattern (originally conceived by Spotify Engineering).
Model-Shunt allows AI coding agents (Antigravity, Cursor, Windsurf, Claude Code, Aider, OpenHands, etc.) to delegate token-heavy I/O (bulk file reading/code analysis) and repetitive boilerplate generation (tests, mocks, stubs, configs) to fast, economical, or local worker models (Gemini 2.5 Flash, Groq/Llama, Ollama, DeepSeek, GPT-4o-mini). This cuts primary agent token consumption by up to 90% while keeping the main context window clean.
β‘ Key Highlights
Zero External Dependencies: Built with pure Python 3 standard library (
urllib,json,re,argparse). Nopip install, no virtual environment, and nonpmrequired.Agent-Agnostic: Works transparently across any AI coding agent via standard MCP (Model Context Protocol), standalone CLI scripts, or PreToolUse lifecycle hooks.
Dynamic Model Discovery & Auto-Routing: Queries the worker endpoint in real time to discover available models and automatically routes to the best model for the task:
Reader Mode (Bulk I/O): Prioritizes massive context windows and ultra-low cost (e.g.,
gemini-2.5-flash,llama-3.3-70b-versatile,gpt-4o-mini).Writer Mode (Code Generation): Prioritizes specialized coding models (e.g.,
qwen2.5-coder:latest,gemini-2.5-flash,deepseek-chat).
Bypasses Linux
ARG_MAXLimits: Unlike naive implementations that pass file contents as CLI arguments (capped at ~128 KB on Linux), Model-Shunt streams corpus data overstdin, allowing analysis of hundreds of thousands of lines without buffer overflows.Deterministic Line Numbering (
N|): Automatically prefixes every line in file blocks with its 1-based index, forcing worker models to cite verifiable, exact line numbers instead of hallucinating locations.Binary File Protection: Inspects byte headers to reject binary files (PDFs, images, compiled objects) before sending them to the LLM.
Network Resilience: Automatic exponential backoff retries for rate limits (HTTP 429) and transient server errors (HTTP 503/502), with configurable timeouts and token limits.
Map-Reduce for Oversized Corpora: When a
bulk_readpayload exceeds the direct limit (SHUNT_MAX_DIRECT_TOKENS, default ~200k tokens), Model-Shunt automatically splits the corpus into chunks, maps the question over each chunk (preserving absoluteN|line numbers), and reduces the extracts into one cited answer. Giant single-line files (minified JSON/JS) are sliced by characters with explicit position markers. Rate-limit pacing waits out provider quota windows instead of failing.
Related MCP server: Houtini LM
π Repository Structure
model-shunt/
βββ src/model_shunt/
β βββ worker.py # Universal LLM worker engine with model discovery (zero-deps)
β βββ server.py # Stdio MCP server exposing routing tools
βββ bin/model-shunt.js # npm/npx launcher shim (requires local Python 3)
βββ plugin/
β βββ .claude-plugin/ # Plugin manifest for hook-compatible agents
β βββ hooks/ # PreToolUse interceptor hooks (check-file-size, check-bash-read)
β βββ scripts/ # Executable streaming CLIs (bulk-read, code-write)
β βββ skills/ # Agent skill manifests (/bulk-reader, /code-writer)
βββ pyproject.toml # PyPI packaging (uvx / pip install)
βββ package.json # npm packaging (npx)
βββ config.example.json # Configuration template
βββ test_shunt.py # Automated test suite
βββ .gitignore # Credential and cache protectionβοΈ Configuration
Configure your worker model via environment variables or a config.json file (placed in ~/.config/model-shunt/config.json or in the project root):
Using config.json
{
"provider": "gemini",
"model": "auto",
"timeout": 90,
"max_tokens": 8192
}Tip: Setting
"model": "auto"(or passing--auto-modelin the CLI) will automatically inspect the provider's active models and pick the optimal one for reading vs writing.
Security: Do not put your API key in
config.jsonβ use environment variables instead (e.g.GEMINI_API_KEY,GROQ_API_KEY, orSHUNT_API_KEY). Anapi_keyfield exists as a last-resort fallback, but keeping secrets out of files is strongly recommended.
Using Environment Variables
# Google Gemini (Recommended: 1M token context, high speed, ultra-low cost)
export SHUNT_PROVIDER="gemini"
export GEMINI_API_KEY="your-api-key"
# Groq (Ultra-low latency inference)
export SHUNT_PROVIDER="groq"
export GROQ_API_KEY="your-api-key"
# Ollama (100% private, local, and free)
export SHUNT_PROVIDER="ollama"
export SHUNT_BASE_URL="http://localhost:11434/v1"
# OpenAI / DeepSeek / OpenRouter / Anthropic
export SHUNT_PROVIDER="deepseek"
export DEEPSEEK_API_KEY="your-api-key"π οΈ Usage Modes
Mode 1: Universal MCP Server (Recommended)
Model-Shunt provides a standard stdio MCP server exposing three tools:
get_available_models(provider?): Queries the provider endpoint and recommends reader and writer models. If discovery fails or is unsupported, returns built-in recommendations whose current availability is not verified.bulk_read(question, file_paths, model?, provider?): Reads large or multiple files and outputs concise, structured bullets with exact line citations. A citationname (N|k)is dropped when source linekdoes not contain that name.code_write(spec, reference_path, target_path?, model?, provider?): Generates code using a specification and reference file. Returns the code whentarget_pathis omitted; otherwise creates missing parent directories and writes the code, overwriting an existing target file.
bulk_read sends the selected files and question to the configured worker provider; code_write sends the specification and reference file. The provider can be remote or local (such as Ollama). Token savings depend on the input and response.
The MCP server runs locally over stdio. Set provider credentials through environment variables. File access follows resolved paths, so symlinks pointing outside the allowed workspace roots are rejected. Invalid requests return structured errors and leave the server available for subsequent calls.
Installation
MCP Registry name: mcp-name: io.github.yasmanycastillo/model-shunt
Universal one-liner (detects uv / pip / pipx / npm, installs the model-shunt command, and registers it with Claude Code if present):
curl -fsSL https://yasmanycastillo.github.io/model-shunt/install.sh | bashManual alternatives:
claude mcp add model-shunt -- uvx model-shunt # if you have uv
claude mcp add model-shunt -- npx -y model-shunt # if you have Node + PythonAny MCP client (Cursor, Windsurf, Antigravity, Claude Desktop, etc.) β add to its MCP settings. No clone, no absolute paths:
{
"mcpServers": {
"model-shunt": {
"command": "uvx",
"args": ["model-shunt"],
"env": {
"SHUNT_PROVIDER": "gemini",
"SHUNT_MODEL": "auto",
"GEMINI_API_KEY": "your-api-key"
}
}
}
}Fallback (offline / no uv / no npx): run straight from a clone with Python 3.9+ β replace
"command"/"args"with"command": "python3", "args": ["/absolute/path/to/model-shunt/src/model_shunt/server.py"].
Security: by default
bulk_read/code_writeonly operate on files inside the server's working directory (the agent workspace). SetSHUNT_ALLOWED_ROOTS(PATH-style list) to expand the sandbox.
Map-Reduce Tuning (optional)
Variable | Default | Purpose |
|
| Payloads above this estimated size switch to map-reduce |
|
| Chunk size in characters (~150k tokens) |
|
| Retries per chunk on rate limits |
|
| Seconds to wait out a provider quota window (free-tier TPM) |
Mode 2: PreToolUse Interceptor Hooks
For agents supporting pre-execution hooks (e.g., Claude Code, custom agent loops):
File Read Interceptor (
check-file-size):If the agent attempts a whole-file read on a file exceeding the threshold (default: 350 lines, configurable via
SHUNT_MIN_LINES), the hook blocks the call and instructs the agent to delegate tobulk-read.Targeted reads with
offsetandlimitare allowed, preserving surgical context for code editing.
Terminal Guard (
check-bash-read):Prevents agents from bypassing the read hook by executing commands like
cat,less, ormoreon large files directly in the terminal context.
Mode 3: Standalone CLI & Scripts
You can also use Model-Shunt directly from the command line or from agent bash sessions:
Discover Available Models & Recommendations
python3 src/model_shunt/worker.py --list-models --provider geminiRun Bulk Reading Analysis
./plugin/scripts/bulk-read \
--question "How does the token refresh cycle work?" \
--paths src/auth.py src/tokens.py \
--auto-modelGenerate Boilerplate Directly to Disk
./plugin/scripts/code-write \
--spec "Create unit tests for the BillingService covering charge and refund" \
--reference tests/test_user.py \
--target tests/test_billing.py \
--auto-modelπ§ͺ Verification
Run the built-in test suite to verify your environment:
python3 test_shunt.pyThe test suite validates:
Configuration resolution, fallback cascades, and model selection.
Binary file detection and rejection.
Hook decisions (surgical reads allowed, large file reads blocked, bash flag parsing).
MCP stdio protocol compliance and tool execution.
CLI discovery flags.
π License
MIT. Inspired by Spotify Engineering's Shunt architecture.
π Privacy
See PRIVACY.md for filesystem scope, provider data handling, and credential practices.
Available Tools
3 toolsbulk_readA
Reads multiple or large files and answers a targeted question using a cheap, fast worker model (e.g. Gemini Flash, Groq, Ollama). Saves ~90% tokens by returning only structured bullet points.
Inputs: question (required), file_paths (required), model, provider.
code_writeA
Generates boilerplate code (tests, mocks, stubs, configs) matching the patterns of a reference file. Can write directly to disk without consuming frontier output tokens.
Inputs: spec (required), reference_path (required), model, provider, +1 more.
get_available_modelsA
Discovers active models from the worker provider and recommends the best model for reading (high context / low cost) and writing (code intelligence). Enables calling agents to delegate dynamically to the best model.
Inputs: provider.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogβ¦
TDQS
Scored across 3 tools
The three tools have distinct purposes: bulk_read handles file reading and summarization, code_write handles code generation, and get_available_models handles model discovery. There is minor potential confusion between bulk_read and code_write since both involve file operations, but their core functions are clearly separated.
Tool names use a mix of conventions: bulk_read and code_write follow a noun_verb pattern, while get_available_models follows a verb_adjective_noun pattern. The naming is readable and descriptive, but the inconsistent verb placement (bulk_read vs get_available_models) creates minor inconsistency.
Three tools is on the low end but appropriate for a focused utility server that handles delegated reading, writing, and model selection. The count feels slightly thin for a server that could benefit from additional tools like a direct file write or model configuration tool, but it is not unreasonable.
The server covers the core workflow of reading files, generating code, and selecting models, but there are notable gaps. There is no tool for direct file writing (code_write writes to disk but only for boilerplate), no tool for updating existing code, and no way to configure or manage the worker provider beyond model discovery.
Maintenance
Related MCP Connectors
Persistent memory and cross-session learning for AI coding assistants (hosted remote MCP).
A paid remote MCP for OpenAI Codex agent coordination MCP, built to return verdicts, receipts, usage
OCR, transcription, file extraction, and image generation for AI agents via MCP.
Task management your AI agents can actually run. One line becomes a context-ready task over MCP.
Related MCP Servers
- FlicenseNot gradedqualityAmaintenanceEnables MCP clients like Claude Code to delegate bounded work β code review, boilerplate, commit messages, format conversion, embeddings β to a local GPU model or a cheaper cloud endpoint, keeping large file contents out of the orchestrator's context window. This cuts token costs dramatically while providing a second model for independent review.-
- FlicenseNot gradedqualityAmaintenanceEnables Claude Code and other MCP clients to offload bounded workβcode review, test stubs, boilerplate, commit messages, format conversion, embeddingsβto a local GPU model or a cheaper cloud, OpenAI-compatible endpoint. Source files are read by the server rather than the main model, cutting token spend while the orchestrating model keeps planning and verifying.-
- FlicenseNot gradedqualityAmaintenanceEnables MCP clients like Claude Code to delegate bounded workβcode review, boilerplate, commit messages, format conversion, embeddingsβto local or cloud OpenAI-compatible models, keeping large files out of the main model's context to cut token costs and provide a second opinion. It routes and profiles the target model automatically, while the orchestrating client retains planning and quality checks.-
- AlicenseNot gradedqualityBmaintenanceEnables Claude Code and other MCP clients to offload bounded tasks such as code review, test stubs, commit messages, and format conversion to local or cheaper cloud LLMs, cutting token usage while the primary model remains the orchestrator.MIT