Skip to main content
A complete chat application built with @cloudflare/ai-chat showcasing the recommended patterns for building AI-powered chat agents.

What it demonstrates

Server (src/server.ts):
  • toUIMessageStreamResponse() - simplest streaming pattern
  • Server-side tools with execute (weather lookup)
  • Client-side tools without execute (browser timezone)
  • Tool approval with needsApproval (calculation with amount threshold)
  • pruneMessages() for managing LLM context in long conversations
  • maxPersistedMessages for storage management
  • MCP server connections and OAuth authentication
Client (src/client.tsx):
  • useAgentChat with onToolCall for client-side tool execution
  • addToolApprovalResponse for approve/reject UI
  • body option for sending custom data with every request
  • Tool part rendering (executing, completed, approval requested)
  • Kumo design system components

Server Implementation

src/server.ts

Key Features

Server-side Tools

Tools with an execute function run on the server:

Client-side Tools

Tools without execute are handled by the client via onToolCall:

Tool Approval

Require user confirmation before executing sensitive tools:
In the client, handle approval UI:

Message Pruning

Manage LLM context in long conversations:

Storage Management

Limit messages stored in SQLite:

Running the Example

1

Install dependencies

2

Start development server

3

Try it out

Visit http://localhost:5173 and try these prompts:
  • “What’s the weather in London?” (server-side tool)
  • “What timezone am I in?” (client-side tool)
  • “Calculate 150 * 3, amount is $450” (requires approval)
This example uses Workers AI (no API key needed) with the @cf/zai-org/glm-4.7-flash model.

Dynamic Tools

Client-defined tools for SDK/platform pattern

Codemode

LLMs write executable code instead of tool calls

MCP Client

Connect to MCP servers as a client

AI Chat Guide

In-depth guide to building AI chat agents