TanStack AI Tutorial: Typed Chat Agent + Custom Tools
TanStack AI tutorial: build a typed chat agent with toolDefinition, a custom tool-calling adapter, MCP support, and live trend tools from TrendsAGI.

This TanStack AI tutorial walks you from a streaming server route to a fully typed chat agent with real custom tool calls. TanStack AI reached 1.0 in October 2026, according to tanstack.com, shipping stable core APIs and an experimental agent harness after growing from a single chat() function into a toolkit covering chat, tools, media, MCP, persistence, sandboxes and agents.
Below you get the full path most tutorials split up: a typed toolDefinition() whose arguments your TypeScript compiler checks, a thin custom tool-calling adapter, and the tool-execution loop that runs on your server. The tools query live trend data from TrendsAGI, so the finished agent does something measurable instead of echoing a greeting. Confirm every signature against the TanStack AI docs before you ship — the research sheet for this article flags exact signatures as unverified.
What is verified about TanStack AI 1.0
Stick to what the sources state. The 1.0 release post on tanstack.com says core APIs are stable and the agent harness is experimental; the GitHub package docs list the core pieces as @tanstack/ai with chat(), toolDefinition(), toServerSentEventsResponse() and maxIterations().
- 23 provider adapters plus
openaiCompatiblefor any OpenAI-style API (tanstack.com). @tanstack/ai-reactexportsuseChat()and re-exports connection adapters (github.com).- OpenRouter's adapter exposes 400+ models through one unified API (openrouter.ai).
- Vercel AI Gateway needs Node.js 22 or later and the
@tanstack/ai-vercel-gatewayadapter (vercel.com). createMCPServerserves TanStack tools as an MCP server, andfakeText()tests chat, tools and middleware with no network key (tanstack.com).- The Quick Start renders tokens as the model writes them in about five minutes (tanstack.com).
Unverified and worth checking yourself: exact toolDefinition and adapter interface signatures, the agent harness API, TanStack pricing and limits, and support/SLA terms. The release post says "eight" UI frameworks in one place while its list suggests nine — treat the count as approximate.
TanStack AI quick start in five minutes
Install the stable packages together; a 1.0 client requires a 1.0 server, per tanstack.com.
npm install @tanstack/ai @tanstack/ai-react
# plus a provider adapter, e.g. the OpenRouter adapterServer route: call chat() and pipe the stream out with toServerSentEventsResponse().
import { chat, toServerSentEventsResponse } from "@tanstack/ai";
export async function POST(req: Request) {
const { messages } = await req.json();
const stream = chat({
messages,
tools: [],
maxIterations: 4,
});
return toServerSentEventsResponse(stream);
}Client: useChat() from @tanstack/ai-react holds typed messages and streams tokens into your component. The adapter that connects the hook to the route comes from the re-exported connection adapters documented on GitHub.
Defining typed tools with toolDefinition
This is where a generic tutorial stops. Give each tool a typed argument shape, then have the handler call TrendsAGI's REST API. The endpoints and parameter names below come from the TrendsAGI fact sheet.
import { toolDefinition } from "@tanstack/ai";
const trendsagiHeaders = {
"X-API-Key": process.env.TRENDSAGI_API_KEY!,
};
export const topTrends = toolDefinition({
name: "top_trends",
description: "List trends currently gaining attention, sorted by velocity.",
parameters: {
type: "object",
properties: {
category: { type: "string" },
limit: { type: "number" },
},
required: ["category"],
},
execute: async ({ category, limit = 5 }: { category: string; limit?: number }) => {
const qs = new URLSearchParams({
category,
sort_by: "velocity",
limit: String(limit),
});
const res = await fetch(`https://api.trendsagi.com/api/trends?${qs}`, {
headers: trendsagiHeaders,
});
return res.json();
},
});A second tool for the AI layer: GET /api/trends/{id}/ai-insights returns the summary, key themes, sentiment, audience and marketing angles for one trend. A third can hit GET /api/trends/{id}/analytics?period=7d to compare movement. Keep each tool narrow — one endpoint, one job — so the loop stays cheap and your logs stay readable.
Wiring a custom tool-calling adapter
Adapters translate between TanStack's tool format and a provider's payload. Use an official adapter when one exists (23 providers, plus openaiCompatible), and reserve a custom adapter for gateways or internal HTTP services. The sketch below mirrors the loop shape in the TanStack docs: validate arguments, run execute, append the result, and repeat until the model stops asking for tools or maxIterations() is hit.
// Shape sketch only — verify the adapter interface in TanStack AI docs.
export function myAdapter(tools) {
return {
toProviderTools: () =>
tools.map((t) => ({ name: t.name, parameters: t.parameters })),
async runToolCall(call) {
const tool = tools.find((t) => t.name === call.name);
if (!tool) return { error: `unknown tool ${call.name}` };
return tool.execute(call.arguments);
},
};
}Two things the loop must handle: invalid arguments (return the error to the model so it can retry) and timeouts (cap fetch calls; TrendsAGI's /api/user/api-usage tells you how many requests you have consumed).
Adding MCP and approval patterns
createMCPServer in 1.0 exposes your TanStack tools to any MCP host, so the same top_trends tool above becomes callable from desktop agents. If you would rather consume MCP tools than publish them, register the TrendsAGI hosted server at https://api.trendsagi.com/mcp — Streamable HTTP with OAuth 2.1 or an API key as a Bearer token, read-only tools. Each tool call there counts as one API request.
# Claude Code against the hosted host
claude mcp add --transport http trendsagi https://api.trendsagi.com/mcpFor approvals, gate write-capable tools behind an explicit human step and leave read tools on auto. TrendsAGI's Python SDK mirrors this: TrendsAGITools(client) is read-only until you construct it with allow_writes=True.
Upgrading a 0.x app to 1.0 safely
- Upgrade every
@tanstack/ai*package in one commit — a 1.0 client requires a 1.0 server. - Run the codemod: the release post describes a jscodeshift transform hosted in the TanStack/ai repo.
- Run type checks; typed tool arguments are the fastest way to surface broken calls.
- Decide whether the experimental agent harness is right for you — it stays opt-in, so production chat can remain on stable core APIs.
Testing tools with fakeText and deterministic fixtures
fakeText() runs chat, tools and middleware with no network and no API key. Pair it with recorded TrendsAGI JSON so tool output is byte-stable, and assert that your custom adapter forwarded the right arguments. This is also where you test rate-limit and error branches without burning requests.
What this changes for production agents
The honest trade-offs: adapter fragmentation is real (23 adapters plus one compatible shim), the harness is experimental, and moving packages together means a single bad release blocks the whole upgrade. The payoff is observability. Because your tools call TrendsAGI endpoints, every tool result carries a measured velocity snapshot and a timestamp — you can chart which tools fire, what they return, and how trend velocity moved between calls. Velocity is a snapshot rate, not a forecast or unique-user count, so log it as observed data, not prediction.
Frequently asked questions
What is TanStack AI 1.0 and what's the difference between the stable core APIs and the experimental agent harness?
TanStack AI 1.0, released October 2026 per tanstack.com, ships stable core APIs for chat, tools and streaming. The agent harness ships alongside it as an experimental feature, so production code can stay on the stable surface while you trial the harness.
How do I go from a streaming chat() server route to a fully typed chat UI in my framework?
Call chat() on the server, return the stream via toServerSentEventsResponse(), then use useChat() from @tanstack/ai-react with a re-exported connection adapter on the client. TanStack's Quick Start gets token-by-token rendering working in about five minutes.
How do I define typed tools with toolDefinition and run the tool execution loop?
Define the argument schema on toolDefinition(), implement execute, then let your adapter validate and run the call while the loop appends results. Set maxIterations() to cap looping. Confirm the exact interface in TanStack's docs; it's not fully shown on the release pages.
How do I add an MCP server or consume MCP tools?
Publish TanStack tools with createMCPServer, or point an MCP host at TrendsAGI's hosted server at https://api.trendsagi.com/mcp for read-only trend tools. Restrict write paths behind explicit approval; read tools can run automatically.
How do I upgrade an existing 0.x app to 1.0 safely?
Upgrade all @tanstack/ai* packages together, run the jscodeshift codemod described on tanstack.com, then type-check. Keeping the experimental harness opt-in limits blast radius if something breaks.
How do I test tools and middleware without an API key?
Use fakeText(), which runs chat, tools and middleware with no network or key, and pair it with recorded TrendsAGI JSON fixtures. Assert on forwarded tool arguments and error branches.
How we researched this
Prepared by TrendsAGI Research. Facts checked on 7 November 2026 against the sources listed below.
We read the official TanStack AI documentation listed below. The TrendsAGI steps and code use its documented REST API and Python SDK; confirm the TanStack AI side against its current documentation, since third-party products change.
| Claim | Applies to | Source |
|---|---|---|
| TanStack AI 1.0 ships stable core APIs plus a new experimental agent harness. | 1.0 (harness experimental) | tanstack.com |
| TanStack AI 1.0 offers 23 provider adapters plus openaiCompatible for any OpenAI-style API. | 1.0 | tanstack.com |
| Core packages are @tanstack/ai with chat(), toolDefinition(), toServerSentEventsResponse(), and maxIterations(). | All plans | github.com |
| The React package @tanstack/ai-react provides useChat() and re-exports connection adapters. | All plans | github.com |
| A 1.0 client requires a 1.0 server, so stable @tanstack/ai* packages must be upgraded together. | 1.0 | tanstack.com |
| The upgrade codemod runs via jscodeshift with a transform URL from the TanStack/ai repo. | 1.0 | tanstack.com |
| createMCPServer serves TanStack tools as an MCP server for MCP hosts. | 1.0 | tanstack.com |
| fakeText() tests chat(), tools, and middleware with no network and no API key. | 1.0 | tanstack.com |
| The OpenRouter adapter exposes 400+ AI models through a single unified API. | All plans | openrouter.ai |
| Using TanStack AI with Vercel AI Gateway requires Node.js 22 or later and the @tanstack/ai-vercel-gateway adapter. | All plans | vercel.com |
| The Quick Start adds a chat that renders tokens while the model writes them, in about five minutes. | All plans | tanstack.com |
Sources
- TanStack AI 1.0: Still Your AI, Still Your Way — tanstack.com
- TanStack AI (React) (GitHub) — github.com
- TanStack AI Integration - OpenRouter SDK Support — openrouter.ai
- TanStack AI with AI Gateway (Vercel) — vercel.com