VENTURESAurabase acquires & invests in your apps, startups, mobile apps, SaaS and software.Read more →

Native AI · 12 min read

Code Mode at Aurabase: Why the Future of AI Agents Combines Traditional MCP and Sandboxed Execution

Affane Daylami · Founder ·

Back to blog

At Aurabase, we already provide a comprehensive 86-tool Model Context Protocol (MCP) server for interactive IDE agents. But for heavy, multi-step autonomous workflows, traditional JSON tool calling hits an unavoidable ceiling. That is why we are developing native Code Mode as a high-performance complement: allowing agents to write and execute sandboxed TypeScript or Python scripts in isolated runtimes.

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 ONLY transactions, 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:

  1. 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.
  2. 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.
  3. 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

  1. Lightweight Type Definitions: The agent is supplied with a compact TypeScript .d.ts declaration representing the @aurabase/aurabase-js SDK. This consumes less than 1,000 tokens.
  2. Programmatic Script Generation: Rather than planning discrete steps across multiple turns, the agent writes a complete programmatic script. It uses standard JavaScript/TypeScript constructs: for loops, map, filter, Promise.all(), and try/catch blocks.
  3. 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.
  4. 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.
Why LLMs prefer code over JSON RPC

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:

MetricTraditional JSON Tool CallingCode Mode (Sandboxed Execution)Architectural Impact
Tool Declaration Footprint20,000 – 1,500,000 tokens~1,000 tokens (Type Definitions)99.9% reduction in prompt overhead
Multi-Step ExecutionN turns with LLM inference1 single script execution turnElimination of N+1 round trips
End-to-End Latency15 – 45 seconds1.2 – 3.5 secondsUp to 10x faster completion
Intermediate Payload HandlingRaw JSON enters prompt contextFiltered in sandbox memoryZero context rot from 5 MB dumps
Error RecoveryLLM must parse error and retryNative try/catch in scriptDeterministic local recovery
ConcurrencySequential or complex async JSONNative 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:

DimensionTraditional MCP Server (@aurabase/mcp-server)Native Code Mode Engine
Primary Use CaseInteractive developer assistance (IDE, coding tools)Autonomous backend agents & analytical workflows
Target ClientsCursor, Claude Code, Claude Desktop, AntigravityBackground worker agents, batch jobs, autonomous loops
Interaction ModelDiscrete atomic tool calls (e.g. list_tables, diff_schema)Programmatic scripts combining queries, vectors, and storage
Payload SizeSmall, targeted JSON responsesHigh-volume raw data processed and summarized in memory
Human in the LoopYes (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:

  1. Zero-Panic Rust Gateway (aura-gateway): Dispatches the execution request in under 500 microseconds without GC spikes.
  2. 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).
  3. 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.
  4. 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:

Never execute agent code with admin privileges

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

  1. 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.
  2. 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).
  3. 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.
  4. 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

FAQ

What is Code Mode at Aurabase?+
Code Mode is an upcoming execution layer in Aurabase designed to complement our 86-tool MCP server. Instead of forcing an autonomous agent to execute dozens of sequential JSON tool calls over the network, Code Mode lets the agent write a TypeScript or Python script that runs inside an isolated sandbox, filters data in memory, and returns only the final distilled answer.
Does Aurabase replace its MCP server with Code Mode?+
No. Aurabase champions a dual architecture: traditional MCP is ideal for interactive developer tooling in IDEs (Cursor, Claude Code, Antigravity) for atomic tasks like checking schemas or generating migrations. Code Mode is designed as a complement for autonomous, multi-step agent pipelines that process thousands of rows or chain complex database, vector, and storage queries.
How does Code Mode achieve a 99% reduction in tokens?+
Instead of injecting 86 distinct JSON schemas into the prompt, Code Mode exposes only a minimal type definition file and two meta-tools (search and execute). Furthermore, intermediate JSON payloads are filtered and aggregated in the sandbox memory rather than being dumped into the LLM context window.
How does Aurabase secure Code Mode in production?+
Aurabase secures Code Mode through a multi-layered zero-panic architecture: sandboxed runtime execution (V8/WASM isolates), strict CPU timeouts (3,000 ms) and memory limits (64 MB), engine-enforced PostgreSQL READ ONLY transactions, and caller-inherited Row-Level Security (RLS).

READY TO DEPLOY?

Your backend in five minutes.

No credit card required · 500 MB free · 50,000 MAU