Skip to content

Fix process termination in stdio client #496

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ dependencies = [
"python-multipart>=0.0.9",
"sse-starlette>=1.6.1",
"pydantic-settings>=2.5.2",
"psutil>=7.0.0",
"uvicorn>=0.23.1; sys_platform != 'emscripten'",
]

Expand Down
39 changes: 33 additions & 6 deletions src/mcp/client/stdio/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import os
import sys
from contextlib import asynccontextmanager
from contextlib import asynccontextmanager, suppress
from pathlib import Path
from typing import Literal, TextIO

import anyio
import anyio.lowlevel
from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream
import psutil
from anyio.abc import Process
from anyio.streams.memory import (
MemoryObjectReceiveStream,
MemoryObjectSendStream,
)
from anyio.streams.text import TextReceiveStream
from pydantic import BaseModel, Field

Expand Down Expand Up @@ -173,10 +178,7 @@ async def stdin_writer():
yield read_stream, write_stream
finally:
# Clean up process to prevent any dangling orphaned processes
if sys.platform == "win32":
await terminate_windows_process(process)
else:
process.terminate()
await _terminate_process(process)


def _get_executable_command(command: str) -> str:
Expand Down Expand Up @@ -214,3 +216,28 @@ async def _create_platform_compatible_process(
)

return process


async def _terminate_process(process: Process):
"""
Terminate the process and its children.

Note: On Windows, `process.terminate()` calls the Win32 `TerminateProcess` API,
which only terminates the specified process. Any child
processes remain running, which can lead to unclosed resources and may cause the
parent process to hang during shutdown. This function uses `psutil` to recursively
terminate the full process tree, ensuring a cleaner and more reliable shutdown.

Args:
process: The AnyIO process to terminate
"""
with suppress(psutil.NoSuchProcess):
proc = psutil.Process(process.pid)
children = proc.children(recursive=True)
for child in children:
child.kill()
with suppress(ProcessLookupError):
if sys.platform == "win32":
await terminate_windows_process(process)
else:
process.terminate()
Loading
Loading