Python tool for converting files and office documents to Markdown.
fix(mcp): migrate to MCP SDK 2.x so 2026-07-28 clients can connect (#2363)
Çağdaş Yürekli57a481e1aa7a
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.ymlindex fb4626c3..7e6b6ba5 100644--- a/.github/workflows/tests.yml+++ b/.github/workflows/tests.yml@@ -44,3 +44,24 @@ jobs:- name: Run testsworking-directory: packages/markitdown-ocrrun: pytest+++ mcp-tests:+ runs-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ python-version: ["3.10", "3.11", "3.12", "3.13"]++ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: ${{ matrix.python-version }}++ - name: Install packages+ run: pip install "./packages/markitdown[all]" ./packages/markitdown-mcp pytest++ - name: Run tests+ working-directory: packages/markitdown-mcp+ run: pytestdiff --git a/packages/markitdown-mcp/pyproject.toml b/packages/markitdown-mcp/pyproject.tomlindex 746253be..b72fc582 100644--- a/packages/markitdown-mcp/pyproject.toml+++ b/packages/markitdown-mcp/pyproject.toml@@ -24,8 +24,9 @@ classifiers = ["Programming Language :: Python :: Implementation :: PyPy",]dependencies = [- "mcp~=1.8.0",+ "mcp>=2.1.1,<3.0.0","markitdown[all]>=0.1.1,<0.2.0",+ "requests>=2.0.0,<3.0.0",][project.urls]diff --git a/packages/markitdown-mcp/src/markitdown_mcp/__main__.py b/packages/markitdown-mcp/src/markitdown_mcp/__main__.pyindex dcc9e38f..f28c429a 100644--- a/packages/markitdown-mcp/src/markitdown_mcp/__main__.py+++ b/packages/markitdown-mcp/src/markitdown_mcp/__main__.py@@ -1,31 +1,50 @@import contextlib-import sys+import loggingimport os+import sysfrom collections.abc import AsyncIterator-from mcp.server.fastmcp import FastMCP-from mcp.server.fastmcp.server import Settings+from mcp.server.mcpserver import MCPServer+from mcp.server.mcpserver.exceptions import ToolErrorfrom starlette.applications import Starlette-from mcp.server.sse import SseServerTransport-from starlette.requests import Request-from starlette.routing import Mount, Route-from starlette.types import Receive, Scope, Send-from mcp.server import Server-from mcp.server.streamable_http_manager import StreamableHTTPSessionManager-from markitdown import MarkItDown+from markitdown import MarkItDown, FileConversionException, UnsupportedFormatException+import requestsimport uvicorn-# Resolve the forward reference in Settings.lifespan before the model is first-# instantiated, otherwise pydantic-settings emits IncompleteFieldDefinitionWarning.-Settings.model_rebuild()+logger = logging.getLogger(__name__)-# Initialize FastMCP server for MarkItDown (SSE)-mcp = FastMCP("markitdown")+# Initialize the MCP server for MarkItDown+mcp = MCPServer("markitdown")@mcp.tool()async def convert_to_markdown(uri: str) -> str:"""Convert a resource described by an http:, https:, file: or data: URI to markdown"""- return MarkItDown(enable_plugins=check_plugins_enabled()).convert_uri(uri).markdown+ converter = MarkItDown(enable_plugins=check_plugins_enabled())+ try:+ return converter.convert_uri(uri).markdown++ # SDK 2.x only exposes ToolError messages.+ except UnsupportedFormatException as exc:+ raise ToolError(str(exc)) from exc+ except requests.exceptions.HTTPError as exc:+ status = exc.response.status_code if exc.response is not None else "unknown"+ raise ToolError(+ f"Fetching the resource failed with HTTP status {status}."+ ) from exc+ except requests.exceptions.RequestException as exc:+ raise ToolError("Could not fetch the resource.") from exc+ except FileConversionException as exc:+ raise ToolError("File conversion failed.") from exc+ except OSError as exc:+ # str(exc) embeds the resolved path; errno's fixed strerror does not.+ detail = (+ os.strerror(exc.errno) if exc.errno else "the resource could not be read"+ )+ raise ToolError(f"Could not read the resource: {detail}.") from exc+ except ValueError as exc:+ # URI validation failures raised by convert_uri itself, which only+ # restate the URI the client supplied.+ raise ToolError(str(exc)) from excdef check_plugins_enabled() -> bool:@@ -36,49 +55,26 @@ def check_plugins_enabled() -> bool:)-def create_starlette_app(mcp_server: Server, *, debug: bool = False) -> Starlette:- sse = SseServerTransport("/messages/")- session_manager = StreamableHTTPSessionManager(- app=mcp_server,- event_store=None,+def create_starlette_app(+ mcp_server: MCPServer, *, host: str = "127.0.0.1", debug: bool = False+) -> Starlette:+ sse_app = mcp_server.sse_app(host=host)+ http_app = mcp_server.streamable_http_app(json_response=True,- stateless=True,+ stateless_http=True,+ host=host,)- async def handle_sse(request: Request) -> None:- async with sse.connect_sse(- request.scope,- request.receive,- request._send,- ) as (read_stream, write_stream):- await mcp_server.run(- read_stream,- write_stream,- mcp_server.create_initialization_options(),- )-- async def handle_streamable_http(- scope: Scope, receive: Receive, send: Send- ) -> None:- await session_manager.handle_request(scope, receive, send)-@contextlib.asynccontextmanagerasync def lifespan(app: Starlette) -> AsyncIterator[None]:- """Context manager for session manager."""- async with session_manager.run():- print("Application started with StreamableHTTP session manager!")- try:+ """Run both sub-apps' lifespans (the Streamable HTTP session manager)."""+ async with sse_app.router.lifespan_context(app):+ async with http_app.router.lifespan_context(app):yield- finally:- print("Application shutting down...")return Starlette(debug=debug,- routes=[- Route("/sse", endpoint=handle_sse),- Mount("/mcp", app=handle_streamable_http),- Mount("/messages/", app=sse.handle_post_message),- ],+ routes=[*sse_app.routes, *http_app.routes],lifespan=lifespan,)@@ -87,8 +83,6 @@ def create_starlette_app(mcp_server: Server, *, debug: bool = False) -> Starlettdef main():import argparse- mcp_server = mcp._mcp_server-parser = argparse.ArgumentParser(description="Run a MarkItDown MCP server")parser.add_argument(@@ -131,7 +125,7 @@ def main():"Only proceed if you understand the security implications.\n",file=sys.stderr,)- starlette_app = create_starlette_app(mcp_server, debug=True)+ starlette_app = create_starlette_app(mcp, host=host, debug=True)uvicorn.run(starlette_app,host=host,diff --git a/packages/markitdown-mcp/tests/test_http_transports.py b/packages/markitdown-mcp/tests/test_http_transports.pynew file mode 100644index 00000000..9f364515--- /dev/null+++ b/packages/markitdown-mcp/tests/test_http_transports.py@@ -0,0 +1,158 @@+"""Exercise the combined HTTP app without a listening socket or subprocess."""++import asyncio+import json+from contextlib import aclosing, asynccontextmanager+from urllib.parse import parse_qs, urlsplit++import httpx2 as httpx++from markitdown_mcp.__main__ import create_starlette_app, mcp+++BASE_URL = "http://127.0.0.1:3001"+INITIALIZE = {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": "2025-06-18",+ "capabilities": {},+ "clientInfo": {"name": "test", "version": "0"},+ },+}+INITIALIZED = {"jsonrpc": "2.0", "method": "notifications/initialized"}+CONVERT = {+ "jsonrpc": "2.0",+ "id": 2,+ "method": "tools/call",+ "params": {+ "name": "convert_to_markdown",+ "arguments": {"uri": "data:text/plain,Hello%20from%20HTTP"},+ },+}+++class _SSEBody(httpx.AsyncByteStream):+ def __init__(self, messages):+ self.messages = messages++ async def __aiter__(self):+ while True:+ message = await self.messages.get()+ assert message["type"] == "http.response.body"+ yield message.get("body", b"")+ if not message.get("more_body", False):+ return+++@asynccontextmanager+async def sse_connection(app):+ # ASGITransport buffers responses until completion, so drive the open SSE+ # request directly and let httpx parse its streamed response body.+ incoming = asyncio.Queue()+ outgoing = asyncio.Queue()+ await incoming.put({"type": "http.request", "body": b"", "more_body": False})+ scope = {+ "type": "http",+ "asgi": {"version": "3.0", "spec_version": "2.4"},+ "http_version": "1.1",+ "method": "GET",+ "scheme": "http",+ "path": "/sse",+ "raw_path": b"/sse",+ "root_path": "",+ "query_string": b"",+ "headers": [+ (b"host", b"127.0.0.1:3001"),+ (b"accept", b"text/event-stream"),+ ],+ "client": ("127.0.0.1", 1234),+ "server": ("127.0.0.1", 3001),+ }+ task = asyncio.create_task(app(scope, incoming.get, outgoing.put))+ try:+ start = await outgoing.get()+ assert start["type"] == "http.response.start"+ assert start["status"] == 200+ response = httpx.Response(+ start["status"],+ headers=start["headers"],+ stream=_SSEBody(outgoing),+ request=httpx.Request("GET", BASE_URL + "/sse"),+ )+ assert response.headers["content-type"].startswith("text/event-stream")+ async with aclosing(httpx.EventSource(response).__aiter__()) as events:+ yield events+ finally:+ await incoming.put({"type": "http.disconnect"})+ await asyncio.wait_for(task, timeout=5)+++def assert_conversion(response):+ assert response["id"] == CONVERT["id"]+ result = response["result"]+ assert result["isError"] is False+ assert result["content"][0]["text"] == "Hello from HTTP"+++def test_streamable_http_initializes_with_app_lifespan():+ async def exercise():+ app = create_starlette_app(mcp)+ async with app.router.lifespan_context(app):+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url=BASE_URL,+ headers={"accept": "application/json, text/event-stream"},+ ) as client:+ response = await client.post("/mcp", json=INITIALIZE)+ assert response.status_code == 200+ assert response.headers["content-type"].startswith("application/json")+ initialized = response.json()+ assert initialized["id"] == INITIALIZE["id"]+ assert initialized["result"]["serverInfo"]["name"] == "markitdown"+ assert "mcp-session-id" not in response.headers++ client.headers["mcp-protocol-version"] = initialized["result"][+ "protocolVersion"+ ]+ response = await client.post("/mcp", json=INITIALIZED)+ assert response.status_code == 202+ response = await client.post("/mcp", json=CONVERT)+ assert response.status_code == 200+ assert_conversion(response.json())++ asyncio.run(asyncio.wait_for(exercise(), timeout=15))+++def test_sse_session_uses_preserved_message_route():+ async def exercise():+ app = create_starlette_app(mcp)+ async with app.router.lifespan_context(app):+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app), base_url=BASE_URL+ ) as client:+ async with sse_connection(app) as events:+ endpoint = await anext(events)+ assert endpoint.event == "endpoint"+ url = urlsplit(endpoint.data)+ assert url.path == "/messages/"+ assert parse_qs(url.query)["session_id"]++ response = await client.post(endpoint.data, json=INITIALIZE)+ assert response.status_code == 202+ event = await anext(events)+ assert event.event == "message"+ initialized = json.loads(event.data)+ assert initialized["id"] == INITIALIZE["id"]+ assert initialized["result"]["serverInfo"]["name"] == "markitdown"++ response = await client.post(endpoint.data, json=INITIALIZED)+ assert response.status_code == 202+ response = await client.post(endpoint.data, json=CONVERT)+ assert response.status_code == 202+ event = await anext(events)+ assert event.event == "message"+ assert_conversion(json.loads(event.data))++ asyncio.run(asyncio.wait_for(exercise(), timeout=15))diff --git a/packages/markitdown-mcp/tests/test_stdio_protocols.py b/packages/markitdown-mcp/tests/test_stdio_protocols.pynew file mode 100644index 00000000..c69c4ed5--- /dev/null+++ b/packages/markitdown-mcp/tests/test_stdio_protocols.py@@ -0,0 +1,227 @@+#!/usr/bin/env python3 -m pytest+"""Drive the stdio server through both MCP handshake eras.++The server must answer clients that open with the legacy `initialize`+handshake as well as clients that open with the 2026-07-28 `server/discover`+request, since both are in use across MCP hosts.+"""++import json+import os+import subprocess+import sys+import tempfile+import threading+import time+from pathlib import Path++import pytest++MODERN_ENVELOPE = {+ "io.modelcontextprotocol/clientCapabilities": {},+ "io.modelcontextprotocol/clientInfo": {"name": "test", "version": "0"},+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",+}++EXPECTED_MARKDOWN = "# Hello\n\nA **markitdown** fixture."+++def fixture_uri():+ with tempfile.TemporaryDirectory() as tmpdir:+ path = os.path.join(tmpdir, "sample.md")+ with open(path, "w") as fh:+ fh.write(EXPECTED_MARKDOWN + "\n")+ yield Path(path).as_uri()+++def run_server(requests, expected_responses):+ """Feed newline-delimited requests to the stdio server, return the responses.++ Stdin is held open until the expected responses arrive: closing it early+ tears the server down before an in-flight request can be answered.+ """+ process = subprocess.Popen(+ [sys.executable, "-m", "markitdown_mcp"],+ stdin=subprocess.PIPE,+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ text=True,+ )+ responses = []+ try:+ for request in requests:+ process.stdin.write(json.dumps(request) + "\n")+ process.stdin.flush()++ reader = threading.Thread(+ target=lambda: [+ responses.append(json.loads(line))+ for line in process.stdout+ if line.strip()+ ],+ daemon=True,+ )+ reader.start()++ deadline = time.monotonic() + 60+ while len(responses) < expected_responses and time.monotonic() < deadline:+ time.sleep(0.05)+ finally:+ process.stdin.close()+ process.terminate()+ process.wait(timeout=10)+ return sorted(responses, key=lambda response: response["id"])+++def test_legacy_initialize_handshake(fixture_uri):+ """A client opening with `initialize` gets the pre-2026 protocol."""+ responses = run_server(+ [+ {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": "2025-06-18",+ "capabilities": {},+ "clientInfo": {"name": "test", "version": "0"},+ },+ },+ {"jsonrpc": "2.0", "method": "notifications/initialized"},+ {+ "jsonrpc": "2.0",+ "id": 2,+ "method": "tools/call",+ "params": {+ "name": "convert_to_markdown",+ "arguments": {"uri": fixture_uri},+ },+ },+ ],+ expected_responses=2,+ )++ assert responses[0]["result"]["serverInfo"]["name"] == "markitdown"+ call = responses[1]["result"]+ assert call["isError"] is False+ assert EXPECTED_MARKDOWN in call["content"][0]["text"]+++def test_modern_discover_handshake(fixture_uri):+ """A client opening with `server/discover` gets the 2026-07-28 protocol."""+ responses = run_server(+ [+ {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "server/discover",+ "params": {"_meta": MODERN_ENVELOPE},+ },+ {+ "jsonrpc": "2.0",+ "id": 2,+ "method": "tools/call",+ "params": {+ "name": "convert_to_markdown",+ "arguments": {"uri": fixture_uri},+ "_meta": MODERN_ENVELOPE,+ },+ },+ ],+ expected_responses=2,+ )++ discover = responses[0]["result"]+ assert "2026-07-28" in discover["supportedVersions"]+ call = responses[1]["result"]+ assert call["isError"] is False+ assert EXPECTED_MARKDOWN in call["content"][0]["text"]+++def test_unknown_method_does_not_kill_the_server(fixture_uri):+ """An unrecognized method is answered, and the session stays usable."""+ responses = run_server(+ [+ {"jsonrpc": "2.0", "id": 1, "method": "totally/bogus", "params": {}},+ {+ "jsonrpc": "2.0",+ "id": 2,+ "method": "initialize",+ "params": {+ "protocolVersion": "2025-06-18",+ "capabilities": {},+ "clientInfo": {"name": "test", "version": "0"},+ },+ },+ ],+ expected_responses=2,+ )++ assert "error" in responses[0]+ assert responses[1]["result"]["serverInfo"]["name"] == "markitdown"++[email protected]("modern", [False, True], ids=["legacy", "modern"])+def test_conversion_errors_are_reported(modern, tmp_path, fixture_uri):+ """Expected failures retain their diagnosis and leave the session usable."""+ if modern:+ requests = [+ {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "server/discover",+ "params": {"_meta": MODERN_ENVELOPE},+ }+ ]+ else:+ requests = [+ {+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": {+ "protocolVersion": "2025-06-18",+ "capabilities": {},+ "clientInfo": {"name": "test", "version": "0"},+ },+ },+ {"jsonrpc": "2.0", "method": "notifications/initialized"},+ ]++ failures = [+ # The resolved local path is deliberately withheld from the client; only+ # the errno's fixed strerror is returned.+ ((tmp_path / "missing.md").as_uri(), "No such file or directory"),+ ("ftp://example.com/sample.md", "Unsupported URI scheme: ftp"),+ ("data:text/plain", "Malformed data URI, missing ',' separator"),+ ]+ for request_id, uri in enumerate(+ [uri for uri, _ in failures] + [fixture_uri], start=2+ ):+ params = {"name": "convert_to_markdown", "arguments": {"uri": uri}}+ if modern:+ params["_meta"] = MODERN_ENVELOPE+ requests.append(+ {+ "jsonrpc": "2.0",+ "id": request_id,+ "method": "tools/call",+ "params": params,+ }+ )++ responses = run_server(requests, expected_responses=len(failures) + 2)+ assert len(responses) == len(failures) + 2+ for response, (_, diagnosis) in zip(responses[1:-1], failures):+ result = response["result"]+ assert result["isError"] is True+ assert diagnosis in result["content"][0]["text"]++ result = responses[-1]["result"]+ assert result["isError"] is False+ assert EXPECTED_MARKDOWN in result["content"][0]["text"]+++if __name__ == "__main__":+ sys.exit(pytest.main([__file__, "-v"]))diff --git a/packages/markitdown-mcp/tests/test_tool_errors.py b/packages/markitdown-mcp/tests/test_tool_errors.pynew file mode 100644index 00000000..751537da--- /dev/null+++ b/packages/markitdown-mcp/tests/test_tool_errors.py@@ -0,0 +1,223 @@+import asyncio+import errno+import os+from unittest.mock import Mock++import httpx2 as httpx+import pytest+import requests+from markitdown import (+ DocumentConverter,+ FileConversionException,+ MarkItDown,+ MarkItDownException,+ UnsupportedFormatException,+)+from mcp.server.mcpserver.exceptions import ToolError, UnexpectedToolError+from requests.exceptions import ConnectionError, HTTPError, Timeout++from markitdown_mcp import __main__ as server+++def call_convert(uri: str = "https://example.com/sample.pdf"):+ return asyncio.run(server.mcp.call_tool("convert_to_markdown", {"uri": uri}))+++def original_cause(exc):+ """The first non-ToolError in the __cause__ chain.++ Sanitized detail is withheld from the client but retained on the chain. The+ SDK re-wraps the tool's ToolError in one of its own, so walk past every+ ToolError rather than assuming a fixed depth.+ """+ while isinstance(exc, ToolError):+ exc = exc.__cause__+ return exc+++ "error",+ [+ UnsupportedFormatException("No converter supports this format."),+ ValueError(+ "Unsupported URI scheme: gopher. Supported schemes are: "+ "file:, data:, http:, https:"+ ),+ ],+)+def test_client_input_failures_reach_the_sdk(monkeypatch, error):+ """Diagnoses that only restate the client's own input are returned verbatim."""+ converter = Mock()+ converter.convert_uri.side_effect = error+ monkeypatch.setattr(server, "MarkItDown", Mock(return_value=converter))++ with pytest.raises(ToolError) as raised:+ call_convert()++ assert not isinstance(raised.value, UnexpectedToolError)+ assert str(error) in str(raised.value)+++def test_http_status_is_returned_without_transport_details(monkeypatch):+ response = requests.Response()+ response.status_code = 404+ error = HTTPError(+ "404 Client Error: Not Found for url: https://internal.corp/sample.pdf",+ response=response,+ )+ converter = Mock()+ converter.convert_uri.side_effect = error+ monkeypatch.setattr(server, "MarkItDown", Mock(return_value=converter))++ with pytest.raises(ToolError) as raised:+ call_convert()++ assert not isinstance(raised.value, UnexpectedToolError)+ assert "HTTP status 404" in str(raised.value)+ assert "internal.corp" not in str(raised.value)+ assert original_cause(raised.value) is error+++ "error",+ [+ # requests exceptions subclass OSError, and their messages describe the+ # server's own network position rather than the client's request.+ ConnectionError(+ "HTTPSConnectionPool(host='10.0.0.5', port=443): Max retries exceeded "+ "(Caused by ProxyError('Unable to connect to proxy', "+ "NameResolutionError(\"Failed to resolve 'proxy.internal.corp'\")))"+ ),+ Timeout(+ "HTTPSConnectionPool(host='10.0.0.5', port=443): Read timed out. "+ "(proxy.internal.corp)"+ ),+ ],+)+def test_network_failure_details_remain_private(monkeypatch, error):+ converter = Mock()+ converter.convert_uri.side_effect = error+ monkeypatch.setattr(server, "MarkItDown", Mock(return_value=converter))++ with pytest.raises(ToolError) as raised:+ call_convert()++ message = str(raised.value)+ assert not isinstance(raised.value, UnexpectedToolError)+ assert "Could not fetch the resource" in message+ assert "10.0.0.5" not in message+ assert "proxy.internal.corp" not in message+ assert "proxy.internal.corp" in str(original_cause(raised.value))+++def test_local_read_failure_reports_errno_without_the_path(monkeypatch):+ error = PermissionError(+ errno.EACCES, os.strerror(errno.EACCES), "/srv/private/sample.pdf"+ )+ converter = Mock()+ converter.convert_uri.side_effect = error+ monkeypatch.setattr(server, "MarkItDown", Mock(return_value=converter))++ with pytest.raises(ToolError) as raised:+ call_convert("file:///srv/private/sample.pdf")++ message = str(raised.value)+ assert not isinstance(raised.value, UnexpectedToolError)+ assert os.strerror(errno.EACCES) in message+ assert "/srv/private/sample.pdf" not in message+ assert "/srv/private/sample.pdf" in str(original_cause(raised.value))++[email protected]("error_type", [RuntimeError, MarkItDownException])+def test_unexpected_failure_details_remain_private(monkeypatch, error_type):+ converter = Mock()+ converter.convert_uri.side_effect = error_type("internal implementation detail")+ monkeypatch.setattr(server, "MarkItDown", Mock(return_value=converter))++ with pytest.raises(UnexpectedToolError) as raised:+ call_convert("file:///sample.pdf")++ assert "internal implementation detail" not in str(raised.value)+++def crashing_markitdown(error_type, private_detail):+ """A MarkItDown whose sole converter raises, to exercise the real+ convert_uri/_convert pipeline that aggregates converter exceptions into+ FileConversionException."""++ class CrashingConverter(DocumentConverter):+ def accepts(self, file_stream, stream_info, **kwargs):+ return True++ def convert(self, file_stream, stream_info, **kwargs):+ raise error_type(private_detail)++ converter = MarkItDown(enable_builtins=False, enable_plugins=False)+ converter.register_converter(CrashingConverter())+ return converter++[email protected]("error_type", [RuntimeError, ValueError, OSError])+def test_wrapped_converter_crash_retains_the_cause(monkeypatch, error_type):+ private_detail = "private converter implementation detail"+ # Replace only construction, so the real pipeline does the aggregation.+ monkeypatch.setattr(+ server,+ "MarkItDown",+ Mock(return_value=crashing_markitdown(error_type, private_detail)),+ )++ with pytest.raises(ToolError) as raised:+ call_convert("data:text/plain,example")++ assert "File conversion failed" in str(raised.value)+ assert private_detail not in str(raised.value)++ cause = original_cause(raised.value)+ assert isinstance(cause, FileConversionException)+ assert cause.attempts+ for attempt in cause.attempts:+ assert isinstance(attempt.exc_info[1], error_type)+ assert str(attempt.exc_info[1]) == private_detail+ assert attempt.exc_info[2] is not None++[email protected]("error_type", [RuntimeError, ValueError, OSError])+def test_wrapped_converter_crash_remains_private_over_http(monkeypatch, error_type):+ private_detail = "private converter implementation detail"+ monkeypatch.setattr(+ server,+ "MarkItDown",+ Mock(return_value=crashing_markitdown(error_type, private_detail)),+ )++ async def call_tool():+ app = server.create_starlette_app(server.mcp)+ async with app.router.lifespan_context(app):+ async with httpx.AsyncClient(+ transport=httpx.ASGITransport(app=app),+ base_url="http://127.0.0.1:3001",+ headers={"accept": "application/json, text/event-stream"},+ ) as client:+ return await client.post(+ "/mcp",+ json={+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": {+ "name": "convert_to_markdown",+ "arguments": {"uri": "data:text/plain,example"},+ },+ },+ )++ response = asyncio.run(asyncio.wait_for(call_tool(), timeout=15))++ assert response.status_code == 200+ result = response.json()["result"]+ assert result["isError"] is True+ assert "File conversion failed" in result["content"][0]["text"]+ assert private_detail not in response.text+ assert error_type.__name__ not in response.text+ assert "CrashingConverter" not in response.text