Skip to content

Commit 03842cd

Browse files
fix: handle cancellation for request ID 0 (modelcontextprotocol#2654)
Co-authored-by: Konstantin Konstantinov <konstantin@mach5technology.com> Co-authored-by: Konstantin Konstantinov <KKonstantinov@users.noreply.github.com>
1 parent 27a94b5 commit 03842cd

3 files changed

Lines changed: 85 additions & 41 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@modelcontextprotocol/core-internal': patch
3+
'@modelcontextprotocol/client': patch
4+
'@modelcontextprotocol/server': patch
5+
---
6+
7+
Treat request id `0` as a real id. Two guards tested a `RequestId` for truthiness, so the legal JSON-RPC ids `0` and `''` were read as absent. Id `0` is not a corner case: the outbound request counter is zero-based, so it is the first id every peer assigns, which on the server→client leg is the first `sampling/createMessage`, `elicitation/create`, or `roots/list` a server sends.
8+
9+
- `notifications/cancelled` carrying id `0` was ignored, and the in-flight handler ran to completion with its `AbortSignal` never fired.
10+
- A notification sent with `relatedRequestId: 0` wrongly passed the debounce gate (for methods opted into `debouncedNotificationMethods`). Because the pending set is keyed by method alone, a second such notification in the same tick was silently dropped rather than sent.
11+
12+
Absent is now the only value that means "no id".

‎packages/core-internal/src/shared/protocol.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -724,7 +724,9 @@ export abstract class Protocol<ContextT extends BaseContext> {
724724
}
725725

726726
private async _oncancel(notification: CancelledNotification): Promise<void> {
727-
if (!notification.params.requestId) {
727+
// `requestId` is optional on the 2025-era wire schema. Absent is the
728+
// only thing that means "no id": `0` and `''` are legal request ids.
729+
if (notification.params.requestId === undefined) {
728730
return;
729731
}
730732
// Handle request cancellation
@@ -1611,7 +1613,11 @@ export abstract class Protocol<ContextT extends BaseContext> {
16111613
const debouncedMethods = this._options?.debouncedNotificationMethods ?? [];
16121614
// A notification can only be debounced if it's in the list AND it's "simple"
16131615
// (i.e., has no parameters and no related request ID that could be lost).
1614-
const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId;
1616+
// Absent is the only thing that means "no id" here too: `0` and `''` are
1617+
// legal request ids, and the pending set is keyed by method alone, so
1618+
// treating them as absent lets a related notification be coalesced away.
1619+
const canDebounce =
1620+
debouncedMethods.includes(notification.method) && !notification.params && options?.relatedRequestId === undefined;
16151621

16161622
if (canDebounce) {
16171623
// If a notification of this type is already scheduled, do nothing.

‎packages/core-internal/test/shared/protocol.test.ts‎

Lines changed: 65 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -656,6 +656,27 @@ describe('protocol tests', () => {
656656
expect(sendSpy).toHaveBeenCalledWith(expect.any(Object), { relatedRequestId: 'req-2' });
657657
});
658658

659+
// Same-tick coverage for every legal request id: the pending set is keyed
660+
// by method alone, so a related notification that wrongly passes the
661+
// debounce gate is coalesced away entirely. Awaiting between the two
662+
// sends would flush the microtask and hide that, so they are fired in one
663+
// tick. `0` and `''` are the ids a truthiness guard swallows.
664+
test.each([0, 123, '', 'req-1'])('should NOT coalesce same-tick notifications related to requestId %j', async relatedRequestId => {
665+
// ARRANGE
666+
protocol = new TestProtocolImpl({ debouncedNotificationMethods: ['test/debounced_with_options'] });
667+
await protocol.connect(transport);
668+
669+
// ACT — two related notifications in the same tick, no await between
670+
void protocol.notification({ method: 'test/debounced_with_options' }, { relatedRequestId });
671+
void protocol.notification({ method: 'test/debounced_with_options' }, { relatedRequestId });
672+
await flushMicrotasks();
673+
674+
// ASSERT — both go out, each still carrying its related request id
675+
expect(sendSpy).toHaveBeenCalledTimes(2);
676+
expect(sendSpy).toHaveBeenNthCalledWith(1, expect.any(Object), { relatedRequestId });
677+
expect(sendSpy).toHaveBeenNthCalledWith(2, expect.any(Object), { relatedRequestId });
678+
});
679+
659680
it('should clear pending debounced notifications on connection close', async () => {
660681
// ARRANGE
661682
protocol = new TestProtocolImpl({ debouncedNotificationMethods: ['test/debounced'] });
@@ -775,50 +796,55 @@ describe('protocol tests', () => {
775796
});
776797

777798
describe('notifications/cancelled behavior', () => {
778-
test('should abort request handler when notifications/cancelled is received', async () => {
779-
await protocol.connect(transport);
780-
781-
// Set up a request handler that checks if it was aborted
782-
let wasAborted = false;
783-
protocol.setRequestHandler('ping', async (_request, ctx) => {
784-
// Simulate a long-running operation
785-
await new Promise(resolve => setTimeout(resolve, 100));
786-
wasAborted = ctx.mcpReq.signal.aborted;
787-
return {};
788-
});
789-
790-
// Simulate an incoming request
791-
const requestId = 123;
792-
if (transport.onmessage) {
793-
transport.onmessage({
794-
jsonrpc: '2.0',
795-
id: requestId,
796-
method: 'ping',
797-
params: {}
799+
// Every legal JSON-RPC request id must cancel, including the ones a
800+
// truthiness guard swallows: `0` (the first id every peer assigns,
801+
// since the counter is zero-based) and the empty string.
802+
test.each([0, 123, '', 'req-1'])(
803+
'should abort request handler when notifications/cancelled carries requestId %j',
804+
async requestId => {
805+
await protocol.connect(transport);
806+
807+
// Set up a request handler that checks if it was aborted
808+
let wasAborted = false;
809+
protocol.setRequestHandler('ping', async (_request, ctx) => {
810+
// Simulate a long-running operation
811+
await new Promise(resolve => setTimeout(resolve, 100));
812+
wasAborted = ctx.mcpReq.signal.aborted;
813+
return {};
798814
});
799-
}
800815

801-
// Wait a bit for the handler to start
802-
await new Promise(resolve => setTimeout(resolve, 10));
816+
// Simulate an incoming request
817+
if (transport.onmessage) {
818+
transport.onmessage({
819+
jsonrpc: '2.0',
820+
id: requestId,
821+
method: 'ping',
822+
params: {}
823+
});
824+
}
825+
826+
// Wait a bit for the handler to start
827+
await new Promise(resolve => setTimeout(resolve, 10));
803828

804-
// Send cancellation notification
805-
if (transport.onmessage) {
806-
transport.onmessage({
807-
jsonrpc: '2.0',
808-
method: 'notifications/cancelled',
809-
params: {
810-
requestId: requestId,
811-
reason: 'User cancelled'
812-
}
813-
});
814-
}
829+
// Send cancellation notification
830+
if (transport.onmessage) {
831+
transport.onmessage({
832+
jsonrpc: '2.0',
833+
method: 'notifications/cancelled',
834+
params: {
835+
requestId: requestId,
836+
reason: 'User cancelled'
837+
}
838+
});
839+
}
815840

816-
// Wait for the handler to complete
817-
await new Promise(resolve => setTimeout(resolve, 150));
841+
// Wait for the handler to complete
842+
await new Promise(resolve => setTimeout(resolve, 150));
818843

819-
// Verify the request was aborted
820-
expect(wasAborted).toBe(true);
821-
});
844+
// Verify the request was aborted
845+
expect(wasAborted).toBe(true);
846+
}
847+
);
822848
});
823849

824850
// Spec basic/patterns/cancellation §Transport-Specific (2026-07-28): on a

0 commit comments

Comments
 (0)