---
title: "TanStack AI"
description: "Stream AI chat from a Farm.js API route with TanStack AI, with server tools, browser tools, and your app's MCP tools, in any renderer."
canonical_url: "https://farmjs.dev/docs/integrations/tanstack-ai"
markdown_url: "https://farmjs.dev/docs/integrations/tanstack-ai.md"
last_updated: "2026-12-04"
x_farming_labs_generated_preamble: true
---

# TanStack AI
URL: /docs/integrations/tanstack-ai
LLM index: /llms.txt
Description: Stream AI chat from a Farm.js API route with TanStack AI, with server tools, browser tools, and your app's MCP tools, in any renderer.

# TanStack AI

[TanStack AI](https://tanstack.com/ai) runs on Farm.js without an adapter. Its server API reads a web `Request` and returns a streaming `Response`, which is the shape of a Farm.js API route, and its `useChat` bindings cover React, Vue, Svelte, Solid, and Preact. There is no `@farm.js` package to install: you use TanStack AI directly.

A complete example lives in [`examples/tanstack-ai-chat`](https://github.com/farming-labs/farm.js/tree/main/examples/tanstack-ai-chat).

## Install

```bash
pnpm add @tanstack/ai @tanstack/ai-react @tanstack/ai-openai zod
```

Use the binding for your renderer instead of `@tanstack/ai-react` where needed: `@tanstack/ai-vue`, `@tanstack/ai-svelte`, `@tanstack/ai-solid`, or `@tanstack/ai-preact`. Swap `@tanstack/ai-openai` for another provider adapter, such as Anthropic or Gemini.

This page uses TanStack AI 1.x. Its tool schemas need **Zod 4.2 or newer**.

## Create a chat route

`useChat` posts an AG-UI run, which `chatParamsFromRequest` reads. For a body that is not a run, it throws a `400` `Response`. Farm.js answers a thrown value with a `500`, so return that `Response` instead:

**src/lib/chat-params.server.ts**

```ts
import { chatParamsFromRequest } from "@tanstack/ai";

export async function readChatParams(request: Request) {
  try {
    return await chatParamsFromRequest(request);
  } catch (error) {
    if (error instanceof Response) return error;
    throw error;
  }
}
```

**src/app/api/chat/route.ts**

```ts
import { chat, toServerSentEventsResponse } from "@tanstack/ai";
import { openaiText } from "@tanstack/ai-openai";
import { readChatParams } from "../../../lib/chat-params.server";

export async function POST(request: Request) {
  const params = await readChatParams(request);
  if (params instanceof Response) return params;
  const { messages, threadId, runId } = params;

  const abortController = new AbortController();
  request.signal.addEventListener("abort", () => abortController.abort(), { once: true });

  const stream = chat({
    adapter: openaiText("gpt-5.4-mini"),
    messages,
    threadId,
    runId,
    abortController,
  });
  return toServerSentEventsResponse(stream, { abortController });
}
```

Set `OPENAI_API_KEY` in your server environment. The adapter and the key stay in the server bundle.

The `AbortController` stops the model when the visitor closes the page or calls `stop()`.

`toServerSentEventsResponse` streams Server-Sent Events, which Farm.js leaves uncompressed so tokens arrive as they are generated. `toHttpResponse` (newline-delimited JSON) also works; Farm.js may compress it in production, but still flushes every chunk.

For long generations on serverless targets, raise the route's limit with [`export const maxDuration`](/docs/route-runtime).

## Add tools

Define each tool once, as a schema shared by the server and the browser:

**src/lib/tools.ts**

```ts
import { toolDefinition } from "@tanstack/ai/client";
import { z } from "zod";

export const getFarmFact = toolDefinition({
  name: "get_farm_fact",
  description: "Look up a fact about Farm.js.",
  inputSchema: z.object({ topic: z.enum(["renderers", "deploy", "agents"]) }),
  outputSchema: z.object({ topic: z.string(), fact: z.string() }),
});

export const setAccent = toolDefinition({
  name: "set_accent",
  description: "Change the accent color of the page.",
  inputSchema: z.object({ color: z.enum(["green", "blue", "orange", "pink"]) }),
  outputSchema: z.object({ applied: z.string() }),
});
```

Import the definitions from `@tanstack/ai/client`, so a browser component can import the same file without pulling server code into its bundle.

### Server tools

Implement a server tool with `.server()` and pass it to `chat()`. Pass a browser tool as the bare definition; the model calls it, and the browser runs it.

**src/app/api/chat/route.ts**

```ts
import { chat, toServerSentEventsResponse } from "@tanstack/ai";
import { openaiText } from "@tanstack/ai-openai";
import { readChatParams } from "../../../lib/chat-params.server";
import { getFarmFact, setAccent } from "../../../lib/tools";

const FACTS = {
  renderers: "Farm.js renders with React, Preact, Solid, Vue, and Svelte.",
  deploy: "Farm.js builds through Nitro to Vercel, Netlify, Cloudflare, Node, and more.",
  agents: "Farm.js apps serve Markdown mirrors and llms.txt, and expose routes as MCP tools.",
} as const;

const getFarmFactServer = getFarmFact.server(async ({ topic }) => ({ topic, fact: FACTS[topic] }));

export async function POST(request: Request) {
  const params = await readChatParams(request);
  if (params instanceof Response) return params;
  const { messages, threadId, runId } = params;
  const stream = chat({
    adapter: openaiText("gpt-5.4-mini"),
    messages,
    threadId,
    runId,
    tools: [getFarmFactServer, setAccent],
  });
  return toServerSentEventsResponse(stream);
}
```

### Browser tools

Implement the browser side with `.client()` and pass it to `useChat`. TanStack AI runs it in the browser and resumes the run with the result.

**src/app/chat.tsx**

```tsx
"use client";

import { clientTools, fetchServerSentEvents, useChat } from "@tanstack/ai-react";
import { setAccent } from "../lib/tools";

const ACCENTS = { green: "#8ce0b5", blue: "#8cb8ff", orange: "#ffb27a", pink: "#ff9ad5" } as const;

const tools = clientTools(
  setAccent.client(({ color }) => {
    document.documentElement.style.setProperty("--accent", ACCENTS[color]);
    return { applied: color };
  }),
);

export function Chat() {
  const { messages, sendMessage, isLoading, stop } = useChat({
    connection: fetchServerSentEvents("/api/chat"),
    threadId: "farm-demo",
    tools,
  });
  // Render messages[].parts and an input that calls sendMessage(text).
}
```

`threadId` names the conversation. It is required in TanStack AI 1.x; use one per conversation when you store history.

## Other renderers

The chat route does not change between renderers; only the component does. In Svelte:

**src/app/page.svelte**

```svelte
<script lang="ts">
  import { createChat, fetchServerSentEvents } from "@tanstack/ai-svelte";

  const chat = createChat({
    connection: fetchServerSentEvents("/api/chat"),
    threadId: "farm-demo",
  });
</script>
```

Vue, Solid, and Preact use `useChat` from their own TanStack AI package, with the same options.

## Use your app's MCP tools

Farm.js can [publish API routes as MCP tools](/docs/plugins/mcp), and TanStack AI can use any MCP server as a tool source. Together, the model in your chat calls your real API routes, with their validation and authorization.

### 1. Publish routes as MCP tools

```bash
pnpm add @farm.js/mcp
```

**farm.config.ts**

```ts
import { defineConfig } from "@farm.js/core";
import { GET as listProjects } from "./src/app/api/projects/route";

export default defineConfig({
  mcp: {
    name: "projects",
    tools: [
      {
        endpoint: listProjects,
        name: "list_projects",
        description: "List projects, optionally filtered by status.",
      },
    ],
    authorize: ({ request }) =>
      request.headers.get("authorization") === `Bearer ${process.env.MCP_TOKEN}`
        ? { subject: "chat-agent" }
        : false,
  },
});
```

`listProjects` is an ordinary endpoint:

**src/app/api/projects/route.ts**

```ts
import { createEndpoint } from "@farm.js/core/api";
import { z } from "zod";
import { projects } from "../../../lib/projects";

export const GET = createEndpoint(
  "/api/projects",
  {
    method: "GET",
    query: z.object({ status: z.enum(["active", "planned"]).optional() }),
  },
  async ({ query }) => ({
    projects: query.status ? projects.filter((p) => p.status === query.status) : projects,
  }),
);
```

### 2. Hand the MCP server to `chat()`

```bash
pnpm add @tanstack/ai-mcp @modelcontextprotocol/client
```

**src/app/api/chat/route.ts**

```ts
import { chat, toServerSentEventsResponse } from "@tanstack/ai";
import { openaiText } from "@tanstack/ai-openai";
import { createMCPClient } from "@tanstack/ai-mcp";
import { readChatParams } from "../../../lib/chat-params.server";

export async function POST(request: Request) {
  const params = await readChatParams(request);
  if (params instanceof Response) return params;
  const { messages, threadId, runId } = params;

  const projectsServer = await createMCPClient({
    transport: {
      type: "http",
      url: new URL("/api/mcp", request.url).href,
      headers: { Authorization: `Bearer ${process.env.MCP_TOKEN}` },
    },
  });

  const stream = chat({
    adapter: openaiText("gpt-5.4-mini"),
    messages,
    threadId,
    runId,
    mcp: { clients: [projectsServer], connection: "close" },
  });
  return toServerSentEventsResponse(stream);
}
```

When a user asks "Which projects are active?":

1. `chat()` connects to `/api/mcp` and finds `list_projects` and its input schema.
2. The model calls `list_projects` with `{ "status": "active" }`.
3. Farm.js checks `authorize`, validates the input against the route's schema, and runs `GET /api/projects`.
4. The result goes back to the model, which answers. `connection: "close"` closes the MCP connection when the run ends.

Keep `MCP_TOKEN` on the server. Calling your own MCP server goes out over HTTP and back in, so external agents and your chat use the same path.

### Browser tools with WebMCP

TanStack AI's `registerWebMCPTools` (`useRegisterWebMCPTools` in React) and Farm.js's [WebMCP plugin](/docs/plugins/webmcp) both register tools through `document.modelContext`, so they can run on the same page. Give their tools distinct names.

## Try it without an API key

The example picks its model from the environment: `OPENAI_API_KEY` for OpenAI, or `AI_BASE_URL` (with `AI_MODEL`) for any OpenAI-compatible endpoint, such as Ollama, OpenRouter, or Groq. It also ships a mock model for local runs and tests:

```bash
cd examples/tanstack-ai-chat
node --experimental-strip-types test/serve-mock.ts   # prints AI_BASE_URL=...
AI_BASE_URL=<that url> pnpm dev
```

## Notes

- **Cancellation.** Abort the `AbortController` you pass to `chat()` from `request.signal`, as in [Create a chat route](#create-a-chat-route), so the model stops when the visitor leaves.
- **WebSockets.** TanStack AI's WebSocket transport needs a socket upgrade, which Farm.js API routes do not expose. Use Server-Sent Events or the HTTP stream transport.
- **Resumable streams.** `memoryStream(request)` keeps a run's log in one process. On serverless targets a reconnect can reach a different instance, so use a shared log such as `durableStream` from `@tanstack/ai-durable-stream` there.

## Sitemap

See the full [sitemap](/sitemap.md) for all pages.
Docs-scoped sitemap: [/docs/sitemap.md](/docs/sitemap.md).
Well-known sitemap: [/.well-known/sitemap.md](/.well-known/sitemap.md).
