Use MCP Events with agentproto: poll, stream or webhook a merged pull request into your agent

Read GitHub events from the agentproto daemon by poll, stream or signed webhook, then wake an agent session with a sentinel. Run on the published CLI.

· Jeremy

A small country post office where three channels, a taut wire, a relief clock and a pneumatic tube, converge on one counter as a sleepy robot agent wakes up.

Your agent's pull request gets merged and nothing tells it. Here is how to make the daemon tell it, three ways, with commands I ran.

I wrote MCP Events, explained to say what the extension is. This is the hands-on follow-up. A pull request, or PR (a proposed code change waiting for approval), closes on GitHub. The agentproto daemon notices, and your client or your agent hears about it without you being the messenger.

I ran every step on 2 December 2026 against @agentproto/cli 1.41.0, installed from npm into an empty folder, on a test daemon with its own home folder.

What you get

  • A local daemon (the background agentproto program) that serves four GitHub event types over MCP, the Model Context Protocol, the standard way for outside software to talk to an assistant.
  • Three ways to read them: events/poll (you ask), events/stream (the daemon writes to an open connection) and events/subscribe (the daemon POSTs a signed message to your web address).
  • A way to wake an agent session instead of a script: a sentinel (a watcher inside the daemon), or session_follow for a supervisor watching other sessions.

Left to right: GitHub, then the agentproto daemon containing a shared watch lease that polls every 15 seconds and feeds a journal, plus a separate webhook sentinel with a signed outbox. The journal feeds events/poll and events/stream; the webhook sentinel feeds events/subscribe. All three lead to your client or agent.

The path of one event. Poll and stream read the same journal; a webhook has its own sentinel.

Prerequisites

  • Node.js 20.9 or later and the @agentproto/cli package. I installed it with npm i @agentproto/[email protected] and ran node node_modules/@agentproto/cli/dist/cli.mjs. If you installed the CLI globally, the command is just agentproto.
  • The GitHub CLI, gh, logged in on the machine that runs the daemon. The daemon does not ask you for a GitHub token. Its default provider, local-gh, runs gh on your behalf and reads PR state with it, so it sees what your gh login can see. That is also why a private repo works.
  • A repo with a PR you can close, or a public repo whose PRs you only watch.

Start a daemon. I use a test port and a separate home folder so it cannot touch my main one:

HOME=$PWD/home agentproto serve --port 18913 --workspace $PWD/ws

I gave my test daemon GH_TOKEN taken from gh auth token, because a changed HOME hides the gh login. You will not need that on a normal setup.

The endpoint is http://127.0.0.1:18913/mcp. From the same machine it needs no token. If you start the daemon with --auth-token <token> (or the daemon.authToken config key), a request that does not arrive on loopback must send Authorization: Bearer <token>. I checked this by faking a proxy with an X-Forwarded-For header: without the bearer I got 401 tunnel_unauthorized, with it the request went through. The token is yours to choose and keep out of files you share.

1. Discover what the server offers

There are two protocol eras on the same endpoint. The older one, 2025-11-25, starts with initialize. The newer one, 2026-07-28, has no handshake: each request names the version and the server answers server/discover. The new era needs three things on every request:

  • an MCP-Protocol-Version: 2026-07-28 header;
  • an Mcp-Method header equal to the method (and Mcp-Name equal to params.name on events/poll, events/stream, events/subscribe and events/unsubscribe);
  • _meta in params, with io.modelcontextprotocol/protocolVersion and io.modelcontextprotocol/clientCapabilities.

I wrapped that in a small shell script, rpc.sh:

#!/bin/sh
# usage: rpc.sh <id> <method> <params-json> [mcp-name]
curl -s http://127.0.0.1:18913/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -H 'MCP-Protocol-Version: 2026-07-28' -H "Mcp-Method: $2" ${4:+-H "Mcp-Name: $4"} \
  -d "{\"jsonrpc\":\"2.0\",\"id\":$1,\"method\":\"$2\",\"params\":$3}"
M='"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}'
./rpc.sh 2 server/discover "{$M}"

What I saw (shortened):

{"result":{"supportedVersions":["2026-07-28","2025-11-25"],
 "capabilities":{"tools":{},"resources":{},"events":{},
  "extensions":{"io.modelcontextprotocol/events":{"listChanged":false}, ...}},
 "resultType":"complete", ...}}

The capability to look for is io.modelcontextprotocol/events. A client that speaks the older era finds the same thing after initialize, in capabilities.extensions. Now list the event types:

