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 @@ -541,6 +541,9 @@ export class Client extends Protocol<ClientContext> {
this._setupListChangedHandlers(this._pendingListChangedConfig);
this._pendingListChangedConfig = undefined;
}

// Start periodic ping after successful initialization
this.startPeriodicPing();
Comment on lines +544 to +546
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Bug: Periodic pings are not restarted after client reconnection. The reconnection path (line 497-501) returns early when transport.sessionId is set, skipping the startPeriodicPing() call at line 546. Since _onclose() clears the ping timer during disconnection, connection health monitoring silently stops working after any reconnect cycle. Fix: add this.startPeriodicPing() before the return at line 501.

Extended reasoning...

What the bug is

In Client.connect(), there are two code paths: the initial connection path (which performs the full MCP initialization handshake) and the reconnection path (when transport.sessionId is already set). The startPeriodicPing() call at line 546 is only reached via the initial connection path. The reconnection path at lines 497-501 returns early, skipping it entirely.

How it manifests

When a client disconnects and reconnects (e.g., due to a transient network failure with an HTTP transport), the following sequence occurs:

  1. The old transport closes, triggering _onclose() in Protocol, which calls stopPeriodicPing() — this clears _pingTimer via clearInterval.
  2. The application calls client.connect(newTransport) where newTransport.sessionId is already set (since it is a reconnection to an existing session).
  3. super.connect(transport) is called, setting up the new transport.
  4. The guard transport.sessionId \!== undefined evaluates to true, so the method sets the protocol version and returns at line 501.
  5. startPeriodicPing() at line 546 is never reached.
  6. Since _pingTimer was cleared in step 1 and _pingIntervalMs is still set from construction, startPeriodicPing() would successfully start a new timer — but it is simply never called.

Why existing code does not prevent it

The startPeriodicPing() method has a guard if (this._pingTimer || \!this._pingIntervalMs) that prevents duplicate timers, but after _onclose() runs, _pingTimer is undefined, so the guard would allow the timer to be started. The problem is purely that the method is never invoked in the reconnection path. Neither super.connect() (i.e., Protocol.connect()) nor any other part of the reconnection flow calls it.

Impact

Any client that uses pingIntervalMs for connection health monitoring will silently lose that monitoring after the first reconnection. This is particularly problematic because reconnections are exactly the scenario where health monitoring is most valuable — the connection was already unstable once, and the user wants to know if it becomes unresponsive again. The client will believe pings are active (since _pingIntervalMs is still set), but no pings will be sent.

Fix

Add this.startPeriodicPing() to the reconnection branch in Client.connect(), just before the return statement at line 501:

if (transport.sessionId \!== undefined) {
    if (this._negotiatedProtocolVersion \!== undefined && transport.setProtocolVersion) {
        transport.setProtocolVersion(this._negotiatedProtocolVersion);
    }
    this.startPeriodicPing();
    return;
}

The idempotency guard in startPeriodicPing() ensures this is safe even if called multiple times.

} catch (error) {
// Disconnect if initialization fails.
void this.close();
Expand Down
68 changes: 68 additions & 0 deletions packages/core/src/shared/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import type {
TaskCreationParams
} from '../types/index.js';
import {
EmptyResultSchema,
getNotificationSchema,
getRequestSchema,
getResultSchema,
Expand Down Expand Up @@ -93,6 +94,21 @@ export type ProtocolOptions = {
* so they should NOT be included here.
*/
tasks?: TaskManagerOptions;

/**
* 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 @@ -309,6 +325,9 @@ export abstract class Protocol<ContextT extends BaseContext> {

private _taskManager: TaskManager;

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

protected _supportedProtocolVersions: string[];

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

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

// Create TaskManager from protocol options
this._taskManager = _options?.tasks ? new TaskManager(_options.tasks) : new NullTaskManager();
Expand Down Expand Up @@ -488,6 +508,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 @@ -709,10 +731,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