modelcontextprotocol / modelcontextprotocol/python-sdk

Simplify and harden session lifecycle with an explicit state machine

Aberta
#1,691 2 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

enhancement P2 v2
Linguagem predominante
Python
Estrelas
24.3k
Forks
4k
Merge médio
1d 1h
PRs com merge (30d)
31

Descrição

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

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Nenhum arquivo ou ponto de entrada é nomeado; comece localizando a inicialização de sessão existente, o caminho HTTP stateless e a limpeza de AsyncExitStack. Revise a issue #756 e os testes do transporte em memória descritos na issue. Considera-se concluído quando houver estados explícitos do ciclo de vida, um caminho stateless dedicado, limpeza confiável em todos os caminhos de saída e testes de transição para os casos de erro e stateful/stateless.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
python
Domínio
api, backend
Tipo de issue
Refatoração
Dificuldade
5/5
Tempo estimado
Mais de uma semana
Status de atividade
Estagnada
Clareza
Precisa de esclarecimento
Facilidade para iniciantes
25/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.