Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 29 additions & 29 deletions src/content/docs/agents/api-reference/agents-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,16 @@ flowchart TD
E --> F["onClose"]
```

| Method | When it runs |
| --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Method | When it runs |
| --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `onStart(props?)` | When the instance starts, or wakes from hibernation. Receives optional [initialization props](/agents/api-reference/routing/#props) passed via `getAgentByName` or `routeAgentRequest`. |
| `onRequest(request)` | For each HTTP request to the instance |
| `onConnect(connection, ctx)` | When a WebSocket connection is established |
| `onMessage(connection, message)` | For each WebSocket message received |
| `onError(connection, error)` | When a WebSocket error occurs |
| `onClose(connection, code, reason, wasClean)` | When a WebSocket connection closes |
| `onEmail(email)` | When an email is routed to the instance |
| `onStateChanged(state, source)` | When state changes (from server or client) |
| `onRequest(request)` | For each HTTP request to the instance |
| `onConnect(connection, ctx)` | When a WebSocket connection is established |
| `onMessage(connection, message)` | For each WebSocket message received |
| `onError(connection, error)` | When a WebSocket error occurs |
| `onClose(connection, code, reason, wasClean)` | When a WebSocket connection closes |
| `onEmail(email)` | When an email is routed to the instance |
| `onStateChanged(state, source)` | When state changes (from server or client) |

## Core properties

Expand All @@ -75,21 +75,21 @@ flowchart TD

## Server-side API reference

| Feature | Methods | Documentation |
| -------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------- |
| **State** | `setState()`, `onStateChanged()`, `initialState` | [Store and sync state](/agents/api-reference/store-and-sync-state/) |
| **Callable methods** | `@callable()` decorator | [Callable methods](/agents/api-reference/callable-methods/) |
| **Scheduling** | `schedule()`, `scheduleEvery()`, `getSchedules()`, `cancelSchedule()` | [Schedule tasks](/agents/api-reference/schedule-tasks/) |
| **Queue** | `queue()`, `dequeue()`, `dequeueAll()`, `getQueue()` | [Queue tasks](/agents/api-reference/queue-tasks/) |
| **WebSockets** | `onConnect()`, `onMessage()`, `onClose()`, `broadcast()` | [WebSockets](/agents/api-reference/websockets/) |
| **HTTP/SSE** | `onRequest()` | [HTTP and SSE](/agents/api-reference/http-sse/) |
| **Email** | `onEmail()`, `replyToEmail()` | [Email routing](/agents/api-reference/email/) |
| **Workflows** | `runWorkflow()`, `waitForApproval()` | [Run Workflows](/agents/api-reference/run-workflows/) |
| **MCP Client** | `addMcpServer()`, `removeMcpServer()`, `getMcpServers()` | [MCP Client API](/agents/api-reference/mcp-client-api/ ) |
| **AI Models** | Workers AI, OpenAI, Anthropic bindings | [Using AI models](/agents/api-reference/using-ai-models/) |
| **Protocol messages** | `shouldSendProtocolMessages()`, `isConnectionProtocolEnabled()` | [Protocol messages](/agents/api-reference/protocol-messages/) |
| **Context** | `getCurrentAgent()` | [getCurrentAgent()](/agents/api-reference/get-current-agent/) |
| **Observability** | `observability.emit()` | [Observability](/agents/api-reference/observability/) |
| Feature | Methods | Documentation |
| --------------------- | --------------------------------------------------------------------- | ------------------------------------------------------------------- |
| **State** | `setState()`, `onStateChanged()`, `initialState` | [Store and sync state](/agents/api-reference/store-and-sync-state/) |
| **Callable methods** | `@callable()` decorator | [Callable methods](/agents/api-reference/callable-methods/) |
| **Scheduling** | `schedule()`, `scheduleEvery()`, `getSchedules()`, `cancelSchedule()` | [Schedule tasks](/agents/api-reference/schedule-tasks/) |
| **Queue** | `queue()`, `dequeue()`, `dequeueAll()`, `getQueue()` | [Queue tasks](/agents/api-reference/queue-tasks/) |
| **WebSockets** | `onConnect()`, `onMessage()`, `onClose()`, `broadcast()` | [WebSockets](/agents/api-reference/websockets/) |
| **HTTP/SSE** | `onRequest()` | [HTTP and SSE](/agents/api-reference/http-sse/) |
| **Email** | `onEmail()`, `replyToEmail()` | [Email routing](/agents/api-reference/email/) |
| **Workflows** | `runWorkflow()`, `waitForApproval()` | [Run Workflows](/agents/api-reference/run-workflows/) |
| **MCP Client** | `addMcpServer()`, `removeMcpServer()`, `getMcpServers()` | [MCP Client API](/agents/api-reference/mcp-client-api/) |
| **AI Models** | Workers AI, OpenAI, Anthropic bindings | [Using AI models](/agents/api-reference/using-ai-models/) |
| **Protocol messages** | `shouldSendProtocolMessages()`, `isConnectionProtocolEnabled()` | [Protocol messages](/agents/api-reference/protocol-messages/) |
| **Context** | `getCurrentAgent()` | [getCurrentAgent()](/agents/api-reference/get-current-agent/) |
| **Observability** | `observability.emit()` | [Observability](/agents/api-reference/observability/) |

## SQL API

Expand All @@ -110,12 +110,12 @@ For state that needs to sync with clients, use the [State API](/agents/api-refer

## Client-side API reference

| Feature | Methods | Documentation |
| -------------------- | ---------------- | ----------------------------------------------- |
| **WebSocket client** | `AgentClient` | [Client SDK](/agents/api-reference/client-sdk/) |
| Feature | Methods | Documentation |
| -------------------- | ---------------- | ----------------------------------------------------------------------------- |
| **WebSocket client** | `AgentClient` | [Client SDK](/agents/api-reference/client-sdk/) |
| **HTTP client** | `agentFetch()` | [Client SDK](/agents/api-reference/client-sdk/#http-requests-with-agentfetch) |
| **React hook** | `useAgent()` | [Client SDK](/agents/api-reference/client-sdk/#react) |
| **Chat hook** | `useAgentChat()` | [Client SDK](/agents/api-reference/client-sdk/) |
| **React hook** | `useAgent()` | [Client SDK](/agents/api-reference/client-sdk/#react) |
| **Chat hook** | `useAgentChat()` | [Client SDK](/agents/api-reference/client-sdk/) |

### Quick example

Expand Down
17 changes: 7 additions & 10 deletions src/content/docs/agents/api-reference/browse-the-web.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,17 @@ Agents can browse the web using the [Browser Rendering](/browser-rendering/) API

The [Browser Rendering](/browser-rendering/) allows you to spin up headless browser instances, render web pages, and interact with websites through your Agent.

You can define a method that uses Puppeteer to pull the content of a web page, parse the DOM, and extract relevant information by calling the OpenAI model:
You can define a method that uses Puppeteer to pull the content of a web page, parse the DOM, and extract relevant information by calling a model via [Workers AI](/workers-ai/):

<TypeScriptExample>

```ts
interface Env {
BROWSER: Fetcher;
AI: Ai;
}

