diff --git a/public/__redirects b/public/__redirects index 315c62644d3..dd31c18fd32 100644 --- a/public/__redirects +++ b/public/__redirects @@ -198,25 +198,120 @@ /aegis/analytics/ /smart-shield/configuration/dedicated-egress-ips/ips-utilization/ 301 # agents -/agents/api-reference/think/ /agents/think/ 301 +/agents/api-reference/think/ /agents/harnesses/think/ 301 +/agents/think/ /agents/harnesses/think/ 301 /agents/build/prompts/ /workers/get-started/prompting/ 301 -/agents/examples/browse-the-web/ /agents/api-reference/browse-the-web/ 301 -/agents/examples/manage-and-sync-state/ /agents/api-reference/store-and-sync-state/ 301 -/agents/examples/rag/ /agents/api-reference/rag/ 301 -/agents/examples/run-workflows/ /agents/api-reference/run-workflows/ 301 -/agents/examples/schedule-tasks/ /agents/api-reference/schedule-tasks/ 301 -/agents/examples/using-ai-models/ /agents/api-reference/using-ai-models/ 301 -/agents/examples/websockets/ /agents/api-reference/websockets/ 301 -/agents/examples/sdk/ /agents/api-reference/agents-api/ 301 -/agents/examples/build-mcp-server/ /agents/guides/remote-mcp-server/ 301 -/agents/api-reference/build-mcp-server/ /agents/guides/remote-mcp-server/ 301 -/agents/api-reference/sdk/ /agents/api-reference/ 301 -/agents/guides/build-mcp-server/ /agents/guides/remote-mcp-server/ 301 +/agents/getting-started/build-a-chat-agent/ /agents/examples/chat-agent/ 301 +/agents/examples/browse-the-web/ /agents/tools/browser/ 301 +/agents/examples/manage-and-sync-state/ /agents/runtime/lifecycle/state/ 301 +/agents/examples/rag/ /agents/tools/ai-search/ 301 +/agents/tools/rag/ /agents/tools/ai-search/ 301 +/agents/examples/run-workflows/ /agents/runtime/execution/run-workflows/ 301 +/agents/examples/schedule-tasks/ /agents/runtime/execution/schedule-tasks/ 301 +/agents/examples/using-ai-models/ /agents/runtime/operations/using-ai-models/ 301 +/agents/examples/websockets/ /agents/runtime/communication/websockets/ 301 +/agents/examples/sdk/ /agents/runtime/agents-api/ 301 +/agents/examples/build-mcp-server/ /agents/model-context-protocol/guides/remote-mcp-server/ 301 +/agents/api-reference/build-mcp-server/ /agents/model-context-protocol/guides/remote-mcp-server/ 301 +/agents/api-reference/sdk/ /agents/runtime/agents-api/ 301 +/agents/guides/build-mcp-server/ /agents/model-context-protocol/guides/remote-mcp-server/ 301 /agents/capabilities/mcp-server/ /agents/model-context-protocol/ 301 -/agents/model-context-protocol/mcp-agent-api/ /agents/api-reference/mcp-agent-api/ 301 -/agents/model-context-protocol/mcp-client-api/ /agents/api-reference/mcp-client-api/ 301 -/agents/model-context-protocol/mcp-handler-api/ /agents/api-reference/mcp-handler-api/ 301 -/agents/api-reference/calling-agents/ /agents/api-reference/routing/ 301 +/agents/model-context-protocol/mcp-agent-api/ /agents/model-context-protocol/apis/agent-api/ 301 +/agents/model-context-protocol/mcp-client-api/ /agents/model-context-protocol/apis/client-api/ 301 +/agents/model-context-protocol/mcp-handler-api/ /agents/model-context-protocol/apis/handler-api/ 301 +/agents/api-reference/calling-agents/ /agents/runtime/communication/routing/ 301 +/agents/community-mcp-server/ /agents/model-context-protocol/cloudflare/servers-for-cloudflare/community-mcp-server/ 301 +/agents/patterns/ /agents/concepts/agentic-patterns/ 301 +/agents/concepts/patterns/ /agents/concepts/agentic-patterns/ 301 +/agents/concepts/anthropic-agent-patterns/ /agents/concepts/agentic-patterns/ 301 +/agents/concepts/human-in-the-loop/ /agents/concepts/agentic-patterns/human-in-the-loop/ 301 +/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/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 +/agents/api-reference/chat-agents/ /agents/communication-channels/chat/chat-agents/ 301 +/agents/api-reference/client-sdk/ /agents/communication-channels/chat/client-sdk/ 301 +/agents/api-reference/codemode/ /agents/model-context-protocol/protocol/codemode/ 301 +/agents/api-reference/configuration/ /agents/runtime/operations/configuration/ 301 +/agents/api-reference/durable-execution/ /agents/runtime/execution/durable-execution/ 301 +/agents/api-reference/email/ /agents/communication-channels/email/ 301 +/agents/api-reference/get-current-agent/ /agents/runtime/lifecycle/get-current-agent/ 301 +/agents/api-reference/http-sse/ /agents/runtime/communication/http-sse/ 301 +/agents/api-reference/mcp-agent-api/ /agents/model-context-protocol/apis/agent-api/ 301 +/agents/api-reference/mcp-client-api/ /agents/model-context-protocol/apis/client-api/ 301 +/agents/api-reference/mcp-handler-api/ /agents/model-context-protocol/apis/handler-api/ 301 +/agents/api-reference/observability/ /agents/runtime/operations/observability/ 301 +/agents/api-reference/protocol-messages/ /agents/runtime/communication/protocol-messages/ 301 +/agents/api-reference/queue-tasks/ /agents/runtime/execution/queue-tasks/ 301 +/agents/api-reference/rag/ /agents/tools/ai-search/ 301 +/agents/api-reference/readonly-connections/ /agents/runtime/communication/readonly-connections/ 301 +/agents/api-reference/retries/ /agents/runtime/execution/retries/ 301 +/agents/api-reference/routing/ /agents/runtime/communication/routing/ 301 +/agents/api-reference/run-workflows/ /agents/runtime/execution/run-workflows/ 301 +/agents/api-reference/schedule-tasks/ /agents/runtime/execution/schedule-tasks/ 301 +/agents/api-reference/sessions/ /agents/runtime/lifecycle/sessions/ 301 +/agents/api-reference/store-and-sync-state/ /agents/runtime/lifecycle/state/ 301 +/agents/api-reference/sub-agents/ /agents/runtime/execution/sub-agents/ 301 +/agents/api-reference/using-ai-models/ /agents/runtime/operations/using-ai-models/ 301 +/agents/api-reference/voice/ /agents/communication-channels/voice/ 301 +/agents/api-reference/websockets/ /agents/runtime/communication/websockets/ 301 +/agents/guides/anthropic-agent-patterns/ /agents/concepts/agentic-patterns/ 301 +/agents/guides/autonomous-responses/ /agents/communication-channels/chat/autonomous-responses/ 301 +/agents/guides/build-a-voice-agent/ /agents/examples/voice-agent/ 301 +/agents/guides/build-mcp-client/ /agents/model-context-protocol/guides/build-mcp-client/ 301 +/agents/guides/chatgpt-app/ /workers/demos/chatgpt-app/ 301 +/agents/communication-channels/chat/chatgpt-app/ /workers/demos/chatgpt-app/ 301 +/agents/guides/connect-mcp-client/ /agents/model-context-protocol/guides/connect-mcp-client/ 301 +/agents/guides/cross-domain-authentication/ /agents/runtime/operations/cross-domain-authentication/ 301 +/agents/guides/human-in-the-loop/ /agents/concepts/agentic-patterns/human-in-the-loop/ 301 +/agents/guides/oauth-mcp-client/ /agents/model-context-protocol/guides/oauth-mcp-client/ 301 +/agents/guides/push-notifications/ /agents/communication-channels/webhooks/push-notifications/ 301 +/agents/guides/remote-mcp-server/ /agents/model-context-protocol/guides/remote-mcp-server/ 301 +/agents/guides/securing-mcp-server/ /agents/model-context-protocol/guides/securing-mcp-server/ 301 +/agents/guides/slack-agent/ /agents/examples/slack-agent/ 301 +/agents/guides/test-remote-mcp-server/ /agents/model-context-protocol/guides/test-remote-mcp-server/ 301 +/agents/guides/webhooks/ /agents/communication-channels/webhooks/ 301 +/agents/model-context-protocol/authorization/ /agents/model-context-protocol/protocol/authorization/ 301 +/agents/model-context-protocol/governance/ /agents/model-context-protocol/protocol/governance/ 301 +/agents/model-context-protocol/mcp-portal/ /agents/model-context-protocol/cloudflare/mcp-portal/ 301 +/agents/model-context-protocol/mcp-servers-for-cloudflare/ /agents/model-context-protocol/cloudflare/servers-for-cloudflare/ 301 +/agents/model-context-protocol/mcp-servers-for-cloudflare/community-mcp-server/ /agents/model-context-protocol/cloudflare/servers-for-cloudflare/community-mcp-server/ 301 +/agents/model-context-protocol/tools/ /agents/model-context-protocol/protocol/tools/ 301 +/agents/model-context-protocol/transport/ /agents/model-context-protocol/protocol/transport/ 301 +/agents/agentic-payments/ /agents/tools/payments/ 301 +/agents/agentic-payments/x402/ /agents/tools/payments/x402/ 301 +/agents/agentic-payments/x402/charge-for-http-content/ /agents/tools/payments/x402/charge-for-http-content/ 301 +/agents/agentic-payments/x402/charge-for-mcp-tools/ /agents/tools/payments/x402/charge-for-mcp-tools/ 301 +/agents/agentic-payments/x402/pay-from-agents-sdk/ /agents/tools/payments/x402/pay-from-agents-sdk/ 301 +/agents/agentic-payments/x402/pay-with-tool-plugins/ /agents/tools/payments/x402/pay-with-tool-plugins/ 301 +/agents/agentic-payments/mpp/ /agents/tools/payments/mpp/ 301 +/agents/guides/ /agents/model-context-protocol/guides/ 301 +/agents/concepts/agent-class/ /agents/runtime/lifecycle/agent-class/ 301 +/agents/concepts/memory/ /agents/concepts/conversation-state-and-memory/ 301 +/agents/getting-started/prompting/ /workers/get-started/prompting/ 301 +/agents/platform/prompting/ /workers/get-started/prompting/ 301 +/agents/platform/prompt.txt/ /workers/prompt.txt 301 +/agents/channels/chat/ /agents/communication-channels/chat/ 301 +/agents/channels/chat/chat-agents/ /agents/communication-channels/chat/chat-agents/ 301 +/agents/channels/chat/client-sdk/ /agents/communication-channels/chat/client-sdk/ 301 +/agents/channels/chat/autonomous-responses/ /agents/communication-channels/chat/autonomous-responses/ 301 +/agents/channels/chat/chatgpt-app/ /workers/demos/chatgpt-app/ 301 +/agents/channels/voice/ /agents/communication-channels/voice/ 301 +/agents/channels/voice/build-a-voice-agent/ /agents/examples/voice-agent/ 301 +/agents/channels/email/ /agents/communication-channels/email/ 301 +/agents/channels/slack/ /agents/communication-channels/slack/ 301 +/agents/channels/slack/slack-agent/ /agents/examples/slack-agent/ 301 +/agents/channels/webhooks/ /agents/communication-channels/webhooks/ 301 +/agents/channels/webhooks/push-notifications/ /agents/communication-channels/webhooks/push-notifications/ 301 +/agents/communication-channels/voice/build-a-voice-agent/ /agents/examples/voice-agent/ 301 +/agents/communication-channels/slack/slack-agent/ /agents/examples/slack-agent/ 301 +/agents/tools/browser/browse-the-web/ /agents/tools/browser/ 301 +/agents/tools/sandbox/codemode/ /agents/model-context-protocol/protocol/codemode/ 301 +/agents/tools/payments/mpp/charge-for-http-content/ /agents/tools/payments/mpp-charge-for-http-content/ 301 +/agents/agentic-payments/mpp/charge-for-http-content/ /agents/tools/payments/mpp-charge-for-http-content/ 301 # ai-audit /ai-audit/features/detect-ai-crawlers/ /ai-crawl-control/features/analyze-ai-crawlers/ 301 @@ -2589,6 +2684,7 @@ # ============================================================================ # DYNAMIC REDIRECTS +/agents/think/* /agents/harnesses/think/:splat 301 # ============================================================================ # Agent Skills legacy discovery path @@ -2819,7 +2915,7 @@ /cloudflare-one/team-and-resources/devices/warp/* /cloudflare-one/team-and-resources/devices/cloudflare-one-client/:splat 301 # Agents x402 (moved under agentic-payments) -/agents/x402/* /agents/agentic-payments/x402/:splat 301 +/agents/x402/* /agents/tools/payments/x402/:splat 301 # AI Gateway models (unified under /ai/models/) /ai-gateway/models/* /ai/models/:splat 301 diff --git a/src/components/AgentsPlatformDiagram.astro b/src/components/AgentsPlatformDiagram.astro new file mode 100644 index 00000000000..f790be4d74f --- /dev/null +++ b/src/components/AgentsPlatformDiagram.astro @@ -0,0 +1,412 @@ +--- +const channels = [ + { type: "Chat", name: "AIChatAgent", href: "/agents/communication-channels/chat/" }, + { type: "Email", name: "onEmail", href: "/agents/communication-channels/email/" }, + { type: "Voice", name: "withVoice", href: "/agents/communication-channels/voice/" }, + { type: "Slack", name: "Events", href: "/agents/communication-channels/slack/" }, + { type: "Webhook", name: "HTTP", href: "/agents/communication-channels/webhooks/" }, +]; + +const runtime = [ + { label: "State", href: "/agents/runtime/lifecycle/state/" }, + { label: "Sessions", href: "/agents/runtime/lifecycle/sessions/" }, + { label: "Routing", href: "/agents/runtime/communication/routing/" }, + { label: "WebSockets", href: "/agents/runtime/communication/websockets/" }, + { label: "Scheduling", href: "/agents/runtime/execution/schedule-tasks/" }, + { label: "Fibers", href: "/agents/runtime/execution/durable-execution/" }, +]; + +const tools = [ + { type: "Sandbox", name: "Bash/Shell", href: "/agents/tools/sandbox/" }, + { type: "MCP", name: "Servers", href: "/agents/tools/mcp/" }, + { type: "Browser", name: "CDP", href: "/agents/tools/browser/" }, + { type: "AI Search", name: "Retrieval", href: "/agents/tools/ai-search/" }, + { type: "Payments", name: "x402 · MPP", href: "/agents/tools/payments/" }, +]; +--- + +
+
+ + +
+
+
Channels
+ {channels.length} +
+
+ {channels.map((item) => ( + {item.type} + ))} +
+
+ +
+
+
+ +
Agent
+ +
+ +
+
+
Agent harness
+

Controls planning, tool use, and response flow.

+
+ +
+ +
+
+
Agents SDK runtime
+

Durable identity, state, connections, scheduling, and recovery.

