m1-m2-agent — Cost-Aware Hierarchical Coding Agent & Context Firewall
Slash AI inference costs by up to 92% while making your frontier model smarter.
A 3-layer agent architecture that routes heavy tool loops to a cheap DeepSeek worker, compresses raw outputs (80–98% CCR) through a Context Firewall, and returns clean structured evidence to your frontier model — with zero context window bloat.
Installation
# Recommended — standard pip install
pip install m1-m2-agent
# Zero-install ephemeral run (uv / uvx)
uvx --from m1-m2-agent m2-mcp-server
# Fallback — pipx
pipx run --spec m1-m2-agent m2-mcp-server
Quickstart: Drop M2 into any project in 30 seconds
cd /your/project
m2-init
That's it. m2-init scaffolds 4 cognitive rule files (AGENTS.md, .cursorrules,
CLAUDE.md, .continuerules) and prints the exact MCP config JSON to paste into
your IDE. Any AI coding agent that reads those files will instantly know when and how
to delegate to M2.
Example output:
🚀 m2-init — scaffolding M2 Worker Agent integration into: /your/project
✅ Created AGENTS.md
✅ Created .cursorrules
✅ Created CLAUDE.md
✅ Created .continuerules
Generated 4 file(s): AGENTS.md, .cursorrules, CLAUDE.md, .continuerules
{
"mcpServers": {
"m2-worker-agent": {
"command": "uvx",
"args": ["--from", "m1-m2-agent", "m2-mcp-server"],
"env": {
"DEEPSEEK_API_KEY": "YOUR_DEEPSEEK_API_KEY_HERE",
"DEEPSEEK_MODEL_NAME": "deepseek-chat",
"WORKSPACE_ROOT": "/your/project"
}
}
}
}
# Fallback if uvx/uv is not installed — use pipx:
# "command": "pipx", "args": ["run", "--spec", "m1-m2-agent", "m2-mcp-server"]
Architecture
┌───────────────────────────────┐
│ L2 │
│ Frontier Reasoner (M1) │
│ Plan • Decide • Review │
└───────┬───────────────┬───────┘
│ │
Path A │ Path B │ (Direct Precision Fallback)
(Delegated) │ │
▼ │
┌───────────────┐ │
│ L1 │ │
│ Worker (M2) │ │
│ Context F/W │ │
└───────┬───────┘ │
│ │
▼ ▼
┌───────────────────────────────┐
│ L0 │
│ Deterministic Fast Execution │
│ AST • Ripgrep • Git • LSP │
└───────────────────────────────┘
| Layer | Who | Role | Cost |
|---|---|---|---|
| L2 | M1 (Gemini, Claude, GPT-4o, Cursor) | Strategic planning, architecture, review | Frontier $$$ |
| L1 | M2 (DeepSeek V3/Chat) | Tool loops, search, compression, diagnosis | ~2% of L2 cost |
| L0 | AST parser + git engine | Symbol extraction, diff indexing | 0 LLM tokens |
Three ways to use it
1. MCP Server — for IDEs with MCP support
Works with: Antigravity, Cursor, Claude Desktop, Cline, Roo Code, Windsurf, Continue.dev
Paste the JSON from m2-init into your IDE's MCP config, restart, and the tools
(delegate_to_m2, l0_ast_*, l0_git_*) appear automatically in your agent's tool list.
{
"mcpServers": {
"m2-worker-agent": {
"command": "uvx",
"args": ["--from", "m1-m2-agent", "m2-mcp-server"],
"env": {
"DEEPSEEK_API_KEY": "YOUR_DEEPSEEK_API_KEY_HERE",
"DEEPSEEK_MODEL_NAME": "deepseek-chat",
"WORKSPACE_ROOT": "/path/to/your/project"
}
}
}
}
IDE config file locations:
| IDE | Config file |
|---|---|
| Antigravity | ~/.gemini/settings.json |
| Cursor | .cursor/mcp.json |
| Claude Desktop | ~/Library/Application Support/Claude/claude_desktop_config.json |
| Cline / Roo Code | VS Code → Cline sidebar → Edit MCP Settings |
| Continue.dev | ~/.continue/config.json (under experimental.modelContextProtocolServers) |
2. CLI — for terminal agents and bash scripts
Works with: Aider, bash scripts, terminal workflows, custom pipelines
# One-shot task with live streaming output
m1-m2-cli -p /your/project --task "Find all auth endpoints and summarize JWT validation logic"
# Interactive REPL mode
m1-m2-cli -p /your/project
3. Python SDK — for custom autonomous pipelines
from m1_m2_agent import M1OrchestratorAgent
agent = M1OrchestratorAgent(workspace_root="/your/project")
# Path A: delegate heavy search to M2
result = agent.route_and_execute(
objective="Locate all ASTParser class references and summarize their signatures"
)
print(result["result"]) # Compressed M2 answer
print(result["execution_path"]) # PATH_A_DELEGATED
# View cost telemetry
report = agent.get_telemetry_report()
print(f"Context Compression Ratio: {report['context_compression_ratio']}%")
print(f"Cost Reduction: {report['cost_reduction_pct']}%")
MCP Tools Reference
| Tool | Type | Description |
|---|---|---|
delegate_to_m2 |
async | Delegate any task to M2 — multi-turn tool loop with live SSE streaming |
l0_ast_extract_symbols |
sync | Classes, methods, imports from a file in 0 LLM tokens |
l0_ast_workspace_outline |
sync | Full structural map of all Python modules in 0 LLM tokens |
l0_ast_find_definition |
sync | Exact file + line where any symbol is defined in 0 LLM tokens |
l0_git_status_summary |
sync | Modified / untracked / staged / deleted files in 0 LLM tokens |
l0_git_diff_summary |
sync | Diff statistics and hunk previews in 0 LLM tokens |
inspect_transcript_step |
sync | Retrieve raw un-truncated output from M2's session transcript |
search_transcript |
sync | Search all recorded steps in M2's session for a query term |
get_m2_action_trace |
sync | Full human-readable Markdown trace of M2's working session |
Core Features
- 🌐 Live Webview HUD (
http://localhost:4040): Real-time SSE stream of M2's thoughts (🧠), actions (⚙️), and results (📋) — auto-collapsing cards, 0 tokens leaked to M1. - ⚡ L0 Zero-Token Layer: AST parsing and git diff indexing at literally 0 LLM cost.
- 🔀 Tri-Modal Routing: Path A (delegated), Path B (direct precision), Path C (autonomous investigation).
- 📜 Typed Contracts:
TaskContract/ResultContractwith confidence scoring and evidence citations. - 🚨 Bidirectional Escalation: M2 self-escalates when confidence < 0.80; M1 triggers Path B override.
- 📊 Cost Telemetry: Live FTAR, CCR, and DSR metrics.
- 💾 Stateful Sessions: M2 maintains memory across turns — Turn 2 reuses Turn 1 context, no re-searching.
Configuration
Set via environment variables or .env file:
DEEPSEEK_API_KEY=your-api-key-here
DEEPSEEK_BASE_URL=https://api.deepseek.com
DEEPSEEK_MODEL_NAME=deepseek-chat
WORKSPACE_ROOT=/path/to/your/project
Get a DeepSeek API key at platform.deepseek.com. DeepSeek V3/Chat costs ~$0.27 per million input tokens — roughly 40-50x cheaper than GPT-4o or Claude Sonnet.
Documentation
- 🏗️ ARCHITECTURE.md — Full layer breakdown and sequence diagrams
- 📜 CONTRACTS_AND_ROUTING.md — Typed contracts, routing, escalation protocol
- 🛠️ REAL_WORLD_SETUP_GUIDE.md — Step-by-step MCP + SDK setup
- 📊 ACHIEVEMENTS_AND_BENCHMARKS.md — Empirical benchmarks, FTAR metrics, cost comparisons
- 🚨 INCIDENT_REPORT_001 — Post-mortem: 8 GB Ripgrep Feedback Loop & Memory Explosion
License
Apache 2.0 — see LICENSE.
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file m1_m2_agent-0.3.0.tar.gz.
File metadata
- Download URL: m1_m2_agent-0.3.0.tar.gz
- Upload date:
- Size: 73.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
920810445da9bddae38d892a7a90bc597ef14b7376e7e700f8b62266c06d6deb
|
|
| MD5 |
399c4be51495a22fde3ddfe01874106a
|
|
| BLAKE2b-256 |
10e6c778618fca939940c22f562a3fba6cb516de9b7865432d869a9f32105eba
|
Provenance
The following attestation bundles were made for m1_m2_agent-0.3.0.tar.gz:
Publisher:
publish.yml on HamzaDevv/hierarchical-coding-agent
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
m1_m2_agent-0.3.0.tar.gz -
Subject digest:
920810445da9bddae38d892a7a90bc597ef14b7376e7e700f8b62266c06d6deb - Sigstore transparency entry: 2468980489
- Sigstore integration time:
-
Permalink:
HamzaDevv/hierarchical-coding-agent@2bcf6d701602c6a8bbcc7c7e6d730d17ac9f71bf -
Branch / Tag:
refs/tags/v0.3.0 - Owner: https://github.com/HamzaDevv
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@2bcf6d701602c6a8bbcc7c7e6d730d17ac9f71bf -
Trigger Event:
push
-
Statement type:
File details
Details for the file m1_m2_agent-0.3.0-py3-none-any.whl.
File metadata
- Download URL: m1_m2_agent-0.3.0-py3-none-any.whl
- Upload date:
- Size: 70.3 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via:
twine/7.0.0 CPython/3.13.14
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b396eafba4e7289b88a66fe303e2325ee0bb928143c8347f8a5816d775855e4e
|
|
| MD5 |
8dacf6f79812b1eaf726531955e322fa
|
|
| BLAKE2b-256 |
970a815c95881014fb40d9cc8c7617fc6fd89df21967d06e782b651e4af4be1d
|
Provenance
The following attestation bundles were made for m1_m2_agent-0.3.0-py3-none-any.whl:
Publisher:
publish.yml on HamzaDevv/hierarchical-coding-agent
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
m1_m2_agent-0.3.0-py3-none-any.whl -
Subject digest:
b396eafba4e7289b88a66fe303e2325ee0bb928143c8347f8a5816d775855e4e - Sigstore transparency entry: 2468980501
- Sigstore integration time:
-
Permalink:
HamzaDevv/hierarchical-coding-agent@2bcf6d701602c6a8bbcc7c7e6d730d17ac9f71bf -
Branch / Tag:
refs/tags/v0.3.0 - Owner: https://github.com/HamzaDevv
-
Access:
private
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@2bcf6d701602c6a8bbcc7c7e6d730d17ac9f71bf -
Trigger Event:
push
-
Statement type: