Back to Skills

Tanstack Ai

TanStack AI (alpha) provider-agnostic type-safe chat with streaming for OpenAI, Anthropic, Gemini, Ollama. Use for chat APIs, React/Solid frontends with useChat/ChatClient, isomorphic tools, tool approval flows, agent loops, multimodal inputs, or troubleshooting streaming and to…

reactapiaiagent
By secondsky
17928Updated 1 day agoTypeScriptMIT

Skill Content

# TanStack AI (Provider-Agnostic LLM SDK)

**Status**: Production Ready ✅  
**Last Updated**: 2025-12-09  
**Dependencies**: Node.js 18+, TypeScript 5+; React 18+ for `@tanstack/ai-react`; Solid 1.8+ for `@tanstack/ai-solid`  
**Latest Versions**: @tanstack/ai@latest (alpha), @tanstack/ai-react@latest, @tanstack/ai-client@latest, adapters: @tanstack/ai-openai@latest @tanstack/ai-anthropic@latest @tanstack/ai-gemini@latest @tanstack/ai-ollama@latest

---

## Quick Start (7 Minutes)

### 1) Install core + adapter

```bash
pnpm add @tanstack/ai @tanstack/ai-react @tanstack/ai-openai
# swap adapters as needed: @tanstack/ai-anthropic @tanstack/ai-gemini @tanstack/ai-ollama
pnpm add zod              # recommended for tool schemas
```

**Why this matters:**
- Core is framework-agnostic; React binding just wraps the headless client. citeturn1search3
- Adapters abstract provider quirks so you can change models without rewriting code. citeturn1search3

### 2) Ship a streaming chat endpoint (Next.js or TanStack Start)

```ts
// app/api/chat/route.ts (Next.js) or src/routes/api/chat.ts (TanStack Start)
import { chat, toStreamResponse } from '@tanstack/ai'
import { openai } from '@tanstack/ai-openai'
import { tools } from '@/tools/definitions' // definitions only

export async function POST(request: Request) {
  const { messages, conversationId } = await request.json()
  const stream = chat({
    adapter: openai(),
    messages,
    model: 'gpt-4o',
    tools,
  })
  return toStreamResponse(stream)
}
```

**CRITICAL:**
- Pass tool **definitions** to the server so the LLM can request them; implementations live in their runtimes. citeturn0search7
- Always stream; chunked responses keep UIs responsive and reduce token waste. citeturn0search1

### 3) Wire the client with `useChat` + SSE

```tsx
// components/Chat.tsx
import { useChat, fetchServerSentEvents } from '@tanstack/ai-react'
import { clientTools } from '@tanstack/ai-client'
import { updateUIDef } from '@/tools/definitions'

const updateUI = updateUIDef.client(({ message }) => {
  alert(message)
  return { success: true }
})

export function Chat() {
  const tools = clientTools(updateUI)
  const { messages, sendMessage, isLoading, approval } = useChat({
    connection: fetchServerSentEvents('/api/chat'),
    tools,
  })

  return (
    <form onSubmit={e => { e.preventDefault(); sendMessage(e.currentTarget.prompt.value) }}>
      <textarea name="prompt" disabled={isLoading} />
      {approval?.pending && (
        <button type="button" onClick={() => approval.approve()}>
          Approve tool
        </button>
      )}
    </form>
  )
}
```

**CRITICAL:**
- Use `fetchServerSentEvents` (or matching adapter) to mirror the streaming response. citeturn0search0
- Keep client tool names identical to definitions to avoid “tool not found” errors. citeturn0search7

---

## The 4-Step Setup Process

### Step 1: Choose provider + model safely
- Add the correct adapter and set the matching API key (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `GEMINI_API_KEY`, or Ollama host).
- Prefer per-model option typing from adapters to avoid invalid options (e.g., vision-only fields). citeturn1search3

### Step 2: Define tools once, implement per runtime

```ts
// tools/definitions.ts
import { z, toolDefinition } from '@tanstack/ai'

export const getWeatherDef = toolDefinition({
  name: 'getWeather',
  description: 'Get current weather for a city',
  inputSchema: z.object({ city: z.string() }),
  needsApproval: true,
})

export const getWeather = getWeatherDef.server(async ({ city }) => {
  const data = await fetch(`https://api.weather.gov/points?q=${city}`).then(r => r.json())
  return { summary: data.properties?.relativeLocation?.properties?.city ?? city }
})

export const showToast = getWeatherDef.client(({ city }) => {
  console.log(`Showing toast for ${city}`)
  return { acknowledged: true }
})
```

**Key Points:**
- `needsApproval: true` forces explicit user approval for sensitive actions. citeturn0search1
- Keep tools single-purpose and idempotent; return structured objects instead of throwing errors. citeturn0search1

### Step 3: Create connection adapter + chat options
- Server: `toStreamResponse(stream)` for HTTP streaming; `toServerSentEventsStream` helper for Server-Sent Events. citeturn0search3turn0search4
- Client: `fetchServerSentEvents('/api/chat')` or a custom adapter for websockets if needed. citeturn0search0
- Configure `agentLoopStrategy` (e.g., `maxIterations(8)`) to cap tool recursion. citeturn1search4

### Step 4: Add observability + guardrails
- Log tool executions and stream chunks for debugging; alpha exposes hooks while devtools are in progress. citeturn0search1
- Validate inputs with Zod; fail fast and return typed error objects.
- Enforce timeouts on external API calls inside tools to prevent stuck agent loops.

---

## Critical Rules

### Always Do

✅ Stream responses; avoid waiting for full completions. citeturn0search1  
✅ Pass **definitions** to the server and **implementations** to the correct runtime. citeturn0search7  
✅ Use Zod schemas for tool inputs/outputs to keep type safety across providers. citeturn0search1  
✅ Cap agent loops with `maxIterations` to prevent runaway tool calls. citeturn1search4  
✅ Require `needsApproval` for destructive or billing-sensitive tools. citeturn0search1  

### Never Do

❌ Mix provider adapters in a single request—instantiate one adapter per call.  
❌ Throw raw errors from tools; return structured error payloads.  
❌ Send client tool **implementations** to the server (definitions only).  
❌ Hardcode model capabilities; rely on adapter typings for per-model options. citeturn0search1  
❌ Skip API key checks; fail fast with helpful messages on the server. citeturn0search1  

---

## Known Issues Prevention

This skill prevents **3** documented issues:

### Issue #1: “tool not found” / silent tool failures
**Why it happens**: Definitions aren’t passed to `chat()`; only implementations exist locally.  
**Prevention**: Export definitions separately and include them in the server `tools` array; keep names stable. citeturn0search7

### Issue #2: Streaming stalls in the UI
**Why it happens**: Mismatch between server response type and client adapter (HTTP chunked vs SSE).  
**Prevention**: Use `toStreamResponse` on the server + `fetchServerSentEvents` (or matching adapter) on the client. citeturn0search1turn0search0

### Issue #3: Model option validation errors
**Why it happens**: Provider-specific options (e.g., vision params) sent to unsupported models.  
**Prevention**: Use adapter-provided types; rely on per-model option typing to surface invalid fields at compile time. citeturn1search3

---

## Configuration Files Reference

### .env.local (Full Example)

```env
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=
GEMINI_API_KEY=
OLLAMA_HOST=http://localhost:11434
AI_STREAM_STRATEGY=immediate
```

**Why these settings:**
- Keep non-active providers empty to avoid accidental multi-provider calls.
- `AI_STREAM_STRATEGY` is read by the sample client to pick chunk strategies (immediate vs buffered).

---

## Common Patterns

### Pattern 1: Agentic cycle with bounded tools

```ts
import { chat, maxIterations } from '@tanstack/ai'
import { openai } from '@tanstack/ai-openai'

const stream = chat({
  adapter: openai(),
  messages,
  tools,
  agentLoopStrategy: maxIterations(8), // hard cap
})
```

**When to use**: Any flow where the LLM could recurse across tools (search → summarize → fetch detail). citeturn1search4

### Pattern 2: Hybrid server + client tools

```ts
// server: data fetch
const fetchUser = fetchUserDef.server(async ({ id }) => db.user.find(id))

// client: UI update
const highlightUser = highlightUserDef.client(({ id }) => {
  document.querySelector(`#user-${id}`)?.classList.add('ring')
  return { highlighted: true }
})

