Skip to content
Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@

- **The `watch` skill without the plugin:** `npx skills add hookdeck/mcp-events-bridge` also installs the plugin's `watch` skill, and without the plugin its `events-bridge` commands fail with `command not found`. The skill now tells the agent to stop and explain how to install the plugin, or what to use outside Claude Code. To install only the setup skill, add `--skill mcp-events-bridge`.

### Fixed

- **Poll tools on a bridge with no subscriptions:** `wait_for_event`, `poll_events`, `events/poll`, `watch`, `get_event` and `list_events` returned no events until something subscribed. A source has a connection only per subscription, and Event Gateway rejects requests to a source with no connection as `NO_CONNECTION` (the sender still gets `200`, and the request is kept); the bridge listed only accepted requests. It now also reads verified requests rejected as `NO_CONNECTION`. Broken since 0.8.0.

## 0.9.0 (2026-11-05)

Breaking, for agents that call `create_callback_url` again for an existing URL with a different `port` or `path`: that's now an error.
Expand Down
4 changes: 2 additions & 2 deletions docs/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -351,13 +351,13 @@ Designed 8 Oct ([#26](https://github.com/hookdeck/mcp-events-bridge/issues/26))

**One shared listing.** The Hookdeck API allows 240 requests per minute per API key, shared with recovery, `get_event` and setup. One poll loop at 2 seconds is 30 a minute, so listings are shared:

- **The live window:** `GET /requests?source_id=<A>&source_id=<B>...&status=accepted&created_at[gte]=<now - L - 65 s>&order_by=created_at&dir=asc&include=data&limit=255`, paged with `next`. Several sources go in one call as a repeated `source_id` (or `source_id[]`); `source_id=A,B` silently returns nothing (verified 8 Oct). It reaches 65 seconds past L because a cursor's watermark is its listing's time less L, that listing can be an interval old when served, and the client waits another interval: two of the longest (30 s) plus a margin for the clock estimate keep a client that polls at `nextPollMs`, even backed off, on the window.
- **The live window:** `GET /requests?source_id=<A>&source_id=<B>...&created_at[gte]=<now - L - 65 s>&order_by=created_at&dir=asc&include=data&limit=255`, paged with `next`. Several sources go in one call as a repeated `source_id` (or `source_id[]`); `source_id=A,B` silently returns nothing (verified 8 Oct). It reaches 65 seconds past L because a cursor's watermark is its listing's time less L, that listing can be an interval old when served, and the client waits another interval: two of the longest (30 s) plus a margin for the clock estimate keep a client that polls at `nextPollMs`, even backed off, on the window.
- **Fetched on demand:** a poll that finds the window more than 2 seconds old fetches it, and polls that arrive during a fetch wait for the same one, and share its failure. No polls, no calls. Every poll and `wait_for_event` reads the same window, so live polling costs about 30 calls a minute (more pages at high event rates), however many clients poll, as long as each polls at the `nextPollMs` it's given; a client slower than about a minute and a half catches up instead (below).
- **Only polled sources:** the window lists the sources polled in the last 60 seconds. A poll for a source not in the window adds it and fetches the window again at once; a source no poll has asked for in 60 seconds is dropped at the next fetch.
- **Catch-up:** a poll whose watermark is older than the window (after a gap, or draining a backlog) lists its own source from its watermark, at most two pages, and returns `hasMore` if there's more. Its rate limit feeds the back-off, and there's no catch-up while backing off.
- **Back-off:** the bridge tracks `X-RateLimit-Remaining`. Below a quarter of the limit, the window's refresh interval and `nextPollMs` grow, up to 30 seconds, and come back to 2 seconds as it recovers; a backlog then drains at that pace, not at once. A `429` (on the window or a catch-up) doesn't fail a poll: it's answered from the existing window if that covers the source, or else with no events, the same cursor and `nextPollMs` of 30 seconds. After a failed call, the bridge makes no listing calls for 30 seconds (2 after other errors).

**Which requests are events,** whatever Event Gateway did with each (since 0.8.0; until then poll matched what the relay would have delivered, from each request's events and ignored events on the inbound connection). `status=accepted` drops `VERIFICATION_FAILED`. Then each request is mapped by the source's runtime (as for `get_event`, and as the transformation does), and kept if the event's name matches and its `data` matches the event's `filter(args)` (`matchesFilter`, the same filter as the subscription connection's). A request without `data` that's newer than L is held: it isn't returned, and the watermark doesn't pass it. Repeats are dropped by `eventId`, so a sender's retry with the same id is returned once while the cursor still holds the first's id. An event's `timestamp` is the source's, or else the request's `created_at`.
**Which requests are events,** whatever Event Gateway did with each (since 0.8.0; until then poll matched what the relay would have delivered, from each request's events and ignored events on the inbound connection). A request is a candidate if it's verified and either accepted or rejected as `NO_CONNECTION` (`isEventRequest`): a source has a connection only per subscription, so until something subscribes, Event Gateway rejects every request as `NO_CONNECTION`, while still answering the sender `200` and keeping the request, verified, with its data. In 0.8.0 to 0.9.0 the listing asked for `status=accepted`, so poll, `get_event` and `list_events` saw nothing on a bridge with no subscriptions. `VERIFICATION_FAILED` and any other rejection are dropped. Then each request is mapped by the source's runtime (as for `get_event`, and as the transformation does), and kept if the event's name matches and its `data` matches the event's `filter(args)` (`matchesFilter`, the same filter as the subscription connection's). A request without `data` that's newer than L is held: it isn't returned, and the watermark doesn't pass it. Repeats are dropped by `eventId`, so a sender's retry with the same id is returned once while the cursor still holds the first's id. An event's `timestamp` is the source's, or else the request's `created_at`.

**The cursor, and late requests.** A request appears in the listing about 2 seconds after its `created_at` (up to 15), and out of order: in the spike, a quarter appeared after one with a later `created_at` was already listed. A cursor at the newest request seen would skip them, so the cursor re-reads a window:

Expand Down
12 changes: 11 additions & 1 deletion src/core/event-history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,16 @@ import { providerSourceName } from './names.js';
export const RECENT_PAGE_SIZE = 100;
export const RECENT_MAX_REQUESTS_PER_SOURCE = 500;

/**
* Whether Event Gateway kept a request as a provider's event: verified, and either accepted or rejected only because
* its source had no connection. A source has a connection per subscription, so with no subscriptions every request is
* rejected as `NO_CONNECTION` (the sender still gets `200`, and the request is kept, verified, with its data); poll and
* the history must still see them. Any other rejection, such as `VERIFICATION_FAILED`, isn't an event.
*/
export function isEventRequest(request: Pick<HookdeckRequest, 'verified' | 'rejection_cause'>): boolean {
return !!request.verified && (!request.rejection_cause || request.rejection_cause === 'NO_CONNECTION');
}

export interface PastEvent {
eventId: string;
name: string;
Expand All @@ -37,7 +47,7 @@ export class EventHistory {

/** Maps a stored request to its MCP event, or undefined if it isn't a verified, enabled event. */
toEvent(providerId: string, request: HookdeckRequest): PastEvent | undefined {
if (!request.verified || request.rejection_cause || !request.data) return undefined;
if (!isEventRequest(request) || !request.data) return undefined;
const headers = Object.fromEntries(Object.entries(request.data.headers ?? {}).map(([k, v]) => [k.toLowerCase(), String(v)]));
const req = { headers, body: request.data.body, receivedAt: request.created_at };
const entry = this.deps.catalog.forProvider(providerId).find((e) => e.runtime.matches(req));
Expand Down
9 changes: 5 additions & 4 deletions src/core/hookdeck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,15 +297,16 @@ export class HookdeckClient {
}

/**
* Accepted requests to several sources, oldest first, with headers and body: poll mode's listing. One call covers
* every source (a repeated `source_id`); the meta has Event Gateway's clock and the rate limit.
* Requests to several sources, oldest first, with headers and body: poll mode's listing. One call covers every
* source (a repeated `source_id`); the meta has Event Gateway's clock and the rate limit. Not only accepted ones: a
* source with no subscriptions has no connection, and Event Gateway rejects its requests as `NO_CONNECTION` while
* keeping them, verified, with their data. `isEventRequest` decides which are events.
*/
async listAcceptedRequests(query: { source_ids: string[]; created_at_gte: string; limit?: number; next?: string }): Promise<{ page: Page<HookdeckRequest>; meta: ResponseMeta }> {
async listPollRequests(query: { source_ids: string[]; created_at_gte: string; limit?: number; next?: string }): Promise<{ page: Page<HookdeckRequest>; meta: ResponseMeta }> {
const { body, meta } = await this.apiWithMeta<Page<HookdeckRequest>>('/requests', {
retry: false,
query: {
source_id: query.source_ids,
status: 'accepted',
include: 'data',
'created_at[gte]': query.created_at_gte,
limit: query.limit ?? 255,
Expand Down
17 changes: 9 additions & 8 deletions src/core/poll.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { canonicalJson } from './canonical-json.js';
import type { Catalog } from './catalog.js';
import { internalError, invalidParams, notFound } from './errors.js';
import { matchesFilter } from './filter.js';
import type { EventHistory, PastEvent } from './event-history.js';
import { isEventRequest, type EventHistory, type PastEvent } from './event-history.js';
import { HookdeckApiError, type HookdeckClient, type HookdeckRequest, type ResponseMeta } from './hookdeck.js';

/*
Expand Down Expand Up @@ -70,27 +70,27 @@ interface CursorState {
}

interface Listing {
/** Accepted requests, oldest first. */
/** Requests, oldest first: accepted ones, and those rejected only because the source had no connection. */
requests: HookdeckRequest[];
/** Event Gateway's clock when the listing was taken. */
t: number;
/** Set when paging stopped early: created_at of the last request listed; nothing after it was read. */
until?: number;
}

type ListingClient = Pick<HookdeckClient, 'listAcceptedRequests'>;
type ListingClient = Pick<HookdeckClient, 'listPollRequests'>;

export class RateLimitedError extends Error {}

/** Reads accepted requests from `from` on, up to `maxPages`, with the meta of the last response. */
/** Reads the requests from `from` on, up to `maxPages`, with the meta of the last response. */
async function listFrom(hookdeck: ListingClient, sourceIds: string[], from: number, maxPages: number): Promise<{ requests: HookdeckRequest[]; meta: ResponseMeta; until?: number }> {
const requests: HookdeckRequest[] = [];
let next: string | undefined;
let meta: ResponseMeta = {};
for (let i = 0; i < maxPages; i++) {
let result;
try {
result = await hookdeck.listAcceptedRequests({ source_ids: sourceIds, created_at_gte: new Date(from).toISOString(), next });
result = await hookdeck.listPollRequests({ source_ids: sourceIds, created_at_gte: new Date(from).toISOString(), next });
} catch (error) {
if (error instanceof HookdeckApiError && error.status === 429) throw new RateLimitedError('Event Gateway API rate limit reached');
throw error;
Expand All @@ -106,7 +106,7 @@ async function listFrom(hookdeck: ListingClient, sourceIds: string[], from: numb
}

/**
* The shared listing: the accepted requests of every source polled in the last minute, from LOOKBACK_MS (plus
* The shared listing: the requests of every source polled in the last minute, from LOOKBACK_MS (plus
* WINDOW_EXTRA_MS) before Event Gateway's now. Fetched when a poll finds it older than the interval or missing its
* source; polls that arrive during a fetch share it, and its failure. After a failure, no fetch until `retryAt`. The
* interval grows as the API's rate limit runs low.
Expand Down Expand Up @@ -371,10 +371,11 @@ export class PollService {
let hasMore = false;
const holdAt = (at: number) => (hold = hold === undefined ? at : Math.min(hold, at));

// Every verified request is an event candidate (Event Gateway rejected the rest at the source); a repeat (a sender
// Every verified request is an event candidate, including one rejected only because the source had no connection
// (no subscriptions yet); a request that failed verification isn't, and can't hold the watermark. A repeat (a sender
// resending, or a request retried) has an event id already returned, and is skipped.
for (const request of listing.requests) {
if (request.source_id !== sourceId) continue;
if (request.source_id !== sourceId || !isEventRequest(request)) continue;
const created = Date.parse(request.created_at);
if (created < start) continue;
const event = this.deps.history.toEvent(entry.providerId, request);
Expand Down
18 changes: 18 additions & 0 deletions test/core/event-history.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,24 @@ describe('EventHistory.recent', () => {
expect(await history.recent({ name: 'nope.order.filled' })).toEqual([]);
});

it('includes requests to a source with no subscriptions (rejected as NO_CONNECTION), but not ones that failed verification', async () => {
const config = resolveConfig(defineConfig({ sources: [broker('broker_a')] }), { HOOKDECK_API_KEY: 'k', HOOKDECK_SIGNING_SECRET: 's' });
const request = (id: string, verified: boolean, rejection_cause: string | null) => ({
id: `req_${id}`,
verified,
rejection_cause,
data: { headers: { 'x-delivery-id': id }, body: { symbol: 'AAPL' } },
});
const hookdeck = {
listSources: async ({ name }: { name: string }) => ({ models: [{ id: `src_${name}` }] }),
listRequests: async () => ({ models: [request('no-subscriptions', true, 'NO_CONNECTION'), request('bad-signature', false, 'VERIFICATION_FAILED')] }),
} as unknown as HookdeckClient;
const history = new EventHistory({ hookdeck, catalog: new Catalog(config.sources), providers: config.sources });

expect((await history.recent({ name: 'broker_a.order.filled' })).map((e) => e.eventId)).toEqual(['no-subscriptions']);
expect((await history.get('broker_a.order.filled', 'no-subscriptions'))?.eventId).toBe('no-subscriptions');
});

it('times an event without occurredAt by when Event Gateway received it, not when it was read back', async () => {
const config = resolveConfig(defineConfig({ sources: [broker('broker_a')] }), { HOOKDECK_API_KEY: 'k', HOOKDECK_SIGNING_SECRET: 's' });
const hookdeck = {
Expand Down
Loading
Loading