Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions .github/workflows/muse-events-test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: "mcp-events for Muse"

on:
push:
paths:
- "polyfills/events/muse/**"
- ".github/workflows/muse-events-test.yml"
pull_request:
paths:
- "polyfills/events/muse/**"
- ".github/workflows/muse-events-test.yml"

permissions:
contents: read

defaults:
run:
working-directory: polyfills/events/muse

jobs:
adapter:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38
with:
node-version: 22
- run: npm ci
- run: npm run typecheck
- run: npm test
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ Claude Code 2.1.332+ includes native Skills in beta. [Migrating from the older p
The Antigravity App renders MCP Apps natively. Copilot CLI advertises Skills and its VS Code integration enables Apps. [Copilot compatibility notes](polyfills/events/copilot/README.md#skills-and-apps-in-copilot).

[T3 Code](docs/t3-code.md) uses the underlying agent’s plugins and has a dedicated Events adapter for Codex threads.
[Muse's experimental Events adapter](polyfills/events/muse) uses Cloudflare Workers and a native Muse hook. Live tests covered a public poll and a signed T3 Code webhook.

## Compatibility and security

Expand Down
3 changes: 3 additions & 0 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ Code closes, until no thread has a watch, and wakes a thread with T3 Code's
`t3 thread send`. The turn it starts runs in the thread's own permission
mode. It reads no stored credentials, Codex's or T3 Code's.

For Meta's cloud-hosted Muse personal agent, see [mcp-events for Muse](polyfills/events/muse/SECURITY.md)
(Cloudflare Worker + Durable Object with a credential-free native Muse polling hook).

These are third-party plugins and extensions that run with your permissions
in each host.

Expand Down
10 changes: 10 additions & 0 deletions docs/host-changes.md
Original file line number Diff line number Diff line change
Expand Up @@ -581,6 +581,16 @@ details:
server with the user's sign-in, which a scope declared by the plugin would
narrow.

### In Muse

- A documented external wake interface could accept an authenticated request
containing an opaque inbox reference and start a worker in a chosen chat.
The [experimental Muse adapter](../polyfills/events/muse) uses a native
polling hook to avoid scheduled model turns. Delivery depends on the hook
scheduler and the worker's connector access, including after VM suspension.
- Native SEP-3415 support could discover and watch Events on a connector's
authenticated connection, eliminating the separate Cloudflare OAuth sign-in.

## What these changes don't cover

- **Events:** a public address for webhook delivery, and sessions that run
Expand Down
4 changes: 4 additions & 0 deletions polyfills/events/muse/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules/
.wrangler/
.dev.vars*
.env*
221 changes: 221 additions & 0 deletions polyfills/events/muse/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
# MCP Events for Muse

**Experimental** host polyfill implementing the client side of the MCP Events extension ([SEP-3415, Final](https://modelcontextprotocol.io/seps/3415-events-extension), and the [Beta Events extension](https://github.com/modelcontextprotocol/ext-events) over MCP `2026-07-28`) for Meta's cloud-hosted **Muse** personal agent.

Wake an idle Muse chat only when a watched MCP server emits a matching event — with **zero scheduled model runs** and **zero idle token burn**.

## Quickstart (3 steps)

Requires **Node.js 22.18+**, a **Cloudflare account** (Workers Free or Paid with SQLite Durable Objects), and a **Muse account** with private custom connectors and native event hooks. Deploy one Worker per Muse account.

### 1. Deploy the Worker

```sh
git clone https://github.com/idosal/AgentPolyfill
cd AgentPolyfill/polyfills/events/muse
npm ci
npx wrangler login
npm run setup
```

`npm run setup` deploys the Worker + SQLite Durable Object, creates separate encrypted **`READER_KEY`** (for Muse's MCP connector) and **`ADMIN_KEY`** (for operator CLI commands) Wrangler secrets (never printed), copies the raw reader key on macOS, and verifies `/healthz`, `/mcp`, and `/admin/servers`.

### 2. Install the connector and hook in Muse

Generate and copy the one-shot Muse setup prompt:

```sh
npm run setup -- prompt
```

*(Optional: pass `--interval 15` to poll every 15 seconds instead of the default 60 seconds.)*

Paste the copied prompt into the Muse chat where you want event reports. Muse will:
1. Create the private **MCP Events** Streamable HTTP connector (`https://<your-worker>.workers.dev/mcp`) and ask you to enter the raw reader key in its secure credential field. *(Run `npm run setup -- reader-key` anytime on macOS to copy it again, or read `readerKey` privately from `~/.muse-events-worker.json`.)*
2. Install `~/hooks/scripts/mcp-events.sh`, register the native `mcp-events` Bash hook, dry-run it, and verify `tools/list`.

### 3. Enable wakes

Once Muse confirms the idle dry-run succeeded and the connector tools are available, turn on the wake feed:

```sh
npm run setup -- wake-on
```

**Done.** Your laptop can sleep and watches keep running 24/7.

---

## How it works

```
MCP servers (SEP-3415) ──events/poll · signed webhooks──► Cloudflare Worker + SQLite Durable Object
├─ stores events & manages OAuth / renewals
├─ GET /wake ──► 204 (idle) or 200 {"signal":"..."}
└─ POST /mcp ──► 8 MCP tools (READER_KEY)
Muse cloud VM (native Bash hook, every 60s) ──GET /wake─────►│
└─ on 204: exits silently (zero model turns) │
└─ on 200: wakes Muse worker ──POST /mcp (read_batch + ack_batch)──► reports events in chat
```

- **Zero idle model tokens:** The native Muse Bash hook (`scripts/muse-hook.sh`) sends `GET /wake` with no credentials. When the inbox is empty, the Worker returns `204` and the Bash script exits silently — no Muse model turn starts.
- **$0 idle Cloudflare cost:** At the default 60-second poll interval, one hook makes **1,440 Worker requests/day** and ~**1,440 Durable Object requests/day**, well inside Cloudflare's free allowance of 100,000/day for each.
- **Public, payload-free wake signal:** When `wake-on` is enabled, anyone who knows the Worker URL can observe when a batch is offered (`204` idle vs `200` with one random hex signal). The `/wake` endpoint never exposes payloads, counts, watch names, or credentials, accepts no state changes, and cannot authorize `read_batch` or `ack_batch`. Run `npm run setup -- wake-off` anytime to park wakes while keeping watches and the inbox active.
- **What Muse's platform supports today:** Meta documents [custom connectors and secure credential storage](https://muse.ai/blog/security-and-safety-for-ai-agents-our-approach-with-muse); see also [Muse custom integrations](https://parallel.ai/articles/meta-muse-custom-integrations) and the [Muse hook reference](https://gist.github.com/juleskuehn/480139a0ea9509e9b085459a045e03dd#namespace-hooks). Because Muse has no documented external wake POST API yet, the native polling hook is the verified zero-idle-token bridge. Unattended hook persistence across VM suspension or replacement remains unverified; check hook availability and connector permissions on your account.

---

## What Muse can do with it

The Worker exposes **8 MCP tools** on `/mcp` (the 6 MCP Events tools plus `read_batch` and `ack_batch` for Muse's wake-and-acknowledge flow):

| You say | Tool | Access |
|---|---|---|
| *(Automatic on hook wake)* | `read_batch` | Read-only (paginated `untrustedEvents` + `notices` for a signal) |
| *(Automatic after reporting)* | `ack_batch` | Advances the inbox cursor without deleting stored events |
| "What can you watch on my servers?" | `list_event_types` | Read-only |
| "Watch this T3 thread and tell me when it finishes." | `watch_event` | Creates a persistent watch |
| "What are you watching? Any delivery issues?" | `list_watches` | Read-only (includes delivery health) |
| "Show me event `e12` in full." | `get_event` | Read-only |
| "Show the last 10 events." | `recent_events` | Read-only |
| "Stop watching that thread." | `unwatch_event` | Stops watch & unsubscribes on upstream server |

---

## Prompt examples for Muse

Copy and paste any of these directly into your Muse chat once setup is complete.

### Try it live (30 seconds — built-in `demo` server)

Ido's public `demo` server (`https://event-feeds.idosalomon.workers.dev/mcp`) is pre-configured out of the box:

1. Open a fresh [private demo button](https://event-feeds.idosalomon.workers.dev/b/new) and copy its channel ID.
2. Send this to Muse:
> Call `watch_event` on **MCP Events** for server `demo`, event `demo.button`, arguments `{"channel": "<YOUR_CHANNEL>"}`, and note `"Tell me what I typed when I press the button."`
3. Let the chat sit idle for two hook polls (~2 minutes) and confirm Muse stays quiet.
4. Press the demo button **once** and wait ~60 seconds without messaging Muse.
5. **Acceptance check:** Confirm Muse wakes unattended, reports `press-1` from `demo.button`, and run `npm run setup -- list-servers` to confirm `Pending events: 0` and a fresh `Last acknowledgment: ... (reader)`.
6. Stop the test watch:
> Stop watching the demo button on **MCP Events**.

### Watch a T3 Code thread (after connecting `t3-current` below)

> Call `watch_event` on **MCP Events** for server `t3-current`, event `thread.run_settled`, arguments `{"threadId": "<THREAD_ID>"}`, and note `"Read the finished thread via my T3 Code connector and summarize the outcome in 3 bullets; keep any follow-up actions manual."`

### Watch any T3 Code thread finish (no thread filter)

> Call `watch_event` on **MCP Events** for server `t3-current`, event `thread.run_settled`, and note `"Tell me which T3 thread finished, read its latest message, and summarize what changed."`

### Watch public feeds on `demo` (`event-feeds`)

- **GitHub releases:**
> Watch `github.release` on `demo` with `{"repo": "idosal/AgentPolyfill"}` and note `"Summarize the release notes and include the release link."`
- **npm package releases:**
> Watch `npm.release` on `demo` with `{"package": "@modelcontextprotocol/sdk"}` and note `"Tell me the new version and summarize what changed."`
- **Hacker News comments:**
> Watch `hn.comment` on `demo` with `{"itemId": 12345678}` and note `"Summarize any new comments mentioning MCP or agents."`

### Inspect and manage watches

- **Discover available events:**
> Call `list_event_types` on **MCP Events** and list what I can watch on each server.
- **Check active watches and inbox health:**
> Call `list_watches` on **MCP Events** and tell me what's active and whether anything is pending or held.
- **Review recent history:**
> Call `recent_events` on **MCP Events** with `limit: 10` and summarize the latest events.
- **Stop a watch:**
> Call `unwatch_event` on **MCP Events** for watch `<w-xxxxxx>`.

---

## Connect T3 Code or another MCP Events server

### Option 1 — OAuth 2.1 browser sign-in (recommended for T3 Code)

For **T3 Code**, copy the public MCP URL from the specific environment that owns the thread you want to watch. If you have multiple T3 environments, verify that the relay's `environmentId` matches the first ID in your thread's `https://app.t3.codes/threads/<environmentId>/<threadId>` URL before signing in (a watch on a different environment will register cleanly but receive zero events):

```sh
T3_MCP_URL="https://YOUR-T3-RELAY.t3coderelay.com/mcp"
curl -fsS "${T3_MCP_URL%/mcp}/.well-known/t3/environment" | jq '{environmentId, label}'
npm run setup -- login t3-current "$T3_MCP_URL" orchestration:read
npm run setup -- list-servers
```

Open the printed URL in any browser and choose **Read only → Approve**. The Worker uses OAuth 2.1 dynamic client registration with PKCE, rotates refresh tokens automatically, rejects grants broader than the requested scope, attempts to revoke both access and refresh tokens on rejection or removal, and explicitly reports whether the provider confirmed revocation.

To verify T3 → Muse end to end: ask Muse to watch `thread.run_settled` on `t3-current` for a test thread, let Muse go idle, send a **fresh prompt** in that T3 thread, and let the run finish. *(Moving an idle thread to the Settled shelf does not emit `thread.run_settled`.)*

### Option 2 — Static bearer token or public server

```sh
npm run setup -- add-server my-server https://your-mcp-server.example.com/mcp
```

Setup scopes your local static server map to the active Worker URL and verifies Wrangler's live deployment version before uploading `UPSTREAM_SERVERS`, preventing credentials from crossing deployments.

---

## Operator CLI commands

All administrative commands authenticate with `ADMIN_KEY` (never Muse's `READER_KEY`):

| Command | Purpose |
|---|---|
| `npm run setup` | Deploy/update Worker, keep/create `READER_KEY` and `ADMIN_KEY`, verify live endpoints |
| `npm run setup -- prompt [--interval S] [origin]` | Print (and copy on macOS) the Muse connector + hook setup prompt (default `60`s poll) |
| `npm run setup -- reader-key` | Copy the raw `READER_KEY` to the macOS clipboard |
| `npm run setup -- wake-on` | Enable public `/wake` signals and resume any pending delivery |
| `npm run setup -- wake-off` | Disable `/wake` signals (parks delivery while keeping watches & inbox active) |
| `npm run setup -- login <name> <url> [scope]` | Connect an OAuth 2.1 MCP server via browser sign-in |
| `npm run setup -- add-server <name> <url>` | Add/update a static server in `UPSTREAM_SERVERS` |
| `npm run setup -- list-servers` | List effective servers (built-in, static, OAuth) and delivery/acknowledgment health |
| `npm run setup -- remove-server <name>` | Retire active watches, remove stored sign-in, and report OAuth revocation status |
| `npm run setup -- retry` | Clear a held batch and reoffer it on `/wake` |
| `npm run setup -- accept <BATCH>` | Record an operator acknowledgment for the exact held batch shown by `list-servers` |
| `npm run setup -- --rotate` | Rotate both keys (`--rotate-reader` or `--rotate-admin` for one) |
| `npm run setup -- help` | Show CLI usage |

---

## Delivery, stand-down, and limits

- **Batching, retry, and hold:** Matching events are batched and offered on `/wake` until `ack_batch` succeeds. Unanswered offers retry with exponential backoff and hold after 4 unanswered offers (default rate cap: 6 offers/hour, at least 60 seconds apart). The hook ignores duplicate polls of the same signal.
- **Recovery:** Run `npm run setup -- retry` to reoffer a held batch, or `npm run setup -- accept <batch>` after independently confirming the exact batch shown by `list-servers`. Repeated offers can cause duplicate reports if Muse finished its work before calling `ack_batch`.
- **Backlog cap & backpressure:** Pending unacknowledged events are capped at 5,000 by default (`MAX_PENDING_EVENTS`). When full, polling pauses and `/hooks/*` returns HTTP `503` with `Retry-After` so upstreams retry later. Watch notices remain readable via `recent_events` and never wake Muse on their own.
- **Protocol modes:** Supports `webhook` and `poll` delivery over Streamable HTTP (MCP `2026-07-28` with narrow legacy `initialize` fallback). Upstreams that only support long-lived `push` (SSE) streams require a different host adapter. Set `MCP_EVENTS_PRE_STANDARD=off` in `wrangler.jsonc` to enforce strict SEP-3415 declarations only.
- **Stand-down:** Set `MCP_EVENTS_OFF=1` in `wrangler.jsonc` and redeploy (`npm run deploy`) to stop alarms, hide all MCP tools, and disable `/wake`, `/hooks/*`, and OAuth. After turning stand-down back off, run `npm run setup -- retry` to resume retained batches.

---

## Troubleshooting & FAQ

- **Why did an event take ~1 minute to show up in Muse?**
The Worker receives signed webhooks in under a second, and Muse's Bash hook polls `/wake` every `poll_interval_secs` (default `60`). To reduce latency, regenerate the hook with a shorter interval (`npm run setup -- prompt --interval 15`) and ask Muse to update the `mcp-events` hook.
- **My T3 Code watch is active, but zero events arrive.**
Confirm the T3 relay URL belongs to the same `environmentId` as your thread (`curl -fsS "${T3_MCP_URL%/mcp}/.well-known/t3/environment" | jq '{environmentId, label}'`), and send a fresh prompt in the thread so a run actually finishes (`thread.run_settled` does not fire when moving an idle thread to Settled).
- **How do I confirm Muse actually read and acknowledged a wake?**
Run `npm run setup -- list-servers` and check for `Pending events: 0` and a recent `Last acknowledgment: <timestamp> (reader)`.
- **Delivery says `Held batch: ...`.**
Fix any connector permission or hook issue in Muse, then run `npm run setup -- retry` (to reoffer the batch) or `npm run setup -- accept <batch>` (if Muse already reported it).

---

## Security

See [SECURITY.md](SECURITY.md) for the credential boundary, `/wake` trade-offs, webhook verification, OAuth scope/revocation handling, and Durable Object storage details.

## Tests and verification

```sh
npm ci
npm run typecheck
npm test
```

- **Automated tests (`npm test`):** Runs Wrangler locally with temporary SQLite storage and loopback fixtures (`test/worker.test.ts`, `test/muse-hook.test.ts`, `test/setup.test.ts`). Covers modern MCP `2026-07-28` and strict `MCP_EVENTS_PRE_STANDARD=off` mode, raw-byte webhook signature and streaming size checks, replay and cursor behavior, interrupted subscription recovery, OAuth PKCE/scope/revocation/401 refresh rotation, `READER_KEY`/`ADMIN_KEY` separation, wake offers and recovery, deployment-pinned static secret uploads, stand-down, and Bash hook simulation (requires `jq`).
- **Live Muse verification:** Tested end-to-end on a live Muse account with both the public `demo` poll server (`demo.button`) and a signed T3 Code webhook (`thread.run_settled`, OAuth `orchestration:read`). In the T3 run, the Worker received the webhook in under a second and Muse's reader acknowledged it ~62 seconds after the run ended. *(Live verification preceded the final review-hardening fixes; repeat the 4-step verification above after redeploying to confirm long-idle hook persistence on your account.)*

## Licence

Part of [AgentPolyfill](../../../README.md). Apache-2.0 — see [LICENSE](../../../LICENSE).
Loading