Skip to content
Source
Sign inSign up
TanStack/ai

feat(ai-mcp-sandbox): add runSandboxed() and sandboxedChatTool() #2220

Mergedjherrmerged 4 commits intosecure-mcp-server-base-v2 fromrefs/pull/2220/headmerged by tombeckenham View on GitHub

jherrcommented

Run an untrusted or AI-written tool body in an isolate. The body can reach only the host functions you inject, under hard limits. sandboxedChatTool() builds a chat() tool whose body can call only its facades. runSandboxed() does the same for a server function or an endpoint. Both are the unscoped siblings of the MCP-only sandboxedTool(), and all three use one isolate engine.

Stacked on #2171 (base secure-mcp-server-base-v2), which adds the @tanstack/ai-mcp-sandbox package.

🎯 Changes

  • runSandboxed(): runs a snippet in an isolate with injected facades and limits (wall-clock, memory, host-call budget, result size). It returns { ok, value | kind + error, injectedCalls, ms }. A failed snippet or a tripped limit returns ok: false. A misconfiguration or an abort through signal throws. A policy needs a real authInfo: the types enforce it, and the run throws without one. With no policy, facades see the anonymous caller.
  • sandboxedChatTool(): wraps a snippet as a plain ServerTool for chat({ tools }). A blocked run throws a fixed message. The raw error text stays on error.cause, so facade internals do not reach the model.
  • Typed request context: facades get the chat({ context }) value as ctx.context. It is required when the context type is known, through core's RuntimeContextField (now exported from @tanstack/ai).
  • sandboxedTool() now calls runSandboxed(), which removes its copy of the engine.
  • Docs and example: docs/tools/sandboxed-tools.md, docs/tutorials/secure-sandbox-tools.md, and examples/react/secure-sandbox-tools.

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested code changes locally with pnpm run test:pr, or these tests do not apply to this pull request.
  • I fully understand the code in this pull request, including any code generated with AI assistance.
  • Docs: I updated docs/ for this change, or this change is not user-facing.
  • Changeset: I added a changeset (pnpm changeset), or this PR does not change a published package.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Public API change

New exports on @tanstack/ai-mcp-sandbox. Before this PR, a chat() tool had no way to run a sandboxed body. After it:

import { chat } from '@tanstack/ai'
import { sandboxedChatTool } from '@tanstack/ai-mcp-sandbox'
import type { FacadeContext } from '@tanstack/ai-mcp-sandbox'
import { createQuickJSIsolateDriver } from '@tanstack/ai-isolate-quickjs'

const listOrders = sandboxedChatTool({
  name: 'listOrders',
  description: "List the current user's orders.",
  inputSchema: z.object({}),
  snippet: `return await host.orders.list({})`,
  facades: {
    'orders.list': {
      // ctx.context is required here, because AppContext is known.
      execute: async (_args, ctx: FacadeContext<AppContext>) =>
        db.orders.findMany({ where: { userId: ctx.context.userId } }),
    },
  },
  driver: createQuickJSIsolateDriver(),
  limits: { wallClockMs: 2000, memoryMb: 64, maxInjectedCalls: 5, resultBytes: 16_384 },
})

chat({ adapter, messages, tools: [listOrders], context: { userId } })

Other changes:

  • FacadeContext, Facade and Facades take an optional TContext type argument. The default is unknown, so existing sandboxedTool() code does not change.
  • SandboxRunResult.value has the type JsonValue | undefined. JsonValue is exported.
  • @tanstack/ai exports RuntimeContextField.

Testing

Commands run. On b618cd886:

  • tsc --noEmit for @tanstack/ai-mcp-sandbox and examples/react/secure-sandbox-tools: pass. testing/e2e passed on 308368b8f and is unchanged since.
  • vitest run in packages/ai-mcp-sandbox: 41/41 pass, including an abort test and a policy-without-authInfo test.
  • oxlint --type-aware in packages/ai-mcp-sandbox and oxfmt --check on the package and the example: clean.
  • kiira check docs/tools/sandboxed-tools.md: 3/3 snippets pass.

I did not run the full pnpm test:pr or the E2E suite locally. CI runs both, including the new sandboxed-chat-tool.spec.ts.

Manual test.

  1. Run pnpm build:all, then cd examples/react/secure-sandbox-tools && pnpm dev (port 3100).
  2. Click the four buttons under "Sandboxed endpoint". Run (allowed) returns metrics. Infinite loop, Reach 169.254.169.254 and Exceed call budget each show blocked.
  3. Or call the API route directly:
curl -X POST http://localhost:3100/api/sandbox-demo \
  -H 'content-type: application/json' -d '{"scenario":"loop"}'
# → {"ok":false,"kind":"limit","error":"Code execution timed out",...}

How this PR makes testing easy. Unit tests in packages/ai-mcp-sandbox/tests/run.test.ts cover the engine and the chat tool. The E2E spec runs three sandboxed tools through chat(). The example app shows both surfaces, and the API route takes one curl.

Risk / rollback

Low. The exports are new, and sandboxedTool() keeps its behavior and still writes one audit record for each call. To undo, revert this PR. It targets the open secure-mcp-server-base-v2 branch, so it lands only when that branch does.

    1. Pushedfa5fb44

    2. Pushed308368b

    3. tombeckenham approved these changes

    4. tombeckenham approved these changes

    5. tombeckenham merged thisde3cf8e

    6. tombeckenham closed this

Sign in to join this conversation.