|
| 1 | +"""Test for issue #1356: SSE parsing fails with Unicode line separator characters.""" |
| 2 | + |
| 3 | +import multiprocessing |
| 4 | +import socket |
| 5 | +import time |
| 6 | +from collections.abc import Generator |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +import anyio |
| 10 | +import pytest |
| 11 | +import uvicorn |
| 12 | +from starlette.applications import Starlette |
| 13 | +from starlette.requests import Request |
| 14 | +from starlette.responses import Response |
| 15 | +from starlette.routing import Mount, Route |
| 16 | + |
| 17 | +from mcp.client.session import ClientSession |
| 18 | +from mcp.client.sse import sse_client |
| 19 | +from mcp.server import Server |
| 20 | +from mcp.server.sse import SseServerTransport |
| 21 | +from mcp.server.transport_security import TransportSecuritySettings |
| 22 | +from mcp.shared.exceptions import McpError |
| 23 | +from mcp.types import TextContent, Tool |
| 24 | + |
| 25 | +pytestmark = pytest.mark.anyio |
| 26 | + |
| 27 | + |
| 28 | +class ProblematicUnicodeServer(Server): |
| 29 | + """Test server that returns problematic Unicode characters.""" |
| 30 | + |
| 31 | + def __init__(self): |
| 32 | + super().__init__("ProblematicUnicodeServer") |
| 33 | + |
| 34 | + @self.list_tools() |
| 35 | + async def handle_list_tools() -> list[Tool]: |
| 36 | + return [ |
| 37 | + Tool( |
| 38 | + name="get_problematic_unicode", |
| 39 | + description="Returns text with problematic Unicode character U+2028", |
| 40 | + inputSchema={"type": "object", "properties": {}}, |
| 41 | + ) |
| 42 | + ] |
| 43 | + |
| 44 | + @self.call_tool() |
| 45 | + async def handle_call_tool(name: str, args: dict[str, Any]) -> list[TextContent]: |
| 46 | + if name == "get_problematic_unicode": |
| 47 | + # Return text with U+2028 (LINE SEPARATOR) which can cause JSON parsing issues |
| 48 | + # U+2028 is a valid Unicode character but can break JSON parsing in some contexts |
| 49 | + problematic_text = "This text contains a line separator\u2028character that may break JSON parsing" |
| 50 | + return [TextContent(type="text", text=problematic_text)] |
| 51 | + return [TextContent(type="text", text=f"Unknown tool: {name}")] |
| 52 | + |
| 53 | + |
| 54 | +def make_problematic_server_app() -> Starlette: |
| 55 | + """Create test Starlette app with SSE transport.""" |
| 56 | + security_settings = TransportSecuritySettings( |
| 57 | + allowed_hosts=["127.0.0.1:*", "localhost:*"], |
| 58 | + allowed_origins=["http://127.0.0.1:*", "http://localhost:*"], |
| 59 | + ) |
| 60 | + sse = SseServerTransport("/messages/", security_settings=security_settings) |
| 61 | + server = ProblematicUnicodeServer() |
| 62 | + |
| 63 | + async def handle_sse(request: Request) -> Response: |
| 64 | + async with sse.connect_sse(request.scope, request.receive, request._send) as streams: |
| 65 | + await server.run(streams[0], streams[1], server.create_initialization_options()) |
| 66 | + return Response() |
| 67 | + |
| 68 | + app = Starlette( |
| 69 | + routes=[ |
| 70 | + Route("/sse", endpoint=handle_sse), |
| 71 | + Mount("/messages/", app=sse.handle_post_message), |
| 72 | + ] |
| 73 | + ) |
| 74 | + |
| 75 | + return app |
| 76 | + |
| 77 | + |
| 78 | +def run_problematic_server(server_port: int) -> None: |
| 79 | + """Run the problematic Unicode test server.""" |
| 80 | + app = make_problematic_server_app() |
| 81 | + server = uvicorn.Server( |
| 82 | + config=uvicorn.Config(app=app, host="127.0.0.1", port=server_port, log_level="error") |
| 83 | + ) |
| 84 | + server.run() |
| 85 | + |
| 86 | + |
| 87 | +@pytest.fixture |
| 88 | +def problematic_server_port() -> int: |
| 89 | + """Get an available port for the test server.""" |
| 90 | + with socket.socket() as s: |
| 91 | + s.bind(("127.0.0.1", 0)) |
| 92 | + return s.getsockname()[1] |
| 93 | + |
| 94 | + |
| 95 | +@pytest.fixture |
| 96 | +def problematic_server(problematic_server_port: int) -> Generator[str, None, None]: |
| 97 | + """Start the problematic Unicode test server in a separate process.""" |
| 98 | + proc = multiprocessing.Process( |
| 99 | + target=run_problematic_server, kwargs={"server_port": problematic_server_port}, daemon=True |
| 100 | + ) |
| 101 | + proc.start() |
| 102 | + |
| 103 | + # Wait for server to be running |
| 104 | + max_attempts = 20 |
| 105 | + attempt = 0 |
| 106 | + while attempt < max_attempts: |
| 107 | + try: |
| 108 | + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: |
| 109 | + s.connect(("127.0.0.1", problematic_server_port)) |
| 110 | + break |
| 111 | + except ConnectionRefusedError: |
| 112 | + time.sleep(0.1) |
| 113 | + attempt += 1 |
| 114 | + else: |
| 115 | + raise RuntimeError(f"Server failed to start after {max_attempts} attempts") |
| 116 | + |
| 117 | + yield f"http://127.0.0.1:{problematic_server_port}" |
| 118 | + |
| 119 | + # Clean up |
| 120 | + proc.kill() |
| 121 | + proc.join(timeout=2) |
| 122 | + |
| 123 | + |
| 124 | +async def test_json_parsing_with_problematic_unicode(problematic_server: str) -> None: |
| 125 | + """Test that special Unicode characters like U+2028 are handled properly. |
| 126 | + |
| 127 | + This test reproduces issue #1356 where special Unicode characters |
| 128 | + cause JSON parsing to fail and the raw exception is sent to the stream, |
| 129 | + preventing proper error handling. |
| 130 | + """ |
| 131 | + # Connect to the server using SSE client |
| 132 | + async with sse_client(problematic_server + "/sse") as streams: |
| 133 | + async with ClientSession(*streams) as session: |
| 134 | + # Initialize the connection |
| 135 | + result = await session.initialize() |
| 136 | + assert result.serverInfo.name == "ProblematicUnicodeServer" |
| 137 | + |
| 138 | + # Call the tool that returns problematic Unicode |
| 139 | + # This should succeed and not hang |
| 140 | + |
| 141 | + # Use a timeout to detect if we're hanging |
| 142 | + with anyio.fail_after(5): # 5 second timeout |
| 143 | + try: |
| 144 | + response = await session.call_tool("get_problematic_unicode", {}) |
| 145 | + |
| 146 | + # If we get here, the Unicode was handled properly |
| 147 | + assert len(response.content) == 1 |
| 148 | + text_content = response.content[0] |
| 149 | + assert hasattr(text_content, "text"), f"Response doesn't have text: {text_content}" |
| 150 | + |
| 151 | + expected = "This text contains a line separator\u2028character that may break JSON parsing" |
| 152 | + assert text_content.text == expected, f"Expected: {expected!r}, Got: {text_content.text!r}" |
| 153 | + |
| 154 | + except McpError: |
| 155 | + pytest.fail("Unexpected error with tool call") |
| 156 | + except TimeoutError: |
| 157 | + # If we timeout, the issue is confirmed - the client hangs |
| 158 | + pytest.fail("Client hangs when handling problematic Unicode (issue #1356 confirmed)") |
| 159 | + except Exception as e: |
| 160 | + # We should not get raw exceptions - they should be wrapped as McpError |
| 161 | + pytest.fail(f"Got raw exception instead of McpError: {type(e).__name__}: {e}") |
0 commit comments