InstaTunnel
Navigation menu o kirikae
API
15 min read
82 views

MCP Events はウェブフックになりました: `events/subscribe` コールバックを localhost でテスト

localhost で MCP Events のウェブフックをテストします: `events/subscribe` コールバックを検証し、署名を確認し、TTL サブスクリプションを更新し、順序が前後する配信に対処します。

IT
InstaTunnel Team
Published by the InstaTunnel team | Editorial policy
MCP Events はウェブフックになりました: `events/subscribe` コールバックを localhost でテスト

Quick answer

MCP Events のウェブフック: localhost で events/subscribe をテスト: webhook testing answer

For local webhook testing, run your app locally, expose it with a public HTTPS tunnel, and paste the stable callback URL into the provider dashboard.

How do I test webhooks on localhost?

Start your local server, open a public HTTPS tunnel to that port, configure the provider webhook URL, and inspect events in your local logs.

Why does a stable webhook URL matter?

Stable URLs prevent provider dashboards from needing manual callback updates every time you restart a tunnel.

ほとんどの期間、Model Context Protocol (MCP) は一方向で機能していました:クライアントがリクエストし、サーバーが応答します。MCP Events はもう一方の方向を追加します。クライアントは現在 HTTPS コールバック URL を登録でき、上流で何かが起こると MCP サーバーが署名付きイベントをそれへ POSTします。たとえば新しい incident、コメント、メールなど。

もし Stripe や GitHub のウェブフックハンドラを作ったことがあるなら、多くの点は馴染みがあると感じるでしょう。3 つの部分にはそれぞれ独自のテストが必要です:endpoint verification、subscription renewal、および out-of-order delivery。このガイドは、ローカル受信機、偽の送信者、そして実物のためのトンネルを使って、3 つすべてをカバーします。

Is MCP Events Beta or Final?

両方の表記は正しく、異なるものを指しています:

  • SEP-3415、設計提案は Final です。
  • The extension, io.modelcontextprotocol/events, は Beta にあります。

公式の概要はまさにそれを述べ、Beta 仕様は、壊れる変更はまれで文書化されることを警告します。拡張機能を「Final」と呼ばないでください。2026-07-28 以降の MCP プロトコル改訂が必要です。

Beta の文言が出る前に普及が始まりました。ChatGPT は 2026年9月29日から webhook モードをサポートしていると報告されています、OpenAI のドキュメントはまだ ドラフト 仕様を実装していると記載しています。テストする際にはこのギャップが影響します。Vercel Connect もドラフトを前提にウェブフックのサポートを文書化しています。

How events/subscribe Works

MCP Events は 3 つの配信モードを定義します:ポーリング(events/poll)、プッシュ(events/stream)そしてウェブフック(events/subscribe)。各イベントタイプはどれをサポートしているかを公表します。この記事はウェブフックについて扱います。

サブスクライブリクエストはこのように見えます(プロトコル _meta は省略):

{
  "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_\u003cbase64 of 24 to 64 random bytes\u003e"
    },
    "cursor": null,
    "ttlMs": 3600000
  }
}

そしてレスポンス:

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

テスト設定にはいくつかのルールがあります:

  • クライアントが秘密を生成します、サーバーが生成することはありません。
  • コールバックは https でなければなりません。 単純な http://localhost URL は InvalidParams で拒否されます。
  • 呼出は認証済みである必要があります。 認証されていないサーバーはポールとプッシュを提供できますが、ウェブフックは提供できません。
  • アイデンティティは (principal, delivery.url, name, arguments) です。 1つでも変更すると別のサブスクリプションになります。
  • Streamable HTTP では、イベント名と一致する Mcp-Name ヘッダーも必要です。

各配信は webhook-id、webhook-timestamp、webhook-signature、X-MCP-Subscription-Id ヘッダー付きの POST で、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

仕様はサーバー側のリクエストフォージェリ(SSRF)対策を求めます。公開されていないアドレス、ループバックやプライベートレンジを解決するコールバックURLを拒否し、デリバリ時に IP をチェックし、リダイレクトに従わないようにします。サーバーはローカルターゲットを許可するよう明示的に設定可能ですが、その保護を弱めてテストするのはやめてください。受信機には公開 HTTPS URL を与えましょう。