chat({ tools: [fetchUser, highlightUser] })
```

**When to use**: When the model must both fetch data and mutate UI state in one loop. citeturn0search1

---

## Using Bundled Resources

### Scripts (scripts/)

- `scripts/check-ai-env.sh` — verifies required provider keys are present before running dev servers.

**Example Usage:**
```bash
./scripts/check-ai-env.sh
```

### References (references/)

- `references/tanstack-ai-cheatsheet.md` — condensed server/client/tool patterns plus troubleshooting cues.

**When Claude should load these**: When debugging tool routing, streaming issues, or recalling exact API calls.

### Assets (assets/)

- `assets/api-chat-route.ts` — copy/paste API route template with streaming + tools.  
- `assets/tool-definitions.ts` — ready-to-use toolDefinition examples with approval + zod schemas.

---

## When to Load References

Load reference files for specific implementation scenarios:

- **Adapter Comparison**: Load `references/adapter-matrix.md` when choosing between OpenAI, Anthropic, Gemini, or Ollama adapters, or when debugging provider-specific quirks.

- **React Integration Details**: Load `references/react-integration.md` when implementing useChat hooks, handling SSE streams in React components, or managing client-side tool state.

- **Routing Setup**: Load `references/start-vs-next-routing.md` when setting up API routes in Next.js vs TanStack Start, or troubleshooting streaming response setup.

- **Streaming Issues**: Load `references/streaming-troubleshooting.md` when debugging SSE connection problems, chunk delivery issues, or HTTP streaming configuration.

- **Quick Reference**: Load `references/tanstack-ai-cheatsheet.md` for condensed API patterns, tool definition syntax, or rapid troubleshooting cues.

- **Tool Architecture**: Load `references/tool-patterns.md` when implementing complex client/server tool workflows, approval flows, or hybrid tool patterns.

- **Type Safety Details**: Load `references/type-safety.md` when working with per-model option typing, multimodal inputs, or debugging type errors across adapters.

---

## Advanced Topics

### Per-model type safety
- Use adapter typings to pick valid options per model; avoid generic `any` options on `chat()`. citeturn1search3
- For multimodal models, send `parts` with correct MIME types; unsupported modalities are caught at compile time. citeturn1search3

### Tool approval UX
- Surfaced via `approval` object in `useChat`; render approve/reject UI and persist decision per tool call. citeturn0search1
- For auditable actions, log approval decisions alongside tool inputs.

### Connection adapters
- Default to `fetchServerSentEvents` (SSE) for minimal setup; switch to custom adapters for websockets or HTTP chunking. citeturn0search0
- Use `ImmediateStrategy` in the client to emit every chunk for typing indicator UIs. citeturn0search0

---

## Dependencies

**Required**:
- @tanstack/ai@latest — core chat + tool engine  
- @tanstack/ai-react@latest — React bindings (skip for headless usage)  
- @tanstack/ai-client@latest — headless chat client + adapters  
- Adapter: one of @tanstack/ai-openai@latest | @tanstack/ai-anthropic@latest | @tanstack/ai-gemini@latest | @tanstack/ai-ollama@latest  
- zod@latest — schema validation for tools

**Optional**:
- @tanstack/ai-solid@latest — Solid bindings  
- @tanstack/react-query@latest — cache data fetched inside tools  
- @tanstack/start@latest — co-locate AI tools with server functions

---

## Official Documentation

- **TanStack AI Overview**: https://tanstack.com/ai/latest/docs/getting-started/overview  
- **Quick Start**: https://tanstack.com/ai/latest/docs/getting-started/quick-start  
- **Tool Architecture & Approval**: https://tanstack.com/ai/latest/docs/guides/tool-architecture  
- **Client Tools**: https://tanstack.com/ai/latest/docs/guides/client-tools  
- **API Reference**: https://tanstack.com/ai/latest/docs/api/ai

---

## Package Versions (Verified 2025-12-09)

```json
{
  "dependencies": {
    "@tanstack/ai": "latest",
    "@tanstack/ai-react": "latest",
    "@tanstack/ai-client": "latest",
    "@tanstack/ai-openai": "latest"
  },
  "devDependencies": {
    "zod": "latest"
  }
}
```

---

## Troubleshooting

### Problem: UI never receives tool output
**Solution**: Ensure tool implementations return serializable objects; avoid returning undefined. Register client implementations via `clientTools(...)`.

### Problem: “Missing API key” responses
**Solution**: Run `./scripts/check-ai-env.sh` and set the relevant provider key in `.env.local`. Fail fast in the route before invoking `chat()`. citeturn0search1

### Problem: Streaming stops after first chunk
**Solution**: Confirm the server returns `toStreamResponse(stream)` (or SSE helper) and that any reverse proxy allows chunked transfer.

---

## Complete Setup Checklist

Use this checklist to verify your setup:

- [ ] Installed core + one adapter and zod
- [ ] API route returns `toStreamResponse(stream)` with tool **definitions** included
- [ ] Client uses `fetchServerSentEvents` (or matching adapter) and registers client tool implementations
- [ ] `needsApproval` paths render approve/reject UI
- [ ] Agent loop capped (e.g., `maxIterations`)
- [ ] Environment keys validated with `check-ai-env.sh`
- [ ] Multimodal inputs tested if targeting vision/audio models

---

**Questions? Issues?**

1. Load `references/tanstack-ai-cheatsheet.md` for deeper examples  
2. Re-run quick start steps with a single provider adapter  
3. Review official docs above for API surface updates

---

How to use

  1. Copy the skill content above
  2. Create a .claude/skills directory in your project
  3. Save as .claude/skills/claude-skills-tanstack-ai.md
  4. Use /claude-skills-tanstack-ai in Claude Code to invoke this skill

Claude Code Skills Collection

170 production-ready skills for Claude Code CLI

Version 3.3.1 | Last Updated: 2026-05-14

<div align="center">

🔌 Platform Support

This repository uses Claude Plugin Patterns — natively supported by:

PlatformStatusNotes
Claude CodeNativeFull marketplace support
Factory DroidNativeFull marketplace support
</div> **For all other Platforms like opencode, codex and others, you can use https://github.com/enulus/OpenPackage **

A curated collection of battle-tested skills for building modern web applications with Cloudflare, AI integrations, React, Tailwind, and more.

PS: if skills.sh warns about any skill: Their scan process is a outdated LLM which flags newest versions pins (like in ZOD) as non existent and by that potentially malicous.


Quick Start

Marketplace Installation (Recommended)

# Add the marketplace
/plugin marketplace add https://github.com/secondsky/claude-skills

# Install individual skills as needed
/plugin install cloudflare-d1@claude-skills
/plugin install tailwind-v4-shadcn@claude-skills
/plugin install ai-sdk-core@claude-skills

See MARKETPLACE.md for complete catalog of all 170 skills.

Bulk Installation (Contributors)

# Clone the repository
git clone https://github.com/secondsky/claude-skills.git
cd claude-skills

# Install all 170 skills at once
./scripts/install-all.sh

# Or install individual skills
./scripts/install-skill.sh cloudflare-d1

Repository Structure

This repository contains 170 production-tested skills for Claude Code, each focused on a specific technology or capability.

Individual Skills: Each skill is a standalone unit with:

  • SKILL.md - Core knowledge and guidance
  • Templates - Working code examples
  • References - Extended documentation
  • Scripts - Helper utilities

Installation Options:

  1. Individual - Install only the skills you need via marketplace
  2. Bulk - Install all 170 skills using ./scripts/install-all.sh

Available Skills (170 Individual Skills)

Each skill is individually installable. Install only the skills you need.

Full Catalog: See MARKETPLACE.md for detailed listings.

Categories

CategorySkillsExamples
tooling29turborepo, plan-interview, code-review
frontend26nuxt-v4, nuxt-v5, tailwind-v4-shadcn, tanstack-query, nuxt-studio, maz-ui, threejs
cloudflare21cloudflare-d1, cloudflare-workers-ai, cloudflare-agents
ai20openai-agents, claude-api, ai-sdk-core
api16api-design-principles, graphql-implementation
web10hono-routing, firecrawl-scraper, web-performance
mobile7swift-best-practices, react-native-app, react-native-skills
database6drizzle-orm-d1, neon-vercel-postgres, supabase-postgres-best-practices
security6csrf-protection, access-control-rbac
auth4better-auth
testing4vitest-testing, playwright-testing
design4design-review, design-system-creation
woocommerce4woocommerce-backend-dev
cms4hugo, sveltia-cms, wordpress-plugin-core
architecture3microservices-patterns, architecture-patterns
data3sql-query-optimization, recommendation-engine
seo2seo-optimizer, seo-keyword-cluster-builder
documentation1technical-specification

How It Works

Auto-Discovery

Claude Code automatically checks ~/.claude/skills/ for relevant skills before planning tasks:

User: "Set up a Cloudflare Worker with D1 database"
           ↓
Claude: [Checks skills automatically]
           ↓
Claude: "Found cloudflare-d1 skills.
         These prevent 12 documented errors. Use them?"
           ↓
User: "Yes"
           ↓
Result: Production-ready setup, zero errors, ~65% token savings

Note: Due to token limits, not all skills may be visible at once. See ⚠️ Important: Token Limits below.

Skill Structure

Each skill includes:

skills/[skill-name]/
├── SKILL.md              # Complete documentation
├── .claude-plugin/
│   └── plugin.json       # Plugin metadata
├── templates/            # Ready-to-copy templates
├── scripts/              # Automation scripts
└── references/           # Extended documentation

Recent Additions

May 2026

Supply Chain Security (cross-cutting):

  • dependency-upgrade expanded with Socket CLI integration — proactive malicious package detection, typosquatting alerts, and CI/CD security gates. New 418-line reference guide, 2 GitHub Actions templates, and expanded supply chain security comparison (3 tools)
  • 31 skills now include "Secure Installation" guidance — contextually-tailored security sections across all high-risk skill categories (scaffolding, MCP/agent SDKs, multi-provider installs, Docker, CI/CD). Covers 8 Bun skills, 5 Nuxt skills, 6 Cloudflare skills, 4 AI/agent skills, and 8 frontend/tooling skills
  • Supply chain security is now a first-class cross-cutting concern woven into the skill collection — not a standalone topic

February - April 2026

Full-Stack Frameworks:

  • nuxt-v5 (v1.0.0) - Full Nuxt 5 support with 4 skills (core, data, server, production), 3 diagnostic agents, and interactive setup wizard
  • supabase-postgres-best-practices - 30 Postgres optimization rules from Supabase across 8 categories
  • threejs (v1.0.0) - 3D web graphics: scenes, geometries, shaders, animations, post-processing

Infrastructure:

  • JSON schema validation - Automated plugin.json validation with CI support
  • GitHub issue templates - Skill-specific issue templates for bug reports, feature requests, and submissions

Plugin Enhancements:

  • mutation-testing - Added Bun native runner support
  • dependency-upgrade - Added supply chain security content

December 2025 - January 2026

Frontend Expansion:

  • nuxt-studio (v1.0.0) - Visual CMS for Nuxt Content with live preview, OAuth auth, and R2 storage integration
  • maz-ui (v1.0.0) - 50+ Vue/Nuxt components with theming, i18n, form generation, and 14 composables

Developer Workflow:

  • plan-interview (v2.0.0) - Adaptive interview-driven spec generation with autonomous quality review
  • turborepo (v2.8.0) - Updated to official Vercel skill with enhanced monorepo build optimization

Mobile Development:

  • react-native-skills (v1.0.0) - React Native & Expo best practices with performance optimization patterns

Enhanced Authentication:

  • better-auth (v2.2.0) - Expanded to 18 framework integrations with 30+ authentication plugins

⚠️ Important: Token Limits

Skill Visibility Constraint

Claude Code has a 15,000 character limit for the total size of skill descriptions in the system prompt. This limit also applies to commands and agents.

What this means:

  • Not all 170 skills may be visible in Claude's context at once
  • Skills are loaded based on relevance and available token budget
  • You can verify how many skills Claude currently sees by asking: "How many skills do you see in your system prompt?"

Checking Visible Skills

To verify which skills are currently loaded:

# Ask Claude Code directly
"Check what skills/plugins you see in your system prompt"

Claude will report something like: "85 of 170 skills visible due to token limits"

Workaround: Increase Token Budget

You can double the headroom for skill descriptions by setting an environment variable:

# Increase limit to 30,000 characters
export SLASH_COMMAND_TOOL_CHAR_BUDGET=30000

# Then launch Claude Code
claude

This gives you approximately 2x more skill visibility in the system prompt.

Note: This is a temporary workaround. The Claude Code team is working on better solutions for skill discovery and loading.


Token Efficiency

MetricManual SetupWith SkillsSavings
Average Tokens12,000-15,0004,000-5,000~65%
Typical Errors2-4 per service0 (prevented)100%
Setup Time2-4 hours15-45 minutes~80%

Across all 170 skills: 400+ documented errors prevented.


Contributing

Prerequisites for Contributors

Install the official plugin development toolkit:

/plugin install plugin-dev@claude-code-marketplace

This provides:

  • /plugin-dev:create-plugin command (8-phase guided workflow)
  • 7 comprehensive skills (hooks, MCP, structure, agents, commands, skills)
  • 2 specialized agents (agent-creator, plugin-validator)

Quick Steps

  1. Create skill directory in plugins/
  2. Add SKILL.md with YAML frontmatter
  3. Run ./scripts/sync-plugins.sh
  4. Submit pull request

See CONTRIBUTING.md and PLUGIN_DEV_BEST_PRACTICES.md for detailed guidelines.


Documentation

DocumentPurpose
START_HERE.mdStart here! Quick navigation guide
PLUGIN_DEV_BEST_PRACTICES.mdRepository-specific best practices (marketplace, budget, quality)
MARKETPLACE.mdFull skill catalog and installation guide
MARKETPLACE_MANAGEMENT.mdTechnical infrastructure (plugin.json, scripts, validation)
CLAUDE.mdProject context and development standards
CONTRIBUTING.mdContribution guidelines

Links


Built with ❤️ by Claude Skills Maintainers

View source on GitHub