Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

tools.md

191 lines8.1 KB

1---
2title: Tools
3id: tools
4order: 6
5description: "Give the in-sandbox agent your app's own server tools. They run on your host, with their database, secrets, and closures, over an authenticated MCP tool proxy."
6---
7​
8A host tool runs in your app, with your database and secrets. The agent in the sandbox calls it. The tool code does not run in the sandbox.
9​
10Pass your server tools to `chat()`. TanStack AI bridges them into the sandbox. The agent calls them like any MCP tool, and each tool runs on your host.
11​
12## Bridge a tool into the sandbox
13​
141. Define a server tool, the same as for any `chat()` call.
152. Pass it in `tools`, next to `withSandbox`.
16​
17```ts
18import { chat, toolDefinition } from '@tanstack/ai'
19import { GROK_CLI_INSTALL_COMMAND, grokBuildText } from '@tanstack/ai-grok-build'
20import {
21 createSecrets,
22 defineSandbox,
23 defineWorkspace,
24 githubRepo,
25 withSandbox,
26} from '@tanstack/ai-sandbox'
27import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
28import { z } from 'zod'
29​
30// Lives on your host. The sandbox never sees it.
31const todos = [{ id: '1', userId: 'u1', title: 'Fix the login bug' }]
32​
33const getTodos = toolDefinition({
34 name: 'getTodos',
35 description: 'List the todos of a user.',
36 inputSchema: z.object({ userId: z.string() }),
37}).server(async ({ userId }) => todos.filter((t) => t.userId === userId))
38​
39const repoSandbox = defineSandbox({
40 id: 'repo-agent',
41 provider: dockerSandbox({ image: 'node:22' }),
42 workspace: defineWorkspace({
43 source: githubRepo({ repo: 'owner/app' }),
44 setup: [GROK_CLI_INSTALL_COMMAND],
45 secrets: createSecrets({ XAI_API_KEY: process.env.XAI_API_KEY ?? '' }),
46 }),
47})
48​
49const stream = chat({
50 threadId: 'thread-1',
51 adapter: grokBuildText('grok-build'),
52 messages: [{ role: 'user', content: 'Fix the bugs in the todos of user u1.' }],
53 tools: [getTodos],
54 middleware: [withSandbox(repoSandbox)],
55})
56```
57​
58The agent can now call `getTodos`. The tool reads `todos` on your host and sends the result into the sandbox.
59​
60## Use the sandbox from a tool
61​
62A server tool can read and write the sandbox of its run. Call `context.get(SandboxCapability)`. It returns the `SandboxHandle` that `withSandbox` opened for this run.
63​
64```ts
65import { chat, toolDefinition } from '@tanstack/ai'
66import { grokBuildText } from '@tanstack/ai-grok-build'
67import { SandboxCapability, withSandbox } from '@tanstack/ai-sandbox'
68import type { SandboxDefinition } from '@tanstack/ai-sandbox'
69import { z } from 'zod'
70​
71// The definition from the step above.
72declare const repoSandbox: SandboxDefinition
73​
74const readPackageName = toolDefinition({
75 name: 'readPackageName',
76 description: 'Return the name in package.json of the repo.',
77 inputSchema: z.object({}),
78}).server(async (_input, context) => {
79 const sandbox = context?.get?.(SandboxCapability)
80 if (!sandbox) return 'No sandbox in this run.'
81 const pkg: unknown = JSON.parse(
82 await sandbox.fs.read('/workspace/package.json'),
83 )
84 return typeof pkg === 'object' && pkg !== null && 'name' in pkg
85 ? String(pkg.name)
86 : 'unknown'
87})
88​
89const stream = chat({
90 threadId: 'thread-1',
91 adapter: grokBuildText('grok-build'),
92 messages: [{ role: 'user', content: 'What is this package called?' }],
93 tools: [readPackageName],
94 middleware: [withSandbox(repoSandbox)],
95})
96```
97​
98- `get` throws if the run has no `withSandbox`.
99- `context.getOptional(SandboxCapability)` returns `undefined` instead.
100- The tool still runs on your host. Only the sandbox calls (`fs.read` here) go to the sandbox.
101​
102For other capabilities, see [Read a middleware capability](../tools/server-tools-advanced#read-a-middleware-capability).
103​
104## How it works
105​
106The agent always has its own native tools (Bash, file edits, search). They run on the sandbox filesystem. Your `chat()` tools go over a host-side MCP tool proxy:
107​
1081. The agent calls the tool by name, like any MCP tool.
1092. The call crosses the sandbox boundary to your host.
1103. The tool's `execute()` runs on your host, with its database handle, secrets, and closures.
1114. The result goes back into the sandbox as the tool output.
112​
113`execute()` never goes into the sandbox. Only the call and the result cross the boundary.
114​
115A random bearer token for each run protects the bridge. Only the agent of this run has that token, so only it can call your tools.
116​
117> [!NOTE]
118> This page is about your own tools, bridged back to your server. To give the agent third-party MCP servers that it calls directly, declare them on the workspace. See [Provisioning](./provisioning). For server tools in general, see [Server Tools](../tools/server-tools).
119​
120## Make sure the sandbox can reach the bridge
121​
122The bridge is an HTTP endpoint that the sandbox calls back to. So the sandbox must be able to connect to your server.
123​
124| Where it runs | Host the sandbox calls | Setup |
125| --- | --- | --- |
126| Local process | `localhost` | None. |
127| Docker container (`dockerSandbox`) | `host.docker.internal` | None. |
128| Docker Sandboxes (`sbxSandbox`) | `host.docker.internal` | A deny or ask allowlist must include `localhost`. `sbxSandbox()` adds it when it writes a real allowlist. |
129| Deployed server (production) | A URL your provisioner advertises | Provide a bridge provisioner. |
130| Cloud sandbox, driven from your laptop | Your laptop, which has no public URL | Tunnel the bridge with `withNgrokBridge`. |
131​
132### Local process and Docker container
133​
134The sandbox runs on the same machine as your server. It reaches it on `localhost` (local process) or `host.docker.internal` (Docker container). Bridged tools need no extra setup. If the HTTP listener cannot start, bridge startup rejects with the original Node.js error.
135​
136### Docker Sandboxes (`sbxSandbox`)
137​
138The guest still calls `host.docker.internal`. The host HTTP proxy changes that host to `localhost` before it checks `sbx policy`. If you write a deny or ask allowlist, allow `localhost` (or let `sbxSandbox()` add it). `denyNetwork` alone does not write that allowlist.
139​
140### A deployed server (production)
141​
142The default provisioner (`nodeHttpBridgeProvisioner`) binds loopback and tells the sandbox to call `127.0.0.1` (`host.docker.internal` for Docker). It does not read your public host from the request. So a remote sandbox cannot reach it, even from a deployed server.
143​
144Provide your own `ToolBridgeProvisioner` from a chat middleware with `provideToolBridgeProvisioner(ctx, provisioner)`. Its `provision()` returns the bridge with a `url` the sandbox can reach, for example your server's public URL. `withNgrokBridge` from `@tanstack/ai-sandbox/ngrok` is a working example. Every call still needs the bearer token for the run, so a public endpoint is safe.
145​
146The Cloudflare package ships its own provisioner, so the edge setup needs no extra step. See [Cloudflare](./cloudflare).
147​
148### A cloud sandbox, driven from your laptop
149​
150A cloud provider (Daytona, Vercel, Sprites, and the others) runs a remote VM. In local dev, that VM cannot call your `localhost`, and your laptop has no public URL.
151​
152The `@tanstack/ai-sandbox/ngrok` subpath tunnels the bridge through [ngrok](https://ngrok.com):
153​
1541. Install the optional peer dependency `@ngrok/ngrok`:
155​
156<!-- ::start:tabs variant="package-manager" mode="install" -->
157​
158react: @ngrok/ngrok
159vue: @ngrok/ngrok
160solid: @ngrok/ngrok
161svelte: @ngrok/ngrok
162preact: @ngrok/ngrok
163angular: @ngrok/ngrok
164vanilla: @ngrok/ngrok
165octane: @ngrok/ngrok
166​
167<!-- ::end:tabs -->
168​
1692. Set `NGROK_AUTHTOKEN`.
1703. Add `withNgrokBridge` **after** `withSandbox(...)`:
171​
172```ts
173import { chat } from '@tanstack/ai'
174import { grokBuildText } from '@tanstack/ai-grok-build'
175import { withSandbox } from '@tanstack/ai-sandbox'
176import { withNgrokBridge } from '@tanstack/ai-sandbox/ngrok'
177import { repoSandbox } from './sandbox'
178import { getTodos } from './tools'
179​
180chat({
181 threadId: 'thread-1',
182 adapter: grokBuildText('grok-build'),
183 messages: [{ role: 'user', content: 'Fix the bugs in the todos of user u1.' }],
184 tools: [getTodos],
185 // Cloud provider in local dev: tunnel the bridge so the remote sandbox can
186 // reach it. Local process and Docker do not need this.
187 middleware: [withSandbox(repoSandbox), withNgrokBridge],
188})
189```
190​
191`withNgrokBridge` is for local dev only. In production your deployed server is already reachable, so you ship without it.