Skip to content

mcp_socket_bridge

mcp_socket_bridge

Multiplexed Unix-socket bridge for stdio MCP servers.

The bridge owns one upstream stdio MCP server process and exposes a Unix socket for multiple MCP clients. Client request IDs are rewritten to bridge-unique upstream IDs, then restored on the way back to the originating client.

Classes

McpSocketBridge

McpSocketBridge(*, name, command, socket_path, upstream_framing='newline')

Expose one stdio MCP server process through a multiplexed Unix socket.

Source code in src/marianne/daemon/mcp_socket_bridge.py
def __init__(
    self,
    *,
    name: str,
    command: str,
    socket_path: Path,
    upstream_framing: McpFraming = "newline",
) -> None:
    self.name = name
    self.command = command
    self.socket_path = socket_path
    self.upstream_framing = upstream_framing

    self.process: asyncio.subprocess.Process | None = None
    self._server: asyncio.AbstractServer | None = None
    self._socket_owner = OwnedUnixSocket(socket_path)
    self._clients: set[_Client] = set()
    self._client_tasks: set[asyncio.Task[None]] = set()
    self._stop_task: asyncio.Task[None] | None = None
    self._pending: dict[int, _PendingClientResponse | asyncio.Future[dict[str, Any]]] = {}
    self._request_id = 0
    self._client_id = 0
    self._write_lock = asyncio.Lock()
    self._upstream_reader_task: asyncio.Task[None] | None = None
    self._stderr_task: asyncio.Task[None] | None = None
    self._initialize_result: dict[str, Any] = {}
    self._stopping = False
    self._upstream_reader_stopped = False
Attributes
is_running property
is_running

Whether the upstream process, its reader and the socket server are all alive.

A live process whose stdout reader has stopped cannot answer anyone (GH #520): every forwarded request would wait forever. Such a bridge reports not running so the pool monitor restarts it under its policy.

Methods:
start async
start()

Start the upstream process, initialize it, and bind the socket.

Source code in src/marianne/daemon/mcp_socket_bridge.py
async def start(self) -> None:
    """Start the upstream process, initialize it, and bind the socket."""
    if self.is_running:
        return

    if self._stop_task is not None and not self._stop_task.done():
        await self.stop()
    self._stop_task = None
    self._stopping = False
    self._upstream_reader_stopped = False
    cmd_parts = shlex.split(self.command)
    if not cmd_parts:
        raise ValueError("MCP server command must not be empty")

    try:
        await self._socket_owner.prepare()
        process = await asyncio.create_subprocess_exec(
            cmd_parts[0],
            *cmd_parts[1:],
            stdin=asyncio.subprocess.PIPE,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
            limit=_READ_CHUNK_LIMIT,
        )
        self.process = process
        if process.stdin is None or process.stdout is None:
            raise RuntimeError(f"MCP server {self.name!r} did not expose stdio pipes")

        self._upstream_reader_task = asyncio.create_task(
            self._read_upstream_loop(),
            name=f"mcp-bridge-{self.name}-upstream",
        )
        if process.stderr is not None:
            self._stderr_task = asyncio.create_task(
                self._drain_stderr(process.stderr),
                name=f"mcp-bridge-{self.name}-stderr",
            )

        self._initialize_result = await self._initialize_upstream()
        # Own the server before its cancellable listener-registration yield.
        self._server = await self._socket_owner.start(self._handle_client, start_serving=False)
        await self._server.start_serving()
    except BaseException:
        await self.stop()
        raise

    _logger.info(
        "mcp_bridge.started",
        extra={
            "server": self.name,
            "pid": process.pid,
            "socket": str(self.socket_path),
        },
    )
stop async
stop()

Finish owned cleanup before propagating caller cancellation.

Source code in src/marianne/daemon/mcp_socket_bridge.py
async def stop(self) -> None:
    """Finish owned cleanup before propagating caller cancellation."""
    self._stopping = True
    if self._stop_task is None:
        self._stop_task = asyncio.create_task(
            self._stop_resources(),
            name=f"mcp-bridge-{self.name}-stop",
        )
    cleanup = self._stop_task
    cancelled = False
    # The pool can discard its bridge handle when stop is canceled. Keep
    # cleanup strongly owned and shielded, and do not return until the
    # upstream has been reaped and our socket lifetime lock released.
    while not cleanup.done():
        try:
            await asyncio.shield(cleanup)
        except asyncio.CancelledError:
            cancelled = True
    cleanup.result()
    if cancelled:
        raise asyncio.CancelledError

Functions: