|
| 1 | +import docker.client |
| 2 | +from contextlib import asynccontextmanager |
| 3 | +import anyio |
| 4 | +import anyio.lowlevel |
| 5 | +import anyio.to_thread |
| 6 | +from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream |
| 7 | +from loguru import logger |
| 8 | +from config.final import DockerMCPServer |
| 9 | +from mcp import types |
| 10 | + |
| 11 | +@asynccontextmanager |
| 12 | +async def docker_client(server: DockerMCPServer): |
| 13 | + """ |
| 14 | + Client transport for Docker: this will connect to a server by |
| 15 | + running a Docker container and communicating with it over its stdin/stdout. |
| 16 | + """ |
| 17 | + read_stream: MemoryObjectReceiveStream[types.JSONRPCMessage | Exception] |
| 18 | + read_stream_writer: MemoryObjectSendStream[types.JSONRPCMessage | Exception] |
| 19 | + |
| 20 | + write_stream: MemoryObjectSendStream[types.JSONRPCMessage] |
| 21 | + write_stream_reader: MemoryObjectReceiveStream[types.JSONRPCMessage] |
| 22 | + |
| 23 | + read_stream_writer, read_stream = anyio.create_memory_object_stream(0) |
| 24 | + write_stream, write_stream_reader = anyio.create_memory_object_stream(0) |
| 25 | + |
| 26 | + client = docker.client.from_env() |
| 27 | + container = client.containers.run( |
| 28 | + image=server.image, |
| 29 | + name=server.container_name if server.container_name else None, |
| 30 | + command=server.args if server.args else None, |
| 31 | + environment=server.env if isinstance(server.env, (dict, list)) else {}, |
| 32 | + detach=True, |
| 33 | + stdin_open=True, |
| 34 | + stdout=True, |
| 35 | + stderr=True, |
| 36 | + tty=False, |
| 37 | + ) |
| 38 | + |
| 39 | + logger.debug(f"made instance of docker client for {container.name}") |
| 40 | + |
| 41 | + # Attach to container's input/output streams |
| 42 | + attach_socket = container.attach_socket(params={"stdin": 1, "stdout": 1, "stderr": 1, "stream": 1}) |
| 43 | + attach_socket._sock.setblocking(False) |
| 44 | + |
| 45 | + async def read_from_stdout(): |
| 46 | + try: |
| 47 | + async with read_stream_writer: |
| 48 | + buffer = "" |
| 49 | + while True: |
| 50 | + chunk = await anyio.to_thread.run_sync(lambda: attach_socket._sock.recv(1024)) |
| 51 | + if not chunk: |
| 52 | + break |
| 53 | + |
| 54 | + chunk = chunk.decode("utf-8") |
| 55 | + lines = (buffer + chunk).split("\n") |
| 56 | + buffer = lines.pop() |
| 57 | + |
| 58 | + for line in lines: |
| 59 | + try: |
| 60 | + message = types.JSONRPCMessage.model_validate_json(line) |
| 61 | + except Exception as exc: |
| 62 | + await read_stream_writer.send(exc) |
| 63 | + continue |
| 64 | + |
| 65 | + await read_stream_writer.send(message) |
| 66 | + except anyio.ClosedResourceError: |
| 67 | + await anyio.lowlevel.checkpoint() |
| 68 | + |
| 69 | + async def write_to_stdin(): |
| 70 | + try: |
| 71 | + async with write_stream_reader: |
| 72 | + async for message in write_stream_reader: |
| 73 | + json = message.model_dump_json(by_alias=True, exclude_none=True) |
| 74 | + await anyio.to_thread.run_sync(lambda: attach_socket._sock.sendall((json + "\n").encode("utf-8"))) |
| 75 | + except anyio.ClosedResourceError: |
| 76 | + await anyio.lowlevel.checkpoint() |
| 77 | + |
| 78 | + try: |
| 79 | + async with anyio.create_task_group() as tg: |
| 80 | + tg.start_soon(read_from_stdout) |
| 81 | + tg.start_soon(write_to_stdin) |
| 82 | + yield read_stream, write_stream |
| 83 | + except Exception as e: |
| 84 | + logger.error(f"Error in docker client: {e}") |
| 85 | + finally: |
| 86 | + attach_socket._sock.close() |
| 87 | + # Do not stop or remove the container |
| 88 | + logger.debug(f"Container {container.name} remains running.") |
0 commit comments