Skip to content
MCP Events: Build a Signed-Webhook Server in Python — ContentBuffer guide

MCP Events: Build a Signed-Webhook Server in Python

K
Kodetra Technologies··13 min read Intermediate

Summary

OpenAI shipped MCP Events at DevDay. Build, sign and harden a server that pushes events to agents.

Until now, an MCP server could only answer when an agent asked. If a reviewer left a comment on a document at 3 a.m., the agent found out the next time it happened to poll. At DevDay on October 2, OpenAI added MCP Events to ChatGPT plugins, and the direction flips: your server tells the agent when something changes, through a signed webhook, and the agent wakes up and reacts.

This guide builds the server side from scratch in Python with nothing but the standard library. You will implement the three event methods, the signed challenge handshake, Standard Webhooks signing, retries, subscription refresh, and the access re-checks that WorkOS argues are the real security story. Everything below was run end to end, and the output shown is real.

One caveat up front: MCP Events requires MCP protocol version 2026-07-28, ChatGPT supports webhook delivery only (no polling, no streaming, no terminated notifications), and the spec is young. Check the official MCP Events page before shipping.

Prerequisites

  • Python 3.10 or newer. No third-party packages are needed.
  • Basic familiarity with MCP (tools, JSON-RPC over HTTP).
  • Comfort reading HMAC signatures. If you have verified a Stripe or GitHub webhook, you have the idea.
  • For production: a public HTTPS endpoint, a real OAuth layer, and a database. The demo uses in-memory dicts on purpose.

How MCP Events actually works

There are three roles. Your MCP server owns the data and defines events. The subscriber (ChatGPT) calls your server to subscribe and gives you a callback URL plus a signing secret. Your server then POSTs each event to that callback, signed, and the subscriber verifies the signature.

MethodWhat it does
server/discoverAdvertises capabilities.events and supported protocol versions
events/listDescribes each event: name, delivery modes, inputSchema (filters), payloadSchema
events/subscribeCreates or refreshes a subscription; returns id and refreshBefore
events/unsubscribeRemoves it; must be idempotent

Two details shape the whole design. First, the secret comes from the subscriber, not from you. It is whsec_ plus a base64 string that must decode to 24 to 64 bytes, and you store it and sign with it. Second, a subscription is a standing authorization. It outlives the access token that created it, which is why the TTL you grant is effectively your revocation window.

Step 1: Sign and verify like Standard Webhooks

Events are signed with Standard Webhooks. The signed string is {webhook-id}.{webhook-timestamp}.{body}, the algorithm is HMAC-SHA256 with the decoded secret bytes as the key, and the header value looks like v1,<base64>. Put this in signing.py:

import base64, hashlib, hmac, time

def decode_secret(secret: str) -> bytes:
    if not secret.startswith("whsec_"):
        raise ValueError("secret must start with whsec_")
    key = base64.b64decode(secret[len("whsec_"):], validate=True)
    if not 24 <= len(key) <= 64:
        raise ValueError("secret must decode to 24-64 bytes")
    return key

def sign(key: bytes, msg_id: str, ts: int, body: bytes) -> str:
    signed = f"{msg_id}.{ts}.".encode() + body
    return "v1," + base64.b64encode(hmac.new(key, signed, hashlib.sha256).digest()).decode()

def verify(key: bytes, msg_id: str, ts_header: str, sig_header: str, body: bytes, tolerance=300) -> bool:
    try:
        ts = int(ts_header)
    except (TypeError, ValueError):
        return False
    if abs(time.time() - ts) > tolerance:
        return False
    expected = sign(key, msg_id, ts, body)
    # header may hold several space-separated signatures
    return any(hmac.compare_digest(expected, s) for s in (sig_header or "").split(" "))

The 300-second tolerance is the five-minute replay window from the spec. compare_digest avoids timing leaks. Notice that verify works on raw bytes. That matters in the next step.

Step 2: The server, method by method

