Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/fuzzy-birds-cancel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@modelcontextprotocol/core': patch
---

Fix `notifications/cancelled` handling for request ID `0`. Previously the cancellation guard treated `0` as missing and left the first request from a protocol instance uncancellable.
2 changes: 1 addition & 1 deletion packages/core/src/shared/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ export abstract class Protocol<ContextT extends BaseContext> {
protected abstract buildContext(ctx: BaseContext, transportInfo?: MessageExtraInfo): ContextT;

private async _oncancel(notification: CancelledNotification): Promise<void> {
if (!notification.params.requestId) {
if (notification.params.requestId === undefined) {
return;
}
// Handle request cancellation
Expand Down
37 changes: 37 additions & 0 deletions packages/core/test/shared/protocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2319,6 +2319,43 @@ describe('Request Cancellation vs Task Cancellation', () => {
expect(wasAborted).toBe(true);
});

test('should abort request handler when cancelling request ID 0', async () => {
await protocol.connect(transport);

let wasAborted = false;
protocol.setRequestHandler('ping', async (_request, ctx) => {
await new Promise(resolve => setTimeout(resolve, 100));
wasAborted = ctx.mcpReq.signal.aborted;
return {};
});

if (transport.onmessage) {
transport.onmessage({
jsonrpc: '2.0',
id: 0,
method: 'ping',
params: {}
});
}

await new Promise(resolve => setTimeout(resolve, 10));

if (transport.onmessage) {
transport.onmessage({
jsonrpc: '2.0',
method: 'notifications/cancelled',
params: {
requestId: 0,
reason: 'User cancelled'
}
});
}

await new Promise(resolve => setTimeout(resolve, 150));

expect(wasAborted).toBe(true);
});

test('should NOT automatically cancel associated tasks when notifications/cancelled is received', async () => {
await protocol.connect(transport);

Expand Down
Loading