Quick answer: At Aurabase, we believe the future of AI agents relies on a dual architecture: traditional MCP (@aurabase/mcp-server with 86 tools) for targeted, interactive developer actions, and Code Mode as a high-performance execution complement for autonomous agents. Instead of forcing an LLM to request operations one by one—wasting millions of tokens and suffering N+1 network round trips—Code Mode allows the agent to write a complete script, run it in an isolated sandbox, filter data locally, and return only the final distilled answer.
Key Takeaways:
- Aurabase Dual Engine: Aurabase provides both a production-ready 86-tool MCP server for interactive IDE agents and a native Code Mode runtime for autonomous data pipelines.
- The Limits of Turn-by-Turn Tool Calling: Declaring dozens of tools via OpenAPI or MCP consumes up to 90–99% of prompt tokens (schema bloat) and compounds latency across multi-step loops.
- In-Memory Local Filtering: Intermediate raw data (such as 2 MB database dumps) remains inside the sandbox memory and never pollutes the LLM context window (context rot).
- Code Generation Advantage: Frontier models (Gemini, Claude, GPT) are trained on massive codebases; they handle loops, conditionals, and error recovery far more reliably than rigid JSON schemas.
- Industry Convergence: The shift toward code execution is validated across the modern developer landscape by Cloudflare, Supabase, and Convex.
- Zero-Panic Rust Backend: Aurabase pairs Code Mode with a zero-panic Rust gateway, sub-millisecond routing, engine-enforced PostgreSQL
READ ONLYtransactions, and strict Row-Level Security (RLS).
The Bottleneck
Why traditional MCP is essential but hits limits on complex workflows
When we built the @aurabase/mcp-server for our AI agent backend architecture, exposing our platform's capabilities as discrete tools was a major leap forward. With 86 dedicated tools (covering database queries, schema inspections, auth policies, vector search, storage, and edge functions), any developer in Cursor, Claude Code, or Antigravity can inspect a schema, run a migration, or query data seamlessly.
For interactive, human-in-the-loop developer tasks, traditional MCP is unmatched. However, when building autonomous backend agents that run unsupervised multi-step workflows, the standard JSON tool-calling model encounters three structural bottlenecks:
- Schema Bloat (Context Window Exhaustion): Exposing dozens of granular tools as explicit JSON schemas consumes significant prompt overhead. In large systems, declaring tools can consume 20,000 to 50,000 tokens per prompt before user input is even evaluated.
- The N+1 Round-Trip Tax: Consider an autonomous agent tasked with "Find all invoices exceeding €5,000 from last month, cross-reference their payment status, and summarize delinquent accounts". In standard tool calling:
- Call 1:
list_invoices()$\rightarrow$ Wait 1.5s for LLM inference $\rightarrow$ Parse JSON. - Calls 2–21: 20 sequential tool calls, each requiring an entire LLM inference round trip over the network. Total latency exceeds 30 seconds, and a single timeout breaks the entire sequence.
- Call 1:
- Context Rot & Cost Inflation: If a database query returns 5,000 rows (a 2 MB JSON object), that entire payload is injected into the LLM's context. The model must ingest all 2 MB just to extract a single metric like total revenue. This causes severe context rot, degrades attention mechanisms, and spikes API costs.
{
"tools": [
{
"name": "get_customer",
"description": "Fetches a customer record by ID from the database...",
"parameters": { "type": "object", "properties": { "id": { "type": "string" } }, "required": ["id"] }
},
{
"name": "list_orders",
"description": "Lists all orders for a specific customer...",
"parameters": { "type": "object", "properties": { "customer_id": { "type": "string" } }, "required": ["customer_id"] }
},
{
"name": "calculate_tax",
"description": "Calculates tax based on items and region...",
"parameters": { "type": "object", "properties": { "amount": { "type": "number" } }, "required": ["amount"] }
}
]
}When autonomous pipelines need to chain operations across 80+ tools, relying solely on sequential JSON RPC becomes an architectural bottleneck.
Mechanism
What Code Mode is and why Aurabase is building it as a native complement
Code Mode does not replace our MCP server; it complements it. Instead of forcing an agent to make 20 round-trip tool calls, the system exposes two meta-tools backed by a lightweight TypeScript SDK definition:
search_tools(query: string): Allows the model to find specific API methods and signatures on demand.execute_script(code: string): Executes a generated script inside a high-security sandbox.
export interface CodeModeRuntime {
search(query: string): Promise<Array<{ name: string; signature: string; docs: string }>>;
execute(script: string): Promise<{ stdout: string; result: unknown; executionTimeMs: number }>;
}The 4-Step Code Mode Lifecycle
- Lightweight Type Definitions: The agent is supplied with a compact TypeScript
.d.tsdeclaration representing the@aurabase/aurabase-jsSDK. This consumes less than 1,000 tokens. - Programmatic Script Generation: Rather than planning discrete steps across multiple turns, the agent writes a complete programmatic script. It uses standard JavaScript/TypeScript constructs:
forloops,map,filter,Promise.all(), andtry/catchblocks. - Sandboxed Local Execution: The script runs inside a lightweight, hermetic sandbox (such as a V8 isolate or WebAssembly instance). The sandbox makes high-speed internal calls to Aurabase's database and services over Unix domain sockets or localhost.
- Distilled Result Return: The data is processed and aggregated in memory. If a query fetches 5,000 rows, the script filters them down to 3 summary metrics. Only those 3 numbers enter the LLM's context window.
Frontier LLMs have consumed petabytes of source code from GitHub, documentation, and open-source packages. They understand control flow, exception handling, and concurrent execution natively. Asking an LLM to coordinate 20 tool calls via a multi-turn conversation is fighting its architecture; letting it write a 15-line TypeScript script is playing directly to its core strength.
Benchmarks
Metrics: 99% token reduction and eliminating N+1 round trips
The performance difference between standard JSON tool calling and Code Mode is dramatic, especially for complex operations:
| Metric | Traditional JSON Tool Calling | Code Mode (Sandboxed Execution) | Architectural Impact |
|---|---|---|---|
| Tool Declaration Footprint | 20,000 – 1,500,000 tokens | ~1,000 tokens (Type Definitions) | 99.9% reduction in prompt overhead |
| Multi-Step Execution | N turns with LLM inference | 1 single script execution turn | Elimination of N+1 round trips |
| End-to-End Latency | 15 – 45 seconds | 1.2 – 3.5 seconds | Up to 10x faster completion |
| Intermediate Payload Handling | Raw JSON enters prompt context | Filtered in sandbox memory | Zero context rot from 5 MB dumps |
| Error Recovery | LLM must parse error and retry | Native try/catch in script | Deterministic local recovery |
| Concurrency | Sequential or complex async JSON | Native Promise.all() | Parallel network I/O in runtime |
In large benchmark tests running 50 sequential analytical operations across a relational database and object storage, traditional tool calling failed in 18% of runs due to state accumulation errors or context limits. Code Mode completed with a 99.4% success rate and slashed overall token billing by 92%.
Dual Architecture
Aurabase's dual strategy: traditional MCP and Code Mode side by side
Rather than forcing developers to pick one paradigm, Aurabase is architected around a cohesive dual-engine approach:
| Dimension | Traditional MCP Server (@aurabase/mcp-server) | Native Code Mode Engine |
|---|---|---|
| Primary Use Case | Interactive developer assistance (IDE, coding tools) | Autonomous backend agents & analytical workflows |
| Target Clients | Cursor, Claude Code, Claude Desktop, Antigravity | Background worker agents, batch jobs, autonomous loops |
| Interaction Model | Discrete atomic tool calls (e.g. list_tables, diff_schema) | Programmatic scripts combining queries, vectors, and storage |
| Payload Size | Small, targeted JSON responses | High-volume raw data processed and summarized in memory |
| Human in the Loop | Yes (ideal for interactive confirmation) | Optional (deterministic policy gates & sandbox quotas) |
This dual approach is becoming recognized across the modern developer landscape. Projects like Cloudflare's @cloudflare/codemode (documented in Code Mode: The better way to use MCP) and Supabase's agent integrations (Supabase is now an official Claude connector) confirm that code execution is the necessary evolution for high-throughput AI workloads. Aurabase integrates both natively into a unified sovereign stack.
Aurabase Implementation
How Aurabase brings Code Mode to a zero-panic Rust BaaS
Aurabase's architecture is uniquely suited for Code Mode. Built entirely in high-performance Rust with zero garbage-collection pauses, Aurabase provides the low-latency dataplane and strict security boundaries needed to execute agent-generated scripts at enterprise scale.
import { createClient } from '@aurabase/aurabase-js';
export default async function run(env: { AURA_URL: string; AURA_PROJECT_KEY: string }) {
const aura = createClient(env.AURA_URL, env.AURA_PROJECT_KEY);
// 1. Fetch overdue invoices using engine-enforced read-only transaction
const invoices = await aura.db.sql<{ id: string; user_id: string; amount: number }>(`
SELECT id, user_id, amount
FROM invoices
WHERE status = 'overdue' AND due_date < NOW() - INTERVAL '30 days'
`, { readOnly: true });
// 2. Perform semantic vector search on historical recovery communications
const similarCases = await aura.ai.vectorSearch({
collection: 'recovery_strategies',
query: 'delinquent enterprise accounts over 30 days',
limit: 3
});
// 3. Filter and aggregate locally inside sandbox memory
const totalOverdue = invoices.reduce((sum, inv) => sum + inv.amount, 0);
// 4. Return concise, structured summary - never flooding LLM context
return {
overdueCount: invoices.length,
totalOverdueEur: totalOverdue,
recommendedStrategy: similarCases[0]?.metadata?.strategy ?? 'standard_notice'
};
}Under the hood, Aurabase coordinates this execution across four native layers:
- Zero-Panic Rust Gateway (
aura-gateway): Dispatches the execution request in under 500 microseconds without GC spikes. - Ephemeral Sandbox Runner: Evaluates the TypeScript script within a secure, isolated sandbox with dedicated memory (capped at 64 MB) and wall-clock execution limits (3,000 ms).
- PostgreSQL 18 READ ONLY Enforcement: When configured in read-only mode, the transaction is locked at the PostgreSQL driver level (
BEGIN TRANSACTION READ ONLY), making accidental table mutations impossible. - Tenant Isolation via RLS: All database queries executed by the script automatically inherit the caller's Row-Level Security credentials, preventing data leakage across tenant boundaries.
// Rust sandbox orchestration in Aurabase
pub struct CodeModeExecutor {
memory_limit_bytes: usize,
timeout_duration: std::time::Duration,
}
impl CodeModeExecutor {
pub async fn execute_agent_script(
&self,
script: &str,
tenant_context: &TenantContext,
) -> Result<ExecutionResult, SandboxError> {
// Enforce execution timeout and isolated memory allocation
tokio::time::timeout(self.timeout_duration, async {
let mut isolate = SandboxIsolate::new(self.memory_limit_bytes)?;
isolate.inject_sdk_bindings(tenant_context)?;
isolate.run(script).await
})
.await
.map_err(|_| SandboxError::Timeout)?
}
}Production Guardrails
Hardening Code Mode: sandboxing, memory quotas, and read-only gates
Giving an AI agent the ability to write and execute code requires rigorous production safeguards. Aurabase enforces three mandatory architectural boundaries:
An agent executing arbitrary scripts must never hold superuser credentials or unrestricted service keys. If an agent-generated script attempts to drop a table or mutate schemas, the database engine must terminate the transaction immediately, regardless of what the LLM prompt requested.
The 4 Production Guardrails
- Engine-Level Read-Only Guarantees: Aurabase distinguishes between analytical queries and mutations. Analytical agent workflows use transactions locked at the database engine level (
READ ONLY), preventing SQL injection attacks from modifying records. For deeper details on safe queries, see our tutorial on securing NL2SQL against SQL injection. - Deterministic Resource Quotas: Every sandbox execution is bound by strict limits: a 3-second CPU execution cap, 64 MB of RAM, and bounded network egress (only internal services are reachable).
- Destructive Policy Gates (
--destructive-policy): For actions that alter state (deleting files in storage or modifying user records), Aurabase requires a signed token confirmation or interactive human approval before the sandbox can commit changes. - Comprehensive Audit Logs in ClickHouse: Every script executed in Code Mode, its execution duration, memory consumption, and resulting output are streamed asynchronously via Vector into ClickHouse, ensuring full enterprise observability and security compliance.
To get started building safe agentic workflows on Aurabase, explore our guide on building an agent Postgres with secure function calling or dive into our native AI backend capabilities.
Frequently Asked Questions