modelcontextprotocol / modelcontextprotocol/python-sdk

MCPServer handlers should raise exceptions, not return error objects

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

Ninguém assumiu esta issue ainda.

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

Descrição

Problem

The current error handling across the two server layers is inconsistent and confusing for users. As noted by Marcelo, the experience should be more like Starlette's raise HTTPException pattern.

Current behavior

MCPServer (high-level) tool handlers:

  • Raising any exception → caught by Tool.run(), re-wrapped as ToolError, then caught by _handle_call_tool()CallToolResult(isError=True) (a JSON-RPC success response)
  • Raising MCPError → re-raised past _handle_call_tool() → becomes a JSON-RPC error response
  • Returning CallToolResult(isError=True) directly → also works
  • Resource/prompt handlers have no try/except at the MCPServer layer — exceptions propagate to the low-level server

Low-level server handlers:

  • _handle_request() catches MCPError → sends its .error as a JSON-RPC error
  • Any other ExceptionErrorData(code=0, message=str(err)) → JSON-RPC error with non-standard code

Users need to understand the difference between ToolError, MCPError, CallToolResult(isError=True), and plain exceptions — each produces different behavior depending on which layer catches it.

Desired behavior
  1. MCPServer users should raise exceptions to signal errors — the framework converts them to the appropriate protocol response. No need to construct and return error result objects.
  2. Low-level server users should return ErrorData explicitly when they want to control the JSON-RPC error response, since they operate at the protocol level.
  3. Unhandled exceptions at either layer should be caught gracefully by the framework and returned as a well-formed JSON-RPC error, without leaking internal details to the client.
Related issues
  • #1742 — Introduce typed error classes with metadata (covers error taxonomy but not the raise-vs-return layering)
  • #698 — Tool.run should not reveal exception value to the client (security concern with current behavior)
  • #396 — Inconsistent Exception Handling in @app.call_tool (older, narrower scope)
  • #1788 — Extensible pattern for protocol flow-control exceptions

AI Disclaimer

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

Comece com _handle_call_tool() em src/mcp/server/mcpserver/server.py e _handle_request() em src/mcp/server/lowlevel/server.py, comparando seus caminhos de exceção e a construção das respostas. O trabalho estará concluído quando os handlers de alto nível puderem sinalizar erros lançando exceções, os handlers de baixo nível puderem retornar explicitamente ErrorData e as exceções não tratadas em qualquer uma das camadas produzirem erros JSON-RPC bem formados sem vazar detalhes internos.

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

Avaliação

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

Receba novas issues na sua caixa de entrada

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