Skip to content

Commit c21f55e

Browse files
Sync docs from PR #633: add agent status monitoring function
1 parent 1a8d1e8 commit c21f55e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/content/docs/agents/api-reference/calling-agents.mdx

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,48 @@ Calling other Agents uses the same APIs as calling into an Agent directly.
6767

6868
:::
6969

70+
### Monitoring Agent status
71+
72+
You can check if an Agent instance is currently active and has connected clients using the `getAgentStatus` helper function:
73+
74+
<TypeScriptExample>
75+
76+
```ts
77+
import { Agent, AgentNamespace, getAgentByName, getAgentStatus } from 'agents';
78+
79+
interface Env {
80+
MyAgent: AgentNamespace<MyAgent>;
81+
}
82+
83+
export default {
84+
async fetch(request, env, ctx): Promise<Response> {
85+
const agent = await getAgentByName<Env, MyAgent>(env.MyAgent, 'user-123');
86+
87+
// Check the agent's connection status
88+
const status = getAgentStatus(agent);
89+
90+
return Response.json({
91+
connectionCount: status.connectionCount,
92+
isActive: status.isActive,
93+
agentId: status.agentId
94+
});
95+
},
96+
} satisfies ExportedHandler<Env>;
97+
98+
export class MyAgent extends Agent<Env> {
99+
// Your Agent implementation
100+
}
101+
```
102+
103+
</TypeScriptExample>
104+
105+
The `getAgentStatus` function returns:
106+
- `connectionCount`: Number of active WebSocket connections to the agent
107+
- `isActive`: Boolean indicating if the agent has any active connections
108+
- `agentId`: The unique identifier of the agent instance (or `undefined` if not available)
109+
110+
This is useful for monitoring agent activity, implementing health checks, or determining if an agent should be kept alive or allowed to hibernate.
111+
70112
### Calling methods on Agents
71113

72114
When using `getAgentByName`, you can pass both requests (including WebSocket) connections and call methods defined directly on the Agent itself using the native [JavaScript RPC](/workers/runtime-apis/rpc/) (JSRPC) API.

0 commit comments

Comments
 (0)