Open History to see the last commit
1---
2title: "@tanstack/ai-octane"
3id: ai-octane
4order: 8
5description: "API reference for @tanstack/ai-octane. Octane hooks including useChat for streaming chat with full type safety."
6keywords:
7 - tanstack ai
8 - "@tanstack/ai-octane"
9 - octane
10 - useChat
11 - octane hooks
12 - api reference
13---
14
15Install `@tanstack/ai-octane`, then call `useChat` the same way you would in React. The hook modules are `.tsrx` and compile in your Octane plugin.
16
17## Installation
18
19<!-- ::start:tabs variant="package-manager" mode="install" -->
20
21octane: @tanstack/ai-octane octane
22
23<!-- ::end:tabs -->
24
25`octane` is a required peer. This package publishes uncompiled source, like Svelte packages that ship `.svelte`.
26
27## `useRegisterWebMCPTools(tools, options?)`
28
29Register executable client tools after the Octane component mounts. Octane removes them on cleanup and replaces them when `tools` or `options` change.
30
31For a complete setup and behavior guide, see [WebMCP Tools](../tools/webmcp).
32
33```tsx
34import {
35 useRegisterWebMCPTools,
36 type UseRegisterWebMCPToolsOptions,
37} from '@tanstack/ai-octane'
38import { searchProducts } from './tools'
39
40const tools = [searchProducts]
41const options: UseRegisterWebMCPToolsOptions<typeof tools> = {
42 onError(error) {
43 console.error(error)
44 },
45}
46
47function ProductsPage() {
48 useRegisterWebMCPTools(tools, options)
49 return null
50}
51```
52
53`UseRegisterWebMCPToolsOptions<TTools, TContext>` contains `toolOptions`, `context`, and `onError`. The hook owns the registration signal.
54
55The `context` field is required when a tool declares a required runtime context. Keep `tools` and `options` stable when their values do not change.
56
57## `usePageWebMCPTools(options?)`
58
59Read the WebMCP tools on the page as client tools. The array starts empty and updates when the page adds or removes a tool. Pass it to `useChat` as `tools`.
60
61```tsx
62import { usePageWebMCPTools } from "@tanstack/ai-octane"
63
64export function useSameOriginPageTools() {
65 return usePageWebMCPTools({
66 filter: (tool) => tool.origin === location.origin,
67 })
68}
69```
70
71`filter` skips a tool when it returns `false`. `onError` gets a failed WebMCP read. For a complete guide, see [Page WebMCP Tools in Chat](../tools/webmcp-page-tools).
72
73## `useChat(options)`
74
75Manages chat state in an Octane component.
76
77```tsx
78import { useState } from 'octane'
79import { useChat, fetchServerSentEvents } from '@tanstack/ai-octane'
80import {
81 createChatClientOptions,
82 type InferChatMessages,
83} from '@tanstack/ai-client'
84import { toolDefinition } from '@tanstack/ai'
85import { z } from 'zod'
86
87const updateUIDef = toolDefinition({
88 name: 'updateUI',
89 description: 'Show a notification in the UI',
90 inputSchema: z.object({ message: z.string() }),
91})
92
93export function ChatComponent() {
94 const [notification, setNotification] = useState<string | null>(null)
95 const updateUI = updateUIDef.client((input) => {
96 setNotification(input.message)
97 return { success: true }
98 })
99 const tools = [updateUI]
100
101 const chatOptions = createChatClientOptions({
102 connection: fetchServerSentEvents('/api/chat'),
103 tools,
104 })
105
106 type ChatMessages = InferChatMessages<typeof chatOptions>
107
108 const { messages, sendMessage, isLoading, error, addToolApprovalResponse } =
109 useChat(chatOptions)
110
111 return (
112 <div>
113 {notification}
114 {isLoading ? 'Loading' : null}
115 {error ? error.message : null}
116 <button onClick={() => void sendMessage('hi')} type="button">
117 Send
118 </button>
119 <button
120 onClick={() =>
121 void addToolApprovalResponse({ id: 'approval-1', approved: true })
122 }
123 type="button"
124 >
125 Approve
126 </button>
127 {messages.length}
128 </div>
129 )
130}
131```
132
133The matching server route still runs `chat({ adapter, messages })` and returns SSE. See [Quick Start](../getting-started/quick-start).
134
135### Options you pass first
136
137Extends `ChatClientOptions` from `@tanstack/ai-client`. Pass `connection` or `fetcher`, not both.
138
139- `connection` or `fetcher` - how the hook talks to your server
140- `tools?` - client tool implementations from `.client()`
141- `threadId?` - the only identity for this chat. Required when persistence is on
142- `initialMessages?` - starting transcript
143- `forwardedProps?` - JSON sent to the server on the AG-UI `forwardedProps` field
144
145### Options you add later
146
147- `live?` - subscribe on mount, unsubscribe on unmount
148- `queue?` - what to do when `sendMessage` runs while a turn is in flight. Default queues
149- `interrupts?` - typed interrupt definitions
150- `context?` - client-only runtime context for client tools. Not sent to the server
151- `onResponse?` / `onChunk?` / `onFinish?` / `onError?` / `onInterruptStateChange?`
152- `devtools?` - display options. The hook always tags `framework: 'octane'`
153- `body?` - deprecated. Use `forwardedProps`
154
155Client tools run automatically. There is no `onToolCall` callback.
156
157Changing `connection` or `fetcher` updates the live `ChatClient`. Changing `threadId` creates a new client.
158
159### Returns
160
161```typescript
162import type { UIMessage } from '@tanstack/ai-octane'
163import type { ModelMessage } from '@tanstack/ai/client'
164import type {
165 MultimodalContent,
166 ChatClientState,
167 ConnectionStatus,
168 QueuedMessage,
169 SendMessageOptions,
170} from '@tanstack/ai-client'
171
172interface UseChatReturn {
173 messages: Array<UIMessage>
174 sendMessage: (
175 content: string | MultimodalContent,
176 options?: SendMessageOptions,
177 ) => Promise<void>
178 append: (message: ModelMessage | UIMessage) => Promise<void>
179 addToolResult: (result: {
180 toolCallId: string
181 tool: string
182 output: unknown
183 state?: 'output-available' | 'output-error'
184 errorText?: string
185 }) => Promise<void>
186 addToolApprovalResponse: (response: {
187 id: string
188 approved: boolean
189 }) => Promise<void>
190 reload: () => Promise<void>
191 stop: () => void
192 isLoading: boolean
193 error: Error | undefined
194 status: ChatClientState
195 isSubscribed: boolean
196 connectionStatus: ConnectionStatus
197 sessionGenerating: boolean
198 setMessages: (messages: Array<UIMessage>) => void
199 clear: () => void
200 queue: Array<QueuedMessage>
201 cancelQueued: (id: string) => void
202 runId: string | null
203}
204```
205
206`queue` holds sends that wait while a run is busy. `runId` is the in-flight turn, or `null`. Interrupt helpers (`interrupts`, `resolveInterrupts`, `cancelInterrupts`, `retryInterrupts`) are on the same object when you pass `interrupts`.
207
208## Connection adapters
209
210Re-exported from `@tanstack/ai-client`:
211
212```typescript
213import {
214 fetchServerSentEvents,
215 fetchHttpStream,
216 stream,
217 type ConnectionAdapter,
218} from '@tanstack/ai-octane'
219```
220
221## Example: basic chat
222
223```tsx
224import { useState } from 'octane'
225import { useChat, fetchServerSentEvents } from '@tanstack/ai-octane'
226
227export function Chat() {
228 const [input, setInput] = useState('')
229 const { messages, sendMessage, isLoading } = useChat({
230 connection: fetchServerSentEvents('/api/chat'),
231 })
232
233 return (
234 <div>
235 {messages.map((message) => (
236 <div key={message.id}>
237 <strong>{message.role}:</strong>
238 {message.parts
239 .filter((part) => part.type === 'text')
240 .map((part) => part.content)
241 .join('')}
242 </div>
243 ))}
244 <input
245 value={input}
246 disabled={isLoading}
247 onInput={(event) => setInput(event.currentTarget.value)}
248 />
249 <button
250 disabled={isLoading}
251 onClick={() => {
252 void sendMessage(input)
253 setInput('')
254 }}
255 type="button"
256 >
257 Send
258 </button>
259 </div>
260 )
261}
262```
263
264## Example: tool approval
265
266```tsx
267import { useChat, fetchServerSentEvents } from '@tanstack/ai-octane'
268
269export function ChatWithApproval() {
270 const { messages, sendMessage, addToolApprovalResponse } = useChat({
271 connection: fetchServerSentEvents('/api/chat'),
272 })
273
274 return (
275 <div>
276 <button onClick={() => void sendMessage('run the tool')} type="button">
277 Send
278 </button>
279 {messages.map((message) =>
280 message.parts.map((part) => {
281 if (
282 part.type !== 'tool-call' ||
283 part.state !== 'approval-requested' ||
284 !part.approval
285 ) {
286 return null
287 }
288 const approvalId = part.approval.id
289 return (
290 <div key={part.id}>
291 <p>Approve: {part.name}</p>
292 <button
293 onClick={() =>
294 void addToolApprovalResponse({
295 id: approvalId,
296 approved: true,
297 })
298 }
299 type="button"
300 >
301 Approve
302 </button>
303 <button
304 onClick={() =>
305 void addToolApprovalResponse({
306 id: approvalId,
307 approved: false,
308 })
309 }
310 type="button"
311 >
312 Deny
313 </button>
314 </div>
315 )
316 }),
317 )}
318 </div>
319 )
320}
321```
322
323## Other hooks
324
325The package also exports `useRealtimeChat`, `useMcpAppBridge`, `useGeneration`, `useGenerateImage`, `useGenerateAudio`, `useGenerateSpeech`, `useGenerateVideo`, `useTranscription`, `useSummarize`, and `useAudioRecorder`.
326
327The `./mcp-apps` React `AppRenderer` subpath is not in this package. `useMcpAppBridge` is.
328
329## Types
330
331Re-exported from `@tanstack/ai-client`:
332
333- `UIMessage<TTools>`
334- `ChatClientOptions<TTools, TContext>`
335- `InferChatMessages<T>`
336- `QueuedMessage`, `SendMessageOptions`, `WhenBusy`
337
338## Next
339
340- [Quick Start](../getting-started/quick-start)
341- [Tools](../tools/tools)
342- [Client tools](../tools/client-tools)