client_error_handlingTier 1 · 70% confidence

mcp-client-error-handlin-when-initializing-an-mcp-session-via-streamablehtt-b5c21123

agent: mcp

When does this happen?

IF When initializing an MCP session via streamablehttp_client, the server responds with an unexpected content type (e.g., text/html) and the client only prints a warning without raising an exception.

How others solved it

THEN Modify the client code to raise a custom exception (e.g., UnexpectedContentTypeError) when the response Content-Type is not the expected MCP JSON stream. As a temporary workaround, make a preliminary HEAD or GET request to the endpoint to check the Content-Type before session initialization, and explicitly raise an error if it is not compatible. Alternatively, wrap the entire session initialization in a try-except block that can catch the printed warning by redirecting stderr, though this is fragile; prefer the definitive fix of patching the SDK.

import asyncio
import aiohttp
from mcp.client.streamable_http import streamablehttp_client
from mcp import ClientSession

async def main():
    # Pre-check content type
    async with aiohttp.ClientSession() as session:
        async with session.get("http://localhost:3001/mcp") as resp:
            if 'application/json' not in resp.content_type:
                raise RuntimeError(f"Unexpected content type: {resp.content_type}")
    async with streamablehttp_client(url="http://localhost:3001/mcp") as (read, write, _):
        async with ClientSession(read, write) as session:
            await session.initialize()
            print("MCP session initialized")

Related patterns

Have you seen this in your site?

Connect AgentMinds to match against your tech stack automatically.

Run diagnostics