|
| 1 | +from aiodocker import Docker |
| 2 | +from contextlib import asynccontextmanager |
| 3 | +import anyio |
| 4 | +import anyio.lowlevel |
| 5 | +from anyio.streams.memory import MemoryObjectReceiveStream, MemoryObjectSendStream |
| 6 | +from loguru import logger |
| 7 | +from config.final import DockerMCPServer |
| 8 | +from mcp import types |
| 9 | + |
| 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 | + docker = Docker() |
| 27 | + |
| 28 | + try: |
| 29 | + # Pull the image if not available |
| 30 | + await docker.images.pull(server.image) |
| 31 | + |
| 32 | + # Create the container |
| 33 | + container = await docker.containers.create({ |
| 34 | + "Image": server.image, |
| 35 | + "Args": server.args, |
| 36 | + "OpenStdin": True, |
| 37 | + "AttachStdout": True, |
| 38 | + "AttachStderr": True, |
| 39 | + "Tty": False, |
| 40 | + "HostConfig": {"AutoRemove": True}, |
| 41 | + }) |
| 42 | + |
| 43 | + await container.start() |
| 44 | + logger.debug(f"Started Docker container {container.id}") |
| 45 | + |
| 46 | + # Attach to the container's input/output streams |
| 47 | + attach_result = container.attach(stdout=True, stdin=True) |
| 48 | + |
| 49 | + async def read_from_stdout(): |
| 50 | + try: |
| 51 | + async with read_stream_writer: |
| 52 | + buffer = "" |
| 53 | + while True: |
| 54 | + msg = await attach_result.read_out() |
| 55 | + if msg is None: |
| 56 | + continue |
| 57 | + chunk = msg.data |
| 58 | + if isinstance(chunk, bytes): |
| 59 | + chunk = chunk.decode("utf-8") |
| 60 | + lines = (buffer + chunk).split("\n") |
| 61 | + buffer = lines.pop() |
| 62 | + |
| 63 | + for line in lines: |
| 64 | + try: |
| 65 | + json_message = types.JSONRPCMessage.model_validate_json(line) |
| 66 | + await read_stream_writer.send(json_message) |
| 67 | + except Exception as exc: |
| 68 | + await read_stream_writer.send(exc) |
| 69 | + except anyio.ClosedResourceError: |
| 70 | + await anyio.lowlevel.checkpoint() |
| 71 | + |
| 72 | + async def write_to_stdin(): |
| 73 | + try: |
| 74 | + async with write_stream_reader: |
| 75 | + async for message in write_stream_reader: |
| 76 | + json = message.model_dump_json(by_alias=True, exclude_none=True) |
| 77 | + await attach_result.write_in(json.encode("utf-8") + b"\n") |
| 78 | + except anyio.ClosedResourceError: |
| 79 | + await anyio.lowlevel.checkpoint() |
| 80 | + |
| 81 | + try: |
| 82 | + async with anyio.create_task_group() as tg: |
| 83 | + tg.start_soon(read_from_stdout) |
| 84 | + tg.start_soon(write_to_stdin) |
| 85 | + yield read_stream, write_stream |
| 86 | + finally: |
| 87 | + await container.stop() |
| 88 | + await container.delete() |
| 89 | + |
| 90 | + except Exception as e: |
| 91 | + logger.error(f"Error in docker client: {e}") |
| 92 | + finally: |
| 93 | + await docker.close() |
| 94 | + logger.debug("Docker client closed.") |
0 commit comments