trusty-mcp
by mategog
README.md
# tRUSTy-code 1.0
[](LICENSE)
[](mcp-server/Cargo.toml)
**A Rust-only, non-LLM neural co-pilot (`~751K` params) and pure-Rust MCP server (`trusty-mcp`) that cuts LLM token usage (`57%–92%`) while helping coding agents produce more accurate, idiomatic, borrow-safe Rust code.**
`tRUSTy-code 1.0` does **not** generate English prose or chat on its own. Instead, it turns Rust source code into typed **AST + Control-Flow + Data-Flow + Borrow graphs** and runs two from-scratch Relational Graph Convolutional Networks (**R-GCNs**) inside a single native Rust binary with **zero Python runtime dependency**:
1. **`TrustyCodeEncoder` (`653,377` params)** — Trained with InfoNCE contrastive learning on 6,000 real functions across 413 `crates.io` crates to map Rust code graphs and developer queries into a shared 128-d embedding space.
2. **`TrustyBorrowAndBugGNN` (`97,866` params)** — Trained on `rustc`-verified code mutations to rank borrow/type error repair strategies (`97.2%` Top-1 / `99.7%` Top-3) and flag silent panic/allocation/`unsafe` risks (`98.3%` Top-1) in `1–25 ms`.
PyTorch ↔ pure-Rust inference parity is verified across golden test vectors at **`max_abs_diff = 2.38e-6`** (`< 1e-4`).
---
## How It Works (Plain English)
Normal coding agents read entire `.rs` files from top to bottom (`15k–50k+` tokens per query) and paste hundreds of lines of raw `cargo check` stderr back into the cloud prompt on every error loop.
`tRUSTy-code 1.0` sits locally between your Rust repository and any MCP-capable LLM (**Antigravity IDE**, **Google Antigravity SDK**, **Claude Code**, or local **Ollama/Qwen**):
- **`rust_repo_outline`**: Strips function bodies and returns a compact API skeleton (structs, enums, traits, `impl` headers, signatures, line ranges) in ~5–10% of the tokens.
- **`rust_neural_search`**: Scores function graphs using `TrustyCodeEncoder` + structural lexical fusion and returns top-`k` 25-line slices with exact `file:start..end` spans.
- **`rust_symbol_slice`**: Extracts one target function/type plus its `impl` blocks and 1-hop local type definitions without dumping whole files.
- **`rust_check_compact`**: Runs `cargo check --message-format=json`, deduplicates cascading errors, runs `TrustyBorrowAndBugGNN` to rank the top-3 fix strategies, and probes micro-patches via `rustc`.
- **`rust_safety_audit`**: Runs `TrustyBorrowAndBugGNN` + deterministic `syn` rules to catch `.unwrap()` panic risks, `&Vec<T>`/`.clone()` smells, and undocumented `unsafe` blocks that `cargo check` passes silently.
---
## Creating New Code: Why LLM + `tRUSTy-code` Produces More Accurate Rust for Fewer Tokens
While a 751K-parameter graph model cannot invent whole applications by itself, pairing an LLM (**Claude**, **Gemini**, or local **Qwen**) with `tRUSTy-code` as a co-pilot directly improves generated Rust quality while slashing token spend at every stage of writing code:
1. **Before Writing — Zero-Hallucination API Wiring (`~90%` fewer input tokens):**
Instead of guessing crate fields/lifetimes or reading `50k–100k` tokens of raw files, the LLM calls `rust_repo_outline` and `rust_symbol_slice` to see exact structs, traits, and lifetimes (`Hook<'a>`, `Result<Value, Fail>`, `&[Finding]`) in a tiny focused window—raising first-try compile accuracy.
2. **During Writing — Shorter Borrow-Checker Fix Loops (`~65%–80%` fewer retry tokens):**
When newly generated Rust hits `E0382`, `E0502`, `E0596`, or `E0277`, `rust_check_compact` suppresses cascading domino errors and feeds the LLM compact ranked repair hints (`[rustc-verified]` when micro-probed), turning 3–4 noisy compiler round-trips into 1.
3. **After Writing — Stopping "Lazy LLM Hacks" (`cargo check` passes, production panics):**
LLMs frequently insert `.unwrap()`, `&Vec<String>`, or `.clone()` inside loops just to satisfy the borrow checker. Running `rust_safety_audit` (`~1–25 ms`) right after generation catches silent panic and `unsafe` UB bugs before the task finishes.
### Honest Boundaries (When *Not* to Use `tRUSTy-code`)
Real-life testing across 100k+ LOC unseen crates (`clap_builder`, `hyper`, `serde_json`, `rayon`, `indexmap`) and a 7,578-LOC production Rust security workspace surfaced clear boundaries:
- **Greenfield single-file scripts (`<100` LOC):** Fixed MCP tool-schema overhead (`~450` tokens) costs more than reading a 30–60 line `.rs` file directly; use only `rust_check_compact` / `rust_safety_audit` after writing.
- **Verbatim log/string-literal search & unexpanded `macro_rules!`:** Plain `grep`/`rg` wins here because `TrustyCodeEncoder` hashes AST nodes and identifiers rather than raw string literals or unexpanded macro bodies.
- **v1.0 `#[test]` ranking noise:** `trusty-mcp` currently indexes `#[test]` functions alongside production code, which can crowd out production functions in test-heavy crates and inflate `PanicUnwrapRisk` counts (`67/78` flags in our real-world audit were inside `#[test]` functions). Filtering `#[test]` by default is the top v1.1 priority.
---
## Benchmarks & Real-World Validation

