The musician-side memory shim: a stdio MCP server in front of one gateway socket.
A harness launches python -m marianne.memory.shim --socket <path>
[--memory-budget-seconds <float>]. The shim speaks MCP over stdio
(JSON-RPC 2.0, one message per line; standard library only) and forwards each
of the six memory tools over the socket with
:class:marianne.memory.gateway.client.MemoryGatewayClient.
It carries no identity. The socket is the session: the shim never sees, sends
or advertises a session id, principal, scope, grant or credential, and its tool
schemas list only each call's own arguments. Every call's timeout is clamped to
the memory budget so the shim never outlives the gateway's own outer budget.
Failure policy: a gateway refusal (errors/1) is an MCP tool result with
isError: true carrying code, subtype, message and remedy; a protocol fault
(bad JSON, unknown method, bad params, oversized line) is a JSON-RPC error.
A socket that is gone at startup ends the process with a non-zero status and one
stderr line; one that disappears later yields a typed tool error per call.
Classes
MemoryShim
MemoryShim(socket_path, budget_seconds=DEFAULT_BUDGET_SECONDS)
Handles MCP messages; one short-lived socket connection per tool call.
Source code in src/marianne/memory/shim.py
| def __init__(self, socket_path: Path | str, budget_seconds: float = DEFAULT_BUDGET_SECONDS):
if not math.isfinite(budget_seconds) or budget_seconds <= 0:
raise ValueError("memory budget must be a positive, finite number of seconds")
self._path = str(socket_path)
self._budget = float(budget_seconds)
|
Methods:
check_socket
Raise a typed unreachable error unless the gateway socket accepts a connection.
Source code in src/marianne/memory/shim.py
| def check_socket(self) -> None:
"""Raise a typed unreachable error unless the gateway socket accepts a connection."""
MemoryGatewayClient(self._path, timeout=self._budget).close()
|
handle_message
One decoded JSON-RPC message in, one response (or None for a notification).
Source code in src/marianne/memory/shim.py
| def handle_message(self, msg: Any) -> dict[str, Any] | None:
"""One decoded JSON-RPC message in, one response (or ``None`` for a notification)."""
if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
return self._fail(None, INVALID_REQUEST, "not a JSON-RPC 2.0 request object")
method = msg.get("method")
has_id = "id" in msg
msg_id = msg.get("id")
if has_id and (isinstance(msg_id, bool) or not isinstance(msg_id, (str, int))):
return self._fail(None, INVALID_REQUEST, "id must be a string or an integer")
if not isinstance(method, str):
if has_id and ("result" in msg or "error" in msg):
return None # a response to something we never asked; ignore
return self._fail(msg_id if has_id else None, INVALID_REQUEST, "method is required")
params = msg.get("params", {})
if not isinstance(params, dict):
return self._fail(
msg_id if has_id else None, INVALID_PARAMS, "params must be an object",
)
if not has_id:
return None # notifications (notifications/initialized, cancelled, ...) get no reply
try:
return {"jsonrpc": "2.0", "id": msg_id, "result": self._dispatch(method, params)}
except _RpcError as exc:
return self._fail(msg_id, exc.code, exc.message)
|
Functions:
serve
serve(shim, stdin, stdout, *, max_line_bytes=MAX_LINE_BYTES)
Run the stdio loop until stdin reaches EOF.
Source code in src/marianne/memory/shim.py
| def serve(
shim: MemoryShim, stdin: BinaryIO, stdout: BinaryIO, *, max_line_bytes: int = MAX_LINE_BYTES,
) -> None:
"""Run the stdio loop until stdin reaches EOF."""
def send(obj: dict[str, Any]) -> None:
stdout.write((json.dumps(obj, ensure_ascii=False) + "\n").encode("utf-8"))
stdout.flush()
while True:
line, too_long = _read_line(stdin, max_line_bytes)
if line is None:
return
if too_long:
send(MemoryShim._fail(
None, INVALID_REQUEST, f"line exceeds the {max_line_bytes} byte limit",
))
continue
if not line.strip():
continue
try:
msg = json.loads(line)
except (ValueError, RecursionError):
send(MemoryShim._fail(None, PARSE_ERROR, "invalid JSON"))
continue
if isinstance(msg, list):
send(MemoryShim._fail(None, INVALID_REQUEST, "batches are not supported"))
continue
reply = shim.handle_message(msg)
if reply is not None:
send(reply)
|