Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Callable Methods, WebSocket RPC, Client Streaming, and TypeScript

How Cloudflare Agents @callable() methods expose WebSocket RPC to browsers, with streaming, errors, timeouts, and TypeScript setup.

This page summarises Cloudflare documentation on callable methods: marking agent methods with @callable() so browsers, mobile apps, and other external runtimes can invoke them over a WebSocket using RPC, distinct from in-Worker Durable Object RPC.

Callable methods: what WebSocket RPC exposes to clients

Section titled “Callable methods: what WebSocket RPC exposes to clients”

Callable methods let clients invoke agent methods over WebSocket using RPC (Remote Procedure Call). Mark methods with @callable() to expose them to external clients like browsers, mobile apps, or other services.

Callable methods let clients invoke agent methods over WebSocket using RPC (Remote Procedure Call). Mark methods with @callable() to expose them to external clients like browsers, mobile apps, or other services.

— Cloudflare, Callable methods

The Agents SDK extends Durable Objects RPC by carrying client calls over WebSockets. On the wire, a client sends a message shaped like an RPC request; the agent runs only methods decorated with @callable().

agents takes Durable Objects RPC one step further by implementing RPC through WebSockets, so clients can call methods on the Agent directly. To make a method callable through WebSocket, use the @callable() decorator. Methods can return a serializable value or a stream (when using @callable({ streaming: true })).

— Cloudflare, Agent class internals

Clients can invoke this method by sending a WebSocket message:

{
"type": "rpc",
"id": "unique-request-id",
"method": "add",
"args": [2, 3]
}

For React apps, the Client SDK documents the same idea: call methods on your agent that are decorated with @callable().

@callable() vs Durable Object RPC: when to use which path

Section titled “@callable() vs Durable Object RPC: when to use which path”

The decorator is only for external WebSocket clients. Calls inside the same Worker codebase or between agents use Durable Object RPC and do not need @callable().

Scenario Mechanism
Browser or mobile calling the agent @callable()
External service over the agent WebSocket @callable()
Worker fetch handler calling the same agent Durable Object RPC via getAgentByName() — no decorator
One agent calling another getAgentByName() on the target agent

The @callable() decorator is specifically for WebSocket-based RPC from external clients. When calling from within the same Worker or another agent, use standard Durable Object RPC directly.

— Cloudflare, Callable methods