./rpc.sh 3 events/list "{$M}"
github.pull_request.closed          A pull request was closed or merged.
github.pull_request.synchronize     New commits were pushed to a pull request's head branch.
github.pull_request_review.submitted A review was submitted on a pull request.
github.check_suite.completed        The checks on a pull request finished.

Each entry also carries delivery, inputSchema and payloadSchema. All four take { "repo": "owner/name", "number": 482 }. On the new era, delivery was ["poll","push","webhook"]. On the older era it was ["poll","webhook"], because events/stream exists only on 2026-07-28.

For github.pull_request.closed the payload has action, merged (true when merged, false when only closed), repo, number, subject and summary. The merged flag is what tells a merge from a plain close.

2. Poll

Poll is the simplest mode: no open connection, no public address. You send the event name, the arguments and a cursor (an opaque bookmark you give back each time). The first call, with cursor: null, means "start from now". It returns the first cursor and no events:

{"result":{"events":[],"cursor":"eyJ2IjoxLCJq...","truncated":false,
 "hasMore":false,"nextPollMs":15000,"resultType":"complete"}}

Here is the loop I ran. It keeps the cursor after every answer, even an empty one, waits nextPollMs, and drops an eventId it has already seen (delivery is at-least-once, so the same event can come twice):

// node poll.mjs <owner/repo> <number>
const [repo, number, name = "github.pull_request.closed"] = process.argv.slice(2)
const URL_ = "http://127.0.0.1:18913/mcp"
const seen = new Set()
let cursor = null, id = 0

async function rpc(method, params) {
  const res = await fetch(URL_, {
    method: "POST",
    headers: { "content-type": "application/json", accept: "application/json, text/event-stream",
      "mcp-protocol-version": "2026-07-28", "mcp-method": method, "mcp-name": params.name },
    body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, params: { ...params, _meta: {
      "io.modelcontextprotocol/protocolVersion": "2026-07-28",
      "io.modelcontextprotocol/clientCapabilities": {} } } }),
  })
  const msg = JSON.parse((await res.text()).replace(/^(event:.*\n)?data: /, ""))
  if (msg.error) throw new Error(`${msg.error.code} ${msg.error.message}`)
  return msg.result
}

for (;;) {
  const r = await rpc("events/poll", { name, arguments: { repo, number: Number(number) }, cursor })
  if (r.truncated) console.log("truncated: possible gap, re-read the PR with a normal tool")
  for (const e of r.events) {
    if (seen.has(e.eventId)) continue // at-least-once: drop duplicates
    seen.add(e.eventId)
    console.log(e.timestamp, e.name, JSON.stringify(e.data))
  }
  cursor = r.cursor // keep it even when the batch is empty
  await new Promise((ok) => setTimeout(ok, r.nextPollMs ?? 30000))
}

I ran it on two PRs of a throwaway private repo of mine, 9 and 10, then closed PR 9 and merged PR 10 with gh. I closed PR 9 at 11:46:04 UTC. About 18 seconds later the loop printed (repo name shortened):

2026-12-02T11:46:22.841Z github.pull_request.closed {"action":"closed","merged":false,"repo":"me/throwaway","number":9,...,"summary":"PR me/throwaway#9 closed"}
2026-12-02T11:46:22.846Z github.pull_request.closed {"action":"closed","merged":true,"repo":"me/throwaway","number":10,...,"summary":"PR me/throwaway#10 merged"}

Two details to know. The first call never returns the past: I pointed the loop at an already merged PR of a public repo and it stayed quiet. And the server stamps the event when its own check sees the change, not when GitHub changed it. In my one run that was 18 seconds after I closed the PR. I measured once, so treat it as an example and not a promise.

Replay comes from a journal on disk (a log of recent events per watched key). The code keeps entries for 24 hours with a cap of 5,000 (poll-journal.ts). If you come back with a cursor older than that, you get truncated: true and the loop above tells you to re-read the PR. A cursor the server did not issue is refused with -32602 invalid_cursor. A poll takes optional maxAgeMs and maxEvents (100 by default, 1,000 at most), and hasMore: true means call again at once.

3. Stream

Streaming keeps one request open and the daemon writes events to it as Server-Sent Events (SSE, one data: line per message). The request needs Accept to list both application/json and text/event-stream. With application/json alone I got a 406. It also needs the new-era headers, including Mcp-Name:

curl -sN http://127.0.0.1:18913/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -H 'MCP-Protocol-Version: 2026-07-28' \
  -H 'Mcp-Method: events/stream' -H 'Mcp-Name: github.pull_request.closed' \
  -d '{"jsonrpc":"2.0","id":7,"method":"events/stream","params":{
        "name":"github.pull_request.closed",
        "arguments":{"repo":"me/throwaway","number":9},
        "cursor":null,"heartbeatMs":10000,
        "_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28",
                 "io.modelcontextprotocol/clientCapabilities":{}}}}'

I left this running while I closed PR 9. These are the frames, with the cursors shortened:

data: {"method":"notifications/events/active","params":{"cursor":"eyJ2...","truncated":false,"heartbeatMs":10000,"_meta":{"io.modelcontextprotocol/subscriptionId":7}}}

data: {"method":"notifications/events/heartbeat","params":{"cursor":"eyJ2...","_meta":{...}}}

data: {"method":"notifications/events/event","params":{"eventId":"evt_6125f2067eb015d7484053e5","name":"github.pull_request.closed","timestamp":"2026-12-02T11:46:22.841Z","data":{"action":"closed","merged":false,...},"cursor":"eyJ2...","_meta":{...}}}

active comes first and tells you the heartbeat the daemon granted: the default is 30 seconds and the code clamps your request to between 5 and 60 seconds. A heartbeat frame arrives after each silence of that length, so you can tell a quiet stream from a dead one. The event frame has the same envelope as a poll result. Each frame carries the cursor, and the subscriptionId is the id of your request.

To resume after a drop, send the last cursor. I reused the first cursor from active and the stream replayed the closed event, with the same eventId, before going back to heartbeats. A poll cursor and a stream cursor are interchangeable.

The daemon allows 32 open streams. I opened 32 and the 33rd answered -32025 with "data":{"limit":"streams","max":32}. A shared pool of 64 watches covers poll and stream together (pollWatches). Behind a tunnel that holds a streamed response until it ends, you would get nothing, and the integration doc tells you to poll there.

4. Webhook

A webhook is the mode for a client that cannot keep a connection open. You give the daemon an https address and a secret you chose. The daemon first sends a signed test message and expects you to echo it back, then POSTs each event.

SECRET="whsec_$(openssl rand -base64 32)"   # whsec_ + base64 of 24 to 64 bytes
./rpc.sh 20 events/subscribe "{\"name\":\"github.pull_request.closed\",
  \"arguments\":{\"repo\":\"me/throwaway\",\"number\":9},
  \"delivery\":{\"mode\":\"webhook\",\"url\":\"https://hooks.example.com/mcp\",\"secret\":\"$SECRET\"},
  \"ttlMs\":3600000,$M}" github.pull_request.closed

ttlMs is the lifetime. The code grants at least 60 seconds, at most 30 days, and 7 days if you omit it. The answer carries refreshBefore, which is the time the subscription ends. Send the same call again before then to renew it. events/unsubscribe with the same name, arguments and URL removes it, and a second call is harmless.

What I ran, and what the daemon said back:

  • An http:// address: -32602, invalid_callback_url.
  • A secret that is not whsec_ plus base64: -32602, invalid_secret.
  • An https address that did not answer: -32027 with "reason":"timeout". The other reasons the code can give are connection_refused, http_4xx, http_5xx and challenge_failed.
  • events/unsubscribe: an empty successful result.

The daemon refuses private addresses on purpose, so a webhook needs a public https URL, which on a laptop means a tunnel. The receiver behind it can be this one, about thirty lines:

// node receiver.mjs   (SECRET = the whsec_ string you gave events/subscribe)
import http from "node:http"
import { createHmac, timingSafeEqual } from "node:crypto"

const key = Buffer.from(process.env.SECRET.slice("whsec_".length), "base64")
const seen = new Set()

