DEV Community

Cover image for Zero External Crates: Pure Rust std Parsers, Scoped Threads, and an Enum Safety Gate
Umair Baig
Umair Baig

Posted on Edited on Originally published at umairbaig8.github.io AI-assisted

Zero External Crates: Pure Rust std Parsers, Scoped Threads, and an Enum Safety Gate

When I started writing tapy (a small local CLI sidecar that inspects project context and talks to databases, containers, and local tools), I set one constraint on Cargo.toml: keep [dependencies] empty.

[package]
name = "tapy"
version = "0.2.0"
edition = "2021"
license = "MIT"

[profile.release]
opt-level = "z"
lto = true
codegen-units = 1
strip = true
Enter fullscreen mode Exit fullscreen mode

That keeps the stripped binary around 1.2 MB and incremental rebuilds around 1.5s, but it also forces you to write a few pieces yourself that normally come from crates: a trait-level safety gate, a Redis RESP2 client over TcpStream, a recursive-descent JSON parser, and a parallel context scanner built on std::thread::scope.

Below is a walkthrough of how those pieces are structured, two real panic bugs I caught in my own hand-rolled JSON parser during review, and how profiling a parallel sniffer dropped wall-clock runtime from 41ms to 12.8ms.

1. Enforcing Safety in a Trait and Enum (src/drivers/mod.rs)

Most tool wrappers put safety instructions in a system prompt and hope the model follows them. Instead, every driver in the binary implements a single TargetDriver trait that separates safety classification from execution:

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum SafetyTier {
    /// Non-mutating observation (`SELECT`, `GET`, `git status`). Runs automatically.
    Read,
    /// State-changing operation (`INSERT`, `POST`, `docker restart`). Requires `[y/N]`.
    Mutate,
    /// Irreversible or high-blast-radius (`DROP`, `DELETE`, `rm`). Requires `CONFIRM`.
    Destructive,
}

pub trait TargetDriver: Sync {
    fn name(&self) -> &'static str;
    fn can_handle(&self, uri: &str) -> bool;
    fn introspect(&self, uri: &str) -> Result<TargetIntrospection, String>;
    fn classify_safety(&self, req: &ActionRequest) -> SafetyTier;
    fn act(&self, req: &ActionRequest) -> Result<ActionResult, String>;
}
Enter fullscreen mode Exit fullscreen mode

The dispatcher calls driver.classify_safety(&req) before driver.act(&req) is ever invoked. Over stdio MCP (tapy mcp) or the local loopback HTTP bridge, SafetyTier::Destructive is rejected unconditionally in Rust before any subprocess, SQL statement, or socket write runs.

One important rule across every classifier: fail closed. Unrecognized commands or subcommands default to SafetyTier::Mutate, never SafetyTier::Read. For example, in src/drivers/redis.rs:

pub fn classify_redis_cmd(cmd_upper: &str) -> SafetyTier {
    match cmd_upper {
        "PING" | "ECHO" | "INFO" | "DBSIZE" | "GET" | "MGET" | "HGET" | "HGETALL" | "HKEYS"
        | "HLEN" | "LRANGE" | "LLEN" | "SMEMBERS" | "SCARD" | "ZRANGE" | "ZCARD" | "TTL"
        | "PTTL" | "TYPE" | "EXISTS" | "KEYS" | "SCAN" | "STRLEN" | "TIME" => SafetyTier::Read,
        "DEL" | "UNLINK" | "FLUSHDB" | "FLUSHALL" | "SHUTDOWN" | "CONFIG" | "DEBUG" | "EVAL"
        | "EVALSHA" | "SCRIPT" | "MODULE" | "ACL" | "SLAVEOF" | "REPLICAOF" | "MIGRATE"
        | "RESTORE" | "SWAPDB" => SafetyTier::Destructive,
        _ => SafetyTier::Mutate,
    }
}
Enter fullscreen mode Exit fullscreen mode

At the database layer, read queries also add OS/engine locks where available: SQLite opens with -readonly, and PostgreSQL runs inside PGOPTIONS="-c default_transaction_read_only=on".

2. Bounded RESP2 Framing Over std::net::TcpStream (src/drivers/redis.rs)

Encoding RESP2 requests is trivial (*<n>\r\n$<byte_len>\r\n<arg>\r\n, using arg.len() for UTF-8 byte length rather than character count). Reading responses safely is where hand-rolled wire code can go wrong.

My first version called BufRead::read_line directly, parsed $ bulk lengths into isize, allocated vec![0u8; len as usize] with no cap, and ignored the trailing \r\n bytes. A corrupted or hostile peer sending $999999999999\r\n or an endless line without \n would OOM the process, and a framing mismatch on the trailing CRLF would silently desync the stream.

The tightened reader bounds line length with Read::take, caps bulk allocations and array counts, tracks recursion depth on nested arrays, and verifies every \r\n terminator:

const MAX_RESP_LINE_BYTES: usize = 64 * 1024;
const MAX_RESP_BULK_BYTES: usize = 8 * 1024 * 1024;
const MAX_RESP_ARRAY_LEN: usize = 10_000;
const MAX_RESP_DEPTH: usize = 32;

fn read_resp_line<R: BufRead>(reader: &mut R) -> Result<String, String> {
    let mut buf = Vec::new();
    let n = reader
        .by_ref()
        .take((MAX_RESP_LINE_BYTES + 1) as u64)
        .read_until(b'\n', &mut buf)
        .map_err(|e| format!("Redis read error: {e}"))?;
    if n == 0 {
        return Err("Redis connection closed unexpectedly".to_string());
    }
    if buf.len() > MAX_RESP_LINE_BYTES {
        return Err(format!("RESP line exceeded {MAX_RESP_LINE_BYTES} bytes"));
    }
    if !buf.ends_with(b"\r\n") {
        return Err("Malformed RESP frame: missing CRLF line terminator".to_string());
    }
    buf.truncate(buf.len() - 2);
    String::from_utf8(buf).map_err(|_| "Malformed RESP header: invalid UTF-8".to_string())
}
Enter fullscreen mode Exit fullscreen mode

For $ bulk strings, only -1 maps to (nil); any other negative length (len < -1) or length above MAX_RESP_BULK_BYTES returns an error, and the 2-byte trailer after read_exact must equal *b"\r\n".

3. Two Real Panic Bugs in a Hand-Rolled JSON Parser (src/json.rs)

Without serde_json, src/json.rs implements a small recursive-descent parser for MCP JSON-RPC, local HTTP payloads, and LLM responses. While auditing it after reader feedback in the comments below, I hit two genuine panic bugs in \uXXXX string escape handling.

Bug 1: u32 underflow on invalid UTF-16 surrogate pairs

My original code checked whether the first \u escape was a high surrogate (0xD800..=0xDBFF), read the next \u escape into low, and computed:

// Buggy: panics on "\uD800\u0041" because 0x0041 < 0xDC00
let combined = 0x10000 + (((code as u32 - 0xD800) << 10) | (low as u32 - 0xDC00));
Enter fullscreen mode Exit fullscreen mode

If low was not in 0xDC00..=0xDFFF, low as u32 - 0xDC00 underflowed and panicked in debug builds (or wrapped silently in release).

Bug 2: UTF-8 char-boundary panic in parse_hex4

The original parse_hex4 sliced &self.src[self.pos..self.pos + 4] after checking self.pos + 4 <= self.bytes.len(). If a multi-byte UTF-8 character appeared inside a malformed escape like "\uƩ", self.pos + 4 could land in the middle of a UTF-8 sequence and panic at runtime.

Fixing both meant validating ASCII hex bytes on &[u8] first, rejecting unpaired or out-of-range surrogates, enforcing a recursion depth limit (MAX_JSON_DEPTH = 128) on arrays/objects, rejecting unescaped control bytes < 0x20, and parsing numbers against strict RFC 8259 grammar instead of delegating loosely to f64::parse (which otherwise accepts +1, 01, 1., and overflows to inf):

fn parse_hex4(&mut self) -> Result<u16, String> {
    let slice = self
        .bytes
        .get(self.pos..self.pos + 4)
        .ok_or_else(|| "incomplete \\u escape".to_string())?;
    if !slice.iter().all(|b| b.is_ascii_hexdigit()) {
        return Err("invalid hex escape".to_string());
    }
    let hex = std::str::from_utf8(slice).map_err(|_| "invalid hex escape".to_string())?;
    self.pos += 4;
    u16::from_str_radix(hex, 16).map_err(|_| format!("invalid hex escape '{hex}'"))
}
Enter fullscreen mode Exit fullscreen mode

4. Parallel Sniffing With std::thread::scope and Cutting Latency From 41ms to 12.8ms

To gather local project context without spawning an async runtime, src/sniffers/mod.rs defines a single Sniffer: Sync trait and runs 7 stack-allocated sniffers concurrently via std::thread::scope:

pub trait Sniffer: Sync {
    fn name(&self) -> &'static str;
    fn sniff(&self, root: &Path) -> Vec<Target>;
}

let results: Vec<(SnifferReport, Vec<Target>)> = thread::scope(|scope| {
    let handles: Vec<_> = active
        .iter()
        .map(|sniffer| {
            scope.spawn(move || {
                let t0 = Instant::now();
                let targets = sniffer.sniff(root);
                let report = SnifferReport {
                    name: sniffer.name(),
                    count: targets.len(),
                    duration_ms: t0.elapsed().as_secs_f64() * 1000.0,
                };
                (report, targets)
            })
        })
        .collect();
    handles.into_iter().filter_map(|h| h.join().ok()).collect()
});
Enter fullscreen mode Exit fullscreen mode

Because thread::scope guarantees all worker threads join before returning, each thread borrows &dyn Sniffer and &Path directly from the stack with no Arc or 'static clones.

When I first timed a warm run on Apple Silicon macOS, the per-sniffer breakdown surprised me. I expected localhost port scanning or .mcp.json discovery to dominate, but git set the entire wall-clock floor:

Sniffer Before (warm) After commit 15ec39a (warm)
git 40.3 - 41.4 ms 10.9 - 12.0 ms
app (lsappinfo) 11.4 - 11.8 ms 12.3 - 16.4 ms
ports 0.4 - 1.6 ms 0.5 - 1.1 ms
folder / cli / mcp / hardware 0.1 - 0.8 ms each 0.1 - 0.9 ms each
Total tapy sniff (warm) 40.8 - 41.9 ms 12.8 - 16.9 ms

The bottleneck in src/sniffers/git.rs was spawning 5 sequential git subprocesses (rev-parse --show-toplevel, rev-parse --abbrev-ref HEAD, status --porcelain=v1 --branch, remote get-url origin, and log -1). At ~8ms per process spawn on macOS, those 5 sequential calls ate the entire budget.

Replacing the first 3 with direct filesystem reads (walking Path::ancestors() for .git, resolving worktree/submodule gitdir: + commondir, parsing .git/HEAD and .git/config) and running the remaining 2 (git status and git log) in parallel inside std::thread::scope cut git by ~3.6x:

pub fn inspect_git_repo(dir: &Path, strict_dir_only: bool) -> Option<GitSummary> {
    let (top_path, git_dir) = find_git_root_and_dir(dir, strict_dir_only)?;
    let branch = read_head_branch(&git_dir).unwrap_or_else(|| "HEAD".to_string());
    let remote = read_origin_remote(&git_dir).map(|u| sanitize_remote(&u));

    let (status_out, log_out) = std::thread::scope(|s| {
        let h_status = s.spawn(|| {
            run_git(&top_path, &["status", "--porcelain=v1", "--branch"]).unwrap_or_default()
        });
        let h_log = s.spawn(|| run_git(&top_path, &["log", "-1", "--format=%cr\t%s"]));
        (
            h_status.join().unwrap_or_default(),
            h_log.join().ok().flatten(),
        )
    });
    // parse ahead/behind, dirty count, and last commit...
}
Enter fullscreen mode Exit fullscreen mode

At ~11ms, git is now slightly faster than macOS lsappinfo (~12ms), which becomes the new wall-clock floor.

5. Honest Trade-Offs of Zero External Crates

Keeping [dependencies] empty worked better than I expected for protocol framing, JSON, parallel discovery, and CLI argument parsing, but there are clear downsides:

  • Testing burden: Hand-rolled parsers do not get the years of fuzzing behind serde_json or redis-rs. Adding cargo-fuzz targets for json.rs and redis.rs plus a live Redis container in CI is still on my list (currently the crate has 50 deterministic unit tests).
  • Precision in JsonValue::Number(f64): Storing all JSON numbers as f64 keeps the DOM tiny, but integers past 2^53 lose precision compared to serde_json::Number.
  • TLS: Reimplementing TLS in pure std is not sensible, so TLS-heavy targets (HTTPS, Postgres, Kubernetes, AWS, Docker) delegate to system binaries (curl, psql, kubectl, aws, docker) rather than opening raw sockets.

