Merged
Conversation
Added docs/docs-to-upstream.md to track documentation ready for upstreaming to Cloudflare. Renamed context-management.md to get-current-agent.md for clarity. Expanded docs/index.md with a detailed, categorized documentation table of contents and TODOs for missing sections.
Introduces `scheduleEvery()` for fixed-interval recurring tasks, updates the Schedule type and database schema, and ensures overlap prevention and error resilience for interval jobs. Updates documentation, playground, and tests to cover interval scheduling, and improves schedule management and filtering for all schedule types.
Introduces a new options object overload for addMcpServer(), allowing cleaner configuration without positional undefineds. Updates all usages, documentation, and adds comprehensive tests for both new and legacy signatures. Also updates MCP client documentation and improves test agent utilities.
Introduces comprehensive documentation for getting started and state management, including new files `getting-started.md` and `state.md`. Updates the docs index and upstream tracking to reference these guides. Adds `TestStateAgent` and `TestStateAgentNoInitial` with corresponding tests in `state.test.ts` to validate agent state persistence, synchronization, and edge cases. Updates test worker and wrangler config to register new test agents.
Added a comprehensive guide (adding-to-existing-project.md) for integrating agents into existing Cloudflare Workers projects, including setup for React, Hono, static assets, and common patterns. Updated docs-to-upstream.md and index.md to reference the new guide.
Introduces support for custom URL routing via `basePath`, allowing clients to connect to arbitrary paths and enabling server-side instance selection with `getAgentByName`. Agents now send their identity (name and agent type) to clients on connect, with new `onIdentity` and `onIdentityChange` callbacks, and expose `identified` and `ready` state. Updates documentation, React and client APIs, and adds comprehensive tests for routing and identity features.
Introduced a comprehensive 'http-websockets.md' guide covering agent HTTP and WebSocket lifecycle, patterns, and API reference. Updated docs-to-upstream.md and index.md to reference the new documentation. Fixed a type for useRef in useAgent hook in react.tsx to allow undefined.
Adds support for client-side RPC timeouts, a new StreamingResponse.error() method for graceful streaming errors, and a getCallableMethods() API for introspection. Improves internal metadata storage with WeakMap, uses crypto.randomUUID() for RPC IDs, and adds observability for streaming calls. Updates agent.call() to accept a unified CallOptions object, documents the callable system, and introduces comprehensive tests for callable and streaming behaviors.
AgentClient.call() now accepts both the legacy streaming options format ({ onChunk, onDone, onError }) and the new CallOptions format ({ stream: { ... }, timeout }). The client auto-detects which format is used for backward compatibility. Documentation and tests have been updated to clarify and demonstrate both formats.
🦋 Changeset detectedLatest commit: 29b9fdd The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
commit: |
This comment was marked as resolved.
This comment was marked as resolved.
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Jan 30, 2026
This commit syncs documentation changes from PR 812 which includes: ## New Features Documented ### Scheduling - scheduleEvery() method for fixed-interval recurring tasks - Overlap prevention and error resilience - Comparison between cron and interval scheduling ### MCP Client - Options-based addMcpServer() API (cleaner alternative to positional params) - Transport options configuration - Backward compatibility maintained ### Callable Methods (NEW PAGE) - @callable decorator for WebSocket RPC - Streaming with StreamingResponse.error() method - Client-side RPC timeout support - Method introspection with getCallableMethods() - Options-based streaming API ### Custom Routing (NEW PAGE) - basePath for custom URL routing - Server-sent identity with onIdentity callbacks - Identity change handling on reconnect - Security controls with sendIdentityOnConnect - Instance naming patterns ### State Management - Enhanced onStateUpdate with source parameter - Bidirectional state updates - Vanilla JS AgentClient examples - Best practices for avoiding loops ### WebSockets - Connection management (getConnections, getConnection) - Connection tags and filtering - Per-connection state - Hibernation behavior documentation - Broadcasting patterns ## New Documentation Pages - api-reference/callable-methods.mdx - Complete @callable decorator reference - concepts/routing.mdx - Custom routing and identity management - getting-started/quickstart.mdx - Comprehensive quickstart guide - guides/add-to-existing-project.mdx - Integration with existing Workers ## Updated Pages - api-reference/schedule-tasks.mdx - api-reference/store-and-sync-state.mdx - api-reference/websockets.mdx - model-context-protocol/mcp-client-api.mdx All documentation follows cloudflare-docs style guidelines with proper component usage (TypeScriptExample, WranglerConfig, PackageManagers), full relative links with trailing slashes, and no contractions. Related PR: cloudflare/agents#812 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This patch addresses three issues: (1) interval schedules now detect and recover from hung callbacks by force-resetting after 30 seconds, (2) agents gracefully recover from corrupted state JSON by falling back to initialState, and (3) getCallableMethods() now traverses the prototype chain to find @callable methods in parent classes. Corresponding tests and test helpers have been added to ensure correct behavior.
Moved the camelCaseToKebabCase function to a new client-utils.ts file for reuse across modules. Updated client.ts to re-export the function for backward compatibility and updated react.tsx to import it from the new utility module.
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Jan 30, 2026
Sync documentation from cloudflare/agents PR #812. This update adds extensive documentation covering: - Core concepts: scheduling, routing, state, callable methods, HTTP/WebSockets - Client SDK: React hooks and vanilla JavaScript integration - API reference: getCurrentAgent() context management - Getting started: quickstart guide for building agents - How-to guides: adding agents to existing projects New features documented: - scheduleEvery() for fixed-interval recurring tasks - basePath routing for custom URL patterns - Server-sent identity with onIdentity callbacks - Callable improvements: timeouts, streaming, introspection - MCP client options-based API All documentation follows Cloudflare style guidelines with proper component usage (WranglerConfig, TypeScriptExample, PackageManagers). Source PR: cloudflare/agents#812
threepointone
commented
Jan 30, 2026
threepointone
commented
Jan 30, 2026
| New method on the Agent class to introspect all callable methods and their metadata: | ||
|
|
||
| ```typescript | ||
| const methods = agent.getCallableMethods(); |
threepointone
commented
Jan 30, 2026
|
|
||
| ```typescript | ||
| // Clean options object | ||
| await this.addMcpServer("server", url, { |
Contributor
There was a problem hiding this comment.
i am actually a fan of this, i like it, it's clean
threepointone
commented
Jan 30, 2026
|
|
||
| ## Custom URL Routing with `basePath` | ||
|
|
||
| New `basePath` option bypasses default `/agents/{agent}/{name}` URL construction, enabling custom routing patterns: |
threepointone
commented
Jan 30, 2026
Reset the client's ready/identified state when the connection closes and ensure pending calls are rejected. AgentClient.ready is now a getter backed by an internal _readyPromise and a _resetReady() helper; the promise is initialized in the constructor and reset on socket close (identified is also set to false). useAgent was updated to initialize/reset its readyRef and to reset identity/ready on onClose, invoking the user's onClose if provided. Added connection lifecycle tests to verify identity messages on initial connection and reconnection and to document the expected ready behavior across reconnects.
When the agent connection closes, reject and clear all pending calls and surface stream errors to match AgentClient behavior (packages/agents/src/react.tsx). Generate call IDs with crypto.randomUUID() instead of Math.random for more robust unique identifiers. Also add documentation explaining how to retry calls after reconnection, advising awaiting agent.ready and retrying only idempotent operations (docs/callable-methods.md).
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Jan 30, 2026
Add comprehensive documentation for Agents SDK features: - Add routing guide covering URL patterns, instance naming, and custom routing with basePath - Add callable methods guide for RPC over WebSocket with @callable decorator - Add client SDK reference for React and vanilla JS (useAgent, AgentClient, agentFetch) - Add integration guide for adding agents to existing Workers projects - Add HTTP/WebSockets guide covering lifecycle hooks, connection management, and hibernation All documentation follows Cloudflare style guide: - TypeScriptExample, WranglerConfig, and PackageManagers components - Relative links with trailing slashes - No contractions or exclamation marks - Proper frontmatter with pcx_content_type and sidebar order Source: cloudflare/agents#812
Introduce a comprehensive human-in-the-loop guide (docs/human-in-the-loop.md) covering approval patterns, workflows, AI chat/tool confirmation, OpenAI/Vercel SDK patterns, MCP elicitation, state/UI patterns, timeouts, escalation, and audit guidance. Update docs/index.md to link to the new guide. Fix useAgent hook (packages/agents/src/react.tsx) to accept a CloseEvent in the onClose handler and pass that event through to the user-provided callback while performing connection cleanup (reset ready state, clear pending calls, and update identity).
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Jan 30, 2026
Add documentation for new features from PR 812: - scheduleEvery() method for fixed-interval scheduling - basePath option for custom URL routing - Server-sent identity with onIdentity and onIdentityChange callbacks - RPC call timeout support - StreamingResponse.error() method for graceful error handling - getCallableMethods() introspection API - Options-based addMcpServer() API Updated files: - api-reference/schedule-tasks.mdx: Added scheduleEvery() docs - api-reference/calling-agents.mdx: Added custom routing with basePath and server-sent identity - api-reference/websockets.mdx: Added callable methods RPC documentation - model-context-protocol/mcp-client-api.mdx: Added options-based API signature Related to cloudflare/agents#812 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Complete overhaul of packages/agents/README.md to reorganize and modernize documentation. Replaces verbose marketing prose with a concise, structured guide: Quick Example, Client SDK (React & vanilla), Callable methods, Scheduling, Background tasks, WebSocket and Email handling, AI Chat integration, MCP integration, configuration, and Coming Soon features. Updated and expanded code samples, durable object usage, MCP examples, and routing/config snippets; clarified Contributing and License sections. Aims to make onboarding and common usage patterns clearer for developers.
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Jan 30, 2026
This commit syncs documentation updates for new features and enhancements from cloudflare/agents PR #812 (DO NOT LAND: docs/tests/enhancements). ## Changes included: ### Scheduling enhancements - Added documentation for scheduleEvery() method for fixed-interval scheduling - Updated schedule-tasks.mdx with overlap prevention and error resilience details - Added scheduleEvery examples and usage patterns ### Routing and identity features - Added custom URL routing with basePath option - Documented server-sent identity system - Added onIdentity and onIdentityChange callbacks - Documented identity state tracking (identified, ready promise) - Added path option for sub-paths - Included sendIdentityOnConnect agent option ### Callable system improvements - Documented client-side RPC timeout option - Added StreamingResponse.error() method documentation - Documented getCallableMethods() introspection API - Added connection close handling details ### MCP client enhancements - Added options-based API for addMcpServer (recommended approach) - Updated examples to show cleaner options object usage - Maintained legacy positional API documentation for backward compatibility All changes maintain backward compatibility and follow Cloudflare docs style guide. Source PR: cloudflare/agents#812 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Add a Workflows Integration section to packages/agents/README.md that shows how to integrate Cloudflare Workflows with AgentWorkflow for durable, multi-step tasks. Includes a TypeScript example demonstrating step retries, human approval via waitForApproval(), progress reporting, and a short features list (durable execution, human-in-the-loop, long-running tasks, progress tracking). Links to additional docs (workflows and human-in-the-loop) are included for further reference.
Change import paths for AgentWorkflow, AgentWorkflowEvent, AgentWorkflowStep and WorkflowInfo from "agents" to "agents/workflows" in demo files (approval-agent.ts, approval-workflow.ts, processing-workflow.ts) to match the package reorganization.
Move email-specific exports into the agents/email module and update import sites accordingly. receive-email-agent.ts and secure-email-agent.ts now import AgentEmail, parseEmailHeaders, and isAutoReplyEmail from agents/email (while keeping Agent and callable from agents). server.ts now imports routeAgentRequest and routeAgentEmail from agents and pulls createAddressBasedEmailResolver and createSecureReplyEmailResolver from agents/email. This refactors email helpers/types into a dedicated module for clearer organization.
threepointone
commented
Feb 2, 2026
threepointone
commented
Feb 2, 2026
Change Agent state handling to make setState() synchronous (returns void) and introduce a new synchronous beforeStateChange(nextState, source) hook that gates persistence/broadcast by throwing. onStateUpdate() is now invoked asynchronously via ctx.waitUntil after the state is persisted and broadcast; errors from onStateUpdate are routed to onError() and do not prevent the state from being saved or broadcast. Changes include: updated packages/agents/src/index.ts (sync _setStateInternal, persistence order, waitUntil for onStateUpdate, new beforeStateChange API, setState signature), docs/docs/state.md and a .changeset describing the breaking change, and test updates to account for the new ordering (polling for onStateUpdate, adjusted message collection counts) plus a new test verifying broadcasts still occur when onStateUpdate throws. Test agent behavior was updated (beforeStateChange validation, onError recording, updateState no longer returns a promise).
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Feb 3, 2026
This PR syncs comprehensive documentation updates from cloudflare/agents PR #812, including new features, API enhancements, and usage guides. ## New Documentation Files ### API Reference - routing.mdx: Complete routing documentation with routeAgentRequest(), bypassRouting, appendPath, server-sent identity, custom URL routing, and instance naming patterns - callable-methods.mdx: @callable decorator, RPC, streaming responses, client-side timeout, stream error signaling, and method introspection API - email.mdx: Email routing with routeAgentEmail(), resolvers (address-based, secure reply, catch-all), and signature verification - webhooks.mdx: Webhook handling with routing patterns, HMAC verification, event deduplication, and real-time broadcasting - get-current-agent.mdx: Context management with getCurrentAgent() for AI SDK tools and external functions ### Getting Started - adding-to-existing-project.mdx: Step-by-step guide for integrating agents into existing Workers, Hono apps, and React applications ## Updated Documentation - schedule-tasks.mdx: Added scheduleEvery() method for fixed-interval recurring tasks with sub-minute precision, AI-assisted scheduling with getSchedulePrompt() - mcp-client-api.mdx: Added options-based addMcpServer() API with custom headers and transport configuration ## Features Documented From cloudflare/agents PR #812: - scheduleEvery(): Fixed-interval recurring tasks with overlap prevention - Routing enhancements: bypassRouting, appendPath, server-sent identity - Callable improvements: RPC timeout, stream error signaling, method introspection - MCP options API: New options-based addMcpServer() overload All documentation follows Cloudflare Style Guide with proper components (WranglerConfig, TypeScriptExample, PackageManagers), frontmatter, and relative links. Source: cloudflare/agents#812
Rename the synchronous validation hook from beforeStateChange to validateStateChange across the codebase and docs, and update Agent to call the new hook. Documentation and examples were updated to show the new validateStateChange signature and usage (including a short example). Simplify email auto-reply detection by removing subject-based heuristics: isAutoReplyEmail now accepts only headers and detects auto-replies using standard headers (Auto-Submitted / RFC 3834, X-Auto-Response-Suppress, Precedence). Update docs, examples, and tests to reflect the new signature and behavior.
Remove several email header parsing utilities (parseEmailHeaders, getEmailHeader, hasEmailHeader, hasAnyEmailHeader, getAllEmailHeaders) and simplify the API to only expose isAutoReplyEmail. Update docs and example code to detect auto-replies via isAutoReplyEmail and to convert postal-mime headers inline (Object.fromEntries). Rename client-utils.ts to utils.ts and update imports (client, index, react) to use ./utils and re-export camelCaseToKebabCase from there. Tests were narrowed to only cover isAutoReplyEmail accordingly. Update the changeset message and examples to reflect the reduced surface area.
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Feb 3, 2026
This sync adds comprehensive documentation for new features and enhancements introduced in cloudflare/agents PR 812. New guides added: - Email routing with secure reply signatures - Scheduling with new scheduleEvery() method for fixed intervals - Workflows integration with tracking and pagination - Callable methods with RPC, streaming, timeouts, and introspection - Routing with custom paths and server-sent identity API reference updates: - schedule-tasks.mdx: Added scheduleEvery() documentation - mcp-client-api.mdx: Documented new options-based addMcpServer() API Key features documented: - scheduleEvery() for fixed-interval recurring tasks with overlap prevention - Email resolvers (address-based, secure reply, catch-all) - Workflow tracking with pagination and control methods - Callable method timeouts and getCallableMethods() introspection - Custom routing with basePath and path options - Server-sent identity with onIdentity callbacks - MCP client options-based API (cleaner than positional params) All documentation follows Cloudflare style guide: - Uses TypeScriptExample, WranglerConfig, and other components - Full relative links with trailing slashes - No contractions or non-standard formatting - Proper frontmatter and sidebar ordering Source: cloudflare/agents#812
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Feb 3, 2026
This sync adds documentation for new features from cloudflare/agents#812: - Routing: Custom URL routing with basePath, identity management, server-sent identity, and advanced routing patterns - Callable methods: RPC over WebSocket, streaming responses, error handling, timeout support, and introspection API - Interval scheduling: New scheduleEvery() method for fixed-interval recurring tasks with overlap prevention Key features documented: - basePath option for custom routing URLs - onIdentity and onIdentityChange callbacks - sendIdentityOnConnect agent option - Callable method improvements (timeout, getCallableMethods) - scheduleEvery() for sub-minute polling - Overlap prevention for interval tasks Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Replace the legacy static `agentOptions` with `options` across the codebase and docs. Updates include: - Docs: update examples and the routing documentation to reference `Agent.options` and expand the options table (hibernate, sendIdentityOnConnect, hungScheduleTimeoutSeconds). - Code: introduce `AgentStaticOptions` and `ResolvedAgentOptions`, set `static options` default (hibernate: true), update the resolved options getter to read from `ctor.options`, and add a ts-expect-error to allow subclasses to omit `hibernate` while defaulting it at runtime. - Tests: update test agent to use `static options`. These changes unify server/static configuration naming, make `hibernate` optional for subclasses while keeping a runtime default, and keep the behavior for sending identity unchanged.
Replace the explicit AgentStaticOptions declaration with Partial<ResolvedAgentOptions> so subclasses can omit fields and rely on runtime defaults. Update the doc comment to state that all fields are optional. Simplify the static options assignment by removing the type assertion and keeping the default { hibernate: true }.
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Feb 3, 2026
This commit syncs documentation updates from cloudflare/agents PR 812, which includes comprehensive docs for new features and enhancements. - Added documentation for new `scheduleEvery()` method for fixed-interval scheduling - Added comprehensive "Scheduling modes" section covering all four scheduling types: - Delayed execution (seconds-based) - Scheduled execution (Date-based) - Recurring (cron expressions) - Fixed intervals (new scheduleEvery feature) - Documented interval-specific features: overlap prevention and error resilience - Updated Schedule type to include "interval" type - Added use cases and examples for each scheduling mode - Added documentation for `validateStateChange()` hook - Documented synchronous state validation before persistence - Explained execution order: validateStateChange → persist → broadcast → onStateUpdate - Added comparison table between validateStateChange() and onStateUpdate() - Included migration note for older SDK versions - Provided examples of validation use cases (score validation, player limits, etc.) - Updated `addMcpServer()` signature to show preferred options-based API - Deprecated legacy positional parameters (callbackHost, agentsPrefix) - Moved callback configuration into options object for cleaner API - Added examples showing both basic and advanced usage with custom options - Documented transport options and custom headers support Source: cloudflare/agents#812 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Add server-side logging for errors thrown in streaming RPC handlers to improve observability (logs the method name and error). Enforce a maximum schedule interval for DO alarms by introducing MAX_INTERVAL_SECONDS (30 days = 30*24*60*60) and throwing if intervalSeconds exceeds this limit. Also tidy up comments in packages/agents/src/tests/state.test.ts (renumbered and removed/condensed several TODO items). These changes help with debugging and prevent excessively long alarm schedules.
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Feb 3, 2026
This PR syncs documentation changes from the agents repository PR #812 which adds comprehensive documentation and feature improvements. ## New Documentation - **whats-new.mdx**: Summary of recent updates including scheduleEvery(), routing enhancements, callable improvements, and MCP updates - **concepts/routing.mdx**: Comprehensive guide to agent routing patterns, custom URL routing with basePath, server-sent identity, and sub-paths ## Updated Documentation - **api-reference/schedule-tasks.mdx**: Added scheduleEvery() method documentation for fixed-interval recurring tasks with overlap prevention - **api-reference/websockets.mdx**: Added callable methods documentation including timeouts, streaming, and introspection ## Key Features Documented ### Scheduling - scheduleEvery() for sub-minute precision intervals - Overlap prevention and error resilience - Support for arbitrary intervals (not constrained to cron patterns) ### Routing - basePath option for custom URL paths - Server-sent identity on connection - onIdentity and onIdentityChange callbacks - path option for sub-paths - sendIdentityOnConnect agent option for security ### Callable Methods - Client-side RPC timeout support - Streaming error handling with stream.error() - getCallableMethods() introspection API - Connection close handling ### MCP Client - Options-based addMcpServer() API - Backward compatibility with legacy signature Related PR: cloudflare/agents#812 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Docs: import and document the @callable decorator, mark Counter methods as callable, add a troubleshooting section for "Method X is not callable", clarify that agent.stub.methodName() calls @callable() methods, and fix the example useAgent generic order. Also switch routeAgentRequest to nullish coalescing (??) to preserve defined falsy responses. Code: add a console.warn in StreamingResponse.send when called after the stream is closed to aid debugging and avoid silently dropping data.
Await routeAgentRequest in the request handler so the promise is resolved before deciding to fall back to the 404 response, and switch to nullish coalescing (??) so only null/undefined triggers the fallback (not other falsy values). Also remove a duplicated JSDoc block in packages/agents/src/index.ts to tidy up the source.
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Feb 3, 2026
This sync includes comprehensive documentation for the Agents SDK covering: - **Quick Start Guide** (getting-started/quick-start.mdx) - Installation, first agent, state basics, and deployment - **Routing** (concepts/routing.mdx) - URL patterns, name resolution, custom routing, and server-sent identity - **Callable Methods** (api-reference/callable-methods.mdx) - @callable decorator, RPC over WebSocket, and streaming responses - **Queue System** (api-reference/queue-system.mdx) - Background task queue with queue(), dequeue(), and related APIs - **Add to Existing Project** (guides/add-to-existing-project.mdx) - Integration guide for adding agents to existing Workers - **Email Routing** (guides/email-routing.mdx) - Email routing with routeAgentEmail(), resolvers, and secure reply handling - **Observability** (platform/observability.mdx) - Tracing and monitoring agent activity All documentation follows Cloudflare docs style guidelines: - MDX format with proper frontmatter - TypeScriptExample, WranglerConfig, and PackageManagers components - No contractions, professional tone - Absolute paths for internal links with trailing slashes Source: cloudflare/agents PR 812 cloudflare/agents#812 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Feb 3, 2026
Syncs documentation for new features from cloudflare/agents PR #812: - validateStateChange() hook for state validation - Synchronous setState() (backward compatible) - scheduleEvery() method for fixed-interval tasks Also includes: - Comprehensive sync plan (SYNC_PLAN_PR_812.md) - Summary of changes made (CHANGES_MADE.md) Updated files: - src/content/docs/agents/api-reference/store-and-sync-state.mdx - src/content/docs/agents/api-reference/schedule-tasks.mdx Remaining features documented in sync plan for follow-up: - Callable improvements (timeouts, introspection) - Custom routing (basePath, identity) - MCP options API enhancements - Email utilities Source: cloudflare/agents#812 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Adjust agents package README examples to match updated APIs and usage patterns:
- Replace direct useAgent state destructuring with React useState and onStateUpdate callbacks in examples so components receive state via setState.
- Add missing useState imports in examples.
- Change Agent.onStateUpdate type to accept Connection | "server" instead of just "server" | "client".
- Update addMcpServer example to new signature (name, url, options) and use transport as an object ({ type: "streamable-http" }).
- Await routeAgentRequest in the fetch handler.
These edits keep the docs aligned with recent runtime/SDK changes and show recommended patterns for handling agent state in React components.
Refine isAutoReplyEmail to inspect header values (case-insensitive) instead of just header presence. Implements RFC 3834 handling: Auto-Submitted is treated as auto-reply unless its value is "no"; X-Auto-Response-Suppress always indicates suppression; Precedence is considered automated only for "bulk", "junk", or "list". Added tests covering Auto-Submitted values (auto-replied, auto-generated, no) and Precedence variants (bulk, junk, list, normal) to prevent false positives.
If there's no initialState, remove potentially corrupted cf_agents_state rows (STATE_ROW_ID and STATE_WAS_CHANGED) to avoid infinite retry loops. Also route errors from scheduled callback execution through this.onError and swallow any errors thrown by onError to prevent cascading failures.
This comment was marked as resolved.
This comment was marked as resolved.
agents-git-bot bot
pushed a commit
to cloudflare/cloudflare-docs
that referenced
this pull request
Feb 3, 2026
Updates documentation to reflect changes from cloudflare/agents PR #812: ## State Management - Document synchronous setState() (no longer returns Promise) - Add validateStateChange() hook for synchronous validation - Clarify onStateUpdate() is non-gating (runs via queueMicrotask) - Document state update execution order ## Callable Methods - Add @callable decorator documentation - Document client-side RPC timeout option - Add stream.error() method for graceful error handling - Document getCallableMethods() introspection API - Document connection close handling for pending calls - Enhance streaming documentation with new options format ## Scheduling - Add scheduleEvery() method for fixed-interval recurring tasks - Document overlap prevention and error resilience - Compare interval vs cron scheduling approaches - Add comprehensive API reference ## MCP Client - Document new options-based addMcpServer() API - Show cleaner syntax avoiding positional undefined parameters - Note legacy signature still supported for backward compatibility Related PR: cloudflare/agents#812
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR adds comprehensive documentation for the Agents SDK and implements several feature improvements across state management, MCP, routing, scheduling, and the callable RPC system.
Highlights:
setState(),validateStateChange()hook,scheduleEvery(),basePathrouting, server-sent identity, callable improvementsDocumentation Added
Documentation Index
docs/index.mdGetting Started & Integration
docs/getting-started.mddocs/adding-to-existing-project.mdCore Concepts
docs/state.mdinitialState,setState(),validateStateChange(),onStateUpdate(), persistence, and client synchronizationdocs/routing.mdrouteAgentRequest(), custom paths withbasePath, server-sent identity, and advanced routing scenariosdocs/http-websockets.mdonRequest,onConnect,onMessage,onClose), connection management, per-connection state, hibernation, and common patternsFeatures
docs/callable-methods.md@callabledecorator, RPC over WebSocket, streaming responses, TypeScript integration, error handling, and when to use DO RPC insteaddocs/mcp-client.mdaddMcpServer(), OAuth flows, transport options, and tool usagedocs/scheduling.mdscheduleEvery), and cron-based schedulingNew Features
State Management
Synchronous
setState()-setState()is now synchronous, returningvoidinstead ofPromise<void>. Existing code usingawait this.setState(...)continues to work.validateStateChange()hook - New synchronous validation hook that runs before state is persisted and broadcast. Throw to reject updates:onStateUpdate()is now non-gating - Runs viactx.waitUntil()after persistence and broadcast. Errors are routed toonError()but don't prevent state updates.Execution order:
validateStateChange(nextState, source)- validation (sync, gating)onStateUpdate(nextState, source)- notifications (async viactx.waitUntil, non-gating)Scheduling
scheduleEvery(intervalSeconds, callback, payload?)- Fixed-interval recurring tasks with overlap prevention and error resilience.hungScheduleTimeoutSeconds)MCP Server API
Options-based
addMcpServer()overload - Cleaner API avoiding positionalundefinedparameters.Custom Routing
basePath- Bypass default URL construction for custom routingpath- Append sub-paths to routesnameandagenttype on connectonIdentity/onIdentityChange- Callbacks for identity eventsidentified/ready- State for identity statusstatic options = { sendIdentityOnConnect }- Server-side controlCallable System Improvements
{ timeout: 5000 }StreamingResponse.error(message)- Graceful stream error signalinggetCallableMethods()- Introspection API for callable methodscrypto.randomUUID()- More robust RPC IDsEmail Utilities
isAutoReplyEmail(headers)- Detect auto-reply emails using standard RFC headers (Auto-Submitted,X-Auto-Response-Suppress,Precedence)Tests Added
packages/agents/src/tests/state.test.tspackages/agents/src/tests/basepath.test.tspackages/agents/src/tests/routing.test.tspackages/agents/src/tests/callable.test.tspackages/agents/src/tests/client-timeout.test.tspackages/agents/src/tests/message-handling.test.tspackages/agents/src/tests/email-headers.test.tspackages/agents/src/tests/mcp/add-mcp-server.test.tsBug Fixes
useReftype fix - Fixed type error inreact.tsxinitialStateon corrupted stateReviewer Notes
Key Areas for Review
State Management (
packages/agents/src/index.ts)setState()refactorvalidateStateChange()hookonStateUpdate()viactx.waitUntil()Routing & Identity (
packages/agents/src/index.ts,client.ts,react.tsx)CF_AGENT_IDENTITYWebSocket message typestatic optionspattern for server-side configurationCallable System (
packages/agents/src/client.ts)Schema Migration (
scheduleEvery)intervalSeconds,running, andexecution_started_atcolumns tocf_agents_schedulesTest Commands
Changesets
.changeset/sync-set-state.md- Synchronous setState refactor.changeset/callable-improvements.md- Callable system enhancements.changeset/identity-routing-enhancements.md- Routing and identity features.changeset/friendly-mcp-options.md- MCP options API.changeset/cool-intervals-run.md- scheduleEvery method.changeset/email-header-utilities.md- Email header utilities.changeset/fix-serializable-interface-types.md- Serializable type fixes.changeset/bug-fixes-three.md- Bug fixes