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

runtime-context.md

366 lines10.3 KB

1---
2title: Runtime Context
3id: runtime-context
4order: 2
5description: "Give your tools and middleware typed runtime values, such as the current user or a database client. The values never go to the model or into the AG-UI context."
6keywords:
7 - tanstack ai
8 - runtime context
9 - typed context
10 - tools context
11 - middleware context
12 - ag-ui context
13---
14​
15`runtimeContext` passes a user id, tenant, or database client into a tool. Those values stay out of the prompt.
16​
17Pass them as runtime context. Your tools and middleware read them from `ctx.context`, with full types. The model never sees them.
18​
19## Quick setup
20​
21### 1. Declare the context that the tool needs
22​
23Put the context type on `.server<TContext>()`. The tool reads the values from `ctx.context`:
24​
25```typescript
26// lib/ai/tools.ts
27import { toolDefinition } from '@tanstack/ai'
28import { z } from 'zod'
29​
30export type AppContext = {
31 userId: string
33​
34const notesByUser = new Map([['user_123', [{ title: 'Groceries' }]]])
35​
36export const listNotes = toolDefinition({
37 name: 'list_notes',
38 description: 'List notes for the current user',
39 inputSchema: z.object({}),
40 outputSchema: z.array(z.object({ title: z.string() })),
41}).server<AppContext>(async (_input, ctx) => {
42 return notesByUser.get(ctx.context.userId) ?? []
43})
44```
45​
46### 2. Pass the context to `chat()`
47​
48```typescript
49// api/chat.ts
50import {
51 chat,
52 chatParamsFromRequest,
53 toServerSentEventsResponse,
54} from '@tanstack/ai'
55import { openaiText } from '@tanstack/ai-openai'
56import { listNotes } from '../lib/ai/tools'
57​
58export async function POST(request: Request) {
59 const { messages, threadId, runId } = await chatParamsFromRequest(request)
60​
61 // Replace this line with your auth check.
62 const userId = request.headers.get('x-user-id') ?? 'user_123'
63​
64 const stream = chat({
65 adapter: openaiText('gpt-6.1-sol'),
66 messages,
67 threadId,
68 runId,
69 tools: [listNotes],
70 context: { userId },
71 })
72​
73 return toServerSentEventsResponse(stream)
75```
76​
77Ask "What are my notes?". The tool answers with the notes of the current user. If you remove `context`, TypeScript reports an error, because `listNotes` needs `userId`.
78​
79## How it works
80​
81The tools and middleware are the contract. The `context` value is what you supply at runtime.
82​
83- Each tool or middleware declares the context shape that it needs.
84- `chat()` merges these needs and checks your `context` value against the result.
85- The value goes only to your tools and middleware. It is not sent to the model.
86- It is also not the AG-UI `RunAgentInput.context` field. See [AG-UI context](#ag-ui-context).
87​
88Declare the type in one of these places:
89​
90- `toolDefinition(...).server<TContext>(...)` for server tools.
91- `toolDefinition(...).client<TContext>(...)` for client tools.
92- `ChatMiddleware<TContext>` for middleware.
93​
94## Server Runtime Context
95​
96Middleware reads the same context. Give it the type with `ChatMiddleware<TContext>`:
97​
98```typescript
99import {
100 chat,
101 chatParamsFromRequest,
102 toServerSentEventsResponse,
103} from '@tanstack/ai'
104import type { ChatMiddleware } from '@tanstack/ai'
105import { openaiText } from '@tanstack/ai-openai'
106​
107type AppContext = {
108 userId: string
109 tenantId: string
111​
112const auditMiddleware: ChatMiddleware<AppContext> = {
113 name: 'audit',
114 onStart(ctx) {
115 console.log('chat started', {
116 requestId: ctx.requestId,
117 userId: ctx.context.userId,
118 tenantId: ctx.context.tenantId,
119 })
120 },
122​
123export async function POST(request: Request) {
124 const { messages, threadId } = await chatParamsFromRequest(request)
125​
126 const stream = chat({
127 adapter: openaiText('gpt-6.1-sol'),
128 messages,
129 threadId,
130 middleware: [auditMiddleware],
131 context: {
132 userId: 'user_123',
133 tenantId: 'tenant_456',
134 },
135 })
136​
137 return toServerSentEventsResponse(stream)
139```
140​
141You can put any value in the context, for example a database client or an audit logger.
142​
143## Client Runtime Context
144​
145Client tools can have runtime context too. Pass it to `useChat`. It stays in the browser and is not sent to the server.
146​
147```tsx
148import { toolDefinition } from '@tanstack/ai'
149import { createChatClientOptions } from '@tanstack/ai-client'
150import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
151​
152type ClientContext = {
153 currentTabId: string
154 toast(message: string): void
156​
157const notifyUser = toolDefinition({
158 name: 'notify_user',
159 description: 'Show a notification in the current browser tab',
160}).client<ClientContext>((_input, ctx) => {
161 ctx.context.toast(`Updated tab ${ctx.context.currentTabId}`)
162 return { ok: true }
163})
164​
165const chatOptions = createChatClientOptions({
166 connection: fetchServerSentEvents('/api/chat'),
167 threadId: 'support-chat',
168 tools: [notifyUser],
169 context: {
170 currentTabId: 'settings',
171 toast: (message) => window.alert(message),
172 },
173})
174​
175export function Chat() {
176 const { sendMessage } = useChat(chatOptions)
177 return <button onClick={() => sendMessage('Update my tab')}>Send</button>
179```
180​
181Use client context for local values only. The server does not receive them.
182​
183## Client-to-Server Handoff
184​
185To send a value from the client to the server, use `forwardedProps`. On the server, validate it, then copy it into the server context.
186​
187On the client, put the value in `forwardedProps`. Unlike `context`, it goes to the server:
188​
189```tsx
190import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
191​
192export function Chat() {
193 const { sendMessage } = useChat({
194 connection: fetchServerSentEvents('/api/chat'),
195 threadId: 'support-chat',
196 forwardedProps: {
197 tenantId: 'tenant_456',
198 },
199 })
200​
201 return <button onClick={() => sendMessage('Hello')}>Send</button>
203```
204​
205On the server, read `forwardedProps` and build the context:
206​
207```typescript
208import {
209 chat,
210 chatParamsFromRequest,
211 toServerSentEventsResponse,
212} from '@tanstack/ai'
213import { openaiText } from '@tanstack/ai-openai'
214​
215type AppContext = {
216 userId: string
217 tenantId: string
219​
220export async function POST(request: Request) {
221 const params = await chatParamsFromRequest(request)
222​
223 // Replace these lines with your auth check and your allowlist of tenants.
224 const userId = 'user_123'
225 const defaultTenantId = 'tenant_default'
226​
227 const tenantId =
228 typeof params.forwardedProps.tenantId === 'string'
229 ? params.forwardedProps.tenantId
230 : defaultTenantId
231​
232 const context: AppContext = { userId, tenantId }
233​
234 const stream = chat({
235 adapter: openaiText('gpt-6.1-sol'),
236 messages: params.messages,
237 threadId: params.threadId,
238 context,
239 })
240​
241 return toServerSentEventsResponse(stream)
243```
244​
245> [!WARNING]
246> The client controls `forwardedProps`. Validate and allowlist every field before you put it in the server context.
247​
248## Advanced
249​
250### How the type checks work
251​
252The tools and middleware decide what the context must contain. The `context` object alone does not decide this. In this call, the tool needs `UserContext` and the middleware needs `TenantContext`, so `context` must have both:
253​
254```typescript
255import { chat, toolDefinition } from '@tanstack/ai'
256import type { ChatMiddleware } from '@tanstack/ai'
257import { openaiText } from '@tanstack/ai-openai'
258​
259type UserContext = { userId: string }
260type TenantContext = { tenantId: string }
261​
262const currentUserTool = toolDefinition({
263 name: 'current_user',
264 description: 'Read the current user',
265}).server<UserContext>((_input, ctx) => {
266 return { userId: ctx.context.userId }
267})
268​
269const tenantMiddleware: ChatMiddleware<TenantContext> = {
270 name: 'tenant',
271 onStart(ctx) {
272 console.log(ctx.context.tenantId)
273 },
275​
276const stream = chat({
277 adapter: openaiText('gpt-6.1-sol'),
278 messages: [{ role: 'user', content: 'Who am I?' }],
279 threadId: 'thread-1',
280 tools: [currentUserTool],
281 middleware: [tenantMiddleware],
282 context: {
283 userId: 'user_123',
284 tenantId: 'tenant_456',
285 },
286})
287```
288​
289If you remove `tenantId`, TypeScript reports an error, because `tenantMiddleware` needs it.
290​
291More rules:
292​
293- Untyped tools and middleware still work. They get `unknown` context and do not make `context` required.
294- The inference also works for tools and middleware that you declare outside the `chat()` call and pass in as arrays.
295- To make the context optional, declare `TContext | undefined`. When all typed consumers accept `undefined`, you can leave out `context`.
296- If you pass a `context` value, it must satisfy every typed consumer.
297​
298### The same rules on the client
299​
300`useChat()` checks `context` against the client tools. This tool declares `ClientRuntimeContext & { mode: 'debug' }`, so `context` needs `currentTabId` and the literal `mode: 'debug'`:
301​
302```tsx
303import { toolDefinition } from '@tanstack/ai'
304import { fetchServerSentEvents, useChat } from '@tanstack/ai-react'
305​
306type ClientRuntimeContext = {
307 currentTabId: string
309​
310const inspectClientContext = toolDefinition({
311 name: 'inspect_client_context',
312 description: 'Inspect local browser context',
313}).client<ClientRuntimeContext & { mode: 'debug' }>((_input, ctx) => {
314 return {
315 tabId: ctx.context.currentTabId,
316 mode: ctx.context.mode,
317 }
318})
319​
320export function DebugChat() {
321 const { sendMessage } = useChat({
322 connection: fetchServerSentEvents('/api/chat'),
323 threadId: 'support-chat',
324 tools: [inspectClientContext],
325 context: {
326 currentTabId: 'settings',
327 mode: 'debug',
328 },
329 })
330​
331 return <button onClick={() => sendMessage('Inspect')}>Send</button>
333```
334​
335### AG-UI Context
336​
337AG-UI defines its own `RunAgentInput.context` field. It holds context entries for agents at the protocol level. `chatParamsFromRequest` gives you this field as `params.aguiContext`. It is separate from `chat({ context })`.
338​
339TanStack AI does not copy `params.aguiContext` into the runtime context. To use these values, validate them and map them yourself:
340​
341```typescript ignore
342import {
343 chat,
344 chatParamsFromRequest,
345 toServerSentEventsResponse,
346} from '@tanstack/ai'
347import { openaiText } from '@tanstack/ai-openai'
348import { buildRuntimeContextFrom } from './context'
349import { serverTools } from './tools'
350​
351export async function POST(request: Request) {
352 const params = await chatParamsFromRequest(request)
353​
354 const stream = chat({
355 adapter: openaiText('gpt-6.1-sol'),
356 messages: params.messages,
357 threadId: params.threadId,
358 tools: serverTools,
359 context: buildRuntimeContextFrom(params.aguiContext),
360 })
361​
362 return toServerSentEventsResponse(stream)
364```
365​
366`buildRuntimeContextFrom` is your own function. It reads the entries you trust and returns your context object.