Skip to content

docs/tests/enhancements #812

Merged
threepointone merged 41 commits intomainfrom
docs
Feb 3, 2026
Merged

docs/tests/enhancements #812
threepointone merged 41 commits intomainfrom
docs

Conversation

@threepointone
Copy link
Contributor

@threepointone threepointone commented Jan 30, 2026

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:

  • 15+ new documentation files covering core concepts and features
  • 10+ new test files with 100+ tests
  • New features: synchronous setState(), validateStateChange() hook, scheduleEvery(), basePath routing, server-sent identity, callable improvements
  • No breaking changes (backward compatibility maintained)

Documentation Added

Documentation Index

File Description
docs/index.md Main table of contents organizing all documentation by category

Getting Started & Integration

File Description
docs/getting-started.md Quick start guide covering installation, first agent, state basics, and deployment
docs/adding-to-existing-project.md Guide for integrating agents into existing Workers, including React apps, Hono, static assets, and common patterns

Core Concepts

File Description
docs/state.md State management covering initialState, setState(), validateStateChange(), onStateUpdate(), persistence, and client synchronization
docs/routing.md URL routing patterns, routeAgentRequest(), custom paths with basePath, server-sent identity, and advanced routing scenarios
docs/http-websockets.md HTTP/WebSocket lifecycle hooks (onRequest, onConnect, onMessage, onClose), connection management, per-connection state, hibernation, and common patterns

Features

File Description
docs/callable-methods.md @callable decorator, RPC over WebSocket, streaming responses, TypeScript integration, error handling, and when to use DO RPC instead
docs/mcp-client.md Connecting to MCP servers with addMcpServer(), OAuth flows, transport options, and tool usage
docs/scheduling.md One-time, recurring (scheduleEvery), and cron-based scheduling

New Features

State Management

Synchronous setState() - setState() is now synchronous, returning void instead of Promise<void>. Existing code using await this.setState(...) continues to work.

// Before (still works - awaiting void is harmless)
await this.setState({ count: 1 });

// After (preferred)
this.setState({ count: 1 });

validateStateChange() hook - New synchronous validation hook that runs before state is persisted and broadcast. Throw to reject updates:

validateStateChange(nextState: State, source: Connection | "server") {
  if (nextState.count < 0) {
    throw new Error("Count cannot be negative");
  }
}

onStateUpdate() is now non-gating - Runs via ctx.waitUntil() after persistence and broadcast. Errors are routed to onError() but don't prevent state updates.

Execution order:

  1. validateStateChange(nextState, source) - validation (sync, gating)
  2. State persisted to SQLite
  3. State broadcast to connected clients
  4. onStateUpdate(nextState, source) - notifications (async via ctx.waitUntil, non-gating)

Scheduling

scheduleEvery(intervalSeconds, callback, payload?) - Fixed-interval recurring tasks with overlap prevention and error resilience.

await this.scheduleEvery(60, "cleanup");
await this.scheduleEvery(300, "syncData", { source: "api" });
  • Validates interval doesn't exceed 30 days (DO alarm limit)
  • Overlap prevention with hung callback detection (configurable via hungScheduleTimeoutSeconds)

MCP Server API

Options-based addMcpServer() overload - Cleaner API avoiding positional undefined parameters.

// New preferred format
await this.addMcpServer("server", url, {
  callbackHost: "https://my-worker.workers.dev",
  transport: { headers: { Authorization: "Bearer ..." } }
});

Custom Routing

  • basePath - Bypass default URL construction for custom routing
  • path - Append sub-paths to routes
  • Server-sent identity - Agents send name and agent type on connect
  • onIdentity / onIdentityChange - Callbacks for identity events
  • identified / ready - State for identity status
  • static options = { sendIdentityOnConnect } - Server-side control
const agent = useAgent({
  basePath: "user",
  onIdentity: (name, agentType) => console.log(`Connected to ${name}`)
});

Callable System Improvements

  • Client-side RPC timeout - { timeout: 5000 }
  • StreamingResponse.error(message) - Graceful stream error signaling
  • getCallableMethods() - Introspection API for callable methods
  • Connection close handling - Pending calls rejected on disconnect
  • WeakMap for metadata - Prevents memory leaks
  • crypto.randomUUID() - More robust RPC IDs
  • Streaming observability - Events for streaming calls
  • Streaming error logging - Server-side errors now logged for observability