export function verify(headers, body) {
  const id = headers["webhook-id"], ts = headers["webhook-timestamp"]
  if (!id || !ts || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false // older than 5 min
  const want = createHmac("sha256", key).update(`${id}.${ts}.`).update(body).digest()
  return String(headers["webhook-signature"]).split(" ").some((s) => {
    const [v, b64] = s.split(",")
    const got = Buffer.from(b64 ?? "", "base64")
    return v === "v1" && got.length === want.length && timingSafeEqual(got, want)
  })
}

if (import.meta.url === `file://${process.argv[1]}`) {
  http.createServer((req, res) => {
    const chunks = []
    req.on("data", (c) => chunks.push(c))
    req.on("end", () => {
      const body = Buffer.concat(chunks) // verify the exact bytes, not re-serialized JSON
      if (!verify(req.headers, body)) { res.writeHead(401).end(); return }
      const msg = JSON.parse(body)
      if (msg.type === "verification") { // subscribe-time challenge: echo it back
        res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ challenge: msg.challenge }))
        return
      }
      if (!seen.has(req.headers["webhook-id"])) { // at-least-once: drop duplicates
        seen.add(req.headers["webhook-id"])
        console.log(msg.name ?? msg.type, JSON.stringify(msg.data))
      }
      res.writeHead(200).end()
    })
  }).listen(8099)
}

I took signWebhook from the daemon's source (packages/runtime/src/webhook-egress/signing.ts, the same logic the daemon uses to sign) and ran my verify against it. A good signature passed, a body with one changed word failed, a signature stamped 400 seconds ago failed, and a message signed with two secrets (the key-rotation case) passed. That shows the receiver matches the daemon's signing code.

The other facts of the format: the key is the base64 part of the secret, decoded. The signature is HMAC-SHA256 over webhook-id, webhook-timestamp and the body, joined with dots, printed as v1,<base64>. Each delivery also has an X-MCP-Subscription-Id header. A delivery is retried up to 5 times with a fresh timestamp and signature each time, and a 410 or 413 is not retried. Bodies over 256 KiB lose their data and keep a summary. A webhook subscription does not replay: passing a cursor on subscribe gives truncated: true.

5. Wake an agent instead of a script

Everything above ends in a program you wrote. The part that matters for an agent is getting the event into a session (a running agent conversation), so the next turn knows about it. For that there is the sentinel. It is the same watcher machinery that feeds the MCP surfaces, pointed at a session's inbox (the queue of messages waiting for that session).

agentproto sentinel watch pr https://github.com/agentproto/ts/pull/3150 \
  --session sess_39a6688d --urgency next-turn --until closed

Output from my test daemon:

id       sen_01M8V8RRHCRFB0PT3XTXE4F6VN
status   active
provider local-gh
match    github:agentproto/ts#3150 [github.check_suite.completed,github.workflow_run.completed,github.pull_request_review.submitted,github.pull_request.closed,github.pull_request.synchronize,github.issue_comment.created]
until    subject_terminal
target   session sess_39a6688d (next-turn)

--session is required from the shell, because a shell has no calling session to default to. --urgency is one of fyi, next-turn, steer or interrupt. --until closed ends the watch when the PR closes or merges. The list shows the comment type, but local-gh does not produce comments, and the docs say to use the webhook or agentpush provider for those. Manage watches with agentproto sentinel list, agentproto sentinel status <id> and agentproto sentinel rm <id>.

My test "agent" is a plain terminal session (agentproto sessions terminal -- sh -c 'sleep 3000'), because a real harness on a test home folder would not be logged in. A terminal session has an inbox, so I could see the delivery. I watched my throwaway PR 9 for it, then closed the PR. Thirty seconds after the poll saw it, this appeared:

agentproto sessions inbox sess_39a6688d --json
{ "id": "msg_c6de6f15", "from": {"relation": "system"}, "kind": "notice", "urgency": "next-turn",
  "text": "[github] PR me/throwaway#9 closed",
  "data": { "type": "github.pull_request.closed", "subject": "github:me/throwaway#9",
            "data": {"action":"closed","merged":false,"number":9}, "terminal": true } }

That is the delivery path: the event reaches the session's inbox, labelled as a notice from the system, with the structured event attached. The sentinel guide in the repo says a next-turn notice starts a fresh turn if the session is idle and queues behind the current turn otherwise, and that fyi only parks it. When a watch has done its job, remove it with agentproto sentinel rm <id>.

If a session opens a PR itself, you do not have to do anything: with gh logged in the daemon watches that PR for the session by default (sentinel.autoWatchPrs, urgency sentinel.autoWatchUrgency).

Two entries into one inbox. Top: sentinel watch pr with --session sess_a, then the local-gh provider diffing the PR through gh, delivers a "[github] PR closed" notice. Bottom: a child session emitting turn-end, exited or pr-merged, then session_follow batching for 15 seconds, delivers a "[session-follow]" digest. Both land in the inbox of sess_a, then an agent turn reads the event.

Two ways in, one inbox. The urgency decides whether the message interrupts or waits.