+
+ Agent class +
+ {runtime.map((item) => {item.label})} +
+
+
+
+ +
+
+
Tools
+ {tools.length} +
+
+ {tools.map((item) => ( + {item.type} + ))} +
+
+ + + Observability + Logs · metrics · traces + +
+
+ + diff --git a/src/components/agent-setup/PlatformAccessSection.astro b/src/components/agent-setup/PlatformAccessSection.astro index ca1c8625b1b..1864103d7d4 100644 --- a/src/components/agent-setup/PlatformAccessSection.astro +++ b/src/components/agent-setup/PlatformAccessSection.astro @@ -45,7 +45,7 @@ import SkillsList from "./SkillsList.astro"; cloudflare/mcp-server-cloudflare {" "} repo. The full catalog is also in the{" "} - + MCP servers for Cloudflare {" "} docs. diff --git a/src/components/index.ts b/src/components/index.ts index 4780cf5faab..92bd51cdffa 100644 --- a/src/components/index.ts +++ b/src/components/index.ts @@ -6,6 +6,7 @@ export { Icon as AstroIcon } from "astro-icon/components"; // Custom components export { default as AnchorHeading } from "./AnchorHeading.astro"; export { default as AnimatedWorkflowDiagram } from "./AnimatedWorkflowDiagram.astro"; +export { default as AgentsPlatformDiagram } from "./AgentsPlatformDiagram.astro"; export { default as APIRequest } from "./APIRequest.astro"; export { default as AutoconfigDiagram } from "./AutoconfigDiagram.astro"; export { default as AvailableNotifications } from "./AvailableNotifications.astro"; diff --git a/src/content/changelog/access/2026-03-26-mcp-portal-code-mode.mdx b/src/content/changelog/access/2026-03-26-mcp-portal-code-mode.mdx index b3858b1df60..afc411be4de 100644 --- a/src/content/changelog/access/2026-03-26-mcp-portal-code-mode.mdx +++ b/src/content/changelog/access/2026-03-26-mcp-portal-code-mode.mdx @@ -6,7 +6,7 @@ products: - access --- -[MCP server portals](/cloudflare-one/access-controls/ai-controls/mcp-portals/) support [code mode](/agents/api-reference/codemode/), a technique that reduces context window usage by replacing individual tool definitions with a single code execution tool. Code mode is turned on by default on all portals. +[MCP server portals](/cloudflare-one/access-controls/ai-controls/mcp-portals/) support [code mode](/agents/model-context-protocol/protocol/codemode/), a technique that reduces context window usage by replacing individual tool definitions with a single code execution tool. Code mode is turned on by default on all portals. To turn it off, edit the portal in **Access controls** > **AI controls** and turn off **Code mode** under **Basic information**. diff --git a/src/content/changelog/agents/2025-03-18-npm-i-agents.mdx b/src/content/changelog/agents/2025-03-18-npm-i-agents.mdx index dbfc550056c..1fdb6fb9928 100644 --- a/src/content/changelog/agents/2025-03-18-npm-i-agents.mdx +++ b/src/content/changelog/agents/2025-03-18-npm-i-agents.mdx @@ -68,7 +68,7 @@ export default { #### Call Agent methods from your client code -We've added a new [`@unstable_callable()`](/agents/api-reference/agents-api/) decorator for defining methods that can be called directly from clients. This allows you call methods from within your client code: you can call methods (with arguments) and get native JavaScript objects back. +We've added a new [`@unstable_callable()`](/agents/runtime/agents-api/) decorator for defining methods that can be called directly from clients. This allows you call methods from within your client code: you can call methods (with arguments) and get native JavaScript objects back. @@ -127,9 +127,9 @@ You can use the starter as a template for your own Agents projects: open up `src We've heard your feedback on the Agents SDK documentation, and we're shipping more API reference material and usage examples, including: -- Expanded [API reference documentation](/agents/api-reference/), covering the methods and properties exposed by the Agents SDK, as well as more usage examples. -- More [Client API](/agents/api-reference/agents-api/#client-api) documentation that documents `useAgent`, `useAgentChat` and the new `@unstable_callable` RPC decorator exposed by the SDK. -- New documentation on how to [route requests to agents](/agents/api-reference/routing/) and (optionally) authenticate clients before they connect to your Agents. +- Expanded [API reference documentation](/agents/runtime/), covering the methods and properties exposed by the Agents SDK, as well as more usage examples. +- More [Client API](/agents/runtime/agents-api/#client-api) documentation that documents `useAgent`, `useAgentChat` and the new `@unstable_callable` RPC decorator exposed by the SDK. +- New documentation on how to [route requests to agents](/agents/runtime/communication/routing/) and (optionally) authenticate clients before they connect to your Agents. Note that the Agents SDK is continually growing: the type definitions included in the SDK will always include the latest APIs exposed by the `agents` package. diff --git a/src/content/changelog/agents/2025-04-07-mcp-servers-agents-sdk-updates.mdx b/src/content/changelog/agents/2025-04-07-mcp-servers-agents-sdk-updates.mdx index d6c32c853dd..d2c50c347ac 100644 --- a/src/content/changelog/agents/2025-04-07-mcp-servers-agents-sdk-updates.mdx +++ b/src/content/changelog/agents/2025-04-07-mcp-servers-agents-sdk-updates.mdx @@ -52,7 +52,7 @@ We've made a number of improvements to the [Agents SDK](/agents/), including: - Support for building MCP servers with the new `MCPAgent` class. - The ability to export the current agent, request and WebSocket connection context using `import { context } from "agents"`, allowing you to minimize or avoid direct dependency injection when calling tools. - Fixed a bug that prevented query parameters from being sent to the Agent server from the `useAgent` React hook. -- Automatically converting the `agent` name in `useAgent` or `useAgentChat` to kebab-case to ensure it matches the naming convention expected by [`routeAgentRequest`](/agents/api-reference/routing/). +- Automatically converting the `agent` name in `useAgent` or `useAgentChat` to kebab-case to ensure it matches the naming convention expected by [`routeAgentRequest`](/agents/runtime/communication/routing/). To install or update the Agents SDK, run `npm i agents@latest` in an existing project, or explore the `agents-starter` project: diff --git a/src/content/changelog/agents/2025-11-26-agents-resumable-streaming.mdx b/src/content/changelog/agents/2025-11-26-agents-resumable-streaming.mdx index e4600fdadc5..2416eca0da8 100644 --- a/src/content/changelog/agents/2025-11-26-agents-resumable-streaming.mdx +++ b/src/content/changelog/agents/2025-11-26-agents-resumable-streaming.mdx @@ -24,7 +24,7 @@ Streams are maintained across page refreshes, broken connections, and syncing ac ### Other improvements - Default JSON schema validator added to MCP client -- [Schedules](https://developers.cloudflare.com/agents/api-reference/schedule-tasks/) can now safely destroy the agent +- [Schedules](https://developers.cloudflare.com/agents/runtime/execution/schedule-tasks/) can now safely destroy the agent ### MCP client API improvements @@ -60,7 +60,7 @@ MCP discovery fetches the available tools, prompts, and resources from an MCP se ### Bug fixes -- Fixed a bug where [schedules](https://developers.cloudflare.com/agents/api-reference/schedule-tasks/) meant to fire immediately with this.schedule(0, ...) or `this.schedule(new Date(), ...)` would not fire +- Fixed a bug where [schedules](https://developers.cloudflare.com/agents/runtime/execution/schedule-tasks/) meant to fire immediately with this.schedule(0, ...) or `this.schedule(new Date(), ...)` would not fire - Fixed an issue where schedules that took longer than 30 seconds would occasionally time out - Fixed SSE transport now properly forwards session IDs and request headers - Fixed AI SDK stream events conversion to UIMessageStreamPart diff --git a/src/content/changelog/agents/2026-02-03-agents-workflows-integration.mdx b/src/content/changelog/agents/2026-02-03-agents-workflows-integration.mdx index 13d276b741b..501893ccad7 100644 --- a/src/content/changelog/agents/2026-02-03-agents-workflows-integration.mdx +++ b/src/content/changelog/agents/2026-02-03-agents-workflows-integration.mdx @@ -175,4 +175,4 @@ To update to the latest version: npm i agents@latest ``` -For the complete Workflows API reference and patterns, see [Run Workflows](/agents/api-reference/run-workflows/). +For the complete Workflows API reference and patterns, see [Run Workflows](/agents/runtime/execution/run-workflows/). diff --git a/src/content/changelog/agents/2026-02-17-agents-sdk-v0.5.0.mdx b/src/content/changelog/agents/2026-02-17-agents-sdk-v0.5.0.mdx index e6ef56288b0..8ecfba40a59 100644 --- a/src/content/changelog/agents/2026-02-17-agents-sdk-v0.5.0.mdx +++ b/src/content/changelog/agents/2026-02-17-agents-sdk-v0.5.0.mdx @@ -73,7 +73,7 @@ class MyAgent extends Agent { Connections with protocol messages disabled still fully participate in RPC and regular messaging. Use `isConnectionProtocolEnabled(connection)` to check a connection's status at any time. The flag persists across Durable Object hibernation. -See [Protocol messages](/agents/api-reference/protocol-messages/) for full documentation. +See [Protocol messages](/agents/runtime/communication/protocol-messages/) for full documentation. ## `@cloudflare/ai-chat` v0.1.0 @@ -81,7 +81,7 @@ The first stable release of `@cloudflare/ai-chat` ships alongside this release w Key new features: -- **Data parts** — Attach typed JSON blobs (`data-*`) to messages alongside text. Supports reconciliation (type+id updates in-place), append, and transient parts (ephemeral via `onData` callback). See [Data parts](/agents/api-reference/chat-agents/#data-parts). +- **Data parts** — Attach typed JSON blobs (`data-*`) to messages alongside text. Supports reconciliation (type+id updates in-place), append, and transient parts (ephemeral via `onData` callback). See [Data parts](/agents/communication-channels/chat/chat-agents/#data-parts). - **Tool approval persistence** — The `needsApproval` approval UI now survives page refresh and DO hibernation. The streaming message is persisted to SQLite when a tool enters `approval-requested` state. - **`maxPersistedMessages`** — Cap SQLite message storage with automatic oldest-message deletion. - **`body` option on `useAgentChat`** — Send custom data with every request (static or dynamic). diff --git a/src/content/changelog/agents/2026-02-20-codemode-sdk-rewrite.mdx b/src/content/changelog/agents/2026-02-20-codemode-sdk-rewrite.mdx index f37a1bd18bc..f2cde79ab71 100644 --- a/src/content/changelog/agents/2026-02-20-codemode-sdk-rewrite.mdx +++ b/src/content/changelog/agents/2026-02-20-codemode-sdk-rewrite.mdx @@ -66,7 +66,7 @@ const result = streamText({ -See the [Code Mode documentation](/agents/api-reference/codemode/) for full API reference and examples. +See the [Code Mode documentation](/agents/model-context-protocol/protocol/codemode/) for full API reference and examples. ## Upgrade diff --git a/src/content/changelog/agents/2026-03-02-agents-sdk-v0.7.0.mdx b/src/content/changelog/agents/2026-03-02-agents-sdk-v0.7.0.mdx index 9e7eec60dde..820b1c70666 100644 --- a/src/content/changelog/agents/2026-03-02-agents-sdk-v0.7.0.mdx +++ b/src/content/changelog/agents/2026-03-02-agents-sdk-v0.7.0.mdx @@ -72,7 +72,7 @@ export default { The custom `Observability` override interface is still supported for users who need to filter or forward events to external services. -For the full event reference, refer to the [Observability documentation](/agents/api-reference/observability/). +For the full event reference, refer to the [Observability documentation](/agents/runtime/operations/observability/). ## `keepAlive()` and `keepAliveWhile()` @@ -117,7 +117,7 @@ Key details: `keepAlive()` is marked `@experimental` and may change between releases. ::: -For the full API reference and when-to-use guidance, refer to [Schedule tasks — Keeping the agent alive](/agents/api-reference/schedule-tasks/#keeping-the-agent-alive). +For the full API reference and when-to-use guidance, refer to [Schedule tasks — Keeping the agent alive](/agents/runtime/execution/schedule-tasks/#keeping-the-agent-alive). ## `waitForMcpConnections` diff --git a/src/content/changelog/agents/2026-03-17-codemode-sdk-v0.2.1.mdx b/src/content/changelog/agents/2026-03-17-codemode-sdk-v0.2.1.mdx index 40c4300b4f4..4152f1ad487 100644 --- a/src/content/changelog/agents/2026-03-17-codemode-sdk-v0.2.1.mdx +++ b/src/content/changelog/agents/2026-03-17-codemode-sdk-v0.2.1.mdx @@ -91,4 +91,4 @@ const executor = new DynamicWorkerExecutor({ npm i @cloudflare/codemode@latest ``` -See the [Code Mode documentation](/agents/api-reference/codemode/) for the full API reference. +See the [Code Mode documentation](/agents/model-context-protocol/protocol/codemode/) for the full API reference. diff --git a/src/content/changelog/agents/2026-05-13-agents-sdk-v0.12.4.mdx b/src/content/changelog/agents/2026-05-13-agents-sdk-v0.12.4.mdx index 698f9c80d5e..7e7d969103c 100644 --- a/src/content/changelog/agents/2026-05-13-agents-sdk-v0.12.4.mdx +++ b/src/content/changelog/agents/2026-05-13-agents-sdk-v0.12.4.mdx @@ -125,4 +125,4 @@ To update to the latest version: npm i agents@latest @cloudflare/ai-chat@latest @cloudflare/think@latest @cloudflare/voice@latest ``` -Refer to the [Agents API reference](/agents/api-reference/) and [Chat agents documentation](/agents/api-reference/chat-agents/) for more information. +Refer to the [Agents API reference](/agents/runtime/) and [Chat agents documentation](/agents/communication-channels/chat/chat-agents/) for more information. diff --git a/src/content/changelog/agents/2026-06-02-agents-sdk-v0.14.0.mdx b/src/content/changelog/agents/2026-06-02-agents-sdk-v0.14.0.mdx index fe35e116eda..55a22f00a9d 100644 --- a/src/content/changelog/agents/2026-06-02-agents-sdk-v0.14.0.mdx +++ b/src/content/changelog/agents/2026-06-02-agents-sdk-v0.14.0.mdx @@ -160,4 +160,4 @@ To update to the latest version: -Refer to the [Agents API reference](/agents/api-reference/) and [Chat agents documentation](/agents/api-reference/chat-agents/) for more information. +Refer to the [Agents API reference](/agents/runtime/) and [Chat agents documentation](/agents/communication-channels/chat/chat-agents/) for more information. diff --git a/src/content/changelog/workers/2026-03-24-dynamic-workers-open-beta.mdx b/src/content/changelog/workers/2026-03-24-dynamic-workers-open-beta.mdx index 2b03afbf16c..1eed9dbbb99 100644 --- a/src/content/changelog/workers/2026-03-24-dynamic-workers-open-beta.mdx +++ b/src/content/changelog/workers/2026-03-24-dynamic-workers-open-beta.mdx @@ -12,7 +12,7 @@ import { TypeScriptExample } from "~/components"; ## Use Dynamic Workers for -- **[Code Mode](/agents/api-reference/codemode/)**: LLMs are trained to write code. Run tool-calling logic written in code instead of stepping through many tool calls, which can save up to 80% in inference tokens and cost. +- **[Code Mode](/agents/model-context-protocol/protocol/codemode/)**: LLMs are trained to write code. Run tool-calling logic written in code instead of stepping through many tool calls, which can save up to 80% in inference tokens and cost. - **AI agents executing code**: Run code for tasks like data analysis, file transformation, API calls, and chained actions. - **Running AI-generated code**: Run generated code for prototypes, projects, and automations in a secure, isolated sandboxed environment. - **Fast development and previews**: Load prototypes, previews, and playgrounds in milliseconds. diff --git a/src/content/docs/agent-lee/index.mdx b/src/content/docs/agent-lee/index.mdx index 8eedd76f325..bd0736ac8f7 100644 --- a/src/content/docs/agent-lee/index.mdx +++ b/src/content/docs/agent-lee/index.mdx @@ -123,13 +123,13 @@ Agent Lee is built on Cloudflare's own developer platform using the same primiti | [Agents SDK](/agents/) | Agent lifecycle, state management, and scheduling | | [Durable Objects](/durable-objects/) | Per-user conversation storage and write approval gate | | [Workers AI](/workers-ai/) | LLM inference | -| [Cloudflare MCP server](/agents/api-reference/mcp-agent-api/) | Tool definitions for Cloudflare API operations | +| [Cloudflare MCP server](/agents/model-context-protocol/apis/agent-api/) | Tool definitions for Cloudflare API operations | --- ## Related resources - [Agents SDK](/agents/) -- [Human in the Loop](/agents/concepts/human-in-the-loop/) +- [Human in the Loop](/agents/concepts/agentic-patterns/human-in-the-loop/) - [Workers AI](/workers-ai/) - [Blog post: Introducing Agent Lee](https://blog.cloudflare.com/introducing-agent-lee) diff --git a/src/content/docs/agent-memory/get-started.mdx b/src/content/docs/agent-memory/get-started.mdx index 0a8025165ac..d244e743e11 100644 --- a/src/content/docs/agent-memory/get-started.mdx +++ b/src/content/docs/agent-memory/get-started.mdx @@ -18,7 +18,7 @@ import { Add Agent Memory to an agent so it can recall durable context across conversations. -This guide uses the [Agents SDK](/agents/) and its [Session API](/agents/api-reference/sessions/) to expose memory recall as a model-callable tool. The same pattern applies if you use another agent framework: store memories with `ingest()` or `remember()`, expose `recall()` through one of your agent's tools, and use the system prompt to tell the model when to search memory. +This guide uses the [Agents SDK](/agents/) and its [Session API](/agents/runtime/lifecycle/sessions/) to expose memory recall as a model-callable tool. The same pattern applies if you use another agent framework: store memories with `ingest()` or `remember()`, expose `recall()` through one of your agent's tools, and use the system prompt to tell the model when to search memory. ## Prerequisites @@ -104,7 +104,7 @@ Generate local TypeScript types for your bindings: The model cannot use memory just because your application has a memory binding. You need to expose recall through a tool and instruct the model when to call it. -With the Agents SDK [Session API](/agents/api-reference/sessions/), add a searchable context provider. Session turns the provider's `search()` method into a `search_context` tool for the model. +With the Agents SDK [Session API](/agents/runtime/lifecycle/sessions/), add a searchable context provider. Session turns the provider's `search()` method into a `search_context` tool for the model. Create `src/server.ts` and add the recall setup: diff --git a/src/content/docs/agents/api-reference/index.mdx b/src/content/docs/agents/api-reference/index.mdx deleted file mode 100644 index 68180264038..00000000000 --- a/src/content/docs/agents/api-reference/index.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: API Reference -description: Explore the Agents SDK classes, methods, and client libraries for building AI agents on Cloudflare. -pcx_content_type: navigation -sidebar: - order: 5 - group: - hideIndex: true -products: - - agents ---- - -import { DirectoryListing } from "~/components"; - -Learn more about what Agents can do, the `Agent` class, and the APIs that Agents expose: - - diff --git a/src/content/docs/agents/api-reference/rag.mdx b/src/content/docs/agents/api-reference/rag.mdx deleted file mode 100644 index 42181f526ed..00000000000 --- a/src/content/docs/agents/api-reference/rag.mdx +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Retrieval Augmented Generation -description: Add RAG to Cloudflare Agents using Vectorize for vector search and the embedded SQL database for context retrieval. -pcx_content_type: concept -sidebar: - order: 20 -products: - - agents ---- - -import { - MetaInfo, - Render, - Type, - TypeScriptExample, - WranglerConfig, -} from "~/components"; - -Agents can use Retrieval Augmented Generation (RAG) to retrieve relevant information and use it augment [calls to AI models](/agents/api-reference/using-ai-models/). Store a user's chat history to use as context for future conversations, summarize documents to bootstrap an Agent's knowledge base, and/or use data from your Agent's [web browsing](/agents/api-reference/browse-the-web/) tasks to enhance your Agent's capabilities. - -You can use the Agent's own [SQL database](/agents/api-reference/store-and-sync-state) as the source of truth for your data and store embeddings in [Vectorize](/vectorize/) (or any other vector-enabled database) to allow your Agent to retrieve relevant information. - -### Vector search - -:::note - -If you're brand-new to vector databases and Vectorize, visit the [Vectorize tutorial](/vectorize/get-started/intro/) to learn the basics, including how to create an index, insert data, and generate embeddings. - -::: - -You can query a vector index (or indexes) from any method on your Agent: any Vectorize index you attach is available on `this.env` within your Agent. If you've [associated metadata](/vectorize/best-practices/insert-vectors/#metadata) with your vectors that maps back to data stored in your Agent, you can then look up the data directly within your Agent using `this.sql`. - -Here's an example of how to give an Agent retrieval capabilities: - - - -```ts -import { Agent } from "agents"; - -interface Env { - AI: Ai; - VECTOR_DB: Vectorize; -} - -export class RAGAgent extends Agent { - // Other methods on our Agent - // ... - // - async queryKnowledge(userQuery: string) { - // Turn a query into an embedding - const queryVector = await this.env.AI.run("@cf/baai/bge-base-en-v1.5", { - text: [userQuery], - }); - - // Retrieve results from our vector index - let searchResults = await this.env.VECTOR_DB.query(queryVector.data[0], { - topK: 10, - returnMetadata: "all", - }); - - let knowledge = []; - for (const match of searchResults.matches) { - console.log(match.metadata); - knowledge.push(match.metadata); - } - - // Use the metadata to re-associate the vector search results - // with data in our Agent's SQL database - let results = this - .sql`SELECT * FROM knowledge WHERE id IN (${knowledge.map((k) => k.id)})`; - - // Return them - return results; - } -} -``` - - - -You'll also need to connect your Agent to your vector indexes: - - - -```jsonc -{ - // ... - "vectorize": [ - { - "binding": "VECTOR_DB", - "index_name": "your-vectorize-index-name", - }, - ], - // ... -} -``` - - - -If you have multiple indexes you want to make available, you can provide an array of `vectorize` bindings. - -#### Next steps - -- Learn more on how to [combine Vectorize and Workers AI](/vectorize/get-started/embeddings/) -- Review the [Vectorize query API](/vectorize/reference/client-api/) -- Use [metadata filtering](/vectorize/reference/metadata-filtering/) to add context to your results diff --git a/src/content/docs/agents/guides/autonomous-responses.mdx b/src/content/docs/agents/communication-channels/chat/autonomous-responses.mdx similarity index 96% rename from src/content/docs/agents/guides/autonomous-responses.mdx rename to src/content/docs/agents/communication-channels/chat/autonomous-responses.mdx index f347ac7986f..6b7d04f96b0 100644 --- a/src/content/docs/agents/guides/autonomous-responses.mdx +++ b/src/content/docs/agents/communication-channels/chat/autonomous-responses.mdx @@ -3,7 +3,7 @@ title: Autonomous responses description: Send server-initiated messages and trigger LLM responses from Cloudflare Agents without user action. pcx_content_type: how-to sidebar: - order: 4 + order: 3 products: - agents --- @@ -66,10 +66,9 @@ return Response.json({ `submitMessages()` stores pending work first and appends the messages to the conversation Session only when the submission starts executing. It accepts serializable `UIMessage[]` values, not the function form supported by `saveMessages((messages) => ...)`. -Use [`startFiber()`](/agents/api-reference/durable-execution/#startfiber) outside Think when the durable unit is a surrounding application job, such as accepting a webhook once, restoring provider state, posting a visible reply, and recording recovery policy. `submitMessages()` owns Think's conversation admission; managed fibers own external side effects around that turn. - -For the full Think API, refer to [`submitMessages()`](/agents/think/programmatic-submissions/#submitmessages). +Use [`startFiber()`](/agents/runtime/execution/durable-execution/#startfiber) outside Think when the durable unit is a surrounding application job, such as accepting a webhook once, restoring provider state, posting a visible reply, and recording recovery policy. `submitMessages()` owns Think's conversation admission; managed fibers own external side effects around that turn. +For the full Think API, refer to [`submitMessages()`](/agents/harnesses/think/programmatic-submissions/#submitmessages). ### When to use `saveMessages` vs `onChatResponse` **Use `saveMessages` when you control the trigger** — schedule callbacks, webhooks, email handlers, or any method where you decide when to inject a message. @@ -153,7 +152,7 @@ export class DigestAgent extends AIChatAgent { -The function form of `saveMessages` — `saveMessages((messages) => [...])` — reads the latest persisted messages at execution time. This avoids stale baselines when multiple calls queue up (for example, rapid webhook arrivals). Refer to [Schedule tasks](/agents/api-reference/schedule-tasks/) for more on `schedule()` and cron syntax. +The function form of `saveMessages` — `saveMessages((messages) => [...])` — reads the latest persisted messages at execution time. This avoids stale baselines when multiple calls queue up (for example, rapid webhook arrivals). Refer to [Schedule tasks](/agents/runtime/execution/schedule-tasks/) for more on `schedule()` and cron syntax. ### Processing a queue @@ -527,24 +526,24 @@ Use `cancelFiber(fiberId)` when the durable unit was accepted with `startFiber() diff --git a/src/content/docs/agents/api-reference/chat-agents.mdx b/src/content/docs/agents/communication-channels/chat/chat-agents.mdx similarity index 98% rename from src/content/docs/agents/api-reference/chat-agents.mdx rename to src/content/docs/agents/communication-channels/chat/chat-agents.mdx index 42349ba78e7..8878d55458d 100644 --- a/src/content/docs/agents/api-reference/chat-agents.mdx +++ b/src/content/docs/agents/communication-channels/chat/chat-agents.mdx @@ -3,7 +3,7 @@ title: Chat agents description: Build AI chat interfaces with AIChatAgent and useAgentChat, including message persistence, streaming, and tool support. pcx_content_type: reference sidebar: - order: 4 + order: 2 products: - agents --- @@ -577,8 +577,7 @@ Use `abortRequest()` when you know the request ID. Use `abortAllRequests()` for Automatic stream resumption (the `resume` option on `useAgentChat`) is **client reconnect recovery** — it resumes an active stream when a client disconnects and reconnects. It does not cover Durable Object eviction: if the Worker process or Durable Object is evicted while the model call is in flight, the stream itself is gone. `chatRecovery` handles that case. -When a Durable Object is evicted mid-stream (code update, inactivity timeout, resource limit), the LLM connection is severed permanently and the in-memory streaming state is lost. `chatRecovery` wraps each chat turn in a [`runFiber()`](/agents/api-reference/durable-execution/), providing automatic `keepAlive` during streaming and a recovery hook on restart. - +When a Durable Object is evicted mid-stream (code update, inactivity timeout, resource limit), the LLM connection is severed permanently and the in-memory streaming state is lost. `chatRecovery` wraps each chat turn in a [`runFiber()`](/agents/runtime/execution/durable-execution/), providing automatic `keepAlive` during streaming and a recovery hook on restart. ```ts @@ -589,7 +588,7 @@ export class ChatAgent extends AIChatAgent { -`AIChatAgent` defaults `chatRecovery` to `false`, so existing chat agents only get client reconnect and resumable-stream behavior unless they opt in. [`Think`](/agents/think/) defaults it to `true`. +`AIChatAgent` defaults `chatRecovery` to `false`, so existing chat agents only get client reconnect and resumable-stream behavior unless they opt in. [`Think`](/agents/harnesses/think/) defaults it to `true`. When enabled, every `onChatMessage` call runs inside a fiber. If the agent is evicted mid-stream, the fiber row survives in SQLite. On the next activation, the framework detects the interrupted fiber, reconstructs the partial response from buffered stream chunks, and calls `onChatRecovery`. @@ -767,13 +766,12 @@ The right strategy depends on whether the provider supports assistant prefill an While a turn is being recovered, the agent broadcasts a `cf_agent_chat_recovering` status frame so clients can show a "recovering…" indicator instead of looking frozen. It is set when a recovery continuation is scheduled and cleared on every terminal outcome, so the indicator never spins forever. Consume it through `useAgentChat`'s `isRecovering` flag (see [Return values](#return-values)). The signal is advisory and backward-compatible — clients that do not understand it ignore it. :::note -`@cloudflare/ai-chat` broadcasts the live signal but does not yet replay it on connect, so a client connecting mid-recovery is not re-told until it reconnects to an active stream. [`Think`](/agents/think/) replays it on connect. +`@cloudflare/ai-chat` broadcasts the live signal but does not yet replay it on connect, so a client connecting mid-recovery is not re-told until it reconnects to an active stream. [`Think`](/agents/harnesses/think/) replays it on connect. ::: Transcript repairs — healing orphaned tool calls (preserved as errored results rather than deleted, so the record survives and the model does not silently re-run the tool) and normalizing malformed or missing tool inputs before a provider call — are emitted on the `transcript` observability channel. -For how chat recovery fits into the broader long-running agents story, refer to [Long-running agents: Recovering interrupted LLM streams](/agents/concepts/long-running-agents/#recovering-interrupted-llm-streams). For the underlying fiber API, refer to [Durable Execution](/agents/api-reference/durable-execution/). - +For how chat recovery fits into the broader long-running agents story, refer to [Long-running agents: Recovering interrupted LLM streams](/agents/concepts/agentic-patterns/long-running-agents/#recovering-interrupted-llm-streams). For the underlying fiber API, refer to [Durable Execution](/agents/runtime/execution/durable-execution/). ## Client API ### `useAgentChat` @@ -1029,7 +1027,7 @@ This sends a `tool_result` to the LLM with your custom error text, so it can res `addToolApprovalResponse` (with `approved: false`) auto-continues the conversation when `autoContinueAfterToolResult` is enabled (the default). `addToolOutput` with `state: "output-error"` does **not** auto-continue — call `sendMessage()` afterward if you want the LLM to respond to the error. -For more patterns, refer to [Human-in-the-loop](/agents/concepts/human-in-the-loop/). +For more patterns, refer to [Human-in-the-loop](/agents/concepts/agentic-patterns/human-in-the-loop/). ## Custom request data @@ -1523,7 +1521,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/api-reference/sub-agents/). To run Think or `AIChatAgent` sub-agents as retained, streaming tools, refer to [Agent tools](/agents/api-reference/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 [Agent tools](/agents/runtime/execution/agent-tools/). ::: @@ -1684,30 +1682,30 @@ If you are upgrading from an earlier version, replace deprecated calls with thei diff --git a/src/content/docs/agents/api-reference/client-sdk.mdx b/src/content/docs/agents/communication-channels/chat/client-sdk.mdx similarity index 97% rename from src/content/docs/agents/api-reference/client-sdk.mdx rename to src/content/docs/agents/communication-channels/chat/client-sdk.mdx index 7a7e44d5215..7fe18dd4742 100644 --- a/src/content/docs/agents/api-reference/client-sdk.mdx +++ b/src/content/docs/agents/communication-channels/chat/client-sdk.mdx @@ -3,7 +3,7 @@ title: Client SDK description: Connect to Cloudflare Agents from browsers or server runtimes using useAgent, AgentClient, and agentFetch. pcx_content_type: reference sidebar: - order: 5 + order: 4 products: - agents --- @@ -616,7 +616,7 @@ client.addEventListener("message", () => {}); ## Agent-tool events -If your chat UI renders retained child runs from [Agent tools](/agents/api-reference/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 [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. @@ -635,24 +635,24 @@ const agentTools = useAgentToolEvents({ agent }); diff --git a/src/content/docs/agents/communication-channels/chat/index.mdx b/src/content/docs/agents/communication-channels/chat/index.mdx new file mode 100644 index 00000000000..d11fc13760b --- /dev/null +++ b/src/content/docs/agents/communication-channels/chat/index.mdx @@ -0,0 +1,12 @@ +--- +title: Chat +pcx_content_type: navigation +sidebar: + order: 1 + group: + hideIndex: true +--- + +import { DirectoryListing } from "~/components"; + + diff --git a/src/content/docs/agents/communication-channels/email.mdx b/src/content/docs/agents/communication-channels/email.mdx new file mode 100644 index 00000000000..1d4ae03ed2e --- /dev/null +++ b/src/content/docs/agents/communication-channels/email.mdx @@ -0,0 +1,108 @@ +--- +title: Email +description: Connect agents to email so they can send outbound messages, process inbound mail, and handle follow-up replies. +pcx_content_type: concept +sidebar: + order: 3 +products: + - agents +--- + +import { LinkCard, TypeScriptExample, WranglerConfig } from "~/components"; + +Email is a communication channel for agents that need to interact with users or systems through inboxes instead of chat UIs. Agents can send outbound email, receive inbound email, route replies back to an existing session, and use email content as part of an agent workflow. + +Use email when you want an agent to: + +- Send notifications, summaries, receipts, or follow-up messages. +- Process inbound messages through [Cloudflare Email Service](/email-service/). +- Continue a conversation from a reply. +- Route support, sales, or operational workflows through an agent. + +## How it works + +Outbound email uses a `send_email` binding in your Worker. Inbound email uses an Email Service routing rule that sends messages to your Worker, where the agent can parse the sender, recipients, headers, and body before deciding how to respond. + +For reply handling, include a stable identifier in the reply address, message metadata, or headers so the Worker can route follow-up messages to the right agent instance. + +## Basic pattern + +Implement `onEmail()` to handle inbound email, and use `sendEmail()` or `replyToEmail()` when the agent needs to send a response. + + + +```ts +import { Agent, callable, routeAgentEmail } from "agents"; +import { createAddressBasedEmailResolver, type AgentEmail } from "agents/email"; + +export class EmailAgent extends Agent { + @callable() + async sendWelcomeEmail(to: string) { + await this.sendEmail({ + binding: this.env.EMAIL, + to, + from: "support@yourdomain.com", + replyTo: "support@yourdomain.com", + subject: "Welcome", + text: "Thanks for signing up. Reply to this email if you need help.", + }); + } + + async onEmail(email: AgentEmail) { + await this.replyToEmail(email, { + fromName: "Support Agent", + body: "Thanks for your email. We received it.", + }); + } +} + +export default { + async email(message, env) { + await routeAgentEmail(message, env, { + resolver: createAddressBasedEmailResolver("EmailAgent"), + }); + }, +} satisfies ExportedHandler; +``` + + + +## Configuration + +Add a `send_email` binding for outbound email, then configure an Email Service routing rule to send inbound mail to your Worker. + + + +```toml +[[send_email]] +name = "EMAIL" +remote = true +``` + + + +The `remote = true` option lets you call the real Email Service API during local development with `wrangler dev`. + +## Build an email agent + +For a complete walkthrough, including domain setup, bindings, inbound routing, and secure replies, use the email agent example. + + + +## Related resources + + + + diff --git a/src/content/docs/agents/communication-channels/index.mdx b/src/content/docs/agents/communication-channels/index.mdx new file mode 100644 index 00000000000..935c15443eb --- /dev/null +++ b/src/content/docs/agents/communication-channels/index.mdx @@ -0,0 +1,14 @@ +--- +title: Communication channels +pcx_content_type: navigation +sidebar: + order: 3 + group: + hideIndex: true +--- + +import { DirectoryListing } from "~/components"; + +Communication channels define how agents communicate with users and external systems. + + diff --git a/src/content/docs/agents/communication-channels/slack.mdx b/src/content/docs/agents/communication-channels/slack.mdx new file mode 100644 index 00000000000..4676030b559 --- /dev/null +++ b/src/content/docs/agents/communication-channels/slack.mdx @@ -0,0 +1,55 @@ +--- +pcx_content_type: concept +title: Slack +description: Connect agents to Slack workspaces so they can respond to direct messages, mentions, and threaded conversations. +sidebar: + order: 4 +--- + +import { LinkCard } from "~/components"; + +Slack is a communication channel for agents that need to participate in team conversations. A Slack-connected agent can receive events from Slack, route each message to the right agent instance, and respond back to direct messages or channel mentions. + +Use Slack when you want an agent to: + +- Respond to direct messages from Slack users. +- Reply when mentioned in public channels. +- Maintain context inside Slack threads. +- Serve multiple Slack workspaces from one deployment. + +## How it works + +Slack sends events to your Worker through the [Slack Events API](https://api.slack.com/apis/events-api). Your Worker verifies each request, identifies the installed workspace, and routes the event to an agent instance. + +Common Slack events include: + +| Event | Use case | +| --- | --- | +| `message.im` | Direct messages to the bot | +| `app_mention` | Mentions in channels | + +For multi-workspace Slack apps, store each workspace installation separately and route events by team or enterprise ID. Each workspace can map to an isolated agent instance with its own Durable Object-backed state. + +## Build a Slack agent + +For a complete walkthrough, including Slack app setup, OAuth, event subscriptions, and deployment, use the Slack agent example. + + + +## Related resources + + + + diff --git a/src/content/docs/agents/api-reference/voice.mdx b/src/content/docs/agents/communication-channels/voice.mdx similarity index 99% rename from src/content/docs/agents/api-reference/voice.mdx rename to src/content/docs/agents/communication-channels/voice.mdx index 2548167307f..c2b7d2b5695 100644 --- a/src/content/docs/agents/api-reference/voice.mdx +++ b/src/content/docs/agents/communication-channels/voice.mdx @@ -1,9 +1,9 @@ --- -title: Voice agents +title: Voice description: Build real-time voice agents with speech-to-text, text-to-speech, and conversation persistence over WebSocket. pcx_content_type: reference sidebar: - order: 22 + order: 2 products: - agents --- diff --git a/src/content/docs/agents/guides/webhooks.mdx b/src/content/docs/agents/communication-channels/webhooks/index.mdx similarity index 98% rename from src/content/docs/agents/guides/webhooks.mdx rename to src/content/docs/agents/communication-channels/webhooks/index.mdx index 80805c48ee7..33887c7a78d 100644 --- a/src/content/docs/agents/guides/webhooks.mdx +++ b/src/content/docs/agents/communication-channels/webhooks/index.mdx @@ -536,7 +536,7 @@ return Response.json( -If the webhook owns application side effects around a turn, such as restoring a provider thread and posting a visible reply, use [`startFiber()`](/agents/api-reference/durable-execution/#startfiber) around that job. Managed fibers retain status, dedupe provider retries, and let `onFiberRecovered()` or `resolveFiber()` record the app-level recovery outcome. +If the webhook owns application side effects around a turn, such as restoring a provider thread and posting a visible reply, use [`startFiber()`](/agents/runtime/execution/durable-execution/#startfiber) around that job. Managed fibers retain status, dedupe provider retries, and let `onFiberRecovered()` or `resolveFiber()` record the app-level recovery outcome. ### Multi-provider routing @@ -659,18 +659,18 @@ const secret = this.env.GITHUB_WEBHOOK_SECRET; diff --git a/src/content/docs/agents/guides/push-notifications.mdx b/src/content/docs/agents/communication-channels/webhooks/push-notifications.mdx similarity index 98% rename from src/content/docs/agents/guides/push-notifications.mdx rename to src/content/docs/agents/communication-channels/webhooks/push-notifications.mdx index 2c84f976a02..e06482bd7f4 100644 --- a/src/content/docs/agents/guides/push-notifications.mdx +++ b/src/content/docs/agents/communication-channels/webhooks/push-notifications.mdx @@ -404,18 +404,18 @@ try { diff --git a/src/content/docs/agents/guides/human-in-the-loop.mdx b/src/content/docs/agents/concepts/agentic-patterns/human-in-the-loop.mdx similarity index 98% rename from src/content/docs/agents/guides/human-in-the-loop.mdx rename to src/content/docs/agents/concepts/agentic-patterns/human-in-the-loop.mdx index 21d70e8c0d9..6538a8067b0 100644 --- a/src/content/docs/agents/guides/human-in-the-loop.mdx +++ b/src/content/docs/agents/concepts/agentic-patterns/human-in-the-loop.mdx @@ -2,7 +2,7 @@ title: Human-in-the-loop patterns pcx_content_type: how-to sidebar: - order: 3 + order: 2 description: Implement human-in-the-loop functionality using Cloudflare Agents for workflow approvals and MCP elicitation products: - agents @@ -533,13 +533,13 @@ class MultiApprovalAgent extends Agent { @@ -551,6 +551,6 @@ class MultiApprovalAgent extends Agent { diff --git a/src/content/docs/agents/patterns.mdx b/src/content/docs/agents/concepts/agentic-patterns/index.mdx similarity index 98% rename from src/content/docs/agents/patterns.mdx rename to src/content/docs/agents/concepts/agentic-patterns/index.mdx index 620803069a7..61701e33f5b 100644 --- a/src/content/docs/agents/patterns.mdx +++ b/src/content/docs/agents/concepts/agentic-patterns/index.mdx @@ -1,9 +1,9 @@ --- pcx_content_type: concept -title: Patterns +title: Agentic patterns description: Implement common AI agent patterns like prompt chaining, routing, parallelization, and orchestrator-workers on Cloudflare. sidebar: - order: 3 + order: 99 head: [] products: - agents diff --git a/src/content/docs/agents/concepts/long-running-agents.mdx b/src/content/docs/agents/concepts/agentic-patterns/long-running-agents.mdx similarity index 91% rename from src/content/docs/agents/concepts/long-running-agents.mdx rename to src/content/docs/agents/concepts/agentic-patterns/long-running-agents.mdx index 8cd2c00623f..98cb4f0ca36 100644 --- a/src/content/docs/agents/concepts/long-running-agents.mdx +++ b/src/content/docs/agents/concepts/agentic-patterns/long-running-agents.mdx @@ -5,7 +5,7 @@ description: Build agents that persist for days, weeks, or months — surviving tags: - AI sidebar: - order: 7 + order: 3 products: - agents --- @@ -124,7 +124,7 @@ A hibernated agent can be woken by any of these sources: | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------- | | **HTTP request** | Any request to the agent's URL triggers `onRequest()` | A webhook from GitHub | | **WebSocket connection** | A client connects, triggering `onConnect()` | A team member opens the dashboard | -| **RPC call** | Another Worker or agent calls a method via [service binding](/workers/runtime-apis/bindings/service-bindings/) or [`@callable`](/agents/api-reference/callable-methods/) | A coordinator agent delegates a task | +| **RPC call** | Another Worker or agent calls a method via [service binding](/workers/runtime-apis/bindings/service-bindings/) or [`@callable`](/agents/runtime/lifecycle/callable-methods/) | A coordinator agent delegates a task | | **Scheduled alarm** | A stored schedule fires, triggering your callback | Daily standup reminder at 9am | | **Email** | An inbound email triggers `onEmail()` | A team member replies to a status email | @@ -220,16 +220,16 @@ try { | Seconds | Normal request handling | | Minutes | `keepAlive()` / `keepAliveWhile()` | | Minutes | `startFiber()` when retryable acceptance matters | -| Minutes to hours | [Workflows](/agents/concepts/workflows/) | +| Minutes to hours | [Workflows](/agents/runtime/execution/run-workflows/) | | Hours to days | Async pattern: start job, hibernate, wake on completion | ## Surviving crashes: fibers and recovery An agent can be evicted at any time — a deploy, a platform restart, or hitting resource limits. If the agent was mid-task, that work is lost unless it was checkpointed. -[`runFiber()`](/agents/api-reference/durable-execution/) provides crash-recoverable execution. It persists a row in SQLite for the duration of the work, and lets you `stash()` intermediate state. If the agent is evicted, the fiber row survives, and `onFiberRecovered()` is called on the next activation. +[`runFiber()`](/agents/runtime/execution/durable-execution/) provides crash-recoverable execution. It persists a row in SQLite for the duration of the work, and lets you `stash()` intermediate state. If the agent is evicted, the fiber row survives, and `onFiberRecovered()` is called on the next activation. -Use [`startFiber()`](/agents/api-reference/durable-execution/#startfiber) when the important boundary is durable acceptance. It adds an idempotency key, retained status records, inspection, cancellation, and cleanup on top of the same fiber machinery. By default it returns after acceptance; pass `waitForCompletion: true` when the request should stay open until the accepted job reaches a terminal status. This is a good fit for webhooks where the provider may retry delivery and the agent must avoid starting duplicate visible side effects. +Use [`startFiber()`](/agents/runtime/execution/durable-execution/#startfiber) when the important boundary is durable acceptance. It adds an idempotency key, retained status records, inspection, cancellation, and cleanup on top of the same fiber machinery. By default it returns after acceptance; pass `waitForCompletion: true` when the request should stay open until the accepted job reaches a terminal status. This is a good fit for webhooks where the provider may retry delivery and the agent must avoid starting duplicate visible side effects. ```ts export class ProjectManager extends Agent { @@ -270,7 +270,7 @@ In `wrangler dev`, fiber recovery works identically to production. Kill the wran ::: -For the full API reference — `FiberContext`, `FiberRecoveryContext`, concurrent fibers, inline vs fire-and-forget patterns — refer to [Durable Execution](/agents/api-reference/durable-execution/). +For the full API reference — `FiberContext`, `FiberRecoveryContext`, concurrent fibers, inline vs fire-and-forget patterns — refer to [Durable Execution](/agents/runtime/execution/durable-execution/). ## Handling long async operations @@ -362,7 +362,7 @@ export class ProjectManager extends Agent { ### Pattern: workflow delegation -A production deployment involves multiple steps that must each retry independently — build, test, stage, promote. The project manager should not manage these steps internally; it delegates to a [Workflow](/agents/concepts/workflows/) that handles retries and step sequencing: +A production deployment involves multiple steps that must each retry independently — build, test, stage, promote. The project manager should not manage these steps internally; it delegates to a [Workflow](/agents/runtime/execution/run-workflows/) that handles retries and step sequencing: ```ts export class ProjectManager extends Agent { @@ -535,8 +535,7 @@ Sub-agents have their own state, schedules, durable fibers, and lifecycle. They Because facets do not have independent alarm slots, the top-level parent owns the physical Durable Object alarm. The Agents SDK records which sub-agent owns each schedule or fiber recovery lease, wakes the parent, and routes the callback back into the child. The parent does not need to stay active while the sub-agent works — it can start the work, hibernate, and be woken by the child-owned schedule or recovery check. -For the full `subAgent()` API — typed RPC stubs, client routing, access control, storage isolation, and alarm-backed APIs — refer to [Sub-agents](/agents/api-reference/sub-agents/). For AI-specific sub-agent streaming (running full LLM turns through a child agent), refer to [Think: Sub-agent RPC](/agents/think/sub-agents/). - +For the full `subAgent()` API — typed RPC stubs, client routing, access control, storage isolation, and alarm-backed APIs — refer to [Sub-agents](/agents/runtime/execution/sub-agents/). For AI-specific sub-agent streaming (running full LLM turns through a child agent), refer to [Think: Sub-agent RPC](/agents/harnesses/think/sub-agents/). ## Recovering interrupted LLM streams The patterns above handle the project manager's coordination work — scheduling, delegating, polling. But the project manager also uses an LLM directly: generating plans, summarizing progress, drafting status emails. Those LLM calls stream tokens over a connection that cannot be resumed if the agent is evicted mid-response. @@ -576,7 +575,7 @@ The right recovery strategy depends on the LLM provider: Use `ctx.createdAt` to suppress stale recoveries. For example, if a recovered chat turn is older than a few minutes, you may persist the partial answer but skip automatic continuation to avoid surprising the user with an old response. -[`Think`](/agents/think/) enables `chatRecovery` by default. The default path persists partial output and auto-continues or retries the turn when safe, so many apps do not need a custom hook. Override `onChatRecovery` when a provider has a better recovery strategy, or configure `chatRecovery = { maxAttempts, terminalMessage, onExhausted }` to tune the terminal user experience. +[`Think`](/agents/harnesses/think/) enables `chatRecovery` by default. The default path persists partial output and auto-continues or retries the turn when safe, so many apps do not need a custom hook. Override `onChatRecovery` when a provider has a better recovery strategy, or configure `chatRecovery = { maxAttempts, terminalMessage, onExhausted }` to tune the terminal user experience. If the agent is interrupted before any assistant stream chunks are written, there is no partial assistant message to continue. When the latest persisted message is still the unanswered user message from that turn, chat recovery retries the turn automatically unless `onChatRecovery` returns `{ continue: false }`. @@ -698,13 +697,13 @@ The agent does not need to run continuously to do any of this. It just needs to ## Related -- [Durable Execution](/agents/api-reference/durable-execution/) — `runFiber()`, `startFiber()`, `stash()`, and crash recovery -- [Schedule tasks](/agents/api-reference/schedule-tasks/) — delayed, cron, and interval tasks -- [Retries](/agents/api-reference/retries/) — retry options and patterns -- [Workflows](/agents/concepts/workflows/) — durable multi-step processing -- [Store and sync state](/agents/api-reference/store-and-sync-state/) — `setState()` and persistence -- [WebSockets](/agents/api-reference/websockets/) — lifecycle hooks and hibernation -- [Callable methods](/agents/api-reference/callable-methods/) — RPC via `@callable` and service bindings -- [Email routing](/agents/api-reference/email/) — receiving inbound email -- [Webhooks](/agents/guides/webhooks/) — receiving external events -- [Human in the loop](/agents/concepts/human-in-the-loop/) — approval flows +- [Durable Execution](/agents/runtime/execution/durable-execution/) — `runFiber()`, `startFiber()`, `stash()`, and crash recovery +- [Schedule tasks](/agents/runtime/execution/schedule-tasks/) — delayed, cron, and interval tasks +- [Retries](/agents/runtime/execution/retries/) — retry options and patterns +- [Workflows](/agents/runtime/execution/run-workflows/) — durable multi-step processing +- [Store and sync state](/agents/runtime/lifecycle/state/) — `setState()` and persistence +- [WebSockets](/agents/runtime/communication/websockets/) — lifecycle hooks and hibernation +- [Callable methods](/agents/runtime/lifecycle/callable-methods/) — RPC via `@callable` and service bindings +- [Email routing](/agents/communication-channels/email/) — receiving inbound email +- [Webhooks](/agents/communication-channels/webhooks/) — receiving external events +- [Human in the loop](/agents/concepts/agentic-patterns/human-in-the-loop/) — approval flows diff --git a/src/content/docs/agents/concepts/calling-llms.mdx b/src/content/docs/agents/concepts/calling-llms.mdx index d6b6d38b7f7..8ad30643d7c 100644 --- a/src/content/docs/agents/concepts/calling-llms.mdx +++ b/src/content/docs/agents/concepts/calling-llms.mdx @@ -14,11 +14,11 @@ import { TypeScriptExample, LinkCard } from "~/components"; Agents change how you work with LLMs. In a stateless Worker, every request starts from scratch — you reconstruct context, call a model, return the response, and forget everything. An Agent keeps state between calls, stays connected to clients over WebSocket, and can call models on its own schedule without a user present. -This page covers the patterns that become possible when your LLM calls happen inside a stateful Agent. For provider setup and code examples, refer to [Using AI Models](/agents/api-reference/using-ai-models/). +This page covers the patterns that become possible when your LLM calls happen inside a stateful Agent. For provider setup and code examples, refer to [Using AI Models](/agents/runtime/operations/using-ai-models/). ## State as context -Every Agent has a built-in [SQL database](/agents/api-reference/store-and-sync-state/) and key-value state. Instead of passing an entire conversation history from the client on every request, the Agent stores it and builds prompts from its own storage. +Every Agent has a built-in [SQL database](/agents/runtime/lifecycle/state/) and key-value state. Instead of passing an entire conversation history from the client on every request, the Agent stores it and builds prompts from its own storage. @@ -82,7 +82,7 @@ export class MyAgent extends Agent { -With [`AIChatAgent`](/agents/api-reference/chat-agents/), this is handled automatically — messages are persisted to SQLite and streams resume on reconnect. +With [`AIChatAgent`](/agents/communication-channels/chat/chat-agents/), this is handled automatically — messages are persisted to SQLite and streams resume on reconnect. ## Autonomous model calls @@ -202,24 +202,24 @@ For provider-level caching and rate limit management across multiple agents, use diff --git a/src/content/docs/agents/concepts/memory.mdx b/src/content/docs/agents/concepts/conversation-state-and-memory.mdx similarity index 96% rename from src/content/docs/agents/concepts/memory.mdx rename to src/content/docs/agents/concepts/conversation-state-and-memory.mdx index 6a32f5a1dca..ecd002751b1 100644 --- a/src/content/docs/agents/concepts/memory.mdx +++ b/src/content/docs/agents/concepts/conversation-state-and-memory.mdx @@ -1,11 +1,11 @@ --- -title: Memory +title: Conversation state and memory pcx_content_type: concept description: How agents store and recall information, including read-only context, writable short-form memory, searchable knowledge, and on-demand skills. tags: - AI sidebar: - order: 8 + order: 4 products: - agents --- @@ -14,9 +14,9 @@ import { TypeScriptExample, LinkCard, WranglerConfig } from "~/components"; Agents need memory to be useful over time. Without it, every conversation starts from zero. The agent forgets who the user is, what it learned, and what it was doing. Memory is what turns a stateless LLM call into a persistent, context-aware agent. -The [Session API](/agents/api-reference/sessions/) provides the memory layer for agents built on the Cloudflare Agents SDK. It manages two kinds of memory: **conversation history** (the messages and tool calls that make up a session) and **context memory** (persistent blocks injected into the system prompt that the agent can read, write, search, and load). +The [Session API](/agents/runtime/lifecycle/sessions/) provides the memory layer for agents built on the Cloudflare Agents SDK. It manages two kinds of memory: **conversation history** (the messages and tool calls that make up a session) and **context memory** (persistent blocks injected into the system prompt that the agent can read, write, search, and load). -Use this page when you need more than simple synced state or flat chat history. For small UI state, use [Store and sync state](/agents/api-reference/store-and-sync-state/). For basic chat persistence, `AIChatAgent` stores messages for you. For opinionated long-term memory, Think builds on Session and context blocks. +Use this page when you need more than simple synced state or flat chat history. For small UI state, use [Store and sync state](/agents/runtime/lifecycle/state/). For basic chat persistence, `AIChatAgent` stores messages for you. For opinionated long-term memory, Think builds on Session and context blocks. :::caution[Experimental] @@ -415,7 +415,7 @@ The Session generates tools dynamically based on what provider types are present The tools include descriptions and parameter schemas that tell the LLM which blocks are available and what they are for. The agent decides when and how to use them based on the conversation. -For the full tool signatures and all Session methods, refer to the [Session API reference](/agents/api-reference/sessions/). +For the full tool signatures and all Session methods, refer to the [Session API reference](/agents/runtime/lifecycle/sessions/). ## The system prompt @@ -556,18 +556,17 @@ const truncated = truncateOlderMessages(history); diff --git a/src/content/docs/agents/concepts/human-in-the-loop.mdx b/src/content/docs/agents/concepts/human-in-the-loop.mdx deleted file mode 100644 index 37465d2bc8f..00000000000 --- a/src/content/docs/agents/concepts/human-in-the-loop.mdx +++ /dev/null @@ -1,308 +0,0 @@ ---- -title: Human in the Loop -description: Add human review and approval steps to Cloudflare Agents for compliance, safety, and quality control. -pcx_content_type: concept -sidebar: - order: 5 -products: - - agents ---- - -import { TypeScriptExample, LinkCard } from "~/components"; - -Human-in-the-Loop (HITL) workflows integrate human judgment and oversight into automated processes. These workflows pause at critical points for human review, validation, or decision-making before proceeding. - -## Why human-in-the-loop? - -- **Compliance**: Regulatory requirements may mandate human approval for certain actions. -- **Safety**: High-stakes operations (payments, deletions, external communications) need oversight. -- **Quality**: Human review catches errors AI might miss. -- **Trust**: Users feel more confident when they can approve critical actions. - -### Common use cases - -| Use Case | Example | -| ------------------- | ------------------------------------ | -| Financial approvals | Expense reports, payment processing | -| Content moderation | Publishing, email sending | -| Data operations | Bulk deletions, exports | -| AI tool execution | Confirming tool calls before running | -| Access control | Granting permissions, role changes | - -## Choosing an approach - -The Agents SDK provides five patterns for human-in-the-loop. Choose based on your architecture: - -| Use Case | Pattern | Best For | -| --- | --- | --- | -| Long-running workflows | Workflow Approval | Multi-step processes, durable approval gates that can wait hours or weeks | -| AIChatAgent tools | `needsApproval` | Chat-based tool calls with server-side approval before execution | -| Client-side tools | `onToolCall` | Tools that need browser APIs or user interaction before execution | -| MCP servers | Elicitation | MCP tools requesting structured user input during execution | -| Simple confirmations | State + WebSocket | Lightweight approval flows without AI chat or workflows | - -### Decision tree - -``` -Is this part of a multi-step workflow? -├── Yes → Use Workflow Approval (waitForApproval) -└── No → Are you building an MCP server? - ├── Yes → Use MCP Elicitation (elicitInput) - └── No → Is this an AI chat interaction? - ├── Yes → Does the tool need browser APIs? - │ ├── Yes → Use onToolCall (client-side execution) - │ └── No → Use needsApproval (server-side with approval) - └── No → Use State + WebSocket for simple confirmations -``` - -## Pattern 1: Workflow approval - -For durable, multi-step processes with approval gates that can wait hours, days, or weeks. Use [Cloudflare Workflows](/workflows/) with the `waitForApproval()` method. - -**Key APIs:** - -- `waitForApproval(step, { timeout })` — Pause workflow until approved -- `approveWorkflow(workflowId, { reason?, metadata? })` — Approve a waiting workflow -- `rejectWorkflow(workflowId, { reason? })` — Reject a waiting workflow - -**Best for:** Expense approvals, content publishing pipelines, data export requests - -## Pattern 2: `needsApproval` (AI chat tools) - -For `AIChatAgent` tools that should pause for user confirmation before executing. Define `needsApproval` on the tool — it can be a boolean or an async predicate based on the tool arguments: - - - -```ts -tools: { - processPayment: tool({ - description: "Process a payment", - inputSchema: z.object({ - amount: z.number(), - recipient: z.string(), - }), - needsApproval: async ({ amount }) => amount > 100, - execute: async ({ amount, recipient }) => charge(amount, recipient), - }); -} -``` - - - -On the client, render pending approvals from message parts and call `addToolApprovalResponse`: - - - -```ts -const { messages, addToolApprovalResponse } = useAgentChat({ agent }); - -{ - messages.map((msg) => - msg.parts - .filter( - (part) => part.type === "tool" && part.state === "approval-required", - ) - .map((part) => ( -
-

