Repository navigation
Description
Summary
Add push delivery (events/stream) to MCP Events, alongside the existing webhook delivery. Today events/list advertises "delivery": ["webhook"] for every event, so only ChatGPT can subscribe. Clients that run on a user's machine cannot receive webhooks and use push instead: the Pi extension pi-mcp-events (push only, events/list + events/stream) and the Codex CLI (0.148+, push via events/stream, currently only against OpenAI's hosted runtime). Claude Code, Cursor and VS Code have no Events support yet.
Tracks #127. Webhook delivery is live in production since v1.0.11 (verified end to end, including a real ChatGPT subscription on staging). This issue is a self-contained plan for an agent to pick up.
Spec: push delivery (draft)
Source: experimental-ext-triggers-events design sketch, section Push-Based Delivery; SEP-3415 is still a draft, so re-read both before starting and follow them over this summary.
- Request. One long-lived JSON-RPC request per subscription:
{"method": "events/stream", "id": N, "params": {"name", "arguments", "cursor", "maxAgeMs"?}}. On Streamable HTTP it is a POST whose response is an SSE stream carrying only this subscription'snotifications/events/*. - Invalid subscription.
NotFound,Forbidden,InvalidParamsorUnsupportedis returned as an immediate JSON-RPC error; no stream is opened. - Notifications. Every one carries the request id in
params._meta["io.modelcontextprotocol/subscriptionId"]:notifications/events/activefirst:{cursor, truncated}.notifications/events/event: theEventOccurrence{eventId, name, timestamp, data, cursor}we already build for webhooks.notifications/events/heartbeat{cursor}at least every 30 s, as an SSEdata:frame (not an SSE comment).notifications/events/errorfor a recoverable failure; the stream stays open.notifications/events/terminated{error}ends the subscription (access revoked, event type removed).
- Cancellation. The client aborts the HTTP request; the server must stop and release resources. No result is sent.
- Cursor. Our events have no replay, so
cursoris alwaysnullandtruncatedisfalse;maxAgeMsis ignored. Events during a reconnect gap are lost, which the spec allows for emit-only event types. - Advertising.
events/list→"delivery": ["webhook", "push"]. A push request for an event type without push returns-32026 Unsupported,data: {"feature": "deliveryMode", "value": "push"}. - Server SDKs must exempt
events/streamfrom request-concurrency caps.
Current design (read first)
docs/events.md and the module docstrings in src/mcp_server_appwrite/events/ are the source of truth. In short:
- The server is stateless. Each webhook subscription is one Appwrite webhook in the subscriber's project, whose id is the subscription id and whose Basic-auth password is a sealed JWE envelope (
envelope.py,mcp-event-subscriptionsprofile) holding everything needed to deliver: server, tenant, resource, event, arguments, callback, secret, expiry. - The webhook name carries the lease (
MCP events | <event> | until <ISO> | owner <principal>);subscriptions.pyrefreshes it and cleans up webhooks expired for over 10 minutes on each subscribe. ingress.pyservesPOST /appwrite/webhooks/{id}: checks retired keys, opens the envelope (expired →200 expired), verifies Appwrite's signature with the HKDF-derived key, projects the Appwrite payload (projection.py) and hands the event todelivery.py(signed Standard Webhooks POST via SSRF-safeegress.py, in-process retries).protocol.pyregistersevents/list,events/subscribeandevents/unsubscribewithServer.add_request_handlerand patches the capability intoserver/discover/initialize(python-sdk#3640). Everything is behindflags.EVENTS(MCP_EVENTS) and HTTP-only.- Telemetry:
mcp.events.subscriptions,mcp.events.ingress,mcp.events.deliveries(Grafana MCP dashboard, Events row). - Error codes follow ChatGPT's current values, not SEP-3415's renumbered ones (see
docs/events.md#errors).
The core problem: routing
A stream lives on one replica, but Appwrite's webhook POST to /appwrite/webhooks/{id} lands on any replica behind the gateway. Production runs 2+ replicas. The ingress therefore needs a cross-replica hop to the replica holding the stream.
Recommended: Redis pub/sub, channel mcp:events:<subscription id>. The ingress publishes the projected EventOccurrence; the stream's replica subscribes while the stream is open. Pub/sub is fire-and-forget, which matches no-replay semantics (an event published while no replica listens is dropped and counted). Redis is not deployed for MCP today: add it to compose.yaml for local/e2e and to appwrite-labs/application-configuration (assets/{staging,production}/mcp) via the generic chart or an existing Redis in the assets cluster; confirm with infra which. NATS is an acceptable alternative if infra prefers it; keep the transport behind a small interface (Bus.publish(id, event), Bus.listen(id) -> AsyncIterator) so the choice is one module.
Rejected: sticky routing (Appwrite calls one public URL; the gateway cannot route by subscription), and holding events in Appwrite (no queue primitive).
Design
Subscription lifecycle for a stream
events/streamvalidates exactly likeevents/subscribe(catalog lookup, argument schema, scopes, project access,webhooks.write) by reusing theSubscriptionschecks, minus the callback, secret and verification handshake.- Create an Appwrite webhook as today, with:
- a random id (push is connection-scoped; two streams with identical arguments are two subscriptions, unlike webhook mode's deterministic id),
- a short lease in the name (for example 5 minutes), renewed by the stream while it is open (for example every 2 minutes, a
PUTlike today's refresh), - an envelope marking the delivery mode as push, with no callback or secret. This likely needs a profile/field addition in
mcp-event-subscriptions(owned by @ChiragAgg5k); check the profile before inventing fields, and keep envelopes for webhook mode byte-compatible.
- Send
notifications/events/active {cursor: null, truncated: false}, then loop: forward events fromBus.listen(id)asnotifications/events/event, sendnotifications/events/heartbeat {cursor: null}every ~25 s, renew the lease on schedule. - On client abort or server shutdown: stop listening and delete the webhook (best effort). If the process dies, the lease expires and the existing expired-webhook cleanup removes it, while the ingress already drops expired envelopes with
200 expired. - If a lease renewal or delete returns 401/403 (token expired or access revoked), send
notifications/events/terminatedwith-32024 Forbiddenand end the stream. Transient Appwrite errors on renewal →notifications/events/error, keep the stream.
Open question for the implementer: lease renewal needs the subscriber's Appwrite credentials for the life of the stream. The bearer token on the events/stream request is the natural one; decide what happens when it expires mid-stream (terminate with Forbidden, letting the client reconnect with a fresh token, is the simplest correct answer).
Ingress
After the existing envelope and signature checks, branch on the envelope's delivery mode: webhook → delivery.py as today; push → Bus.publish(id, occurrence). Count a new ingress/delivery outcome for "no listener" so dropped push events are visible. Keep ingress latency bounded (publish is a single Redis call; do not wait for the stream).
Protocol layer
- The low-level SDK handler model returns one result per request. Spike first: can an
add_request_handlerhandler forevents/streamstream SSE notifications for its own request on mcp 2.3.0's Streamable HTTP transport (as the hosted app configures it; checkhttp_app.pyfor stateless/JSON-response mode), and is it exempt from any concurrency or timeout limits? If not, serveevents/streamwith a dedicated ASGI branch inhttp_app.pythat runs the same auth as the MCP endpoint, the way/appwrite/webhooks/*bypasses the SDK. Record the choice in the module docstring. - Advertise
"push"indescribe()only when push is available (flag on and a bus configured). - Gate push behind its own flag (
MCP_EVENTS_PUSHinflags.py, off by default) so webhook delivery can stay live while push rolls out.
Limits
- Per principal and per replica caps on open streams; refusals use
-32025 ResourceExhaustedwithdata.limit. - Free-plan projects allow 2 webhooks; each open stream uses one. Map Appwrite's limit error the way
_webhook_errordoes today. - Heartbeat ≤ 30 s keeps idle connections alive through the gateway; confirm Traefik's idle/read timeouts for
mcp.appwrite.ioandmcp.staging.appwrite.ioinapplication-configurationand raise them if they cut streams. - Rolling deploys drop every stream; that is expected (clients reconnect). On SIGTERM, close streams cleanly and delete their webhooks within the grace period.
Telemetry and docs
- New counter or up-down counter for open streams, and
mode(webhook/push) onmcp.events.deliveries; add panels toappwrite-labs/monitoringdashboards/Cloud/mcp.json(Events row). - Update
docs/events.md(delivery modes, push lifecycle, limits, Redis),docs/development.md(local Redis),docs/flags.md, andAGENTS.md's module table.
Tests
Follow the repo rule: extend e2e flows; unit tests only for what e2e cannot reach.
tests/e2e/test_events_stream.py(new flow, shared harness intests/e2e/support.pyand the fake Appwrite used bytest_events_subscribe.py/test_events_ingress.py):- open
events/streamover real HTTP withhttpxstreaming; assertactivefirst, then a projectedeventafter posting a signed Appwrite webhook to the ingress, with the right_metasubscription id; - two server instances sharing one Redis: stream on instance A, Appwrite webhook to instance B, event arrives on A (the reason this feature exists);
- heartbeat within the interval; lease renewal writes the webhook; client abort deletes the webhook; a killed server leaves a lease that expires and is cleaned up;
- invalid subscriptions return immediate errors (
NotFound,Forbidden,InvalidParams,Unsupportedfor push on an event without it,ResourceExhaustedat the cap); - token revoked mid-stream →
terminated; - push flag off:
events/listadvertises webhook only andevents/streamreturns-32601.
- open
- CI: the e2e job needs Redis (a
services: redisentry in.github/workflows/ci.yml). - Manual: run
pi-mcp-events(pi install npm:pi-mcp-adapter@^5.1.0andnpm:@realmikekelly/pi-mcp-events@^0.2.0) against staging with the push flag on, subscribe tousers.user.created, create a user, confirm the agent wakes.
Rollout
- Spike the protocol-layer question above and post the result here.
- Bus + push behind
MCP_EVENTS_PUSH, e2e green, PR(s). - Redis for staging MCP in
application-configuration; enable push on staging; verify withpi-mcp-events. - Production Redis, then enable push in production.
Acceptance criteria
-
events/listadvertisespushonly when push is enabled. -
events/streamdelivers Appwrite events across replicas, withactive,event,heartbeat,errorandterminatedper the spec. - Streams own exactly one Appwrite webhook each, removed on close and expired on crash.
- Webhook delivery is unchanged (existing e2e flows pass untouched).
- Verified on staging with a real push client.
Activity