docs/tests/enhancements #812
Merged
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.
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).
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.
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).
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.
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 }.
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.
threepointone
marked this pull request as ready for review
February 3, 2026 10:21
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