SitePoint21 min readintermediate
Securing AI Agent Tool Execution with TypeScript AST Sandboxes
Summary
The article shows how to protect AI‑generated shell/SQL commands by parsing them with real AST parsers (tree‑sitter for Bash, Babel for JS‑embedded SQL) and enforcing structural allowlists plus command/path whitelists, instead of fragile regex filters.
- Regex deny‑lists cannot reliably block injection because they operate on raw strings, not on command structure.
- Parsing the payload into a concrete syntax tree (CST) lets you whitelist only safe node types (e.g., `command`, `word`, `raw_string`).
- Tree‑sitter‑bash provides a Bash grammar that can be used in Node.js to produce a CST and detect dangerous constructs like `command_substitution`, `expansion`, and `subshell`.
- A two‑layer validation is needed: first structural validation of the AST, then a command‑name and filesystem path allowlist (e.g., using `minimatch`).
AI agents that auto‑generate commands are increasingly used in production. A single injection can give the model arbitrary code execution on your infrastructure. Moving from regex filters to AST‑based validation provides a deterministic, language‑aware security boundary that can be audited and exte…
6/10




