Calyx MCP
Calyx MCP is an MCP server that gives AI coding agents fast, zero-token, bio-inspired associative memory for code patterns, with tools to check, learn, query, inspect, and reset reflex memories.
check_code_reflex: Evaluate a code snippet against past bug/fix patterns and return an immediate
avoid,safe, orneutralreflex with valence, confidence, similarity, warning, and recommendation.remember_code_outcome: Apply one-shot dopamine reward or punishment to Mushroom Body synaptic weights after a test passes or fails, storing the code outcome for future reflex checks.
query_associative_memory: Search stored code patterns using Fly-LSH sparse Hamming similarity, returning nearest-neighbor matches with similarity scores and optional compact results.
inspect_memory_state: Inspect operational statistics such as total memories stored, Kenyon cell count, sparsity, weight distribution, and storage location.
reset_memory: Reset synaptic weights and purge stored associative memories, with optional automatic backup creation.
All operations are local, deterministic, and use zero LLM tokens, operating over the MCP JSON-RPC protocol.
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., "@Calyx MCP evaluate this code snippet for bugs and remember the outcome"
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.
Calyx MCP
Bio-inspired associative memory and instant code reflex server for AI coding agents, implementing the Drosophila Mushroom Body circuit and Fly-LSH sparse projection algorithm over the Model Context Protocol (MCP).
At a Glance
The Problem: AI coding agents repeatedly consume thousands of LLM prompt tokens and multi-second roundtrip latency diagnosing recurring bugs, antipatterns, and project constraints.
The Solution: Calyx brings the Drosophila Mushroom Body (fruit fly brain) circuit to AI agents—using Fly-LSH sparse Kenyon Cell projection ($D=2048, k=102$) and dopaminergic synaptic plasticity to give agents instant, zero-overhead associative memory without internal LLM calls.
The Proof (Benchmark):
Latency: 0.217 ms (p50) / 0.533 ms (p99) in-memory (>6,600x faster), 2.013 ms (p50) / 3.711 ms (p99) real-path end-to-end (>700x faster) vs ~1,450 ms LLM API roundtrip
Token Cost: 0 tokens (100% local Mushroom Body execution; zero LLM inference calls)
Related MCP server: Senior Code MCP
Why "Calyx"?
In insect neuroanatomy, the Calyx (plural: calyces) is the primary input neuropil of the Mushroom Body (Corpora Pedunculata)—the learning and memory center of the Drosophila melanogaster brain. Within the calyx, olfactory and sensory Projection Neurons (PNs) synapse directly onto the clawed dendritic arborizations of thousands of Kenyon Cells (KCs).
It is inside the calyx that dense, low-dimensional sensory signals undergo high-dimensional sparse expansion, turning raw input into a distinct neural fingerprint that dopaminergic circuits can reinforce or suppress.
The name Calyx was chosen because this MCP server functions as that exact input and associative expansion layer for AI coding agents: converting raw code AST tokens into high-dimensional, ultra-sparse Kenyon Cell representations that drive fast reflexes (in-memory: p50 0.217 ms / p99 0.533 ms; real-path: p50 2.013 ms / p99 3.711 ms), pattern recognition, and persistent synaptic memory without LLM inference costs.
Overview
Traditional AI coding workflows incur substantial token overhead and multi-second latency by repeatedly sending multi-thousand-token prompt context to Large Language Models (LLMs) to detect recurring bugs, antipatterns, or architectural guidelines.
Calyx provides local, zero-token associative memory modeled after the Drosophila melanogaster (fruit fly) Mushroom Body circuit. Code snippets and AST structures are expanded into high-dimensional, ultra-sparse Kenyon Cell representations ($D=2048, k=102$). Synaptic plasticity between Kenyon Cells and Mushroom Body Output Neurons (MBONs) is modulated by reward and punishment signals (dopamine), delivering fast pattern recognition (p50: 0.217 ms in-memory, 2.013 ms real-path) without LLM inference costs.
Architectural Principles
+-----------------------------------------------------------------------+
| Calyx MCP |
+-----------------------------------------------------------------------+
| Input Code Snippet / AST Tokens |
| | |
| v |
| Fly-LSH Hash Projection (Projection Dimension = 2048) |
| | |
| v |
| Winner-Take-All Sparsification (k = 102 active Kenyon Cells, ~5%) |
| | |
| v |
| Mushroom Body Output Neuron (MBON) Synaptic Weight Matrix |
| | |
| +----+------------------------------------------------------------+ |
| | Dopaminergic Modulation: dW = eta * Dopamine * (KC (x) MBON) | |
| +-----------------------------------------------------------------+ |
| | |
| v |
| Reflex Output: Neutral / Safe / Avoid (p50: 2.01ms, 0 Tokens) |
+-----------------------------------------------------------------------+Fly-LSH Projection: Projects token distributions into a 2,048-dimensional space using deterministic hashing, mimicking the projection neuron to Kenyon cell expansion.
Winner-Take-All (WTA) Sparsity: Retains only the top $k=102$ activations (~4.98% sparsity) via inhibitory feedback (APL neuron equivalent).
Dopamine Synaptic Plasticity: Adjusts synaptic weights based on coding execution outcomes (success/failure), enabling rapid aversion to bug patterns and attraction to proven implementations.
Local Atomic Persistence: Synaptic states and associative memory records persist locally in compressed
.npzand JSON formats (~/.calyx/).
Benchmark and Token Savings
An actual v1.0.5 agent-usage pilot records six fresh Luna sessions against 100 synthetic lessons. Only one pair met the retrieval protocol in both arms; it used 43,591 more tokens with Calyx. Failed attempts are retained. This bounded pilot does not demonstrate end-to-end token savings; zero internal LLM calls and agent usage are different measurements.
The performance metrics below were measured on a Windows x86_64 host running Python 3.13 with native NumPy operations. Because Fly-LSH sparse projection and synaptic valence calculations execute locally in memory, pattern recognition requires zero external LLM inference calls:
Test Execution Log
============================================================================
CALYX MCP: LIVE TOOL EXECUTION & TOKEN SAVINGS BENCHMARK
============================================================================
[Step 1] Initial Code Reflex Check (Zero Prior Training):
* Latency: 2.013 ms (p50 real-path) / 0.217 ms (in-memory)
* Reflex Status: NEUTRAL
* Valence: 1.000
* Recommendation: Novel or unverified code pattern. Proceed normally.
* LLM Tokens Used: 0 tokens (Zero API overhead)
[Step 2] Dopamine Reinforcement (Negative Dopamine Delivery):
* Plasticity Latency: 2.450 ms
* Status: recorded
* Valence Type: punishment (Dopaminergic depression signal)
* Active Synapses: 102 Kenyon Cells updated
* Persistent State: Saved to ~/.calyx/mushroom_body_weights.npz
[Step 3] Fast Bio-Reflex on Reintroduced Bug Pattern:
* Latency: 2.013 ms (p50 real-path) / 0.217 ms (in-memory)
* Reflex Status: AVOID (AVERSION TRIGGERED)
* Valence Score: 0.775 (Aversive)
* Bug Similarity: 70.0% (Jaccard: 0.700 >= 0.65 threshold)
* Warning: High resemblance (70%) to a previously punished bug pattern.
* Recommendation: Review code logic, check edge cases, or adopt alternative.
============================================================================
TOKEN SAVINGS & SPEEDUP
============================================================================
Traditional LLM Querying Loop:
* Latency per review: ~1450 ms
* Inspection Cost: ~650 prompt tokens per check
* Debugging Loop: ~2400 tokens per repeated bug
Calyx Mushroom Body Reflex:
* Latency per review: 2.013 ms p50 real-path / 0.217 ms in-memory (>700x real-path, >6,600x in-memory speedup)
* Token Cost: 0 tokens (Local Fly-LSH sparse projection)
* Token Efficiency: 100% local execution (Zero LLM inference overhead)
============================================================================
MUSHROOM BODY NEURAL ARCHITECTURE STATE
============================================================================
* Kenyon Cells Dimension: 2048
* Sparsity Active Ratio: 4.98% active neurons
* Total Memories Stored: 1
* Depressed Synapses (W): 102
* Weights Min / Avg / Max: 0.775 / 0.9888 / 1.0
* Storage Directory: ~/.calyx
============================================================================Performance Summary
Metric | Traditional LLM Inspection | Calyx Mushroom Body | Improvement |
Latency (In-Memory) | ~1,450 ms | 0.217 ms (p50) / 0.533 ms (p99) | > 6,600x faster |
Latency (Real-Path End-to-End) | ~1,450 ms | 2.013 ms (p50) / 3.711 ms (p99) | > 700x faster (Includes cross-process lock & disk snapshot sync) |
Throughput | 0.5 - 2 req/s | 452 req/s (real-path) / 4,189 req/s (in-memory) | Zero external network calls |
Token Consumption | 650 - 2,400 tokens per loop | 0 tokens (Local Fly-LSH) | 100% local execution |
Memory Footprint | External API | < 15 MB RAM | Local execution |
Pattern Match Type | Full prompt parsing | Sparse Kenyon Cell overlap | Deterministic associative recall |
Latency figures are measured across 1,000 iterations usingscripts/bench_reflex.py. Real-path measurements include full MCP request parsing, inter-process file locking (msvcrt/fcntl), shared disk state verification, and Kenyon cell projection.
Empirical Generalization & Measured Reflex Verification
Calyx operates as a deterministic, zero-token associative code memory. In a pre-registered benchmark across 60 multi-language bug-fix pairs (180 paraphrased variants, 60 fixes, and 120 negative controls in Python, JS, Go, Rust, and SQL), Calyx produced the following measured results:
Evaluation Dimension | Metric Measured | Result | Details |
Unrelated Negative Controls | False-Positive Rate | 0.00% (0/120) | Zero false alarms on safe, unrelated code |
Fixed Code Contradiction Guard | False-Positive Rate | 5.00% (3/60) | Contradiction guard protects fixes from false |
Paraphrased Variant Generalization | Full-Path Avoid Rate | 4.44% (8/180) | Measured end-to-end; reordered statements achieve 13.3%, renamed/restructured tokens collapse similarity below 0.65 threshold |
Abstracted Tokenizer Experiment | Offline Proxy Metric | 34.44% (62/180) | Raw pairwise hash Jaccard >= 0.65; offline proxy bypassing multi-turn train/valence dynamics |
See benchmarks/2026-09-eval/ for complete JSONL test records, pre-registered targets, methodology, and reproduction scripts (scripts/eval_generalization.py).
Loss Asymmetry by Design: Calyx implements biologically inspired loss aversion. A single punished failure immediately triggers an avoid reflex (one-shot aversive conditioning) to shield against regressions. Conversely, achieving a confirmed safe reflex requires multiple verified successes (>= 2 rewards) to avoid premature complacency on unverified edge cases.
MCP Tools Reference
Calyx registers the following tools conforming to the MCP JSON-RPC 2.0 specification (2024-11-05):
1. check_code_reflex
Evaluates a code snippet against synaptic valence weights and stored experiences (p50: 2.013ms / p99: 3.711ms real-path; p50: 0.217ms in-memory) with 0 LLM prompt tokens.
Annotations:
readOnlyHint: true,openWorldHint: falseParameters:
code(string, required): The proposed code snippet, function, or diff to evaluate (aliases:code_snippet,query_code,query).context(string, optional): Optional context or filename describing the task.
Returns:
status(avoid,safe,neutral),valence,confidence,similarity_with_past_bugs,warning,recommendation.
2. remember_code_outcome
Applies one-shot dopamine reward (test passed) or punishment (test failed/bug) to Mushroom Body synaptic weights.
Annotations:
readOnlyHint: false,destructiveHint: true,idempotentHint: false,openWorldHint: falseParameters:
code(string, required): The code snippet that was executed or tested (aliases:code_snippet,query_code).outcome(string, required):"success"(rewards synapses) or"failure"(punishes synapses).error_message(string, optional): Error trace or description if outcome was"failure".tags(array of strings, optional): Categorical tags (e.g.["auth", "database", "deadlock"]).
Returns:
status,outcome,valence_type,pattern_valence,active_synapses_updated,total_memories_stored.
3. query_associative_memory
Searches stored code patterns using Fly-LSH sparse binary Hamming similarity.
Annotations:
readOnlyHint: true,openWorldHint: falseParameters:
query_code(string, required): Code snippet to search against associative memory (aliases:query,code,code_snippet).top_k(integer, optional): Number of nearest neighbors to return (default:5, clamped $[1, 50]$).compact(boolean, optional): Whether to return compact match objects to reduce prompt token footprint (default:false).
Returns:
query,matches_count,matches(array of nearest records with similarity scores).
4. inspect_memory_state
Returns operational metrics, weight distribution, and health statistics of the Mushroom Body.
Annotations:
readOnlyHint: true,openWorldHint: falseParameters: None.
Returns:
total_memories_stored,total_kenyon_cells,active_sparsity_pct,weights_avg,weights_min,weights_max,depressed_synapses_count,potentiated_synapses_count,storage_location.
5. reset_memory
Resets synaptic weights to neutral baseline (1.0) and purges stored experiences with automatic backup creation.
Annotations:
readOnlyHint: false,destructiveHint: true,idempotentHint: false,openWorldHint: falseParameters:
confirm(boolean, required): Must be set totrueto confirm reset.backup(boolean, optional): Whether to create a backup file before resetting (default:true).
Returns:
status,backup_created,backup_path.
1-Click Automatic Setup (Recommended)
Calyx includes built-in auto-discovery to configure your IDE's MCP settings automatically without manually editing JSON files:
# 1. Install Calyx
pip install calyx-mcp
# 2. Check which IDEs are detected on your machine
calyx-mcp install --status
# 3. Automatically configure all detected IDEs
calyx-mcp install --all
# Or configure a specific IDE:
calyx-mcp install --target claude # Claude Desktop
calyx-mcp install --target cursor # Cursor
calyx-mcp install --target antigravity # Google Antigravity / Gemini (alias: gemini)
calyx-mcp install --target windsurf # Windsurf / Codeium (alias: codeium)
calyx-mcp install --target roo # Roo Code (VS Code) (alias: vscode)
calyx-mcp install --target cline # Cline (VS Code)
calyx-mcp install --target zed # Zed Editor
# Optional: Explicitly specify a custom Python interpreter path
calyx-mcp install --all --python-path /path/to/python
# 4. Initialize AGENTS.md in your current workspace
calyx-mcp initManual Installation & Configuration
Standard Installation via pip or uv
pip install calyx-mcpRun Without Installation via uvx
uvx calyx-mcpManual MCP Client JSON Configuration
Add Calyx to your MCP client configuration file (e.g. ~/.gemini/config/mcp_config.json, Claude Desktop, or Cursor):
{
"mcpServers": {
"calyx": {
"command": "python",
"args": [
"-m",
"calyx_mcp.server"
]
}
}
}Recommended Agent Rules (AGENTS.md / .cursorrules / CLAUDE.md)
To ensure AI coding agents consistently leverage Calyx before applying code changes and reinforce synapses after testing, add this policy to your project's AGENTS.md, GEMINI.md, CLAUDE.md, or .cursorrules:
## Calyx Associative Memory Policy
1. **Pre-Flight Reflex Check (Before Modifying Code)**:
- Before writing or modifying functions, call `check_code_reflex(code=...)`.
- If `status: "avoid"`, do not proceed with that pattern. Review the past bug warning and choose an alternative approach.
2. **Post-Execution Learning (After Testing)**:
- If tests fail, call `remember_code_outcome(code=..., outcome="failure", error_message=...)`.
- If tests pass, call `remember_code_outcome(code=..., outcome="success")`.Running Tests
Execute the 92-test suite:
python -m pytest tests/ -vTest Suite Results (92 / 92 Passing)
Test Suite | Scope & Invariants Tested | Test Count | Status |
| Failure Override Rule (recent failure overrides positive history), recency tie-breaking, state transitions | 3 | PASSED |
| Empty/whitespace rejection, 150KB code blocks, polyglot resilience (Rust, TypeScript, Go, SQL, JSON), unicode | 4 | PASSED |
| 500-record ring buffer bounds, corrupt file baseline recovery, passive synaptic weight decay | 3 | PASSED |
| Fly-LSH $D=2048, k=102$ top-k sparsity, deterministic random projection, AST token extraction | 5 | PASSED |
| Dopaminergic PAM reward / PPL1 punishment updates, synaptic weight bounds $[0.0, 5.0]$ | 2 | PASSED |
| MBON decision thresholds across | 4 | PASSED |
| Multi-OS paths, safe JSON merging, aliases, backup creation, Zed context_servers, interpreter resolution | 10 | PASSED |
| JSONC string preservation, malformed-input rejection, JSONC discovery, native Cursor paths | 4 | PASSED |
| Deserialization guards ( | 6 | PASSED |
| Input validation, parameter clamping, aliases ( | 7 | PASSED |
| Async lock correctness and state integrity under 50 concurrent agent coroutines | 1 | PASSED |
| 15 parametrized valid and invalid input formats (rejects arbitrary strings, booleans, empty strings) | 15 | PASSED |
| MCP protocol annotations ( | 2 | PASSED |
| End-to-end MCP JSON-RPC 2.0 stdio initialization, tool listing, and tool dispatch | 1 | PASSED |
| CLI subcommands: | 3 | PASSED |
| Atomic synaptic weight save/reload and persistent reflex evaluation across instances | 2 | PASSED |
| Custom filenames, exact weight shape, stale and concurrent process writes, reader refresh and reset | 5 | PASSED |
| Hidden-failure recall across insertion orders, disk write error propagation, and stdio subprocess restart | 5 | PASSED |
| Schema token budget (<800 tokens), reflex response footprint (<80 tokens), and mathematical ROI modeling | 3 | PASSED |
| Synthetic corpus integrity and repair validation, including hardcoded-value rejection | 4 | PASSED |
| Negative savings, cache accounting, invalid telemetry and ineligible pairs | 3 | PASSED |
Total | 92 passing test cases | 92 | 100% PASS |
Persistence & Error Handling: Synaptic weights and associative records persist locally in ~/.calyx/. File writes use atomic replacements (.tmp to target). In the event of an I/O or filesystem error during disk persistence, an OSError is raised and propagated to the MCP caller with actionable diagnostics rather than falsely acknowledging successful recording.
Shared Storage: Cooperating clients serialize reload/update/save operations with an OS file lock. Queries refresh their snapshot so another client's writes and resets are visible. All clients sharing a directory must use a version with this locking behavior; older clients do not participate. Each file replacement is atomic, but the two-file format is not a crash-atomic transaction. A failed write can still leave partial state, as reported by the persistence error. These reads now include filesystem work; the historical in-memory latency measurements above are not a benchmark of shared-store reads.
Reflex Evaluation Invariant: The reflex engine inspects qualifying failure records ($\ge 0.65$ similarity) before candidate truncation, ensuring previously identified bug patterns reliably trigger the avoid reflex even if multiple subsequent successes have been recorded for related code. Ordinary associative memory queries continue to return the nearest records across all outcomes.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Available Tools
5 toolscheck_code_reflexARead-only
Instant (<1ms) associative memory check of proposed code against past rewarded or punished bug patterns. Returns 'avoid', 'safe', or 'neutral'.
Inputs: code (required), context.
inspect_memory_stateARead-only
Returns total active memories, synaptic weight distribution, and health statistics of the Mushroom Body.
Inputs: no named parameters.
query_associative_memoryBRead-only
Searches stored code patterns using Fly-LSH sparse binary Hamming similarity.
Inputs: query_code (required), top_k, compact.
remember_code_outcomeBDestructive
Applies one-shot dopamine reward (test passed) or punishment (test failed/bug) to Mushroom Body synaptic weights.
Inputs: code (required), outcome (required), tags, error_message.
reset_memoryADestructive
Resets or prunes the synaptic weights and associative memory back to baseline.
Inputs: confirm (required), backup.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 5 tools
Each tool has a distinct role: querying memory, checking code reflexes, inspecting state, learning outcomes, and resetting. The only mild overlap is between query_associative_memory and check_code_reflex, since both access stored patterns, but their purposes are clearly separated by general search versus instant classification.
All tool names follow a consistent verb_noun snake_case pattern: query_, check_, inspect_, remember_, and reset_. The naming clearly communicates the action and target for every tool.
Five tools is well-scoped for a memory system server. Each tool covers a necessary operation without redundancy or bloat.
The tool set covers the full lifecycle of associative memory: querying, fast checking, inspecting state, learning from outcomes, and resetting/pruning. No obvious dead ends or missing critical operations exist for the stated purpose.
Maintenance
Related MCP Connectors
Cuts coding agent token burn up to 72% continuously via contradiction-free memory & verification.
Collective memory for AI agents. One agent solves a bug — every agent gets the fix instantly.
Persistent engineering memory designed to follow developers across coding agents.
Persistent memory, inline redaction, per-agent access, and code localization for AI agents.
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceHebbian memory system for AI coding agents that learns file associations, error-fix patterns, and tool sequences, enabling instant recall of related context to save tokens.52 npm14MIT
- FlicenseAqualityCmaintenanceGives coding agents a memory of codebases by searching repositories using semantic similarity and structural call/import graphs, enabling reuse of proven patterns and reducing token usage.6-
- FlicenseNot gradedqualityCmaintenancePersistent, self-curating memory for coding agents. It enables local, zero-cost context recall through MCP tools with hybrid retrieval and autonomous consolidation.-
- AlicenseBqualityDmaintenanceEnables programming agents to capture errors and conversation signals, reflect on root causes, consolidate reusable skills, and retrieve relevant context for future tasks, providing a self-learning memory loop.15MIT