diff --git a/CHANGELOG.md b/CHANGELOG.md index f35e193..0256f83 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,11 @@ ### Changed - **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`. +- **`list_sources` lists each event's filters:** a new `filters` field maps each event name to the arguments it takes, each with its type and description, from the event's inputSchema. Clients with tools only (Claude Code without the plugin, Codex, Cursor) can't call `events/list`, so they had no way to find the filters, and guessed. `events` is still a list of names. The descriptions of `list_sources`, and of `poll_events` and `wait_for_event`'s `name` and `arguments`, point there instead of at `events/list`, and so do `get_event` and `list_events`' unknown-name errors. ### Fixed +- **Arguments that don't match an event's inputSchema say what's wrong:** `poll_events` and `wait_for_event` returned only "arguments do not match the inputSchema", dropping the protocol error's `data.detail`, so an agent couldn't tell which argument was wrong (seen on 5 Nov: Claude Code passed `action` for `github.issues`, whose filter is `actions`, a list, then dropped the filter). The tool error now includes the detail, which names the unknown or wrong argument and lists the event's arguments: `arguments do not match the inputSchema: unknown argument "action". github.issues takes repository (string), actions (string[]), sender (string)`. `events/poll` and `events/subscribe` return the same `data.detail`, which was the validator's raw JSON, and `watch` and `watches add` print it. Unknown arguments were already refused, not ignored. - **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) diff --git a/README.md b/README.md index 0e941b2..70fc10b 100644 --- a/README.md +++ b/README.md @@ -384,7 +384,7 @@ Each `source()`'s credentials, named as its `env()` references name them. `sourc - `events/list`, `events/subscribe`, `events/unsubscribe`, with webhook delivery, and `events/poll`, for poll delivery. Event names are `{id}.{event}` (see [Sources](#sources)). - `poll_events(name, arguments?, cursor?, maxAgeMs?, maxEvents?)` and `wait_for_event(name, arguments?, cursor?, timeoutMs?)`: the same polling as tools, for MCP clients without MCP Events support (see [Polling](#polling)). - `get_event(name, eventId)` and `list_events(name?, since?, limit?)`: events that happened, read from Event Gateway (`events/list` is the catalog of events you can subscribe to). `get_event` takes the event's name as well as its id, since an id is the service's own and two sources can share one. -- `list_sources()`: configured sources, their types and events, and their subscriptions. +- `list_sources()`: configured sources, their types and events, the filters each event takes (`filters`, by event name: each argument's type and description, from the event's inputSchema, for clients that can't call `events/list`), and their subscriptions. - `create_callback_url(agent, name, port?, path?, secret?)` and `list_callback_urls(agent)`: public callback URLs for agents on the same machine as a local bridge (see [Local agents](#local-agents)). Calling again with the same `agent`, `name` and secret returns the existing URL; a different secret, port or path for that name is an error. Not offered by a deployed bridge. - Every tool is annotated `readOnlyHint: true` except `create_callback_url`, which is `idempotentHint: true` and `destructiveHint: false`. `list_sources` and `list_callback_urls` are also `openWorldHint: false`: they answer from the bridge's own state. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f92e54e..ec2d213 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -374,6 +374,7 @@ Designed 8 Oct ([#26](https://github.com/hookdeck/mcp-events-bridge/issues/26)) - `poll_events(name, arguments?, cursor?, maxAgeMs?, maxEvents?)`: the same as `events/poll`. - `wait_for_event(name, arguments?, cursor?, timeoutMs?)`: polls at each `nextPollMs` (at least 2 seconds, so it reads the shared window), at once while `hasMore` with nothing matching, with progress notifications, and returns as soon as there are events, or with none and the cursor at `timeoutMs` (default 45 s, at most 50 s: Claude Code's HTTP timer and Codex's tool timeout are 60 s by default). +- Errors are tool errors with the protocol error's message and its `data.detail`. For arguments that don't match the event's inputSchema (every source's arguments are strict, so an unknown key is refused, not ignored), the detail names the field and lists the arguments the event takes; `events/poll` and `events/subscribe` return the same detail. **Acceptance (#26).** A property test against a fake listing (requests appearing late and out of order, duplicates, unprocessed requests, `maxEvents` from 1 to 100). pi-mcp-events calling `events/poll`. A 10-minute live soak with bursts, wrong signatures and duplicates, with Claude Code calling `wait_for_event` during it. A local bridge with `listen` stopped. A long gap, and concurrent pollers with no `429` reaching a caller. @@ -708,7 +709,7 @@ Handlers registered by hand: Tools: -- `list_sources()`: configured sources, their types and events, and how many subscriptions each has. (`list_providers()`, the pre-0.6.0 name, was removed in 0.8.0.) +- `list_sources()`: configured sources, their types and events, each event's filters (`filters`: by event name, each argument's type and description from the event's inputSchema, for clients with tools only, which can't call `events/list`), and how many subscriptions each has. (`list_providers()`, the pre-0.6.0 name, was removed in 0.8.0.) - `create_callback_url(agent, name, port?, path?, secret?)` and `list_callback_urls(agent)`: callback URLs for local agents, on a bridge with CLI inbound (see "Callback URLs from the bridge"). Results include the name, URL, port, path and `passThrough`, never a secret. (`create_tunnel_url` and `list_tunnel_urls` until 0.8.0.) - `get_event(name, eventId)` and `list_events(name?, since?, limit?)`: events that happened, read from Event Gateway (not the catalog of event kinds, which is `events/list`). These also work around openai/codex#50714, where dot runs don't receive event data. - Poll mode ("Poll mode", [#26](https://github.com/hookdeck/mcp-events-bridge/issues/26)): `events/poll` (`name`, `arguments`, `cursor`, `maxAgeMs`, `maxEvents`), read from Event Gateway's stored requests on the source; the cursor is a position in that history. `events/list` offers `"poll"` in each event's `delivery`. For hosts that don't support MCP Events, the same implementation as the `poll_events` and `wait_for_event` tools. diff --git a/plugins/mcp-events-bridge/skills/watch/SKILL.md b/plugins/mcp-events-bridge/skills/watch/SKILL.md index 6f45d6d..8742351 100644 --- a/plugins/mcp-events-bridge/skills/watch/SKILL.md +++ b/plugins/mcp-events-bridge/skills/watch/SKILL.md @@ -20,7 +20,7 @@ This skill is part of the bridge's Claude Code plugin, `mcp-events-bridge`. The ## Find event names and filters -Call the `events-bridge` MCP server's `list_sources` tool (`list_providers` on a bridge before 0.6.0). Event names look like `github.issue_comment` or `resend.email.received`, and each event's filters are in its input schema (for GitHub: `repository` as owner/name, `actions` as a list, `sender`). +Call the `events-bridge` MCP server's `list_sources` tool (`list_providers` on a bridge before 0.6.0). Event names look like `github.issue_comment` or `resend.email.received`. Its `filters` field maps each event name to the filters it takes, each with a type and description (for GitHub: `repository` as owner/name, `actions` as a list, `sender`). An older bridge's `list_sources` has no `filters`; either way, `watches add` checks the filters with the bridge and says which one is wrong. ## Add, remove and list watches diff --git a/skills/mcp-events-bridge/SKILL.md b/skills/mcp-events-bridge/SKILL.md index 51bdacd..4e85d64 100644 --- a/skills/mcp-events-bridge/SKILL.md +++ b/skills/mcp-events-bridge/SKILL.md @@ -93,6 +93,7 @@ Every event is named **`{source id}.{event}`**: the source `id` (by default its - `wait_for_event` (`name`, `arguments`, `cursor`): waits up to 45 s and returns as soon as there are events. Call it again with the `cursor` it returned to keep waiting. - `poll_events` (same, plus `maxEvents`, `maxAgeMs`): returns at once; call again after `nextPollMs`, or at once when `hasMore` is true. - Without a cursor, both start from now. Events can repeat: dedupe by `eventId`. For events that already happened, use `list_events` and `get_event`. + - Event names and filters: the `list_sources` tool. Its `filters` maps each event name to the arguments it takes, each with a type and description (for GitHub, `repository`, `actions` as a list such as `["opened"]`, and `sender`). Arguments that don't match are a tool error that names the wrong or unknown one and lists the event's arguments, for example `arguments do not match the inputSchema: unknown argument "action". github.issues takes repository (string), actions (string[]), sender (string)`. - **Claude Code, between prompts:** the poll tools only wait while Claude is working on a request. To be told about events while it's idle, the user installs the plugin, `/plugin install mcp-events-bridge --marketplace hookdeck/mcp-events-bridge` (it asks for the MCP URL), then says "watch … for …"; see [references/claude-code.md](references/claude-code.md), section 3. Other agents that wake on a background command's output can run `npx @hookdeck/mcp-events-bridge watch [--filter key=value]`, which prints one JSON line per event. - **Clients that implement MCP Events poll mode** call `events/poll` (same arguments and cursor) instead of subscribing. @@ -102,7 +103,7 @@ Every event is named **`{source id}.{event}`**: the source `id` (by default its 2. Trigger a real event: send an email to the Resend receiving address, open a GitHub issue, or have the sender post one. 3. The agent gets it. Events don't pass through the bridge, so `serve` logs nothing for it, except for a local agent: `[listen] agent : ... POST http://localhost:`. 4. In the Event Gateway dashboard, the subscription's connection, `mcp-sub-` on `bridge-`, shows each request: delivered, with its attempts, or `FILTERED` when the subscription's filter or event type didn't match. -5. The `list_sources` tool shows each source's type, events, and how many subscriptions each has. +5. The `list_sources` tool shows each source's type, events, each event's filters, and how many subscriptions each has. ## Troubleshooting diff --git a/skills/mcp-events-bridge/references/claude-code.md b/skills/mcp-events-bridge/references/claude-code.md index 23d2ae2..1a4ed27 100644 --- a/skills/mcp-events-bridge/references/claude-code.md +++ b/skills/mcp-events-bridge/references/claude-code.md @@ -34,7 +34,7 @@ Name the event and its filter, and ask Claude to keep waiting. The examples here > Wait for new comments on issues in `/` (github.issue_comment, repository `/`) and summarize each one. -Claude calls `wait_for_event`, which returns as soon as there are events, or with none after up to 45 seconds, and calls it again with the `cursor` it returned. `events/list` (or asking "what events can the bridge give me?") lists the names and their filters. +Claude calls `wait_for_event`, which returns as soon as there are events, or with none after up to 45 seconds, and calls it again with the `cursor` it returned. The `list_sources` tool lists the names and each event's filters (ask "what events can the bridge give me?"). - **Start from now:** the first call has no cursor, so it returns only events after it. For events that already happened, ask for them: Claude uses `list_events` and `get_event`. - **Repeats:** delivery is at least once. If the same `eventId` comes back, it's the same event. diff --git a/src/core/catalog.ts b/src/core/catalog.ts index 4683dcc..34291c2 100644 --- a/src/core/catalog.ts +++ b/src/core/catalog.ts @@ -1,5 +1,6 @@ import type { ResolvedSource } from './config.js'; -import type { EventRuntime, SourceEvent } from './sources/types.js'; +import { invalidParams } from './errors.js'; +import type { EventRuntime, JsonSchema, SourceEvent } from './sources/types.js'; import { instantiateRuntime } from './transformation.js'; /** @@ -26,6 +27,72 @@ export const descriptionWarnings = (catalog: Catalog) => `whose description is over about ${LONG_DESCRIPTION}, so shorten it if ChatGPT doesn't offer ${e.name}`, ); +/** A JSON Schema's type in TypeScript's notation, which models read well: `string`, `string[]`, `string | number`. */ +function schemaType(schema: unknown): string { + if (typeof schema !== 'object' || schema === null) return 'unknown'; + const s = schema as Record; + const union = s.anyOf ?? s.oneOf; + if (Array.isArray(union)) return union.map(schemaType).join(' | '); + if (Array.isArray(s.enum)) return s.enum.map((value) => JSON.stringify(value)).join(' | '); + if (s.const !== undefined) return JSON.stringify(s.const); + if (Array.isArray(s.type)) return s.type.join(' | '); + if (s.type === 'array') { + const item = schemaType(s.items); + return item.includes(' ') ? `(${item})[]` : `${item}[]`; + } + return typeof s.type === 'string' ? s.type : 'unknown'; +} + +export interface FilterDescription { + type: string; + description?: string; + required?: true; +} + +/** + * The filters (subscribe and poll arguments) an event takes, from its inputSchema: each one's type and description. + * For list_sources, so a client with tools only, which can't call events/list, can find them. + */ +export function describeFilters(inputSchema: JsonSchema): Record { + const properties = (inputSchema.properties ?? {}) as Record>; + const required = Array.isArray(inputSchema.required) ? (inputSchema.required as string[]) : []; + return Object.fromEntries( + Object.entries(properties).map(([key, schema]) => [ + key, + { + type: schemaType(schema), + ...(typeof schema.description === 'string' && { description: schema.description }), + ...(required.includes(key) && { required: true as const }), + }, + ]), + ); +} + +/** What a parseArguments error says, in a line: zod's issues by field (an unknown key named as such), else its message. */ +function describeArgumentsError(error: unknown): string { + const issues = (error as { issues?: unknown }).issues; + if (!Array.isArray(issues) || issues.length === 0) return error instanceof Error ? error.message : String(error); + return issues + .map((issue: { code?: string; keys?: string[]; path?: PropertyKey[]; message?: string }) => { + if (issue.code === 'unrecognized_keys' && Array.isArray(issue.keys)) { + return `unknown argument${issue.keys.length === 1 ? '' : 's'} ${issue.keys.map((key) => JSON.stringify(key)).join(', ')}`; + } + const path = issue.path?.length ? issue.path.map(String).join('.') : 'arguments'; + return `${path}: ${issue.message ?? 'invalid'}`; + }) + .join('; '); +} + +/** + * The InvalidParams error for arguments an event's parseArguments refused. `data.detail` names the bad or unknown + * field and lists the arguments the event takes, so an agent can correct the call. + */ +export function argumentsError(name: string, event: Pick, error: unknown) { + const filters = Object.entries(describeFilters(event.inputSchema)); + const takes = filters.length ? `${name} takes ${filters.map(([key, f]) => `${key} (${f.type})`).join(', ')}` : `${name} takes no arguments`; + return invalidParams('arguments do not match the inputSchema', { detail: `${describeArgumentsError(error)}. ${takes}` }); +} + export interface CatalogEntry { /** The MCP event name: `{instance id}.{event.name}`. */ name: string; diff --git a/src/core/mcp.ts b/src/core/mcp.ts index d43a391..cdbaf30 100644 --- a/src/core/mcp.ts +++ b/src/core/mcp.ts @@ -53,7 +53,7 @@ export function buildMcpServer(deps: { }, async ({ name, eventId }) => { const lookup = history.lookup(name); - if (lookup === 'unknown') return error(`Unknown event name ${name}; events/list has the names`); + if (lookup === 'unknown') return error(`Unknown event name ${name}; list_sources has the names`); if (lookup === 'no-id-header') return error(`${name} events can't be looked up by id; use list_events with name ${name}`); const event = await history.get(name, eventId); return event ? json(event) : { content: [{ type: 'text', text: `No ${name} event ${eventId}` }], isError: true }; @@ -78,7 +78,7 @@ export function buildMcpServer(deps: { }), }, async (args) => { - if (args.name !== undefined && history.lookup(args.name) === 'unknown') return error(`Unknown event name ${args.name}; events/list has the names`); + if (args.name !== undefined && history.lookup(args.name) === 'unknown') return error(`Unknown event name ${args.name}; list_sources has the names`); return json({ events: await history.recent(args) }); }, ); @@ -87,9 +87,10 @@ export function buildMcpServer(deps: { 'list_sources', { description: - 'List the configured event sources (the services events come from): each one\'s id, type, event names, and how many subscriptions it has. ' + - 'Use it first, to find the event names that list_events, get_event, wait_for_event and poll_events take. ' + - "For each event's description and filters, see events/list (an MCP Events method, not a tool); for the events themselves, list_events.", + 'List the configured event sources (the services events come from): each one\'s id, type, event names, the filters each event takes, and how many subscriptions it has. ' + + 'Use it first, to find the event names that list_events, get_event, wait_for_event and poll_events take, ' + + 'and the filters (the arguments of wait_for_event and poll_events): filters maps each event name to its argument names, each with a type and description. ' + + "For each event's description, see events/list (an MCP Events method, not a tool); for the events themselves, list_events.", // Answered from the bridge's config and loaded subscriptions, without calling Event Gateway. annotations: { readOnlyHint: true, openWorldHint: false }, inputSchema: z.object({}), @@ -100,16 +101,23 @@ export function buildMcpServer(deps: { const poll = deps.poll; if (poll) { const pollInput = { - name: z.string().describe('The event name, from events/list, such as fills.order.filled'), - arguments: z.record(z.string(), z.unknown()).optional().describe("Filters, as the event's inputSchema in events/list describes, e.g. { \"symbol\": \"AAPL\" }"), + name: z.string().describe('The event name, from list_sources (or events/list), such as github.issues'), + arguments: z + .record(z.string(), z.unknown()) + .optional() + .describe( + "Filters: only the argument names list_sources gives for the event under filters (its inputSchema in events/list), e.g. { \"repository\": \"owner/name\", \"actions\": [\"opened\"] } for github.issues. An unknown name or a wrong type is an error that lists the event's arguments.", + ), cursor: z.string().nullable().optional().describe('The cursor from your last call. Omit (or null) to start from now: the first call returns no events, only a cursor.'), }; - // A ProtocolError (unknown name, bad arguments or cursor) becomes a tool error the model can read. + // A ProtocolError (unknown name, bad arguments or cursor) becomes a tool error the model can read, with its + // data.detail, which says which argument is wrong and which the event takes. const asTool = async (run: () => Promise) => { try { return json(await run()); } catch (caught) { - return error((caught as Error).message); + const detail = (caught as { data?: { detail?: unknown } }).data?.detail; + return error(typeof detail === 'string' ? `${(caught as Error).message}: ${detail}` : (caught as Error).message); } }; diff --git a/src/core/poll.ts b/src/core/poll.ts index a0aa6cb..8628dba 100644 --- a/src/core/poll.ts +++ b/src/core/poll.ts @@ -1,6 +1,6 @@ import { createHash } from 'node:crypto'; import { canonicalJson } from './canonical-json.js'; -import type { Catalog } from './catalog.js'; +import { argumentsError, type Catalog } from './catalog.js'; import { internalError, invalidParams, notFound } from './errors.js'; import { matchesFilter } from './filter.js'; import { isEventRequest, type EventHistory, type PastEvent } from './event-history.js'; @@ -263,7 +263,7 @@ export class PollService { try { args = entry.event.parseArguments(rawArgs); } catch (error) { - throw invalidParams('arguments do not match the inputSchema', { detail: (error as Error).message }); + throw argumentsError(entry.name, entry.event, error); } const { cursor, maxAgeMs, maxEvents } = params; if (cursor !== undefined && cursor !== null && typeof cursor !== 'string') throw invalidParams('cursor must be a string or null', { field: 'cursor' }); diff --git a/src/core/subscriptions.ts b/src/core/subscriptions.ts index 5708b67..fb983ff 100644 --- a/src/core/subscriptions.ts +++ b/src/core/subscriptions.ts @@ -1,5 +1,5 @@ import { CallbackUrlError, parseCallbackUrl, verifyEndpoint, type CallbackTransport, type VerificationResult, type VerifyEndpointOptions } from './callback.js'; -import type { Catalog } from './catalog.js'; +import { argumentsError, type Catalog } from './catalog.js'; import type { SubscriptionSettings } from './config.js'; import { callbackEndpointError, forbidden, internalError, invalidParams, notFound, resourceExhausted, unsupported, type CallbackFailureReason } from './errors.js'; import { deriveSubscriptionId, verificationKey } from './identity.js'; @@ -132,7 +132,7 @@ export class SubscriptionService { try { args = event.parseArguments(rawArgs); } catch (error) { - throw invalidParams('arguments do not match the inputSchema', { detail: (error as Error).message }); + throw argumentsError(key.name, event, error); } if (!isValidWebhookSecret(delivery.secret)) { throw invalidParams('delivery.secret must be whsec_ followed by base64 of 24 to 64 bytes', { field: 'delivery.secret' }); diff --git a/src/host/server.ts b/src/host/server.ts index 1f5e762..85e771f 100644 --- a/src/host/server.ts +++ b/src/host/server.ts @@ -3,7 +3,7 @@ import http from 'node:http'; import { toNodeHandler } from '@modelcontextprotocol/node'; import { createMcpHandler, type McpServer } from '@modelcontextprotocol/server'; import { CallbackRegistry, type CallbackSettings } from '../core/callbacks.js'; -import { Catalog, descriptionWarnings } from '../core/catalog.js'; +import { Catalog, describeFilters, descriptionWarnings } from '../core/catalog.js'; import { assertCredentials, type ResolvedConfig } from '../core/config.js'; import { EventGatewayStore } from '../core/event-gateway-store.js'; import { EventHistory } from '../core/event-history.js'; @@ -184,8 +184,11 @@ export async function createBridgeServer(config: ResolvedConfig, options: Bridge const sources = () => config.sources.map((p) => { // MCP names, as in events/list and events/subscribe. - const events = catalog.forProvider(p.id).map((e) => e.name); - return { id: p.id, type: p.definition.type, events, subscriptions: store.list().filter((s) => events.includes(s.name)).length }; + const entries = catalog.forProvider(p.id); + const events = entries.map((e) => e.name); + // Each event's filters, for clients with tools only, which can't call events/list. `events` stays a list of names. + const filters = Object.fromEntries(entries.map((e) => [e.name, describeFilters(e.event.inputSchema)])); + return { id: p.id, type: p.definition.type, events, filters, subscriptions: store.list().filter((s) => events.includes(s.name)).length }; }); const localAgents = options.localAgents ?? config.inbound === 'cli'; diff --git a/test/core/catalog.test.ts b/test/core/catalog.test.ts index 3c5da61..5d010fc 100644 --- a/test/core/catalog.test.ts +++ b/test/core/catalog.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { Catalog, descriptionWarnings } from '../../src/core/catalog.js'; +import { argumentsError, Catalog, describeFilters, descriptionWarnings } from '../../src/core/catalog.js'; import { defineConfig, env, resolveConfig } from '../../src/core/config.js'; import { github, resend, source } from '../../src/sources.js'; @@ -41,3 +41,53 @@ describe('Catalog', () => { expect(warnings[0]).toMatch(/^fills\.order\.filled's description is \d+ characters\. ChatGPT has been reported/); }); }); + +describe("an event's filters, for clients with tools only", () => { + const config = resolveConfig( + defineConfig({ + sources: [ + github({ webhookSecret: 'a-long-enough-secret', events: ['issues'] }), + source({ type: 'webhook', id: 'fills', verification: { type: 'hmac', algorithm: 'sha256', encoding: 'hex', header: 'x-signature', secret: env('A_SECRET') }, events: ['order.filled'], filters: ['symbol'] }), + ], + }), + environment, + ); + const catalog = new Catalog(config.sources); + const issues = catalog.get('github.issues')!; + const refusal = (args: unknown) => { + try { + issues.event.parseArguments(args); + } catch (error) { + return error; + } + throw new Error('parseArguments accepted the arguments'); + }; + + it("describes each argument in the event's inputSchema: its type, in TypeScript's notation, and description", () => { + expect(describeFilters(issues.event.inputSchema)).toEqual({ + repository: { type: 'string', description: 'Only events for this repository (owner/name).' }, + actions: { type: 'string[]', description: 'Only these actions, for example ["opened", "reopened"].' }, + sender: { type: 'string', description: 'Only events caused by this GitHub user (login).' }, + }); + expect(describeFilters(catalog.get('fills.order.filled')!.event.inputSchema)).toEqual({ + symbol: { type: 'string | number | boolean', description: 'Only events whose symbol equals this value.' }, + }); + expect(describeFilters({ type: 'object', properties: { n: { type: 'integer' } }, required: ['n'] })).toEqual({ n: { type: 'integer', required: true } }); + }); + + // Seen on 5 Nov: Claude Code guessed `action` for github.issues, and the error didn't say which field was wrong. + it('names an unknown argument, which parseArguments refuses, and lists the arguments the event takes', () => { + expect(argumentsError('github.issues', issues.event, refusal({ action: 'opened', repository: 'hookdeck/mcp-events-bridge' }))).toMatchObject({ + code: -32602, + message: 'arguments do not match the inputSchema', + data: { detail: 'unknown argument "action". github.issues takes repository (string), actions (string[]), sender (string)' }, + }); + }); + + it('names an argument of the wrong type, and passes on any other error', () => { + expect((argumentsError('github.issues', issues.event, refusal({ actions: 'opened' })).data as { detail: string }).detail).toBe( + 'actions: Invalid input: expected array, received string. github.issues takes repository (string), actions (string[]), sender (string)', + ); + expect((argumentsError('x.y', { inputSchema: { type: 'object', properties: {} } }, new Error('no good')).data as { detail: string }).detail).toBe('no good. x.y takes no arguments'); + }); +}); diff --git a/test/core/poll.test.ts b/test/core/poll.test.ts index af0841a..2cac116 100644 --- a/test/core/poll.test.ts +++ b/test/core/poll.test.ts @@ -270,7 +270,11 @@ describe('poll mode: cursor', () => { await expect(service.poll({ name: NAME, arguments: { symbol: 'MSFT' }, cursor: start.cursor })).rejects.toMatchObject({ code: EventsErrorCode.InvalidParams }); await expect(service.poll({ name: NAME, cursor: 'not-a-cursor' })).rejects.toMatchObject({ code: EventsErrorCode.InvalidParams }); await expect(service.poll({ name: 'nope.order.filled' })).rejects.toMatchObject({ code: EventsErrorCode.NotFound }); - await expect(service.poll({ name: NAME, arguments: { side: 'buy' } })).rejects.toMatchObject({ code: EventsErrorCode.InvalidParams }); + // An unknown argument is refused, and the error names it and the arguments the event takes. + await expect(service.poll({ name: NAME, arguments: { side: 'buy' } })).rejects.toMatchObject({ + code: EventsErrorCode.InvalidParams, + data: { detail: 'unknown argument "side". fills.order.filled takes symbol (string | number | boolean)' }, + }); // maxEvents above the limit is lowered, not refused. await expect(service.poll({ name: NAME, maxEvents: 1000 })).resolves.toMatchObject({ resultType: 'complete' }); }); diff --git a/test/core/subscriptions.test.ts b/test/core/subscriptions.test.ts index 2dc1465..517c63c 100644 --- a/test/core/subscriptions.test.ts +++ b/test/core/subscriptions.test.ts @@ -71,6 +71,13 @@ describe('SubscriptionService.subscribe', () => { await expect(setup().service.subscribe(principal, request)).rejects.toMatchObject({ code }); }); + it("says which argument is wrong, and which the event takes, when the arguments don't match", async () => { + await expect(setup().service.subscribe('owner', params({ arguments: { subject: 'x' } }))).rejects.toMatchObject({ + code: -32602, + data: { detail: 'unknown argument "subject". resend.email.received takes from (string), to (string)' }, + }); + }); + it('rejects callbacks that resolve to non-public addresses', async () => { await expect(setup({ publicHost: false }).service.subscribe('owner', params())).rejects.toMatchObject({ code: -32602 }); }); diff --git a/test/host/bridge.test.ts b/test/host/bridge.test.ts index 1ee02c4..6104244 100644 --- a/test/host/bridge.test.ts +++ b/test/host/bridge.test.ts @@ -169,14 +169,29 @@ describe('bridge server', () => { expect(typeof subscriber.events[0]!.cursor).toBe('string'); }); - it('lists sources with their MCP event names and how many subscriptions each has', async () => { + it("lists sources with their MCP event names, each event's filters, and how many subscriptions each has", async () => { const { port } = await startBridge(); await startSubscriber(port); const client = new Client({ name: 'test', version: '0.0.0' }, { versionNegotiation: { mode: 'auto' } }); await client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${port}/mcp/${MCP_SECRET}`))); try { expect(client.getServerVersion()).toMatchObject({ name: 'mcp-events-bridge', version: '9.9.9' }); - const expected = [{ id: 'resend', type: 'resend', events: ['resend.email.received'], subscriptions: 1 }]; + // `events` stays a list of names (the plugin's watch skill and other clients read it); `filters` is by event name, + // for clients with tools only, which can't call events/list for the inputSchema. + const expected = [ + { + id: 'resend', + type: 'resend', + events: ['resend.email.received'], + filters: { + 'resend.email.received': { + from: { type: 'string', description: expect.stringMatching(/^Only emails from this sender address\./) }, + to: { type: 'string', description: 'Only emails sent to this address.' }, + }, + }, + subscriptions: 1, + }, + ]; const result = (await client.callTool({ name: 'list_sources', arguments: {} })) as { structuredContent?: { sources: unknown[] } }; expect(result.structuredContent?.sources).toEqual(expected); // The old name, removed in 0.8.0. @@ -201,6 +216,8 @@ describe('bridge server', () => { const listed = await call('list_events', { name: 'email.received' }); expect(listed).toMatchObject({ isError: true }); expect(listed.content?.[0]?.text).toContain('Unknown event name email.received'); + // A tool, not events/list, which a client with tools only can't call. + expect(listed.content?.[0]?.text).toContain('list_sources has the names'); } finally { await client.close(); } @@ -360,6 +377,21 @@ describe('poll mode over MCP', () => { await expect(poll({ name: 'email.received', arguments: {}, cursor: null })).rejects.toMatchObject({ code: -32023 }); expect((await client.callTool({ name: 'poll_events', arguments: { name: 'email.received' } })).isError).toBe(true); + // Arguments that don't match: the tool error says which argument is wrong and which the event takes (it used to + // be only "arguments do not match the inputSchema"). The protocol error has the same in data.detail. + const takes = 'resend.email.received takes from (string), to (string)'; + type ToolError = { isError?: boolean; content?: Array<{ text?: string }> }; + for (const tool of ['poll_events', 'wait_for_event']) { + const unknownKey = (await client.callTool({ name: tool, arguments: { name: 'resend.email.received', arguments: { sender: 'a@example.com' }, cursor: next.cursor } })) as ToolError; + expect(unknownKey).toMatchObject({ isError: true, content: [{ text: `arguments do not match the inputSchema: unknown argument "sender". ${takes}` }] }); + const wrongType = (await client.callTool({ name: tool, arguments: { name: 'resend.email.received', arguments: { from: 42 } } })) as ToolError; + expect(wrongType).toMatchObject({ isError: true, content: [{ text: `arguments do not match the inputSchema: from: Invalid input: expected string, received number. ${takes}` }] }); + } + await expect(poll({ name: 'resend.email.received', arguments: { sender: 'a@example.com' }, cursor: null })).rejects.toMatchObject({ + code: -32602, + data: { detail: `unknown argument "sender". ${takes}` }, + }); + // Push isn't offered: events/stream is Unsupported for a known event, NotFound for an unknown one. const stream = (name: string) => client.request({ method: 'events/stream', params: { name, arguments: {} } } as never, anyResult); await expect(stream('resend.email.received')).rejects.toMatchObject({ code: -32026, data: { feature: 'deliveryMode', value: 'push' } });