### 1. From-Scratch ML Evaluation (Zero Crate Overlap Across Train/Val/Test)
Trained on 413 cached crates (`encoder`: `4,200 / 900 / 900`; `repair`: `1,680 / 360 / 360`; **0 shared crates across splits**):
| Model | Task | Metric (Held-Out Test Set, 95% Bootstrap CI) | vs Best Baseline |
|---|---|---|---|
| `TrustyCodeEncoder` (`653,377` params) | Semantic Code Retrieval (`fn_name` stripped) | Hybrid MRR **`0.405`** `[0.381, 0.432]` | TF-IDF `0.281` (+44% rel.) |
| `TrustyBorrowAndBugGNN` (`97,866` params) | Borrow/Type Fix Strategy (`0..5`) | Macro-F1 **`0.946`** (`97.2%` Top-1, `99.7%` Top-3) | LogReg `0.897` |
| `TrustyBorrowAndBugGNN` (`97,866` params) | Safety & Idiom Risk (`0..3`) | Macro-F1 **`0.959`** (`98.3%` Top-1) | LogReg `0.710` |

### 2. Token Reduction & Real-Life Engineering Results
| Benchmark Suite | Scope | Baseline | `tRUSTy-code 1.0` | Result |
|---|---|---|---|---|
| **12-Task MCP Payload (`tiktoken`)** | 4 Rust categories (`anyhow`, `regex-syntax`, `serde_json`, fixtures) | `150,197` tok | **`11,197` tok** | **92.55% saved** (`100%` completeness) |
| **Google Antigravity SDK (`UsageMetadata`)** | 4 live `Agent` sessions (`LocalOpenAIAgentConfig` + `McpStdioServer`) | `98,068` tok | **`41,801` tok** | **57.38% total saved** (`4/4` verified) |
| **Broken 5-File App (`real_task_hub`)** | 5 compile errors + 3 silent UB/panic/clone bugs | `1,801` tok (`0/3` silent bugs) | **`629` tok** (**`3/3` silent bugs**) | **65.07% saved** + caught hidden UB |
| **Live Blind A/B AI Subagent Trial** | 3 real tasks (`hyper`, `rayon-core`, `real_task_hub`) | `12/12` score, `24` tool calls, `28,806` tool tok | **`12/12` score, `14` tool calls, `22,181` tool tok** | **-41.7% tool calls**, **-23.0% tool tok** |
| **Real Repo Audit (`7,578` LOC, `24` `.rs` files)** | Workspace check + outline + safety audit + neural search | `100,258` raw tok | **`~8,500` tok** | **~91.5% fewer tokens**, `<720 ms` |
| **20-Query Unseen Discovery (`2k` cap)** | 5 unseen 100k-LOC crates, zero file hints | `grep_top3` `0%` (`49.6k` tok); `BM25_2k` **`40%`** | `AST-only` `30%` (`1.36k`); `Neural` `10%` (`1.17k`) | Exposed v1.0 `#[test]` bloat & fusion calibration |