export class MyAgent extends Agent {
export class MyAgent extends Agent<Env> {
async browse(browserInstance: Fetcher, urls: string[]) {
let responses = [];
for (const url of urls) {
Expand All @@ -42,21 +43,14 @@ export class MyAgent extends Agent {
"body",
(element) => element.innerHTML,
);
const client = new OpenAI({
apiKey: this.env.OPENAI_API_KEY,
});

let resp = await client.chat.completions.create({
model: this.env.MODEL,
let resp = await this.env.AI.run("@cf/zai-org/glm-4.7-flash", {
messages: [
{
role: "user",
content: `Return a JSON object with the product names, prices and URLs with the following format: { "name": "Product Name", "price": "Price", "url": "URL" } from the website content below. <content>${bodyContent}</content>`,
},
],
response_format: {
type: "json_object",
},
});

responses.push(resp);
Expand All @@ -79,6 +73,9 @@ You'll also need to add install the `@cloudflare/puppeteer` package and add the
```jsonc
{
// ...
"ai": {
"binding": "AI",
},
"browser": {
"binding": "MYBROWSER",
},
Expand Down
10 changes: 5 additions & 5 deletions src/content/docs/agents/api-reference/chat-agents.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -675,11 +675,11 @@

### Three patterns

| Pattern | How | Persisted? | Use case |
| --- | --- | --- | --- |
| **Reconciliation** | Same `type` + `id` → updates in-place | Yes | Progressive state (searching → found) |
| **Append** | No `id`, or different `id` → appends | Yes | Log entries, multiple citations |
| **Transient** | `transient: true` → not added to `message.parts` | No | Ephemeral status (thinking indicator) |
| Pattern | How | Persisted? | Use case |
| ------------------ | ------------------------------------------------ | ---------- | ------------------------------------- |
| **Reconciliation** | Same `type` + `id` → updates in-place | Yes | Progressive state (searching → found) |
| **Append** | No `id`, or different `id` → appends | Yes | Log entries, multiple citations |
| **Transient** | `transient: true` → not added to `message.parts` | No | Ephemeral status (thinking indicator) |

Transient parts are broadcast to connected clients in real time but excluded from SQLite persistence and `message.parts`. Use the `onData` callback to consume them.

Expand Down Expand Up @@ -860,7 +860,7 @@

const anthropic = createAnthropic({ apiKey: this.env.ANTHROPIC_API_KEY });
const result = streamText({
model: anthropic("claude-sonnet-4-20250514"),

Check warning on line 863 in src/content/docs/agents/api-reference/chat-agents.mdx

View workflow job for this annotation

GitHub Actions / Semgrep

semgrep.style-guide-potential-date-year

Potential year found. Documentation should strive to represent universal truth, not something time-bound. (add [skip style guide checks] to commit message to skip)
messages: await convertToModelMessages(this.messages),
});
```
Expand Down
6 changes: 3 additions & 3 deletions src/content/docs/agents/api-reference/email.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -316,9 +316,9 @@

```jsonc
{
"vars": {
"EMAIL_SECRET": "change-me-in-production",
},
"vars": {
"EMAIL_SECRET": "change-me-in-production",
},
}
```

Expand Down Expand Up @@ -508,7 +508,7 @@
| Option | Description |
| -------------------- | ------------------------------------------------------------------------ |
| `secret` | Secret key for HMAC verification (must match the key used to sign) |
| `maxAge` | Maximum age of signature in seconds (default: 30 days / 2592000 seconds) |

Check warning on line 511 in src/content/docs/agents/api-reference/email.mdx

View workflow job for this annotation

GitHub Actions / Semgrep

semgrep.style-guide-potential-date-year

Potential year found. Documentation should strive to represent universal truth, not something time-bound. (add [skip style guide checks] to commit message to skip)
| `onInvalidSignature` | Optional callback for logging when signature verification fails |

### `signAgentHeaders`
Expand Down
14 changes: 8 additions & 6 deletions src/content/docs/agents/api-reference/http-sse.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -115,18 +115,20 @@ The [AI SDK](https://sdk.vercel.ai/) provides built-in SSE streaming:
```ts
import { Agent } from "agents";
import { streamText } from "ai";
import { createOpenAI } from "@ai-sdk/openai";
import { createWorkersAI } from "workers-ai-provider";

export class ChatAgent extends Agent {
interface Env {
AI: Ai;
}

export class ChatAgent extends Agent<Env> {
async onRequest(request: Request): Promise<Response> {
const { prompt } = await request.json<{ prompt: string }>();

const openai = createOpenAI({
apiKey: this.env.OPENAI_API_KEY,
});
const workersai = createWorkersAI({ binding: this.env.AI });

const result = streamText({
model: openai("gpt-4o"),
model: workersai("@cf/zai-org/glm-4.7-flash"),
prompt: prompt,
});

Expand Down
2 changes: 1 addition & 1 deletion src/content/docs/agents/api-reference/mcp-agent-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ You can use the APIs below in order to do so.
| `state` | Current state object (persisted) |
| `initialState` | Default state when instance starts |
| `setState(state)` | Update and persist state |
| `onStateChanged(state)` | Called when state changes |
| `onStateChanged(state)` | Called when state changes |
| `sql` | Execute SQL queries on embedded database |
| `server` | The `McpServer` instance for registering tools |
| `props` | User identity and tokens from OAuth authentication |
Expand Down
31 changes: 13 additions & 18 deletions src/content/docs/agents/api-reference/mcp-client-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -161,14 +161,8 @@ class MyAgent extends Agent {
);

if (result.state === "authenticating") {
// Option 1: Redirect the user
// Redirect the user to the OAuth authorization page
return Response.redirect(result.authUrl);

// Option 2: Return the URL for client-side redirect
return Response.json({
status: "needs_auth",
authUrl: result.authUrl,
});
}

return Response.json({ status: "connected", id: result.id });
Expand Down Expand Up @@ -345,14 +339,15 @@ To use MCP tools with the Vercel AI SDK, use `this.mcp.getAITools()` which conve

```ts
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";
import { createWorkersAI } from "workers-ai-provider";

export class MyAgent extends Agent {
export class MyAgent extends Agent<Env> {
async onRequest(request: Request) {
const workersai = createWorkersAI({ binding: this.env.AI });
const response = await generateText({
model: openai("gpt-4"),
model: workersai("@cf/zai-org/glm-4.7-flash"),
prompt: "What's the weather in San Francisco?",
tools: this.mcp.getAITools(), // Converts MCP tools to AI SDK format
tools: this.mcp.getAITools(),
});

return new Response(response.text);
Expand Down Expand Up @@ -633,26 +628,26 @@ The override is used for both new connections (`addMcpServer`) and restored conn
import { Agent } from "agents";
import type { AgentMcpOAuthProvider } from "agents";

export class MyAgent extends Agent {
export class MyAgent extends Agent<Env> {
createMcpOAuthProvider(callbackUrl: string): AgentMcpOAuthProvider {
const env = this.env;
return {
get redirectUrl() {
return callbackUrl;
},
get clientMetadata() {
return {
client_id: this.env.MCP_CLIENT_ID,
client_secret: this.env.MCP_CLIENT_SECRET,
client_id: env.MCP_CLIENT_ID,
client_secret: env.MCP_CLIENT_SECRET,
redirect_uris: [callbackUrl],
};
},
clientInformation() {
return {
client_id: this.env.MCP_CLIENT_ID,
client_secret: this.env.MCP_CLIENT_SECRET,
client_id: env.MCP_CLIENT_ID,
client_secret: env.MCP_CLIENT_SECRET,
};
},
// ... implement other AgentMcpOAuthProvider methods
};
}
}
Expand Down Expand Up @@ -831,7 +826,7 @@ Use error detection utilities to handle connection errors:
<TypeScriptExample>

```ts
import { isUnauthorized, isTransportNotImplemented } from "agents/mcp";
import { isUnauthorized, isTransportNotImplemented } from "agents";

export class MyAgent extends Agent {
async onRequest(request: Request) {
Expand Down
Loading
Loading