
Poppy Protocol: Build a Personal Agent Client
Summary
Meta and Sierra's draft agent standard, in Python: discovery, DPoP sessions, and replay tests.
On October 6, Sierra announced the Personal Agent Protocol with Meta, Shopify, Stripe, Walmart, Genesys and others. It goes by the name Poppy, and the draft spec went up on October 9 with 35 more design partners, including OpenAI, PayPal, Mastercard and Visa. The idea is simple to state: a personal AI agent (your assistant, acting for you) should be able to walk up to a company, prove who it is, get the user's permission, and then use the company's website, API or support agent without pretending to be a human in a browser.
Most of the coverage so far is high level. The spec itself (Draft 0.1, at personalagentprotocol.org/docs/spec) is concrete: a discovery file, an issuer check, a JWT bearer grant, and DPoP-bound tokens. In this guide you will implement the agent side of that handshake in about 90 lines of Python, run it against a local mock company, and then try to break it with a replayed request and a stolen token. Everything below was run before it was written down.
A caveat up front: this is a Draft 0.1 spec that the authors say may change incompatibly, and there is no official reference implementation yet. The code here follows the spec as published on October 10, 2026, uses a local HTTP mock instead of a real company, and fills a few gaps (marked below) with the underlying RFCs. Treat it as a way to learn the shape of the protocol, not as production auth code.
What you need
- Python 3.10+ with
pip install pyjwt cryptography requests - Basic familiarity with OAuth and JWTs (you do not need to know DPoP; it is explained below)
- Three files in one folder:
poppy_agent.py,mock_company.py,demo.py. All three are shown in full.
How Poppy works in one page
There are two parties. The Personal Agent acts for a user. The Company runs the service. A company advertises Poppy support by serving a file at https://{domain}/.well-known/poppy.json. That file lists how to sign in, which scopes exist, and what the agent can use: a browser session endpoint, OpenAPI or MCP APIs, or a conversation endpoint where a company-side agent answers.
Trust comes from two checks. First, the auth.issuer in poppy.json must serve OAuth metadata at /.well-known/oauth-authorization-server, and that metadata must repeat the same issuer string and list the company's domain in a poppy_domains field. That stops a site from pointing at someone else's issuer. Second, the agent identifies itself with a client_id that is an HTTPS URL returning its metadata (jwks_uri, redirect_uris, and private_key_jwt as the auth method), so the company can fetch the agent's public key.
A session starts with a JWT bearer grant (RFC 7523). The agent signs an assertion whose sub is a stable, opaque per-company user ID, and posts it to the token endpoint along with a client assertion and a DPoP proof. The response carries an access_token, a session_id, and signed_in. A brand-new session is a guest session: the agent can ask about return policies, but account data needs a sign-in step (direct authorization code with PKCE, device grant, or a mediated flow).
| Piece | Where it comes from | What it protects |
|---|---|---|
| poppy.json | Company, /.well-known/ | Tells the agent what is offered |
| poppy_domains check | Issuer metadata | Stops a domain borrowing someone else's issuer |
| private_key_jwt | Agent, client_id metadata | Proves which agent is calling |
| DPoP proof | Agent, per request | Binds tokens to the agent's key, blocks replay |
| Scopes | poppy:read, poppy:write, custom | Limits what the agent may do |
Step 1: discovery with the issuer check
The first function fetches poppy.json and refuses to trust it until the issuer agrees. Notice what it does not do: it never follows redirects blindly (the spec requires redirects to stay on HTTPS), and it rejects non-HTTPS URLs unless you flip a flag that exists only for the localhost demo.
def discover(domain):
base = f"{'http' if ALLOW_HTTP else 'https'}://{domain}"
doc = fetch_json(f"{base}/.well-known/poppy.json")
for k in ("protocol_version", "organization", "auth"):
if k not in doc: raise PoppyError(f"poppy.json missing {k}")
if doc["organization"]["domain"] != domain:
raise PoppyError("organization.domain does not match the domain we fetched")
issuer = doc["auth"]["issuer"]
meta = fetch_json(f"{issuer}/.well-known/oauth-authorization-server")
if meta.get("issuer") != issuer:
raise PoppyError("issuer metadata mismatch")
if domain not in meta.get("poppy_domains", []):
raise PoppyError("issuer does not vouch for this domain (poppy_domains)")
for k in ("token_endpoint", "revocation_endpoint"):
if k not in meta: raise PoppyError(f"issuer metadata missing {k}")
return doc, meta
Step 2: the agent's identity and keys
The agent needs two key pairs. One signs assertions that prove who the agent is; its public half is published at the jwks_uri. The other is the DPoP key. Keeping them separate means a leaked per-session DPoP key does not let anyone impersonate the agent itself. (Using two keys is my design choice for the demo, not a spec requirement.)
DPoP (RFC 9449) is the part most people have not used. Every request carries a small signed JWT, the proof, containing the HTTP method (htm), the exact URL (htu), a unique jti, a timestamp, and, when calling an API, a hash of the access token (ath). The proof header embeds the public key. The server remembers which key a token was issued to, so a stolen token is useless without the private key.
def dpop_proof(self, method, url, access_token=None, nonce=None):
claims = {"jti": str(uuid.uuid4()), "htm": method, "htu": url, "iat": int(time.time())}
if access_token:
claims["ath"] = b64u(hashlib.sha256(access_token.encode()).digest())
if nonce: claims["nonce"] = nonce
return self._sign(claims, self.dpop_key,
{"typ": "dpop+jwt", "jwk": self.dpop_jwk})
Step 3: start a session
Starting a session posts three things to the token endpoint: the grant assertion (iss is your client_id, sub is the opaque user ID, aud is the token endpoint, a short exp, a unique jti), a client assertion, and the DPoP header. The spec summary says the request carries a client assertion without spelling out its claims; I used the standard RFC 7523 shape (iss and sub both equal to client_id), which is a gap-fill you should recheck against the final spec.
def start_session(self, meta, user_id, scope="poppy:read", session_id=None):
tok = meta["token_endpoint"]; now = int(time.time())
grant = self._sign({"iss": self.client_id, "sub": user_id, "aud": tok,
"iat": now, "exp": now + 60, "jti": str(uuid.uuid4())}, self.key)
client_assertion = self._sign({"iss": self.client_id, "sub": self.client_id,
"aud": tok, "iat": now, "exp": now + 60,
"jti": str(uuid.uuid4())}, self.key)
form = {"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": grant,
"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
"client_assertion": client_assertion, "scope": scope}
if session_id: form["session_id"] = session_id # renewal
r = requests.post(tok, data=form, headers={"DPoP": self.dpop_proof("POST", tok)}, timeout=10)
if r.status_code == 400 and r.json().get("error") == "invalid_session":
raise PoppyError("session ended; start a new one")
r.raise_for_status()
return r.json()
Renewal is the same call with the session_id from the earlier response. If the company ended that session, you get invalid_session and must start over.
The full code
Here is the complete agent module, then the mock company that verifies everything the spec says a company should verify, then the demo script.
poppy_agent.py
"""Minimal Poppy (Personal Agent Protocol, Draft 0.1) client.
Discovery -> issuer check -> session via JWT bearer grant + DPoP -> API call."""
import base64, hashlib, json, time, uuid
from urllib.parse import urlparse
import requests, jwt
from cryptography.hazmat.primitives.asymmetric import ec
ALLOW_HTTP = False # flip to True ONLY for the localhost demo
def b64u(b: bytes) -> str:
return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
class PoppyError(Exception): pass
def fetch_json(url):
if urlparse(url).scheme != "https" and not ALLOW_HTTP:
raise PoppyError(f"refusing non-HTTPS url: {url}")
r = requests.get(url, timeout=10, allow_redirects=False)
r.raise_for_status()
return r.json()
def discover(domain):
base = f"{'http' if ALLOW_HTTP else 'https'}://{domain}"
doc = fetch_json(f"{base}/.well-known/poppy.json")
for k in ("protocol_version", "organization", "auth"):
if k not in doc: raise PoppyError(f"poppy.json missing {k}")
if doc["organization"]["domain"] != domain:
raise PoppyError("organization.domain does not match the domain we fetched")
issuer = doc["auth"]["issuer"]
meta = fetch_json(f"{issuer}/.well-known/oauth-authorization-server")
if meta.get("issuer") != issuer:
raise PoppyError("issuer metadata mismatch")
if domain not in meta.get("poppy_domains", []):
raise PoppyError("issuer does not vouch for this domain (poppy_domains)")
for k in ("token_endpoint", "revocation_endpoint"):
if k not in meta: raise PoppyError(f"issuer metadata missing {k}")
return doc, meta
class PersonalAgent:
def __init__(self, client_id):
self.client_id = client_id
self.key = ec.generate_private_key(ec.SECP256R1()) # signs assertions
self.dpop_key = ec.generate_private_key(ec.SECP256R1()) # binds tokens
pub = self.dpop_key.public_key().public_numbers()
self.dpop_jwk = {"kty": "EC", "crv": "P-256",
"x": b64u(pub.x.to_bytes(32, "big")),
"y": b64u(pub.y.to_bytes(32, "big"))}
def jwks(self):
pub = self.key.public_key().public_numbers()
return {"keys": [{"kty": "EC", "crv": "P-256", "alg": "ES256", "use": "sig",
"x": b64u(pub.x.to_bytes(32, "big")),
"y": b64u(pub.y.to_bytes(32, "big"))}]}
def _sign(self, claims, key, headers=None):
return jwt.encode(claims, key, algorithm="ES256", headers=headers)
def dpop_proof(self, method, url, access_token=None, nonce=None):
claims = {"jti": str(uuid.uuid4()), "htm": method, "htu": url, "iat": int(time.time())}
if access_token:
claims["ath"] = b64u(hashlib.sha256(access_token.encode()).digest())
if nonce: claims["nonce"] = nonce
return self._sign(claims, self.dpop_key,
{"typ": "dpop+jwt", "jwk": self.dpop_jwk})
def start_session(self, meta, user_id, scope="poppy:read", session_id=None):
tok = meta["token_endpoint"]; now = int(time.time())
grant = self._sign({"iss": self.client_id, "sub": user_id, "aud": tok,
"iat": now, "exp": now + 60, "jti": str(uuid.uuid4())}, self.key)
client_assertion = self._sign({"iss": self.client_id, "sub": self.client_id,
"aud": tok, "iat": now, "exp": now + 60,
"jti": str(uuid.uuid4())}, self.key)
form = {"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": grant,
"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer",
"client_assertion": client_assertion, "scope": scope}
if session_id: form["session_id"] = session_id
r = requests.post(tok, data=form, headers={"DPoP": self.dpop_proof("POST", tok)}, timeout=10)
if r.status_code == 400 and r.json().get("error") == "invalid_session":
raise PoppyError("session ended; start a new one")
r.raise_for_status()
return r.json()
def call_api(self, session, method, url):
h = {"Authorization": f"DPoP {session['access_token']}",
"DPoP": self.dpop_proof(method, url, session["access_token"])}
return requests.request(method, url, headers=h, timeout=10)
mock_company.py
"""Local stand-in for a company + the agent's metadata host. Plain HTTP, demo only."""
import json, threading, time, hashlib, base64
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import parse_qs
import jwt, requests
from jwt.algorithms import ECAlgorithm
import poppy_agent as pa
COMPANY, AGENT = "127.0.0.1:8765", "127.0.0.1:8766"
CLIENT_ID = f"http://{AGENT}/agent/client.json"
USER_ID = "u_7f3a91c2" # opaque, not derived from PII
SEEN_JTI, SESSIONS = set(), {}
agent = pa.PersonalAgent(CLIENT_ID)
def send(h, code, obj, extra=None):
body = json.dumps(obj).encode()
h.send_response(code); h.send_header("Content-Type", "application/json")
for k, v in (extra or {}).items(): h.send_header(k, v)
h.send_header("Content-Length", str(len(body))); h.end_headers(); h.wfile.write(body)
class Company(BaseHTTPRequestHandler):
def log_message(self, *a): pass
def do_GET(self):
if self.path == "/.well-known/poppy.json":
send(self, 200, {"protocol_version": "0.1",
"organization": {"name": "Acme Outfitters", "domain": COMPANY},
"auth": {"issuer": f"http://{COMPANY}", "direct": {"scopes": ["poppy:read", "poppy:write"]}},
"apis": [{"type": "openapi", "url": f"http://{COMPANY}/api/orders",
"description": "Order lookup"}]})
elif self.path == "/.well-known/oauth-authorization-server":
send(self, 200, {"issuer": f"http://{COMPANY}", "poppy_domains": [COMPANY],
"token_endpoint": f"http://{COMPANY}/oauth/token",
"revocation_endpoint": f"http://{COMPANY}/oauth/revoke"})
elif self.path == "/api/orders":
self.api()
else:
send(self, 404, {})
def verify_dpop(self, proof, method, url, token=None):
hdr = jwt.get_unverified_header(proof)
assert hdr["typ"] == "dpop+jwt"
key = ECAlgorithm(ECAlgorithm.SHA256).from_jwk(json.dumps(hdr["jwk"]))
c = jwt.decode(proof, key, algorithms=["ES256"], options={"verify_aud": False})
assert c["htm"] == method and c["htu"] == url, "htm/htu mismatch"
assert abs(time.time() - c["iat"]) < 60, "stale proof"
assert c["jti"] not in SEEN_JTI, "replayed proof"; SEEN_JTI.add(c["jti"])
if token:
want = pa.b64u(hashlib.sha256(token.encode()).digest())
assert c["ath"] == want, "ath mismatch"
return hdr["jwk"]
def do_POST(self):
if self.path != "/oauth/token": return send(self, 404, {})
f = {k: v[0] for k, v in parse_qs(self.rfile.read(int(self.headers["Content-Length"])).decode()).items()}
tok = f"http://{COMPANY}/oauth/token"
try:
meta = requests.get(CLIENT_ID).json() # fetch agent metadata
jwks = requests.get(meta["jwks_uri"]).json()["keys"][0]
key = ECAlgorithm(ECAlgorithm.SHA256).from_jwk(json.dumps(jwks))
ca = jwt.decode(f["client_assertion"], key, algorithms=["ES256"], audience=tok)
assert ca["iss"] == CLIENT_ID == ca["sub"]
g = jwt.decode(f["assertion"], key, algorithms=["ES256"], audience=tok)
assert g["iss"] == CLIENT_ID and g["jti"] not in SEEN_JTI; SEEN_JTI.add(g["jti"])
jwk = self.verify_dpop(self.headers["DPoP"], "POST", tok)
except Exception as e:
return send(self, 400, {"error": "invalid_grant", "error_description": str(e)})
sid = "ses_" + g["jti"][:8]; at = "at_" + g["jti"][-8:]
SESSIONS[at] = {"user": g["sub"], "jwk": jwk, "scope": f.get("scope", "poppy:read")}
send(self, 200, {"access_token": at, "token_type": "DPoP", "expires_in": 300,
"scope": SESSIONS[at]["scope"], "session_id": sid, "signed_in": False})
def api(self):
auth = self.headers.get("Authorization", "")
tok = auth.split(" ", 1)[1] if auth.startswith("DPoP ") else None
if tok not in SESSIONS:
return send(self, 401, {}, {"WWW-Authenticate": 'DPoP error="invalid_token"'})
try:
jwk = self.verify_dpop(self.headers["DPoP"], "GET", f"http://{COMPANY}/api/orders", tok)
assert jwk == SESSIONS[tok]["jwk"], "token is bound to a different key"
except Exception as e:
return send(self, 401, {"error": str(e)}, {"WWW-Authenticate": 'DPoP error="invalid_token"'})
if not SESSIONS[tok].get("signed_in_user"):
return send(self, 403, {"error": "sign_in_required"},
{"WWW-Authenticate": 'DPoP error="sign_in_required"'})
send(self, 200, {"orders": []})
class AgentHost(BaseHTTPRequestHandler):
def log_message(self, *a): pass
def do_GET(self):
if self.path == "/agent/client.json":
send(self, 200, {"client_id": CLIENT_ID, "jwks_uri": f"http://{AGENT}/agent/jwks.json",
"redirect_uris": [f"http://{AGENT}/agent/callback"],
"token_endpoint_auth_method": "private_key_jwt"})
elif self.path == "/agent/jwks.json":
send(self, 200, agent.jwks())
else: send(self, 404, {})
def serve(handler, port):
s = HTTPServer(("127.0.0.1", port), handler)
threading.Thread(target=s.serve_forever, daemon=True).start()
demo.py
import json, mock_company as m, poppy_agent as pa
pa.ALLOW_HTTP = True
m.serve(m.Company, 8765); m.serve(m.AgentHost, 8766)
doc, meta = pa.discover(m.COMPANY)
print("discovered:", doc["organization"]["name"], "| scopes:", doc["auth"]["direct"]["scopes"])
print("token endpoint:", meta["token_endpoint"])
s = m.agent.start_session(meta, m.USER_ID, "poppy:read")
print("session:", {k: s[k] for k in ("token_type", "scope", "session_id", "signed_in")})
r = m.agent.call_api(s, "GET", doc["apis"][0]["url"])
print("API call as guest ->", r.status_code, r.headers.get("WWW-Authenticate"), r.json())
# attack 1: replay the same DPoP proof
proof = m.agent.dpop_proof("GET", doc["apis"][0]["url"], s["access_token"])
h = {"Authorization": f"DPoP {s['access_token']}", "DPoP": proof}
import requests
print("first use ->", requests.get(doc["apis"][0]["url"], headers=h).status_code)
print("replay ->", requests.get(doc["apis"][0]["url"], headers=h).status_code)
# attack 2: stolen token, attacker's own key
thief = pa.PersonalAgent(m.CLIENT_ID)
print("stolen tok ->", thief.call_api(s, "GET", doc["apis"][0]["url"]).status_code)
# bad discovery
m.COMPANY_BAK = m.COMPANY
try: pa.discover("127.0.0.1:8766")
except Exception as e: print("bad domain ->", type(e).__name__, str(e)[:70])
Step 4: run it and read the output
PYTHONPATH=. python3 demo.py
This is the real output from my run (session IDs vary):
discovered: Acme Outfitters | scopes: ['poppy:read', 'poppy:write']
token endpoint: http://127.0.0.1:8765/oauth/token
session: {'token_type': 'DPoP', 'scope': 'poppy:read', 'session_id': 'ses_ddb82e39', 'signed_in': False}
API call as guest -> 403 DPoP error="sign_in_required" {'error': 'sign_in_required'}
first use -> 403
replay -> 401
stolen tok -> 401
bad domain -> HTTPError 404 Client Error: Not Found for url: http://127.0.0.1:8766/.well-known
Line by line: discovery works, and the session comes back as signed_in: False. Calling the orders API as a guest gets 403 sign_in_required, which is exactly the error the spec defines for this case, delivered in a WWW-Authenticate header. The agent's next move in a real deployment would be to start a sign-in (direct, device, or mediated) and ask the user to approve.
The two attack lines matter more. Replaying a captured proof is rejected with 401 because the jti was already seen. Presenting a valid token from a different key (what a thief would do) is also 401 because the token is bound to the original agent's key. The last line points discovery at a host that is not a Poppy company; it fails closed.
Step 5: what to add before this is real
- Sign-in. Implement
auth.direct: authorization code with PKCE, sendsession_idat code exchange, and checkstateand theissresponse parameter (RFC 9207). Then store the refresh token as the Account Token and use it only at the token endpoint. - DPoP nonces. A company may answer with
use_dpop_nonce. Catch that error, read the nonce the server supplies, and retry once with it in the proof. - Rate limits. Honor HTTP 429 and
Retry-After. Do not loop. - MCP APIs. These use Bearer tokens instead of DPoP, with the
resourceparameter set to the MCP URL (RFC 8707). Do not reuse your DPoP code path for them. - Conversations. If poppy.json lists an
agent.protocolsentry of typepoppy, you can start a conversation, post messages, and read events with a cursor. Never act ontext-deltaevents from a stream; they are partial.
Common pitfalls
- Trusting poppy.json alone. Anyone can host a JSON file. The issuer cross-check (
issuerequality andpoppy_domains) is the actual trust anchor. Skipping it is the most likely bug in early agents. - URL mismatch in the DPoP proof.
htumust match the request URL exactly. A trailing slash, a different host casing, or a query string you forgot to account for gives youinvalid_dpop_proofand a confusing afternoon. - Reusing a
jti. Generate a fresh UUID for every assertion and every proof. Servers are expected to remember them. - Clock skew. The browser assertion in the spec may live at most 60 seconds past
iat, and my mock rejects proofs older than 60 seconds. Keep your clock synced. - Putting tokens in URLs. The spec forbids it. Logs and referrers leak URLs.
- Treating the demo as secure. It serves plain HTTP on localhost and keeps state in memory. The ALLOW_HTTP flag must never ship.
- Assuming the spec is stable. It is Draft 0.1. Pin to the version you built against and watch the changelog before relying on any field name.
Quick reference
| Task | Spec element |
|---|---|
| Find a company's offer | GET /.well-known/poppy.json |
| Verify the issuer | GET {issuer}/.well-known/oauth-authorization-server, match issuer and poppy_domains |
| Agent identity | client_id = HTTPS URL with jwks_uri, redirect_uris, private_key_jwt |
| Start a session | JWT bearer grant (RFC 7523) + client assertion + DPoP |
| Renew a session | Same request plus session_id |
| Call an OpenAPI API | Authorization: DPoP token, DPoP proof with ath |
| Call an MCP API | Bearer token, resource = MCP url |
| Scopes | poppy:read, poppy:write, company custom scopes |
| Auth failures | invalid_token (401), sign_in_required (403), insufficient_scope (403) |
Why this is worth learning now
A lot of agent traffic today is a model driving a headless browser and hoping the site does not block it. Poppy is one proposal for a cleaner contract, with the company deciding what agents may do and the user granting read or write access per account. Whether it wins is open: the reference implementation is still described as forthcoming, and a community demo on Cloudflare Workers covers only discovery and direct sign-in. But the building blocks (well-known discovery, JWT bearer grants, DPoP) are standard and you will meet them elsewhere, so the code above is reusable even if the protocol changes.
Next steps
- Add the direct sign-in flow with PKCE to the agent and a matching authorize endpoint to the mock.
- Add
use_dpop_noncehandling on both sides and test the retry. - Read the spec's conversation section and build a small client for the five conversation endpoints.
- Wrap your agent's tool calls so every company call goes through one function that handles 401, 403 and 429 consistently.
- Re-run your tests when v0.1 final or the reference implementation lands.
Sources: the Personal Agent Protocol Draft 0.1 spec at personalagentprotocol.org/docs/spec; Sierra's announcement post, 'Introducing the Personal Agent Protocol'; RFC 7523 (JWT bearer grant), RFC 9449 (DPoP), RFC 9207, RFC 8707.
Comments
Be the first to comment
Found this useful?
Get new AI guides for builders by email. Free.
Join 3,604 newsletter subscribers.