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
16 changes: 16 additions & 0 deletions .changeset/periodic-ping.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
"@modelcontextprotocol/core": minor
"@modelcontextprotocol/client": minor
"@modelcontextprotocol/server": minor
---

feat: add opt-in periodic ping for connection health monitoring

Adds a `pingIntervalMs` option to `ProtocolOptions` that enables automatic
periodic pings to verify the remote side is still responsive. Per the MCP
specification, implementations SHOULD periodically issue pings to detect
connection health, with configurable frequency.

The feature is disabled by default. When enabled, pings begin after
initialization completes and stop automatically when the connection closes.
Failures are reported via the `onerror` callback without stopping the timer.
3 changes: 3 additions & 0 deletions packages/client/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,9 @@ export class Client extends Protocol<ClientContext> {
this._setupListChangedHandlers(this._pendingListChangedConfig);
this._pendingListChangedConfig = undefined;
}

// Start periodic ping after successful initialization
this.startPeriodicPing();
} catch (error) {
// Disconnect if initialization fails.
void this.close();
Expand Down
67 changes: 67 additions & 0 deletions packages/core/src/shared/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import type {
import {
CancelTaskResultSchema,
CreateTaskResultSchema,
EmptyResultSchema,
getNotificationSchema,
getRequestSchema,
getResultSchema,
Expand Down Expand Up @@ -119,6 +120,20 @@ export type ProtocolOptions = {
* appropriately (e.g., by failing the task, dropping messages, etc.).
*/
maxTaskQueueSize?: number;
/**
* Interval (in milliseconds) between periodic ping requests sent to the remote side
* to verify connection health. If set, pings will begin after {@linkcode Protocol.connect | connect()}
* completes and stop automatically when the connection closes.
*
* Per the MCP specification, implementations SHOULD periodically issue pings to
* detect connection health, with configurable frequency.
*
* Disabled by default (no periodic pings). Typical values: 15000-60000 (15s-60s).
*
* Ping failures are reported via the {@linkcode Protocol.onerror | onerror} callback
* and do not stop the periodic timer.
*/
pingIntervalMs?: number;
};

/**
Expand Down Expand Up @@ -413,6 +428,9 @@ export abstract class Protocol<ContextT extends BaseContext> {

private _requestResolvers: Map<RequestId, (response: JSONRPCResultResponse | Error) => void> = new Map();

private _pingTimer?: ReturnType<typeof setInterval>;
private _pingIntervalMs?: number;

protected _supportedProtocolVersions: string[];

/**
Expand Down Expand Up @@ -441,6 +459,7 @@ export abstract class Protocol<ContextT extends BaseContext> {

constructor(private _options?: ProtocolOptions) {
this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS;
this._pingIntervalMs = _options?.pingIntervalMs;

this.setNotificationHandler('notifications/cancelled', notification => {
this._oncancel(notification);
Expand Down Expand Up @@ -724,6 +743,8 @@ export abstract class Protocol<ContextT extends BaseContext> {
}

private _onclose(): void {
this.stopPeriodicPing();

const responseHandlers = this._responseHandlers;
this._responseHandlers = new Map();
this._progressHandlers.clear();
Expand Down Expand Up @@ -992,10 +1013,56 @@ export abstract class Protocol<ContextT extends BaseContext> {
return this._transport;
}

/**
* Starts sending periodic ping requests at the configured interval.
* Pings are used to verify that the remote side is still responsive.
* Failures are reported via the {@linkcode onerror} callback but do not
* stop the timer; pings continue until the connection is closed.
*
* This is called automatically at the end of {@linkcode connect} when
* `pingIntervalMs` is set. Subclasses that override `connect()` and
* perform additional initialization (e.g., the MCP handshake) may call
* this method after their initialization is complete instead.
*
* Has no effect if periodic ping is already running or if no interval
* is configured.
*/
protected startPeriodicPing(): void {
if (this._pingTimer || !this._pingIntervalMs) {
return;
}

this._pingTimer = setInterval(async () => {
try {
await this._requestWithSchema({ method: 'ping' }, EmptyResultSchema, {
timeout: this._pingIntervalMs
});
} catch (error) {
this._onerror(error instanceof Error ? error : new Error(`Periodic ping failed: ${String(error)}`));
}
}, this._pingIntervalMs);

// Allow the process to exit even if the timer is still running
if (typeof this._pingTimer === 'object' && 'unref' in this._pingTimer) {
this._pingTimer.unref();
}
}

/**
* Stops periodic ping requests. Called automatically when the connection closes.
*/
protected stopPeriodicPing(): void {
if (this._pingTimer) {
clearInterval(this._pingTimer);
this._pingTimer = undefined;
}
}

/**
* Closes the connection.
*/
async close(): Promise<void> {
this.stopPeriodicPing();
await this._transport?.close();
}

Expand Down
Loading
Loading