- Approve {part.toolName}? -

- - -
- )), - ); -} -``` - -
- -For custom denial messages, use `addToolOutput` with `state: "output-error"` instead of `addToolApprovalResponse`: - - - -```ts -addToolOutput({ - toolCallId: part.toolCallId, - state: "output-error", - errorText: "User declined: insufficient budget for this quarter", -}); -``` - - - -## Pattern 3: `onToolCall` (client-side execution) - -For tools that need browser APIs (geolocation, clipboard, camera) or user interaction before returning a result. Define the tool on the server without `execute`, then handle it on the client: - - - -```ts -const { messages, sendMessage } = useAgentChat({ - agent, - onToolCall: async ({ toolCall, addToolOutput }) => { - if (toolCall.toolName === "getLocation") { - const pos = await new Promise((resolve, reject) => - navigator.geolocation.getCurrentPosition(resolve, reject), - ); - addToolOutput({ - toolCallId: toolCall.toolCallId, - output: { lat: pos.coords.latitude, lng: pos.coords.longitude }, - }); - } - }, -}); -``` - - - -When `autoContinueAfterToolResult` is `true` (the default), the conversation automatically continues after the client provides the tool output. - -## Pattern 4: MCP elicitation - -For MCP servers that need to request additional structured input from users during tool execution. The MCP client renders a form based on your JSON Schema: - - - -```ts -export class MyMcpAgent extends McpAgent { - async init() { - this.server.server.setRequestHandler( - CallToolRequestSchema, - async (request, extra) => { - const result = await this.server.server.elicitInput({ - message: "Please confirm the transfer details", - requestedSchema: { - type: "object", - properties: { - confirmed: { type: "boolean", description: "Confirm transfer?" }, - notes: { type: "string", description: "Optional notes" }, - }, - required: ["confirmed"], - }, - }); - - if (result.action === "accept" && result.content?.confirmed) { - return { content: [{ type: "text", text: "Transfer confirmed" }] }; - } - return { content: [{ type: "text", text: "Transfer cancelled" }] }; - }, - ); - } -} -``` - - - -**Best for:** Interactive tool confirmations, gathering additional parameters mid-execution - -## How workflows handle approvals - -![A human-in-the-loop diagram](~/assets/images/agents/human-in-the-loop.svg) - -In a workflow-based approval: - -1. The workflow reaches an approval step and calls `waitForApproval()` -2. The workflow pauses and reports progress to the agent -3. The agent updates its state with the pending approval -4. Connected clients see the pending approval and can approve or reject -5. When approved, the workflow resumes with the approval metadata -6. If rejected or timed out, the workflow handles the rejection appropriately - -## Timeouts and escalation - -Set timeouts to prevent workflows from waiting indefinitely: - - - -```ts -const approval = await this.waitForApproval(step, { - timeout: "7 days", -}); -``` - - - -Use [scheduling](/agents/api-reference/schedule-tasks/) for escalation: - - - -```ts -await this.schedule(86400, "sendApprovalReminder", { workflowId }); - -await this.schedule(604800, "escalateToManager", { workflowId }); -``` - - - -## Best practices - -### Audit trails - -Maintain immutable audit logs of all approval decisions using the [SQL API](/agents/api-reference/store-and-sync-state/). Record: - -- Who made the decision -- When the decision was made -- The reason or justification -- Any relevant metadata - -### Long-term state persistence - -Human review processes do not operate on predictable timelines. A reviewer might need days or weeks to make a decision. Your system needs to maintain state consistency throughout this period — the original request, intermediate decisions, partial progress, and review history. - -:::note[Tip] -[Durable Objects](/durable-objects/) provide persistent compute instances that maintain state for hours, weeks, or months — ideal for long-lived approval flows. -::: - -### Continuous improvement - -Human reviewers play a crucial role in evaluating and improving LLM performance: - -- **Decision quality assessment**: Have reviewers evaluate the LLM's reasoning process and decision points. -- **Edge case identification**: Use human expertise to identify scenarios where performance could be improved. -- **Feedback collection**: Gather structured feedback that can be used to fine-tune the LLM. [AI Gateway](/ai-gateway/evaluations/add-human-feedback/) can help set up an LLM feedback loop. - -### Error handling and recovery - -Your system should gracefully handle reviewer unavailability, system outages, conflicting reviews, and timeout expiration. Implement clear escalation paths for exceptional cases and automatic checkpointing that allows workflows to resume from the last stable state after any interruption. - -## Next steps - - - - - - - - diff --git a/src/content/docs/agents/concepts/tools.mdx b/src/content/docs/agents/concepts/tools.mdx index 6ffcaa27294..3ffba4ef643 100644 --- a/src/content/docs/agents/concepts/tools.mdx +++ b/src/content/docs/agents/concepts/tools.mdx @@ -18,11 +18,11 @@ Cloudflare Agents support several tool patterns. Choose the smallest one that fi | 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/api-reference/chat-agents/#server-side-tools) | -| Client-side tools | The tool needs browser APIs such as geolocation, clipboard, or local storage | [Chat agents](/agents/api-reference/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/human-in-the-loop/) | +| 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/api-reference/agent-tools/) | +| 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/) | ### Understanding tools diff --git a/src/content/docs/agents/concepts/what-are-agents.mdx b/src/content/docs/agents/concepts/what-are-agents.mdx index bfe592e1306..0e6ab0ca45f 100644 --- a/src/content/docs/agents/concepts/what-are-agents.mdx +++ b/src/content/docs/agents/concepts/what-are-agents.mdx @@ -97,12 +97,12 @@ The Cloudflare Agents SDK provides the infrastructure for building production ag diff --git a/src/content/docs/agents/concepts/workflows.mdx b/src/content/docs/agents/concepts/workflows.mdx index 09bb8b67add..ed9bd495115 100644 --- a/src/content/docs/agents/concepts/workflows.mdx +++ b/src/content/docs/agents/concepts/workflows.mdx @@ -1,9 +1,9 @@ --- -title: Workflows +title: Using Agents with Workflows description: Integrate Cloudflare Workflows with Agents for durable, multi-step background processing with automatic retries. pcx_content_type: concept sidebar: - order: 3 + order: 7 products: - agents --- @@ -37,8 +37,7 @@ Agents can loop, branch, and interact directly with users. Workflows execute ste - Quick API calls and responses - Real-time collaborative features - Tasks under 30 seconds -- One durable Think chat turn with [`submitMessages()`](/agents/think/programmatic-submissions/#submitmessages) - +- One durable Think chat turn with [`submitMessages()`](/agents/harnesses/think/programmatic-submissions/#submitmessages) **Use Agents with Workflows for:** - Data processing pipelines @@ -187,7 +186,7 @@ A Workflow updates Agent state at key milestones using `step.updateAgentState()` @@ -199,6 +198,6 @@ A Workflow updates Agent state at key milestones using `step.updateAgentState()` diff --git a/src/content/docs/agents/api-reference/browse-the-web.mdx b/src/content/docs/agents/examples/browser-agent.mdx similarity index 96% rename from src/content/docs/agents/api-reference/browse-the-web.mdx rename to src/content/docs/agents/examples/browser-agent.mdx index 5b72d21a087..d54c208f4aa 100644 --- a/src/content/docs/agents/api-reference/browse-the-web.mdx +++ b/src/content/docs/agents/examples/browser-agent.mdx @@ -1,11 +1,9 @@ --- -title: Browse the web -description: Give Agents full Chrome DevTools Protocol access to inspect pages, scrape data, and capture screenshots with Browser Run. -pcx_content_type: reference +title: Browser agent +pcx_content_type: example +description: Build an agent that uses Browser Run tools to inspect pages, capture screenshots, scrape rendered content, and debug frontend issues. sidebar: - order: 21 -products: - - agents + order: 3 --- import { @@ -15,7 +13,7 @@ import { PackageManagers, } from "~/components"; -Give your agents full access to the [Chrome DevTools Protocol (CDP)](/browser-run/cdp/) with [Browser Run](/browser-run/) tools. +Build an agent that can browse the web, inspect pages, capture screenshots, and debug frontend issues with [Browser Run](/browser-run/) tools. Instead of a fixed set of browser actions (click, screenshot, navigate), the LLM writes JavaScript code that runs CDP commands against a live browser session — accessing all domains, commands, events, and types in the protocol. @@ -146,7 +144,7 @@ async () => { ## Use with an Agent -The typical pattern is to create browser tools inside an [`AIChatAgent`](/agents/api-reference/chat-agents/) message handler, which gives you message persistence and streaming: +The typical pattern is to create browser tools inside an [`AIChatAgent`](/agents/communication-channels/chat/chat-agents/) message handler, which gives you message persistence and streaming: diff --git a/src/content/docs/agents/getting-started/build-a-chat-agent.mdx b/src/content/docs/agents/examples/chat-agent.mdx similarity index 97% rename from src/content/docs/agents/getting-started/build-a-chat-agent.mdx rename to src/content/docs/agents/examples/chat-agent.mdx index d62979ab51a..99a448e3882 100644 --- a/src/content/docs/agents/getting-started/build-a-chat-agent.mdx +++ b/src/content/docs/agents/examples/chat-agent.mdx @@ -1,9 +1,9 @@ --- -title: Build a chat agent -pcx_content_type: tutorial +title: Chat agent +pcx_content_type: example difficulty: Intermediate sidebar: - order: 4 + order: 1 head: [] description: Build a streaming AI chat agent with tools using Workers AI — no API keys required. products: @@ -352,24 +352,24 @@ Your chat agent has: diff --git a/src/content/docs/agents/api-reference/email.mdx b/src/content/docs/agents/examples/email-agent.mdx similarity index 95% rename from src/content/docs/agents/api-reference/email.mdx rename to src/content/docs/agents/examples/email-agent.mdx index b67bd8d9ce0..c9de40a1e70 100644 --- a/src/content/docs/agents/api-reference/email.mdx +++ b/src/content/docs/agents/examples/email-agent.mdx @@ -1,11 +1,9 @@ --- -title: Email -description: Send and receive email from Cloudflare Agents using the Email Service binding and inbound routing rules. -pcx_content_type: concept +title: Email agent +pcx_content_type: example +description: Build an agent that sends, receives, routes, and replies to email using Cloudflare Email Service and the Agents SDK. sidebar: - order: 16 -products: - - agents + order: 4 --- import { TypeScriptExample, WranglerConfig, LinkCard } from "~/components"; @@ -511,20 +509,20 @@ When your agent sends emails and expects replies, use secure reply routing to pr ```ts export default { - async email(message, env) { - const secureReplyResolver = createSecureReplyEmailResolver( - env.EMAIL_SECRET, - ); - const addressResolver = createAddressBasedEmailResolver("EmailAgent"); - - await routeAgentEmail(message, env, { - resolver: async (email, env) => { - const replyRouting = await secureReplyResolver(email, env); - if (replyRouting) return replyRouting; - return addressResolver(email, env); - }, - }); - }, + async email(message, env) { + const secureReplyResolver = createSecureReplyEmailResolver( + env.EMAIL_SECRET, + ); + const addressResolver = createAddressBasedEmailResolver("EmailAgent"); + + await routeAgentEmail(message, env, { + resolver: async (email, env) => { + const replyRouting = await secureReplyResolver(email, env); + if (replyRouting) return replyRouting; + return addressResolver(email, env); + }, + }); + }, } satisfies ExportedHandler; ``` @@ -536,13 +534,13 @@ When your agent sends emails and expects replies, use secure reply routing to pr ```ts class MyAgent extends Agent { - async onEmail(email: AgentEmail) { - await this.replyToEmail(email, { - fromName: "My Agent", - body: "Thanks for your email!", - secret: this.env.EMAIL_SECRET, // Signs the routing headers - }); - } + async onEmail(email: AgentEmail) { + await this.replyToEmail(email, { + fromName: "My Agent", + body: "Thanks for your email!", + secret: this.env.EMAIL_SECRET, // Signs the routing headers + }); + } } ``` @@ -758,18 +756,18 @@ Useful when sending emails through external services while maintaining secure re diff --git a/src/content/docs/agents/examples/index.mdx b/src/content/docs/agents/examples/index.mdx new file mode 100644 index 00000000000..30f96cdf37a --- /dev/null +++ b/src/content/docs/agents/examples/index.mdx @@ -0,0 +1,14 @@ +--- +title: Examples +pcx_content_type: navigation +sidebar: + order: 7 + group: + hideIndex: true +--- + +import { DirectoryListing } from "~/components"; + +End-to-end examples showing how to build complete agents. + + diff --git a/src/content/docs/agents/guides/slack-agent.mdx b/src/content/docs/agents/examples/slack-agent.mdx similarity index 98% rename from src/content/docs/agents/guides/slack-agent.mdx rename to src/content/docs/agents/examples/slack-agent.mdx index b2c4d3d8719..084cd174af7 100644 --- a/src/content/docs/agents/guides/slack-agent.mdx +++ b/src/content/docs/agents/examples/slack-agent.mdx @@ -1,9 +1,9 @@ --- -pcx_content_type: concept -title: Build a Slack Agent +pcx_content_type: example +title: Slack agent description: Build and deploy an AI-powered Slack bot on Cloudflare Workers using the Agents SDK. sidebar: - order: 5 + order: 1 products: - agents --- @@ -456,11 +456,11 @@ export class MyAgent extends SlackAgent { ## Next steps - Add [Slack Interactive Components](https://api.slack.com/interactivity) (buttons, modals) -- Connect your Agent to an [MCP server](/agents/api-reference/mcp-client-api/) +- Connect your Agent to an [MCP server](/agents/model-context-protocol/apis/client-api/) - Add rate limiting to prevent abuse - Implement conversation state management - Use [Workers Analytics Engine](/analytics/analytics-engine/) to track usage -- Add [schedules](/agents/api-reference/schedule-tasks/) for scheduled tasks +- Add [schedules](/agents/runtime/execution/schedule-tasks/) for scheduled tasks ## Related resources diff --git a/src/content/docs/agents/guides/build-a-voice-agent.mdx b/src/content/docs/agents/examples/voice-agent.mdx similarity index 97% rename from src/content/docs/agents/guides/build-a-voice-agent.mdx rename to src/content/docs/agents/examples/voice-agent.mdx index 643cd7244e3..2c8df8e0f91 100644 --- a/src/content/docs/agents/guides/build-a-voice-agent.mdx +++ b/src/content/docs/agents/examples/voice-agent.mdx @@ -1,9 +1,9 @@ --- -title: Build a voice agent +title: Voice agent description: Build a real-time voice agent with speech-to-text, LLM processing, and text-to-speech on Cloudflare Workers. -pcx_content_type: tutorial +pcx_content_type: example sidebar: - order: 15 + order: 2 products: - workers - agents @@ -290,18 +290,18 @@ export class MyVoiceAgent extends VoiceAgent { diff --git a/src/content/docs/agents/getting-started/add-to-existing-project.mdx b/src/content/docs/agents/getting-started/add-to-existing-project.mdx index 220de7622be..326728cf0e8 100644 --- a/src/content/docs/agents/getting-started/add-to-existing-project.mdx +++ b/src/content/docs/agents/getting-started/add-to-existing-project.mdx @@ -15,7 +15,7 @@ import { LinkCard, } 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/getting-started/build-a-chat-agent/) instead. +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. ## Prerequisites @@ -146,7 +146,7 @@ export default defineConfig({ If your project does not use Vite, the `tsconfig.json` change alone is sufficient — your bundler must support TC39 decorators (stage 3, version `2023-11`). -For more details, refer to the [TypeScript configuration](/agents/api-reference/configuration/#typescript-configuration) and [Vite configuration](/agents/api-reference/configuration/#vite-configuration) reference. +For more details, refer to the [TypeScript configuration](/agents/runtime/operations/configuration/#typescript-configuration) and [Vite configuration](/agents/runtime/operations/configuration/#vite-configuration) reference. ## 5. Export the Agent class @@ -271,7 +271,7 @@ npx wrangler types This creates a type definition file with all your bindings typed, including your agent Durable Object namespaces. The `Agent` class defaults to using the generated `Env` type, so you do not need to pass it as a type parameter — `extends Agent` is sufficient unless you need to pass a second type parameter for state (for example, `Agent`). -Refer to [Configuration](/agents/api-reference/configuration/#generating-types) for more details on type generation. +Refer to [Configuration](/agents/runtime/operations/configuration/#generating-types) for more details on type generation. ## 8. Connect from the frontend @@ -426,7 +426,7 @@ const agentResponse = await routeAgentRequest(request, env, { -Refer to [Routing](/agents/api-reference/routing/) for more options including CORS, custom instance naming, and location hints. +Refer to [Routing](/agents/runtime/communication/routing/) for more options including CORS, custom instance naming, and location hints. ### Accessing agents from server code @@ -508,24 +508,24 @@ Check that: diff --git a/src/content/docs/agents/getting-started/index.mdx b/src/content/docs/agents/getting-started/index.mdx index 3f38062162b..8566f53c0a8 100644 --- a/src/content/docs/agents/getting-started/index.mdx +++ b/src/content/docs/agents/getting-started/index.mdx @@ -24,7 +24,7 @@ Start building agents that can remember context, communicate with users, and act diff --git a/src/content/docs/agents/getting-started/prompting.mdx b/src/content/docs/agents/getting-started/prompting.mdx deleted file mode 100644 index e4e33896fc3..00000000000 --- a/src/content/docs/agents/getting-started/prompting.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -pcx_content_type: navigation -title: Prompt an AI model -external_link: /workers/get-started/prompting/ -sidebar: - order: 5 -head: [] -description: Use the Workers "mega prompt" to build Agents using your preferred AI tools and IDEs. The prompt understands the Agents SDK APIs, best practices, and guidelines, and makes it easier to build valid Agents and Workers. -products: - - agents ---- diff --git a/src/content/docs/agents/getting-started/quick-start.mdx b/src/content/docs/agents/getting-started/quick-start.mdx index d6e4ccd0007..e1ff81f5caf 100644 --- a/src/content/docs/agents/getting-started/quick-start.mdx +++ b/src/content/docs/agents/getting-started/quick-start.mdx @@ -333,34 +333,34 @@ Now that you have a working agent, explore these topics: | Learn how to | Refer to | | ------------------------ | --------------------------------------------------------- | -| Add AI/LLM capabilities | [Using AI models](/agents/api-reference/using-ai-models/) | -| Expose tools via MCP | [MCP servers](/agents/api-reference/mcp-agent-api/) | -| Run background tasks | [Schedule tasks](/agents/api-reference/schedule-tasks/) | -| Handle emails | [Email routing](/agents/api-reference/email/) | -| Use Cloudflare Workflows | [Run Workflows](/agents/api-reference/run-workflows/) | +| Add AI/LLM capabilities | [Using AI models](/agents/runtime/operations/using-ai-models/) | +| Expose tools via MCP | [MCP servers](/agents/model-context-protocol/apis/agent-api/) | +| Run background tasks | [Schedule tasks](/agents/runtime/execution/schedule-tasks/) | +| Handle emails | [Email routing](/agents/communication-channels/email/) | +| Use Cloudflare Workflows | [Run Workflows](/agents/runtime/execution/run-workflows/) | ### Explore more diff --git a/src/content/docs/agents/guides/anthropic-agent-patterns.mdx b/src/content/docs/agents/guides/anthropic-agent-patterns.mdx deleted file mode 100644 index 714eca656d0..00000000000 --- a/src/content/docs/agents/guides/anthropic-agent-patterns.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -pcx_content_type: navigation -title: Implement Effective Agent Patterns -external_link: https://github.com/cloudflare/agents/tree/main/guides/anthropic-patterns -sidebar: - order: 2 -head: [] -description: Implement common agent patterns using the Agents SDK framework. -products: - - agents ---- diff --git a/src/content/docs/agents/harnesses/index.mdx b/src/content/docs/agents/harnesses/index.mdx new file mode 100644 index 00000000000..bb7b75c9603 --- /dev/null +++ b/src/content/docs/agents/harnesses/index.mdx @@ -0,0 +1,69 @@ +--- +title: Harnesses +description: Understand agent harnesses — the loop that controls planning, tool use, and response flow. +pcx_content_type: concept +sidebar: + order: 5 +--- + +import { LinkCard } from "~/components"; + +A harness is the loop that makes an agent behave like an agent instead of a single model call. + +It is responsible for the turn-by-turn work around the model: building the prompt, loading memory, selecting tools, handling tool results, streaming responses, persisting messages, and deciding whether the agent should continue or stop. + +You can build this loop yourself on top of the [Agents SDK runtime](/agents/runtime/agents-api/), or use an opinionated harness like [Project Think](/agents/harnesses/think/). + +## How harnesses fit + +Harnesses sit on top of the Agents SDK runtime: + +- **The runtime** gives the agent durable infrastructure: the [`Agent` class](/agents/runtime/lifecycle/agent-class/), [state](/agents/runtime/lifecycle/state/), [sessions](/agents/runtime/lifecycle/sessions/), [routing](/agents/runtime/communication/routing/), [WebSockets](/agents/runtime/communication/websockets/), [scheduling](/agents/runtime/execution/schedule-tasks/), [fibers](/agents/runtime/execution/durable-execution/), and [observability](/agents/runtime/operations/observability/). +- **The harness** gives the agent behavior: model calls, prompt construction, tool selection, stream handling, memory strategy, and lifecycle hooks. + +The runtime answers “where does this agent live and how does it stay durable?” The harness answers “what does this agent do on each turn?” + +## Choose an approach + +Use a build-your-own harness when you need full control over the model call, message format, tool loop, or UI protocol. This is the right approach when you want to compose low-level APIs directly from the Agents SDK. + +Use Project Think when you want an opinionated chat-agent harness with defaults for memory, workspace tools, streaming, lifecycle hooks, sub-agent RPC, and durable chat recovery. + +## Current harnesses + + + +## What a harness usually owns + +A harness usually owns: + +- **Prompt construction** — system prompts, memory, retrieved context, and per-turn instructions. +- **Model execution** — the call to Workers AI, OpenAI, Anthropic, Gemini, or another provider. +- **Tool orchestration** — server tools, client tools, MCP tools, approval flows, and continuation after tool results. +- **Message persistence** — how user, assistant, and tool messages are saved and replayed. +- **Streaming and recovery** — how responses stream to clients and resume after disconnects or Durable Object eviction. +- **Extension points** — hooks before and after turns, steps, tool calls, and recovery events. + +## Related resources + + + + + + diff --git a/src/content/docs/agents/think/client-tools.mdx b/src/content/docs/agents/harnesses/think/client-tools.mdx similarity index 100% rename from src/content/docs/agents/think/client-tools.mdx rename to src/content/docs/agents/harnesses/think/client-tools.mdx diff --git a/src/content/docs/agents/think/configuration.mdx b/src/content/docs/agents/harnesses/think/configuration.mdx similarity index 86% rename from src/content/docs/agents/think/configuration.mdx rename to src/content/docs/agents/harnesses/think/configuration.mdx index 26663eef6ec..33522f6c309 100644 --- a/src/content/docs/agents/think/configuration.mdx +++ b/src/content/docs/agents/harnesses/think/configuration.mdx @@ -19,21 +19,21 @@ Think is configured by overriding methods and properties on your `Think` subclas | `getModel()` | throws | Return the `LanguageModel` to use | | `getSystemPrompt()` | `"You are a helpful assistant."` | System prompt (fallback when no context blocks) | | `getTools()` | `{}` | AI SDK `ToolSet` for the agentic loop | -| `getScheduledTasks()` | `{}` | Code-declared recurring prompts or handlers — refer to [Scheduled tasks](/agents/think/scheduled-tasks/) | +| `getScheduledTasks()` | `{}` | Code-declared recurring prompts or handlers — refer to [Scheduled tasks](/agents/harnesses/think/scheduled-tasks/) | | `getDefaultTimezone()` | `undefined` | Default timezone for wall-clock scheduled tasks | -| `getMessengers()` | `{}` | Messenger ingress and delivery declarations — refer to [Messengers](/agents/think/messengers/) | +| `getMessengers()` | `{}` | Messenger ingress and delivery declarations — refer to [Messengers](/agents/harnesses/think/messengers/) | | `maxSteps` | `10` | Max tool-call rounds per turn | | `sendReasoning` | `true` | Send reasoning chunks to chat clients | -| `configureSession()` | identity | Add context blocks, compaction, search, skills — refer to [Sessions](/agents/api-reference/sessions/) | -| `getSkills()` | `[]` | Return Agent Skills sources for on-demand skill activation — refer to [Agent Skills](/agents/api-reference/agent-skills/) | +| `configureSession()` | identity | Add context blocks, compaction, search, skills — refer to [Sessions](/agents/runtime/lifecycle/sessions/) | +| `getSkills()` | `[]` | Return Agent Skills sources for on-demand skill activation — refer to [Agent Skills](/agents/runtime/execution/agent-skills/) | | `getSkillScriptRunner()` | `null` | Enable the optional `run_skill_script` tool | -| `workspaceBash` | `true` | Include or configure the default workspace `bash` tool — refer to [Tools](/agents/think/tools/) | -| `messageConcurrency` | `"queue"` | How overlapping submits behave — refer to [Client tools](/agents/think/client-tools/#message-concurrency) | +| `workspaceBash` | `true` | Include or configure the default workspace `bash` tool — refer to [Tools](/agents/harnesses/think/tools/) | +| `messageConcurrency` | `"queue"` | How overlapping submits behave — refer to [Client tools](/agents/harnesses/think/client-tools/#message-concurrency) | | `waitForMcpConnections` | `false` | Wait for MCP servers before inference | | `chatRecovery` | `true` | Wrap WebSocket, sub-agent, programmatic, and continuation turns in `runFiber` for durable execution. Set to `{ maxAttempts, stableTimeoutMs, terminalMessage, onExhausted }` to tune bounded recovery | | `chatStreamStallTimeoutMs` | `0` (off) | Opt-in inactivity watchdog: abort a turn whose model stream produces no chunk for this long (measures the gap between chunks, including tool execution). With `chatRecovery` on, a stall routes into bounded recovery | -For `chatRecovery` and `chatStreamStallTimeoutMs` behavior, refer to [Durable recovery](/agents/think/recovery/). +For `chatRecovery` and `chatStreamStallTimeoutMs` behavior, refer to [Durable recovery](/agents/harnesses/think/recovery/). ## Dynamic configuration @@ -86,7 +86,7 @@ export class MyAgent extends Think { ## Session integration -Think stores conversations in a [Session](/agents/api-reference/sessions/) — the storage layer that holds your messages and gives the model writable memory. Two concepts come up here: **context blocks** are labelled sections of the system prompt the model can read and update (for example, a `memory` block of facts about the user), and **compaction** summarizes older messages so long conversations stay within the model's context window. Override `configureSession` to add persistent memory, compaction, search, and skills: +Think stores conversations in a [Session](/agents/runtime/lifecycle/sessions/) — the storage layer that holds your messages and gives the model writable memory. Two concepts come up here: **context blocks** are labelled sections of the system prompt the model can read and update (for example, a `memory` block of facts about the user), and **compaction** summarizes older messages so long conversations stay within the model's context window. Override `configureSession` to add persistent memory, compaction, search, and skills: @@ -116,7 +116,7 @@ export class MyAgent extends Think { When `configureSession` adds context blocks, Think builds the system prompt from those blocks instead of using `getSystemPrompt()`. Think's `this.messages` getter reads directly from Session's tree-structured storage. -For the full Session API — context blocks, compaction, search, skills, and multi-session support — refer to the [Sessions documentation](/agents/api-reference/sessions/). +For the full Session API — context blocks, compaction, search, skills, and multi-session support — refer to the [Sessions documentation](/agents/runtime/lifecycle/sessions/). ## Package exports @@ -151,4 +151,4 @@ Bundled with `@cloudflare/think`: | `@cloudflare/codemode` | Code execution for `createExecuteTool()` | | `just-bash` | Sandboxed shell for the default workspace `bash` tool | -The Agent Skills engine and its script runner live in [`agents/skills`](/agents/api-reference/agent-skills/), so skill scripts pull `@cloudflare/worker-bundler` and `just-bash` through `agents`, not Think. +The Agent Skills engine and its script runner live in [`agents/skills`](/agents/runtime/execution/agent-skills/), so skill scripts pull `@cloudflare/worker-bundler` and `just-bash` through `agents`, not Think. diff --git a/src/content/docs/agents/think/getting-started.mdx b/src/content/docs/agents/harnesses/think/getting-started.mdx similarity index 91% rename from src/content/docs/agents/think/getting-started.mdx rename to src/content/docs/agents/harnesses/think/getting-started.mdx index 7f002ffb12a..ade92ba3198 100644 --- a/src/content/docs/agents/think/getting-started.mdx +++ b/src/content/docs/agents/harnesses/think/getting-started.mdx @@ -253,7 +253,7 @@ Now the model sees a `MEMORY` section in its system prompt and gets a `set_conte When you use `configureSession`, the system prompt is built from context blocks rather than `getSystemPrompt()`. The `"soul"` block above acts as the system identity — it is read-only and always appears first. The `"memory"` block is writable, and the model proactively updates it when it learns something useful. -Refer to the [Sessions documentation](/agents/api-reference/sessions/) for context blocks, compaction, search, skills, and multi-session support. +Refer to the [Sessions documentation](/agents/runtime/lifecycle/sessions/) for context blocks, compaction, search, skills, and multi-session support. ## 7. Add custom tools @@ -336,12 +336,12 @@ export class MyAgent extends Think { -Refer to [Lifecycle hooks](/agents/think/lifecycle-hooks/) for the full reference. +Refer to [Lifecycle hooks](/agents/harnesses/think/lifecycle-hooks/) for the full reference. ## Next steps -- [Lifecycle hooks](/agents/think/lifecycle-hooks/) — control model behavior, switch models per-turn, restrict tools -- [Tools](/agents/think/tools/) — workspace tools, code execution, extensions -- [Client tools](/agents/think/client-tools/) — browser-side tools, approval flows, concurrency -- [Sub-agent RPC and programmatic turns](/agents/think/sub-agents/) — RPC streaming, scheduled turns, recovery -- [Sessions](/agents/api-reference/sessions/) — context blocks, compaction, search, multi-session +- [Lifecycle hooks](/agents/harnesses/think/lifecycle-hooks/) — control model behavior, switch models per-turn, restrict tools +- [Tools](/agents/harnesses/think/tools/) — workspace tools, code execution, extensions +- [Client tools](/agents/harnesses/think/client-tools/) — browser-side tools, approval flows, concurrency +- [Sub-agent RPC and programmatic turns](/agents/harnesses/think/sub-agents/) — RPC streaming, scheduled turns, recovery +- [Sessions](/agents/runtime/lifecycle/sessions/) — context blocks, compaction, search, multi-session diff --git a/src/content/docs/agents/think/index.mdx b/src/content/docs/agents/harnesses/think/index.mdx similarity index 77% rename from src/content/docs/agents/think/index.mdx rename to src/content/docs/agents/harnesses/think/index.mdx index 4c7392baed6..55c1ddab27c 100644 --- a/src/content/docs/agents/think/index.mdx +++ b/src/content/docs/agents/harnesses/think/index.mdx @@ -24,7 +24,7 @@ import { Think works as both a **top-level agent** (WebSocket chat to browser clients via `useAgentChat`) and a **sub-agent** (a child agent that another agent drives over RPC via `chat()`). :::note[New to Cloudflare Agents?] -If this is your first agent, start with the [Getting started tutorial](/agents/think/getting-started/) for a guided build. For the bigger picture of what agents are and how they run, read [What are agents?](/agents/concepts/what-are-agents/). Think builds on two Cloudflare primitives worth a quick look: [Workers AI](/workers-ai/) provides the model, and each agent instance is a [Durable Object](/durable-objects/) that stores its state. The rest of this section is reference material you can dip into as you need it. +If this is your first agent, start with the [Getting started tutorial](/agents/harnesses/think/getting-started/) for a guided build. For the bigger picture of what agents are and how they run, read [What are agents?](/agents/concepts/what-are-agents/). Think builds on two Cloudflare primitives worth a quick look: [Workers AI](/workers-ai/) provides the model, and each agent instance is a [Durable Object](/durable-objects/) that stores its state. The rest of this section is reference material you can dip into as you need it. ::: ## Quick start @@ -133,7 +133,7 @@ tag = "v1" ## Think vs AIChatAgent -Both Think and [`AIChatAgent`](/agents/api-reference/chat-agents/) extend `Agent` and speak the same `cf_agent_chat_*` WebSocket protocol. They serve different goals. +Both Think and [`AIChatAgent`](/agents/communication-channels/chat/chat-agents/) extend `Agent` and speak the same `cf_agent_chat_*` WebSocket protocol. They serve different goals. **AIChatAgent** is a protocol adapter. You override `onChatMessage` and are responsible for calling `streamText`, wiring tools, converting messages, and returning a `Response`. AIChatAgent handles the plumbing — message persistence, streaming, abort, resume — but the LLM call is entirely your concern. @@ -183,73 +183,73 @@ Think has several ways to start or continue a turn. Choose based on who starts t | Add context or messages without starting a model turn | `persistMessages()` | | Advanced subclass or recovery code continues an assistant turn | `continueLastTurn()` | -Use `saveMessages()` when the caller owns the trigger and can wait for the turn to finish. Use [`submitMessages()`](/agents/think/programmatic-submissions/) when timeout ambiguity would make retries unsafe. +Use `saveMessages()` when the caller owns the trigger and can wait for the turn to finish. Use [`submitMessages()`](/agents/harnesses/think/programmatic-submissions/) when timeout ambiguity would make retries unsafe. -Use `chat()` for low-level parent-to-child streaming when your code owns forwarding, cancellation, and replay policy. Use [Agent tools](/agents/api-reference/agent-tools/) when a parent model or workflow delegates to a child agent and you want retained child runs, event replay, abort bridging, and UI drill-in. +Use `chat()` for low-level parent-to-child streaming when your code owns forwarding, cancellation, and replay policy. Use [Agent tools](/agents/runtime/execution/agent-tools/) when a parent model or workflow delegates to a child agent and you want retained child runs, event replay, abort bridging, and UI drill-in. -Use [`startFiber()`](/agents/api-reference/durable-execution/#startfiber) outside Think when the durable unit is an application job around a turn: accepting a webhook once, restoring a serialized channel or thread target, posting a visible reply, or recording app-level recovery policy. Think submissions own conversation admission and turn serialization; managed fibers own external job acceptance, idempotent side effects, and application recovery. +Use [`startFiber()`](/agents/runtime/execution/durable-execution/#startfiber) outside Think when the durable unit is an application job around a turn: accepting a webhook once, restoring a serialized channel or thread target, posting a visible reply, or recording app-level recovery policy. Think submissions own conversation admission and turn serialization; managed fibers own external job acceptance, idempotent side effects, and application recovery. ## In this section @@ -268,9 +268,9 @@ Think's design is inspired by [Pi](https://pi.dev). ## Related -- [Sessions](/agents/api-reference/sessions/) — context blocks, compaction, search, multi-session (the storage layer Think builds on) -- [Sub-agents](/agents/api-reference/sub-agents/) — `subAgent()`, `abortSubAgent()`, `deleteSubAgent()` (the base Agent methods for spawning children) -- [Chat agents](/agents/api-reference/chat-agents/) — `AIChatAgent` for when you need full control over the LLM call -- [Long-running agents](/agents/concepts/long-running-agents/) — sub-agent delegation patterns for multi-week agent lifetimes -- [Durable execution](/agents/api-reference/durable-execution/) — `runFiber()` and crash recovery (used by `chatRecovery`) -- [Browse the web](/agents/api-reference/browse-the-web/) — full CDP helper API reference +- [Sessions](/agents/runtime/lifecycle/sessions/) — context blocks, compaction, search, multi-session (the storage layer Think builds on) +- [Sub-agents](/agents/runtime/execution/sub-agents/) — `subAgent()`, `abortSubAgent()`, `deleteSubAgent()` (the base Agent methods for spawning children) +- [Chat agents](/agents/communication-channels/chat/chat-agents/) — `AIChatAgent` for when you need full control over the LLM call +- [Long-running agents](/agents/concepts/agentic-patterns/long-running-agents/) — sub-agent delegation patterns for multi-week agent lifetimes +- [Durable execution](/agents/runtime/execution/durable-execution/) — `runFiber()` and crash recovery (used by `chatRecovery`) +- [Browse the web](/agents/tools/browser/) — full CDP helper API reference diff --git a/src/content/docs/agents/think/lifecycle-hooks.mdx b/src/content/docs/agents/harnesses/think/lifecycle-hooks.mdx similarity index 99% rename from src/content/docs/agents/think/lifecycle-hooks.mdx rename to src/content/docs/agents/harnesses/think/lifecycle-hooks.mdx index 44780844199..bec16a6f616 100644 --- a/src/content/docs/agents/think/lifecycle-hooks.mdx +++ b/src/content/docs/agents/harnesses/think/lifecycle-hooks.mdx @@ -78,7 +78,7 @@ All fields are optional. Return only what you want to change. | `toolChoice` | `ToolChoice` | Force a specific tool call | | `maxSteps` | `number` | Override `maxSteps` for this turn | | `sendReasoning` | `boolean` | Send reasoning chunks for this turn | -| `chatStreamStallTimeoutMs` | `number` | Override the stream-stall watchdog for this turn (`0` disables it); auto-resets after the turn. Useful for a turn with a known-slow tool — refer to [Durable recovery](/agents/think/recovery/) | +| `chatStreamStallTimeoutMs` | `number` | Override the stream-stall watchdog for this turn (`0` disables it); auto-resets after the turn. Useful for a turn with a known-slow tool — refer to [Durable recovery](/agents/harnesses/think/recovery/) | | `output` | `Output` | Request structured output for this turn | | `providerOptions` | `Record` | Provider-specific options | | `experimental_telemetry` | `object` | AI SDK telemetry settings for this turn | diff --git a/src/content/docs/agents/think/messengers.mdx b/src/content/docs/agents/harnesses/think/messengers.mdx similarity index 98% rename from src/content/docs/agents/think/messengers.mdx rename to src/content/docs/agents/harnesses/think/messengers.mdx index 24c6fe6d988..601af04155f 100644 --- a/src/content/docs/agents/think/messengers.mdx +++ b/src/content/docs/agents/harnesses/think/messengers.mdx @@ -196,4 +196,4 @@ Every custom messenger must provide `verifyWebhook` or explicitly use `verifyWeb The `examples/think-chat-sdk` example demonstrates the Think-native `getMessengers()` path with a small Vite dashboard that inspects the root Think conversation over the Agent WebSocket. -The `examples/chat-sdk-messenger` example demonstrates a larger manual ingress agent with an admin dashboard, menu handling, and application-owned reply fibers. Use `getMessengers()` for the simple Think-native path. Use the example when you need to own the Chat SDK runtime and control-plane UI yourself. Refer to [Chat SDK state](/agents/api-reference/chat-sdk/) for the underlying state adapter. +The `examples/chat-sdk-messenger` example demonstrates a larger manual ingress agent with an admin dashboard, menu handling, and application-owned reply fibers. Use `getMessengers()` for the simple Think-native path. Use the example when you need to own the Chat SDK runtime and control-plane UI yourself. Refer to [Chat SDK state](/agents/runtime/execution/chat-sdk/) for the underlying state adapter. diff --git a/src/content/docs/agents/think/programmatic-submissions.mdx b/src/content/docs/agents/harnesses/think/programmatic-submissions.mdx similarity index 90% rename from src/content/docs/agents/think/programmatic-submissions.mdx rename to src/content/docs/agents/harnesses/think/programmatic-submissions.mdx index 08c84a90166..94b39eeeb15 100644 --- a/src/content/docs/agents/think/programmatic-submissions.mdx +++ b/src/content/docs/agents/harnesses/think/programmatic-submissions.mdx @@ -12,7 +12,7 @@ import { TypeScriptExample } from "~/components"; Durably accept a Think turn and return before inference runs. Use `submitMessages()` for webhook handlers, RPC callers, and parent Workers that need a fast acknowledgement, safe retry, and later status inspection. -Declarative [scheduled prompt tasks](/agents/think/scheduled-tasks/) use the same durable submission path under the hood. Use `getScheduledTasks()` when the trigger is recurring and code-declared; use `submitMessages()` directly when an external caller or webhook creates one-off work. To wait for the response inline, use [`saveMessages()`](/agents/think/sub-agents/#savemessages) instead. +Declarative [scheduled prompt tasks](/agents/harnesses/think/scheduled-tasks/) use the same durable submission path under the hood. Use `getScheduledTasks()` when the trigger is recurring and code-declared; use `submitMessages()` directly when an external caller or webhook creates one-off work. To wait for the response inline, use [`saveMessages()`](/agents/harnesses/think/sub-agents/#savemessages) instead. ## submitMessages @@ -119,4 +119,4 @@ If the chat is cleared or turn state is reset before a pending submission runs, ## Compared with Workflows -Use Workflows for multi-step orchestration, retries per step, long waits, external events, human approvals, or pipelines that may trigger Think as one part of a larger process. Refer to [Think Workflows](/agents/think/workflows/). +Use Workflows for multi-step orchestration, retries per step, long waits, external events, human approvals, or pipelines that may trigger Think as one part of a larger process. Refer to [Think Workflows](/agents/harnesses/think/workflows/). diff --git a/src/content/docs/agents/think/recovery.mdx b/src/content/docs/agents/harnesses/think/recovery.mdx similarity index 94% rename from src/content/docs/agents/think/recovery.mdx rename to src/content/docs/agents/harnesses/think/recovery.mdx index ece916d28ac..f7cb5550bfb 100644 --- a/src/content/docs/agents/think/recovery.mdx +++ b/src/content/docs/agents/harnesses/think/recovery.mdx @@ -10,7 +10,7 @@ products: import { TypeScriptExample } from "~/components"; -Think wraps chat turns in recoverable [fibers](/agents/api-reference/durable-execution/) by default (`chatRecovery = true`). If the Durable Object is evicted mid-stream, Think reconstructs any buffered chunks, persists partial output, and schedules either a continuation of the assistant turn or a retry of the unanswered user turn. +Think wraps chat turns in recoverable [fibers](/agents/runtime/execution/durable-execution/) by default (`chatRecovery = true`). If the Durable Object is evicted mid-stream, Think reconstructs any buffered chunks, persists partial output, and schedules either a continuation of the assistant turn or a retry of the unanswered user turn. :::note This is on by default and works without configuration — most apps never touch this page. Read it when you want provider-specific recovery, a stall watchdog, or to tune the terminal experience after recovery gives up. @@ -45,7 +45,7 @@ export class MyAgent extends Think { -The same recovery events are available through `agents/observability` on the `chat` channel; transcript repairs are emitted on the `transcript` channel. Refer to [Observability](/agents/api-reference/observability/#chat-recovery-events). +The same recovery events are available through `agents/observability` on the `chat` channel; transcript repairs are emitted on the `transcript` channel. Refer to [Observability](/agents/runtime/operations/observability/#chat-recovery-events). ## onChatRecovery diff --git a/src/content/docs/agents/think/scheduled-tasks.mdx b/src/content/docs/agents/harnesses/think/scheduled-tasks.mdx similarity index 82% rename from src/content/docs/agents/think/scheduled-tasks.mdx rename to src/content/docs/agents/harnesses/think/scheduled-tasks.mdx index 9f4ddd60f32..702d4322845 100644 --- a/src/content/docs/agents/think/scheduled-tasks.mdx +++ b/src/content/docs/agents/harnesses/think/scheduled-tasks.mdx @@ -59,10 +59,10 @@ export class DigestAgent extends Think { The DSL supports `every minutes`, `every hours`, `every day at HH:mm`, `every weekday at HH:mm`, and `every week on monday,wednesday at HH:mm`. Wall-clock schedules require either an inline timezone, a task `timezone`, or `getDefaultTimezone()`. If an alarm is late, Think runs the intended occurrence once and schedules the next future occurrence; it does not backfill missed runs. -Each task must define exactly one of `prompt` or `handler`. Prompt tasks create a durable submission with [`submitMessages()`](/agents/think/programmatic-submissions/). Handler tasks receive `{ taskId, scheduledFor, scheduledForDate, occurrenceKey, idempotencyKey, schedule, scheduleKind, timezone, metadata }` and are intended for app-owned work such as creating a Workflow run or writing a run ledger. Delivery is at-least-once; use `idempotencyKey` or `occurrenceKey` for your own durable idempotency. +Each task must define exactly one of `prompt` or `handler`. Prompt tasks create a durable submission with [`submitMessages()`](/agents/harnesses/think/programmatic-submissions/). Handler tasks receive `{ taskId, scheduledFor, scheduledForDate, occurrenceKey, idempotencyKey, schedule, scheduleKind, timezone, metadata }` and are intended for app-owned work such as creating a Workflow run or writing a run ledger. Delivery is at-least-once; use `idempotencyKey` or `occurrenceKey` for your own durable idempotency. Static declarations reconcile on startup. If `getScheduledTasks()` reads product-owned data that can change while the Durable Object is live, call `internal_reconcileScheduledTasks()` after updating that data. During reconciliation Think records the task row before creating the underlying Agent schedule, so a missing `schedule_id` is only a pending reconcile state and is repaired on the next reconcile. The task `retry` option retries the prompt or handler action before the failure is logged. The next occurrence is still scheduled after the action succeeds or exhausts its retries, so failed occurrences do not block future runs. ## When to use a workflow instead -For a recurring job whose steps matter — multiple deterministic steps, long waits, or human approval — use a handler task to create a [Think Workflow](/agents/think/workflows/) run. Keep simple recurring prompts as prompt tasks, and keep one-off background turns on [`submitMessages()`](/agents/think/programmatic-submissions/). +For a recurring job whose steps matter — multiple deterministic steps, long waits, or human approval — use a handler task to create a [Think Workflow](/agents/harnesses/think/workflows/) run. Keep simple recurring prompts as prompt tasks, and keep one-off background turns on [`submitMessages()`](/agents/harnesses/think/programmatic-submissions/). diff --git a/src/content/docs/agents/think/sub-agents.mdx b/src/content/docs/agents/harnesses/think/sub-agents.mdx similarity index 96% rename from src/content/docs/agents/think/sub-agents.mdx rename to src/content/docs/agents/harnesses/think/sub-agents.mdx index b3fa0c9b6b1..77f23ada0a5 100644 --- a/src/content/docs/agents/think/sub-agents.mdx +++ b/src/content/docs/agents/harnesses/think/sub-agents.mdx @@ -13,10 +13,10 @@ import { TypeScriptExample } from "~/components"; Think works as both a top-level agent and a sub-agent. When used as a sub-agent, the `chat()` method runs a full turn and streams events via a callback. :::note -This page covers calling Think from server code instead of a browser — multi-agent systems, scheduled or webhook-triggered turns, and recovery. If you are building a single chat agent that users talk to in the browser, you can skip it; `useAgentChat` (see [Getting started](/agents/think/getting-started/)) is all you need. +This page covers calling Think from server code instead of a browser — multi-agent systems, scheduled or webhook-triggered turns, and recovery. If you are building a single chat agent that users talk to in the browser, you can skip it; `useAgentChat` (see [Getting started](/agents/harnesses/think/getting-started/)) is all you need. ::: -For durable acceptance with idempotent retry and later status inspection, refer to [Programmatic submissions](/agents/think/programmatic-submissions/). For recovery after eviction, refer to [Durable recovery](/agents/think/recovery/). +For durable acceptance with idempotent retry and later status inspection, refer to [Programmatic submissions](/agents/harnesses/think/programmatic-submissions/). For recovery after eviction, refer to [Durable recovery](/agents/harnesses/think/recovery/). ## chat @@ -209,7 +209,7 @@ await this.saveMessages((current) => [ ### Scheduled responses -Trigger a recurring prompt turn with [`getScheduledTasks()`](/agents/think/scheduled-tasks/): +Trigger a recurring prompt turn with [`getScheduledTasks()`](/agents/harnesses/think/scheduled-tasks/): diff --git a/src/content/docs/agents/think/tools.mdx b/src/content/docs/agents/harnesses/think/tools.mdx similarity index 97% rename from src/content/docs/agents/think/tools.mdx rename to src/content/docs/agents/harnesses/think/tools.mdx index 42afabbb468..ea6a65e54f5 100644 --- a/src/content/docs/agents/think/tools.mdx +++ b/src/content/docs/agents/harnesses/think/tools.mdx @@ -20,11 +20,11 @@ On every turn, Think merges tools from multiple sources. Later sources override 2. **`getTools()`** — your custom server-side tools 3. **Extension tools** — tools from loaded extensions (prefixed by extension name) 4. **Session tools** — `set_context`, `load_context`, `search_context` (from `configureSession`) -5. **Skill tools** — `activate_skill`, `read_skill_resource`, `run_skill_script` (from `getSkills()`, refer to [Agent Skills](/agents/api-reference/agent-skills/)) +5. **Skill tools** — `activate_skill`, `read_skill_resource`, `run_skill_script` (from `getSkills()`, refer to [Agent Skills](/agents/runtime/execution/agent-skills/)) 6. **MCP tools** — from connected MCP servers -7. **Client tools** — from the browser (refer to [Client tools](/agents/think/client-tools/)) +7. **Client tools** — from the browser (refer to [Client tools](/agents/harnesses/think/client-tools/)) -Tools belong to the agent running the turn. For parent-child orchestration, use [Agent tools](/agents/api-reference/agent-tools/) instead of passing one-off tools through `chat()`. +Tools belong to the agent running the turn. For parent-child orchestration, use [Agent tools](/agents/runtime/execution/agent-tools/) instead of passing one-off tools through `chat()`. ## Built-in workspace tools @@ -340,7 +340,7 @@ createBrowserTools({ -For the full CDP helper API, refer to [Browse the web](/agents/api-reference/browse-the-web/). +For the full CDP helper API, refer to [Browse the web](/agents/tools/browser/). ## Extensions diff --git a/src/content/docs/agents/think/workflows.mdx b/src/content/docs/agents/harnesses/think/workflows.mdx similarity index 86% rename from src/content/docs/agents/think/workflows.mdx rename to src/content/docs/agents/harnesses/think/workflows.mdx index 08ef323b182..3a82c91f4ec 100644 --- a/src/content/docs/agents/think/workflows.mdx +++ b/src/content/docs/agents/harnesses/think/workflows.mdx @@ -19,7 +19,7 @@ Use it when the Workflow owns the process: - retryable deterministic side effects - a Think turn that should produce typed structured output -Keep recurring prompts as [scheduled tasks](/agents/think/scheduled-tasks/), and keep simple one-off background turns on [`submitMessages()`](/agents/think/programmatic-submissions/). Workflows are for jobs where the steps matter. +Keep recurring prompts as [scheduled tasks](/agents/harnesses/think/scheduled-tasks/), and keep simple one-off background turns on [`submitMessages()`](/agents/harnesses/think/programmatic-submissions/). Workflows are for jobs where the steps matter. ## API @@ -141,7 +141,7 @@ Set `cancelOnTimeout: false` when you intentionally want the Think submission to ## Boundary with other primitives -Use [`getScheduledTasks()`](/agents/think/scheduled-tasks/) for recurring prompt submissions or deterministic scheduled handlers: +Use [`getScheduledTasks()`](/agents/harnesses/think/scheduled-tasks/) for recurring prompt submissions or deterministic scheduled handlers: ```ts getScheduledTasks() { @@ -166,8 +166,8 @@ getScheduledTasks() { } ``` -Use [`submitMessages()`](/agents/think/programmatic-submissions/) for durable one-off turns where the caller can inspect submission status later. +Use [`submitMessages()`](/agents/harnesses/think/programmatic-submissions/) for durable one-off turns where the caller can inspect submission status later. -Use [`startFiber()`](/agents/api-reference/durable-execution/#startfiber) for app-owned idempotent Agent jobs that need recovery inside the Agent. Think's workflow notification delivery does not use fibers; it uses a private outbox because it needs to store an event until delivery succeeds. +Use [`startFiber()`](/agents/runtime/execution/durable-execution/#startfiber) for app-owned idempotent Agent jobs that need recovery inside the Agent. Think's workflow notification delivery does not use fibers; it uses a private outbox because it needs to store an event until delivery succeeds. Use Workflows when the process has multiple deterministic steps, long waits, or human approval. diff --git a/src/content/docs/agents/index.mdx b/src/content/docs/agents/index.mdx index 2fb1303800f..114557dda0d 100644 --- a/src/content/docs/agents/index.mdx +++ b/src/content/docs/agents/index.mdx @@ -9,32 +9,27 @@ sidebar: head: - tag: title content: Agents -products: - - agents --- import { - CardGrid, - Description, - Feature, - LinkButton, - LinkTitleCard, - PackageManagers, - Plan, + AgentsPlatformDiagram, RelatedProduct, - Render, - TabItem, - Tabs, - TypeScriptExample, - WranglerConfig, - LinkCard, } from "~/components"; -Most AI applications today are stateless — they process a request, return a response, and forget everything. Real agents need more. They need to remember conversations, act on schedules, call tools, coordinate with other agents, and stay connected to users in real-time. The Agents SDK gives you all of this as a TypeScript class. +Build and host Agents on Cloudflare, connect chat, voice, email, Slack, and webhooks to a durable agent runtime with Browser, Sandbox, AI Search, MCP, Payments, and other MCP tools. -Each agent runs on a [Durable Object](/durable-objects/) — a stateful micro-server with its own SQL database, WebSocket connections, and scheduling. Deploy once and Cloudflare runs your agents across its global network, scaling to tens of millions of instances. No infrastructure to manage, no sessions to reconstruct, no state to externalize. +When you host agents on Cloudflare, each agent session has a durable identity, local SQL storage, real-time connections, scheduled work, and recoverable execution. -The mental model is simple: define a TypeScript class, give each real-world thing a stable name, and route requests or WebSocket connections to that named instance. The instance wakes when something happens, reads its durable state, does work, and hibernates when idle. +Deploy once and Cloudflare runs your agents across its global network, scaling to tens of millions of instances. No infrastructure to manage, no sessions to reconstruct, no state to externalize. + + + +Agents on Cloudflare are composed from four parts: + +- **Communication channels** define how users and systems reach your agent, such as [chat](/agents/communication-channels/chat/), [voice](/agents/communication-channels/voice/), [email](/agents/communication-channels/email/), [Slack](/agents/communication-channels/slack/), [webhooks](/agents/communication-channels/webhooks/), and other event sources. +- **The agent harness** defines the loop: how the agent calls models, selects tools, handles tool results, streams responses, and decides whether to continue. Use [Project Think](/agents/harnesses/think/) for an opinionated harness, or build your own loop directly on the [Agents SDK runtime](/agents/runtime/agents-api/). +- **The Agents SDK runtime** provides durable infrastructure: the [`Agent` class](/agents/runtime/lifecycle/agent-class/), [state](/agents/runtime/lifecycle/state/), [sessions](/agents/runtime/lifecycle/sessions/), [routing](/agents/runtime/communication/routing/), [WebSockets](/agents/runtime/communication/websockets/), [scheduling](/agents/runtime/execution/schedule-tasks/), [fibers](/agents/runtime/execution/durable-execution/), and [observability](/agents/runtime/operations/observability/). +- **Tools** give the agent capabilities: [browser automation](/agents/tools/browser/), [sandboxed code execution](/agents/tools/sandbox/), [AI Search](/agents/tools/ai-search/), [MCP tools](/agents/tools/mcp/), and [payments](/agents/tools/payments/). ### Get started @@ -46,123 +41,36 @@ cd agents-starter && npm install npm run dev ``` -The starter includes streaming AI chat, server-side and client-side tools, human-in-the-loop approval, and task scheduling — a foundation you can build on or tear apart. You can also swap in [OpenAI, Anthropic, Google Gemini, or any other provider](/agents/api-reference/using-ai-models/). - - - - - -### What agents can do - -- **Remember everything** — Every agent has a built-in [SQL database](/agents/api-reference/store-and-sync-state/) and key-value state that syncs to connected clients in real-time. State survives restarts, deploys, and hibernation. -- **Build AI chat** — [`AIChatAgent`](/agents/api-reference/chat-agents/) gives you streaming AI chat with automatic message persistence, resumable streams, and tool support. Pair it with the [`useAgentChat`](/agents/api-reference/chat-agents/) React hook to build chat UIs in minutes. -- **Think with any model** — Call [any AI model](/agents/api-reference/using-ai-models/) — Workers AI, OpenAI, Anthropic, Gemini — and stream responses over [WebSockets](/agents/api-reference/websockets/) or [Server-Sent Events](/agents/api-reference/http-sse/). Long-running reasoning models that take minutes to respond work out of the box. -- **Use and serve tools** — Define server-side tools, client-side tools that run in the browser, and [human-in-the-loop](/agents/concepts/human-in-the-loop/) approval flows. Expose your agent's tools to other agents and LLMs via [MCP](/agents/api-reference/mcp-agent-api/). -- **Act on their own** — [Schedule tasks](/agents/api-reference/schedule-tasks/) on a delay, at a specific time, or on a cron. Agents can wake themselves up, do work, and go back to sleep — without a user present. -- **Browse the web** — Give your agents [browser tools](/agents/api-reference/browse-the-web/) powered by the Chrome DevTools Protocol to scrape, screenshot, debug, and interact with web pages. -- **Talk to users** — Build real-time [voice agents](/agents/api-reference/voice/) with speech-to-text, text-to-speech, and conversation persistence, or connect messenger platforms with [Chat SDK](/agents/api-reference/chat-sdk/) and store conversation state in Agents sub-agents. -- **Orchestrate work** — Run multi-step [workflows](/agents/api-reference/run-workflows/) with automatic retries, coordinate across [sub-agents](/agents/api-reference/sub-agents/), or run chat-capable [agent tools](/agents/api-reference/agent-tools/) with retained streaming timelines. -- **React to events** — Handle [inbound email](/agents/api-reference/email/) (see the [email agent example](https://github.com/cloudflare/agents/tree/main/examples/email-agent)), HTTP requests, WebSocket messages, and state changes — all from the same class. - -### How it works - -An agent is a TypeScript class. Methods marked with `@callable()` become typed RPC that clients can call directly over WebSocket. - - - -```ts -import { Agent, callable } from "agents"; - -export class CounterAgent extends Agent { - initialState = { count: 0 }; - - @callable() - increment() { - this.setState({ count: this.state.count + 1 }); - return this.state.count; - } -} -``` - - - -```tsx -import { useAgent } from "agents/react"; - -function Counter() { - const [count, setCount] = useState(0); - const agent = useAgent({ - agent: "CounterAgent", - onStateUpdate: (state) => setCount(state.count), - }); - - return ; -} -``` - -For AI chat, extend `AIChatAgent` instead. Messages are persisted automatically, streams resume on disconnect, and the React hook handles the UI. - - - -```ts -import { AIChatAgent } from "@cloudflare/ai-chat"; -import { createWorkersAI } from "workers-ai-provider"; -import { streamText, convertToModelMessages } from "ai"; - -export class ChatAgent extends AIChatAgent { - async onChatMessage() { - const workersai = createWorkersAI({ binding: this.env.AI }); - const result = streamText({ - model: workersai("@cf/zai-org/glm-4.7-flash"), - messages: await convertToModelMessages(this.messages), - }); - return result.toUIMessageStreamResponse(); - } -} -``` - - - -Refer to the [quick start](/agents/getting-started/quick-start/) for a full walkthrough, the [chat agents guide](/agents/api-reference/chat-agents/) for the full chat API, or the [Agents API reference](/agents/api-reference/agents-api/) for the complete SDK. - ---- +The starter includes streaming AI chat, server-side and client-side tools, human-in-the-loop approval, and task scheduling — a foundation you can build on or tear apart. You can also swap in [OpenAI, Anthropic, Google Gemini, or any other provider](/agents/runtime/operations/using-ai-models/). -### Build on the Cloudflare Platform +### Example agents - + -Run machine learning models, powered by serverless GPUs, on Cloudflare's global network. No API keys required. +Build a streaming AI chat agent with tools and human-in-the-loop approvals. - + -Build serverless applications and deploy instantly across the globe for exceptional performance, reliability, and scale. +Build an agent that responds to Slack messages, mentions, and commands. - + -Observe and control your AI applications with caching, rate limiting, request retries, model fallback, and more. +Build a real-time voice agent with speech-to-text and text-to-speech. - + -Build full-stack AI applications with Vectorize, Cloudflare's vector database for semantic search, recommendations, and providing context to LLMs. +Build an agent that can inspect pages, capture screenshots, and use browser tools. - + -Build stateful agents that guarantee executions, including automatic retries, persistent state that runs for minutes, hours, days, or weeks. +Build an agent that sends, receives, routes, and replies to email. diff --git a/src/content/docs/agents/api-reference/mcp-agent-api.mdx b/src/content/docs/agents/model-context-protocol/apis/agent-api.mdx similarity index 90% rename from src/content/docs/agents/api-reference/mcp-agent-api.mdx rename to src/content/docs/agents/model-context-protocol/apis/agent-api.mdx index 222a083286b..777a9d24905 100644 --- a/src/content/docs/agents/api-reference/mcp-agent-api.mdx +++ b/src/content/docs/agents/model-context-protocol/apis/agent-api.mdx @@ -38,9 +38,9 @@ export class MyMCP extends McpAgent { -This means that each instance of your MCP server has its own durable state, backed by a [Durable Object](/durable-objects/), with its own [SQL database](/agents/api-reference/store-and-sync-state). +This means that each instance of your MCP server has its own durable state, backed by a [Durable Object](/durable-objects/), with its own [SQL database](/agents/runtime/lifecycle/state/). -Your MCP server doesn't necessarily have to be an Agent. You can build MCP servers that are stateless, and just add [tools](/agents/model-context-protocol/tools) to your MCP server using the `@modelcontextprotocol/sdk` package. +Your MCP server doesn't necessarily have to be an Agent. You can build MCP servers that are stateless, and just add [tools](/agents/model-context-protocol/protocol/tools/) to your MCP server using the `@modelcontextprotocol/sdk` package. But if you want your MCP server to: @@ -175,11 +175,11 @@ const eventStore = new DurableObjectEventStore(this.ctx.storage); -Refer to [MCP Transport](/agents/model-context-protocol/transport/) for transport configuration. +Refer to [MCP Transport](/agents/model-context-protocol/protocol/transport/) for transport configuration. ## Authentication and authorization -The McpAgent class provides seamless integration with the [OAuth Provider Library](https://github.com/cloudflare/workers-oauth-provider) for [authentication and authorization](/agents/model-context-protocol/authorization/). +The McpAgent class provides seamless integration with the [OAuth Provider Library](https://github.com/cloudflare/workers-oauth-provider) for [authentication and authorization](/agents/model-context-protocol/protocol/authorization/). When a user authenticates to your MCP server, their identity information and tokens are made available through the `props` parameter, allowing you to: @@ -190,16 +190,16 @@ When a user authenticates to your MCP server, their identity information and tok ## State synchronization APIs -The `McpAgent` class provides full access to the [Agent state APIs](/agents/api-reference/store-and-sync-state/): +The `McpAgent` class provides full access to the [Agent state APIs](/agents/runtime/lifecycle/state/): -- [`state`](/agents/api-reference/store-and-sync-state/) — Current persisted state -- [`initialState`](/agents/api-reference/store-and-sync-state/#set-the-initial-state-for-an-agent) — Default state when instance starts -- [`setState`](/agents/api-reference/store-and-sync-state/) — Update and persist state -- [`onStateChanged`](/agents/api-reference/store-and-sync-state/#synchronizing-state) — React to state changes -- [`sql`](/agents/api-reference/agents-api/#sql-api) — Execute SQL queries on embedded database +- [`state`](/agents/runtime/lifecycle/state/) — Current persisted state +- [`initialState`](/agents/runtime/lifecycle/state/#set-the-initial-state-for-an-agent) — Default state when instance starts +- [`setState`](/agents/runtime/lifecycle/state/) — Update and persist state +- [`onStateChanged`](/agents/runtime/lifecycle/state/#synchronizing-state) — React to state changes +- [`sql`](/agents/runtime/agents-api/#sql-api) — Execute SQL queries on embedded database :::note[State resets after the session ends] -Currently, each client session is backed by an instance of the `McpAgent` class. This is handled automatically for you, as shown in the [getting started guide](/agents/guides/remote-mcp-server). This means that when the same client reconnects, they will start a new session, and the state will be reset. +Currently, each client session is backed by an instance of the `McpAgent` class. This is handled automatically for you, as shown in the [getting started guide](/agents/model-context-protocol/guides/remote-mcp-server/). This means that when the same client reconnects, they will start a new session, and the state will be reset. ::: For example, the following code implements an MCP server that remembers a counter value, and updates the counter when the `add` tool is called: @@ -421,36 +421,36 @@ switch (result.action) { Elicitation requires MCP client support. Not all MCP clients implement the elicitation capability. Check the client documentation for compatibility. ::: -For more human-in-the-loop patterns including workflow-based approval, refer to [Human-in-the-loop patterns](/agents/guides/human-in-the-loop/). +For more human-in-the-loop patterns including workflow-based approval, refer to [Human-in-the-loop patterns](/agents/concepts/agentic-patterns/human-in-the-loop/). ## Next steps diff --git a/src/content/docs/agents/api-reference/mcp-client-api.mdx b/src/content/docs/agents/model-context-protocol/apis/client-api.mdx similarity index 96% rename from src/content/docs/agents/api-reference/mcp-client-api.mdx rename to src/content/docs/agents/model-context-protocol/apis/client-api.mdx index ab3101d7de7..9e788905866 100644 --- a/src/content/docs/agents/api-reference/mcp-client-api.mdx +++ b/src/content/docs/agents/model-context-protocol/apis/client-api.mdx @@ -25,7 +25,7 @@ The MCP client capability lets your agent: :::note -This page covers connecting to MCP servers as a client. To create your own MCP server, refer to [Creating MCP servers](/agents/api-reference/mcp-agent-api/). +This page covers connecting to MCP servers as a client. To create your own MCP server, refer to [Creating MCP servers](/agents/model-context-protocol/apis/agent-api/). ::: @@ -60,7 +60,7 @@ export class MyAgent extends Agent { -Connections persist in the agent's [SQL storage](/agents/api-reference/store-and-sync-state/), and when an agent connects to an MCP server, all tools from that server become available automatically. +Connections persist in the agent's [SQL storage](/agents/runtime/lifecycle/state/), and when an agent connects to an MCP server, all tools from that server become available automatically. ## Adding MCP servers @@ -156,7 +156,7 @@ MCP server URLs are validated before connection to prevent Server-Side Request F Loopback addresses (`localhost`, `127.x.x.x`, `[::1]`) are **allowed** for local development. -For production connections to internal services, use the [RPC transport](/agents/model-context-protocol/transport/) with a Durable Object binding instead of HTTP. +For production connections to internal services, use the [RPC transport](/agents/model-context-protocol/protocol/transport/) with a Durable Object binding instead of HTTP. ### Return value @@ -541,7 +541,7 @@ async addMcpServer( - `transport` — Transport layer configuration: - `headers` — Custom HTTP headers for authentication - `type` — Transport type: `"auto"` (default), `"streamable-http"`, or `"sse"` - - `retry` — Retry options for connection and reconnection attempts. Persisted and used when restoring connections after hibernation or after OAuth completion. Default: 3 attempts, 500ms base delay, 5s max delay. Refer to [Retries](/agents/api-reference/retries/) for details on `RetryOptions`. + - `retry` — Retry options for connection and reconnection attempts. Persisted and used when restoring connections after hibernation or after OAuth completion. Default: 3 attempts, 500ms base delay, 5s max delay. Refer to [Retries](/agents/runtime/execution/retries/) for details on `RetryOptions`. #### Parameters (RPC transport) @@ -553,7 +553,7 @@ async addMcpServer( - `client` — MCP client configuration options - `retry` — Retry options for the connection -RPC transport connects your Agent directly to an `McpAgent` via Durable Object bindings without HTTP overhead. Refer to [MCP Transport](/agents/model-context-protocol/transport/) for details on configuring RPC transport. +RPC transport connects your Agent directly to an `McpAgent` via Durable Object bindings without HTTP overhead. Refer to [MCP Transport](/agents/model-context-protocol/protocol/transport/) for details on configuring RPC transport. #### Returns @@ -810,7 +810,7 @@ const disposable = this.mcp.onServerStateChanged(() => { :::note -MCP server list broadcasts (`cf_agent_mcp_servers`) are automatically filtered to exclude connections where [`shouldSendProtocolMessages`](/agents/api-reference/protocol-messages/) returned `false`. +MCP server list broadcasts (`cf_agent_mcp_servers`) are automatically filtered to exclude connections where [`shouldSendProtocolMessages`](/agents/runtime/communication/protocol-messages/) returned `false`. ::: ### Lifecycle methods @@ -875,7 +875,7 @@ await this.mcp.waitForConnections({ timeout: 10_000 }); ``` :::note -`AIChatAgent` calls this automatically via its [`waitForMcpConnections`](/agents/api-reference/chat-agents/#waitformcpconnections) property (defaults to `{ timeout: 10_000 }`). You only need `waitForConnections()` directly when using `Agent` with MCP, or when you want finer control inside `onChatMessage`. +`AIChatAgent` calls this automatically via its [`waitForMcpConnections`](/agents/communication-channels/chat/chat-agents/#waitformcpconnections) property (defaults to `{ timeout: 10_000 }`). You only need `waitForConnections()` directly when using `Agent` with MCP, or when you want finer control inside `onChatMessage`. ::: #### `this.mcp.closeConnection()` @@ -969,18 +969,18 @@ export class MyAgent extends Agent { diff --git a/src/content/docs/agents/api-reference/mcp-handler-api.mdx b/src/content/docs/agents/model-context-protocol/apis/handler-api.mdx similarity index 93% rename from src/content/docs/agents/api-reference/mcp-handler-api.mdx rename to src/content/docs/agents/model-context-protocol/apis/handler-api.mdx index d12b9ca0a14..18db6e245d8 100644 --- a/src/content/docs/agents/api-reference/mcp-handler-api.mdx +++ b/src/content/docs/agents/model-context-protocol/apis/handler-api.mdx @@ -12,7 +12,7 @@ products: import { TypeScriptExample, LinkCard } from "~/components"; -The `createMcpHandler` function creates a fetch handler to serve your [MCP server](/agents/model-context-protocol/). Use it when you want a stateless MCP server that runs in a plain Worker (no Durable Object). For stateful MCP servers that persist state across requests, use the [`McpAgent`](/agents/api-reference/mcp-agent-api) class instead. +The `createMcpHandler` function creates a fetch handler to serve your [MCP server](/agents/model-context-protocol/). Use it when you want a stateless MCP server that runs in a plain Worker (no Durable Object). For stateful MCP servers that persist state across requests, use the [`McpAgent`](/agents/model-context-protocol/apis/agent-api/) class instead. It uses an implementation of the MCP Transport interface, `WorkerTransport`, built on top of web standards, which conforms to the [streamable-http](https://modelcontextprotocol.io/specification/draft/basic/transports/#streamable-http) transport specification. @@ -89,9 +89,9 @@ const handler = createMcpHandler(server, { #### authContext -An authentication context object that will be available to MCP tools via [`getMcpAuthContext()`](/agents/api-reference/mcp-handler-api#authentication-context). +An authentication context object that will be available to MCP tools via [`getMcpAuthContext()`](/agents/model-context-protocol/apis/handler-api/#authentication-context). -When using the [`OAuthProvider`](/agents/model-context-protocol/authorization/) from `@cloudflare/workers-oauth-provider`, the authentication context is automatically populated with information from the OAuth flow. You typically don't need to set this manually. +When using the [`OAuthProvider`](/agents/model-context-protocol/protocol/authorization/) from `@cloudflare/workers-oauth-provider`, the authentication context is automatically populated with information from the OAuth flow. You typically don't need to set this manually. #### transport @@ -127,7 +127,7 @@ MCP SDK 1.26.0 introduces a guard that prevents connecting to a server instance **If your stateless MCP server declares `McpServer` or transport instances in the global scope, you must create new instances per request.** -See the [migration guide](/agents/api-reference/mcp-handler-api/#migration-guide-for-mcp-sdk-1260) below for details. +See the [migration guide](/agents/model-context-protocol/apis/handler-api/#migration-guide-for-mcp-sdk-1260) below for details. ::: @@ -546,7 +546,7 @@ const transport = new WorkerTransport({ ## Authentication Context -When using [OAuth authentication](/agents/model-context-protocol/authorization/) with `createMcpHandler`, user information is made available to your MCP tools through `getMcpAuthContext()`. Under the hood this uses `AsyncLocalStorage` to pass the request to the tool handler, keeping the authentication context available. +When using [OAuth authentication](/agents/model-context-protocol/protocol/authorization/) with `createMcpHandler`, user information is made available to your MCP tools through `getMcpAuthContext()`. Under the hood this uses `AsyncLocalStorage` to pass the request to the tool handler, keeping the authentication context available. ```ts interface McpAuthContext { @@ -595,7 +595,7 @@ function createServer() { :::note -For a complete guide on setting up OAuth authentication with MCP servers, see the [MCP Authorization documentation](/agents/model-context-protocol/authorization/). View the [complete authenticated MCP server in a Worker example on GitHub](https://github.com/cloudflare/agents/tree/main/examples/mcp-worker-authenticated). +For a complete guide on setting up OAuth authentication with MCP servers, see the [MCP Authorization documentation](/agents/model-context-protocol/protocol/authorization/). View the [complete authenticated MCP server in a Worker example on GitHub](https://github.com/cloudflare/agents/tree/main/examples/mcp-worker-authenticated). ::: ## Error Handling @@ -631,24 +631,24 @@ server.tool("riskyOperation", "An operation that might fail", {}, async () => { diff --git a/src/content/docs/agents/model-context-protocol/apis/index.mdx b/src/content/docs/agents/model-context-protocol/apis/index.mdx new file mode 100644 index 00000000000..5e9a4fa782e --- /dev/null +++ b/src/content/docs/agents/model-context-protocol/apis/index.mdx @@ -0,0 +1,12 @@ +--- +title: APIs +pcx_content_type: navigation +sidebar: + order: 1 + group: + hideIndex: true +--- + +import { DirectoryListing } from "~/components"; + + diff --git a/src/content/docs/agents/model-context-protocol/cloudflare/index.mdx b/src/content/docs/agents/model-context-protocol/cloudflare/index.mdx new file mode 100644 index 00000000000..0d398f640fa --- /dev/null +++ b/src/content/docs/agents/model-context-protocol/cloudflare/index.mdx @@ -0,0 +1,12 @@ +--- +title: Cloudflare +pcx_content_type: navigation +sidebar: + order: 4 + group: + hideIndex: true +--- + +import { DirectoryListing } from "~/components"; + + diff --git a/src/content/docs/agents/model-context-protocol/mcp-portal.mdx b/src/content/docs/agents/model-context-protocol/cloudflare/mcp-portal.mdx similarity index 100% rename from src/content/docs/agents/model-context-protocol/mcp-portal.mdx rename to src/content/docs/agents/model-context-protocol/cloudflare/mcp-portal.mdx diff --git a/src/content/docs/agents/community-mcp-server.mdx b/src/content/docs/agents/model-context-protocol/cloudflare/servers-for-cloudflare/community-mcp-server.mdx similarity index 100% rename from src/content/docs/agents/community-mcp-server.mdx rename to src/content/docs/agents/model-context-protocol/cloudflare/servers-for-cloudflare/community-mcp-server.mdx diff --git a/src/content/docs/agents/model-context-protocol/mcp-servers-for-cloudflare.mdx b/src/content/docs/agents/model-context-protocol/cloudflare/servers-for-cloudflare/index.mdx similarity index 96% rename from src/content/docs/agents/model-context-protocol/mcp-servers-for-cloudflare.mdx rename to src/content/docs/agents/model-context-protocol/cloudflare/servers-for-cloudflare/index.mdx index 57b604ef4f6..ecfa815c1cd 100644 --- a/src/content/docs/agents/model-context-protocol/mcp-servers-for-cloudflare.mdx +++ b/src/content/docs/agents/model-context-protocol/cloudflare/servers-for-cloudflare/index.mdx @@ -18,7 +18,7 @@ These MCP servers allow your MCP client to read configurations from your account The [Cloudflare API MCP server](https://github.com/cloudflare/mcp) provides access to the entire [Cloudflare API](/api/) — over 2,500 endpoints across DNS, Workers, R2, Zero Trust, and every other product — through just two tools: `search()` and `execute()`. -It uses [Codemode](/agents/api-reference/codemode/), a technique where the model writes JavaScript against a typed representation of the OpenAPI spec and the Cloudflare API client, rather than loading individual tool definitions for each endpoint. The generated code runs inside an isolated [Dynamic Worker](/workers/runtime-apis/bindings/worker-loader/) sandbox. +It uses [Codemode](/agents/model-context-protocol/protocol/codemode/), a technique where the model writes JavaScript against a typed representation of the OpenAPI spec and the Cloudflare API client, rather than loading individual tool definitions for each endpoint. The generated code runs inside an isolated [Dynamic Worker](/workers/runtime-apis/bindings/worker-loader/) sandbox. This approach uses approximately 1,000 tokens regardless of how many API endpoints exist. An equivalent MCP server that exposed every endpoint as a native tool would consume over 1 million tokens — more than the entire context window of most foundation models. diff --git a/src/content/docs/agents/guides/build-mcp-client.mdx b/src/content/docs/agents/model-context-protocol/guides/build-mcp-client.mdx similarity index 82% rename from src/content/docs/agents/guides/build-mcp-client.mdx rename to src/content/docs/agents/model-context-protocol/guides/build-mcp-client.mdx index ad9250dbf80..dc7fd9f64df 100644 --- a/src/content/docs/agents/guides/build-mcp-client.mdx +++ b/src/content/docs/agents/model-context-protocol/guides/build-mcp-client.mdx @@ -1,9 +1,9 @@ --- pcx_content_type: navigation -title: Build a Remote MCP Client +title: Build MCP client external_link: https://github.com/cloudflare/ai/tree/main/demos/mcp-client sidebar: - order: 11 + order: 1 head: [] description: Build an AI Agent that acts as a remote MCP client. products: diff --git a/src/content/docs/agents/guides/connect-mcp-client.mdx b/src/content/docs/agents/model-context-protocol/guides/connect-mcp-client.mdx similarity index 96% rename from src/content/docs/agents/guides/connect-mcp-client.mdx rename to src/content/docs/agents/model-context-protocol/guides/connect-mcp-client.mdx index 9ba5b2e50b0..d01eff88b8b 100644 --- a/src/content/docs/agents/guides/connect-mcp-client.mdx +++ b/src/content/docs/agents/model-context-protocol/guides/connect-mcp-client.mdx @@ -230,18 +230,18 @@ You created an Agent that can: - List all available tools from connected servers - Monitor connection status -Connections persist in the Agent's [SQL storage](/agents/api-reference/store-and-sync-state/), so they remain active across requests. +Connections persist in the Agent's [SQL storage](/agents/runtime/lifecycle/state/), so they remain active across requests. ## Next steps diff --git a/src/content/docs/agents/guides/index.mdx b/src/content/docs/agents/model-context-protocol/guides/index.mdx similarity index 96% rename from src/content/docs/agents/guides/index.mdx rename to src/content/docs/agents/model-context-protocol/guides/index.mdx index e3143b6fd1c..9152074bf97 100644 --- a/src/content/docs/agents/guides/index.mdx +++ b/src/content/docs/agents/model-context-protocol/guides/index.mdx @@ -3,7 +3,7 @@ title: Guides description: Step-by-step guides for building and extending Cloudflare Agents with real-world patterns. pcx_content_type: navigation sidebar: - order: 4 + order: 3 group: hideIndex: true products: diff --git a/src/content/docs/agents/guides/oauth-mcp-client.mdx b/src/content/docs/agents/model-context-protocol/guides/oauth-mcp-client.mdx similarity index 98% rename from src/content/docs/agents/guides/oauth-mcp-client.mdx rename to src/content/docs/agents/model-context-protocol/guides/oauth-mcp-client.mdx index 20a2c757a13..e8511720f67 100644 --- a/src/content/docs/agents/guides/oauth-mcp-client.mdx +++ b/src/content/docs/agents/model-context-protocol/guides/oauth-mcp-client.mdx @@ -382,12 +382,12 @@ export default { diff --git a/src/content/docs/agents/guides/remote-mcp-server.mdx b/src/content/docs/agents/model-context-protocol/guides/remote-mcp-server.mdx similarity index 88% rename from src/content/docs/agents/guides/remote-mcp-server.mdx rename to src/content/docs/agents/model-context-protocol/guides/remote-mcp-server.mdx index 3c94319162b..1e78e89fc21 100644 --- a/src/content/docs/agents/guides/remote-mcp-server.mdx +++ b/src/content/docs/agents/model-context-protocol/guides/remote-mcp-server.mdx @@ -12,10 +12,10 @@ products: import { Details, Render, PackageManagers, LinkCard } from "~/components"; -This guide will show you how to deploy your own remote MCP server on Cloudflare using [Streamable HTTP transport](/agents/model-context-protocol/transport/), the current MCP specification standard. You have two options: +This guide will show you how to deploy your own remote MCP server on Cloudflare using [Streamable HTTP transport](/agents/model-context-protocol/protocol/transport/), the current MCP specification standard. You have two options: - **Without authentication** — anyone can connect and use the server (no login required). -- **With [authentication and authorization](/agents/guides/remote-mcp-server/#add-authentication)** — users sign in before accessing tools, and you can control which tools an agent can call based on the user's permissions. +- **With [authentication and authorization](/agents/model-context-protocol/guides/remote-mcp-server/#add-authentication)** — users sign in before accessing tools, and you can control which tools an agent can call based on the user's permissions. ## Choosing an approach @@ -23,8 +23,8 @@ The Agents SDK provides multiple ways to create MCP servers. Choose the approach | Approach | Stateful? | Requires Durable Objects? | Best for | | -------------------------------------------------------------- | --------- | ------------------------- | ---------------------------------------------- | -| [`createMcpHandler()`](/agents/api-reference/mcp-handler-api/) | No | No | Stateless tools, simplest setup | -| [`McpAgent`](/agents/api-reference/mcp-agent-api/) | Yes | Yes | Stateful tools, per-session state, elicitation | +| [`createMcpHandler()`](/agents/model-context-protocol/apis/handler-api/) | No | No | Stateless tools, simplest setup | +| [`McpAgent`](/agents/model-context-protocol/apis/agent-api/) | Yes | Yes | Stateful tools, per-session state, elicitation | | Raw `WebStandardStreamableHTTPServerTransport` | No | No | Full control, no SDK dependency | - **`createMcpHandler()`** is the fastest way to get a stateless MCP server running. Use it when your tools do not need per-session state. @@ -33,7 +33,7 @@ The Agents SDK provides multiple ways to create MCP servers. Choose the approach ## Deploy your first MCP server -You can start by deploying a [public MCP server](https://github.com/cloudflare/ai/tree/main/demos/remote-mcp-authless) without authentication, then add user authentication and scoped authorization later. If you already know your server will require authentication, you can skip ahead to the [next section](/agents/guides/remote-mcp-server/#add-authentication). +You can start by deploying a [public MCP server](https://github.com/cloudflare/ai/tree/main/demos/remote-mcp-authless) without authentication, then add user authentication and scoped authorization later. If you already know your server will require authentication, you can skip ahead to the [next section](/agents/model-context-protocol/guides/remote-mcp-server/#add-authentication). ### Via the dashboard @@ -41,9 +41,9 @@ The button below will guide you through everything you need to do to deploy an [ [![Deploy to Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/cloudflare/ai/tree/main/demos/remote-mcp-authless) -Once deployed, this server will be live at your `workers.dev` subdomain (for example, `remote-mcp-server-authless.your-account.workers.dev/mcp`). You can connect to it immediately using the [AI Playground](https://playground.ai.cloudflare.com/) (a remote MCP client), [MCP inspector](https://github.com/modelcontextprotocol/inspector) or [other MCP clients](/agents/guides/remote-mcp-server/#connect-from-an-mcp-client-via-a-local-proxy). +Once deployed, this server will be live at your `workers.dev` subdomain (for example, `remote-mcp-server-authless.your-account.workers.dev/mcp`). You can connect to it immediately using the [AI Playground](https://playground.ai.cloudflare.com/) (a remote MCP client), [MCP inspector](https://github.com/modelcontextprotocol/inspector) or [other MCP clients](/agents/model-context-protocol/guides/remote-mcp-server/#connect-from-an-mcp-client-via-a-local-proxy). -A new git repository will be set up on your GitHub or GitLab account for your MCP server, configured to automatically deploy to Cloudflare each time you push a change or merge a pull request to the main branch of the repository. You can clone this repository, [develop locally](/agents/guides/remote-mcp-server/#via-the-cli), and start customizing the MCP server with your own [tools](/agents/model-context-protocol/tools/). +A new git repository will be set up on your GitHub or GitLab account for your MCP server, configured to automatically deploy to Cloudflare each time you push a change or merge a pull request to the main branch of the repository. You can clone this repository, [develop locally](/agents/model-context-protocol/guides/remote-mcp-server/#via-the-cli), and start customizing the MCP server with your own [tools](/agents/model-context-protocol/protocol/tools/). ### Via the CLI @@ -150,7 +150,7 @@ For example, to connect from Claude Desktop: Claude should invoke the tool and show the result generated by the remote MCP server. -To learn how to use remote MCP servers with other MCP clients, refer to [Test a Remote MCP Server](/agents/guides/test-remote-mcp-server). +To learn how to use remote MCP servers with other MCP clients, refer to [Test a Remote MCP Server](/agents/model-context-protocol/guides/test-remote-mcp-server/). ## Add Authentication @@ -164,7 +164,7 @@ For a step-by-step deployment guide, refer to [Secure MCP servers with Access fo ### Third-party OAuth -You can connect your MCP server with any [OAuth provider](/agents/model-context-protocol/authorization/#2-third-party-oauth-provider) that supports the OAuth 2.0 specification, including GitHub, Google, Slack, [Stytch](/agents/model-context-protocol/authorization/#stytch), [Auth0](/agents/model-context-protocol/authorization/#auth0), [WorkOS](/agents/model-context-protocol/authorization/#workos), and more. +You can connect your MCP server with any [OAuth provider](/agents/model-context-protocol/protocol/authorization/#2-third-party-oauth-provider) that supports the OAuth 2.0 specification, including GitHub, Google, Slack, [Stytch](/agents/model-context-protocol/protocol/authorization/#stytch), [Auth0](/agents/model-context-protocol/protocol/authorization/#auth0), [WorkOS](/agents/model-context-protocol/protocol/authorization/#workos), and more. The following example demonstrates how to use GitHub as an OAuth provider. @@ -308,18 +308,18 @@ Use any random string for `COOKIE_ENCRYPTION_KEY`, for example the output of `op npm run deploy ``` -5. Connect to your server running at `worker-name.account-name.workers.dev/mcp` using the [AI Playground](https://playground.ai.cloudflare.com/), MCP Inspector, or [other MCP clients](/agents/guides/test-remote-mcp-server/), and authenticate with GitHub. +5. Connect to your server running at `worker-name.account-name.workers.dev/mcp` using the [AI Playground](https://playground.ai.cloudflare.com/), MCP Inspector, or [other MCP clients](/agents/model-context-protocol/guides/test-remote-mcp-server/), and authenticate with GitHub. ## Next steps diff --git a/src/content/docs/agents/guides/securing-mcp-server.mdx b/src/content/docs/agents/model-context-protocol/guides/securing-mcp-server.mdx similarity index 98% rename from src/content/docs/agents/guides/securing-mcp-server.mdx rename to src/content/docs/agents/model-context-protocol/guides/securing-mcp-server.mdx index ff6a93c5cea..7623477c3cc 100644 --- a/src/content/docs/agents/guides/securing-mcp-server.mdx +++ b/src/content/docs/agents/model-context-protocol/guides/securing-mcp-server.mdx @@ -276,13 +276,13 @@ When reading the cookie, verify the HMAC signature before trusting the data. If diff --git a/src/content/docs/agents/guides/test-remote-mcp-server.mdx b/src/content/docs/agents/model-context-protocol/guides/test-remote-mcp-server.mdx similarity index 97% rename from src/content/docs/agents/guides/test-remote-mcp-server.mdx rename to src/content/docs/agents/model-context-protocol/guides/test-remote-mcp-server.mdx index 8b6addff89f..8f3538dcc99 100644 --- a/src/content/docs/agents/guides/test-remote-mcp-server.mdx +++ b/src/content/docs/agents/model-context-protocol/guides/test-remote-mcp-server.mdx @@ -14,7 +14,7 @@ import { Render } from "~/components"; Remote, authorized connections are an evolving part of the [Model Context Protocol (MCP) specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization). Not all MCP clients support remote connections yet. -This guide will show you options for how to start using your remote MCP server with MCP clients that support remote connections. If you haven't yet created and deployed a remote MCP server, you should follow the [Build a Remote MCP Server](/agents/guides/remote-mcp-server/) guide first. +This guide will show you options for how to start using your remote MCP server with MCP clients that support remote connections. If you haven't yet created and deployed a remote MCP server, you should follow the [Build a Remote MCP Server](/agents/model-context-protocol/guides/remote-mcp-server/) guide first. ## The Model Context Protocol (MCP) inspector diff --git a/src/content/docs/agents/model-context-protocol/index.mdx b/src/content/docs/agents/model-context-protocol/index.mdx index 17226e3269a..a50df326d3e 100644 --- a/src/content/docs/agents/model-context-protocol/index.mdx +++ b/src/content/docs/agents/model-context-protocol/index.mdx @@ -5,7 +5,7 @@ pcx_content_type: navigation tags: - MCP sidebar: - order: 6 + order: 8 products: - agents --- @@ -20,13 +20,13 @@ You can build and deploy [Model Context Protocol (MCP)](https://modelcontextprot - **MCP Hosts**: AI assistants (like [Claude](https://claude.ai) or [Cursor](https://cursor.com)), AI agents, or applications that need to access external capabilities. - **MCP Clients**: Clients embedded within the MCP hosts that connect to MCP servers and invoke tools. Each MCP client instance has a single connection to an MCP server. -- **MCP Servers**: Applications that expose [tools](/agents/model-context-protocol/tools/), [prompts](https://modelcontextprotocol.io/docs/concepts/prompts), and [resources](https://modelcontextprotocol.io/docs/concepts/resources) that MCP clients can use. +- **MCP Servers**: Applications that expose [tools](/agents/model-context-protocol/protocol/tools/), [prompts](https://modelcontextprotocol.io/docs/concepts/prompts), and [resources](https://modelcontextprotocol.io/docs/concepts/resources) that MCP clients can use. ### Remote vs. local MCP connections The MCP standard supports two modes of operation: -- **Remote MCP connections**: MCP clients connect to MCP servers over the Internet, establishing a connection using [Streamable HTTP](/agents/model-context-protocol/transport/), and authorizing the MCP client access to resources on the user's account using [OAuth](/agents/model-context-protocol/authorization/). +- **Remote MCP connections**: MCP clients connect to MCP servers over the Internet, establishing a connection using [Streamable HTTP](/agents/model-context-protocol/protocol/transport/), and authorizing the MCP client access to resources on the user's account using [OAuth](/agents/model-context-protocol/protocol/authorization/). - **Local MCP connections**: MCP clients connect to MCP servers on the same machine, using [stdio](https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#stdio) as a local transport method. ### Best Practices @@ -38,4 +38,4 @@ The MCP standard supports two modes of operation: ### Get Started -Go to the [Getting Started](/agents/guides/remote-mcp-server/) guide to learn how to build and deploy your first remote MCP server to Cloudflare. +Go to the [Getting Started](/agents/model-context-protocol/guides/remote-mcp-server/) guide to learn how to build and deploy your first remote MCP server to Cloudflare. diff --git a/src/content/docs/agents/model-context-protocol/authorization.mdx b/src/content/docs/agents/model-context-protocol/protocol/authorization.mdx similarity index 95% rename from src/content/docs/agents/model-context-protocol/authorization.mdx rename to src/content/docs/agents/model-context-protocol/protocol/authorization.mdx index 5a56aa84942..586c15644f1 100644 --- a/src/content/docs/agents/model-context-protocol/authorization.mdx +++ b/src/content/docs/agents/model-context-protocol/protocol/authorization.mdx @@ -37,7 +37,7 @@ To deploy an [example MCP server](https://github.com/cloudflare/ai/tree/main/dem ### (2) Third-party OAuth Provider -The [OAuth Provider Library](https://github.com/cloudflare/workers-oauth-provider) can be configured to use a third-party OAuth provider, such as GitHub or Google. You can see a complete example of this in the [GitHub example](/agents/guides/remote-mcp-server/#add-authentication). +The [OAuth Provider Library](https://github.com/cloudflare/workers-oauth-provider) can be configured to use a third-party OAuth provider, such as GitHub or Google. You can see a complete example of this in the [GitHub example](/agents/model-context-protocol/guides/remote-mcp-server/#add-authentication). When you use a third-party OAuth provider, you must provide a handler to the `OAuthProvider` that implements the OAuth flow for the third-party provider. @@ -148,7 +148,7 @@ export default new OAuthProvider({ }); ``` -Refer to the [getting started example](/agents/guides/remote-mcp-server/) for a complete example of the `OAuthProvider` in use, with a mock authentication flow. +Refer to the [getting started example](/agents/model-context-protocol/guides/remote-mcp-server/) for a complete example of the `OAuthProvider` in use, with a mock authentication flow. The authorization flow in this case works like this: @@ -172,7 +172,7 @@ sequenceDiagram Note over C,M: Begin standard MCP message exchange ``` -Remember — [authentication is different from authorization](https://www.cloudflare.com/learning/access-management/authn-vs-authz/). Your MCP Server can handle authorization itself, while still relying on an external authentication service to first authenticate users. The [example](/agents/guides/remote-mcp-server) in getting started provides a mock authentication flow. You will need to implement your own authentication handler — either handling authentication yourself, or using an external authentication services. +Remember — [authentication is different from authorization](https://www.cloudflare.com/learning/access-management/authn-vs-authz/). Your MCP Server can handle authorization itself, while still relying on an external authentication service to first authenticate users. The [example](/agents/model-context-protocol/guides/remote-mcp-server/) in getting started provides a mock authentication flow. You will need to implement your own authentication handler — either handling authentication yourself, or using an external authentication services. ## Using authentication context in tools diff --git a/src/content/docs/agents/api-reference/codemode.mdx b/src/content/docs/agents/model-context-protocol/protocol/codemode.mdx similarity index 98% rename from src/content/docs/agents/api-reference/codemode.mdx rename to src/content/docs/agents/model-context-protocol/protocol/codemode.mdx index 3d7cafed9dd..576eed3e26b 100644 --- a/src/content/docs/agents/api-reference/codemode.mdx +++ b/src/content/docs/agents/model-context-protocol/protocol/codemode.mdx @@ -5,7 +5,7 @@ description: Let LLMs write and execute JavaScript to orchestrate multiple tool tags: - AI sidebar: - order: 19 + order: 5 products: - agents --- @@ -305,7 +305,7 @@ const { messages, sendMessage } = useAgentChat({ agent, tools }); This pattern is useful when the browser owns the tool surface at runtime, the page exposes client-side capabilities that only the browser can run, or you want codemode's typed code-generation prompt without routing tool execution through the server. -If you need approval-gated tools, use the standard `needsApproval` and `useAgentChat` approval flow described in [Human in the Loop](/agents/concepts/human-in-the-loop/). Codemode excludes tools with `needsApproval` instead of pausing execution for approval. +If you need approval-gated tools, use the standard `needsApproval` and `useAgentChat` approval flow described in [Human in the Loop](/agents/concepts/agentic-patterns/human-in-the-loop/). Codemode excludes tools with `needsApproval` instead of pausing execution for approval. ## MCP server wrappers @@ -483,12 +483,12 @@ sanitizeToolName("delete"); // "delete_" diff --git a/src/content/docs/agents/model-context-protocol/governance.mdx b/src/content/docs/agents/model-context-protocol/protocol/governance.mdx similarity index 65% rename from src/content/docs/agents/model-context-protocol/governance.mdx rename to src/content/docs/agents/model-context-protocol/protocol/governance.mdx index e14e1190055..bde421c18e3 100644 --- a/src/content/docs/agents/model-context-protocol/governance.mdx +++ b/src/content/docs/agents/model-context-protocol/protocol/governance.mdx @@ -28,6 +28,6 @@ Cloudflare Access logs MCP server requests and tool executions made through the ## Remote MCP servers -To maintain a modern security posture, Cloudflare recommends the use of [remote MCP servers](/agents/guides/remote-mcp-server/) over local installations. Running MCP servers locally introduces risks similar to unmanaged [shadow IT](https://www.cloudflare.com/learning/access-management/what-is-shadow-it/), making it difficult to audit data flow or verify the integrity of the server code. Remote MCP servers give administrators visibility into what servers are being used, along with the ability to control who access them and what tools are authorized for employee use. +To maintain a modern security posture, Cloudflare recommends the use of [remote MCP servers](/agents/model-context-protocol/guides/remote-mcp-server/) over local installations. Running MCP servers locally introduces risks similar to unmanaged [shadow IT](https://www.cloudflare.com/learning/access-management/what-is-shadow-it/), making it difficult to audit data flow or verify the integrity of the server code. Remote MCP servers give administrators visibility into what servers are being used, along with the ability to control who access them and what tools are authorized for employee use. -You can [build your remote MCP servers](/agents/guides/remote-mcp-server/) directly on Cloudflare Workers. When both your [MCP server portal](#mcp-server-portals) and remote MCP servers run on Cloudflare's network, requests stay on the same infrastructure, minimizing latency and maximizing performance. +You can [build your remote MCP servers](/agents/model-context-protocol/guides/remote-mcp-server/) directly on Cloudflare Workers. When both your [MCP server portal](#mcp-server-portals) and remote MCP servers run on Cloudflare's network, requests stay on the same infrastructure, minimizing latency and maximizing performance. diff --git a/src/content/docs/agents/model-context-protocol/protocol/index.mdx b/src/content/docs/agents/model-context-protocol/protocol/index.mdx new file mode 100644 index 00000000000..891142f62a2 --- /dev/null +++ b/src/content/docs/agents/model-context-protocol/protocol/index.mdx @@ -0,0 +1,12 @@ +--- +title: Protocol +pcx_content_type: navigation +sidebar: + order: 2 + group: + hideIndex: true +--- + +import { DirectoryListing } from "~/components"; + + diff --git a/src/content/docs/agents/model-context-protocol/tools.mdx b/src/content/docs/agents/model-context-protocol/protocol/tools.mdx similarity index 90% rename from src/content/docs/agents/model-context-protocol/tools.mdx rename to src/content/docs/agents/model-context-protocol/protocol/tools.mdx index 97a05647328..507c18060cb 100644 --- a/src/content/docs/agents/model-context-protocol/tools.mdx +++ b/src/content/docs/agents/model-context-protocol/protocol/tools.mdx @@ -14,7 +14,7 @@ import { TypeScriptExample, LinkCard } from "~/components"; MCP tools are functions that an [MCP server](/agents/model-context-protocol/) exposes for clients to call. When an LLM decides it needs to take an action — look up data, run a calculation, call an API — it invokes a tool. The MCP server executes the tool and returns the result. -Tools are defined using the `@modelcontextprotocol/sdk` package. The Agents SDK handles transport and lifecycle; the tool definitions are the same regardless of whether you use [`createMcpHandler`](/agents/api-reference/mcp-handler-api/) or [`McpAgent`](/agents/api-reference/mcp-agent-api/). +Tools are defined using the `@modelcontextprotocol/sdk` package. The Agents SDK handles transport and lifecycle; the tool definitions are the same regardless of whether you use [`createMcpHandler`](/agents/model-context-protocol/apis/handler-api/) or [`McpAgent`](/agents/model-context-protocol/apis/agent-api/). :::note[Experimental WebMCP adapter] @@ -134,7 +134,7 @@ server.tool( ## Using tools with `createMcpHandler` -For stateless MCP servers, define tools inside a factory function and pass the server to [`createMcpHandler`](/agents/api-reference/mcp-handler-api/): +For stateless MCP servers, define tools inside a factory function and pass the server to [`createMcpHandler`](/agents/model-context-protocol/apis/handler-api/): @@ -165,7 +165,7 @@ export default { ## Using tools with `McpAgent` -For stateful MCP servers, define tools in the `init()` method of an [`McpAgent`](/agents/api-reference/mcp-agent-api/). Tools have access to the agent instance via `this`, which means they can read and write state. +For stateful MCP servers, define tools in the `init()` method of an [`McpAgent`](/agents/model-context-protocol/apis/agent-api/). Tools have access to the agent instance via `this`, which means they can read and write state. @@ -200,24 +200,24 @@ export class MyMCP extends McpAgent { diff --git a/src/content/docs/agents/model-context-protocol/transport.mdx b/src/content/docs/agents/model-context-protocol/protocol/transport.mdx similarity index 91% rename from src/content/docs/agents/model-context-protocol/transport.mdx rename to src/content/docs/agents/model-context-protocol/protocol/transport.mdx index 8d14f6ca004..c657f14078e 100644 --- a/src/content/docs/agents/model-context-protocol/transport.mdx +++ b/src/content/docs/agents/model-context-protocol/protocol/transport.mdx @@ -18,14 +18,14 @@ The Model Context Protocol (MCP) specification defines two standard [transport m 2. **Streamable HTTP** — The standard transport method for remote MCP connections, [introduced](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http) in March 2025. It uses a single HTTP endpoint for bidirectional messaging. :::note -Server-Sent Events (SSE) was previously used for remote MCP connections but has been deprecated in favor of Streamable HTTP. If you need SSE support for legacy clients, use the [`McpAgent`](/agents/api-reference/mcp-agent-api/) class. +Server-Sent Events (SSE) was previously used for remote MCP connections but has been deprecated in favor of Streamable HTTP. If you need SSE support for legacy clients, use the [`McpAgent`](/agents/model-context-protocol/apis/agent-api/) class. ::: -MCP servers built with the [Agents SDK](/agents) use [`createMcpHandler`](/agents/api-reference/mcp-handler-api/) to handle Streamable HTTP transport. +MCP servers built with the [Agents SDK](/agents) use [`createMcpHandler`](/agents/model-context-protocol/apis/handler-api/) to handle Streamable HTTP transport. ## Implementing remote MCP transport -Use [`createMcpHandler`](/agents/api-reference/mcp-handler-api/) to create an MCP server that handles Streamable HTTP transport. This is the recommended approach for new MCP servers. +Use [`createMcpHandler`](/agents/model-context-protocol/apis/handler-api/) to create an MCP server that handles Streamable HTTP transport. This is the recommended approach for new MCP servers. #### Get started quickly @@ -103,9 +103,9 @@ export default new OAuthProvider({ If your MCP server needs to maintain state across requests, use `createMcpHandler` with a `WorkerTransport` inside an [Agent](/agents/) class. This allows you to persist session state in Durable Object storage and use advanced MCP features like [elicitation](https://modelcontextprotocol.io/specification/draft/client/elicitation) and [sampling](https://modelcontextprotocol.io/specification/draft/client/sampling). -See [Stateful MCP Servers](/agents/api-reference/mcp-handler-api#stateful-mcp-servers) for implementation details. +See [Stateful MCP Servers](/agents/model-context-protocol/apis/handler-api/#stateful-mcp-servers) for implementation details. -Streamable HTTP streams are resumable: configure an `EventStore` so clients can reconnect with a `Last-Event-ID` header and replay missed events, keeping in-flight tool calls alive across the edge idle-stream watchdog. `DurableObjectEventStore` is exported from `agents/mcp` for stateful `WorkerTransport` callers. Refer to [`McpAgent`: Stream resumability](/agents/api-reference/mcp-agent-api/#stream-resumability). +Streamable HTTP streams are resumable: configure an `EventStore` so clients can reconnect with a `Last-Event-ID` header and replay missed events, keeping in-flight tool calls alive across the edge idle-stream watchdog. `DurableObjectEventStore` is exported from `agents/mcp` for stateful `WorkerTransport` callers. Refer to [`McpAgent`: Stream resumability](/agents/model-context-protocol/apis/agent-api/#stream-resumability). ## RPC transport @@ -192,7 +192,7 @@ export class Chat extends AIChatAgent { RPC connections are automatically restored after Durable Object hibernation, just like HTTP connections. The binding name and props are persisted to storage so the connection can be re-established without any extra code. -For RPC transport, if `addMcpServer` is called with a name that already has an active connection, the existing connection is returned instead of creating a duplicate. For HTTP transport, deduplication matches on both server name and URL (refer to [MCP Client API](/agents/api-reference/mcp-client-api/) for details). This makes it safe to call in `onStart()`. +For RPC transport, if `addMcpServer` is called with a name that already has an active connection, the existing connection is returned instead of creating a duplicate. For HTTP transport, deduplication matches on both server name and URL (refer to [MCP Client API](/agents/model-context-protocol/apis/client-api/) for details). This makes it safe to call in `onStart()`. #### 3. Configure Durable Object bindings @@ -331,11 +331,11 @@ export class MyMCP extends McpAgent { If you have an existing MCP server using the `McpAgent` class: - **Not using state?** Replace your `McpAgent` class with `McpServer` from `@modelcontextprotocol/sdk` and use `createMcpHandler(server)` in a Worker `fetch` handler. -- **Using state?** Use `createMcpHandler` with a `WorkerTransport` inside an [Agent](/agents/) class. See [Stateful MCP Servers](/agents/api-reference/mcp-handler-api#stateful-mcp-servers) for details. -- **Need SSE support?** Continue using `McpAgent` with `serveSSE()` for legacy client compatibility. See the [McpAgent API reference](/agents/api-reference/mcp-agent-api/). +- **Using state?** Use `createMcpHandler` with a `WorkerTransport` inside an [Agent](/agents/) class. See [Stateful MCP Servers](/agents/model-context-protocol/apis/handler-api/#stateful-mcp-servers) for details. +- **Need SSE support?** Continue using `McpAgent` with `serveSSE()` for legacy client compatibility. See the [McpAgent API reference](/agents/model-context-protocol/apis/agent-api/). ### Testing with MCP clients You can test your MCP server using an MCP client that supports remote connections, or use [`mcp-remote`](https://www.npmjs.com/package/mcp-remote), an adapter that lets MCP clients that only support local connections work with remote MCP servers. -Follow [this guide](/agents/guides/test-remote-mcp-server/) for instructions on how to connect to your remote MCP server to Claude Desktop, Cursor, Windsurf, and other MCP clients. +Follow [this guide](/agents/model-context-protocol/guides/test-remote-mcp-server/) for instructions on how to connect to your remote MCP server to Claude Desktop, Cursor, Windsurf, and other MCP clients. diff --git a/src/content/docs/agents/platform/index.mdx b/src/content/docs/agents/platform/index.mdx index a13e9ccf12f..4dd2f7adb1e 100644 --- a/src/content/docs/agents/platform/index.mdx +++ b/src/content/docs/agents/platform/index.mdx @@ -3,7 +3,7 @@ pcx_content_type: reference title: Platform description: Review platform details for Cloudflare Agents, including limits and configuration options. sidebar: - order: 7 + order: 9 group: hideIndex: true products: diff --git a/src/content/docs/agents/platform/limits.mdx b/src/content/docs/agents/platform/limits.mdx index b12fc8e6b78..b531c72fad9 100644 --- a/src/content/docs/agents/platform/limits.mdx +++ b/src/content/docs/agents/platform/limits.mdx @@ -28,6 +28,6 @@ Many limits are inherited from those applied to Workers scripts and/or Durable O [^2]: You can deploy up to [500 scripts per account](/workers/platform/limits/), but each script (project) can define multiple Agents. Each deployed script can be up to 10 MB on the [Workers Paid Plan](/workers/platform/pricing/#workers) -[^3]: Compute (CPU) time per Agent is limited to 30 seconds, but this is refreshed when an Agent receives a new HTTP request, runs a [scheduled task](/agents/api-reference/schedule-tasks/), or an incoming WebSocket message. +[^3]: Compute (CPU) time per Agent is limited to 30 seconds, but this is refreshed when an Agent receives a new HTTP request, runs a [scheduled task](/agents/runtime/execution/schedule-tasks/), or an incoming WebSocket message. diff --git a/src/content/docs/agents/platform/prompt.txt.mdx b/src/content/docs/agents/platform/prompt.txt.mdx deleted file mode 100644 index 60d3bf4a67a..00000000000 --- a/src/content/docs/agents/platform/prompt.txt.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -pcx_content_type: navigation -title: prompt.txt -external_link: /workers/prompt.txt -sidebar: - order: 99 -head: [] -description: Provide context to your AI models & tools when building on Cloudflare. -products: - - agents ---- diff --git a/src/content/docs/agents/platform/prompting.mdx b/src/content/docs/agents/platform/prompting.mdx deleted file mode 100644 index b21821c05a9..00000000000 --- a/src/content/docs/agents/platform/prompting.mdx +++ /dev/null @@ -1,11 +0,0 @@ ---- -pcx_content_type: navigation -title: Prompt Engineering -external_link: /workers/get-started/prompting/ -sidebar: - order: 98 -head: [] -description: Learn how to prompt engineer your AI models & tools when building Agents & Workers on Cloudflare. -products: - - agents ---- diff --git a/src/content/docs/agents/api-reference/agents-api.mdx b/src/content/docs/agents/runtime/agents-api.mdx similarity index 79% rename from src/content/docs/agents/api-reference/agents-api.mdx rename to src/content/docs/agents/runtime/agents-api.mdx index 064581ea18a..ad7907fd3d8 100644 --- a/src/content/docs/agents/api-reference/agents-api.mdx +++ b/src/content/docs/agents/runtime/agents-api.mdx @@ -23,7 +23,7 @@ The Agents SDK provides two main APIs: :::note -Agents require [Cloudflare Durable Objects](/durable-objects/). Refer to [Configuration](/agents/api-reference/configuration/) to learn how to add the required bindings. +Agents require [Cloudflare Durable Objects](/durable-objects/). Refer to [Configuration](/agents/runtime/operations/configuration/) to learn how to add the required bindings. ::: @@ -65,7 +65,7 @@ flowchart TD | 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`. | +| `onStart(props?)` | When the instance starts, or wakes from hibernation. Receives optional [initialization props](/agents/runtime/communication/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 | @@ -87,25 +87,26 @@ flowchart TD | 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()`, `getScheduleById()`, `listSchedules()` | [Schedule tasks](/agents/api-reference/schedule-tasks/) | -| **Durable execution** | `runFiber()`, `startFiber()`, `stash()`, `onFiberRecovered()`, `keepAlive()`, `keepAliveWhile()` | [Durable execution](/agents/api-reference/durable-execution/) | -| **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** | `subscribe()`, diagnostics channels, Tail Workers | [Observability](/agents/api-reference/observability/) | -| **Sub-agents** | `subAgent()`, `abortSubAgent()`, `deleteSubAgent()` | [Sub-agents](/agents/api-reference/sub-agents/) | -| **Agent tools** | `runAgentTool()`, `clearAgentToolRuns()`, `hasAgentToolRun()` | [Agent tools](/agents/api-reference/agent-tools/) | -| **Sessions** | `Session.create()`, context blocks, compaction, search | [Sessions](/agents/api-reference/sessions/) | -| **Think** | `Think` base class, workspace tools, lifecycle hooks, extensions | [Think](/agents/think/) | -| **Chat SDK** | `createChatSdkState()`, `ChatSdkStateAgent` | [Chat SDK](/agents/api-reference/chat-sdk/) | +| **State** | `setState()`, `onStateChanged()`, `initialState` | [Store and sync state](/agents/runtime/lifecycle/state/) | +| **Callable methods** | `@callable()` decorator | [Callable methods](/agents/runtime/lifecycle/callable-methods/) | +| **Scheduling** | `schedule()`, `scheduleEvery()`, `getScheduleById()`, `listSchedules()` | [Schedule tasks](/agents/runtime/execution/schedule-tasks/) | +| **Durable execution** | `runFiber()`, `startFiber()`, `stash()`, `onFiberRecovered()`, `keepAlive()`, `keepAliveWhile()` | [Durable execution](/agents/runtime/execution/durable-execution/) | +| **Queue** | `queue()`, `dequeue()`, `dequeueAll()`, `getQueue()` | [Queue tasks](/agents/runtime/execution/queue-tasks/) | +| **WebSockets** | `onConnect()`, `onMessage()`, `onClose()`, `broadcast()` | [WebSockets](/agents/runtime/communication/websockets/) | +| **HTTP/SSE** | `onRequest()` | [HTTP and SSE](/agents/runtime/communication/http-sse/) | +| **Email** | `onEmail()`, `replyToEmail()` | [Email routing](/agents/communication-channels/email/) | +| **Workflows** | `runWorkflow()`, `waitForApproval()` | [Run Workflows](/agents/runtime/execution/run-workflows/) | +| **MCP Client** | `addMcpServer()`, `removeMcpServer()`, `getMcpServers()` | [MCP Client API](/agents/model-context-protocol/apis/client-api/) | +| **AI Models** | Workers AI, OpenAI, Anthropic bindings | [Using AI models](/agents/runtime/operations/using-ai-models/) | +| **Protocol messages** | `shouldSendProtocolMessages()`, `isConnectionProtocolEnabled()` | [Protocol messages](/agents/runtime/communication/protocol-messages/) | +| **Context** | `getCurrentAgent()` | [getCurrentAgent()](/agents/runtime/lifecycle/get-current-agent/) | +| **Observability** | `subscribe()`, diagnostics channels, Tail Workers | [Observability](/agents/runtime/operations/observability/) | +| **Sub-agents** | `subAgent()`, `abortSubAgent()`, `deleteSubAgent()` | [Sub-agents](/agents/runtime/execution/sub-agents/) | +| **Agent tools** | `runAgentTool()`, `clearAgentToolRuns()`, `hasAgentToolRun()` | [Agent tools](/agents/runtime/execution/agent-tools/) | +| **Agent Skills** | `skills` registry, bundled skill sources, script runners | [Agent Skills](/agents/runtime/execution/agent-skills/) | +| **Sessions** | `Session.create()`, context blocks, compaction, search | [Sessions](/agents/runtime/lifecycle/sessions/) | +| **Think** | `Think` base class, workspace tools, lifecycle hooks, extensions | [Think](/agents/harnesses/think/) | +| **Chat SDK** | `createChatSdkState()`, `ChatSdkStateAgent` | [Chat SDK](/agents/runtime/execution/chat-sdk/) | ## SQL API @@ -122,17 +123,17 @@ this.sql`INSERT INTO users (id, name) VALUES (${id}, ${name})`; const users = this.sql`SELECT * FROM users WHERE id = ${id}`; ``` -For state that needs to sync with clients, use the [State API](/agents/api-reference/store-and-sync-state/) instead. +For state that needs to sync with clients, use the [State API](/agents/runtime/lifecycle/state/) instead. ## Client-side API reference | 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/) | -| **Agent tool events** | `useAgentToolEvents()` | [Agent tools](/agents/api-reference/agent-tools/#render-child-timelines-in-react) | +| **WebSocket client** | `AgentClient` | [Client SDK](/agents/communication-channels/chat/client-sdk/) | +| **HTTP client** | `agentFetch()` | [Client SDK](/agents/communication-channels/chat/client-sdk/#http-requests-with-agentfetch) | +| **React hook** | `useAgent()` | [Client SDK](/agents/communication-channels/chat/client-sdk/#react) | +| **Chat hook** | `useAgentChat()` | [Client SDK](/agents/communication-channels/chat/client-sdk/) | +| **Agent tool events** | `useAgentToolEvents()` | [Agent tools](/agents/runtime/execution/agent-tools/#render-child-timelines-in-react) | Module-level helper exports include `agentTool()` from `agents/agent-tools`, which converts a Think or `AIChatAgent` subclass into an AI SDK tool definition. @@ -177,7 +178,7 @@ Features include: - Automatic resumable streaming (reconnect mid-stream) - Works with `useAgentChat` React hook -Refer to [Build a chat agent](/agents/getting-started/build-a-chat-agent/) for a complete tutorial. +Refer to [Build a chat agent](/agents/examples/chat-agent/) for a complete tutorial. ## Routing @@ -202,7 +203,7 @@ export default { } satisfies ExportedHandler; ``` -Refer to [Routing](/agents/api-reference/routing/) for custom paths, CORS, and instance naming patterns. +Refer to [Routing](/agents/runtime/communication/routing/) for custom paths, CORS, and instance naming patterns. ## Next steps @@ -214,18 +215,18 @@ Refer to [Routing](/agents/api-reference/routing/) for custom paths, CORS, and i diff --git a/src/content/docs/agents/api-reference/http-sse.mdx b/src/content/docs/agents/runtime/communication/http-sse.mdx similarity index 92% rename from src/content/docs/agents/api-reference/http-sse.mdx rename to src/content/docs/agents/runtime/communication/http-sse.mdx index bb854ae0d94..cda13eb8cda 100644 --- a/src/content/docs/agents/api-reference/http-sse.mdx +++ b/src/content/docs/agents/runtime/communication/http-sse.mdx @@ -146,8 +146,8 @@ export class ChatAgent extends Agent { SSE connections can be long-lived. Handle client disconnects gracefully: -- **Persist progress** — Write to [agent state](/agents/api-reference/store-and-sync-state/) so clients can resume -- **Use agent routing** — Clients can [reconnect to the same agent instance](/agents/api-reference/routing/) without session stores +- **Persist progress** — Write to [agent state](/agents/runtime/lifecycle/state/) so clients can resume +- **Use agent routing** — Clients can [reconnect to the same agent instance](/agents/runtime/communication/routing/) without session stores - **No timeout limits** — Cloudflare Workers have no effective limit on SSE response duration @@ -190,24 +190,24 @@ export class ResumeAgent extends Agent { **Recommendation:** Use WebSockets for interactive applications. Use SSE for streaming AI responses or server-push notifications. -Refer to [WebSockets](/agents/api-reference/websockets/) for WebSocket documentation. +Refer to [WebSockets](/agents/runtime/communication/websockets/) for WebSocket documentation. ## Next steps diff --git a/src/content/docs/agents/runtime/communication/index.mdx b/src/content/docs/agents/runtime/communication/index.mdx new file mode 100644 index 00000000000..afc1b725017 --- /dev/null +++ b/src/content/docs/agents/runtime/communication/index.mdx @@ -0,0 +1,12 @@ +--- +title: Communication +pcx_content_type: navigation +sidebar: + order: 2 + group: + hideIndex: true +--- + +import { DirectoryListing } from "~/components"; + + diff --git a/src/content/docs/agents/api-reference/protocol-messages.mdx b/src/content/docs/agents/runtime/communication/protocol-messages.mdx similarity index 88% rename from src/content/docs/agents/api-reference/protocol-messages.mdx rename to src/content/docs/agents/runtime/communication/protocol-messages.mdx index 19310ef8462..1097bf4606a 100644 --- a/src/content/docs/agents/api-reference/protocol-messages.mdx +++ b/src/content/docs/agents/runtime/communication/protocol-messages.mdx @@ -24,7 +24,7 @@ On every new connection, the Agent sends three protocol messages: State and MCP messages are also broadcast to all connections whenever they change. -For most web clients this is fine — the [Client SDK](/agents/api-reference/client-sdk/) and `useAgent` hook consume these messages automatically. However, some clients cannot handle JSON text frames: +For most web clients this is fine — the [Client SDK](/agents/communication-channels/chat/client-sdk/) and `useAgent` hook consume these messages automatically. However, some clients cannot handle JSON text frames: - **Binary-only clients** — MQTT devices, IoT sensors, custom binary protocols - **Lightweight clients** — Embedded systems with minimal WebSocket stacks @@ -173,7 +173,7 @@ An overridable hook that determines if a connection should receive protocol mess Default: returns `true` (all connections receive protocol messages). -This hook is evaluated once on connect. The result is persisted in the connection's WebSocket attachment and survives [hibernation](/agents/api-reference/websockets/#hibernation). +This hook is evaluated once on connect. The result is persisted in the connection's WebSocket attachment and survives [hibernation](/agents/runtime/communication/websockets/#hibernation). ### `isConnectionProtocolEnabled` @@ -188,18 +188,18 @@ Safe to call at any time, including after the agent wakes from hibernation. ## How it works -Protocol status is stored as an internal flag in the connection's WebSocket attachment — the same mechanism used by [readonly connections](/agents/api-reference/readonly-connections/). This means: +Protocol status is stored as an internal flag in the connection's WebSocket attachment — the same mechanism used by [readonly connections](/agents/runtime/communication/readonly-connections/). This means: - **Survives hibernation** — the flag is serialized and restored when the agent wakes up - **No cleanup needed** — connection state is automatically discarded when the connection closes - **Zero overhead** — no database tables or queries, just the connection's built-in attachment - **Safe from user code** — `connection.state` and `connection.setState()` never expose or overwrite the flag -Unlike [readonly](/agents/api-reference/readonly-connections/) which can be toggled dynamically with `setConnectionReadonly()`, protocol status is set once on connect and cannot be changed afterward. To change a connection's protocol status, the client must disconnect and reconnect. +Unlike [readonly](/agents/runtime/communication/readonly-connections/) which can be toggled dynamically with `setConnectionReadonly()`, protocol status is set once on connect and cannot be changed afterward. To change a connection's protocol status, the client must disconnect and reconnect. ## Related resources -- [Readonly connections](/agents/api-reference/readonly-connections/) -- [WebSockets](/agents/api-reference/websockets/) -- [Store and sync state](/agents/api-reference/store-and-sync-state/) -- [MCP Client API](/agents/api-reference/mcp-client-api/) +- [Readonly connections](/agents/runtime/communication/readonly-connections/) +- [WebSockets](/agents/runtime/communication/websockets/) +- [Store and sync state](/agents/runtime/lifecycle/state/) +- [MCP Client API](/agents/model-context-protocol/apis/client-api/) diff --git a/src/content/docs/agents/api-reference/readonly-connections.mdx b/src/content/docs/agents/runtime/communication/readonly-connections.mdx similarity index 97% rename from src/content/docs/agents/api-reference/readonly-connections.mdx rename to src/content/docs/agents/runtime/communication/readonly-connections.mdx index 4fc9ecc76d8..35e683a7e6f 100644 --- a/src/content/docs/agents/api-reference/readonly-connections.mdx +++ b/src/content/docs/agents/runtime/communication/readonly-connections.mdx @@ -455,7 +455,7 @@ function GameComponent() { ## How it works -Readonly status is stored in the connection's WebSocket attachment, which persists through the WebSocket Hibernation API. The flag is namespaced internally so it cannot be accidentally overwritten by `connection.setState()`. The same mechanism is used by [protocol message control](/agents/api-reference/protocol-messages/) — both flag coexist safely in the attachment. This means: +Readonly status is stored in the connection's WebSocket attachment, which persists through the WebSocket Hibernation API. The flag is namespaced internally so it cannot be accidentally overwritten by `connection.setState()`. The same mechanism is used by [protocol message control](/agents/runtime/communication/protocol-messages/) — both flag coexist safely in the attachment. This means: - **Survives hibernation** — the flag is serialized and restored when the agent wakes up - **No cleanup needed** — connection state is automatically discarded when the connection closes @@ -627,7 +627,7 @@ export class AuditedAgent extends Agent { ## Related resources -- [Store and sync state](/agents/api-reference/store-and-sync-state/) -- [Protocol messages](/agents/api-reference/protocol-messages/) — suppress JSON protocol frames for binary-only clients (can be combined with readonly) -- [WebSockets](/agents/api-reference/websockets/) -- [Callable methods](/agents/api-reference/callable-methods/) +- [Store and sync state](/agents/runtime/lifecycle/state/) +- [Protocol messages](/agents/runtime/communication/protocol-messages/) — suppress JSON protocol frames for binary-only clients (can be combined with readonly) +- [WebSockets](/agents/runtime/communication/websockets/) +- [Callable methods](/agents/runtime/lifecycle/callable-methods/) diff --git a/src/content/docs/agents/api-reference/routing.mdx b/src/content/docs/agents/runtime/communication/routing.mdx similarity index 97% rename from src/content/docs/agents/api-reference/routing.mdx rename to src/content/docs/agents/runtime/communication/routing.mdx index b5b7a44ee81..151d1a8175a 100644 --- a/src/content/docs/agents/api-reference/routing.mdx +++ b/src/content/docs/agents/runtime/communication/routing.mdx @@ -472,7 +472,7 @@ export default { For agent-specific initialization, use `getAgentByName` instead where you control exactly which agent receives the props. :::note -For `McpAgent`, props are automatically stored and accessible via `this.props`. Refer to [MCP servers](/agents/api-reference/mcp-agent-api/) for details. +For `McpAgent`, props are automatically stored and accessible via `this.props`. Refer to [MCP servers](/agents/model-context-protocol/apis/agent-api/) for details. ::: ### Routing retry @@ -514,7 +514,7 @@ const response = await routeAgentRequest(request, env, { -These hooks are useful for authentication and validation. Refer to [Cross-domain authentication](/agents/guides/cross-domain-authentication/) for detailed examples. +These hooks are useful for authentication and validation. Refer to [Cross-domain authentication](/agents/runtime/operations/cross-domain-authentication/) for detailed examples. ## Server-side agent access @@ -767,7 +767,7 @@ export default app; -For WebSocket authentication patterns (tokens in URLs, JWT refresh), refer to [Cross-domain authentication](/agents/guides/cross-domain-authentication/). +For WebSocket authentication patterns (tokens in URLs, JWT refresh), refer to [Cross-domain authentication](/agents/runtime/operations/cross-domain-authentication/). ## Troubleshooting @@ -878,24 +878,24 @@ class SecureAgent extends Agent { diff --git a/src/content/docs/agents/api-reference/websockets.mdx b/src/content/docs/agents/runtime/communication/websockets.mdx similarity index 97% rename from src/content/docs/agents/api-reference/websockets.mdx rename to src/content/docs/agents/runtime/communication/websockets.mdx index bbe45beb77c..077ab9f6687 100644 --- a/src/content/docs/agents/api-reference/websockets.mdx +++ b/src/content/docs/agents/runtime/communication/websockets.mdx @@ -10,7 +10,7 @@ products: import { TypeScriptExample, LinkCard } from "~/components"; -Agents support WebSocket connections for real-time, bi-directional communication. This page covers server-side WebSocket handling. For client-side connection, refer to the [Client SDK](/agents/api-reference/client-sdk/). +Agents support WebSocket connections for real-time, bi-directional communication. This page covers server-side WebSocket handling. For client-side connection, refer to the [Client SDK](/agents/communication-channels/chat/client-sdk/). ## Lifecycle hooks @@ -224,7 +224,7 @@ export class ChatAgent extends Agent { | `getConnection` | `(id: string) => Connection \| undefined` | Get connection by ID | | `getConnectionTags` | `(connection, ctx) => string[]` | Override to tag connections | | `broadcast` | `(message, without?: string[]) => void` | Send to all connections | -| `isConnectionReadonly` | `(connection) => boolean` | Check if a connection is [readonly](/agents/api-reference/readonly-connections/) | +| `isConnectionReadonly` | `(connection) => boolean` | Check if a connection is [readonly](/agents/runtime/communication/readonly-connections/) | | `isConnectionProtocolEnabled` | `(connection) => boolean` | Check if protocol messages are enabled for this connection | ## Handling binary data @@ -255,7 +255,7 @@ export class FileAgent extends Agent { :::note -Agents automatically send JSON text frames (identity, state, MCP servers) to every connection. If your client only handles binary data and cannot process these frames, use [`shouldSendProtocolMessages`](/agents/api-reference/protocol-messages/) to suppress them. +Agents automatically send JSON text frames (identity, state, MCP servers) to every connection. If your client only handles binary data and cannot process these frames, use [`shouldSendProtocolMessages`](/agents/runtime/communication/protocol-messages/) to suppress them. ::: ## Error and close handling @@ -554,24 +554,24 @@ For browser connections, use the Agents client SDK: - **Vanilla JS**: `AgentClient` from `agents/client` - **React**: `useAgent` hook from `agents/react` -Refer to [Client SDK](/agents/api-reference/client-sdk/) for full documentation. +Refer to [Client SDK](/agents/communication-channels/chat/client-sdk/) for full documentation. ## Next steps diff --git a/src/content/docs/agents/api-reference/agent-skills.mdx b/src/content/docs/agents/runtime/execution/agent-skills.mdx similarity index 91% rename from src/content/docs/agents/api-reference/agent-skills.mdx rename to src/content/docs/agents/runtime/execution/agent-skills.mdx index ed5621b0e85..133da646ae1 100644 --- a/src/content/docs/agents/api-reference/agent-skills.mdx +++ b/src/content/docs/agents/runtime/execution/agent-skills.mdx @@ -16,7 +16,7 @@ Agent Skills are on-demand instructions, resources, and scripts. A skill source Agent Skills are experimental, and script execution in particular is early. The API may change in a future release. ::: -The skills engine lives in `agents/skills` and is framework-agnostic, so any agent (including a plain [`AIChatAgent`](/agents/api-reference/chat-agents/) `onChatMessage`) can build a `SkillRegistry`. [`@cloudflare/think`](/agents/think/) re-exports it as the `skills` namespace and wires `getSkills()` into the turn automatically. +The skills engine lives in `agents/skills` and is framework-agnostic, so any agent (including a plain [`AIChatAgent`](/agents/communication-channels/chat/chat-agents/) `onChatMessage`) can build a `SkillRegistry`. [`@cloudflare/think`](/agents/harnesses/think/) re-exports it as the `skills` namespace and wires `getSkills()` into the turn automatically. ## Using skills with Think @@ -135,5 +135,5 @@ Refer to the [`agent-skills` example](https://github.com/cloudflare/agents/tree/ ## Related -- [Think](/agents/think/) — wires `getSkills()` and `getSkillScriptRunner()` into the agentic loop -- [Think tools](/agents/think/tools/) — how skill tools merge with workspace, custom, MCP, and client tools +- [Think](/agents/harnesses/think/) — wires `getSkills()` and `getSkillScriptRunner()` into the agentic loop +- [Think tools](/agents/harnesses/think/tools/) — how skill tools merge with workspace, custom, MCP, and client tools diff --git a/src/content/docs/agents/api-reference/agent-tools.mdx b/src/content/docs/agents/runtime/execution/agent-tools.mdx similarity index 97% rename from src/content/docs/agents/api-reference/agent-tools.mdx rename to src/content/docs/agents/runtime/execution/agent-tools.mdx index 9b5425e92f6..da496ce6d8d 100644 --- a/src/content/docs/agents/api-reference/agent-tools.mdx +++ b/src/content/docs/agents/runtime/execution/agent-tools.mdx @@ -18,8 +18,7 @@ Agent tools support `@cloudflare/think` agents and `AIChatAgent` subclasses. `AI Use `subAgent(...).chat()` when parent code needs direct streaming RPC to a specific child and your code owns forwarding, cancellation, and replay policy. -Use `agentTool()` or `runAgentTool()` when a parent model or workflow delegates work to a child agent and you want retained child runs, event replay, abort bridging, and UI drill-in. For Think-specific turn choices, refer to [Choose a turn API](/agents/think/#choose-a-turn-api). - +Use `agentTool()` or `runAgentTool()` when a parent model or workflow delegates work to a child agent and you want retained child runs, event replay, abort bridging, and UI drill-in. For Think-specific turn choices, refer to [Choose a turn API](/agents/harnesses/think/#choose-a-turn-api). ## Use an agent as an AI SDK tool Use `agentTool()` when the parent model should decide when to call the helper. @@ -270,12 +269,12 @@ Raw `diagnostics_channel` subscribers should use the channel name `agents:agent_ diff --git a/src/content/docs/agents/api-reference/chat-sdk.mdx b/src/content/docs/agents/runtime/execution/chat-sdk.mdx similarity index 100% rename from src/content/docs/agents/api-reference/chat-sdk.mdx rename to src/content/docs/agents/runtime/execution/chat-sdk.mdx diff --git a/src/content/docs/agents/api-reference/durable-execution.mdx b/src/content/docs/agents/runtime/execution/durable-execution.mdx similarity index 95% rename from src/content/docs/agents/api-reference/durable-execution.mdx rename to src/content/docs/agents/runtime/execution/durable-execution.mdx index 5790c71b7db..c82697923a7 100644 --- a/src/content/docs/agents/api-reference/durable-execution.mdx +++ b/src/content/docs/agents/runtime/execution/durable-execution.mdx @@ -1,5 +1,5 @@ --- -title: Durable execution +title: Durable execution with fibers pcx_content_type: reference description: Run work that survives Durable Object eviction with runFiber(), startFiber(), keepAlive(), and crash recovery. tags: @@ -16,7 +16,7 @@ Use `startFiber()` when a caller needs to durably accept background work, return :::note -For how fibers fit into the bigger picture of building agents that run for weeks or months, refer to [Long-running agents](/agents/concepts/long-running-agents/). +For how fibers fit into the bigger picture of building agents that run for weeks or months, refer to [Long-running agents](/agents/concepts/agentic-patterns/long-running-agents/). ::: @@ -60,7 +60,7 @@ When eviction happens mid-work, the upstream HTTP connection (to an LLM provider `keepAlive()` reduces the chance of eviction. `runFiber()` makes eviction survivable. -For work that should run independently of the agent with per-step retries and multi-step orchestration, use [Workflows](/agents/concepts/workflows/) instead. Fibers are for work that is part of the agent's own execution. Refer to [Long-running agents: Workflows vs agent-internal patterns](/agents/concepts/long-running-agents/#when-to-use-workflows-vs-agent-internal-patterns) for a comparison. +For work that should run independently of the agent with per-step retries and multi-step orchestration, use [Workflows](/agents/runtime/execution/run-workflows/) instead. Fibers are for work that is part of the agent's own execution. Refer to [Long-running agents: Workflows vs agent-internal patterns](/agents/concepts/agentic-patterns/long-running-agents/#when-to-use-workflows-vs-agent-internal-patterns) for a comparison. ## keepAlive @@ -401,7 +401,7 @@ Key points: ### Chat recovery -`AIChatAgent` builds on fibers for LLM streaming recovery. When `chatRecovery` is enabled, each chat turn is wrapped in a fiber automatically. The framework handles the internal recovery path and exposes `onChatRecovery` for provider-specific strategies. Refer to [Long-running agents: Recovering interrupted LLM streams](/agents/concepts/long-running-agents/#recovering-interrupted-llm-streams) for details. +`AIChatAgent` builds on fibers for LLM streaming recovery. When `chatRecovery` is enabled, each chat turn is wrapped in a fiber automatically. The framework handles the internal recovery path and exposes `onChatRecovery` for provider-specific strategies. Refer to [Long-running agents: Recovering interrupted LLM streams](/agents/concepts/agentic-patterns/long-running-agents/#recovering-interrupted-llm-streams) for details. ## Concurrent fibers @@ -494,8 +494,8 @@ Run an async function while keeping the DO alive. Heartbeat starts before `fn` a ## Related -- [Long-running agents](/agents/concepts/long-running-agents/) — how fibers compose with schedules, plans, and async operations -- [Schedule tasks](/agents/api-reference/schedule-tasks/) — `keepAlive` details and the alarm system -- [Sub-agents](/agents/api-reference/sub-agents/) — durable execution and schedules inside sub-agents -- [Workflows](/agents/concepts/workflows/) — durable multi-step execution outside the agent -- [Chat agents](/agents/api-reference/chat-agents/) — `chatRecovery` and `onChatRecovery` +- [Long-running agents](/agents/concepts/agentic-patterns/long-running-agents/) — how fibers compose with schedules, plans, and async operations +- [Schedule tasks](/agents/runtime/execution/schedule-tasks/) — `keepAlive` details and the alarm system +- [Sub-agents](/agents/runtime/execution/sub-agents/) — durable execution and schedules inside sub-agents +- [Workflows](/agents/runtime/execution/run-workflows/) — durable multi-step execution outside the agent +- [Chat agents](/agents/communication-channels/chat/chat-agents/) — `chatRecovery` and `onChatRecovery` diff --git a/src/content/docs/agents/runtime/execution/index.mdx b/src/content/docs/agents/runtime/execution/index.mdx new file mode 100644 index 00000000000..6014c2a070b --- /dev/null +++ b/src/content/docs/agents/runtime/execution/index.mdx @@ -0,0 +1,12 @@ +--- +title: Execution +pcx_content_type: navigation +sidebar: + order: 3 + group: + hideIndex: true +--- + +import { DirectoryListing } from "~/components"; + + diff --git a/src/content/docs/agents/api-reference/queue-tasks.mdx b/src/content/docs/agents/runtime/execution/queue-tasks.mdx similarity index 94% rename from src/content/docs/agents/api-reference/queue-tasks.mdx rename to src/content/docs/agents/runtime/execution/queue-tasks.mdx index cad118f92bb..bedead7d6ac 100644 --- a/src/content/docs/agents/api-reference/queue-tasks.mdx +++ b/src/content/docs/agents/runtime/execution/queue-tasks.mdx @@ -47,7 +47,7 @@ async queue( - `callback` - The name of the method to call when processing the task - `payload` - Data to pass to the callback method - `options` - Optional configuration: - - `retry` - Retry options for the callback execution. If the callback throws, it is retried with exponential backoff. Refer to [Retries](/agents/api-reference/retries/) for details on `RetryOptions` + - `retry` - Retry options for the callback execution. If the callback throws, it is retried with exponential backoff. Refer to [Retries](/agents/runtime/execution/retries/) for details on `RetryOptions` **Returns:** The unique ID of the queued task @@ -338,7 +338,7 @@ class RobustAgent extends Agent { -If no `retry` option is provided, the class-level defaults from `static options.retry` are used (3 attempts, 100ms base delay, 3s max delay). Refer to [Retries](/agents/api-reference/retries/) for full details. +If no `retry` option is provided, the class-level defaults from `static options.retry` are used (3 attempts, 100ms base delay, 3s max delay). Refer to [Retries](/agents/runtime/execution/retries/) for full details. ## Best practices @@ -353,7 +353,7 @@ If no `retry` option is provided, the class-level defaults from `static options. The queue system works with other Agent SDK features: - **State management**: Access agent state within queued callbacks. -- **Scheduling**: Combine with [`schedule()`](/agents/api-reference/schedule-tasks/) for time-based queue processing. +- **Scheduling**: Combine with [`schedule()`](/agents/runtime/execution/schedule-tasks/) for time-based queue processing. - **Context**: Queued tasks maintain the original request context. - **Database**: Uses the same database as other agent data. @@ -365,7 +365,7 @@ The queue system works with other Agent SDK features: ## Queue vs Schedule -Use **queue** when you want tasks to execute as soon as possible in order. Use [**schedule**](/agents/api-reference/schedule-tasks/) when you need tasks to run at specific times or on a recurring basis. +Use **queue** when you want tasks to execute as soon as possible in order. Use [**schedule**](/agents/runtime/execution/schedule-tasks/) when you need tasks to run at specific times or on a recurring basis. | Feature | Queue | Schedule | | ---------------- | ------------------------ | --------------------------- | @@ -377,18 +377,18 @@ Use **queue** when you want tasks to execute as soon as possible in order. Use [ diff --git a/src/content/docs/agents/api-reference/retries.mdx b/src/content/docs/agents/runtime/execution/retries.mdx similarity index 98% rename from src/content/docs/agents/api-reference/retries.mdx rename to src/content/docs/agents/runtime/execution/retries.mdx index 766c3c7b5e4..3cd350f13f8 100644 --- a/src/content/docs/agents/api-reference/retries.mdx +++ b/src/content/docs/agents/runtime/execution/retries.mdx @@ -507,18 +507,18 @@ class MyAgent extends Agent { diff --git a/src/content/docs/agents/api-reference/run-workflows.mdx b/src/content/docs/agents/runtime/execution/run-workflows.mdx similarity index 99% rename from src/content/docs/agents/api-reference/run-workflows.mdx rename to src/content/docs/agents/runtime/execution/run-workflows.mdx index 6fce2192371..93fc3e33c18 100644 --- a/src/content/docs/agents/api-reference/run-workflows.mdx +++ b/src/content/docs/agents/runtime/execution/run-workflows.mdx @@ -847,18 +847,18 @@ Workflows cannot open WebSocket connections directly. Use `broadcastToClients()` diff --git a/src/content/docs/agents/api-reference/schedule-tasks.mdx b/src/content/docs/agents/runtime/execution/schedule-tasks.mdx similarity index 98% rename from src/content/docs/agents/api-reference/schedule-tasks.mdx rename to src/content/docs/agents/runtime/execution/schedule-tasks.mdx index 289467335aa..b73a8fc8f34 100644 --- a/src/content/docs/agents/api-reference/schedule-tasks.mdx +++ b/src/content/docs/agents/runtime/execution/schedule-tasks.mdx @@ -704,7 +704,7 @@ Schedule a task for future execution. - `when` - When to execute: `number` (seconds delay), `Date` (specific time), or `string` (cron expression) - `callback` - Name of the method to call - `payload` - Data to pass to the callback (must be JSON-serializable) -- `options.retry` - Optional retry configuration. Refer to [Retries](/agents/api-reference/retries/) for details +- `options.retry` - Optional retry configuration. Refer to [Retries](/agents/runtime/execution/retries/) for details - `options.idempotent` - Deduplicate by callback + payload. Defaults to `true` for cron schedules, `false` for delayed and Date-based schedules **Returns:** A `Schedule` object with the task details @@ -752,7 +752,7 @@ Schedule a task to run repeatedly at a fixed interval. - `intervalSeconds` - Number of seconds between executions (must be greater than 0) - `callback` - Name of the method to call - `payload` - Data to pass to the callback (must be JSON-serializable) -- `options.retry` - Optional retry configuration. Refer to [Retries](/agents/api-reference/retries/) for details. +- `options.retry` - Optional retry configuration. Refer to [Retries](/agents/runtime/execution/retries/) for details. **Returns:** A `Schedule` object with `type: "interval"` @@ -916,24 +916,24 @@ dispose2(); // Now the agent can go idle diff --git a/src/content/docs/agents/api-reference/sub-agents.mdx b/src/content/docs/agents/runtime/execution/sub-agents.mdx similarity index 95% rename from src/content/docs/agents/api-reference/sub-agents.mdx rename to src/content/docs/agents/runtime/execution/sub-agents.mdx index 54f1b123ae1..1b173a5d06f 100644 --- a/src/content/docs/agents/api-reference/sub-agents.mdx +++ b/src/content/docs/agents/runtime/execution/sub-agents.mdx @@ -5,7 +5,7 @@ description: Spawn child agents with isolated storage and typed RPC using subAge tags: - AI sidebar: - order: 15 + order: 5 products: - agents --- @@ -16,7 +16,7 @@ Spawn child agents as co-located Durable Objects with their own isolated SQLite Use sub-agents when a single user or entity owns an open-ended set of long-lived agents, such as chats, documents, sessions, shards, or projects. Each sub-agent runs in parallel with its own state while the parent coordinates discovery, access control, and lifecycle. -If you want a parent chat agent to dispatch another chat-capable agent during a single turn and render that child's progress inline, use [Agent tools](/agents/api-reference/agent-tools/). Agent tools are built on sub-agents, but add a parent-side run registry, streaming `agent-tool-event` frames, replay, cancellation, and cleanup. +If you want a parent chat agent to dispatch another chat-capable agent during a single turn and render that child's progress inline, use [Agent tools](/agents/runtime/execution/agent-tools/). Agent tools are built on sub-agents, but add a parent-side run registry, streaming `agent-tool-event` frames, replay, cancellation, and cleanup. ## Quick start @@ -516,8 +516,8 @@ Calling `this.destroy()` inside a sub-agent delegates cleanup to the parent. The ## Related -- [Think](/agents/think/) — `chat()` method for streaming AI turns through sub-agents -- [Long-running agents](/agents/concepts/long-running-agents/) — sub-agent delegation in the context of multi-week agent lifetimes -- [Callable methods](/agents/api-reference/callable-methods/) — RPC via `@callable` and service bindings -- [Agent tools](/agents/api-reference/agent-tools/) — run Think or `AIChatAgent` sub-agents as retained, streaming tools -- [Schedule tasks](/agents/api-reference/schedule-tasks/) — scheduling primitives for top-level agents and sub-agents +- [Think](/agents/harnesses/think/) — `chat()` method for streaming AI turns through sub-agents +- [Long-running agents](/agents/concepts/agentic-patterns/long-running-agents/) — sub-agent delegation in the context of multi-week agent lifetimes +- [Callable methods](/agents/runtime/lifecycle/callable-methods/) — RPC via `@callable` and service bindings +- [Agent tools](/agents/runtime/execution/agent-tools/) — run Think or `AIChatAgent` sub-agents as retained, streaming tools +- [Schedule tasks](/agents/runtime/execution/schedule-tasks/) — scheduling primitives for top-level agents and sub-agents \ No newline at end of file diff --git a/src/content/docs/agents/runtime/index.mdx b/src/content/docs/agents/runtime/index.mdx new file mode 100644 index 00000000000..af883fedb83 --- /dev/null +++ b/src/content/docs/agents/runtime/index.mdx @@ -0,0 +1,14 @@ +--- +title: Runtime +pcx_content_type: navigation +sidebar: + order: 6 + group: + hideIndex: true +--- + +import { DirectoryListing } from "~/components"; + +The runtime powers your agent — state, communication, execution, and operations. + + diff --git a/src/content/docs/agents/concepts/agent-class.mdx b/src/content/docs/agents/runtime/lifecycle/agent-class.mdx similarity index 96% rename from src/content/docs/agents/concepts/agent-class.mdx rename to src/content/docs/agents/runtime/lifecycle/agent-class.mdx index 861c8934aaf..96afc85310f 100644 --- a/src/content/docs/agents/concepts/agent-class.mdx +++ b/src/content/docs/agents/runtime/lifecycle/agent-class.mdx @@ -10,7 +10,7 @@ products: The core of the `agents` library is the `Agent` class. You extend it, override a few methods, and get state management, WebSockets, scheduling, RPC, and more for free. This page explains how `Agent` is built, layer by layer, so you understand what is happening under the hood. -The snippets shown here are illustrative and do not necessarily represent best practices. For the full API, refer to the [API reference](/agents/api-reference/) and the [source code](https://github.com/cloudflare/agents/blob/main/packages/agents/src/index.ts). +The snippets shown here are illustrative and do not necessarily represent best practices. For the full API, refer to the [API reference](/agents/runtime/) and the [source code](https://github.com/cloudflare/agents/blob/main/packages/agents/src/index.ts). ## What is the Agent? @@ -210,7 +210,7 @@ class MyAgent extends Agent { } ``` -State is stored in the `cf_agents_state` SQL table. State messages are sent with `type: "cf_agent_state"` (both from the client and the server). Since `agents` provides [JS and React clients](/agents/api-reference/store-and-sync-state/#synchronizing-state), real-time state updates are available out of the box. +State is stored in the `cf_agents_state` SQL table. State messages are sent with `type: "cf_agent_state"` (both from the client and the server). Since `agents` provides [JS and React clients](/agents/runtime/lifecycle/state/#synchronizing-state), real-time state updates are available out of the box. ### `this.sql` @@ -328,7 +328,7 @@ Schedules are stored in the `cf_agents_schedules` SQL table. Cron schedules auto ### `this.mcp` and friends -`Agent` includes a multi-server MCP client. This enables your Agent to interact with external services that expose MCP interfaces. The MCP client is properly documented in [MCP client API](/agents/api-reference/mcp-client-api/). +`Agent` includes a multi-server MCP client. This enables your Agent to interact with external services that expose MCP interfaces. The MCP client is properly documented in [MCP client API](/agents/model-context-protocol/apis/client-api/). ```ts class MyAgent extends Agent { @@ -507,7 +507,7 @@ class MyAgent extends Agent { } ``` -`AIChatAgent` uses `keepAliveWhile` internally to keep the agent alive during streaming LLM responses. For more details, refer to [Schedule tasks — Keeping the agent alive](/agents/api-reference/schedule-tasks/#keeping-the-agent-alive). +`AIChatAgent` uses `keepAliveWhile` internally to keep the agent alive during streaming LLM responses. For more details, refer to [Schedule tasks — Keeping the agent alive](/agents/runtime/execution/schedule-tasks/#keeping-the-agent-alive). ### Routing @@ -525,7 +525,7 @@ return new Response("Not found", { status: 404 }); ## Layer 3: `AIChatAgent` -The [`AIChatAgent`](/agents/api-reference/chat-agents/) class from `@cloudflare/ai-chat` extends `Agent` with an opinionated layer for AI chat. It adds automatic message persistence to SQLite, resumable streaming, tool support (server-side, client-side, and human-in-the-loop), and a React hook (`useAgentChat`) for building chat UIs. +The [`AIChatAgent`](/agents/communication-channels/chat/chat-agents/) class from `@cloudflare/ai-chat` extends `Agent` with an opinionated layer for AI chat. It adds automatic message persistence to SQLite, resumable streaming, tool support (server-side, client-side, and human-in-the-loop), and a React hook (`useAgentChat`) for building chat UIs. The full hierarchy is: **DurableObject** > **Server** > **Agent** > **AIChatAgent**. diff --git a/src/content/docs/agents/api-reference/callable-methods.mdx b/src/content/docs/agents/runtime/lifecycle/callable-methods.mdx similarity index 99% rename from src/content/docs/agents/api-reference/callable-methods.mdx rename to src/content/docs/agents/runtime/lifecycle/callable-methods.mdx index d4d21d3f3ae..4a398a7706a 100644 --- a/src/content/docs/agents/api-reference/callable-methods.mdx +++ b/src/content/docs/agents/runtime/lifecycle/callable-methods.mdx @@ -743,18 +743,18 @@ Do not set `"experimentalDecorators": true` in your `tsconfig.json`. The Agents diff --git a/src/content/docs/agents/api-reference/get-current-agent.mdx b/src/content/docs/agents/runtime/lifecycle/get-current-agent.mdx similarity index 98% rename from src/content/docs/agents/api-reference/get-current-agent.mdx rename to src/content/docs/agents/runtime/lifecycle/get-current-agent.mdx index 61416697f3c..61bd432d712 100644 --- a/src/content/docs/agents/api-reference/get-current-agent.mdx +++ b/src/content/docs/agents/runtime/lifecycle/get-current-agent.mdx @@ -277,18 +277,18 @@ The context available depends on how the method was invoked: diff --git a/src/content/docs/agents/runtime/lifecycle/index.mdx b/src/content/docs/agents/runtime/lifecycle/index.mdx new file mode 100644 index 00000000000..cc12db0abd2 --- /dev/null +++ b/src/content/docs/agents/runtime/lifecycle/index.mdx @@ -0,0 +1,12 @@ +--- +title: Lifecycle +pcx_content_type: navigation +sidebar: + order: 1 + group: + hideIndex: true +--- + +import { DirectoryListing } from "~/components"; + + diff --git a/src/content/docs/agents/api-reference/sessions.mdx b/src/content/docs/agents/runtime/lifecycle/sessions.mdx similarity index 98% rename from src/content/docs/agents/api-reference/sessions.mdx rename to src/content/docs/agents/runtime/lifecycle/sessions.mdx index 5f8f61ec9e1..012770117bc 100644 --- a/src/content/docs/agents/api-reference/sessions.mdx +++ b/src/content/docs/agents/runtime/lifecycle/sessions.mdx @@ -902,6 +902,6 @@ By default, storage is in Durable Object SQLite and tables are created lazily on ## Related -- [Think](/agents/think/) — opinionated chat agent that uses Session for conversation storage via `configureSession()` -- [Chat agents](/agents/api-reference/chat-agents/) — `AIChatAgent` with its own message persistence layer -- [Store and sync state](/agents/api-reference/store-and-sync-state/) — `setState()` for simpler key-value persistence +- [Think](/agents/harnesses/think/) — opinionated chat agent that uses Session for conversation storage via `configureSession()` +- [Chat agents](/agents/communication-channels/chat/chat-agents/) — `AIChatAgent` with its own message persistence layer +- [Store and sync state](/agents/runtime/lifecycle/state/) — `setState()` for simpler key-value persistence \ No newline at end of file diff --git a/src/content/docs/agents/api-reference/store-and-sync-state.mdx b/src/content/docs/agents/runtime/lifecycle/state.mdx similarity index 95% rename from src/content/docs/agents/api-reference/store-and-sync-state.mdx rename to src/content/docs/agents/runtime/lifecycle/state.mdx index d0b98cd996a..903b195108c 100644 --- a/src/content/docs/agents/api-reference/store-and-sync-state.mdx +++ b/src/content/docs/agents/runtime/lifecycle/state.mdx @@ -27,7 +27,7 @@ State within an Agent is: Agent state is stored in a SQL database embedded within each individual Agent instance. You can interact with it using the higher-level `this.setState` API (recommended), which allows you to sync state and trigger events on state changes, or by directly querying the database with `this.sql`. :::note[State vs Props] -**State** is persistent data that survives restarts and syncs across clients. **[Props](/agents/api-reference/routing/#props)** are one-time initialization arguments passed when an agent is instantiated - use props for configuration that does not need to persist. +**State** is persistent data that survives restarts and syncs across clients. **[Props](/agents/runtime/communication/routing/#props)** are one-time initialization arguments passed when an agent is instantiated - use props for configuration that does not need to persist. ::: @@ -186,7 +186,7 @@ export class MinimalAgent extends Agent { Use `setState()` to update state. This: 1. Saves to SQLite (persistent) -2. Broadcasts to all connected clients (excluding connections where [`shouldSendProtocolMessages`](/agents/api-reference/protocol-messages/) returned `false`) +2. Broadcasts to all connected clients (excluding connections where [`shouldSendProtocolMessages`](/agents/runtime/communication/protocol-messages/) returned `false`) 3. Triggers `onStateChanged()` (after broadcast; best-effort) @@ -426,7 +426,7 @@ flowchart TD ## State from Workflows -When using [Workflows](/agents/api-reference/run-workflows/), you can update agent state from workflow steps: +When using [Workflows](/agents/runtime/execution/run-workflows/), you can update agent state from workflow steps: @@ -642,7 +642,7 @@ onStateChanged(state: State, source: Connection | "server") { ## Use Agent state as model context -You can combine the state and SQL APIs in your Agent with its ability to [call AI models](/agents/api-reference/using-ai-models/) to include historical context within your prompts to a model. Modern Large Language Models (LLMs) often have very large context windows (up to millions of tokens), which allows you to pull relevant context into your prompt directly. +You can combine the state and SQL APIs in your Agent with its ability to [call AI models](/agents/runtime/operations/using-ai-models/) to include historical context within your prompts to a model. Modern Large Language Models (LLMs) often have very large context windows (up to millions of tokens), which allows you to pull relevant context into your prompt directly. For example, you can use an Agent's built-in SQL database to pull history, query a model with it, and append to that history ahead of the next call to the model: @@ -719,24 +719,24 @@ This works because each instance of an Agent has its own database, and the state diff --git a/src/content/docs/agents/api-reference/configuration.mdx b/src/content/docs/agents/runtime/operations/configuration.mdx similarity index 98% rename from src/content/docs/agents/api-reference/configuration.mdx rename to src/content/docs/agents/runtime/operations/configuration.mdx index 0ab4244656e..1212b041e92 100644 --- a/src/content/docs/agents/api-reference/configuration.mdx +++ b/src/content/docs/agents/runtime/operations/configuration.mdx @@ -325,7 +325,7 @@ export default defineConfig({ The `agents()` plugin is safe to include even if your project does not use decorators. It only runs the transform on files that contain `@` syntax. -The starter template and all examples include this plugin by default. If you encounter `SyntaxError: Invalid or unexpected token` with decorators, refer to [Callable methods — Troubleshooting](/agents/api-reference/callable-methods/#troubleshooting). +The starter template and all examples include this plugin by default. If you encounter `SyntaxError: Invalid or unexpected token` with decorators, refer to [Callable methods — Troubleshooting](/agents/runtime/lifecycle/callable-methods/#troubleshooting). ## Generating types @@ -944,18 +944,18 @@ Migration tags must be unique. If you see conflicts: diff --git a/src/content/docs/agents/guides/cross-domain-authentication.mdx b/src/content/docs/agents/runtime/operations/cross-domain-authentication.mdx similarity index 98% rename from src/content/docs/agents/guides/cross-domain-authentication.mdx rename to src/content/docs/agents/runtime/operations/cross-domain-authentication.mdx index e0f26eb6c49..f226884d5b7 100644 --- a/src/content/docs/agents/guides/cross-domain-authentication.mdx +++ b/src/content/docs/agents/runtime/operations/cross-domain-authentication.mdx @@ -286,13 +286,13 @@ export class SecureAgent extends Agent { @@ -304,6 +304,6 @@ export class SecureAgent extends Agent { diff --git a/src/content/docs/agents/runtime/operations/index.mdx b/src/content/docs/agents/runtime/operations/index.mdx new file mode 100644 index 00000000000..a451c862df9 --- /dev/null +++ b/src/content/docs/agents/runtime/operations/index.mdx @@ -0,0 +1,12 @@ +--- +title: Operations +pcx_content_type: navigation +sidebar: + order: 4 + group: + hideIndex: true +--- + +import { DirectoryListing } from "~/components"; + + diff --git a/src/content/docs/agents/api-reference/observability.mdx b/src/content/docs/agents/runtime/operations/observability.mdx similarity index 99% rename from src/content/docs/agents/api-reference/observability.mdx rename to src/content/docs/agents/runtime/operations/observability.mdx index b96a6f73593..715a7f809b0 100644 --- a/src/content/docs/agents/api-reference/observability.mdx +++ b/src/content/docs/agents/runtime/operations/observability.mdx @@ -293,7 +293,7 @@ These events track chat message lifecycle, client-side tool interactions, and Th @@ -305,6 +305,6 @@ These events track chat message lifecycle, client-side tool interactions, and Th diff --git a/src/content/docs/agents/api-reference/using-ai-models.mdx b/src/content/docs/agents/runtime/operations/using-ai-models.mdx similarity index 92% rename from src/content/docs/agents/api-reference/using-ai-models.mdx rename to src/content/docs/agents/runtime/operations/using-ai-models.mdx index e5e724a3415..13a93257a05 100644 --- a/src/content/docs/agents/api-reference/using-ai-models.mdx +++ b/src/content/docs/agents/runtime/operations/using-ai-models.mdx @@ -26,13 +26,13 @@ The [AI SDK](https://ai-sdk.dev/docs/introduction) provides a unified interface ## Calling AI Models -You can call models from any method within an Agent, including from HTTP requests using the [`onRequest`](/agents/api-reference/agents-api/) handler, when a [scheduled task](/agents/api-reference/schedule-tasks/) runs, when handling a WebSocket message in the [`onMessage`](/agents/api-reference/websockets/) handler, or from any of your own methods. +You can call models from any method within an Agent, including from HTTP requests using the [`onRequest`](/agents/runtime/agents-api/) handler, when a [scheduled task](/agents/runtime/execution/schedule-tasks/) runs, when handling a WebSocket message in the [`onMessage`](/agents/runtime/communication/websockets/) handler, or from any of your own methods. Agents can call AI models on their own — autonomously — and can handle long-running responses that take minutes (or longer) to respond in full. If a client disconnects mid-stream, the Agent keeps running and can catch the client up when it reconnects. ### Streaming over WebSockets {/* long-running-model-requests */} -Modern reasoning models can take some time to both generate a response _and_ stream the response back to the client. Instead of buffering the entire response, you can stream it back over [WebSockets](/agents/api-reference/websockets/). +Modern reasoning models can take some time to both generate a response _and_ stream the response back to the client. Instead of buffering the entire response, you can stream it back over [WebSockets](/agents/runtime/communication/websockets/). @@ -79,7 +79,7 @@ export class MyAgent extends Agent { -You can also persist AI model responses back to [Agent state](/agents/api-reference/store-and-sync-state/) using `this.setState`. If a user disconnects, read the message history back and send it to the user when they reconnect. +You can also persist AI model responses back to [Agent state](/agents/runtime/lifecycle/state/) using `this.setState`. If a user disconnects, read the message history back and send it to the user when they reconnect. ## Workers AI @@ -242,7 +242,7 @@ export class MyAgent extends Agent { Agents can call models across any service that supports the OpenAI API. For example, you can use the OpenAI SDK to call one of [Google's Gemini models](https://ai.google.dev/gemini-api/docs/openai#node.js) directly from your Agent. -Agents can stream responses back over HTTP using Server-Sent Events (SSE) from within an `onRequest` handler, or by using the native [WebSocket API](/agents/api-reference/websockets/) to stream responses back to a client. +Agents can stream responses back over HTTP using Server-Sent Events (SSE) from within an `onRequest` handler, or by using the native [WebSocket API](/agents/runtime/communication/websockets/) to stream responses back to a client. diff --git a/src/content/docs/agents/tools/ai-search.mdx b/src/content/docs/agents/tools/ai-search.mdx new file mode 100644 index 00000000000..964b74449d3 --- /dev/null +++ b/src/content/docs/agents/tools/ai-search.mdx @@ -0,0 +1,111 @@ +--- +title: AI Search +description: Give agents retrieval capabilities with Cloudflare AI Search. +pcx_content_type: concept +sidebar: + order: 4 +products: + - agents +--- + +import { LinkCard, TypeScriptExample, WranglerConfig } from "~/components"; + +Agents can use [AI Search](/ai-search/) to retrieve relevant information from indexed content and use it to augment [calls to AI models](/agents/runtime/operations/using-ai-models/). AI Search manages the retrieval pipeline for you, including indexing, search, and optional chat completions over your content. + +Use AI Search when you want an agent to: + +- Search product docs, support content, user files, or internal knowledge bases. +- Retrieve relevant chunks before calling a model. +- Use managed indexing instead of building retrieval infrastructure yourself. +- Query content from an R2 bucket, website, or uploaded files. + +## Basic pattern + +Bind AI Search to your Worker, then query an instance from an agent method. + + + +```ts +import { Agent, callable } from "agents"; + +type Env = { + AI_SEARCH: AiSearchNamespace; +}; + +export class SearchAgent extends Agent { + @callable() + async searchKnowledge(query: string) { + const instance = this.env.AI_SEARCH.get("my-instance"); + + const results = await instance.search({ + messages: [{ role: "user", content: query }], + }); + + return results; + } +} +``` + + + +For answer generation, use `chatCompletions()` to retrieve relevant content and generate a response in one call. + + + +```ts +const instance = this.env.AI_SEARCH.get("my-instance"); + +const response = await instance.chatCompletions({ + messages: [{ role: "user", content: "How do I deploy an Agent?" }], + model: "@cf/meta/llama-3.3-70b-instruct-fp8-fast", + ai_search_options: { + retrieval: { + max_num_results: 5, + }, + }, +}); +``` + + + +## Configuration + +Use an `ai_search_namespaces` binding when the agent needs to access AI Search instances by name. + + + +```jsonc +{ + "ai_search_namespaces": [ + { + "binding": "AI_SEARCH", + "namespace": "default", + "remote": true + } + ] +} +``` + + + +Use `remote: true` to query deployed AI Search instances during local development with `wrangler dev`. + +## Related resources + + + + + + diff --git a/src/content/docs/agents/tools/browser.mdx b/src/content/docs/agents/tools/browser.mdx new file mode 100644 index 00000000000..aee02b8e6a0 --- /dev/null +++ b/src/content/docs/agents/tools/browser.mdx @@ -0,0 +1,115 @@ +--- +title: Browser +description: Give Agents full Chrome DevTools Protocol access to inspect pages, scrape data, and capture screenshots with Browser Run. +pcx_content_type: concept +sidebar: + order: 3 +products: + - agents +--- + +import { InlineBadge, LinkCard, TypeScriptExample, WranglerConfig } from "~/components"; + +Agents can use [Browser Run](/browser-run/) to inspect and interact with web pages through the [Chrome DevTools Protocol (CDP)](/browser-run/cdp/). Browser tools are useful when an agent needs to understand rendered pages, capture screenshots, debug frontend behavior, or extract information that is only available after JavaScript runs. + +Use browser tools when you want an agent to: + +- Open and inspect live web pages. +- Capture screenshots or page state. +- Scrape rendered content that is not present in static HTML. +- Debug frontend issues using CDP commands. +- Combine page inspection with other tools, such as RAG or Sandbox. + +## How it works + +Browser Run provides isolated browser sessions that agents can control with CDP. The agent can navigate pages, evaluate JavaScript, read DOM state, capture screenshots, and inspect network or console output. + +Because browser sessions run outside the Worker isolate, use them for work that needs a real browser environment rather than lightweight HTTP fetches. + +## Basic pattern + +Create browser tools with the Browser Run and Worker Loader bindings, then pass those tools to your model call. + + + +```ts +import { AIChatAgent } from "@cloudflare/ai-chat"; +import { createBrowserTools } from "agents/browser/ai"; +import { streamText, convertToModelMessages, stepCountIs } from "ai"; +import { createWorkersAI } from "workers-ai-provider"; + +export class BrowserAgent extends AIChatAgent { + async onChatMessage() { + const workersai = createWorkersAI({ binding: this.env.AI }); + const browserTools = createBrowserTools({ + browser: this.env.BROWSER, + loader: this.env.LOADER, + }); + + const result = streamText({ + model: workersai("@cf/zai-org/glm-4.7-flash"), + system: "You can inspect web pages with browser tools.", + messages: await convertToModelMessages(this.messages), + tools: browserTools, + stopWhen: stepCountIs(10), + }); + + return result.toUIMessageStreamResponse(); + } +} +``` + + + +Browser tools expose two capabilities: + +| Tool | Description | +| --- | --- | +| `browser_search` | Query the CDP specification to discover commands, events, and types. | +| `browser_execute` | Run CDP commands against a live browser session. | + +## Configuration + +Add the Browser Run and Worker Loader bindings to `wrangler.jsonc`. + + + +```jsonc +{ + "compatibility_flags": ["nodejs_compat"], + "browser": { + "binding": "BROWSER" + }, + "worker_loaders": [ + { + "binding": "LOADER" + } + ] +} +``` + + + +## Build a browser agent + +For a complete walkthrough, including Browser Run setup, tool definitions, and screenshot capture, use the browser agent example. + + + +## Related resources + + + + diff --git a/src/content/docs/agents/tools/index.mdx b/src/content/docs/agents/tools/index.mdx new file mode 100644 index 00000000000..46dcf1412aa --- /dev/null +++ b/src/content/docs/agents/tools/index.mdx @@ -0,0 +1,14 @@ +--- +title: Tools +pcx_content_type: navigation +sidebar: + order: 4 + group: + hideIndex: true +--- + +import { DirectoryListing } from "~/components"; + +Tools extend what agents can do — browse the web, process payments, run code, and more. + + diff --git a/src/content/docs/agents/tools/mcp.mdx b/src/content/docs/agents/tools/mcp.mdx new file mode 100644 index 00000000000..e9b2589fbd2 --- /dev/null +++ b/src/content/docs/agents/tools/mcp.mdx @@ -0,0 +1,98 @@ +--- +title: MCP +pcx_content_type: concept +description: Connect agents to external Model Context Protocol servers and use their tools in model calls. +sidebar: + order: 2 +products: + - agents +--- + +import { LinkCard, TypeScriptExample } from "~/components"; + +Agents can use [Model Context Protocol (MCP)](/agents/model-context-protocol/) as clients. Connect an agent to external MCP servers, discover the tools those servers expose, and pass those tools into model calls. + +Use MCP when you want an agent to: + +- Call tools exposed by external MCP servers. +- Reuse tools across agents, IDEs, and other AI clients. +- Connect to services that already expose an MCP endpoint. +- Add OAuth or token-based authorization around external tool access. + +To build an MCP server instead, refer to [Model Context Protocol (MCP)](/agents/model-context-protocol/). + +## Basic pattern + +Call `addMcpServer()` to connect to a remote MCP server, then pass `this.mcp.getAITools()` to the AI SDK. + + + +```ts +import { Agent } from "agents"; +import { generateText } from "ai"; +import { createWorkersAI } from "workers-ai-provider"; + +export class ToolAgent extends Agent { + async onStart() { + await this.addMcpServer("github", "https://mcp.github.com/mcp"); + } + + async onRequest(request: Request) { + const workersai = createWorkersAI({ binding: this.env.AI }); + + const response = await generateText({ + model: workersai("@cf/zai-org/glm-4.7-flash"), + prompt: "Use available tools to summarize the latest issue activity.", + tools: this.mcp.getAITools(), + }); + + return new Response(response.text); + } +} +``` + + + +If the server requires OAuth, `addMcpServer()` returns an authentication state and authorization URL. The connection is persisted in the agent's [SQL storage](/agents/runtime/lifecycle/state/). + +## Configuration + +For public MCP servers, no binding configuration is required. Store server URLs, API tokens, or OAuth settings as environment variables or secrets. + +For MCP servers that require bearer tokens or Cloudflare Access headers, pass custom transport headers when connecting. + + + +```ts +await this.addMcpServer("internal", this.env.MCP_SERVER_URL, { + transport: { + headers: { + Authorization: `Bearer ${this.env.MCP_TOKEN}`, + "CF-Access-Client-Id": this.env.CF_ACCESS_CLIENT_ID, + "CF-Access-Client-Secret": this.env.CF_ACCESS_CLIENT_SECRET, + }, + }, +}); +``` + + + +## Related resources + + + + + + diff --git a/src/content/docs/agents/agentic-payments/index.mdx b/src/content/docs/agents/tools/payments/index.mdx similarity index 96% rename from src/content/docs/agents/agentic-payments/index.mdx rename to src/content/docs/agents/tools/payments/index.mdx index ba0a72efb1f..c7a5133d215 100644 --- a/src/content/docs/agents/agentic-payments/index.mdx +++ b/src/content/docs/agents/tools/payments/index.mdx @@ -2,7 +2,7 @@ title: Agentic Payments pcx_content_type: overview sidebar: - order: 8 + order: 5 group: hideIndex: false description: Let AI agents pay for services programmatically using payment protocols like MPP and x402 with Cloudflare's Agents SDK. @@ -46,12 +46,12 @@ MPP supports multiple payment methods beyond blockchain — including cards (via diff --git a/src/content/docs/agents/agentic-payments/mpp/charge-for-http-content.mdx b/src/content/docs/agents/tools/payments/mpp-charge-for-http-content.mdx similarity index 100% rename from src/content/docs/agents/agentic-payments/mpp/charge-for-http-content.mdx rename to src/content/docs/agents/tools/payments/mpp-charge-for-http-content.mdx diff --git a/src/content/docs/agents/agentic-payments/mpp/index.mdx b/src/content/docs/agents/tools/payments/mpp.mdx similarity index 93% rename from src/content/docs/agents/agentic-payments/mpp/index.mdx rename to src/content/docs/agents/tools/payments/mpp.mdx index a151680ae87..0c916b415af 100644 --- a/src/content/docs/agents/agentic-payments/mpp/index.mdx +++ b/src/content/docs/agents/tools/payments/mpp.mdx @@ -47,7 +47,7 @@ MPP defines two payment intents: ## Compatibility with x402 -MPP is backwards-compatible with [x402](/agents/agentic-payments/x402/). The core x402 `exact` payment flows map directly onto MPP's `charge` intent, so MPP clients can consume existing x402 services without modification. +MPP is backwards-compatible with [x402](/agents/tools/payments/x402/). The core x402 `exact` payment flows map directly onto MPP's `charge` intent, so MPP clients can consume existing x402 services without modification. ## Charge for resources @@ -55,7 +55,7 @@ MPP is backwards-compatible with [x402](/agents/agentic-payments/x402/). The cor diff --git a/src/content/docs/agents/agentic-payments/x402/charge-for-http-content.mdx b/src/content/docs/agents/tools/payments/x402/charge-for-http-content.mdx similarity index 95% rename from src/content/docs/agents/agentic-payments/x402/charge-for-http-content.mdx rename to src/content/docs/agents/tools/payments/x402/charge-for-http-content.mdx index 6c4eb6ba342..06684a4f2a8 100644 --- a/src/content/docs/agents/agentic-payments/x402/charge-for-http-content.mdx +++ b/src/content/docs/agents/tools/payments/x402/charge-for-http-content.mdx @@ -107,5 +107,5 @@ Refer to the [x402 Workers example](https://github.com/cloudflare/agents/tree/ma ## Related - [Pay Per Crawl](/ai-crawl-control/features/pay-per-crawl/) — Native Cloudflare monetization without custom code -- [Charge for MCP tools](/agents/agentic-payments/x402/charge-for-mcp-tools/) — Charge per tool call instead of per request +- [Charge for MCP tools](/agents/tools/payments/x402/charge-for-mcp-tools/) — Charge per tool call instead of per request - [x402.org](https://x402.org) — Protocol specification diff --git a/src/content/docs/agents/agentic-payments/x402/charge-for-mcp-tools.mdx b/src/content/docs/agents/tools/payments/x402/charge-for-mcp-tools.mdx similarity index 89% rename from src/content/docs/agents/agentic-payments/x402/charge-for-mcp-tools.mdx rename to src/content/docs/agents/tools/payments/x402/charge-for-mcp-tools.mdx index 96fd9323a99..5243a05d424 100644 --- a/src/content/docs/agents/agentic-payments/x402/charge-for-mcp-tools.mdx +++ b/src/content/docs/agents/tools/payments/x402/charge-for-mcp-tools.mdx @@ -90,6 +90,6 @@ For a complete working example, refer to [x402-mcp on GitHub](https://github.com ## Related -- [Pay from Agents SDK](/agents/agentic-payments/x402/pay-from-agents-sdk/) — Build clients that pay for tools -- [Charge for HTTP content](/agents/agentic-payments/x402/charge-for-http-content/) — Gate HTTP endpoints -- [MCP server guide](/agents/guides/remote-mcp-server/) — Build your first MCP server +- [Pay from Agents SDK](/agents/tools/payments/x402/pay-from-agents-sdk/) — Build clients that pay for tools +- [Charge for HTTP content](/agents/tools/payments/x402/charge-for-http-content/) — Gate HTTP endpoints +- [MCP server guide](/agents/model-context-protocol/guides/remote-mcp-server/) — Build your first MCP server diff --git a/src/content/docs/agents/agentic-payments/x402/index.mdx b/src/content/docs/agents/tools/payments/x402/index.mdx similarity index 95% rename from src/content/docs/agents/agentic-payments/x402/index.mdx rename to src/content/docs/agents/tools/payments/x402/index.mdx index 4ae0cb18581..7b825da9698 100644 --- a/src/content/docs/agents/agentic-payments/x402/index.mdx +++ b/src/content/docs/agents/tools/payments/x402/index.mdx @@ -58,12 +58,12 @@ Supported networks include Base, Ethereum, Polygon, Optimism, Arbitrum, Avalanch @@ -73,12 +73,12 @@ Supported networks include Base, Ethereum, Polygon, Optimism, Arbitrum, Avalanch diff --git a/src/content/docs/agents/agentic-payments/x402/pay-from-agents-sdk.mdx b/src/content/docs/agents/tools/payments/x402/pay-from-agents-sdk.mdx similarity index 82% rename from src/content/docs/agents/agentic-payments/x402/pay-from-agents-sdk.mdx rename to src/content/docs/agents/tools/payments/x402/pay-from-agents-sdk.mdx index 7a20bfafb47..aeb80aada22 100644 --- a/src/content/docs/agents/agentic-payments/x402/pay-from-agents-sdk.mdx +++ b/src/content/docs/agents/tools/payments/x402/pay-from-agents-sdk.mdx @@ -61,6 +61,6 @@ Use `base-sepolia` for testing. Get test USDC from the [Circle faucet](https://f ## Related -- [Charge for MCP tools](/agents/agentic-payments/x402/charge-for-mcp-tools/) — Build servers that charge for tools -- [Pay from coding tools](/agents/agentic-payments/x402/pay-with-tool-plugins/) — Add payments to OpenCode or Claude Code -- [Human-in-the-loop guide](/agents/guides/human-in-the-loop/) — Implement approval workflows +- [Charge for MCP tools](/agents/tools/payments/x402/charge-for-mcp-tools/) — Build servers that charge for tools +- [Pay from coding tools](/agents/tools/payments/x402/pay-with-tool-plugins/) — Add payments to OpenCode or Claude Code +- [Human-in-the-loop guide](/agents/concepts/agentic-patterns/human-in-the-loop/) — Implement approval workflows diff --git a/src/content/docs/agents/agentic-payments/x402/pay-with-tool-plugins.mdx b/src/content/docs/agents/tools/payments/x402/pay-with-tool-plugins.mdx similarity index 92% rename from src/content/docs/agents/agentic-payments/x402/pay-with-tool-plugins.mdx rename to src/content/docs/agents/tools/payments/x402/pay-with-tool-plugins.mdx index 0d1d29e4ba1..8fec047db45 100644 --- a/src/content/docs/agents/agentic-payments/x402/pay-with-tool-plugins.mdx +++ b/src/content/docs/agents/tools/payments/x402/pay-with-tool-plugins.mdx @@ -158,7 +158,7 @@ Register the hook in `.claude/settings.json`: ## Related -- [Pay from Agents SDK](/agents/agentic-payments/x402/pay-from-agents-sdk/) — Use the Agents SDK for more control -- [Charge for HTTP content](/agents/agentic-payments/x402/charge-for-http-content/) — Build the server side -- [Human-in-the-loop guide](/agents/guides/human-in-the-loop/) — Implement approval workflows +- [Pay from Agents SDK](/agents/tools/payments/x402/pay-from-agents-sdk/) — Use the Agents SDK for more control +- [Charge for HTTP content](/agents/tools/payments/x402/charge-for-http-content/) — Build the server side +- [Human-in-the-loop guide](/agents/concepts/agentic-patterns/human-in-the-loop/) — Implement approval workflows - [x402.org](https://x402.org) — Protocol specification diff --git a/src/content/docs/agents/tools/sandbox.mdx b/src/content/docs/agents/tools/sandbox.mdx new file mode 100644 index 00000000000..7bf1400be2b --- /dev/null +++ b/src/content/docs/agents/tools/sandbox.mdx @@ -0,0 +1,123 @@ +--- +title: Sandbox +pcx_content_type: concept +sidebar: + order: 1 +description: Give agents isolated Linux environments for running code, managing files, and executing commands. +--- + +import { LinkCard, TypeScriptExample, WranglerConfig } from "~/components"; + +Agents can use [Sandbox](/sandbox/) to run code in isolated container environments. Use Sandbox when an agent needs a real filesystem, shell commands, language runtimes, package installation, or long-lived project state that should not run inside the agent's own Worker isolate. + +Sandbox is built on [Cloudflare Containers](/containers/) and exposes a TypeScript API for command execution, file operations, background processes, and service previews. + +## When to use Sandbox + +Use Sandbox for agents that need to: + +- Run untrusted or model-generated code in isolation. +- Execute Python, Node.js, shell commands, or package managers. +- Read, write, and manage project files. +- Run tests, linters, build tools, or data analysis scripts. +- Maintain a workspace across multiple agent turns. + +## Basic pattern + +Bind the Sandbox Durable Object to your Worker, then access a sandbox from your agent methods with `getSandbox()`. + + + +```ts +import { Agent, callable } from "agents"; +import { getSandbox } from "@cloudflare/sandbox"; +import type { Sandbox } from "@cloudflare/sandbox"; + +export { Sandbox } from "@cloudflare/sandbox"; + +type Env = { + Sandbox: DurableObjectNamespace; +}; + +export class CodeAgent extends Agent { + @callable() + async runPython(code: string) { + const sandbox = getSandbox(this.env.Sandbox, this.name); + + await sandbox.writeFile("/workspace/script.py", code); + const result = await sandbox.exec("python3 /workspace/script.py"); + + this.setState({ lastOutput: result.stdout }); + + return { + success: result.success, + stdout: result.stdout, + stderr: result.stderr, + exitCode: result.exitCode, + }; + } +} +``` + + + +## Configuration + +Configure the Sandbox container, Durable Object binding, and migration in `wrangler.jsonc`. + + + +```jsonc +{ + "containers": [ + { + "class_name": "Sandbox", + "image": "./Dockerfile", + "instance_type": "lite", + "max_instances": 1 + } + ], + "durable_objects": { + "bindings": [ + { + "name": "Sandbox", + "class_name": "Sandbox" + } + ] + }, + "migrations": [ + { + "tag": "v1", + "new_sqlite_classes": ["Sandbox"] + } + ] +} +``` + + + +## Sandbox and agent state + +Use agent state for user-visible progress and small metadata. Use the sandbox filesystem for workspace files, generated code, package installs, logs, and artifacts. + +For long-running sandbox work, pair Sandbox with [durable execution with fibers](/agents/runtime/execution/durable-execution/) or [Workflows](/agents/runtime/execution/run-workflows/) so the agent can recover or report progress if work outlives a single request. + +## Related resources + + + + + + diff --git a/src/content/docs/ai-crawl-control/reference/worker-templates.mdx b/src/content/docs/ai-crawl-control/reference/worker-templates.mdx index d41282715df..b4ac5ce4aed 100644 --- a/src/content/docs/ai-crawl-control/reference/worker-templates.mdx +++ b/src/content/docs/ai-crawl-control/reference/worker-templates.mdx @@ -24,4 +24,4 @@ For setup instructions and Bot Management integration examples, see the [templat - [Cloudflare Workers](/workers/) — Build and deploy serverless applications - [Workers templates](https://github.com/cloudflare/templates) — More templates on GitHub - [Pay Per Crawl](/ai-crawl-control/features/pay-per-crawl/what-is-pay-per-crawl/) — Native Cloudflare integration for monetizing crawler access -- [x402 payments](/agents/agentic-payments/x402/) — Gate resources, charge for MCP tools, add payments to coding agents +- [x402 payments](/agents/tools/payments/x402/) — Gate resources, charge for MCP tools, add payments to coding agents diff --git a/src/content/docs/cloudflare-one/access-controls/ai-controls/mcp-portals.mdx b/src/content/docs/cloudflare-one/access-controls/ai-controls/mcp-portals.mdx index cfff5ab05a7..0e29f536987 100644 --- a/src/content/docs/cloudflare-one/access-controls/ai-controls/mcp-portals.mdx +++ b/src/content/docs/cloudflare-one/access-controls/ai-controls/mcp-portals.mdx @@ -23,7 +23,7 @@ This guide explains how to add MCP servers to Cloudflare Access, create an MCP p MCP server portals provide the following capabilities: -- **Streamlined access to multiple MCP servers**: MCP server portals support both unauthenticated MCP servers and MCP servers secured using OAuth (for example, via [Access for SaaS](/cloudflare-one/access-controls/ai-controls/secure-mcp-servers/) or a [third-party OAuth provider](/agents/model-context-protocol/authorization/)). Users log in to the portal URL through Cloudflare Access and are prompted to authenticate separately to each server that requires OAuth. +- **Streamlined access to multiple MCP servers**: MCP server portals support both unauthenticated MCP servers and MCP servers secured using OAuth (for example, via [Access for SaaS](/cloudflare-one/access-controls/ai-controls/secure-mcp-servers/) or a [third-party OAuth provider](/agents/model-context-protocol/protocol/authorization/)). Users log in to the portal URL through Cloudflare Access and are prompted to authenticate separately to each server that requires OAuth. - **Customized tools per portal**: Admins can tailor an MCP portal to a particular use case by choosing the specific tools and prompt templates that they want to make available to users through the portal. This allows users to access a curated set of tools and prompts — the less external context exposed to the AI model, the better the AI responses tend to be. @@ -271,7 +271,7 @@ To manually trigger a synchronization of tools and prompts from an upstream MCP ## Code mode -[Code mode](/agents/api-reference/codemode/) is turned on by default on all MCP server portals. It reduces context window usage by collapsing all tools in the portal into a single `code` tool. Instead of loading a separate tool definition for each upstream MCP server tool, the connected AI agent writes JavaScript that calls typed `codemode.*` methods. The generated code runs in an isolated [Dynamic Worker](/workers/runtime-apis/bindings/worker-loader/) environment, which keeps authentication credentials and environment variables out of the model context. +[Code mode](/agents/model-context-protocol/protocol/codemode/) is turned on by default on all MCP server portals. It reduces context window usage by collapsing all tools in the portal into a single `code` tool. Instead of loading a separate tool definition for each upstream MCP server tool, the connected AI agent writes JavaScript that calls typed `codemode.*` methods. The generated code runs in an isolated [Dynamic Worker](/workers/runtime-apis/bindings/worker-loader/) environment, which keeps authentication credentials and environment variables out of the model context. To use code mode, the MCP client must request it when connecting to the portal URL. Refer to [Connect with code mode](#connect-with-code-mode) for the required query parameter. @@ -306,7 +306,7 @@ For MCP clients with server configuration files, use the portal URL with the que When code mode is active, the portal advertises a single `code` tool to connected MCP clients. The AI agent discovers available tools by inspecting the typed method signatures in the Dynamic Worker environment and composes multiple tool calls into a single code execution. -For more information on building with code mode, refer to the [code mode SDK reference](/agents/api-reference/codemode/). +For more information on building with code mode, refer to the [code mode SDK reference](/agents/model-context-protocol/protocol/codemode/). ### Turn off code mode @@ -375,7 +375,7 @@ DLP [AI prompt profiles](/cloudflare-one/data-loss-prevention/dlp-profiles/prede ## Connect to a portal -Users can connect to your MCP server running at `https://./mcp` using [Workers AI Playground](https://playground.ai.cloudflare.com/), [MCP inspector](https://github.com/modelcontextprotocol/inspector), or [other MCP clients](/agents/guides/remote-mcp-server/#connect-your-mcp-server-to-claude-and-other-mcp-clients) that support remote MCP servers. +Users can connect to your MCP server running at `https://./mcp` using [Workers AI Playground](https://playground.ai.cloudflare.com/), [MCP inspector](https://github.com/modelcontextprotocol/inspector), or [other MCP clients](/agents/model-context-protocol/guides/remote-mcp-server/#connect-your-mcp-server-to-claude-and-other-mcp-clients) that support remote MCP servers. To test in Workers AI Playground: @@ -515,7 +515,7 @@ For MCP clients with server configuration files: } ``` -For more information on the code mode pattern behind `search_and_execute`, refer to the [Code mode SDK reference](/agents/api-reference/codemode/). +For more information on the code mode pattern behind `search_and_execute`, refer to the [Code mode SDK reference](/agents/model-context-protocol/protocol/codemode/). ## Manage portal sessions diff --git a/src/content/docs/cloudflare-one/access-controls/ai-controls/secure-mcp-servers.mdx b/src/content/docs/cloudflare-one/access-controls/ai-controls/secure-mcp-servers.mdx index 78ed2086ddb..84df1ad2f94 100644 --- a/src/content/docs/cloudflare-one/access-controls/ai-controls/secure-mcp-servers.mdx +++ b/src/content/docs/cloudflare-one/access-controls/ai-controls/secure-mcp-servers.mdx @@ -182,7 +182,7 @@ To configure the environment variables for our [example MCP server](#1-deploy-an ### 4. Test the connection -You can now connect to your MCP server at `https://mcp-access-self-hosted..workers.dev/mcp` using [Workers AI Playground](https://playground.ai.cloudflare.com/), [MCP inspector](https://github.com/modelcontextprotocol/inspector), or [other MCP clients](/agents/guides/remote-mcp-server/#connect-your-mcp-server-to-claude-and-other-mcp-clients) that support remote MCP servers. +You can now connect to your MCP server at `https://mcp-access-self-hosted..workers.dev/mcp` using [Workers AI Playground](https://playground.ai.cloudflare.com/), [MCP inspector](https://github.com/modelcontextprotocol/inspector), or [other MCP clients](/agents/model-context-protocol/guides/remote-mcp-server/#connect-your-mcp-server-to-claude-and-other-mcp-clients) that support remote MCP servers. To test in Workers AI Playground: @@ -447,7 +447,7 @@ To add OAuth endpoints and credentials to our [example MCP server](#1-deploy-an- ### 4. Test the connection -You can now connect to your MCP server at `https://mcp-server-cf-access..workers.dev/mcp` using [Workers AI Playground](https://playground.ai.cloudflare.com/), [MCP inspector](https://github.com/modelcontextprotocol/inspector), or [other MCP clients](/agents/guides/remote-mcp-server/#connect-your-mcp-server-to-claude-and-other-mcp-clients) that support remote MCP servers. +You can now connect to your MCP server at `https://mcp-server-cf-access..workers.dev/mcp` using [Workers AI Playground](https://playground.ai.cloudflare.com/), [MCP inspector](https://github.com/modelcontextprotocol/inspector), or [other MCP clients](/agents/model-context-protocol/guides/remote-mcp-server/#connect-your-mcp-server-to-claude-and-other-mcp-clients) that support remote MCP servers. To test in Workers AI Playground: diff --git a/src/content/docs/docs-for-agents/index.mdx b/src/content/docs/docs-for-agents/index.mdx index 3106d83cee6..26828b6eca6 100644 --- a/src/content/docs/docs-for-agents/index.mdx +++ b/src/content/docs/docs-for-agents/index.mdx @@ -50,10 +50,10 @@ Cloudflare runs managed remote MCP servers that give your agent the ability to s There are two approaches: -- **[Code Mode](/agents/api-reference/codemode/)**: A single MCP server that covers the entire Cloudflare API (over 2,500 endpoints). Use this when your agent needs broad access across multiple Cloudflare products. +- **[Code Mode](/agents/model-context-protocol/protocol/codemode/)**: A single MCP server that covers the entire Cloudflare API (over 2,500 endpoints). Use this when your agent needs broad access across multiple Cloudflare products. - **Domain-specific servers**: Focused servers for documentation, observability, DNS analytics, and more. Use these when your agent only needs access to a specific area. The full catalog is in the [cloudflare/mcp-server-cloudflare](https://github.com/cloudflare/mcp-server-cloudflare) repository. -Each agent's [Agent setup](#set-up-your-agent) guide includes MCP server installation as part of its Quick start. For the full list of available MCP servers, refer to [MCP servers for Cloudflare](/agents/model-context-protocol/mcp-servers-for-cloudflare/). +Each agent's [Agent setup](#set-up-your-agent) guide includes MCP server installation as part of its Quick start. For the full list of available MCP servers, refer to [MCP servers for Cloudflare](/agents/model-context-protocol/cloudflare/servers-for-cloudflare/). ### Model flexibility diff --git a/src/content/docs/dynamic-workers/getting-started.mdx b/src/content/docs/dynamic-workers/getting-started.mdx index 54c62eab74a..e95dcaa3037 100644 --- a/src/content/docs/dynamic-workers/getting-started.mdx +++ b/src/content/docs/dynamic-workers/getting-started.mdx @@ -17,7 +17,7 @@ Dynamic Workers support two loading modes: - `load(code)` creates a fresh Dynamic Worker for one-time execution. - `get(id, callback)` caches a Dynamic Worker by ID so it can stay warm across requests. -`load()` is best for one-time code execution, for example when using [Codemode](/agents/api-reference/codemode/). `get(id, callback)` is better when the same code will receive subsequent requests, for example when you are building applications. +`load()` is best for one-time code execution, for example when using [Codemode](/agents/model-context-protocol/protocol/codemode/). `get(id, callback)` is better when the same code will receive subsequent requests, for example when you are building applications. ### Try it out diff --git a/src/content/docs/agents/guides/chatgpt-app.mdx b/src/content/docs/workers/demos/chatgpt-app.mdx similarity index 99% rename from src/content/docs/agents/guides/chatgpt-app.mdx rename to src/content/docs/workers/demos/chatgpt-app.mdx index ae4cba2198c..03b82e29cfa 100644 --- a/src/content/docs/agents/guides/chatgpt-app.mdx +++ b/src/content/docs/workers/demos/chatgpt-app.mdx @@ -870,7 +870,7 @@ Now that you have a working ChatGPT App, you can: diff --git a/src/content/docs/workers/get-started/prompting.mdx b/src/content/docs/workers/get-started/prompting.mdx index 2fee9ae23ce..cb2ec179040 100644 --- a/src/content/docs/workers/get-started/prompting.mdx +++ b/src/content/docs/workers/get-started/prompting.mdx @@ -18,7 +18,7 @@ You can create Workers applications from simple prompts in your favorite agent o ## Teach your agent about Workers -Connect the [`cloudflare-docs`](https://github.com/cloudflare/mcp-server-cloudflare/tree/main/apps/docs-vectorize) MCP (Model Context Protocol) server to teach your agent about Workers. Add the server URL `https://docs.mcp.cloudflare.com/mcp` to your agent configuration ([learn more](/agents/model-context-protocol/mcp-servers-for-cloudflare/)). +Connect the [`cloudflare-docs`](https://github.com/cloudflare/mcp-server-cloudflare/tree/main/apps/docs-vectorize) MCP (Model Context Protocol) server to teach your agent about Workers. Add the server URL `https://docs.mcp.cloudflare.com/mcp` to your agent configuration ([learn more](/agents/model-context-protocol/cloudflare/servers-for-cloudflare/)). You can also connect the [`cloudflare-observability`](https://github.com/cloudflare/mcp-server-cloudflare/tree/main/apps/workers-observability) MCP server (`https://observability.mcp.cloudflare.com/mcp`). This helps your agent check logs, look for exceptions, and automatically fix issues. diff --git a/src/content/docs/workers/runtime-apis/bindings/worker-loader.mdx b/src/content/docs/workers/runtime-apis/bindings/worker-loader.mdx index 3c6b8609de2..854c82a84b7 100644 --- a/src/content/docs/workers/runtime-apis/bindings/worker-loader.mdx +++ b/src/content/docs/workers/runtime-apis/bindings/worker-loader.mdx @@ -30,7 +30,7 @@ With proper sandboxing configured, you can safely run code you do not trust in a ## Codemode -A primary use case for Dynamic Worker Loaders is [Codemode](/agents/api-reference/codemode/) in the [Agents SDK](/agents/). Codemode converts your tools into typed TypeScript APIs and gives the LLM a single "write code" tool. The generated code runs in an isolated Worker sandbox, which lets AI agents chain multiple tool calls in one execution and reduces round-trips through the model. +A primary use case for Dynamic Worker Loaders is [Codemode](/agents/model-context-protocol/protocol/codemode/) in the [Agents SDK](/agents/). Codemode converts your tools into typed TypeScript APIs and gives the LLM a single "write code" tool. The generated code runs in an isolated Worker sandbox, which lets AI agents chain multiple tool calls in one execution and reduces round-trips through the model. Codemode works with both standard AI SDK tools and [MCP](/agents/model-context-protocol/) tools. diff --git a/src/content/docs/workflows/get-started/durable-agents.mdx b/src/content/docs/workflows/get-started/durable-agents.mdx index ea281439b38..5a8e95ecaa7 100644 --- a/src/content/docs/workflows/get-started/durable-agents.mdx +++ b/src/content/docs/workflows/get-started/durable-agents.mdx @@ -649,7 +649,7 @@ Agent class names are automatically converted to kebab-case for URLs (`ResearchA