modelcontextprotocol / modelcontextprotocol/python-sdk

Initialize call hangs forever if MCP server does not return a `Content-Type: text/plain`

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

Ninguém assumiu esta issue ainda.

bug fix proposed P2 ready for work
Linguagem predominante
Python
Estrelas
24.3k
Forks
4k
Merge médio
1d 1h
PRs com merge (30d)
31

Descrição

Initial Checks
Description

We had some timeouts on our server while using MCP client from the SDK.
When users try to integrate our client with their MCP server, we do an initialize call to the server and we are waiting infinitely to the following:

sync with self:
    ...

After investigation, it seems the error happens when the MCP server is misconfigured, and returns something different than Content-Type: text/event-stream as a response from the initialize call.

Although it is on the server side, the client should be able to fail immediately with a understandable error to warn the user something went wrong with the server's initialize output.

Example Code
# server.py

from http.server import BaseHTTPRequestHandler, HTTPServer

class PlainTextHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        self.rfile.read(length)

        body = b"this is not json"
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, format, *args):
        print(f"[server] {format % args}")

server = HTTPServer(("localhost", 9000), PlainTextHandler)
print("[server] listening on http://localhost:9000")
server.serve_forever()

# client.py
import asyncio
import mcp
from mcp.client.streamable_http import streamable_http_client

async def main():
    print("connecting…")
    async with streamable_http_client("http://localhost:9000/mcp") as (
        read_stream, write_stream, _,
    ):
        async with mcp.ClientSession(read_stream, write_stream) as session:
            await session.initialize()  # ← hangs here forever

    print("done (you should never see this)")
Python & MCP Python SDK
- Python 3.12.12
- MCP - 1.27.0

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 pelo ponto de entrada streamable_http_client mostrado em client.py e reproduza o comportamento usando o exemplo PlainTextHandler em server.py. Rastreie o tratamento da resposta de initialize e adicione cobertura para uma resposta non-text/event-stream; estará concluído quando o cliente falhar prontamente com um erro compreensível em vez de ficar travado.

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
Bug
Dificuldade
3/5
Tempo estimado
1-2 dias
Status de atividade
Pouca atividade
Clareza
Razoavelmente clara
Facilidade para iniciantes
58/100

Receba novas issues na sua caixa de entrada

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