---
## Quick Start
### 1. Build the Pure-Rust MCP Binary
```bash
cd mcp-server
cargo build --release
cd ..
```
Verify PyTorch ↔ Rust neural parity (`max_abs_diff < 1e-4`):
```bash
./mcp-server/target/release/trusty-mcp verify-parity ./models/golden_parity.json --models-dir ./models
```
### 2. Connect to Claude Code or Antigravity
- **Claude Code:** [`.mcp.json`](.mcp.json) in this repo registers `trusty_code` automatically, or register globally:
```bash
claude mcp add trusty_code -- "$(pwd)/mcp-server/target/release/trusty-mcp" serve --models-dir "$(pwd)/models"
```
- **Antigravity IDE:** Open this repo as your workspace (uses [`.agents/skills/trusty-code/SKILL.md`](.agents/skills/trusty-code/SKILL.md) and [`AGENTS.md`](AGENTS.md)) or add `trusty_code` to `~/.gemini/config/mcp_config.json`.
- **Google Antigravity SDK (`google-antigravity`):** See [`sdk_agent/trusty_agent.py`](sdk_agent/trusty_agent.py):
```python
from sdk_agent.trusty_agent import build_trusty_agent
agent = build_trusty_agent(backend="hosted") # or "local_openai" / "litert"
```
### 3. Run Directly in Terminal
```bash
echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"rust_safety_audit","arguments":{"path":"./benchmarks/fixtures/real_task_hub/src"}}}' \
| ./mcp-server/target/release/trusty-mcp serve --models-dir ./models
```
### 4. Reproduce Benchmarks or Re-Train From Scratch
```bash
python3.11 -m venv .venv
./.venv/bin/pip install -r requirements.txt
# Run both benchmark suites
./.venv/bin/python benchmarks/run_benchmarks.py
./.venv/bin/python benchmarks/real_life_benchmark.py
# Optional: re-extract cached crates.io corpus & retrain PyTorch R-GCNs
cargo run --release --manifest-path extractor/Cargo.toml
./.venv/bin/python -m ml.train_encoder
./.venv/bin/python -m ml.train_repair
./.venv/bin/python -m ml.export_and_plot
```
---
## Repository Layout
- [`extractor/`](extractor) — Rust crate extracting AST/CFG/Data-Flow/Borrow graphs + `rustc`-labeled mutations.
- [`ml/`](ml) — Pure-PyTorch R-GCN training, bootstrap CIs, parity export, and plots (`results/ml/`).
- [`models/`](models) — Pretrained pure-JSON weights (`encoder_weights.json`, `repair_gnn_weights.json`, `golden_parity.json`).
- [`mcp-server/`](mcp-server) — Pure-Rust neural inference & MCP stdio server (`trusty-mcp`).
- [`sdk_agent/`](sdk_agent) — Google Antigravity SDK integration + local OpenAI-compatible eval server.
- [`benchmarks/`](benchmarks) — 12-task `tiktoken`/SDK suite (`run_benchmarks.py`) + 4-suite real-life benchmark (`real_life_benchmark.py`).
## License
Licensed under the **Apache License, Version 2.0**. See [LICENSE](LICENSE).