modelcontextprotocol / modelcontextprotocol/java-sdk

Add timeout and fallback logging for closeGracefully() to prevent hanging shutdown

Aperta
#635 1 commento 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

enhancement needs repro
Lingua principale
Java
Stelle
3.7k
Fork
1.1k
Merge medio
1g 15h
PR unite (30g)
9

Descrizione

Problem

When using McpAsyncClient.closeGracefully(), the client executes:

return this.initializer.closeGracefully()
        .then(transport.closeGracefully());

Both initializer.closeGracefully() and transport.closeGracefully() return Mono<Void>.
However, if either of them hangs—for example:

  • The underlying transport (HTTP/SSE/WebSocket) never completes
  • The server doesn’t respond to shutdown
  • A Reactor pipeline remains open (no onComplete)

then the returned Mono never completes, causing the application to hang indefinitely during shutdown.

This results in JVMs or containers that never terminate, blocking CI/CD or production deployments.


Goal

Add a timeout and fallback mechanism to ensure that the client always terminates safely, even when the transport or initializer fails to complete.


Proposed Change

1. Wrap shutdown calls with timeout and fallback

Use Reactor’s timeout(Duration, fallbackMono) operator to guarantee a bounded shutdown duration.

public Mono<Void> closeGracefully() {
    return Mono.defer(() -> {
        long start = logger.isDebugEnabled() ? System.nanoTime() : 0L;
        Duration timeout = Duration.ofSeconds(
                Integer.getInteger("mcp.shutdown.timeout.seconds", 10));

        Mono<Void> graceful = this.initializer.closeGracefully()
            .then(transport.closeGracefully());

        Mono<Void> fallback = Mono.fromRunnable(() -> {
                logger.warn("closeGracefully() timed out after {} seconds; proceeding with best-effort shutdown.", timeout.getSeconds());
                try {
                    this.transport.close(); // force-close if needed
                } catch (Throwable t) {
                    logger.warn("Fallback forced close encountered error: {}", t.toString());
                }
            })
            .then();

        return graceful
            .timeout(timeout, fallback)
            .doOnError(e -> logger.warn("closeGracefully() failed: {}", e.toString()))
            .onErrorResume(e -> Mono.empty()) // ensure app doesn't hang
            .doFinally(sig -> {
                if (logger.isDebugEnabled()) {
                    long durationMs = (System.nanoTime() - start) / 1_000_000;
                    logger.debug("closeGracefully() finished with signal={}, took {} ms", sig, durationMs);
                }
            });
    });
}

Summary

Introduce a timeout and fallback mechanism for closeGracefully() to guarantee reliable termination, preventing hanging shutdowns when the transport or lifecycle initializer fails to complete.


Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Leggi prima McpAsyncClient.closeGracefully(), poi esamina initializer.closeGracefully() e transport.closeGracefully() per comprenderne il comportamento al completamento. Verifica che la gestione dei timeout, l’avviso e la chiusura forzata di fallback, la gestione degli errori e il completamento finale rendano lo shutdown delimitato senza modificare il percorso graceful previsto.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
java
Ambito
api
Tipo di issue
Funzionalità
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
50/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.