modelcontextprotocol / modelcontextprotocol/python-sdk
Simplify and harden session lifecycle with an explicit state machine
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 24.3k
- Forks
- 4k
- Merge medio
- 1 d 1 h
- PR fusionados (30 d)
- 31
Descripción
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
-
Introduce an explicit session state machine
Represent distinct states as separate types, for example:
UninitializedSessionNegotiatingSessionActiveSessionClosedSessionStatelessSession(for per-request / ephemeral cases)
Each state exposes only the operations that are valid in that state, and transitions return the next state type.
-
Model stateless mode explicitly
- Instead of marking a stateful session as "Initialized" prematurely, model stateless HTTP as a dedicated
StatelessSessiontype with a simpler lifecycle. - Make behavior differences clear in code and docs.
- Instead of marking a stateful session as "Initialized" prematurely, model stateless HTTP as a dedicated
-
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.
- Ensure that all lifecycle paths (happy path, error, cancellation) lead through code that:
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
Guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
No se nombran archivos ni puntos de entrada; empieza por localizar la inicialización de sesión existente, la ruta HTTP sin estado y la limpieza de AsyncExitStack. Revisa el issue #756 y las pruebas del transporte en memoria descritas en el issue. Se considera terminado cuando haya estados de ciclo de vida explícitos, una ruta sin estado dedicada, una limpieza fiable en todas las rutas de salida y pruebas de transición para los casos de error y con estado/sin estado.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- api, backend
- Tipo de issue
- Refactorización
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Necesita aclaración
- Aptitud para principiantes
- 25/100