The full source (including src/json.rs, src/drivers/redis.rs, and src/sniffers/git.rs) is on GitHub at UmairBaig8/tapy. If you see other edge cases in the wire parsers or ways to trim more overhead from the git sniffer, I would appreciate the critique.

Top comments (3)

Collapse
 
userxnom profile image
Abdullah Naseer •

The part that actually changes the design is SafetyTier. Most agent wrappers put the safety rule in the prompt and hope the model obeys it; you put it in an enum match that runs before any subprocess, SQL statement, or network write, so a prompt injection literally cannot talk its way past it. That is the idea worth stealing.

The trade-off I would watch is the hand-rolled wire code. The Redis classifier and the recursive-descent JSON parser are exactly the two places where a small parsing bug silently changes semantics instead of failing loudly — a misread RESP2 bulk-string length, a JSON number edge case. With no serde or redis crate to lean on, what is the test story for those two pieces — fuzzing, property tests against a real Redis, or something else?

And one number I would love to see broken down: of the 45–60ms sniff, which sniffer dominates the budget? If it is the ports scan or the .mcp.json walk, that tells me where the next millisecond lives.

Collapse
 
umairbaig8 profile image
Umair Baig •

Fair critique on both points.

1. Test story on the hand-rolled wire code (json.rs & redis.rs)

Honest answer: right now it is just deterministic unit tests (cargo test has 45 tests across the crate, with basic round-trip and classification tests in json.rs and redis.rs using an in-memory Cursor). No cargo-fuzz harness or live Redis container in CI yet.

On the safety side, classify_redis_cmd fails closed: it allowlists explicit read commands, marks destructive ones (DEL, FLUSHDB, FLUSHALL, CONFIG, SHUTDOWN, DEBUG), and defaults _ to SafetyTier::Mutate, so an unexpected command still hits the [y/N] gate rather than running silently.

Looking closely at the parser code with your lens, there are a few real gaps to tighten up:

  • read_resp_value allocates vec![0u8; len as usize] directly from the $ bulk length without an upper bound and ignores the trailing \r\n bytes.
  • json.rs stores all numbers as f64 (so integers past 2^53 lose precision), delegates number parsing to f64::parse (slightly looser than strict RFC 8259), and does not cap nesting depth yet.

Adding a bulk-length cap, recursion depth limit, cargo-fuzz targets for both parsers, and a real Redis service container in GitHub Actions is a solid next hardening pass.

2. Per-sniffer breakdown of the 45-60ms budget

Surprised me too when I first timed it: ports and .mcp.json are actually tiny. Here is a typical run on Apple Silicon macOS (all 7 sniffers run in parallel under std::thread::scope):

  • git: ~45-65ms (sets the entire wall-clock floor)
  • app (lsappinfo): ~14ms
  • ports: ~1.6-2.3ms
  • mcp (.mcp.json): ~0.9-1.0ms
  • folder, cli, hardware: ~0.4-2.0ms each

The reason git dominates is in src/sniffers/git.rs: inspect_git_repo currently spawns 5 sequential git subprocesses (rev-parse --show-toplevel, rev-parse --abbrev-ref HEAD, status --porcelain=v1 --branch, remote get-url origin, and log -1). At ~8-12ms per macOS process spawn, that eats the whole budget.

So the next 30ms lives in reading .git/HEAD and .git/config directly from disk and dropping down to a single git call (or parallelizing the remaining two), which would bring the floor down to lsappinfo (~14ms).

Collapse
 
umairbaig8 profile image
Umair Baig •

Quick follow-up: your comment pushed me to actually fix both right away in commit 15ec39a:

  • git sniffer: replaced 3 subprocess spawns with direct .git/HEAD + .git/config reads and parallelized git status + git log. Warm tapy sniff dropped from 40.8ms to 12.8ms (git itself went from 40.3ms down to 10.9ms).
  • json.rs & redis.rs: fixed two real panic bugs I spotted while auditing (\uD800\u0041 surrogate underflow and UTF-8 boundary slicing in \u escapes), added strict RFC 8259 number parsing, nesting/bulk/array caps (8 MiB / depth 128 & 32), strict CRLF checks, and moved EVAL/SCRIPT/ACL/MODULE into SafetyTier::Destructive.