diff --git a/CHANGELOG.md b/CHANGELOG.md index 31950e7..f35e193 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 38fd282..f92e54e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -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=&source_id=...&status=accepted&created_at[gte]=&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=&source_id=...&created_at[gte]=&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: diff --git a/src/core/event-history.ts b/src/core/event-history.ts index 7b0b616..738e497 100644 --- a/src/core/event-history.ts +++ b/src/core/event-history.ts @@ -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): boolean { + return !!request.verified && (!request.rejection_cause || request.rejection_cause === 'NO_CONNECTION'); +} + export interface PastEvent { eventId: string; name: string; @@ -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)); diff --git a/src/core/hookdeck.ts b/src/core/hookdeck.ts index 0f6d836..dcbed50 100644 --- a/src/core/hookdeck.ts +++ b/src/core/hookdeck.ts @@ -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; meta: ResponseMeta }> { + async listPollRequests(query: { source_ids: string[]; created_at_gte: string; limit?: number; next?: string }): Promise<{ page: Page; meta: ResponseMeta }> { const { body, meta } = await this.apiWithMeta>('/requests', { retry: false, query: { source_id: query.source_ids, - status: 'accepted', include: 'data', 'created_at[gte]': query.created_at_gte, limit: query.limit ?? 255, diff --git a/src/core/poll.ts b/src/core/poll.ts index 45c90db..a0aa6cb 100644 --- a/src/core/poll.ts +++ b/src/core/poll.ts @@ -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'; /* @@ -70,7 +70,7 @@ 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; @@ -78,11 +78,11 @@ interface Listing { until?: number; } -type ListingClient = Pick; +type ListingClient = Pick; 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; @@ -90,7 +90,7 @@ async function listFrom(hookdeck: ListingClient, sourceIds: string[], from: numb 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; @@ -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. @@ -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); diff --git a/test/core/event-history.test.ts b/test/core/event-history.test.ts index 4a52918..e52660a 100644 --- a/test/core/event-history.test.ts +++ b/test/core/event-history.test.ts @@ -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 = { diff --git a/test/core/poll.test.ts b/test/core/poll.test.ts index 455cb83..af0841a 100644 --- a/test/core/poll.test.ts +++ b/test/core/poll.test.ts @@ -29,6 +29,8 @@ interface FakeRequest { kind: 'event' | 'duplicate' | 'filtered' | 'cli-disconnected'; symbol: string; deliveryId: string; + /** Rejected at the source: `NO_CONNECTION` (no subscriptions, so no connection) or a failed signature. */ + rejection?: 'NO_CONNECTION' | 'VERIFICATION_FAILED'; } /** Event Gateway's request listing, with requests that appear late and out of order. */ @@ -51,22 +53,22 @@ class FakeListing { private view(r: FakeRequest): HookdeckRequest { const processed = this.now >= r.processedAt; - const events = processed && r.kind === 'event' ? 1 : 0; + const events = processed && !r.rejection && r.kind === 'event' ? 1 : 0; return { id: r.id, source_id: r.source_id, created_at: new Date(r.createdAt).toISOString(), - verified: true, - rejection_cause: null, + verified: r.rejection !== 'VERIFICATION_FAILED', + rejection_cause: r.rejection ?? null, events_count: events, cli_events_count: 0, - ignored_count: processed && r.kind !== 'event' ? 1 : 0, + ignored_count: processed && !r.rejection && r.kind !== 'event' ? 1 : 0, data: { headers: { 'x-delivery-id': r.deliveryId }, body: { symbol: r.symbol, qty: 1 } }, }; } readonly client = { - listAcceptedRequests: async ({ source_ids, created_at_gte, limit = 255, next }: { source_ids: string[]; created_at_gte: string; limit?: number; next?: string }) => { + listPollRequests: async ({ source_ids, created_at_gte, limit = 255, next }: { source_ids: string[]; created_at_gte: string; limit?: number; next?: string }) => { this.attempts++; if (this.rateLimited) throw new HookdeckApiError('GET', '/requests', 429, '{}'); const from = Date.parse(created_at_gte); @@ -169,6 +171,17 @@ describe('poll mode: cursor', () => { expect(result.events.map((e) => e.eventId).sort()).toEqual(['aapl', 'filtered', 'laptop-asleep']); }); + it('returns requests to a source with no subscriptions (rejected as NO_CONNECTION), but not ones that failed verification', async () => { + const { listing, service } = setup(); + const start = await service.poll({ name: NAME }); + listing.add({ createdAt: T0 + 1000, deliveryId: 'no-subscriptions', rejection: 'NO_CONNECTION' }); + listing.add({ createdAt: T0 + 1500, deliveryId: 'bad-signature', rejection: 'VERIFICATION_FAILED' }); + listing.add({ createdAt: T0 + 2000, deliveryId: 'subscribed' }); + listing.now += 5000; + const result = await service.poll({ name: NAME, cursor: start.cursor }); + expect(result.events.map((e) => e.eventId)).toEqual(['no-subscriptions', 'subscribed']); + }); + it("returns a request as soon as it's listed, whether or not Event Gateway has routed it yet", async () => { const { listing, service } = setup(); const start = await service.poll({ name: NAME }); @@ -263,6 +276,72 @@ describe('poll mode: cursor', () => { }); }); +describe('poll mode: sources with and without subscriptions (NO_CONNECTION)', () => { + // A source has a connection only per subscription: with none, Event Gateway rejects each request as NO_CONNECTION + // (and keeps it); once something subscribes, requests are accepted; when the last subscription goes, NO_CONNECTION again. + + it('returns events once, in order, across a subscription starting and ending, on one cursor', async () => { + const { listing, service } = setup(); + const start = await service.poll({ name: NAME }); + listing.add({ createdAt: T0 + 1000, deliveryId: 'before-subscribe', rejection: 'NO_CONNECTION' }); + listing.add({ createdAt: T0 + 2000, deliveryId: 'while-subscribed' }); + listing.add({ createdAt: T0 + 3000, deliveryId: 'after-unsubscribe', rejection: 'NO_CONNECTION' }); + listing.add({ createdAt: T0 + 3500, deliveryId: 'bad-signature', rejection: 'VERIFICATION_FAILED' }); + listing.now += 5000; + const first = await service.poll({ name: NAME, cursor: start.cursor }); + listing.now += 5000; + const again = await service.poll({ name: NAME, cursor: first.cursor }); + expect(first.events.map((e) => e.eventId)).toEqual(['before-subscribe', 'while-subscribed', 'after-unsubscribe']); + expect(again.events).toEqual([]); + }); + + it("returns a sender's redelivery once when the first try was NO_CONNECTION and the retry was accepted", async () => { + const { listing, service } = setup(); + const start = await service.poll({ name: NAME }); + listing.add({ createdAt: T0 + 1000, deliveryId: 'same', rejection: 'NO_CONNECTION' }); + listing.add({ createdAt: T0 + 4000, deliveryId: 'same' }); + listing.now += 10_000; + const result = await service.poll({ name: NAME, cursor: start.cursor }); + expect(result.events.map((e) => e.eventId)).toEqual(['same']); + }); + + it('catches up on NO_CONNECTION requests after a long gap (a cursor resumed later, as watch does)', async () => { + const { listing, service } = setup(); + const start = await service.poll({ name: NAME }); + for (let i = 0; i < 30; i++) listing.add({ createdAt: T0 + 1000 + i * 1000, deliveryId: `gap-${i}`, rejection: i % 2 ? 'NO_CONNECTION' : undefined }); + listing.now += 10 * 60_000; + let cursor = start.cursor; + const got: string[] = []; + for (;;) { + const result = await service.poll({ name: NAME, cursor, maxEvents: 7 }); + got.push(...result.events.map((e) => e.eventId)); + cursor = result.cursor; + if (!result.hasMore) break; + } + expect(got).toEqual(Array.from({ length: 30 }, (_, i) => `gap-${i}`)); + }); + + it('replays NO_CONNECTION requests from a webhook cursor, so a subscription made with one gets what arrived before it', async () => { + const { listing, service } = setup(); + listing.now = T0 + 120_000; + const cursor = service.webhookCursor(NAME, {}, { at: listing.now }); + listing.add({ createdAt: T0 + 200_000, deliveryId: 'while-unsubscribed', rejection: 'NO_CONNECTION' }); + listing.now = T0 + 300_000; + const result = await service.poll({ name: NAME, arguments: {}, cursor }); + expect(result.events.map((e) => e.eventId)).toEqual(['while-unsubscribed']); + }); + + it('applies the arguments filter to NO_CONNECTION requests, as to accepted ones', async () => { + const { listing, service } = setup(); + const start = await service.poll({ name: NAME, arguments: { symbol: 'AAPL' } }); + listing.add({ createdAt: T0 + 1000, deliveryId: 'aapl', rejection: 'NO_CONNECTION' }); + listing.add({ createdAt: T0 + 2000, deliveryId: 'msft', symbol: 'MSFT', rejection: 'NO_CONNECTION' }); + listing.now += 5000; + const result = await service.poll({ name: NAME, arguments: { symbol: 'AAPL' }, cursor: start.cursor }); + expect(result.events.map((e) => e.eventId)).toEqual(['aapl']); + }); +}); + describe('poll mode: shared listing and back-off', () => { it('answers concurrent polls with one listing, and lists only sources polled recently', async () => { const { listing, service } = setup({ sources: ['fills', 'orders'] }); diff --git a/test/host/bridge.test.ts b/test/host/bridge.test.ts index 678f9ff..1ee02c4 100644 --- a/test/host/bridge.test.ts +++ b/test/host/bridge.test.ts @@ -333,13 +333,15 @@ describe('poll mode over MCP', () => { // (The SDK client consumes resultType when it decodes a result; the poll tests check it's 'complete'.) expect(first).toMatchObject({ events: [], truncated: false, hasMore: false }); + // Nothing has subscribed, so the source has no connection: Event Gateway keeps the request but rejects it as + // NO_CONNECTION, as it does live. Poll still returns it. gateway.requests.push({ id: 'req_1', source_id: 'src_resend', created_at: new Date(Date.now() + 1000).toISOString(), verified: true, - rejection_cause: null, - events_count: 1, + rejection_cause: 'NO_CONNECTION', + events_count: 0, ignored_count: 0, data: { headers: fixture.headers, body: freshEmail() }, });