Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 12 additions & 7 deletions src/mcp/server/mcpserver/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,13 +291,18 @@ def run(
if transport not in TRANSPORTS.__args__: # type: ignore # pragma: no cover
raise ValueError(f"Unknown transport: {transport}")

match transport:
case "stdio":
anyio.run(self.run_stdio_async)
case "sse": # pragma: no cover
anyio.run(lambda: self.run_sse_async(**kwargs))
case "streamable-http": # pragma: no cover
anyio.run(lambda: self.run_streamable_http_async(**kwargs))
try:
match transport:
case "stdio":
anyio.run(self.run_stdio_async)
case "sse": # pragma: no cover
anyio.run(lambda: self.run_sse_async(**kwargs))
case "streamable-http": # pragma: no cover
anyio.run(lambda: self.run_streamable_http_async(**kwargs))
except KeyboardInterrupt:
# Ctrl+C should exit cleanly without a traceback when running
# a server from the terminal (e.g. stdio transport).
pass

async def _handle_list_tools(
self, ctx: ServerRequestContext[LifespanResultT], params: PaginatedRequestParams | None
Expand Down
17 changes: 17 additions & 0 deletions tests/server/test_stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,3 +169,20 @@ async def lifespan(server: MCPServer) -> AsyncIterator[None]:
assert events == ["setup", "cleanup"]
response = jsonrpc_message_adapter.validate_json(captured.getvalue().decode().strip())
assert response == JSONRPCResponse(jsonrpc="2.0", id=1, result={})


def test_mcpserver_run_catches_keyboard_interrupt(monkeypatch: pytest.MonkeyPatch) -> None:
"""Ctrl+C during `run()` should exit cleanly without a traceback.

Regression test for #2663: when running a stdio server from the terminal,
KeyboardInterrupt (Ctrl+C) should not produce a multi-frame traceback
through anyio.run() → asyncio.runners.
"""

def mock_anyio_run(*args: object, **kwargs: object) -> None:
raise KeyboardInterrupt()

monkeypatch.setattr(anyio, "run", mock_anyio_run)

# Should not raise — KeyboardInterrupt is caught inside run()
MCPServer(name="KeyboardInterruptServer").run("stdio")