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
23 changes: 23 additions & 0 deletions clients/cli/__tests__/events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,29 @@ describe("events/stream through runMethod (#3032)", () => {
expect(end).not.toHaveBeenCalled();
});

it("sends --metadata on the events/stream request, not only on the lookup (#3062)", async () => {
const url = await startFixture();
const client = await connect(url);
const stream = vi.spyOn(client, "streamEvents");
const list = vi.spyOn(client, "listAllEvents");
const metadata = { "com.example/trace": "abc" };
const outcome = await runMethod(client, {
method: "events/stream",
eventName: EVENT_TYPE_NAMES.allModes,
metadata,
});
if (outcome.kind !== "stream") throw new Error("expected a stream");
const lines: Line[] = [];
const stop = outcome.start((line) => lines.push(line as Line));
await vi.waitFor(() =>
expect(lines.some((l) => l.type === "active")).toBe(true),
);
expect(list.mock.calls[0]![0]).toMatchObject({ metadata });
expect(stream).toHaveBeenCalled();
expect(stream.mock.calls[0]![2]).toMatchObject({ metadata });
stop();
});

it("ends the stream on its own when the server terminates it", async () => {
const url = await startFixture();
const client = await connect(url);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,83 @@ describe("EventSubscriptionsState (#3029)", () => {
});
});

describe("request metadata (#3062)", () => {
const META = { "com.example/trace": "abc" };

it("sends it on a push stream and on every reconnect", async () => {
state.subscribe(typed, { mode: "push", metadata: META });
expect(client.streamEvents.mock.calls[0]![2]).toMatchObject({
metadata: META,
});
client.lastStream().reject(new Error("ECONNRESET"));
await flush();
await flush();
expect(client.streamEvents).toHaveBeenCalledTimes(2);
expect(client.streamEvents.mock.calls[1]![2]).toMatchObject({
metadata: META,
});
});

it("sends it on every poll", async () => {
state.subscribe(typed, { mode: "poll", metadata: META });
await flush();
await vi.advanceTimersByTimeAsync(1000);
expect(client.pollEvents.mock.calls.length).toBeGreaterThanOrEqual(2);
for (const call of client.pollEvents.mock.calls) {
expect(call[2]).toEqual(META);
}
});

it("re-lists with it after a contract-changing termination", async () => {
state.subscribe(typed, { mode: "push", metadata: META });
const first = client.lastStream();
client.eventPages.push({ events: [typed], excluded: [] });
client.notify(EVENTS_TERMINATED_NOTIFICATION, first.id, {
error: { code: EVENTS_ERROR_CODES.NotFound, message: "gone" },
});
await flush();
expect(client.listAllEvents).toHaveBeenCalledWith({ metadata: META });
});

it("hands it to an injected relist", async () => {
const relist = vi.fn(async () => [typed]);
const hosted = new EventSubscriptionsState(client, {
random: () => 0,
relist,
});
hosted.subscribe(typed, { mode: "push", metadata: META });
client.notify(EVENTS_TERMINATED_NOTIFICATION, client.lastStream().id, {
error: { code: EVENTS_ERROR_CODES.NotFound, message: "gone" },
});
await flush();
expect(relist).toHaveBeenCalledWith(META);
hosted.destroy();
});

it("sends none when the caller gave none", async () => {
state.subscribe(typed, { mode: "poll" });
await flush();
expect(client.pollEvents.mock.calls[0]![2]).toBeUndefined();
state.subscribe(typed, { mode: "push" });
expect(client.streamEvents.mock.calls[0]![2]?.metadata).toBeUndefined();
});

it("keeps it across a resume that omits it, and takes new metadata over it", async () => {
const sub = state.subscribe(typed, { mode: "poll", metadata: META });
await flush();
state.stop(sub.id);
state.subscribe(typed, { mode: "poll" });
await flush();
expect(client.pollEvents.mock.calls[1]![2]).toEqual(META);

const NEXT = { "com.example/trace": "def" };
state.stop(sub.id);
state.subscribe(typed, { mode: "poll", metadata: NEXT });
await flush();
expect(client.pollEvents.mock.calls[2]![2]).toEqual(NEXT);
});
});

describe("stop, resume, remove", () => {
it("stops a running subscription, keeps its cursor, and resumes it", async () => {
client.pollResults.push(polled({ cursor: "kept" }));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,40 @@ describe("EventSubscriptionsState webhook (#3031)", () => {
expect(state.refreshWebhook("nope")).toBe(false);
});

it("sends request metadata on subscribe, every refresh and the unsubscribe (#3062)", async () => {
const META = { "com.example/trace": "abc" };
client.subscribeResults.push(
{
id: "sub_1",
refreshBefore: new Date(NOW + HOUR).toISOString(),
cursor: "c1",
truncated: false,
},
{
id: "sub_1",
refreshBefore: new Date(NOW + 2 * HOUR).toISOString(),
cursor: "c2",
truncated: false,
},
);
const sub = state.subscribe(hooked, {
mode: "webhook",
webhook: { url: URL_A },
metadata: META,
});
await flush();
await vi.advanceTimersByTimeAsync(HOUR);
expect(client.subscribeEvents).toHaveBeenCalledTimes(2);
for (const call of client.subscribeEvents.mock.calls) {
expect(call[2]).toMatchObject({ metadata: META });
}
state.stop(sub.id);
await Promise.resolve(); // the teardown is sent a microtask later
expect(client.unsubscribeEvents.mock.calls[0]![2]).toEqual({
metadata: META,
});
});

describe("stop, resume, remove", () => {
it("unsubscribes on stop, and resumes with the same secret and cursor", async () => {
client.subscribeResults.push({
Expand Down
8 changes: 7 additions & 1 deletion core/cli/handlers/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,12 @@ function activeLine(subscription: EventSubscription): Record<string, unknown> {
export function eventsStreamOutcome(
client: InspectorClient,
eventType: EventType,
args: { arguments?: Record<string, JsonValue>; cursor?: string },
args: {
arguments?: Record<string, JsonValue>;
cursor?: string;
/** `--metadata`: sent on the stream and on every reconnect (#3062). */
metadata?: RequestMetadata;
},
): MethodOutcome {
return {
kind: "stream",
Expand Down Expand Up @@ -294,6 +299,7 @@ export function eventsStreamOutcome(
arguments: eventArgs,
// Omitted → the engine's `null` ("start from now").
...(args.cursor !== undefined && { cursor: args.cursor }),
...(args.metadata !== undefined && { metadata: args.metadata }),
});
} catch (error) {
stop();
Expand Down
1 change: 1 addition & 0 deletions core/cli/handlers/run-method.ts
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,7 @@ export async function runMethod(
return eventsStreamOutcome(inspectorClient, eventType, {
arguments: args.eventArgs,
cursor: args.cursor,
metadata: args.metadata,
});
} else if (args.method === "roots/list") {
result = { roots: inspectorClient.getRoots() };
Expand Down
54 changes: 43 additions & 11 deletions core/mcp/state/eventSubscriptionsState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
import type { jsonSchemaValidator } from "@modelcontextprotocol/client";
import type { InspectorClientProtocol } from "../inspectorClientProtocol.js";
import type { InspectorClientEventMap } from "../inspectorClientEventTarget.js";
import type { RequestMetadata } from "../types.js";
import {
TypedEventTarget,
type TypedEventGeneric,
Expand Down Expand Up @@ -160,6 +161,12 @@ export interface EventSubscribeOptions {
heartbeatMs?: number;
/** Webhook only, and required for it: where and how to deliver. */
webhook?: EventWebhookOptions;
/**
* Request `_meta` sent on every request this subscription makes: the first
* poll, stream or subscribe, every reconnect and refresh, and a webhook's
* unsubscribe. Omitted on a resume, the previous run's metadata is kept.
*/
metadata?: RequestMetadata;
Comment thread
Copilot marked this conversation as resolved.
Resolved
}

/** What a webhook subscription is created with. */
Expand Down Expand Up @@ -286,10 +293,12 @@ export interface EventSubscriptionsStateOptions extends RunnerTiming {
pollFloorMs?: number;
/**
* Re-list the event types after a contract-changing termination. Defaults to
* a full `listAllEvents()` walk; a host with a managed events list passes its
* refresh, so the list it shows is the one the offer was based on.
* a full `listAllEvents()` walk with the terminated subscription's request
* metadata (#3062); a host with a managed events list passes its refresh, so
* the list it shows is the one the offer was based on. It receives that
* metadata and may ignore it, since a shared list is not one subscription's.
*/
relist?: () => Promise<EventType[]>;
relist?: (metadata?: RequestMetadata) => Promise<EventType[]>;
}

export const DEFAULT_MAX_EVENT_LOG_ENTRIES = 1000;
Expand All @@ -303,6 +312,8 @@ interface Entry {
seen: Set<string>;
/** Webhook: the signing secret, kept off the snapshot. */
secret?: string;
/** Request `_meta` for every request this subscription sends (#3062). */
metadata?: RequestMetadata;
}

export class EventSubscriptionsState extends TypedEventTarget<EventSubscriptionsStateEventMap> {
Expand Down Expand Up @@ -475,11 +486,15 @@ export class EventSubscriptionsState extends TypedEventTarget<EventSubscriptions
reconnects: 0,
},
};
// A resume keeps the metadata its first run was started with, unless the
// caller passes new metadata.
const metadata = options.metadata ?? existing?.metadata;
const entry: Entry = {
snapshot,
runner: undefined,
seen: existing?.seen ?? new Set(),
...(secret !== undefined && { secret }),
...(metadata !== undefined && { metadata }),
};
this.entries.set(id, entry);
this.run(entry);
Expand Down Expand Up @@ -626,10 +641,14 @@ export class EventSubscriptionsState extends TypedEventTarget<EventSubscriptions
};
const unsubscribeEvents = client.unsubscribeEvents.bind(client);
const send = (): Promise<void> =>
unsubscribeEvents(entry.snapshot.eventType, {
arguments: entry.snapshot.arguments,
delivery: { url: webhook.url },
});
unsubscribeEvents(
entry.snapshot.eventType,
{
arguments: entry.snapshot.arguments,
delivery: { url: webhook.url },
},
...(entry.metadata !== undefined ? [{ metadata: entry.metadata }] : []),
);
// `then(send)` also turns a synchronous throw into a rejection.
idle.then(send).then(
() => settle({ status: "done" }),
Expand Down Expand Up @@ -672,6 +691,10 @@ export class EventSubscriptionsState extends TypedEventTarget<EventSubscriptions
random: this.options.random,
};
const eventType = snapshot.eventType;
// Sent on every request the runner makes, reconnects and refreshes
// included, not only on the first one (#3062).
const { metadata } = entry;
const withMetadata = metadata !== undefined ? { metadata } : {};
if (snapshot.mode === "webhook") {
// `subscribe` set both for every webhook entry.
const webhook = snapshot.webhook!;
Expand All @@ -691,7 +714,10 @@ export class EventSubscriptionsState extends TypedEventTarget<EventSubscriptions
},
cursor: snapshot.cursor,
subscribe: (params, signal) =>
client.subscribeEvents!(eventType, params, { signal }),
client.subscribeEvents!(eventType, params, {
signal,
...withMetadata,
}),
callbacks,
});
} else if (snapshot.mode === "poll") {
Expand All @@ -710,7 +736,7 @@ export class EventSubscriptionsState extends TypedEventTarget<EventSubscriptions
pollFloorMs: this.options.pollFloorMs,
// `subscribe` checked the method exists before creating the entry.
poll: (params, signal) =>
client.pollEvents!(eventType, params, undefined, { signal }),
client.pollEvents!(eventType, params, metadata, { signal }),
callbacks,
});
} else {
Expand Down Expand Up @@ -738,6 +764,7 @@ export class EventSubscriptionsState extends TypedEventTarget<EventSubscriptions
client.streamEvents!(eventType, params, {
signal,
onSubscriptionId,
...withMetadata,
}),
routes,
callbacks,
Expand Down Expand Up @@ -851,10 +878,15 @@ export class EventSubscriptionsState extends TypedEventTarget<EventSubscriptions
private relistAfter(entry: Entry): void {
const relist =
this.options.relist ??
(async () => (await this.requireClient().listAllEvents!()).events);
(async (metadata?: RequestMetadata) =>
(
await this.requireClient().listAllEvents!(
metadata !== undefined ? { metadata } : undefined,
)
).events);
let pending: Promise<EventType[]>;
try {
pending = relist();
pending = relist(entry.metadata);
} catch (err) {
pending = Promise.reject(err);
}
Expand Down