modelcontextprotocol / modelcontextprotocol/python-sdk

Simplify and harden session lifecycle with an explicit state machine

Aperta
#1,691 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

enhancement P2 v2
Lingua principale
Python
Stelle
24.3k
Fork
4k
Merge medio
1g 1h
PR unite (30g)
31

Descrizione

Description

Summary

Server and client sessions use an internal initialization state machine combined with various flags and manual AsyncExitStack management. Stateless mode complicates this further by setting an "Initialized" state early as a workaround.

This makes the lifecycle hard to reason about and contributes to subtle bugs (e.g., past issues like #756 in stateless mode).

Problems

  • Scattered state management: Initialization and teardown logic are spread across methods and files.
  • Special cases for stateless mode: Stateless HTTP sets the session as initialized even though no real protocol negotiation has occurred.
  • Resource management risk: If initialization fails midway, transport tasks and resources may not be cleaned up reliably.
  • Testing difficulty: Tests often bypass parts of the lifecycle using in-memory transports.

Proposal

  1. Introduce an explicit session state machine

    Represent distinct states as separate types, for example:

    • UninitializedSession
    • NegotiatingSession
    • ActiveSession
    • ClosedSession
    • StatelessSession (for per-request / ephemeral cases)

    Each state exposes only the operations that are valid in that state, and transitions return the next state type.

  2. Model stateless mode explicitly

    • Instead of marking a stateful session as "Initialized" prematurely, model stateless HTTP as a dedicated StatelessSession type with a simpler lifecycle.
    • Make behavior differences clear in code and docs.
  3. Centralize resource cleanup

    • Ensure that all lifecycle paths (happy path, error, cancellation) lead through code that:
      • cancels outstanding tasks,
      • closes transports,
      • releases resources stored in AsyncExitStack.

Why this matters

  • Reliability: Fewer edge cases and surprise states where messages can be processed incorrectly.
  • Debuggability: Easier to reason about what can happen in each state.
  • Extensibility: Adding new lifecycle behavior (e.g., resuming sessions) becomes more manageable.

Acceptance criteria

  • Session lifecycle is represented via explicit types or a clearly defined state machine.
  • Stateless HTTP mode uses a dedicated path rather than setting "Initialized" as a hack.
  • All entry/exit paths of sessions ensure proper cleanup of transports and tasks.
  • Tests cover state transitions, including error cases and stateless/stat eful differences.
References

No response

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

Non vengono indicati file né punti di ingresso; inizia individuando l’inizializzazione della sessione esistente, il percorso HTTP stateless e la pulizia di AsyncExitStack. Esamina l’issue #756 e i test del trasporto in memoria descritti nell’issue. Il lavoro è completo quando sono presenti stati espliciti del ciclo di vita, un percorso stateless dedicato, una pulizia affidabile in ogni percorso di uscita e test delle transizioni per i casi di errore e stateful/stateless.

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

Valutazione

Stack tecnologico
python
Ambito
api, backend
Tipo di issue
Refactoring
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Da chiarire
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.