どの部分をトンネルにするかは、作成しているもの次第です:

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

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 の free plan は現在、サインイン済みユーザーの予約済みサブドメイン、24時間セッション、1日あたりのリクエスト上限をリストしています。ロードテストをする場合は最後の数字を注視してください。

基本認証やトンネルパスワードをコールバックパスの前に置かないでください。拡張機能はサーバーとエンドポイント間の認証として HMAC を唯一の認証として定義しており、サーバーは追加の認証情報を送る方法を持ちません。

A Minimal Local Receiver

この Node.js の受信機は依存関係を持ちません。生の本文を検証し、検証チャレンジに答え、重複を除去し、ディスクへ書き込んだ後に応答します。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;
// イベント/subscribe に入れた秘密( rotation 時にはカンマ区切り)
const secrets = (process.env.MCP_WEBHOOK_SECRETS ?? "").split(",").filter(Boolean);
if (!secrets.length) throw new Error("Set MCP_WEBHOOK_SECRETS");

// 再起動時に以前のメッセージを再処理してしまうのを防ぐため、重複排除キーを再読込
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; // また numeric でない値にも対応

  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); // すぐにディスクへ書き込み
  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); // そのままのバイト列
    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(); // 再試行可能
    }
  });
}).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

署名秘密は偽造イベントから信頼を守りますが、あなたの URL を購読して大量に送る人を止めるわけではありません。したがってサーバーは配信を送る前にエンドポイントが配信を受け付けることを確認する必要があります。通常の方法はチャレンジです:

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

エンドポイントは署名を検証し、{"challenge":"..."} を 2xx ステータスでエコーします。サーバーは定数時間で比較します。Beta 仕様は、サーバー側の許可リスト、アウト・オブ・バンド登録、または受信機の起源上にある /.well-known/mcp-webhook-receiver.json のファイルを許可することもあります。

落とし穴: 初回のサブスクライブ時には、チャレンジが発生している最中に到着します。これは X-MCP-Subscription-Id をクライアントがまだ受け取っていない状態で含みます。受信機がその ID で秘密を照合して未知のものを拒否すると、初回サブスクライブはすべて失敗します。秘密を登録済みだがまだ ID に結びついていないものを照合して署名を検証してください。

次のケースをテストします:

  1. ハッピーパス: チャレンジがエコーされ、サブスクライブ呼び出しが成功します。
  2. 秘密が間違い: 受信機は 401 を返し、サブスクライブは失敗します。
  3. 受信機が停止: サーバーは CallbackEndpointError を報告します。
  4. リダイレクト: サーバーはそれに従ってはなりません。 /hooks/mcp/ を /hooks/mcp にリダイレクトするフレームワークには注意してください。

検証は主体と URL ごとにキャッシュされるため、リフレッシュで新しいチャレンジが発生しないことがあります。テスト中に強制的にチャレンジを表示させるには、コールバックパスを変更し、ルートを一致させてください。

期待される一つのバージョン差分: Beta 仕様では CallbackEndpointError を -32027 としますが、OpenAI のドラフトベースのドキュメントは -32015 を使用します。

Test 2: Subscription Renewal

ウェブフックのサブスクリプションはリースです。あなたの ttlMs はあくまで提案であり、サーバーの refreshBefore が正式です。期限を更新するには、同じ名前、同じ引数、同じ URL で再度 events/subscribe を呼び出します。別個の更新メソッドはありません。

Request ttlMs Meaning
omitted サーバーのデフォルトを使用
a number ミリ秒単位の希望寿命
null 期限なしを要求(ただしサーバーが有限のものを返す場合があります)

このスケジューラは各 grant の半ばで更新し、エラー時にはバックオフします:

// subscribe(params) はあなたの認証済み 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); // cursor を永続化; truncated と deliveryStatus を確認
      if (result.refreshBefore === null) return; // no-expiry ガント
      const lifetime = Date.parse(result.refreshBefore) - Date.now();
      // ガントの半分を過ぎた時点で次を設定; 過熱ループとタイマーのオーバーフローを回避
      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();
  // 受信機が新しいカーソルを見つけたらここに渡してください
  return {
    setCursor: (c) => { cursor = c; },
    stop: () => { stopped = true; clearTimeout(timer); },
  };
}

本番環境では、長いバックオフが refreshBefore を超えて sleep しないよう、リトライ回数をデッドラインで抑制してください。

リフレッシュはリースを延長する以上の意味を持ちます:

  • Cursor: 常に、あなたが永続化した最後のカーソルを送信してください。null は“今から開始”を意味します。 lapse の後で送信すると、見逃したものをスキップします。いくつかのイベントタイプはリプレイをサポートせず、常に null を返します。
  • truncated: true: カーソルより後の配信が再開されます。イベントを見逃したと仮定し、ソースを再読します。
  • deliveryStatus: 任意。active: false はサーバーが失敗後の配信を一時停止していたことを意味し、このリフレッシュで再アクティブ化します。lastError は timeout や tls_error などのカテゴリを示します。
  • Secret rotation: 新しい delivery.secret を送ってください。短期間の間に双方のキーで署名するべきで、どちらを受け入れても構いません。

更新をテストするには、サーバーに 60 秒の TTL を付与させてください。次にクライアントを停止し、期限切れ後にイベントをトリガーし、再起動してカーソルで回復するか、期限切れで消えたことを確認します。サーバーを再起動することも忘れずに。短寿命のサブスクリプションを失い、次のリフレッシュで再作成されるべきです。

完了したら、events/unsubscribe を名前、引数、コールバック URL とともに呼び出します。サブスクリプション ID は入力として受け付けられません。

なお、トンネルセッションとサブスクリプションは別々の時計を持っています。トンネルが閉じている状態でのライブサブスクリプションは配送失敗のみを生み出します。

Test 3: Out-of-Order and Duplicate Delivery

MCP Events のウェブフックの順序は 最善努力 です。各イベントは独立して再試行されるため、最初のイベントが失敗しても、成功した2 番目のイベントの後に到着することがあります。シーケンス番号はありません。

仕様はリミット付きリトライを示唆しています。例えば3〜5回の試行を、10〜15分の間に行います。長いリトライスケジュールを期待して、眠っていたノートパソコンを跨いだテストを行うべきではありません。

受信機が動作している状態で、偽の送信者を使って必要なケースを再現できます。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

カーソルは微妙なものです。これは ウォーターマークです:それ以下のすべては確認済みまたは破棄済みです。受信した各カーソルを永続化してください。カーソルを比較してイベントを並べ替えないでください。カーソルは不透明です。

順序が重要なら、各オブジェクトの最新のイベント timestamp を保存し、古い状態変化を無視してください。さらなるのは、イベントを nudge として扱い、MCP ツールで現在の状態を取得してください。

サブスクリプション ID で重複排除を絞り込みます。上流の1つのイベントが、同じ eventId を持つ2つのサブスクリプションに正当に一致して到着することがあります。

Status codes and control messages

イベントが安全に保存された後にのみ 2xx を返し、その後非同期で遅い処理を行います。その他の非 2xx 応答は一般に再試行されますが、410 Gone と 413 Payload Too Large は対象外です。サーバーは本文を 256 KiB 以下に保つべきです。

トップレベルの type を持つ本文はコントロールメッセージで、イベントではありません:

  • verification: それに返答します。
  • gap: 新しいカーソルを保存し、ソースと調整します。
  • terminated: サブスクリプションはもはや存在しません。

ChatGPT vs. the Beta Spec

サーバーを今日構築している場合、クライアントが実際に行うことと照らしてテストします。現在のドキュメントに基づくと:

Behavior Beta specification ChatGPT (draft-based)
Capability capabilities.extensions["io.modelcontextprotocol/events"] capabilities.events
Protocol 2026-07-28 以降 2026-07-28、または initialize を持つ Streamable HTTP
Delivery modes Poll、push、webhook Webhook のみ
webhook-id on events サーバー生成; eventId 由来ではない eventId と同じ値
gap and terminated 定義済み 未対応
Callback error code -32027 -32015

webhook-id 行は最も影響を受けやすい箇所です。webhook-id === eventId を前提とする受信機は Beta 準拠のサーバーと衝突します。webhook-id でグローバルに重複排除できる受信機は、ドラフト型のサーバーが同じイベントを2つのサブスクリプションへ送る場合、正当なイベントを落としてしまうことがあります。サブスクリプションIDと webhook-id をキーにする受信機の実装は、上記の両方を扱います。

ChatGPT でのテストには、MCP サーバーをトンネルし、プラグイン経由で追加し、Work チャットにイベントのモニターを依頼してください。OpenAI は Work チャットをウェブ上で、デスクトップアプリの Cloud 選択付きで、ドット表示; ワークスペースのコントロールは適用されます。サーバーは ChatGPT が提供する URL へコールバックを送る必要があるため、ラップトップにはアウトバウンド HTTPS アクセスが必要です。

Security Checklist

  • 実 pars ークの前に、RAW バイトの上で HMAC を検証します。
  • タイムスタンプが5分を超えて古い場合は拒否し、機械の時計を同期させてください。
  • data は信頼できない入力として扱います。イベントテキストはプロンプトの注入を含む可能性があります。
  • イベントを受け取っても、それ自体がエージェントの権限を与えることはありません。
  • 送信者側なら、すべての接続で解決済み IP を検証し、リダイレクトをブロックしてください。
  • whsec_ 系の秘密はログに残さず、履歴やスクリーンショットに漏れたものをローテーションしてください。
  • トンネルのサブドメインを公開前に解約すること。

この記事は意図的に MCP Oauth の discovery や登録、A2A push 通知をスキップしています。どちらも別個の問題であり、公開 URL を含む点は共通しています。

Frequently Asked Questions

Can MCP Events deliver webhooks to localhost?

標準構成では直接は難しいです。コールバックは https を使う必要があり、公開アドレス以外を拒否するべきです。トンネルを使えばローカル受信機に公開 HTTPS URL が与えられます。

What happens if I don’t renew a subscription?

refreshBefore で期限切れとなり配信が停止します。カーソルを保存して再購読すれば、そのイベントタイプがリプレイをサポートしており履歴がまだ存在する場合、イベントを回復できます。

Are MCP Events delivered exactly once?

いいえ。再生可能なイベントタイプは少なくとも一度の配送を提供することがあり、重複が予想されます。再生されないイベントタイプはサーバー再起動時にイベントを失うことがあります。

Is MCP Events the same as MCP notifications?

いいえ。既存の通知(例:list_changed)は開いた接続を必要とし、イベントペイロードやリジュームカーソルを持ちません。

Final Takeaway

MCP Events のウェブフックは、署名付きの POST でリースが付随します。購読 ID を知る前にチャレンジに答え、refreshBefore から更新し、イベントが遅れて到着する、2回目、順序が乱れて到着する可能性もあると想定してください。localhost でこの3点をまずテストし、次にご自身のクライアントが Beta テキストとどう異なるかを確認してください。

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

Continue from this article into the most relevant product guides and workflows.

Related Topics

#MCP Events#MCP Events webhook#events/subscribe#MCP events/subscribe#MCP webhook#MCP webhooks localhost#test MCP webhooks locally#MCP Events extension#MCP Events beta#SEP-3415#io.modelcontextprotocol/events#Model Context Protocol#Model Context Protocol events#MCP server#MCP client#MCP server development#MCP server testing#MCP 2026-07-28#MCP specification#MCP callback URL#webhook callback verification#webhook endpoint verification#MCP challenge verification#MCP subscription renewal#webhook subscription TTL#events/list#events/poll#events/stream#MCP webhook mode#ChatGPT MCP Events#ChatGPT webhooks#ChatGPT MCP server#signed webhooks#Standard Webhooks#webhook signature verification#HMAC webhook verification#whsec secret#X-MCP-Subscription-Id#webhook-signature header#webhook-timestamp header#out-of-order webhook delivery#webhook event ordering#webhook deduplication#idempotent webhook handler#webhook retries#localhost webhook testing#test webhooks on localhost#localhost HTTPS callback#HTTPS tunnel#localhost tunnel#tunnel for webhooks#expose localhost to internet#public URL for localhost#stable tunnel URL#custom subdomain tunnel#InstaTunnel#ngrok alternative#AI agent webhooks#event-driven AI agents#agentic AI infrastructure

Keep building with InstaTunnel

Read the docs for implementation details or compare plans before you ship.

Share this article

More InstaTunnel Insights

Discover more tutorials, tips, and updates to help you build better with localhost tunneling.

Browse All Articles