Open History to see the last commit
1---
2title: Event metadata
3id: protocol-event-metadata
4order: 1
5description: "Which fields a custom AG-UI server puts in metadata.tanstack, so that TanStack useChat gets the finish reason, the model, and extra usage."
6keywords:
7 - tanstack ai
8 - ag-ui protocol
9 - metadata.tanstack
10 - finishReason
11 - custom server
12 - SSE
13---
14
15TanStack AI puts the finish reason and the model id in AG-UI metadata. `useChat` reads those fields from there.
16
17Put these extras in `metadata.tanstack` on the event. The spec fields stay at the top level.
18
19> [!NOTE]
20> A TanStack `chat()` server already writes `metadata.tanstack`. If your server sends AG-UI events itself, use this page.
21
22## Quick setup
23
24### 1. Send a complete `RUN_FINISHED` event
25
26Copy this event. Change the ids, the counts, and the model:
27
28```json
29{
30 "type": "RUN_FINISHED",
31 "threadId": "thread-1",
32 "runId": "run-1",
33 "usage": [
34 {
35 "inputTokens": 12,
36 "outputTokens": 34,
37 "totalTokens": 46
38 }
39 ],
40 "metadata": {
41 "tanstack": {
42 "finishReason": "stop",
43 "model": "gpt-6.1-sol"
44 }
45 }
46}
47```
48
49### 2. Read the fields on the client
50
51Check `chunk.type`, then read `chunk.metadata?.tanstack`. You do not need a helper:
52
53```tsx
54import { useChat, fetchServerSentEvents } from "@tanstack/ai-react";
55
56export function Chat() {
57 const { messages } = useChat({
58 connection: fetchServerSentEvents("/api/chat"),
59 threadId: "support-chat",
60 onChunk: (chunk) => {
61 if (chunk.type === "RUN_FINISHED") {
62 console.log(chunk.usage);
63 console.log(chunk.metadata?.tanstack?.finishReason);
64 console.log(chunk.metadata?.tanstack?.model);
65 }
66 },
67 });
68
69 return <pre>{JSON.stringify(messages, null, 2)}</pre>;
70}
71```
72
73Send a message. The console now shows the token usage, `"stop"`, and the model id.
74
75## How it works
76
77The client copies `metadata.tanstack` from the wire event onto the chunk. Spec fields such as `usage` stay where the spec puts them.
78
79Send these fields on every successful run:
80
81| Field | Where | Why the client needs it |
82| --- | --- | --- |
83| `type`, `threadId`, `runId` | Spec top level | They frame the run. Without the ids, resume and correlation break. |
84| `usage[]` | Spec top level on `RUN_FINISHED` and `RUN_ERROR` | Token counts: `inputTokens`, `outputTokens`, `totalTokens`. |
85| `finishReason` | `metadata.tanstack` on `RUN_FINISHED` | After a tool result, the client continues only when this is not `"stop"`. |
86| `model` | `metadata.tanstack` | Generation reconstruct uses it. |
87
88`finishReason` is one of these values: `"stop"`, `"length"`, `"content_filter"`, `"tool_calls"`, or `null`.
89
90> [!WARNING]
91> Always send `finishReason` after a tool result. If it is missing, the client treats it as not `"stop"` and can send another turn.
92
93For the full event list, see [Stream Events](../chat/stream-events). For the request body, see [AG-UI Client Compliance](../migration/ag-ui-compliance).
94
95## Advanced
96
97### Usage on the wire and in process
98
99The wire uses the spec `usage[]` array with `inputTokens`. In process, `usage` is the TanStack `TokenUsage` type with `promptTokens`. The client rebuilds `TokenUsage` from the array.
100
101### `RUN_ERROR`
102
103An AG-UI `RUN_ERROR` has `message` and an optional `code` at the top level. Put the correlation ids in `metadata.tanstack`:
104
105```json
106{
107 "type": "RUN_ERROR",
108 "message": "Provider timeout",
109 "code": "TIMEOUT",
110 "metadata": {
111 "tanstack": {
112 "threadId": "thread-1",
113 "runId": "run-1",
114 "model": "gpt-6.1-sol"
115 }
116 }
117}
118```
119
120For a rate limit, put the wait time in `metadata.tanstack.retryAfterMs`, in milliseconds. Clients read it from there. See [Rate limits](../chat/stream-events#rate-limits).
121
122### Fields for other features
123
124When you use one of these features, add its field:
125
126- **Extra usage.** Spec `usage[]` also accepts `cachedInputTokens` and `reasoningTokens`. Put `cost` and other usage fields without a spec slot in `metadata.tanstack.usage`. The client merges them into `TokenUsage`.
127- **Interrupt errors.** On `RUN_ERROR`, set `metadata.tanstack.interruptErrors`. Then `ChatClient` can match a failed interrupt submit.
128- **Tool output error.** On `TOOL_CALL_RESULT`, set `metadata.tanstack.state` to `"output-error"` when the tool result is an error payload.
129- **Message timestamps.** On wire messages, `metadata.tanstack.createdAt` is an ISO-8601 string.
130- **Signatures.** Stream thinking signatures on `REASONING_ENCRYPTED_VALUE`. In the next-turn body, set the spec `encryptedValue` on `role: "reasoning"` messages and on `toolCalls`. Other provider fields for a tool call go in `metadata.tanstack.toolCallMetadata`. See [Thinking & Reasoning](../chat/thinking-content).