Skip to content
Open
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
3 changes: 2 additions & 1 deletion public/__redirects
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,8 @@
/agents/concepts/long-running-agents/ /agents/concepts/agentic-patterns/long-running-agents/ 301
/agents/api-reference/agents-api/ /agents/runtime/agents-api/ 301
/agents/api-reference/ /agents/runtime/ 301
/agents/api-reference/chat-sdk/ /agents/runtime/execution/chat-sdk/ 301
/agents/api-reference/chat-sdk/ /agents/runtime/communication/chat-sdk/ 301
Comment thread
thomasgauvin marked this conversation as resolved.
/agents/runtime/execution/chat-sdk/ /agents/runtime/communication/chat-sdk/ 301
/agents/api-reference/agent-tools/ /agents/runtime/execution/agent-tools/ 301
/agents/api-reference/browse-the-web/ /agents/tools/browser/ 301
/agents/api-reference/callable-methods/ /agents/runtime/lifecycle/callable-methods/ 301
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1582,7 +1582,7 @@ export class ChatAgent extends AIChatAgent {
:::note
This section covers **in-process** subagents using the AI SDK's `ToolLoopAgent`. For **Durable Object sub-agents** with their own isolated storage and typed RPC, refer to [Sub-agents](/agents/runtime/execution/sub-agents/). To run Think or `AIChatAgent` sub-agents as retained, streaming tools, refer to [Agent tools](/agents/runtime/execution/agent-tools/).
This section covers **in-process** subagents using the AI SDK's `ToolLoopAgent`. For **Durable Object sub-agents** with their own isolated storage and typed RPC, refer to [Sub-agents](/agents/runtime/execution/sub-agents/). To run Think or `AIChatAgent` sub-agents as retained, streaming tools, refer to [Agents as tools](/agents/runtime/execution/agent-tools/).
:::
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ client.addEventListener("message", () => {});

## Agent-tool events

If your chat UI renders retained child runs from [Agent tools](/agents/runtime/execution/agent-tools/), use `useAgentToolEvents()` alongside `useAgent()` and `useAgentChat()`. The hook subscribes to the parent connection, replays retained child timelines, and groups runs by parent tool call ID.
If your chat UI renders retained child runs from [Agents as tools](/agents/runtime/execution/agent-tools/), use `useAgentToolEvents()` alongside `useAgent()` and `useAgentChat()`. The hook subscribes to the parent connection, replays retained child timelines, and groups runs by parent tool call ID.

<TypeScriptExample>

Expand Down
10 changes: 5 additions & 5 deletions src/content/docs/agents/concepts/tools.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ Tools enable AI systems to interact with external services and perform actions.

Cloudflare Agents support several tool patterns. Choose the smallest one that fits the job:

| Pattern | Use when | Start here |
| ----------------- | ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
| Pattern | Use when | Start here |
| ----------------- | ----------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| Server-side tools | The tool can run entirely in the Worker, such as fetching an API or querying SQL | [Chat agents](/agents/communication-channels/chat/chat-agents/#server-side-tools) |
| Client-side tools | The tool needs browser APIs such as geolocation, clipboard, or local storage | [Chat agents](/agents/communication-channels/chat/chat-agents/#client-side-tools) |
| Human approvals | The tool is sensitive and needs a user decision before it runs | [Human-in-the-loop](/agents/concepts/agentic-patterns/human-in-the-loop/) |
| MCP tools | You want to expose or consume tools through the Model Context Protocol | [Model Context Protocol](/agents/model-context-protocol/) |
| Agent tools | You want a chat agent to run another chat-capable sub-agent as a retained, streaming tool | [Agent tools](/agents/runtime/execution/agent-tools/) |
| Human approvals | The tool is sensitive and needs a user decision before it runs | [Human-in-the-loop](/agents/concepts/agentic-patterns/human-in-the-loop/) |
| MCP tools | You want to expose or consume tools through the Model Context Protocol | [Model Context Protocol](/agents/model-context-protocol/) |
| Agents as tools | You want a chat agent to run another chat-capable sub-agent as a retained, streaming tool | [Agents as tools](/agents/runtime/execution/agent-tools/) |

### Understanding tools

Expand Down
213 changes: 15 additions & 198 deletions src/content/docs/agents/getting-started/add-to-existing-project.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {
PackageManagers,
TypeScriptExample,
WranglerConfig,
LinkCard,
Render,
} from "~/components";

This guide shows how to add agents to an existing Cloudflare Workers project. If you are starting fresh, refer to [Building a chat agent](/agents/examples/chat-agent/) instead.
Expand Down Expand Up @@ -304,6 +304,12 @@ function CounterWidget() {

</TypeScriptExample>

Key points:

- `useAgent` connects to your agent via WebSocket
- `onStateUpdate` fires whenever the agent's state changes
- `agent.stub.methodName()` calls methods marked with `@callable()` on your agent

### Vanilla JavaScript

<TypeScriptExample>
Expand All @@ -325,207 +331,18 @@ document.getElementById("increment").onclick = () => agent.call("increment");

</TypeScriptExample>

## Adding multiple agents

Add more agents by extending the configuration:

<TypeScriptExample>

```ts
// src/agents/chat.ts
export class Chat extends Agent {
// ...
}

// src/agents/scheduler.ts
export class Scheduler extends Agent {
// ...
}
```

</TypeScriptExample>

Update the Wrangler configuration file:

<WranglerConfig>

```jsonc
{
"durable_objects": {
"bindings": [
{ "name": "CounterAgent", "class_name": "CounterAgent" },
{ "name": "Chat", "class_name": "Chat" },
{ "name": "Scheduler", "class_name": "Scheduler" },
],
},
"migrations": [
{
"tag": "v1",
"new_sqlite_classes": ["CounterAgent", "Chat", "Scheduler"],
},
],
}
```

</WranglerConfig>

Export all agents from your entry point:

<TypeScriptExample>

```ts
export { CounterAgent } from "./agents/counter";
export { Chat } from "./agents/chat";
export { Scheduler } from "./agents/scheduler";
```

</TypeScriptExample>

## Common integration patterns

### Agents behind authentication
<Render file="what-just-happened" product="agents" />

Check auth before routing to agents:

<TypeScriptExample>

```ts
export default {
async fetch(request: Request, env: Env) {
// Check auth for agent routes
if (request.url.includes("/agents/")) {
const authResult = await checkAuth(request, env);
if (!authResult.valid) {
return new Response("Unauthorized", { status: 401 });
}
}

const agentResponse = await routeAgentRequest(request, env);
if (agentResponse) return agentResponse;

// ... rest of routing
},
} satisfies ExportedHandler<Env>;
```

</TypeScriptExample>
## Deploy to Cloudflare

### Custom agent path prefix

By default, agents are routed at `/agents/{agent-name}/{instance-name}`. You can customize this:

<TypeScriptExample>

```ts
import { routeAgentRequest } from "agents";

const agentResponse = await routeAgentRequest(request, env, {
prefix: "/api/agents", // Now routes at /api/agents/{agent-name}/{instance-name}
});
```

</TypeScriptExample>

Refer to [Routing](/agents/runtime/communication/routing/) for more options including CORS, custom instance naming, and location hints.

### Accessing agents from server code

You can interact with agents directly from your Worker code:

<TypeScriptExample>

```ts
import { getAgentByName } from "agents";

export default {
async fetch(request: Request, env: Env) {
if (request.url.endsWith("/api/increment")) {
// Get a specific agent instance
const counter = await getAgentByName(env.CounterAgent, "shared-counter");
const newCount = await counter.increment();
return Response.json({ count: newCount });
}
// ...
},
} satisfies ExportedHandler<Env>;
```

</TypeScriptExample>

## Troubleshooting

### Agent not found, or 404 errors

1. **Check the export** - Agent class must be exported from your main entry point.
2. **Check the binding** - `class_name` in the Wrangler configuration file must exactly match the exported class name.
3. **Check the route** - Default route is `/agents/{agent-name}/{instance-name}`.

### No such Durable Object class error

Add the migration to the Wrangler configuration file:

<WranglerConfig>

```jsonc
{
"migrations": [
{
"tag": "v1",
"new_sqlite_classes": ["YourAgentClass"],
},
],
}
```

</WranglerConfig>

### WebSocket connection fails

Ensure your routing passes the response unchanged:

<TypeScriptExample>

```ts
// Correct - return the response directly
const agentResponse = await routeAgentRequest(request, env);
if (agentResponse) return agentResponse;

// Wrong - this breaks WebSocket connections
if (agentResponse) return new Response(agentResponse.body);
```sh
npm run deploy
```

</TypeScriptExample>

### State not persisting

Check that:

1. You are using `this.setState()`, not mutating `this.state` directly.
2. The agent class is in `new_sqlite_classes` in migrations.
3. You are connecting to the same agent instance name.

## Next steps

<LinkCard
title="State management"
href="/agents/runtime/lifecycle/state/"
description="Manage and synchronize agent state."
/>
Your agent is now live on Cloudflare's global network, running close to your users.

<LinkCard
title="Schedule tasks"
href="/agents/runtime/execution/schedule-tasks/"
description="Background tasks and cron jobs."
/>
<Render file="common-integration-patterns" product="agents" />

<LinkCard
title="Agent class internals"
href="/agents/runtime/lifecycle/agent-class/"
description="Full lifecycle and methods reference."
/>
<Render file="troubleshooting" product="agents" />

<LinkCard
title="Agents API"
href="/agents/runtime/agents-api/"
description="Complete API reference for the Agents SDK."
/>
<Render file="next-steps" product="agents" />
Loading