A living system where LLMs write, test, register, and invoke AI skills at runtime β governed by biosafety, resurrected by cron, and immune to gene duplication.
Darwin-MCP is not a server. It is an organism β composed of three decoupled entities with precisely defined roles:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β HOST (The Mind) β
β ChatGPT Β· Claude Β· Copilot Β· Gemma 2b on your phone β
β Issues mutation requests Β· Invokes skills Β· Reads SSE stream β
ββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββ
β MCP SSE over HTTPS (Bearer Token)
β β or β NordVPN Meshnet (cloud-less mode)
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β BRAIN (The Logic) β This repository β
β github.com/mehdibadjian/Darwin-MCP β
β β
β bridge/sse_server.py β Membrane: SSE transport + auth β
β bridge/router.py β Dynamic Tool Router (TF-IDF top-3) β
β engine/mutator.py β Ribosome: mutation pipeline β
β engine/sandbox.py β Lysosome: isolated venv + cache purge β
β engine/guard.py β Circuit breaker: CPU/RAM/depth limits β
β engine/inquiry.py β LeanKG Guard: gene duplication check β
β engine/peer_review.py β Council of Peers: multi-model review β
β watcher/hot_reload.py β MCP notifications/tools/list_changed β
β scripts/sanity_check.shβ Resurrection: hourly health monitor β
β utils/git_manager.py β Git state machine β
β utils/registry.py β Atomic registry I/O β
ββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββ
β Git Submodule (SSH)
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β MEMORY (The Vault) β Private submodule β
β github.com/mehdibadjian/mcp-evolution-vault β
β β
β dna/registry.json β Single source of truth for all skills β
β species/*.py β Living AI skill files (the genome) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
The Brain is stateless. The Memory is stateful. The Host is autonomous. The separation is absolute β the Brain can be redeployed, upgraded, or swapped without touching a single species file.
Every new skill passes through three phases before it earns a place in the genome:
Before synthesising anything, the Brain checks whether a semantically equivalent skill already exists.
# LeanKG Guard prevents gene duplication
# "excel_to_json" β detected as similar to "csv_parser" β suggest adaptation
match = check_semantic_similarity("excel_to_json", registry,
description="Converts Excel rows to JSON objects")
# Returns: SemanticMatch(existing_skill='csv_parser', score=0.27,
# suggestion='Consider adapting csv_parser instead...')If a near-duplicate is detected, the pipeline halts and suggests adaptation. Gene duplication is evolution's waste β Darwin-MCP rejects it.
New code runs in complete isolation: a temporary virtualenv at /tmp/mutation_{timestamp}, with its own pip, its own dependencies, and no access to the host environment.
/tmp/mutation_1745123456/
βββ venv/
βββ bin/pip β isolated pip (never touches system)
βββ bin/python β isolated python
βββ lib/ β dependencies quarantined here
After every mutation β success or failure β the Lysosome runs:
pip cache purgevia the sandbox pip (reclaims~/.cache/pipspace)shutil.rmtreeon the entire sandbox directory
On a $5 Droplet, disk usage stays flat across thousands of mutations.
Only code that passes all its tests is promoted to the genome:
request_evolution()
β
ββ 1. Validate inputs
ββ 1b. Semantic similarity check (LeanKG Guard)
ββ 2. Resolve species/registry paths
ββ 3. Run pytest in sandbox β fail hard if any test fails
β ββ on failure: increment_failure_count(name)
β ββ at 3 failures: Council of Peers escalation
ββ 4. Write species file to memory/species/{name}.py
ββ 5. Atomic registry update (registry.json)
ββ 6. Dependency tracking + env rebuild
ββ 7. Git commit + push to private vault (atomic with registry)
ββ 8. Record invocation stats
ββ 9. Emit notifications/tools/list_changed β IDE refreshes instantly
No code enters the genome without passing its tests. No exceptions.
brain/engine/sandbox.py Β· commit 4cfe20a
After every mutation, Sandbox.cleanup() calls purge_pip_cache() β running pip cache purge via the sandbox's own pip binary. Disk usage on the $5 Droplet remains flat regardless of mutation volume.
brain/watcher/hot_reload.py Β· commit 66692a9
The Brain emits the official MCP notification format the moment a mutation succeeds:
MCP_LIST_CHANGED = {"method": "notifications/tools/list_changed", "params": {}}Connected IDEs (Cursor, Claude Desktop, VS Code) refresh their tool palette instantly β no reconnect required.
brain/scripts/sanity_check.sh Β· commit afdcd5f
An hourly cron job performs three checks:
- Port 8000 β restarts
darwin.serviceif the SSE server is unresponsive - Stale
.git/index.lockfiles β removed silently after a crashed mid-mutation git submodule update --remoteβ keeps the Brain in sync with the Vault
The system recovers from a mid-mutation power failure without manual SSH intervention.
# Install once
bash brain/scripts/install_cron.shbrain/engine/inquiry.py Β· commit 4e3fd05
Before evolving any new skill, the Brain runs a two-pass semantic similarity check:
- Pass 1 β difflib token ratio on skill names (threshold: 0.55)
- Pass 2 β Jaccard coefficient on description word sets (threshold: 0.20)
If either pass detects a near-duplicate, evolution is blocked and the Host receives a suggestion to adapt the existing species. The algorithm is API-stable β drop in an embedding model later without touching request_evolution.
brain/engine/peer_review.py Β· commit 97f6885
After 3 consecutive failures for the same skill, the Brain escalates to a secondary LLM configured in brain/config/meshnet.json. The secondary model receives the failing code, tests, and error context, and returns a fixed_code + explanation. If no secondary model is configured, the system degrades gracefully.
# Automatically triggered inside request_evolution() β no changes needed
# To configure: set base_url + api_key + model in brain/config/meshnet.jsonbrain/bridge/router.py Β· brain/middleware/json_validator.py
Run a free, private AI assistant over NordVPN Meshnet with zero API costs:
| Component | Role |
|---|---|
| Dynamic Tool Router | GET /sse?query=<text> β TF-IDF scoring, returns top-3 tools. Prevents hallucination on small models. |
| JSON Validator Middleware | Catches malformed tool calls, returns retry_hint so Gemma 2b self-corrects. |
| Flash Summarizer | Compresses web pages to β€400 tokens before Meshnet transmission. |
| XML Reasoning Rails | <thought>/<call>/<answer> system prompt enforces rigid syntax on small models. |
| Golden Log | 3 curated transcripts as few-shot context at session start. |
| Level | Component | Protection |
|---|---|---|
| BSL-1 | brain/engine/deps.py |
Dependency isolation β each mutation gets its own requirements.txt scope |
| BSL-2 | brain/engine/guard.py |
Circuit breaker β recursion depth β€3, CPU β€80%, RAM β€256 MB, Toxic flag |
| BSL-3 | brain/engine/mutator.py |
Contextualized error reporting β file + line + assertion detail in every failure |
- Python 3.9+
- Git with SSH key configured for the private Memory submodule
- $5 Droplet or local machine
git clone https://github.com/mehdibadjian/Darwin-MCP.git
cd Darwin-MCP
git submodule update --init --recursive
pip install -r brain/requirements.txt# Required
export MCP_BEARER_TOKEN="$(python3 -c 'import secrets; print(secrets.token_hex(32))')"
export GIT_SSH_COMMAND="ssh -i ~/.ssh/id_rsa"
# Optional β enables Brave Search species and cloud-less mode
export BRAVE_API_KEY="your-brave-api-key"# Development (hot-reload)
uvicorn brain.bridge.sse_server:app --reload --host 0.0.0.0 --port 8000
# Production (systemd β see Production Deployment below)
sudo systemctl start darwin// Cursor / Claude Desktop β settings.json
{
"mcpServers": {
"darwin-brain": {
"url": "https://brain.yourdomain.com/sse",
"headers": { "Authorization": "Bearer <your-token>" }
}
}
}from brain.engine.mutator import request_evolution
result = request_evolution(
name="double_it",
code="def double_it(x): return x * 2",
tests="def test_double(): assert double_it(5) == 10",
requirements=[],
description="Multiplies a number by two",
git_commit=True,
)
print(result.message)
# β "Skill 'double_it' evolved successfully at version 1"
# Connected IDEs refresh their tool list automatically.sudo apt update && sudo apt install -y nginx certbot python3-certbot-nginxsudo cp brain/config/nginx.conf.template /etc/nginx/sites-available/darwin-mcp
sudo sed -i 's/DOMAIN_NAME/brain.yourdomain.com/g' /etc/nginx/sites-available/darwin-mcp
sudo ln -s /etc/nginx/sites-available/darwin-mcp /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginxsudo certbot --nginx -d brain.yourdomain.com
# Auto-renewal is managed by Certbot's systemd timer.# Generate and store β never hardcode
echo "MCP_BEARER_TOKEN=$(python3 -c 'import secrets; print(secrets.token_hex(32))')" \
| sudo tee /opt/mcp-evolution-core/.env
sudo chmod 600 /opt/mcp-evolution-core/.envsudo cp darwin.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now darwin
sudo journalctl -u darwin -fsudo -u darwin bash brain/scripts/install_cron.sh
# Runs sanity_check.sh hourly: port check + lock cleanup + submodule syncsudo ufw allow 22 && sudo ufw allow 80 && sudo ufw allow 443
sudo ufw deny 8000 # port 8000 never exposed directly β Nginx only
sudo ufw enableβ Full Deployment Hardening Guide
| Component | File | Role |
|---|---|---|
| Membrane | brain/bridge/sse_server.py |
SSE transport, Bearer auth, MCP protocol, vault routing |
| Tool Router | brain/bridge/router.py |
TF-IDF queryβtool scoring, top-N filtering |
| Ribosome | brain/engine/mutator.py |
Full mutation pipeline orchestration |
| Lysosome | brain/engine/sandbox.py |
Isolated virtualenv + post-mutation pip cache purge |
| Circuit Breaker | brain/engine/guard.py |
Recursion depth, CPU/RAM limits, Toxic flag |
| LeanKG Guard | brain/engine/inquiry.py |
Semantic similarity β blocks gene duplication |
| Council of Peers | brain/engine/peer_review.py |
Multi-model fallback after 3 failures |
| JSON Middleware | brain/middleware/json_validator.py |
Self-healing malformed JSON with retry hints |
| Flash Summarizer | brain/utils/context_buffer.py |
Extractive β€400-token compression |
| Registry I/O | brain/utils/registry.py |
Atomic read/write of registry.json with file locking |
| Git Manager | brain/utils/git_manager.py |
Commit, push, rebase; atomic with registry write |
| Hot Reload | brain/watcher/hot_reload.py |
Watchdog + MCP notifications/tools/list_changed |
| Resurrection | brain/scripts/sanity_check.sh |
Hourly: port check, lock cleanup, submodule sync |
| Nginx Template | brain/config/nginx.conf.template |
Production reverse proxy with SSL + SSE headers |
# Run the full test suite
pytest tests/ -q
# β 298 passed, 2 skipped
# Evolve a skill via the REST API
curl -X POST https://brain.yourdomain.com/evolve \
-H "Authorization: Bearer $MCP_BEARER_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name":"add","code":"def add(a,b): return a+b","tests":"def test(): assert add(2,3)==5","requirements":[]}'
# Query tools by relevance (cloud-less routing)
curl -H "Authorization: Bearer $MCP_BEARER_TOKEN" \
"https://brain.yourdomain.com/sse?query=search+the+web"
# Web search via Brain
curl -X POST https://brain.yourdomain.com/search \
-H "Authorization: Bearer $MCP_BEARER_TOKEN" \
-H "Content-Type: application/json" \
-d '{"query": "latest Python release", "fetch": true}'
# View the genome
cat memory/dna/registry.json | jq '.skills | keys'
# Check Droplet vitals
curl https://brain.yourdomain.com/tools/get_droplet_vitals/invoke \
-H "Authorization: Bearer $MCP_BEARER_TOKEN"Darwin-MCP/
βββ brain/
β βββ bridge/
β β βββ sse_server.py β Membrane: SSE + auth + vault routing
β β βββ router.py β Dynamic Tool Router
β βββ config/
β β βββ meshnet.json β Meshnet / Council of Peers config
β β βββ nginx.conf.template β Production Nginx template
β βββ engine/
β β βββ mutator.py β Full mutation pipeline
β β βββ sandbox.py β Lysosome: isolated venv + cache purge
β β βββ guard.py β Circuit breaker (BSL-2)
β β βββ inquiry.py β LeanKG Guard: semantic similarity
β β βββ peer_review.py β Council of Peers: multi-model fallback
β β βββ scavenger.py β External skill harvesting
β β βββ vitals.py β Droplet metrics MCP tool
β β βββ pytest_runner.py β Sandboxed test execution
β β βββ deps.py β Dependency tracking (BSL-1)
β βββ middleware/
β β βββ json_validator.py β Self-healing JSON (BSL-3)
β βββ prompts/
β β βββ system_prompt.txt β XML reasoning rails (cloud-less)
β β βββ golden_log.txt β Few-shot primer (cloud-less)
β βββ scripts/
β β βββ sanity_check.sh β Resurrection: hourly health monitor
β β βββ install_cron.sh β Crontab installer
β βββ utils/
β β βββ registry.py β Atomic registry I/O
β β βββ git_manager.py β Git state machine
β β βββ web_fetch.py β HTTP fetch + DuckDuckGo search
β β βββ context_buffer.py β Flash Summarizer
β βββ watcher/
β βββ hot_reload.py β Watchdog + MCP list_changed
βββ memory/ β Git submodule (private vault)
β βββ dna/registry.json β The genome index
β βββ species/*.py β Living skill files
βββ docs/
β βββ reference/
β β βββ technical-manifesto.md
β β βββ agile-backlog.md
β β βββ hardening-backlog.md
β βββ tutorials/getting-started.md
β βββ how-to/
β βββ common-tasks.md
β βββ meshnet-setup.md
β βββ deployment-hardening.md
βββ tests/ β pytest suite (298 passing)
βββ darwin.service β Systemd unit (uvicorn + hardening)
βββ CONTRIBUTING.md
| Document | Purpose |
|---|---|
| Getting Started | Local setup, first skill, verify install |
| Common Tasks | Create, debug, deploy, rollback skills |
| Deployment Hardening | Nginx, SSL, bearer token, UFW, crontab |
| Meshnet Setup | NordVPN Meshnet + Gemma 2b on phone |
| Technical Manifesto | API contracts, Git state machine, BSL layers |
| Hardening Backlog | Security epics, user stories, sprint plans |
| Agile Backlog | Full feature backlog and story points |
| CONTRIBUTING | Contribution model, mutation standards, branching |
- Issues β github.com/mehdibadjian/Darwin-MCP/issues
- Discussions β github.com/mehdibadjian/Darwin-MCP/discussions
TBD
The genome is open. Evolve responsibly. π§¬