The server is one file. I will walk through the interesting parts and then show it whole.

Discovery and listing

server/discover returns capabilities.events as an empty object, plus the protocol version. events/list returns one event, comment.created, whose inputSchema requires a document_id. Filters matter: subscribers should only receive events for the documents they asked about.

Subscribing safely

A subscribe call does six things in order: check the event exists, check the user is allowed to see that document, decode and validate the secret, validate the callback URL, run the challenge handshake, and store the subscription. Skipping any of these is how you end up pushing someone's data to the wrong place.

  • Deterministic IDs. The subscription ID is a truncated SHA-256 of principal, callback URL, event name and canonicalized arguments. A second subscribe with the same inputs is a refresh, not a duplicate, and it skips the challenge.
  • Capped TTL. We grant at most 24 hours and treat ttlMs: null (infinite) as 24 hours. Never grant more than requested, but you may grant less.
  • Challenge handshake. Before activating, POST {"type":"verification","challenge":"..."}, signed, to the callback. The receiver must echo the challenge in a 2xx response. Failure returns JSON-RPC error -32015.
  • SSRF guard. HTTPS only, resolve the hostname and reject private, loopback, link-local and reserved addresses, and never follow redirects. The demo has an ALLOW_LOCAL switch so we can test on localhost; it must be off in production.

Emitting events

emit() builds the body once and sends those exact bytes to every matching subscriber. It never parses and re-serializes, because a changed byte invalidates the signature. Each attempt gets a fresh timestamp and signature, but the eventId stays the same across retries so receivers can deduplicate. A 410 or 413 is never retried, and a 410 deletes the subscription.

Here is the full server.py:

"""MCP Events server (stdlib only). Run: python server.py"""
import hashlib, ipaddress, json, os, socket, threading, time, uuid
import urllib.request, urllib.error
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse
from signing import decode_secret, sign

PROTOCOL = "2026-07-28"
MAX_TTL_MS = 24 * 3600 * 1000          # our revocation window
ALLOW_LOCAL = os.environ.get("ALLOW_LOCAL") == "1"   # demo only!
TOKENS = {"tok_alice": "alice", "tok_bob": "bob"}     # bearer -> principal
DOC_ACL = {"doc_123": {"alice"}, "doc_999": {"bob"}}  # who may watch what

SUBS = {}   # sub_id -> dict
LOCK = threading.Lock()

EVENTS = [{
    "name": "comment.created",
    "description": "A new review comment was added to the specified document.",
    "delivery": ["webhook"],
    "inputSchema": {"type": "object", "required": ["document_id"],
                    "properties": {"document_id": {"type": "string"}}},
    "payloadSchema": {"type": "object", "properties": {
        "document_id": {"type": "string"}, "comment_id": {"type": "string"}}},
}]

class RpcError(Exception):
    def __init__(self, code, msg): self.code, self.msg = code, msg

def check_url(url):
    u = urlparse(url)
    if not ALLOW_LOCAL and u.scheme != "https":
        raise RpcError(-32602, "callback must be https")
    host = u.hostname or ""
    for info in socket.getaddrinfo(host, u.port or 443, proto=socket.IPPROTO_TCP):
        ip = ipaddress.ip_address(info[4][0])
        if not ALLOW_LOCAL and (ip.is_private or ip.is_loopback or ip.is_link_local
                                or ip.is_reserved or ip.is_multicast):
            raise RpcError(-32602, "callback resolves to a non-public address")

def sub_id(principal, url, name, args):
    canon = json.dumps(args, sort_keys=True, separators=(",", ":"))
    return "sub_" + hashlib.sha256(f"{principal}|{url}|{name}|{canon}".encode()).hexdigest()[:16]

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *a, **k): return None
OPENER = urllib.request.build_opener(NoRedirect)

def post_signed(url, key, msg_id, body: bytes, sid):
    ts = int(time.time())                     # fresh on every attempt
    req = urllib.request.Request(url, data=body, method="POST", headers={
        "Content-Type": "application/json", "webhook-id": msg_id,
        "webhook-timestamp": str(ts), "webhook-signature": sign(key, msg_id, ts, body),
        "X-MCP-Subscription-Id": sid})
    try:
        with OPENER.open(req, timeout=5) as r:
            return r.status, r.read()
    except urllib.error.HTTPError as e:
        return e.code, e.read()

def handle(method, params, principal):
    if method == "server/discover":
        return {"resultType": "complete", "supportedVersions": [PROTOCOL],
                "capabilities": {"tools": {}, "events": {}}}
    if method == "events/list":
        return {"events": EVENTS}
    if method in ("events/subscribe", "events/unsubscribe"):
        name, args = params["name"], params.get("arguments", {})
        if name not in {e["name"] for e in EVENTS}:
            raise RpcError(-32602, f"unknown event {name}")
        d = params["delivery"]
        if d.get("mode") != "webhook":
            raise RpcError(-32602, "only webhook delivery")
        sid = sub_id(principal, d["url"], name, args)
        if method == "events/unsubscribe":
            with LOCK: SUBS.pop(sid, None)       # idempotent
            return {}
        if principal not in DOC_ACL.get(args.get("document_id"), set()):
            raise RpcError(-32003, "not authorized for this document")
        try: key = decode_secret(d["secret"])
        except ValueError as e: raise RpcError(-32602, str(e))
        check_url(d["url"])
        ttl = params.get("ttlMs", MAX_TTL_MS)
        ttl = MAX_TTL_MS if ttl is None else min(ttl, MAX_TTL_MS)  # refuse infinite
        with LOCK: existing = SUBS.get(sid)
        if not existing:                          # challenge only on first create
            challenge = uuid.uuid4().hex
            body = json.dumps({"type": "verification", "challenge": challenge}).encode()
            try: status, resp = post_signed(d["url"], key, "vrf_" + uuid.uuid4().hex, body, sid)
            except Exception: raise RpcError(-32015, "challenge_failed: timeout")
            ok = 200 <= status < 300 and json.loads(resp or b"{}").get("challenge") == challenge
            if not ok: raise RpcError(-32015, "challenge_failed")
        refresh = time.time() + ttl / 1000
        with LOCK:
            SUBS[sid] = {"principal": principal, "name": name, "args": args, "url": d["url"],
                         "key": key, "expires": refresh, "reverified_at": time.time()}
        return {"id": sid, "refreshBefore": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(refresh)),
                "cursor": None, "truncated": False}
    raise RpcError(-32601, "method not found")

def emit(name, data):
    """Fan an event out to matching subscriptions. Returns list of (sub_id, status)."""
    results = []
    event_id = "evt_" + uuid.uuid4().hex[:10]
    body = json.dumps({"eventId": event_id, "name": name,
        "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
        "data": data, "cursor": None}, separators=(",", ":")).encode()  # serialize ONCE
    if len(body) > 262_144: raise ValueError("event > 256 KiB")
    with LOCK: subs = list(SUBS.items())
    for sid, s in subs:
        if s["name"] != name or s["args"].get("document_id") != data.get("document_id"): continue
        if s["expires"] < time.time(): continue
        if data.get("document_id") and s["principal"] not in DOC_ACL.get(data["document_id"], set()):
            with LOCK: SUBS.pop(sid, None); continue          # access revoked -> drop
        status = None
        for attempt in range(4):
            try: status, _ = post_signed(s["url"], s["key"], event_id, body, sid)
            except Exception: status = 599
            if 200 <= status < 300 or status in (410, 413): break   # never retry these
            time.sleep(0.2 * 2 ** attempt)
        if status == 410:
            with LOCK: SUBS.pop(sid, None)
        results.append((sid, status))
    return results

class H(BaseHTTPRequestHandler):
    def log_message(self, *a): pass
    def do_POST(self):
        n = int(self.headers.get("Content-Length", 0))
        req = json.loads(self.rfile.read(n))
        principal = TOKENS.get((self.headers.get("Authorization") or "").removeprefix("Bearer "))
        if not principal:
            self.send_response(401); self.end_headers(); return
        try: out = {"jsonrpc": "2.0", "id": req.get("id"),
                    "result": handle(req["method"], req.get("params", {}), principal)}
        except RpcError as e:
            out = {"jsonrpc": "2.0", "id": req.get("id"), "error": {"code": e.code, "message": e.msg}}
        b = json.dumps(out).encode()
        self.send_response(200); self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)

def serve(port=8765):
    srv = ThreadingHTTPServer(("127.0.0.1", port), H)
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    return srv

Step 3: The receiver

This is the code on the other side of the wire. If you are the plugin author you will not write it (ChatGPT does), but writing it once is the fastest way to understand every check, and it doubles as your test double.

"""Webhook receiver (what ChatGPT-side / your agent runs)."""
import json, threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from signing import verify

SEEN, INBOX = set(), []
def make_handler(key):
    class R(BaseHTTPRequestHandler):
        def log_message(self, *a): pass
        def _reply(self, code, obj=None):
            b = json.dumps(obj or {}).encode()
            self.send_response(code); self.send_header("Content-Length", str(len(b)))
            self.end_headers(); self.wfile.write(b)
        def do_POST(self):
            n = int(self.headers.get("Content-Length", 0))
            if n > 262_144: return self._reply(413)
            raw = self.rfile.read(n)                      # raw bytes, never re-serialized
            h = self.headers
            if not verify(key, h.get("webhook-id"), h.get("webhook-timestamp"),
                          h.get("webhook-signature"), raw):
                return self._reply(401, {"error": "bad signature"})
            msg = json.loads(raw)
            if msg.get("type") == "verification":
                return self._reply(200, {"challenge": msg["challenge"]})
            if h["webhook-id"] in SEEN:                   # idempotent
                return self._reply(200, {"duplicate": True})
            SEEN.add(h["webhook-id"]); INBOX.append(msg)
            self._reply(200)
    return R

def serve(key, port=8766):
    srv = ThreadingHTTPServer(("127.0.0.1", port), make_handler(key))
    threading.Thread(target=srv.serve_forever, daemon=True).start()
    return srv

Four rules live here: reject bodies over 256 KiB (262,144 bytes), verify against the raw bytes, echo the challenge for verification messages, and deduplicate on webhook-id. The spec says events can arrive out of order, so your downstream writes should be idempotent too.

Step 4: Run it and read the output

The demo script starts both servers on localhost, then walks the whole lifecycle including the failure cases. Run python3 demo.py:

import base64, json, os, time, urllib.request
os.environ["ALLOW_LOCAL"] = "1"
import server, receiver
from signing import decode_secret

SECRET = "whsec_" + base64.b64encode(os.urandom(32)).decode()
server.serve(8765); receiver.serve(decode_secret(SECRET), 8766)

def rpc(method, params, token="tok_alice", i=[0]):
    i[0] += 1
    req = urllib.request.Request("http://127.0.0.1:8765/mcp", method="POST",
        data=json.dumps({"jsonrpc": "2.0", "id": i[0], "method": method, "params": params}).encode(),
        headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"})
    return json.load(urllib.request.urlopen(req))

sub = {"name": "comment.created", "arguments": {"document_id": "doc_123"},
       "delivery": {"mode": "webhook", "url": "http://127.0.0.1:8766/cb", "secret": SECRET}}
print("discover   ->", rpc("server/discover", {})["result"]["capabilities"])
print("list       ->", [e["name"] for e in rpc("events/list", {})["result"]["events"]])
r = rpc("events/subscribe", sub); print("subscribe  ->", r["result"])
r2 = rpc("events/subscribe", sub); print("refresh    ->", r2["result"]["id"] == r["result"]["id"], "(same id)")
print("bob/doc_123->", rpc("events/subscribe", sub, "tok_bob")["error"])
bad = json.loads(json.dumps(sub)); bad["delivery"]["secret"] = "whsec_c2hvcnQ="
print("short key  ->", rpc("events/subscribe", bad)["error"])
print("emit       ->", server.emit("comment.created", {"document_id": "doc_123", "comment_id": "c1", "text": "Add rollout dates?"}))
print("emit again ->", server.emit("comment.created", {"document_id": "doc_123", "comment_id": "c2", "text": "Typo in section 2"}))
print("other doc  ->", server.emit("comment.created", {"document_id": "doc_999", "comment_id": "c3"}))
print("inbox      ->", [(m["eventId"], m["data"]["comment_id"]) for m in receiver.INBOX])
# forged delivery
import signing
body = b'{"eventId":"evt_forged","name":"comment.created","data":{}}'
req = urllib.request.Request("http://127.0.0.1:8766/cb", data=body, method="POST", headers={
    "webhook-id": "evt_forged", "webhook-timestamp": str(int(time.time())),
    "webhook-signature": "v1,AAAA", "X-MCP-Subscription-Id": "x"})
try: urllib.request.urlopen(req)
except Exception as e: print("forged     ->", e)
# replay with stale timestamp
key = decode_secret(SECRET); old = int(time.time()) - 900
req = urllib.request.Request("http://127.0.0.1:8766/cb", data=body, method="POST", headers={
    "webhook-id": "evt_old", "webhook-timestamp": str(old),
    "webhook-signature": signing.sign(key, "evt_old", old, body)})
try: urllib.request.urlopen(req)
except Exception as e: print("stale ts   ->", e)
# ACL revoked -> next emit drops sub
server.DOC_ACL["doc_123"].discard("alice")
print("revoked    ->", server.emit("comment.created", {"document_id": "doc_123", "comment_id": "c4"}), "subs left:", len(server.SUBS))
# unsubscribe idempotent
print("unsub      ->", rpc("events/unsubscribe", sub), rpc("events/unsubscribe", sub))
# SSRF guard
server.DOC_ACL["doc_123"].add("alice"); server.ALLOW_LOCAL = False
s3 = json.loads(json.dumps(sub)); s3["delivery"]["url"] = "https://127.0.0.1/cb"
print("ssrf       ->", rpc("events/subscribe", s3)["error"])

Real output from that run:

discover   -> {'tools': {}, 'events': {}}
list       -> ['comment.created']
subscribe  -> {'id': 'sub_9e47ac0a63fddb62', 'refreshBefore': '2026-10-06T15:05:00Z', 'cursor': None, 'truncated': False}
refresh    -> True (same id)
bob/doc_123-> {'code': -32003, 'message': 'not authorized for this document'}
short key  -> {'code': -32602, 'message': 'secret must decode to 24-64 bytes'}
emit       -> [('sub_9e47ac0a63fddb62', 200)]
emit again -> [('sub_9e47ac0a63fddb62', 200)]
other doc  -> []
inbox      -> [('evt_5cc5058afd', 'c1'), ('evt_cbdef5f45a', 'c2')]
forged     -> HTTP Error 401: Unauthorized
stale ts   -> HTTP Error 401: Unauthorized
revoked    -> [] subs left: 0
unsub      -> {... 'result': {}} {... 'result': {}}
ssrf       -> {'code': -32602, 'message': 'callback resolves to a non-public address'}

Read it line by line. Subscribing twice returned the same ID, so refresh works. Bob was refused for Alice's document. A key that decodes to 6 bytes was refused. Two comments reached the inbox, a forged signature and a 15-minute-old replay were both rejected with 401, and once Alice lost access the next emit dropped her subscription instead of leaking data.

A worked example: a review-comment agent

Suppose your product is a document editor and you want a ChatGPT agent to draft replies whenever a reviewer comments. Without events, you would build a polling tool and hope the agent calls it. With events, the flow is:

  • A reviewer posts a comment. Your app calls emit("comment.created", {...}).
  • The payload carries ids and a short preview, not the whole record. The agent then calls a read tool, which re-checks authorization at call time.
  • ChatGPT receives the signed event, verifies it, and starts the agent with that context.
  • The agent calls your reply_to_comment tool. That write should be idempotent, keyed on comment_id, because delivery can repeat or arrive out of order.

Keep payloads small. The WorkOS analysis makes the point that anything you push can end up in an agent's context, so a payload full of free text is an injection channel. Ids plus a pointer is safer, and the pointer forces a fresh access check.

Common pitfalls and gotchas

  • Re-serializing the body. Parsing JSON and dumping it again changes whitespace and key order, and the signature breaks. Serialize once, sign those bytes, send those bytes. The receiver must also hash the raw request body, not json.dumps(request.json).
  • Treating the secret as yours. You do not generate it. The subscriber supplies whsec_...; strip the prefix, base64-decode, and check 24 to 64 bytes. Using the literal string as the HMAC key gives signatures that never verify.
  • Granting infinite subscriptions. A subscription created under a one-hour token can keep pushing data for months. ChatGPT does not enforce a maximum TTL, so you must. Refuse ttlMs: null and re-verify access on a schedule (WorkOS suggests sweeping every 15 minutes).
  • Checking access only at subscribe time. The spec says you must check at subscribe and should re-check during the subscription. In the demo, emit() checks the ACL on each delivery. Wire the same idea to your offboarding flow so deleting a user deletes their subscriptions.
  • No termination signal. ChatGPT does not support the signed terminated envelope, so a revoked subscription can only be noticed when the refresh fails. Short TTLs are your only lever.
  • SSRF through the callback URL. Resolve and check at connection time, every time, for both the challenge and deliveries. Never follow redirects. A cached DNS check is bypassable by rebinding.
  • Retrying the wrong errors. Backoff on 5xx and timeouts. Do not retry 410 (receiver says the subscription is gone) or 413 (your body is too big; it will never fit). Keep the same eventId but a fresh timestamp and signature on each attempt, or the receiver will reject old timestamps.
  • Forgetting persistence. The demo keeps subscriptions in a dict. In production, store them keyed on principal, URL, name and arguments so a restart does not silently cancel everyone. Store the secret in a secrets manager, not a plain column.
  • Assuming ordering. The spec states that events can arrive out of order. Include enough in the payload (or the read tool) for the agent to tell which state is newer.

Quick reference

ItemValue
Protocol version2026-07-28
Capabilitycapabilities.events in server/discover
Deliverywebhook only (ChatGPT)
Secret formatwhsec_ + base64, decodes to 24 to 64 bytes
Signed stringwebhook-id.webhook-timestamp.body
Signature headerwebhook-signature: v1,<base64 HMAC-SHA256>
Other headerswebhook-id, webhook-timestamp, X-MCP-Subscription-Id
Replay window5 minutes
Max body256 KiB (262,144 bytes), one event per request
Challenge failureJSON-RPC error -32015
Do not retryHTTP 410, HTTP 413
Unsubscribeidempotent, returns empty result

Next steps

  • Replace the in-memory dict with a database, and add a background sweeper that re-verifies access and expires old subscriptions.
  • Put the JSON-RPC handler behind your real OAuth layer and derive the principal from the token's sub claim.
  • Add a second event type with its own filter schema, and write a contract test that runs the receiver against your server in CI.
  • Read the WorkOS analysis on why a subscription is a credential, then decide your TTL and re-verification interval deliberately.

Sources: the OpenAI MCP Events documentation, the Standard Webhooks spec, the InfoQ DevDay 2026 recap, and the WorkOS write-up linked above.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,605 newsletter subscribers.

Also get