The `@callable() decorator is only required for methods called from external runtimes (browsers, other services). When calling from within the same Worker, you can use standard Durable Object RPC directly on the stub without the decorator.

— Cloudflare, Client SDK

From a Worker entrypoint, obtain a stub and call the method as a normal async RPC:

import { getAgentByName } from "agents";
const agent = await getAgentByName(env.MyAgent, "instance-name");
const result = await agent.processData(data);

Whether or not the server method is declared async, Durable Object RPC on the client side must be awaited; the return type behaves like a Promise (Workers RPC).

Sub-agents use typed stubs from subAgent() for parent-to-child work; that is colocated facet RPC, not the WebSocket @callable() surface.

Defining @callable() methods: args, returns, and metadata

Section titled “Defining @callable() methods: args, returns, and metadata”

Add @callable() to any instance method you want clients to reach. Sync and async bodies both work; void methods still complete a Promise on the client when the server finishes.

Arguments and return values must be JSON-serializable (primitives, plain objects, arrays). Functions, Date, Map, Set, and similar types cannot cross the wire (Serializable types).

Optional metadata on the decorator:

Field Purpose
description Human-readable label; surfaced by getCallableMethods()
streaming: true First parameter is StreamingResponse; see streaming section
import { Agent, callable } from "agents";
export class CounterAgent extends Agent {
@callable()
increment() {
this.setState({ count: this.state.count + 1 });
return this.state.count;
}
@callable({ description: "Add two numbers" })
async add(a: number, b: number) {
return a + b;
}
}

Expose methods to clients with @callable() (Add to existing project). Real-time apps such as the ChatGPT app demo use @callable() for connection-aware actions (for example reading connection from getCurrentAgent() inside a callable).

If the client reports that a method is not callable, the method is almost always missing the decorator:

Make sure your methods are decorated with @callable()

— Cloudflare, Add to existing project

Only decorated methods appear on agent.stub types; undecorated methods are internal unless you deliberately narrow types with Omit<> (Typed client calls).

TypeScript and Vite: TC39 decorators for @callable()

Section titled “TypeScript and Vite: TC39 decorators for @callable()”

@callable() relies on TC39 stage 3 decorators. Projects using Vite need both TypeScript and the Agents Vite plugin.

tsconfig.json — extend the package baseline (or set "target": "ES2021"):

{
"extends": "agents/tsconfig"
}

vite.config.ts — register the plugin that applies decorator transforms (including Vite 8):

import agents from "agents/vite";
export default defineConfig({
plugins: [agents(), /* ... */],
});

If you do not use Vite, the tsconfig.json change alone is enough provided your bundler supports TC39 decorators (stage 3, version 2023-11) (Configure TypeScript and Vite).

There are two ways to call methods from the client (Callable methods):

agent.stub (recommended) — typed proxy:

const count = await agent.stub.increment();
const items = await agent.stub.addItem("new item");

agent.call() — explicit method name and argument array:

const count = await agent.call("increment");
const items = await agent.call("addItem", ["new item"]);

The stub proxy provides better ergonomics and TypeScript support.

— Cloudflare, Callable methods

Pass the agent class (and optionally state type) into useAgent<MyAgent, CounterState>() so agent.stub picks up signatures (Quick start, Client SDK).

Timeouts, introspection, and disconnect behavior

Section titled “Timeouts, introspection, and disconnect behavior”

Recent callable improvements (Agents SDK v0.3.7 changelog) include:

  • Client-side timeout on agent.call()
  • StreamingResponse.error(message) for mid-stream failures
  • getCallableMethods() to list decorated methods and metadata
  • Automatic rejection of pending calls when the WebSocket closes
await agent.call("method", [args], {
timeout: 5000,
stream: { onChunk, onDone, onError },
});
const methods = agent.getCallableMethods();
for (const [name, meta] of methods) {
console.log(name, meta.description, meta.streaming ? "(streaming)" : "");
}

If the connection drops during a long RPC, callers receive a "Connection closed" error (Connection errors).

Streaming @callable() methods and StreamingResponse

Section titled “Streaming @callable() methods and StreamingResponse”

Mark a method with @callable({ streaming: true }). The framework injects StreamingResponse as the first parameter (before user args).

Method Role
send(chunk) Push a chunk to the client
end(finalChunk?) Finish; optional final value
error(message) Signal failure and close the stream

On the client, prefer nested stream options (legacy top-level onChunk / onDone / onError still work):

await agent.call("generateText", [prompt], {
stream: {
onChunk: (chunk) => { /* ... */ },
onDone: (finalValue) => { /* ... */ },
onError: (error) => { /* ... */ },
},
});

Server-side, call stream.error() to abort gracefully without throwing past the streaming layer (Streaming error handling).

Errors, observability, and getCurrentAgent() inside RPC

Section titled “Errors, observability, and getCurrentAgent() inside RPC”

Thrown errors in @callable() methods propagate to the client try / catch around agent.stub or agent.call (Throwing errors).

For operations tied to the live WebSocket, read connection context inside the callable:

const { connection } = getCurrentAgent();
if (!connection) throw new Error("Not connected");

The runtime wraps custom agent methods with AsyncLocalStorage so getCurrentAgent() can return agent, connection, request, or email depending on how the handler was entered (Agent class internals, getCurrentAgent()).

Custom methods — including those invoked as RPC — are now wrapped automatically, so getCurrentAgent() works inside RPC bodies where it previously failed (MCP update changelog). Prefer this.* on the agent class when you already have this; use getCurrentAgent() in shared utilities (Best practices).

Diagnostics channels emit when callable RPC runs or fails:

Event Payload When
rpc { method, streaming? } A @callable method is invoked
rpc:error { method, error } A @callable method throws

(Diagnostics channels)

  1. Confirm each client-facing method has @callable() and builds with agents/tsconfig (and agents/vite if you use Vite), following Add to existing project.

  2. From your UI, call a known method via agent.stub and via agent.call(); compare results with the patterns in Client SDK.

  3. Run getCallableMethods() in development and verify the method list matches what you expose (Callable methods).

  4. Trigger a streaming callable and confirm onChunk, onDone, and onError fire; watch Diagnostics channels for rpc and rpc:error events during the test.

  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact sentence you are asking about, and we will correct or clarify it.