For a supervisor: session_follow

A supervisor agent that starts helper sessions does not need a PR URL. It calls the MCP tool session_follow and gets a digest when a helper ends a turn, exits, crashes, opens a PR (pr-opened) or sees one merged (pr-merged). There is no CLI verb for it; it is a tool on the daemon's /mcp. I called it from curl with a second terminal session as the "helper":

curl -s http://127.0.0.1:18913/mcp -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"session_follow","arguments":{
        "follower":"sess_39a6688d","selector":{"sessionIds":["sess_4dfc666d"]},
        "events":["turn-end","exited","crashed"],"key":"helpers","batchMs":2000}}}'

The answer holds a fol_... id and an expiry seven days out. When the helper's 25-second command ended, the follower's inbox got:

[session-follow] automatic digest — 1 event from sessions you follow. Decide whether anything needs the human's attention; if not, no reply is needed.
[session-follow] sess_4dfc666d exited ...

A follow's default batch window is 15 seconds. session_follows lists your follows and session_unfollow removes one by key. A session never gets its own events.

6. Give a chat assistant the events

A chat assistant cannot reach http://127.0.0.1 on your laptop. For that, the daemon can mount a second, public origin that serves only the events surface. It is off unless you set a secret:

AGENTPROTO_MCP_EVENTS_SECRET=<at least 32 characters> \
AGENTPROTO_MCP_EVENTS_REPOS=agentproto/ts \
agentproto serve --port 18914
  • AGENTPROTO_MCP_EVENTS_SECRET: the path secret. Under 32 characters, the route is not mounted.
  • AGENTPROTO_MCP_EVENTS_REPOS: a comma-separated list of owner/repo the origin may watch. Empty means every repo is refused.
  • AGENTPROTO_MCP_EVENTS_ORIGINS: browser Origin values to accept. None by default, so any request with an Origin header gets a 403.

The URL is https://<your-host>/mcp/events/<secret>. On my second test daemon, server/discover on it returned agentproto-events as the server name and only the events extension. tools/list returned one tool, events_ping, a liveness probe. A wrong secret gave 404 {"error":"not_found"}. A poll for a repo outside the list gave -32024, and a poll for the listed repo worked. This origin acts as its own principal, so it sees only subscriptions it created, and its secret grants nothing on /mcp.

A tunnel must forward only paths that start with /mcp/events/. A tunnel reaches the daemon from loopback, which skips the bearer check, so forwarding anything else would expose it. The repo's cloudflared example matches path: ^/mcp/events/ and sends the rest to http_status:404.

The integration doc notes that validation of this origin against ChatGPT is still pending.

7. Settings and limits

Two switches, both applied while the daemon runs:

agentproto config set mcp.eventsExtension false   # no poll, no stream; webhook only
agentproto config set mcp.eventsStream false      # no events/stream; "push" leaves `delivery`

I turned mcp.eventsStream off on my test daemon: events/list then showed poll,webhook and events/stream answered -32601. I turned it back on.

What to expect:

  • Not real time. The daemon asks GitHub every 15 seconds for the shared watch, and nextPollMs tells you so. A sentinel watching the same PR runs on its own check, which the sentinel guide puts at every 15 to 60 seconds. In my run the inbox message came about 30 seconds after the MCP event.
  • At least once. The same event can arrive twice. Keep a set of eventIds. Do not rely on order across subscriptions, and a webhook's order is best-effort.
  • Gaps are visible. truncated: true means you may have missed events. Re-read the PR with a normal tool.
  • Short memory. The journal keeps 24 hours and 5,000 entries. A watch with no reader is released after 5 minutes, and a new watch after a restart leaves a gap marker.
  • Payloads are untrusted data. A PR title can say anything. Fetch details with a tool and keep normal permissions on what the agent does next.
  • Beta. The extension text is Beta and the daemon's wire contract, AIP-76, is a draft.

Start here

  1. Install @agentproto/cli, log in to gh, and start agentproto serve.
  2. Call server/discover, then events/list, and note the four event names.
  3. Run the poll loop on a PR you own and close it. Keep the cursor, drop duplicate eventIds.
  4. To wake an agent, run agentproto sentinel watch pr <url> --session <id>, and check the inbox with agentproto sessions inbox <id>.
  5. Only add a stream, a webhook or the public origin when polling is not enough, and test each with a visible step.

MCP Events, explained · Get your agent to react when a PR merges · MCP Events specification · AIP-76 · Runtime source