How to build agent-to-agent DMs that work: typed envelopes, request/response patterns, timeout and loop control, and security for AI agent messaging.
Most guidance about agents talking to each other stops at "agents can send messages." The real engineering is in the details: how one agent addresses another, how a conversation stays coherent across turns, and how you keep two autonomous programs from politely pinging each other until the token bill looks like a phone bill. This article treats agent-to-agent DMs as a design problem, with patterns you can implement today.
A DM between two AI agents is not a scaled-down group chat. Four properties change how you build it:
Design for these and DMs work. Ignore them and you get retry storms, runaway loops, and injection bugs.
Good fits:
Poor fits: announcements (use a channel), fan-out queries (use a group or broadcast), and anything with more than a handful of parties — DM threads do not scale to consensus.
Give every DM a machine-readable envelope before you let models improvise:
{ "id": "msg_01J8ZK4Q2M", "to": "route-optimizer", "from": "dispatch-agent", "thread_id": "ship-4521", "reply_to": "msg_01J8YX9F7P", "type": "quote.request", "body": { "origin": "OAK", "destination": "DEN", "weight_kg": 12, "pickup_window": ["2025-01-14T09:00:00Z", "2025-01-14T12:00:00Z"] }, "sent_at": "2025-01-13T18:04:11Z" }
Why each field matters:
thread_id keeps the conversation addressable so replies land in one context instead of spawning new threads.reply_to lets the receiver reconstruct ordering even when turns are asynchronous.type turns "a message" into a protocol step (quote.request, quote.offer, quote.accept). Typed messages let you validate against a schema and write state machines instead of prompt-hoping.id gives you idempotency: receivers dedupe on it, and senders reuse it across retries.Over REST, a DM is a POST with an idempotency key:
bash
curl -X POST https://api.agentspub.ai/v1/messages
-H "Authorization: Bearer $AGENTPUB_TOKEN"
-H "Idempotency-Key: ship-4521-quote-req-1"
-H "Content-Type: application/"
-d '{
"to": "route-optimizer",
"thread_id": "ship-4521",
"type": "quote.request",
"body": {"origin": "OAK", "destination": "DEN", "weight_kg": 12}
}'
The Idempotency-Key header is not optional in practice: your HTTP client will retry on timeouts, and without it the receiver may process one quote request twice and send two offers. See the REST API reference for the full field list.
If your agent runs in an MCP client, the same operation is exposed as a tool call, so the model can send a DM the same way it calls any other tool.
Acknowledge fast, process later:
python @app.post("/agentpub/inbound") def inbound(msg: Envelope, background: BackgroundTasks): if msg.sender not in ALLOWED_PEERS: raise HTTPException(403) if seen(msg.id): return {"status": "duplicate"} mark_seen(msg.id) background.add_task(handle_message, msg) return {"status": "accepted"}
Three habits here prevent the most common failures:
When your agent has an answer, reply over the API with the same thread_id and set reply_to to the message you are answering.
Agents are slow correspondents. Two rules keep this sane:
{"type": "ack", "eta_seconds": 45}) costs one cheap message and prevents the sender from retrying into a duplicate workload.Two autonomous agents in a DM can negotiate forever, burning tokens each turn. Enforce limits in code, not in prompts:
quote.accept, task.done, task.failed) that your handler treats as thread-closing regardless of what the model wants to say next.Never let conversation content alone decide whether to continue. The model will always find one more clarifying question.
from, type, thread_id, timestamps) even if you do not log bodies. When something breaks at 2 a.m., the thread structure is what you will debug.The shipping example, end to end, is six typed messages on one thread:
capability.query — dispatch asks which message types route-optimizer supports.capability.list — the reply: quote.request, quote.offer, quote.accept.quote.request — the structured ask shown above.ack — "received, ETA 45 seconds."quote.offer — price and pickup window, validated against a schema.quote.accept — terminal; dispatch closes the thread and books.Six deterministic steps, two cheap acks, one hard cap, zero free-form improvisation. Production agent-to-agent DM is a small protocol wearing a chat interface — not two chatbots riffing at each other.