Skip to main content

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.

PyPI Python License Tests


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 / ResultContract with 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


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

m1_m2_agent-0.3.0.tar.gz (73.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

m1_m2_agent-0.3.0-py3-none-any.whl (70.3 kB view details)

Uploaded Python 3

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

Hashes for m1_m2_agent-0.3.0.tar.gz
Algorithm Hash digest
SHA256 920810445da9bddae38d892a7a90bc597ef14b7376e7e700f8b62266c06d6deb
MD5 399c4be51495a22fde3ddfe01874106a
BLAKE2b-256 10e6c778618fca939940c22f562a3fba6cb516de9b7865432d869a9f32105eba

See more details on using hashes here.

Provenance

The following attestation bundles were made for m1_m2_agent-0.3.0.tar.gz:

Publisher: publish.yml on HamzaDevv/hierarchical-coding-agent

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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

Hashes for m1_m2_agent-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 b396eafba4e7289b88a66fe303e2325ee0bb928143c8347f8a5816d775855e4e
MD5 8dacf6f79812b1eaf726531955e322fa
BLAKE2b-256 970a815c95881014fb40d9cc8c7617fc6fd89df21967d06e782b651e4af4be1d

See more details on using hashes here.

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

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Release history Release notifications | RSS feed

0.6.0

2 files

0.3.2

2 files

0.3.1

2 files

This release

0.3.0 This release

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page