MCP Events Is a Webhook Now: Testing `events/subscribe` Callbacks on Localhost

MCP Events Is a Webhook Now: Testing `events/subscribe` Callbacks on Localhost

For most of its life, the Model Context Protocol (MCP) worked in one direction: the client asked and the server answered. MCP Events adds the other direction. A client can now register an HTTPS callback URL, and an MCP server will POST signed events to it when something happens upstream, such as a new incident, comment or email.

If you've built a Stripe or GitHub webhook handler, much of this will feel familiar. Three parts deserve their own tests: endpoint verification, subscription renewal and out-of-order delivery. This guide covers all three, with a local receiver, a fake sender and a tunnel for the real thing.

Is MCP Events Beta or Final?

Both labels are correct, because they describe different things:

  • SEP-3415, the design proposal, is Final.
  • The extension, io.modelcontextprotocol/events, is in Beta.

The official overview says exactly that, and the Beta specification warns that breaking changes are expected to be rare and will be documented. So don't call the extension "Final". It requires MCP protocol revision 2026-07-28 or later.

Adoption started before the Beta text did. ChatGPT has reportedly supported webhook mode since September 29, and OpenAI's documentation still says it implements the draft specification. That gap matters when you test, as you'll see below. Vercel Connect also documents webhook support built against the draft.

How events/subscribe Works

MCP Events defines three delivery modes: poll (events/poll), push (events/stream) and webhook (events/subscribe). Each event type advertises which ones it supports. This article is about webhooks.

A subscribe request looks like this (protocol _meta omitted):

{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "events/subscribe",
  "params": {
    "name": "incident.created",
    "arguments": { "severity": "P1" },
    "delivery": {
      "mode": "webhook",
      "url": "https://mcp-hooks.example.com/hooks/mcp",
      "secret": "whsec_<base64 of 24 to 64 random bytes>"
    },
    "cursor": null,
    "ttlMs": 3600000
  }
}

And the response:

{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "resultType": "complete",
    "id": "sub_a3f1c8e2b0d49f7e",
    "refreshBefore": "2026-12-04T11:00:00Z",
    "cursor": null,
    "truncated": false
  }
}

Several rules shape your test setup:

  • The client generates the secret, never the server.
  • The callback must be https. A plain http://localhost URL is rejected with InvalidParams.
  • The call must be authenticated. Unauthenticated servers can offer poll and push, but not webhooks.
  • Identity is (principal, delivery.url, name, arguments). Change any one and you have a different subscription.
  • Over Streamable HTTP, the request also needs an Mcp-Name header matching the event name.

Each delivery is a POST with webhook-id, webhook-timestamp, webhook-signature and X-MCP-Subscription-Id headers, following Standard Webhooks:

{
  "eventId": "evt_789",
  "name": "incident.created",
  "timestamp": "2026-12-04T10:00:00Z",
  "data": { "incidentId": "INC-1234", "severity": "P1" },
  "cursor": null
}

Why Localhost Needs a Tunnel

The specification tells servers to guard against server-side request forgery (SSRF). They should reject callback URLs that resolve to non-public addresses, including loopback and private ranges, check the IP at delivery time, and refuse to follow redirects. A server may be explicitly configured to allow local targets, but don't weaken that guard just to test. Give your receiver a public HTTPS URL instead.

Which piece you tunnel depends on what you're building:

You're building Runs locally Needs a public URL
A client or gateway that receives events Webhook receiver The receiver
An MCP server for ChatGPT MCP server The MCP endpoint (ChatGPT supplies the callback URL)
Your server's delivery logic Server and test receiver The receiver, if your SSRF guard is on

With InstaTunnel:

npm install -g instatunnel
instatunnel 8787 --subdomain mcp-hooks

Use the HTTPS URL it prints, plus /hooks/mcp, as delivery.url.

A stable subdomain matters more here than usual. Because the URL is part of the subscription key, a random hostname on every restart creates a new subscription and leaves the old one sending to a dead address until it expires. InstaTunnel's free plan currently lists reserved subdomains for signed-in users, 24-hour sessions and 2,000 requests per day. Keep an eye on that last figure if you load-test.

Don't put Basic Auth or a tunnel password in front of the callback path. The extension defines HMAC as the only authentication between server and endpoint, so a server has no way to send your extra credentials.

A Minimal Local Receiver

This Node.js receiver has no dependencies. It verifies the raw body, answers the verification challenge, deduplicates, and writes to disk before acknowledging. Save it as receiver.mjs:

import http from "node:http";
import crypto from "node:crypto";
import fs from "node:fs";

const INBOX = "inbox.jsonl";
const MAX_BODY = 256 * 1024;
// Secrets you've put in events/subscribe (comma-separated while rotating)
const secrets = (process.env.MCP_WEBHOOK_SECRETS ?? "").split(",").filter(Boolean);
if (!secrets.length) throw new Error("Set MCP_WEBHOOK_SECRETS");

// Reload dedupe keys so a restart doesn't reprocess old messages
const seen = new Set();
if (fs.existsSync(INBOX)) {
  for (const line of fs.readFileSync(INBOX, "utf8").split("\n").filter(Boolean)) {
    seen.add(JSON.parse(line).key);
  }
}

function verify(headers, raw) {
  const id = headers["webhook-id"];
  const ts = headers["webhook-timestamp"];
  const sigs = headers["webhook-signature"];
  if (!id || !ts || !sigs || !headers["x-mcp-subscription-id"]) return false;
  const age = Math.abs(Date.now() / 1000 - Number(ts));
  if (!(age <= 300)) return false; // also rejects non-numeric values

  return secrets.some((secret) => {
    const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
    const expected = Buffer.from(
      "v1," + crypto.createHmac("sha256", key).update(`${id}.${ts}.`).update(raw).digest("base64"),
    );
    return sigs.split(" ").some((s) => {
      const got = Buffer.from(s);
      return got.length === expected.length && crypto.timingSafeEqual(got, expected);
    });
  });
}

function persist(record) {
  const fd = fs.openSync(INBOX, "a");
  fs.writeSync(fd, JSON.stringify(record) + "\n");
  fs.fsyncSync(fd); // on disk before we say 2xx
  fs.closeSync(fd);
}

http.createServer((req, res) => {
  if (req.method !== "POST" || req.url !== "/hooks/mcp") return res.writeHead(404).end();
  const chunks = [];
  let size = 0;
  req.on("data", (c) => {
    size += c.length;
    if (size <= MAX_BODY) chunks.push(c);
  });
  req.on("end", () => {
    if (size > MAX_BODY) return res.writeHead(413).end();
    const raw = Buffer.concat(chunks); // exact bytes, never re-serialized
    if (!verify(req.headers, raw)) return res.writeHead(401).end();

    try {
      const body = JSON.parse(raw);
      if (body.type === "verification") {
        res.writeHead(200, { "Content-Type": "application/json" });
        return res.end(JSON.stringify({ challenge: body.challenge }));
      }
      const sub = req.headers["x-mcp-subscription-id"];
      const key = `${sub}:${req.headers["webhook-id"]}`;
      if (!seen.has(key)) {
        persist({ key, sub, body });
        seen.add(key);
        console.log("accepted", sub, body.type ?? body.eventId, body.timestamp ?? "");
      } else {
        console.log("duplicate", key);
      }
      res.writeHead(204).end();
    } catch (err) {
      console.error(err);
      res.writeHead(503).end(); // retryable
    }
  });
}).listen(8787, "127.0.0.1", () => console.log("listening on :8787"));

Generate a secret, start the receiver, and use the same secret in your subscribe call:

export MCP_WEBHOOK_SECRETS="whsec_$(openssl rand -base64 32)"
node receiver.mjs

This is a test harness, not production code. It tries every configured secret and ignores which subscription each belongs to. A real receiver should bind each secret to its subscription ID, return 503 or 425 for an event whose ID it can't route yet, and keep its inbox in a database.

Test 1: Endpoint Verification

A signing secret stops forged events from being trusted, but it doesn't stop someone subscribing your URL and flooding it. So a server must confirm the endpoint wants deliveries before sending any. The usual method is a challenge:

{ "type": "verification", "challenge": "a-single-use-random-value" }

Your endpoint verifies the signature, then echoes {"challenge":"..."} with a 2xx status. The server compares it in constant time. The Beta spec also allows three alternatives: a server-side allowlist, out-of-band registration, or a /.well-known/mcp-webhook-receiver.json file on the receiver's origin.

The trap: on a first subscribe, the challenge arrives while events/subscribe is still in progress. It carries an X-MCP-Subscription-Id your client hasn't received yet. If your receiver looks up the secret by that ID and rejects unknown ones, every first subscription fails. Check the signature against secrets you've registered but not yet bound to an ID.

Test these cases:

  1. Happy path: the challenge is echoed and the subscribe call succeeds.
  2. Wrong secret: your receiver returns 401 and the subscribe call fails.
  3. Receiver stopped: the server reports a CallbackEndpointError.
  4. Redirect: the server must not follow it. Watch for frameworks that redirect /hooks/mcp/ to /hooks/mcp.

Verification is cached per principal and URL, so a refresh may not trigger a new challenge. To force one during testing, change the callback path (and update your route to match).

One version difference to expect: the Beta spec numbers CallbackEndpointError as -32027, while OpenAI's draft-based documentation uses -32015.

Test 2: Subscription Renewal

Webhook subscriptions are leases. Your ttlMs is only a suggestion; the server's refreshBefore is authoritative. To renew, call events/subscribe again with the same name, arguments and URL before that time. There is no separate renew method.

Request ttlMs Meaning
Omitted Use the server's default
A number Requested lifetime in milliseconds
null Ask for no expiry (the server may still return a finite one)

This scheduler renews halfway through each grant and backs off on errors:

// subscribe(params) is your authenticated MCP call to events/subscribe
export function keepAlive(subscribe, params, { onResult, onError = console.error } = {}) {
  let timer, stopped = false, cursor = params.cursor ?? null, retry = 1000;

  async function refresh() {
    try {
      const result = await subscribe({ ...params, cursor });
      if (stopped) return;
      retry = 1000;
      cursor = result.cursor ?? null;
      onResult?.(result); // persist cursor; check truncated and deliveryStatus
      if (result.refreshBefore === null) return; // no-expiry grant
      const lifetime = Date.parse(result.refreshBefore) - Date.now();
      // halfway through the grant; clamp to avoid hot loops and timer overflow
      schedule(Math.min(Math.max(lifetime / 2, 1000), 2 ** 31 - 1));
    } catch (err) {
      if (stopped) return;
      onError(err);
      schedule(retry);
      retry = Math.min(retry * 2, 60_000);
    }
  }
  const schedule = (ms) => { timer = setTimeout(refresh, ms); };

  refresh();
  // When your receiver sees newer cursors, feed them in here
  return {
    setCursor: (c) => { cursor = c; },
    stop: () => { stopped = true; clearTimeout(timer); },
  };
}

In production, also cap retries against the deadline, so a long backoff can't sleep past refreshBefore when grants are short.

A refresh does more than extend the lease:

  • Cursor: always send the last cursor you persisted. null means "start from now", so sending it after a lapse skips whatever you missed. Some event types don't support replay and always return null.
  • truncated: true: delivery resumed later than your cursor. Assume you missed events and re-read the source.
  • deliveryStatus: optional. active: false means the server had suspended delivery after failures, and this refresh reactivated it. lastError gives a category such as timeout or tls_error.
  • Secret rotation: send a new delivery.secret. Servers should sign with both keys for a short window, so accept either.

To test renewal, have your server grant a 60-second TTL. Then stop the client, trigger an event after expiry, restart, and confirm you either recover it by cursor or see that it's gone. Restart the server too: it may lose short-lived subscriptions and should recreate them on the next refresh.

When you're finished, call events/unsubscribe with the name, arguments and callback URL. The subscription ID isn't accepted as input.

Note that your tunnel session and your subscription have separate clocks. A live subscription pointing at a closed tunnel just produces failed deliveries.

Test 3: Out-of-Order and Duplicate Delivery

Webhook ordering in MCP Events is best-effort. Each event is retried independently, so a failed first event can arrive after a successful second one. There are no sequence numbers.

The spec suggests bounded retries, for example 3 to 5 attempts within 10 to 15 minutes. Don't expect a long retry schedule to cover a laptop that slept overnight.

With the receiver running, a fake sender lets you reproduce the awkward cases on demand. Save it as send.mjs:

import crypto from "node:crypto";

const url = process.argv[2] ?? "http://127.0.0.1:8787/hooks/mcp";
const secret = process.env.MCP_WEBHOOK_SECRETS.split(",")[0];
const key = Buffer.from(secret.slice("whsec_".length), "base64");

async function send(label, payload, { id = `msg_${crypto.randomUUID()}`, age = 0, tamper = false } = {}) {
  const body = JSON.stringify(payload);
  const ts = Math.floor(Date.now() / 1000) - age;
  const sig = crypto.createHmac("sha256", key).update(`${id}.${ts}.${body}`).digest("base64");
  const res = await fetch(url, {
    method: "POST",
    redirect: "manual",
    headers: {
      "Content-Type": "application/json",
      "webhook-id": id,
      "webhook-timestamp": String(ts),
      "webhook-signature": `v1,${sig}`,
      "X-MCP-Subscription-Id": "sub_local_test",
    },
    body: tamper ? body + " " : body,
  });
  console.log(label.padEnd(22), res.status, await res.text());
}

const event = (n, minute) => ({
  eventId: `evt_${n}`,
  name: "incident.created",
  timestamp: `2026-12-04T10:0${minute}:00Z`,
  data: { incidentId: `INC-${n}` },
  cursor: null,
});

await send("verification", { type: "verification", challenge: crypto.randomUUID() });
await send("newer event first", event(2, 2), { id: "msg_two" });
await send("older event second", event(1, 1), { id: "msg_one" });
await send("retry of newer", event(2, 2), { id: "msg_two" });
await send("tampered body", event(3, 3), { tamper: true });
await send("stale timestamp", event(4, 4), { age: 600 });
await send("gap envelope", { type: "gap", cursor: "c_99" });
await send("terminated envelope", { type: "terminated", error: { code: -32024, message: "Forbidden" } });

In a second terminal, with the same secret exported:

node send.mjs
# or through the tunnel:
node send.mjs https://YOUR-TUNNEL-HOST/hooks/mcp

Against a fresh inbox, expect 200 for verification, 204 for the two events, the retry and both control messages, and 401 for the tampered and stale requests. The receiver logs the retry as a duplicate.

The sender signs with your own secret and skips SSRF checks, so it tests your receiver, not a server.

What to use for ordering and deduplication

Field What it tells you Don't use it for
webhook-id This message; unchanged across retries Ordering
eventId The upstream event Deduplicating across different subscriptions
timestamp (body) When the event occurred Detecting gaps
webhook-timestamp When this attempt was signed Ordering events
cursor Safe resume point This event's position

The cursor is the subtle one. It's a watermark: everything at or before it has been acknowledged or abandoned. Persist each one you receive, but don't compare cursors to sort events; they're opaque.

If order matters, store each object's latest event timestamp and ignore older state changes. Better still, treat the event as a nudge and fetch current state with an MCP tool.

Scope deduplication to the subscription ID. One upstream event can legitimately match two subscriptions and arrive on both with the same eventId.

Status codes and control messages

Return 2xx only after the event is safely stored, then do slow work asynchronously. Other non-2xx responses are generally retried, but 410 Gone and 413 Payload Too Large are not. Servers should keep bodies at or under 256 KiB.

A body with a top-level type is a control message, not an event:

  • verification: answer it.
  • gap: save the new cursor and reconcile with the source.
  • terminated: the subscription no longer exists.

ChatGPT vs. the Beta Spec

If you're building a server today, test against what your client actually does. Based on current documentation:

Behavior Beta specification ChatGPT (draft-based)
Capability capabilities.extensions["io.modelcontextprotocol/events"] capabilities.events
Protocol 2026-07-28 or later 2026-07-28, or Streamable HTTP with initialize
Delivery modes Poll, push, webhook Webhook only
webhook-id on events Server-generated; must not be derived from eventId Same value as eventId
gap and terminated Defined Not supported
Callback error code -32027 -32015

The webhook-id row is the one most likely to bite. A receiver that assumes webhook-id === eventId will break against a Beta-conformant server. One that deduplicates on webhook-id globally can drop legitimate events when a draft-style server sends the same event to two subscriptions. Keying on subscription ID plus webhook-id, as the receiver above does, handles both.

To test with ChatGPT, tunnel your MCP server, add it through a plugin, and ask a Work chat to monitor one of your events. OpenAI lists Work chats on the web, Work chats in the desktop app with Cloud selected, and dots; workspace controls apply. Your server must send callbacks to the URL ChatGPT provides, so your laptop needs outbound HTTPS access.

Security Checklist

  • Verify the HMAC over the raw bytes before parsing.
  • Reject timestamps more than five minutes old, and keep your machine's clock synced.
  • Treat data as untrusted input. Event text can carry prompt injection.
  • Receiving an event never authorizes an agent to act on it.
  • If you're the sender, validate the resolved IP on every connection and block redirects.
  • Don't log whsec_ secrets, and rotate any that leak into shell history or screenshots.
  • Unsubscribe test subscriptions before releasing a tunnel subdomain.

This article deliberately skips MCP OAuth discovery and registration, and A2A push notifications. Both are separate problems, even though they also involve public URLs.

Frequently Asked Questions

Can MCP Events deliver webhooks to localhost?

Not directly in a standard setup. The callback must use https, and servers should reject non-public addresses unless explicitly configured otherwise. A tunnel gives your local receiver a public HTTPS URL.

What happens if I don't renew a subscription?

It expires at refreshBefore and deliveries stop. Resubscribing with a stored cursor can recover events if that event type supports replay and the history still exists.

Are MCP Events delivered exactly once?

No. Replayable event types can provide at-least-once delivery, so duplicates are expected. Event types without replay can lose events across server restarts.

Is MCP Events the same as MCP notifications?

No. Existing notifications such as list_changed need an open connection and have no event payload or resume cursor.

Final Takeaway

An MCP Events webhook is a signed POST with a lease attached. Answer the challenge before you know the subscription ID, renew from refreshBefore rather than your own ttlMs, and assume events arrive late, twice or in the wrong order. Test those three on localhost first, then check how your particular client differs from the Beta text.

Details checked on December 4, 2026. The extension is in Beta, so confirm current behavior before shipping.


Originally published at https://instatunnel.my/blog/mcp-events-is-a-webhook-now-testing-eventssubscribe-callbacks-on-localhost

Comments