mcp-context-forge icon indicating copy to clipboard operation
mcp-context-forge copied to clipboard

[EPIC][CORE]: Secure Code Execution & Virtual Tool Filesystem (MCP Code Mode)

Open crivetimihai opened this issue 9 months ago • 1 comments

[EPIC][CORE]: Secure Code Execution & Virtual Tool Filesystem

Goal

Build a secure code execution layer with a virtual tool filesystem that exposes MCP tools as navigable files and directories, enabling AI agents to discover, compose, and run thousands of tools through a single sandboxed shell interface—reducing context token consumption by up to 98% while maintaining security, observability, and multi-tenancy guarantees.

Instead of injecting all tool definitions into an agent's context upfront, tools are mounted as typed files on a virtual filesystem (inspired by Unix /dev). The agent receives one meta-tool—a sandboxed shell—and explores, searches, and orchestrates tools by writing code against the filesystem API.

This does not replace MCP. Code execution is a layer on top of the MCP protocol. The gateway still manages MCP servers, transports, auth, and tool registries. What changes is how agents consume those tools: instead of receiving 1000 tool definitions in their context and making sequential tool calls, they receive a sandboxed environment where tools are importable typed modules. Every tool call still flows through the MCP gateway's existing pipeline (RBAC, rate limiting, plugin hooks, audit). The goal is to build dynamic MCPs that improve token consumption, accuracy in multi-tool workflows, and orchestration of complex tool chains—not to bypass the protocol.

Why Now?

  1. Token Explosion: Production gateways host 1000+ tools. Injecting all definitions upfront consumes 100K+ tokens before the agent does anything useful. Anthropic's research demonstrates a 98.7% token reduction with filesystem-based progressive disclosure.
  2. Intermediate Result Bloat: Sequential tool calls force every intermediate result through model context. A 50K-token meeting transcript passed between two tools costs 150K tokens. Code keeps data in the sandbox, never re-entering context.
  3. Composition Gap: Current tool invocation is stateless and sequential—agents can't loop, filter, or compose tools natively. Code enables for loops, conditionals, and piping between tools without additional model round-trips.
  4. Existing Foundation: The Rust filesystem server (mcp-servers/rust/filesystem-server/) provides sandboxed file I/O, the plugin framework supports pre/post hooks for security, and plugins_rust/ demonstrates PyO3 acceleration for performance-critical paths.
  5. Complementary to Semantic Discovery: The sweng-group-19 epic (#2228) solves "find the right tool among thousands" with embeddings and NL. This epic solves "run tools efficiently once found"—they compose naturally (semantic search narrows, filesystem exposes, code runs).
  6. Industry Convergence: Both Anthropic and Cloudflare independently published code-mode approaches confirming that agents writing code against tool APIs outperform sequential function calling for multi-step workflows.

Platform Components

+-----------------------------------------------------------------------------------+
|                  Secure Code Execution & Virtual Tool Filesystem                  |
+-----------------------------------------------------------------------------------+
|                                                                                   |
|  +-----------------------------------------------------------------------------+ |
|  |                         Agent-Facing Layer                                   | |
|  |                                                                              | |
|  |   +---------------+    +---------------+    +----------------------------+   | |
|  |   |  shell_exec   |    |  fs_browse    |    |     skills_manager        |   | |
|  |   |  (meta-tool)  |    |  (discovery)  |    |     (reusable code)       |   | |
|  |   +-------+-------+    +-------+-------+    +------------+---------------+   | |
|  |           |                    |                         |                    | |
|  |           +--------------------+-------------------------+                    | |
|  |                                |                                              | |
|  +--------------------------------|----------------------------------------------+ |
|                                   v                                               |
|  +-----------------------------------------------------------------------------+ |
|  |                      Security & Isolation Layer                              | |
|  |                                                                              | |
|  |   +---------------+    +---------------+    +---------------+                | |
|  |   |   Sandbox     |    |   Data        |    |   Resource    |                | |
|  |   |   Runtime     |    |   Tokenizer   |    |   Limiter     |                | |
|  |   |   (isolate)   |    |   (PII mask)  |    |   (cpu/mem)   |                | |
|  |   +---------------+    +---------------+    +---------------+                | |
|  |                                                                              | |
|  |   +---------------+    +---------------+    +---------------+                | |
|  |   |   Audit       |    |   RBAC        |    |   Network     |                | |
|  |   |   Logger      |    |   Enforcer    |    |   Policy      |                | |
|  |   +---------------+    +---------------+    +---------------+                | |
|  +-----------------------------------------------------------------------------+ |
|                                   |                                               |
|  +--------------------------------|----------------------------------------------+ |
|  |                     Virtual Tool Filesystem                                  | |
|  |                                v                                              | |
|  |   /tools/                                                                     | |
|  |   +-- _catalog.json            (full tool index + metadata, searchable)       | |
|  |   +-- _schema.json             (filesystem schema version)                    | |
|  |   +-- google-drive/                                                           | |
|  |   |   +-- _meta.json           (server info, auth status, health)             | |
|  |   |   +-- get_document.ts      (typed async function + JSDoc)                 | |
|  |   |   +-- list_files.ts                                                       | |
|  |   |   +-- search.ts                                                           | |
|  |   +-- salesforce/                                                             | |
|  |   |   +-- _meta.json                                                          | |
|  |   |   +-- update_record.ts                                                    | |
|  |   |   +-- query.ts                                                            | |
|  |   |   +-- create_record.ts                                                    | |
|  |   +-- analytics/                                                              | |
|  |   |   +-- ...                                                                 | |
|  |   +-- .search_index            (pre-built ripgrep-compatible index)           | |
|  |                                                                               | |
|  |   /scratch/                    (agent working directory)                       | |
|  |   /skills/                     (reusable saved functions)                      | |
|  |   /results/                    (outputs, downloadable)                         | |
|  +-----------------------------------------------------------------------------+ |
|                                   |                                               |
|  +--------------------------------|----------------------------------------------+ |
|  |                     MCP Gateway Tool Registry                                | |
|  |                                v                                              | |
|  |   +---------------+    +---------------+    +---------------+                | |
|  |   |  1000s of     |    |  A2A Agents   |    |  Peer         |                | |
|  |   |  MCP Tools    |    |               |    |  Gateways     |                | |
|  |   +---------------+    +---------------+    +---------------+                | |
|  +-----------------------------------------------------------------------------+ |
|                                                                                   |
+-----------------------------------------------------------------------------------+

Data Flow: Sequential Tool Calls vs. Code

Before (sequential tool calls — ~220K tokens for 2 calls):

Agent                          Model Context              MCP Gateway
  |                                |                          |
  |  inject 1000 tool defs         |                          |
  |  ----------------------------->|  +120K tokens            |
  |                                |                          |
  |  call: get_transcript(id)      |                          |
  |  ----------------------------->|------------------------->|
  |                                |  +50K tokens (result)    |
  |                                |<-------------------------|
  |                                |                          |
  |  call: update_record(data)     |  transcript re-parsed    |
  |  ----------------------------->|------------------------->|
  |                                |  +50K tokens (re-sent)   |
  |                                |                          |
  |           Total: ~220K tokens for 2 tool calls            |

After (code execution — ~2.2K tokens for the same operation):

Agent                          Model Context              Sandbox
  |                                |                          |
  |  inject 3 meta-tools           |                          |
  |  ----------------------------->|  +2K tokens              |
  |                                |                          |
  |  shell_exec(code):             |                          |
  |  ----------------------------->|                          |
  |    const t = await gdrive      |                          |
  |      .getDocument({id})        |------------------------->|
  |    await salesforce             |  transcript stays in     |
  |      .updateRecord({data: t})  |  sandbox memory -------> |
  |                                |                          |
  |  result: "Done, 1 record"      |  +200 tokens (summary)  |
  |                                |<-------------------------|
  |                                |                          |
  |           Total: ~2.2K tokens for the same operation      |

User Stories

US-1: AI Agent — Discover Tools via Filesystem Navigation

As an AI Agent connected to a gateway with 2000+ tools I want to explore available tools by browsing a virtual filesystem So that I load only the tool definitions I need, on demand

Acceptance Criteria:

Given the agent is connected to a code-execution-enabled virtual server:
When the agent calls:
  shell_exec(code="ls /tools/")
Then it receives a directory listing:
  google-drive/
  salesforce/
  analytics/
  slack/
  ... (47 servers)

When the agent calls:
  shell_exec(code="cat /tools/google-drive/get_document.ts")
Then it receives the typed function signature and JSDoc:
  /**
   * Retrieve a Google Drive document by ID.
   * @param documentId - The document's unique identifier
   * @param format - Output format: "text" | "markdown" | "html"
   * @returns { content: string, metadata: DocumentMeta }
   */
  export async function get_document(args: {
    documentId: string;
    format?: "text" | "markdown" | "html";
  }): Promise<{ content: string; metadata: DocumentMeta }>;

And only ~200 tokens were consumed (not 120K for all tools)

Technical Requirements:

  • Define filesystem schema: /tools/<server>/<tool>.ts|.py, _catalog.json, _meta.json
  • Tool stub codegen from JSON Schema inputSchema to TypeScript (interfaces + JSDoc) and Python (TypedDict + docstrings)
  • Virtual server config selects language via stub_language: "typescript" | "python" (default matches runtime)
  • Lazy generation: stubs materialized on first access, cached with TTL
  • _catalog.json includes entity metadata (created_by, created_at, created_via, federation_source, modified_by, modified_at) for in-sandbox metadata queries via jq
  • Per-server _meta.json with health, auth status, tool count, server metadata
  • ~150 bytes per tool in catalog = ~75KB for 500 tools
US-2: AI Agent — Search Tools with Standard Unix Tools

As an AI Agent looking for tools related to "CSV" or "spreadsheet" I want to search the virtual filesystem using grep/ripgrep patterns So that I can discover relevant tools without semantic search infrastructure

Acceptance Criteria:

Given the virtual filesystem is mounted with tool stubs:
When the agent calls:
  shell_exec(code="grep -r 'csv\\|spreadsheet' /tools/ --include='*.ts' -l")
Then it receives matching file paths:
  /tools/google-drive/get_sheet.ts
  /tools/analytics/csv_analyzer.ts
  /tools/data-pipeline/csv_transform.ts

When the agent calls:
  shell_exec(code="cat /tools/_catalog.json | jq '.tools[] | select(.tags | contains([\"csv\"]))'")
Then it receives structured tool metadata for CSV-tagged tools

When the agent queries entity metadata:
  shell_exec(code="cat /tools/_catalog.json | jq '.tools[] | select(.created_via == \"federation\")'")
Then it receives tools that came from peer gateways

And the agent can combine text search with structured metadata queries
And no additional model round-trips were required for discovery

Technical Requirements:

  • Pre-built .search_index for ripgrep-compatible search
  • _catalog.json supports both tag-based and metadata-based filtering
  • Metadata fields sourced from existing DB columns on all entity tables (#1359)
US-3: AI Agent — Multi-Tool Workflows as Code

As an AI Agent I want to write and run code that orchestrates multiple tool calls So that intermediate data stays in the sandbox and never re-enters my context

Acceptance Criteria:

Given the agent needs to process a 10,000-row spreadsheet:
When the agent calls:
  shell_exec(code=`
    const sheet = await tools.googleDrive.getSheet({ sheetId: 'abc123' });
    const highValue = sheet.rows.filter(r => r.revenue > 100000);
    for (const row of highValue) {
      await tools.salesforce.updateRecord({
        objectType: 'Account',
        recordId: row.accountId,
        data: { tier: 'enterprise', lastSync: new Date().toISOString() }
      });
    }
    return { processed: highValue.length, total: sheet.rows.length };
  `)
Then the agent receives only the summary:
  { "processed": 47, "total": 10000 }
And the 10,000 rows never entered model context
And all 47 Salesforce updates ran within the sandbox
And the run is logged with timing and tool call counts

Technical Requirements:

  • shell_exec MCP tool: accepts code, language (typescript|python), timeout_ms, stream (reserved, ignored for now)
  • fs_browse companion tool for lightweight directory listing without full sandbox session
  • Plugin pre/post hooks (tool_pre_invoke, tool_post_invoke) fire for shell_exec
  • Each __toolcall__ inside the sandbox goes through gateway's RBAC, rate limiting, and audit
  • Structured result: { output, error, metrics, tool_calls_made }
US-4: Platform Admin — Configure Sandbox Security Policies

As a Platform Administrator I want to define security policies for the code sandbox So that agent-generated code runs within strict resource and access bounds

Acceptance Criteria:

Given the sandbox configuration:
  code_execution:
    enabled: true
    runtime: "deno"  # or "gvisor", "wasm", "nsjail"
    limits:
      max_execution_time_ms: 30000
      max_memory_mb: 256
      max_cpu_percent: 50
      max_network_connections: 0  # no raw network access
      max_file_size_mb: 10
      max_total_disk_mb: 100
    permissions:
      filesystem:
        read: ["/tools/**", "/skills/**"]
        write: ["/scratch/**", "/results/**"]
        deny: ["/etc/**", "/proc/**", "/sys/**"]
      tools:
        allow: ["google-drive/*", "salesforce/*"]
        deny: ["admin/*", "system/*"]
      network:
        allow_tool_calls: true   # tools can reach their backends
        allow_raw_http: false    # no arbitrary HTTP from code

When agent code attempts to exceed memory limit:
  Then the run is terminated with OOM error
  And the violation is logged with context

When agent code attempts to access /etc/passwd:
  Then the read is denied with EACCES
  And a security event is emitted

When agent code attempts raw HTTP via fetch():
  Then the call is blocked
  And only tool-mediated external access is permitted

Technical Requirements:

  • SandboxRuntime pluggable interface: create_session(), execute(code, timeout), destroy_session(), health_check()
  • DenoRuntime default + PythonSandboxRuntime (builds on existing mcp-servers/python/python_sandbox_server/)
  • Two __toolcall__ bridge implementations: Deno FFI/message-passing for TypeScript, async IPC for Python
  • Follows StdIOEndpoint subprocess lifecycle pattern from mcpgateway/translate.py
  • New virtual server type: code_execution alongside static, dynamic, meta
  • Mount rules (include/exclude tags/servers) integrate with team scoping and RBAC
  • Dynamic server rules (#123) can feed mount decisions

Pluggable Runtime Interface (two isolation tiers):

Tier Runtimes Isolation Startup Status
Process-level Deno, gVisor, nsjail, Wasm Shared kernel <200ms Deno ships day one
VM-level Firecracker, Kata Containers Separate kernel 125-500ms Future
sandbox_policy:
  runtime: "deno"                    # Explicit runtime (default)
  # OR declare requirements, let the gateway choose:
  runtime_requirements:
    isolation_level: "process"       # "process" | "kernel" | "vm"
    language: "typescript"           # "typescript" | "python" | "any"
    max_cold_start_ms: 100
US-5: Security Admin — Data Tokenization for PII Protection

As a Security Administrator I want PII in tool results to be automatically tokenized before reaching the model So that real customer data flows between external systems but the model only sees tokens

Acceptance Criteria:

Given the data tokenization plugin is enabled:
  code_execution:
    tokenization:
      enabled: true
      types: [email, phone, ssn, credit_card, name]
      strategy: "bidirectional"  # tokens map back to real values

When agent code reads customer data:
  const contacts = await tools.crm.listContacts({ limit: 100 });

Then the model context shows:
  [{ name: "[NAME_1]", email: "[EMAIL_1]", phone: "[PHONE_1]" }, ...]

But when the code writes data to another system:
  await tools.email.send({ to: contacts[0].email, body: "Hello" });

Then the real email address is resolved at the tool layer
And the model never sees "[email protected]"
And the tokenization map is per-session and ephemeral

Technical Requirements:

  • Extend plugins_rust/pii_filter/ PIIDetectorRust with bidirectional token map
  • Intercept at __toolcall__ bridge: tokenize results going to sandbox, de-tokenize arguments going to tools
  • Deterministic tokens within session (same input = same token)
  • Token map in-memory only, destroyed on session end
  • Configurable per virtual server, per PII type
US-6: AI Agent — Save and Reuse Skills

As an AI Agent that frequently performs similar multi-tool operations I want to save reusable code functions to a skills directory So that I can invoke complex workflows with a single function call in future sessions

Acceptance Criteria:

Given the agent has written a useful multi-tool function:
When the agent saves it:
  shell_exec(code=`
    const skill = \`
      /**
       * Sync high-value accounts from spreadsheet to CRM.
       * @param sheetId - Google Sheets ID
       * @param revenueThreshold - Minimum revenue to qualify
       */
      export async function syncHighValueAccounts(
        sheetId: string,
        revenueThreshold: number = 100000
      ) {
        const sheet = await tools.googleDrive.getSheet({ sheetId });
        const qualified = sheet.rows.filter(r => r.revenue > revenueThreshold);
        const results = [];
        for (const row of qualified) {
          const result = await tools.salesforce.updateRecord({
            objectType: 'Account',
            recordId: row.accountId,
            data: { tier: 'enterprise' }
          });
          results.push(result);
        }
        return { synced: results.length, total: sheet.rows.length };
      }
    \`;
    await fs.writeFile('/skills/sync_accounts.ts', skill);
  `)
Then the skill is persisted with status "pending"
And it is NOT available for import until approved

When a team_admin approves the skill:
  POST /skills/{id}/approve
Then it appears in future sessions for the same team

When the agent later calls:
  shell_exec(code=`
    const { syncHighValueAccounts } = await import('/skills/sync_accounts.ts');
    return await syncHighValueAccounts('sheet_xyz', 50000);
  `)
Then the saved skill runs with the new parameters
And the skill's tool calls go through normal RBAC/audit

Technical Requirements:

  • /skills/ directory: scoped as global/, team:<team_id>/, user:<user_id>/
  • SKILL.md companion doc convention
  • Versioning: overwrite creates new version, rollback supported
  • RBAC-based approval following PendingUserApproval pattern:
    • skills.create — developer creates drafts
    • skills.approve — team_admin approves/rejects in their team
    • skills.read — viewer reads and uses approved skills
    • skills.revoke — team_admin or platform_admin revokes
    • SkillApproval table: status (pending/approved/rejected/expired), reviewed_by, reviewed_at, rejection_reason, admin_notes, expires_at
    • Consider allow_admin_bypass=False on approve endpoint since skills execute arbitrary tool chains
  • Admin API: POST /skills/{id}/submit, POST /skills/{id}/approve, POST /skills/{id}/reject
US-7: Platform Admin — Mount Tool Subsets per Virtual Server

As a Platform Administrator I want to control which tools are mounted into the virtual filesystem per virtual server So that different teams see different tool catalogs in their sandbox

Acceptance Criteria:

Given virtual server configuration:
  POST /servers
  {
    "name": "sales-team-sandbox",
    "type": "code_execution",
    "stub_language": "typescript",
    "mount_rules": [
      { "include_tags": ["sales", "crm"], "include_servers": ["salesforce", "hubspot"] },
      { "include_tags": ["productivity"], "include_servers": ["google-drive", "slack"] }
    ],
    "exclude_servers": ["admin-tools", "infrastructure"],
    "sandbox_policy": {
      "runtime": "deno",
      "max_execution_time_ms": 60000,
      "max_memory_mb": 512
    },
    "skills_scope": "team:sales"
  }

When the sales team's agent lists /tools/:
  Then it sees: salesforce/, hubspot/, google-drive/, slack/
  And it does NOT see: admin-tools/, infrastructure/

When an AI agent connects to this server via SSE:
  Then it sees exactly 2 tools: shell_exec, fs_browse
  And the agent does NOT see the underlying 1000+ tools

When the platform team's agent lists /tools/:
  Then it sees ALL servers (admin bypass)

And mount rules integrate with existing team scoping and RBAC
And dynamic server rules (#123) can also feed mount decisions

Technical Requirements:

  • code_execution virtual server type alongside static, dynamic, meta
  • Supports SSE, WebSocket, and Streamable HTTP transports
  • Integrates with existing POST /servers CRUD API
US-8: Observability Engineer — Monitor Code Runs

As an Observability Engineer I want detailed telemetry from sandbox code runs So that I can monitor performance, detect abuse, and debug failures

Acceptance Criteria:

Given code-execution observability is enabled:
When an agent runs code in the sandbox:
Then the following telemetry is emitted:
  - OpenTelemetry span for the entire run
  - Child spans for each tool call within the code
  - Run metrics: wall_time_ms, cpu_time_ms, peak_memory_mb
  - Tool call metrics: count, latency_p50/p95/p99, error_rate
  - Security events: permission denials, resource limit hits
  - Data flow: bytes_read, bytes_written, tools_invoked

And metrics are exported to the existing OTEL pipeline
And run logs include the code hash (not the full code, for privacy)
And a replay endpoint allows admins to re-run with debug logging

Technical Requirements:

  • OTEL spans via existing OTEL_EXPORTER_OTLP_ENDPOINT
  • Code hash (SHA-256) for correlation without storing raw code
  • Structured security events queryable through admin API
  • Dashboard data: top skills, tool call frequency, error rates, latency percentiles

Technical Design

Tool Stub Code Generation

Tool stubs are auto-generated from JSON Schema inputSchema in both TypeScript and Python. The virtual server config selects the stub language via stub_language: "typescript" | "python" (default matches the runtime: TypeScript for Deno, Python for Python runtimes). Each language requires its own __toolcall__ bridge implementation.

TypeScript stub (for Deno runtime):

// Auto-generated from tool registry. Do not edit.
// Server: google-drive | Last synced: 2025-11-04T10:00:00Z

import { type ToolResult } from "/tools/_runtime.ts";

interface GetDocumentArgs {
  /** The document's unique identifier */
  documentId: string;
  /** Output format */
  format?: "text" | "markdown" | "html";
}

interface GetDocumentResult {
  content: string;
  metadata: {
    title: string;
    lastModified: string;
    owner: string;
  };
}

/**
 * Retrieve a Google Drive document by ID.
 *
 * @tags file-management, google, documents
 * @server google-drive
 * @rateLimit 100/min
 * @example
 *   const doc = await get_document({ documentId: "abc123" });
 *   console.log(doc.content.substring(0, 100));
 */
export async function get_document(
  args: GetDocumentArgs
): Promise<ToolResult<GetDocumentResult>> {
  return __toolcall__("google-drive", "get_document", args);
}

Python stub (for Python sandbox runtime):

# Auto-generated from tool registry. Do not edit.
# Server: google-drive | Last synced: 2025-11-04T10:00:00Z

from __future__ import annotations
from typing import TypedDict, Literal
from tools._runtime import toolcall, ToolResult


class GetDocumentArgs(TypedDict, total=False):
    """Arguments for get_document."""
    document_id: str                                        # required
    format: Literal["text", "markdown", "html"]             # optional


class DocumentMeta(TypedDict):
    title: str
    last_modified: str
    owner: str


class GetDocumentResult(TypedDict):
    content: str
    metadata: DocumentMeta


async def get_document(args: GetDocumentArgs) -> ToolResult[GetDocumentResult]:
    """Retrieve a Google Drive document by ID.

    Tags: file-management, google, documents
    Server: google-drive
    Rate limit: 100/min

    Example::

        doc = await get_document({"document_id": "abc123"})
        print(doc["content"][:100])
    """
    return await toolcall("google-drive", "get_document", args)

The __toolcall__ / toolcall bridge is injected by the sandbox runtime and routes through the gateway's existing tool invocation pipeline (including plugin hooks, RBAC, rate limiting, and audit logging).

Security Architecture

+------------------------------------------------------------------+
|                        Security Layers                            |
+------------------------------------------------------------------+
|                                                                   |
|  Layer 1: Sandbox Isolation                                       |
|  +--------------------------------------------------------------+ |
|  |  - Process isolation (Deno --allow-* / gVisor / nsjail)      | |
|  |  - Filesystem namespace (only /tools, /scratch, /skills)     | |
|  |  - No raw network access                                     | |
|  |  - Resource limits (CPU, memory, wall time, disk)            | |
|  |  - Seccomp syscall filtering (when using nsjail/gVisor)      | |
|  +--------------------------------------------------------------+ |
|                                                                   |
|  Layer 2: Tool-Level Authorization                                |
|  +--------------------------------------------------------------+ |
|  |  - RBAC check on every __toolcall__ invocation               | |
|  |  - Team scoping determines which tools are mounted           | |
|  |  - Token delegation for upstream service auth                | |
|  |  - Rate limiting per tool, per session, per user             | |
|  +--------------------------------------------------------------+ |
|                                                                   |
|  Layer 3: Data Protection                                         |
|  +--------------------------------------------------------------+ |
|  |  - PII tokenization on tool results entering model context   | |
|  |  - De-tokenization on tool arguments leaving sandbox         | |
|  |  - Tokenization map is session-scoped and ephemeral          | |
|  |  - Extends existing plugins_rust PII detection engine        | |
|  +--------------------------------------------------------------+ |
|                                                                   |
|  Layer 4: Audit & Monitoring                                      |
|  +--------------------------------------------------------------+ |
|  |  - Every run logged with code hash + tool calls              | |
|  |  - Security events (denials, limit hits) as structured log   | |
|  |  - OTEL spans for run and per-tool latency                   | |
|  |  - Admin replay endpoint for post-incident analysis          | |
|  +--------------------------------------------------------------+ |
|                                                                   |
+------------------------------------------------------------------+

Threat Model Summary

Threat Mitigation
Sandbox escape Deno permission flags + optional gVisor/nsjail wrapper for defense-in-depth
Resource exhaustion CPU, memory, wall time, disk limits; cgroup enforcement
Data exfiltration via raw HTTP --deny-net; only __toolcall__ bridge permitted
Data exfiltration via tool abuse RBAC check on every tool call; rate limiting per tool/session/user
Skill poisoning RBAC approval workflow; team_admin must approve before available
Code injection (eval, Deno.run) Static analysis blocks dangerous patterns before execution
External imports Only /tools/, /skills/, /scratch/ imports permitted; external URLs blocked
Fork bombs Process limits via cgroups/nsjail prevent system impact

Virtual Server Configuration Example

# Minimal code-execution server
POST /servers
{
  "name": "dev-sandbox",
  "type": "code_execution",
  "stub_language": "typescript",
  "mount_rules": {
    "include_tags": ["dev", "staging"],
    "include_servers": ["github", "jira", "slack"]
  },
  "sandbox_policy": {
    "runtime": "deno",
    "max_execution_time_ms": 60000,
    "max_memory_mb": 512
  },
  "tokenization": {
    "enabled": true,
    "types": ["email", "phone", "ssn"]
  },
  "skills_scope": "team:engineering"
}

High-Security Configuration (Production)

POST /servers
{
  "name": "production-sandbox",
  "type": "code_execution",
  "stub_language": "python",
  "mount_rules": {
    "include_tags": ["production", "verified"],
    "exclude_servers": ["internal-only", "admin-tools"]
  },
  "sandbox_policy": {
    "runtime": "deno",
    "runtime_requirements": {
      "isolation_level": "kernel"
    },
    "max_execution_time_ms": 30000,
    "max_memory_mb": 256,
    "max_runs_per_minute": 50
  },
  "tokenization": {
    "enabled": true,
    "types": ["email", "phone", "ssn", "credit_card", "name"],
    "strategy": "bidirectional"
  },
  "skills_scope": "team:production",
  "skills_require_approval": true
}

Implementation Order

Phase 1: Foundation
  - Virtual tool filesystem schema & stub generation engine (TS + Python)
  - Sandboxed runtime with pluggable SandboxRuntime interface (Deno default)
  - __toolcall__ bridge (TypeScript + Python variants)

Phase 2: Integration
  - shell_exec + fs_browse MCP meta-tools
  - code_execution virtual server type with mount rules
  - Plugin hook integration (tool_pre_invoke, tool_post_invoke)

Phase 3: Security & Data Protection
  - Bidirectional PII tokenization (extend plugins_rust)
  - Threat model document + security hardening
  - Static analysis for dangerous code patterns
  - Rate limiting per session/user/minute

Phase 4: Features & Performance
  - Skills persistence with RBAC approval workflow
  - Rust-accelerated stub codegen + catalog builder (PyO3)
  - In-memory filesystem search (ripgrep-compatible)

Phase 5: Observability & UI
  - OTEL tracing + structured security events
  - UI: sandbox servers, skills review, active sessions, run history
  - Admin replay endpoint

Success Criteria

  • [ ] Virtual Filesystem: Tool stubs generated from JSON Schema for both TypeScript and Python
  • [ ] Catalog: _catalog.json includes tool metadata; searchable via grep/jq in <100ms for 500+ tools
  • [ ] Sandbox Runtime: Deno-based isolation with filesystem, network, and resource enforcement
  • [ ] Pluggable Interface: SandboxRuntime abstraction; new runtimes addable without changing shell_exec
  • [ ] Meta-Tools: shell_exec and fs_browse registered and functional via MCP protocol
  • [ ] Virtual Server: code_execution type exposes only meta-tools; hides underlying 1000+ tools
  • [ ] RBAC Integration: Every __toolcall__ checked against existing RBAC; team scoping determines mounts
  • [ ] PII Tokenization: Bidirectional tokenization via extended plugins_rust PII engine
  • [ ] Skills: Persistence, versioning, team scoping, RBAC approval workflow
  • [ ] Security Hardening: Threat model documented; static analysis blocks dangerous patterns
  • [ ] Observability: OTEL spans per execution and per tool call; structured security events
  • [ ] UI: Sandbox server management, skill review, session monitoring, run history
  • [ ] Performance: Stub codegen for 1000 tools in <100ms (Rust); catalog search in <10ms
  • [ ] Testing: Integration tests for sandbox isolation, RBAC enforcement, PII tokenization
  • [ ] Documentation: Configuration guide, security model, admin guide

Definition of Done

  • [ ] Filesystem schema defined (/tools/, /scratch/, /skills/, /results/)
  • [ ] TypeScript stub codegen from JSON Schema inputSchema
  • [ ] Python stub codegen from JSON Schema inputSchema
  • [ ] _catalog.json generation with entity metadata fields
  • [ ] Per-server _meta.json generation
  • [ ] Lazy stub generation with TTL cache
  • [ ] SandboxRuntime interface defined
  • [ ] DenoRuntime implemented with permission flags
  • [ ] PythonSandboxRuntime implemented (extends existing python_sandbox_server)
  • [ ] TypeScript __toolcall__ bridge (Deno FFI / message-passing)
  • [ ] Python toolcall bridge (async IPC)
  • [ ] Resource limits enforced (CPU, memory, wall time, disk)
  • [ ] Filesystem permissions enforced (read/write/deny paths)
  • [ ] Raw network access blocked
  • [ ] shell_exec MCP tool schema with code, language, timeout_ms, stream (reserved)
  • [ ] fs_browse companion MCP tool
  • [ ] code_execution virtual server type with mount rules
  • [ ] Plugin pre/post hook integration
  • [ ] SSE, WebSocket, Streamable HTTP transport support
  • [ ] Bidirectional PII tokenization at __toolcall__ bridge
  • [ ] Session-scoped ephemeral token map
  • [ ] skills.create, skills.approve, skills.read, skills.revoke permissions added
  • [ ] SkillApproval table following PendingUserApproval pattern
  • [ ] Skill approval API endpoints (submit, approve, reject)
  • [ ] Skill versioning and team scoping
  • [ ] Static analysis for dangerous code patterns (eval, Deno.run, external imports)
  • [ ] Rate limiting per session, per user, per minute
  • [ ] Threat model document
  • [ ] OTEL spans for shell_exec + child spans per tool call
  • [ ] Structured security event logging
  • [ ] Code hash logging (SHA-256)
  • [ ] Admin replay endpoint
  • [ ] Rust json_schema_to_stubs module (PyO3, dual-language output)
  • [ ] Rust catalog_builder module (incremental, metadata-aware)
  • [ ] Rust fs_search module (ripgrep-compatible, in-memory)
  • [ ] Graceful fallback to pure Python when Rust unavailable
  • [ ] UI: sandbox server CRUD
  • [ ] UI: skill review and approval
  • [ ] UI: active session monitoring
  • [ ] UI: run history and security events
  • [ ] Code passes make verify checks
  • [ ] Security review completed

Additional Notes

Bell-LaPadula / Clearance Integration: If the Security Clearance Plugin (#1245) is deployed, tool clearance levels should gate what mounts into /tools/. A user with CONFIDENTIAL clearance should not see TOP_SECRET tools in their virtual filesystem — the mount rules should intersect with clearance levels.

Streaming (Future): The shell_exec schema reserves a stream: boolean parameter (ignored in v1). When implemented, partial stdout pipes through existing SSE/Streamable HTTP transports. No schema change needed.

Federation: Federation was deprecated in ADR-008 (2026-01-07). Tools discovered from peer gateways via POST /gateways are cached locally with federation_source metadata and appear in /tools/ like any other tool. The _meta.json surfaces the federation_source field. No special namespace needed.

Performance: Rust-accelerated codegen targets <100ms for 1000 tools (vs ~2s in Python). Follows the plugins_rust/pii_filter/ PyO3 pattern using serde_json, askama templates, and regex::RegexSet.

Existing Reuse:

  • mcp-servers/rust/filesystem-server/src/sandbox.rs — path validation and sandboxed file I/O
  • plugins_rust/pii_filter/ — PII detection engine, extended for bidirectional tokenization
  • mcpgateway/translate.py StdIOEndpoint — subprocess lifecycle for sandbox process management
  • mcpgateway/db.py PendingUserApproval — approval workflow model for skill review
  • Plugin transport abstraction (PluginConfig) — pattern for pluggable runtime interface

Remaining Open Questions

  1. Composability with #2228: Should the search_tools meta-tool from the semantic discovery epic also be available inside the sandbox as an importable module at /tools/_search.ts, or is grep / jq on /tools/_catalog.json sufficient? Semantic search would be more powerful for large catalogs but adds a dependency on the embedding index.

  2. Skill TTL: Should approved skills expire after a configurable period and require re-approval, or remain approved indefinitely until explicitly revoked? Expiration follows the precedent set by PendingUserApproval.expires_at but may create unnecessary churn for stable skills.

  3. Cross-language skills: Can a TypeScript sandbox import a Python skill (or vice versa)? Simplest answer is no — skills match the sandbox language. But some teams may want mixed-language skill libraries.


Related Issues

  • #2228 — AI-Powered Conversational Gateway & Semantic Discovery Platform
  • #2230 — Virtual Meta-Server
  • #2229 — Tool Embedding Index & Semantic Search
  • #2246 — Tool Chain Templates & Workflow Automation
  • #123 — Dynamic Server Catalog via Rule, Regexp, Tags, or LLM-Based Selection
  • #1305 — AI Service Discovery and Gateway Proxy
  • #1359 — Custom Metadata Fields
  • #1245 — Security Clearance Levels Plugin (Bell-LaPadula MAC)

References

crivetimihai avatar Feb 15 '26 10:02 crivetimihai

The secure code execution layer you're describing here aligns closely with sandlock (https://github.com/multikernel/sandlock), which provides kernel-enforced sandboxing using Landlock + seccomp. No root, no containers, about 1ms startup via fork().

A few features that map to your requirements:

  • Multi-tenancy: each sandboxed process gets its own Landlock + seccomp policy, forks share memory via COW
  • Per-tool permissions: McpSandbox module gives each MCP tool call its own kernel-enforced security policy (e.g. one tool gets network, another gets filesystem only)
  • Checkpoint/restore/fork: snapshot a running sandbox and branch from it, useful for the exploratory shell workflow you described
  • Pipeline operator: chain sandboxed stages with different policies via Sandbox(policy_a).cmd(["step1"]) | Sandbox(policy_b).cmd(["step2"])

Could be useful as the enforcement backend for your sandboxed shell layer. Happy to discuss.

congwang-mk avatar Mar 28 '26 03:03 congwang-mk