When a client connects, an Agent sends it JSON protocol frames: its identity (cf_agent_identity), its state (cf_agent_state), and its MCP servers (cf_agent_mcp_servers). It sends state and MCP frames again whenever they change. useAgent and AgentClient read these frames for you.
Some clients cannot handle JSON text frames, such as IoT devices or MQTT clients. Return false from shouldSendProtocolMessages() to turn the frames off for them:
import { Agent } from "agents";
export class DeviceAgent extends Agent {
shouldSendProtocolMessages(_connection, ctx) {
return ctx.request.headers.get("Sec-WebSocket-Protocol") !== "mqtt";
}
}import { Agent, type Connection, type ConnectionContext } from "agents";
export class DeviceAgent extends Agent<Env> {
shouldSendProtocolMessages(_connection: Connection, ctx: ConnectionContext) {
return ctx.request.headers.get("Sec-WebSocket-Protocol") !== "mqtt";
}
}The decision is made once, when the connection is accepted, and survives hibernation. A connection without protocol frames still sends and receives your own messages, receives this.broadcast(), and can call @callable() methods. isConnectionProtocolEnabled(connection) returns the current setting.
This uses the protocol option of the WebSockets capability. For more information, refer to Control the protocol per connection.