feat(ai-mcp-sandbox): add runSandboxed() and sandboxedChatTool() #2220
secure-mcp-server-base-v2 fromrefs/pull/2220/head·merged by tombeckenham View on GitHubRun 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 returnsok: false. A misconfiguration or an abort throughsignalthrows. Apolicyneeds a realauthInfo: the types enforce it, and the run throws without one. With nopolicy, facades see theanonymouscaller.sandboxedChatTool(): wraps a snippet as a plainServerToolforchat({ tools }). A blocked run throws a fixed message. The raw error text stays onerror.cause, so facade internals do not reach the model.- Typed request context: facades get the
chat({ context })value asctx.context. It is required when the context type is known, through core'sRuntimeContextField(now exported from@tanstack/ai). sandboxedTool()now callsrunSandboxed(), which removes its copy of the engine.- Docs and example:
docs/tools/sandboxed-tools.md,docs/tutorials/secure-sandbox-tools.md, andexamples/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,FacadeandFacadestake an optionalTContexttype argument. The default isunknown, so existingsandboxedTool()code does not change.SandboxRunResult.valuehas the typeJsonValue | undefined.JsonValueis exported.@tanstack/aiexportsRuntimeContextField.
Testing#
Commands run. On b618cd886:
tsc --noEmitfor@tanstack/ai-mcp-sandboxandexamples/react/secure-sandbox-tools: pass.testing/e2epassed on308368b8fand is unchanged since.vitest runinpackages/ai-mcp-sandbox: 41/41 pass, including an abort test and apolicy-without-authInfotest.oxlint --type-awareinpackages/ai-mcp-sandboxandoxfmt --checkon 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.
- Run
pnpm build:all, thencd examples/react/secure-sandbox-tools && pnpm dev(port 3100). - Click the four buttons under "Sandboxed endpoint".
Run (allowed)returns metrics.Infinite loop,Reach 169.254.169.254andExceed call budgeteach showblocked. - 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.
tombeckenham approved these changes