Reference
Wire protocol
Everything that crosses the network between your browser, AgentGraft, and your host app.
6 min read
Most integrations never need to look at the wire โ the SDK and the widget handle every byte automatically. But the moment something goes wrong (a 401, a missing tool result, a streaming hang) you want to know exactly what's supposed to be on the network. This page is the ground-truth contract.
#The four connections
Four sets of HTTP exchanges happen for a working integration. They're independent โ none of them block on each other โ and each has its own auth model.
- Browser โ AgentGraft: every chat message the visitor types. Authenticated by the public key + user external id + HMAC headers, signed by the host app server-side.
- AgentGraft โ Host app: every tool call the LLM decides to make. Authenticated by an HMAC signature header keyed on the graft's webhook secret.
- Host app โ AgentGraft (config): the sync command, exactly when the operator runs it, and the
/import/endpoint (see Importing users). Authenticated by the graft'ssk_live_API key as a Bearer token. - Host server โ AgentGraft (chat): the SDK's
Clientchatting for a user or a bot, on the same widget endpoints and headers as the browser. Choosing the agent, a turn'sinstructionsandX-AgentGraft-Spend-Asalso need the graft'ssk_live_key inX-AgentGraft-Server-Key.
#Browser โ AgentGraft (chat messages)
The widget POSTs every visitor message to /api/v1/widget/conversations/{id}/stream/ on the AgentGraft API. The response is a Server-Sent Events stream of tokens, tool-call notifications, agent changes and a final done event.
POST /api/v1/widget/conversations/5b0c7d2e-.../stream/ HTTP/1.1
Host: agentgraft.com
Content-Type: application/json
X-AgentGraft-Public-Key: pk_live_a1b2c3...
X-AgentGraft-User-Id: user:42
X-AgentGraft-User-HMAC: v2.1796000000.9f4d2e3a8b7c...
{"message": "what datasets do I have?", "attachment_ids": []}
POST /api/v1/widget/conversations/{id}/send/ takes the same body and answers with one JSON object once the whole turn is done: message_id, text, agent_name, input_tokens, output_tokens, cost_usd, model_used, cut_short, title_update, followups, quota, tokens and accepts_images. Every path ends in a slash: a POST without it fails.
/send/ and /stream/ take turn_key; only /send/ takes budget_s and reply_s. A key used before in the conversation runs nothing: a finished turn sends back its saved reply with "replayed": true (on /stream/, as one token and a done), one still running is a 409, one that started and never finished is a 409 with "code": "turn_unfinished", and the same key with other words is a 400. The widget sends a new key with every message. budget_s (up to 480 seconds) is how long the turn's agents may call your tools; then they have reply_s (30 by default, up to 60) for their last reply and are stopped, and the reply says cut_short.
#Optional headers
X-AgentGraft-Visitor-Nameโ a display name, up to 60 characters, control characters stripped; stored on the visitor and given to the agents.X-AgentGraft-Visitor-Timezoneโ an IANA name such asEurope/London; anything else is ignored.Accept-Languageโ the language of error and quota messages, streamed ones included.X-AgentGraft-Server-Keyโ the graft'ssk_live_key, from your server only; a wrong one is a 401. It is needed foragentwhen starting a conversation, a turn'sinstructions(up to 20,000 characters) andX-AgentGraft-Spend-As; any of them without it is a 403.X-AgentGraft-Spend-Asโ the external id whose allowance this visitor spends from, from this request on; the visitor's own id gives them back their own. Blank or over 255 characters is a 400.
The HMAC header is a visitor token the host app signs server-side (the SDK's compute_user_hmac helper), keyed with the graft's webhook secret. AgentGraft re-derives it from the same secret on the way in and rejects any request where they don't match. This means the public key alone isn't enough to talk to the API โ an attacker would need the webhook secret to act as any of your users, and the webhook secret never leaves your server.
v2.<expiry>.<hex>
hex = HMAC-SHA256(webhook_secret, "agentgraft:visitor:v2\0" + user_id + "\0" + expiry)
A token holds until its expiry, give or take 60 seconds of clock skew; after that the request is a 401 that says it expired. One that expires more than 7 days ahead is refused. The SDK's template tag signs one for 24 hours on every render, and its Client one for an hour on every request. SDKs before 0.18 send the legacy bare HMAC-SHA256 of the id, which never expires; AgentGraft still accepts it while hosts upgrade, except for an id that starts with {.
For 24 hours after you rotate the webhook secret, AgentGraft also accepts visitor tokens and legacy HMACs signed with the one it replaced, so pages rendered before you redeploy keep working. Tool calls are signed with the new secret at once.
A logged-out visitor has no id of yours to sign, so the page shows the placeholder data-user-id="browser:*" and signs a token for the anonymous grant, the exact string agentgraft:anonymous-visitor:v1 (ag.ANONYMOUS_VISITOR_GRANT), instead. The widget then sends a random id it picked for the browser, browser: followed by 22 base64url characters, with the grant's token. A valid grant vouches for any id of that shape and nothing else, never a user: id. Anyone can start a new anonymous conversation on a page that signs the grant, as anyone can by loading that page, but no one can take over another visitor's: that takes the random id kept in their browser. AgentGraft never stores it; your webhook and the dashboard see a session: id derived from it.
The graft's owner can turn anonymous visitors off in the dashboard without rotating the secret; the grant is then refused with a 401. Each network may bring a graft 30 new anonymous visitors an hour (ANONYMOUS_VISITORS_PER_IP_PER_HOUR); past that a new one gets a 429, and returning ones are unaffected.
The widget's face reacts to the conversation. As a visitor types, and again as the reply streams, the widget POSTs the text to /api/v1/widget/affect/ with the same headers. AgentGraft asks TypeSafe's Jev how the face should look and answers with a blend of its expressions; the face eases into it while the words are still arriving. It is always on and needs nothing in your config.
#AgentGraft โ Host app (tool calls)
When an agent decides to call a tool, the runtime POSTs a tool dispatch payload to the host app's webhook URL (whatever you configured at sync time, e.g. https://yourapp.com/agentgraft/webhook/). The Django adapter handles this entire request โ you don't write any view code.
POST /agentgraft/webhook/ HTTP/1.1
Host: yourapp.com
Content-Type: application/json
X-AgentGraft-Graft: 3f2a9c1e-...
X-AgentGraft-Signature-V2: 51c08e7a2d94...
X-AgentGraft-Signature: 9f4d2e3a8b7c...
{
"tool": "get_dataset",
"arguments": {"dataset_id": 42},
"user_external_id": "user:7",
"is_anonymous": false,
"private": false,
"agent": "researcher",
"conversation_id": "5b0c7d2e-...",
"turn_key": "nightly-digest-2026-11-29",
"request_id": "req_018f3a...",
"timestamp": 1712345678
}
X-AgentGraft-Signature-V2 is the hex HMAC-SHA256, keyed on the graft's webhook secret, of the raw request body after a domain tag (below), so no visitor token can pass for it. Because timestamp and request_id are inside the signed body, they can't be altered or stripped without breaking the signature. The SDK rejects the request with 401 if the signature doesn't match or the timestamp is more than 5 minutes away from the host's clock (replay protection), so keep the host's clock in sync with NTP.
X-AgentGraft-Signature-V2 = hex HMAC-SHA256(webhook_secret, "agentgraft:webhook:v2\0" + body)
X-AgentGraft-Signature = hex HMAC-SHA256(webhook_secret, body) (legacy)
X-AgentGraft-Signature, the bare HMAC of the body, is sent too, for hosts on SDKs before 0.18. It is the construction those SDKs signed visitor ids with, so a host that signed an id an attacker chose handed them a valid signature for a forged body. SDK 0.18 verifies only the V2 header and refuses a request with the legacy one alone; verify the V2 one in your own code too.
is_anonymous is true when user_external_id is in the session: namespace AgentGraft uses for logged-out visitors. The server derives it from the verified id, never from a flag the browser sends, and a browser can't leave the namespace: an id outside it needs your signature.
AgentGraft retries a tool call once on connection errors, connect and write timeouts, and 502/503/504 responses, resending the exact same body. It never retries a read timeout (your tool may still be running) or any 4xx. It waits up to 120 seconds for an answer, never follows a redirect, connects only to public addresses, and reads at most 1 MB of the response. If your tool writes, use request_id as an idempotency key so a retry of a call that already ran doesn't write twice. Inside a tool, ag.current_request_id() returns it.
private is true when the call came from the widget's private chat. AgentGraft does not store that chat, and its tool calls carry conversation_id: null. Inside the tool, ag.current_call_is_private() returns the flag so a tool that writes can skip the write. Older servers omit the field; treat that as false.
agent names the agent that made the call, as declared in your config (@ag.agent def researcher(): ... calls arrive as "researcher"). The SDK hands it to your tool-call hooks as ToolCall.agent; older servers omit it.
conversation_id is the stored conversation whose turn made the call, null from a private chat, which is not stored. turn_key is the key your server sent with that turn on /send/, null without one. The SDK hands both to your hooks as ToolCall.conversation_id and ToolCall.turn_key. user_external_id is always the visitor's own id, even when X-AgentGraft-Spend-As points their spending at someone else. Once a turn with budget_s has spent its budget, its tool calls stop reaching you: the model is told time is up.
@ag.tool
def create_note(user: User, text: str) -> dict:
request_id = ag.current_request_id() # None outside a webhook call
if request_id is None:
note = Note.objects.create(owner=user, text=text)
else:
# agentgraft_request_id: CharField(unique=True, null=True)
note, _ = Note.objects.get_or_create(
agentgraft_request_id=request_id,
defaults={"owner": user, "text": text},
)
return {"id": note.pk}
The response is the JSON-serialised return value of your tool function, wrapped in {"result": ...}:
HTTP/1.1 200 OK
Content-Type: application/json
{"result": {"id": 42, "name": "Q1 sales", "rows": 12000}}
Failures come back as {"error": "<message>"} with a status code the runtime passes to the LLM as the tool result, so the conversation carries on: 400 for bad arguments, 401 for a bad signature or a missing or stale timestamp, 403 when your user_loader raises, 404 for an unknown tool, and 500 when the tool itself raises. The model sees webhook returned <status>: <your error>, cut to 300 characters. The SDK's own 400 and 404 messages reach it, and so does your message from raise ag.WebhookError(status, "message"); any other exception is logged on your side and answered generically, unless the profile sets "detailed_errors": True. A 2xx body with no result key is taken as the result whole.
#Host app โ AgentGraft (sync)
Run by manage.py agentgraft_sync. POSTs the entire declarative bundle (every tool, agent, and prompt block) to the admin API. Authenticated with the graft's sk_live_ API key as a Bearer token. Server-side this is atomic: either every change lands, or none of them do.
POST /api/v1/admin/grafts/018f3a7c-.../sync/ HTTP/1.1
Host: agentgraft.com
Authorization: Bearer sk_live_a1b2c3...
Content-Type: application/json
User-Agent: agentgraft-python/0.19.0 (+https://agentgraft.com)
{
"tools": [
{"name": "list_datasets", "description": "...", "parameters_schema": {...}},
{"name": "get_dataset", "description": "...", "parameters_schema": {...}}
],
"agents": [
{"name": "helper", "instructions": "...", "tool_names": ["list_datasets", "get_dataset"], "is_entry_point": true}
],
"graft": {
"name": "Acme",
"identity": "You are Acme's in-app assistant.",
"voice": "Be concise...",
"policies": "...resolved policy text..."
},
"webhook_url": "https://yourapp.com/agentgraft/webhook/"
}
Policies referenced by ag.policy(codename) are resolved client-side before the POST โ the SDK fetches each one from the public Policy Shop endpoint and concatenates the bodies into the graft.policies string. The runtime never has to know about codenames.
#Streaming responses
The chat send endpoint streams its response as Server-Sent Events. Each event has a type and a payload. The widget consumes them in order; an LLM agent integrating directly would do the same.
data: {"type":"token","text":"I"}
data: {"type":"handoff_initiated"}
data: {"type":"agent_changed","name":"data_helper"}
data: {"type":"tool_call","name":"list_datasets","call_id":"call_9x...","arguments":{}}
data: {"type":"tool_result","call_id":"call_9x...","result":"[...]"}
data: {"type":"token","text":" found 3 datasets:"}
: keepalive
data: {"type":"followups","questions":["..."]}
data: {"type":"done","message_id":"5f1c...","text":"I found 3 datasets: ...","agent_name":"data_helper","input_tokens":812,"output_tokens":64,"cost_usd":"0.000431","model_used":"...","quota":{...},"tokens":{...},"accepts_images":false}
tokenโtext, a piece of the reply.tool_callโname,call_idandarguments;tool_resultโ the samecall_idand itsresult.handoff_initiated, thenagent_changedwith the new agent'sname.reading_imagesโimages, how many images this turn's agent waits to have described.titleโevent(title_setortitle_suggested),titleandconversation_id.followupsโquestions, sent beforedone.speechandspeech_errorโ only when the body asked for"speak": trueon a graft with voice.doneโ the saved reply and its metadata (quotaandtokensare null if reading them after the reply failed);errorโdetail, and the stream ends.- Lines starting with
:are keepalives, sent after 15 quiet seconds; ignore them. A stream silent for longer than that has dropped: the widget gives up after 45 seconds and shows the turn as failed, with a retry.
#Private chat
POST /api/v1/widget/private/stream/ runs one turn with the graft's private agent and stores nothing. The body carries message, the history the browser keeps (role, content, and images data URLs on user turns) and this message's images, up to 32 MB in all. One private turn runs at a time per visitor, and its cost counts against the allowance. Its done has no message_id and no tokens.
#Voice
A stream body with "speak": true, on a graft with voice, adds speech events (audio: base64 16-bit PCM, encoding linear16, sample_rate 24000, language) alongside the tokens, or one speech_error. POST /api/v1/widget/speech/token/ returns a short-lived Deepgram token, which the browser uses to stream the microphone itself; POST /api/v1/widget/speech/transition/ returns one spoken bridge between queued replies. Both are a 403 without voice and count against the allowance.
#Errors
Every refusal is a JSON body, {"detail": "..."}, in the request's language. A refused stream answers before it starts, so it is never an SSE stream that errors at once.
400 bad body, message too long, unknown agent, bad Spend-As,
turn_key reused with other words
401 missing or invalid widget headers, invalid user HMAC, invalid
server key, anonymous visitors turned off
403 a server-only field or header without X-AgentGraft-Server-Key;
voice requests on a graft without voice
404 conversation not found; no private agent
409 a turn is already running in this conversation;
{"code": "turn_unfinished"} for a keyed turn that never finished
413 private chat body over 32 MB
429 allowance spent (the body adds "quota": {is_exceeded, quota_usd,
used_usd, remaining_usd, refill_in_seconds, next_refill_at, ...});
also too many new anonymous visitors, or face and voice requests
500 the turn failed on send/; on stream/ an "error" event instead
#Every widget endpoint
/api/v1/widget/
i18n/<lang>/ GET the widget's strings, no auth
visitor/ PATCH send and pause phrases, language
usage/ GET the allowance and who spent it
conversations/ GET threads + the graft's settings
POST start one
DELETE wipe the visitor's data
conversations/search/?q= GET
conversations/export/ GET
route/ POST where a message belongs
conversations/<id>/ GET, PATCH, DELETE
pin/ archive/ POST, DELETE
fork/ branch-archive/ promote/ POST
title/accept/ title/dismiss/ POST
messages/ GET
messages/<message_id>/from/ DELETE
attachments/ quota/ recap/ GET
compact/ POST
send/ POST JSON reply
stream/ POST SSE reply
private/stream/ POST SSE reply, nothing stored
affect/ POST the face's mood
speech/token/ speech/transition/ POST
attachments/ GET, POST
attachments/<id>/ DELETE
attachments/<id>/content/ GET
attachments/<id>/reattach/ POST
messages/<id>/feedback/ POST
messages/<id>/highlights/[<id>/] POST; PATCH, DELETE
memories/ GET, POST
memories/consolidate/ POST
memories/<id>/ PATCH, DELETE
#Identity flow at a glance
Putting it all together for a single chat turn: the host app server renders the widget tag, which signs the user's id with the webhook secret and embeds the signature in the <script> element's data attributes. The widget boots in the browser, includes those headers on every API call to AgentGraft. The runtime verifies the HMAC, runs the agent loop, and POSTs any tool calls back to the host app's webhook signed with the same secret. The host app re-verifies, runs the tool, returns the result. The runtime streams the final answer back to the widget. AgentGraft never sees your user records: it knows the visitor by the opaque external id, and keeps their conversations, memories and the display name the widget sends, encrypted per visitor.