// New format (supports timeout)
await agent.call("method", [args], {
  timeout: 5000,
  stream: { onChunk, onDone, onError }
});

// Legacy format (still supported)
await agent.call("method", [args], { onChunk, onDone, onError });

Email Utilities

  • isAutoReplyEmail(headers) - Detect auto-reply emails using standard RFC headers (Auto-Submitted, X-Auto-Response-Suppress, Precedence)

Tests Added

File Coverage
packages/agents/src/tests/state.test.ts State persistence, sync, validation, edge cases
packages/agents/src/tests/basepath.test.ts Custom path routing
packages/agents/src/tests/routing.test.ts General routing (22 tests)
packages/agents/src/tests/callable.test.ts RPC, streaming, errors, introspection (17 tests)
packages/agents/src/tests/client-timeout.test.ts Client-side RPC timeouts
packages/agents/src/tests/message-handling.test.ts WebSocket message handling
packages/agents/src/tests/email-headers.test.ts Email header utilities
packages/agents/src/tests/mcp/add-mcp-server.test.ts MCP options API, legacy signature

Bug Fixes

  • React useRef type fix - Fixed type error in react.tsx
  • Memory leak prevention - WeakMap for callable metadata storage
  • Connection cleanup - Pending RPC calls rejected on WebSocket close
  • JSON parse error handling - Graceful fallback to initialState on corrupted state
  • Streaming error logging - Server-side errors in streaming methods are now logged

Reviewer Notes

Key Areas for Review

  1. State Management (packages/agents/src/index.ts)

    • Synchronous setState() refactor
    • validateStateChange() hook
    • onStateUpdate() via ctx.waitUntil()
  2. Routing & Identity (packages/agents/src/index.ts, client.ts, react.tsx)

    • New CF_AGENT_IDENTITY WebSocket message type
    • Client state management for identity
    • static options pattern for server-side configuration
  3. Callable System (packages/agents/src/client.ts)

    • Backward compatibility detection for streaming options
    • Timeout implementation with cleanup
  4. Schema Migration (scheduleEvery)

    • Adds intervalSeconds, running, and execution_started_at columns to cf_agents_schedules
    • Auto-migrates existing agents

Test Commands

# Run all tests
CI=true npm test

# Run specific test files
cd packages/agents && npm run test:workers -- callable.test.ts
cd packages/agents && npm run test:workers -- routing.test.ts
cd packages/agents && npm run test:workers -- state.test.ts

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

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-bot
Copy link

changeset-bot bot commented Jan 30, 2026

🦋 Changeset detected

Latest commit: 29b9fdd

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
agents Patch

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

@pkg-pr-new
Copy link

pkg-pr-new bot commented Jan 30, 2026

Open in StackBlitz

npm i https://pkg.pr.new/cloudflare/agents@812

commit: 29b9fdd

@claude

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
New method on the Agent class to introspect all callable methods and their metadata:

```typescript
const methods = agent.getCallableMethods();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@craigsdennis you wanted this


```typescript
// Clean options object
await this.addMcpServer("server", url, {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mattzcarey better, no?

Copy link
Contributor

@whoiskatrin whoiskatrin Feb 1, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i am actually a fan of this, i like it, it's clean


## Custom URL Routing with `basePath`

New `basePath` option bypasses default `/agents/{agent}/{name}` URL construction, enabling custom routing patterns:
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@whoiskatrin ramp wanted this

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.
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>
@threepointone threepointone changed the title DO NOT LAND: docs/tests/enhancements docs/tests/enhancements Feb 3, 2026
@threepointone threepointone marked this pull request as ready for review February 3, 2026 10:21
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.
@claude

This comment was marked as resolved.

@threepointone threepointone merged commit 6218541 into main Feb 3, 2026
5 checks passed
@threepointone threepointone deleted the docs branch February 3, 2026 10:58
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
@github-actions github-actions bot mentioned this pull request Feb 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants