Skip to content

feat(events): push delivery (events/stream) #137

Closed

Description

@ChiragAgg5k

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's notifications/events/*.
  • Invalid subscription. NotFound, Forbidden, InvalidParams or Unsupported is 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/active first: {cursor, truncated}.
    • notifications/events/event: the EventOccurrence {eventId, name, timestamp, data, cursor} we already build for webhooks.
    • notifications/events/heartbeat {cursor} at least every 30 s, as an SSE data: frame (not an SSE comment).
    • notifications/events/error for 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 cursor is always null and truncated is false; maxAgeMs is 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/stream from 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-subscriptions profile) 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.py refreshes it and cleans up webhooks expired for over 10 minutes on each subscribe.
  • ingress.py serves POST /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 to delivery.py (signed Standard Webhooks POST via SSRF-safe egress.py, in-process retries).
  • protocol.py registers events/list, events/subscribe and events/unsubscribe with Server.add_request_handler and patches the capability into server/discover/initialize (python-sdk#3640). Everything is behind flags.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

  1. events/stream validates exactly like events/subscribe (catalog lookup, argument schema, scopes, project access, webhooks.write) by reusing the Subscriptions checks, minus the callback, secret and verification handshake.
  2. 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 PUT like 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.
  3. Send notifications/events/active {cursor: null, truncated: false}, then loop: forward events from Bus.listen(id) as notifications/events/event, send notifications/events/heartbeat {cursor: null} every ~25 s, renew the lease on schedule.
  4. 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.
  5. If a lease renewal or delete returns 401/403 (token expired or access revoked), send notifications/events/terminated with -32024 Forbidden and 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_handler handler for events/stream stream SSE notifications for its own request on mcp 2.3.0's Streamable HTTP transport (as the hosted app configures it; check http_app.py for stateless/JSON-response mode), and is it exempt from any concurrency or timeout limits? If not, serve events/stream with a dedicated ASGI branch in http_app.py that runs the same auth as the MCP endpoint, the way /appwrite/webhooks/* bypasses the SDK. Record the choice in the module docstring.
  • Advertise "push" in describe() only when push is available (flag on and a bus configured).
  • Gate push behind its own flag (MCP_EVENTS_PUSH in flags.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 ResourceExhausted with data.limit.
  • Free-plan projects allow 2 webhooks; each open stream uses one. Map Appwrite's limit error the way _webhook_error does today.
  • Heartbeat ≤ 30 s keeps idle connections alive through the gateway; confirm Traefik's idle/read timeouts for mcp.appwrite.io and mcp.staging.appwrite.io in application-configuration and 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) on mcp.events.deliveries; add panels to appwrite-labs/monitoring dashboards/Cloud/mcp.json (Events row).
  • Update docs/events.md (delivery modes, push lifecycle, limits, Redis), docs/development.md (local Redis), docs/flags.md, and AGENTS.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 in tests/e2e/support.py and the fake Appwrite used by test_events_subscribe.py/test_events_ingress.py):
    • open events/stream over real HTTP with httpx streaming; assert active first, then a projected event after posting a signed Appwrite webhook to the ingress, with the right _meta subscription 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, Unsupported for push on an event without it, ResourceExhausted at the cap);
    • token revoked mid-stream → terminated;
    • push flag off: events/list advertises webhook only and events/stream returns -32601.
  • CI: the e2e job needs Redis (a services: redis entry in .github/workflows/ci.yml).
  • Manual: run pi-mcp-events (pi install npm:pi-mcp-adapter@^5.1.0 and npm:@realmikekelly/pi-mcp-events@^0.2.0) against staging with the push flag on, subscribe to users.user.created, create a user, confirm the agent wakes.

Rollout

  1. Spike the protocol-layer question above and post the result here.
  2. Bus + push behind MCP_EVENTS_PUSH, e2e green, PR(s).
  3. Redis for staging MCP in application-configuration; enable push on staging; verify with pi-mcp-events.
  4. Production Redis, then enable push in production.

Acceptance criteria

  • events/list advertises push only when push is enabled.
  • events/stream delivers Appwrite events across replicas, with active, event, heartbeat, error and terminated per 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

  1. self-assigned this
    on Oct 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions