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
6 changes: 6 additions & 0 deletions .changeset/aborted-requests-distinct-error.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@modelcontextprotocol/client': patch
'@modelcontextprotocol/server': patch
---

Aborting a request via `AbortSignal` now rejects with `SdkErrorCode.RequestAborted` (`REQUEST_ABORTED`) instead of `RequestTimeout`, so callers can tell a deliberate cancellation apart from a real timeout. A genuine timeout still rejects with `RequestTimeout`, including a timeout set with `AbortSignal.timeout()`. An `SdkError` passed as the abort reason is still rethrown untouched.
11 changes: 5 additions & 6 deletions packages/client/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ import {
scanXMcpHeaderDeclarations,
SdkError,
SdkErrorCode,
sdkErrorForAbortReason,
SERVER_INFO_META_KEY,
setProtocolInstrumentation,
SUBSCRIPTION_ID_META_KEY,
Expand Down Expand Up @@ -1881,12 +1882,11 @@ export class Client extends Protocol<ClientContext> {
if (hit !== undefined) {
// A pre-aborted caller signal must reject the same way it would on
// the wire path (`Protocol.request()` wraps an already-aborted
// signal as `SdkError(RequestTimeout, reason)`); without this guard
// signal as `SdkError(RequestAborted, reason)`); without this guard
// a cache hit would resolve successfully and silently swallow the
// abort.
if (options?.signal?.aborted) {
const reason = options.signal.reason;
throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));
throw sdkErrorForAbortReason(options.signal.reason);
}
return hit.value as R;
}
Expand Down Expand Up @@ -2050,12 +2050,11 @@ export class Client extends Protocol<ClientContext> {

// Honor RequestOptions.signal exactly as request() does: an
// already-aborted signal rejects synchronously before any setup, and
// the rejection is the same `SdkError(RequestTimeout, reason)` wrap
// the rejection is the same `SdkError(RequestAborted, reason)` wrap
// request() / `_serveFromCache` apply (unless `reason` is already an
// SdkError — preserved verbatim).
if (options?.signal?.aborted) {
const reason = options.signal.reason;
throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));
throw sdkErrorForAbortReason(options.signal.reason);
}

const requestAbort = new AbortController();
Expand Down
6 changes: 3 additions & 3 deletions packages/client/test/client/listen.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -379,7 +379,7 @@ describe('Client.listen()', () => {
await client.close();
});

it('options.signal already aborted: listen() rejects with SdkError(RequestTimeout) before any setup (parity with request())', async () => {
it('options.signal already aborted: listen() rejects with SdkError(RequestAborted) before any setup (parity with request())', async () => {
const { clientTx, written } = await scriptedModern();
const client = new Client({ name: 'c', version: '1' }, { versionNegotiation: { mode: 'auto' } });
await client.connect(clientTx);
Expand All @@ -388,9 +388,9 @@ describe('Client.listen()', () => {
ac.abort('user cancelled');
const error = await client.listen({ toolsListChanged: true }, { signal: ac.signal }).catch(e => e as SdkError);
// Same wrap as `Protocol.request()` / `_serveFromCache`: a non-SdkError
// reason is wrapped as RequestTimeout; the reason text is preserved.
// reason is wrapped as RequestAborted; the reason text is preserved.
expect(error).toBeInstanceOf(SdkError);
expect((error as SdkError).code).toBe(SdkErrorCode.RequestTimeout);
expect((error as SdkError).code).toBe(SdkErrorCode.RequestAborted);
expect((error as SdkError).message).toContain('user cancelled');
// No subscriptions/listen reached the wire; no listen state registered.
await flush();
Expand Down
4 changes: 2 additions & 2 deletions packages/client/test/client/responseCache.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1143,7 +1143,7 @@ describe('Client honours cacheHints (SEP-2549)', () => {
expect(wireCount('resources/read')).toBe(3);
});

it('a pre-aborted signal on a warm-cache hit rejects with SdkError(RequestTimeout) — the abort is not swallowed by the cache serve', async () => {
it('a pre-aborted signal on a warm-cache hit rejects with SdkError(RequestAborted) — the abort is not swallowed by the cache serve', async () => {
const store = new InMemoryResponseCacheStore();
const { clientTx, listCount } = await scriptedModernServer([[TOOL_A]], { listHint: { ttlMs: 60_000, cacheScope: 'public' } });
const client = modernClient(store);
Expand All @@ -1158,7 +1158,7 @@ describe('Client honours cacheHints (SEP-2549)', () => {
ac.abort('user cancelled');
const error = await client.listTools(undefined, { signal: ac.signal }).catch(e => e as SdkError);
expect(error).toBeInstanceOf(SdkError);
expect((error as SdkError).code).toBe(SdkErrorCode.RequestTimeout);
expect((error as SdkError).code).toBe(SdkErrorCode.RequestAborted);
expect((error as SdkError).message).toContain('user cancelled');
// The aborted call did not reach the wire.
expect(listCount()).toBe(1);
Expand Down
28 changes: 28 additions & 0 deletions packages/core-internal/src/errors/sdkErrors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ export enum SdkErrorCode {
// Transport errors
/** Request timed out waiting for response */
RequestTimeout = 'REQUEST_TIMEOUT',
/**
* Request was cancelled via an `AbortSignal`. Distinct from
* {@linkcode SdkErrorCode.RequestTimeout} so callers can tell a deliberate
* cancellation apart from a real timeout.
*/
RequestAborted = 'REQUEST_ABORTED',
/** Connection was closed */
ConnectionClosed = 'CONNECTION_CLOSED',
/** Failed to send message */
Expand Down Expand Up @@ -166,6 +172,28 @@ export class SdkError extends Error {
}
}

/**
* Wrap an `AbortSignal` reason in an `SdkError` for the abort paths
* (`Protocol.request()`, the client cache/listen guards, the multi-round-trip
* pacing delay). A reason that is already an `SdkError` passes through
* untouched, including one built by a foreign bundled copy of the SDK (matched
* through the cross-bundle brand). Anything else becomes
* {@linkcode SdkErrorCode.RequestAborted}, so callers can tell a deliberate
* cancellation apart from a real timeout. The one exception is a `TimeoutError`
* reason, which only `AbortSignal.timeout()` produces: that is a timeout the
* caller asked for, so it keeps {@linkcode SdkErrorCode.RequestTimeout}.
*/
export function sdkErrorForAbortReason(reason: unknown): SdkError {
if (reason instanceof SdkError) {
return reason;
}
const code =
(reason as { name?: unknown } | null | undefined)?.name === 'TimeoutError'
? SdkErrorCode.RequestTimeout
: SdkErrorCode.RequestAborted;
return new SdkError(code, String(reason));
}

/**
* Typed shape for HTTP error data carried by {@linkcode SdkHttpError}.
*/
Expand Down
6 changes: 3 additions & 3 deletions packages/core-internal/src/shared/inputRequiredDriver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by
* shrinking the budget passed to each leg — no new timer system.
*/
import { SdkError, SdkErrorCode } from '../errors/sdkErrors';
import { SdkError, SdkErrorCode, sdkErrorForAbortReason } from '../errors/sdkErrors';
import { isInputRequiredResult } from '../types/guards';
import type { Progress } from '../types/types';

Expand Down Expand Up @@ -160,7 +160,7 @@ export function inputRequiredRoundsExceededMessage(method: string, maxRounds: nu
export function sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason)));
reject(sdkErrorForAbortReason(signal.reason));
return;
}
const timer = setTimeout(() => {
Expand All @@ -169,7 +169,7 @@ export function sleep(ms: number, signal: AbortSignal | undefined): Promise<void
}, ms);
const onAbort = (): void => {
clearTimeout(timer);
reject(signal?.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal?.reason)));
reject(sdkErrorForAbortReason(signal?.reason));
};
signal?.addEventListener('abort', onAbort, { once: true });
});
Expand Down
1 change: 1 addition & 0 deletions packages/core-internal/src/shared/instrumentation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ export function outcomeForError(error: unknown): OperationOutcome {
if (error instanceof SdkError) {
if (error.code === SdkErrorCode.ConnectionClosed) return { type: 'closed' };
if (error.code === SdkErrorCode.RequestTimeout) return { type: 'timeout' };
if (error.code === SdkErrorCode.RequestAborted) return { type: 'cancelled' };
}
return { type: 'failed', error };
}
Expand Down
22 changes: 15 additions & 7 deletions packages/core-internal/src/shared/protocol.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { SdkError, SdkErrorCode } from '../errors/sdkErrors';
import { SdkError, SdkErrorCode, sdkErrorForAbortReason } from '../errors/sdkErrors';
import type {
AuthInfo,
CancelledNotification,
Expand Down Expand Up @@ -122,7 +122,8 @@ export type RequestOptions = {
onprogress?: ProgressCallback;

/**
* Can be used to cancel an in-flight request. This will cause an `AbortError` to be raised from {@linkcode Protocol.request | request()}.
* Can be used to cancel an in-flight request. This will cause an {@linkcode SdkError}
* with code {@linkcode SdkErrorCode.RequestAborted} to be raised from {@linkcode Protocol.request | request()}.
*/
signal?: AbortSignal;

Expand Down Expand Up @@ -1524,14 +1525,13 @@ export abstract class Protocol<ContextT extends BaseContext> {
}

// An already-aborted caller signal must surface the same way an
// in-flight abort does (`SdkError(RequestTimeout, reason)` via
// in-flight abort does (`SdkError(RequestAborted, reason)` via
// `cancel()` below). Bare `throwIfAborted()` would propagate the
// raw `signal.reason` instead, so callers that introduce an async
// hop before `request()` (e.g. a cache freshness check) would see
// a different rejection type depending on where the abort lands.
if (options?.signal?.aborted) {
const reason = options.signal.reason;
throw reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));
throw sdkErrorForAbortReason(options.signal.reason);
}

// Spec basic/patterns/cancellation §Transport-Specific (2026-07-28):
Expand Down Expand Up @@ -1612,8 +1612,16 @@ export abstract class Protocol<ContextT extends BaseContext> {
requestAbort.abort();
}

// Wrap the reason in an SdkError if it isn't already
const error = reason instanceof SdkError ? reason : new SdkError(SdkErrorCode.RequestTimeout, String(reason));
// Wrap the reason in an SdkError if it isn't already. An abort
// gets RequestAborted so callers can tell it apart from a real
// timeout; only the timeout path (which already passes a typed
// RequestTimeout error) keeps RequestTimeout.
const error =
outcome === 'cancelled'
? sdkErrorForAbortReason(reason)
: reason instanceof SdkError
? reason
: new SdkError(SdkErrorCode.RequestTimeout, String(reason));
reject(error);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,42 @@ describe('request() abort-reason passthrough', () => {
await expect(protocol.request({ method: 'ping' }, { signal: controller.signal })).rejects.toBe(reason);
});

it('wraps a non-SdkError abort reason in SdkError(RequestTimeout)', async () => {
it('wraps a non-SdkError abort reason in SdkError(RequestAborted)', async () => {
const protocol = await connectedProtocol();
const controller = new AbortController();
controller.abort(new Error('plain'));

const rejection = await protocol.request({ method: 'ping' }, { signal: controller.signal }).then(
() => {
throw new Error('request unexpectedly resolved');
},
(e: unknown) => e
);
expect(rejection).toBeInstanceOf(SdkError);
expect((rejection as SdkError).code).toBe(SdkErrorCode.RequestAborted);
});

it('rejects an in-flight abort with RequestAborted, not RequestTimeout', async () => {
const protocol = await connectedProtocol();
const controller = new AbortController();
const pending = protocol.request({ method: 'ping' }, { signal: controller.signal, timeout: 60_000 });
setTimeout(() => controller.abort(new DOMException('User cancelled', 'AbortError')), 10);
const rejection = await pending.then(
() => {
throw new Error('request unexpectedly resolved');
},
(e: unknown) => e
);
expect(rejection).toBeInstanceOf(SdkError);
expect((rejection as SdkError).code).toBe(SdkErrorCode.RequestAborted);
expect((rejection as SdkError).message).toContain('User cancelled');
});

it('keeps RequestTimeout for an AbortSignal.timeout() reason', async () => {
const protocol = await connectedProtocol();
const controller = new AbortController();
controller.abort(new DOMException('The operation timed out.', 'TimeoutError'));

const rejection = await protocol.request({ method: 'ping' }, { signal: controller.signal }).then(
() => {
throw new Error('request unexpectedly resolved');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ describe('SdkErrorCode', () => {
NotInitialized: 'NOT_INITIALIZED',
CapabilityNotSupported: 'CAPABILITY_NOT_SUPPORTED',
RequestTimeout: 'REQUEST_TIMEOUT',
RequestAborted: 'REQUEST_ABORTED',
ConnectionClosed: 'CONNECTION_CLOSED',
SendFailed: 'SEND_FAILED',
InvalidResult: 'INVALID_RESULT',
Expand Down
Loading