"""A guest's mailbox and pet store, and its methods as an MCP server. The methods follow Endo's EndoGuest (listMessages, request, resolve, lookup, ...), restricted to data: arguments are pet names, strings, and message numbers, and references stay here, in the pet store. A guest never holds one; it moves them between messages and names. As in toybox's wallet, it may `call` a named reference's methods, and propose code to its host with `define`. >>> host = HostSide(on_request=lambda description: Ref('Pen')) >>> guest = Mailbox(host) >>> host.send(guest, ['Hello. Please ask me for a pen.'], [], []) >>> [m['strings'] for m in guest.listMessages()] [['Hello. Please ask me for a pen.']] >>> guest.request('HOST', 'a pen', 'pen') {'interface': 'Pen'} >>> guest.list() ['HOST', 'pen'] >>> guest.reply(0, ['Thanks for the ', '!'], ['it'], ['pen']) >>> host.inbox[-1]['strings'], host.inbox[-1]['names'] (['Thanks for the ', '!'], ['it']) >>> host.received['it'] Ref(interface='Pen') Calling a WebApp, by name; it reaches only within its URL: >>> fetch = lambda url, method, body: (200, ('fetched ' + url).encode()) >>> host = HostSide(on_request=lambda d: WebApp(fetch, 'https://registry.npmjs.org/')) >>> guest = Mailbox(host) >>> guest.request('HOST', 'https://registry.npmjs.org/', 'npm') {'interface': 'WebApp'} >>> guest.call('npm', 'pathjoin', ['ms'], 'ms') {'@name': 'ms', 'interface': 'WebApp'} >>> guest.call('ms', 'get') 'fetched https://registry.npmjs.org/ms' >>> guest.call('npm', 'pathjoin', ['https://elsewhere.example/']) Traceback (most recent call last): ... ValueError: pathjoin: https://elsewhere.example/ is not within https://registry.npmjs.org/ >>> guest.define({'main.js': 'export const buildRootObject = () => ({});'}, ... {'site': {'label': 'a WebApp for the site'}}) >>> host.definitions[0]['slots'] {'site': {'label': 'a WebApp for the site'}} """ import base64 import json import logging import re import threading from dataclasses import dataclass, field from urllib.parse import urlencode, urljoin, urlsplit @dataclass(frozen=True) class Ref: """A reference, as the pet store holds it: never sent to the guest.""" interface: str def describe(value): """What the guest may see of a stored value: data as is, a Ref by its interface. >>> describe(Ref('Counter')) {'interface': 'Counter'} >>> describe(3) 3 """ return {"interface": value.interface} if is_ref(value) else value def is_ref(value): return hasattr(value, "interface") class WebApp: """Toybox's WebApp: an attenuated handle to one URL. Narrow with pathjoin and query, then fire with get or post. getBase64 is this host's addition, for bytes: toybox's fetch device answers text.""" interface = "WebApp" METHODS = ("pathjoin", "query", "get", "getBase64", "post") def __init__(self, fetch, url): self._fetch, self._url = fetch, url def pathjoin(self, ref): there, here = urlsplit(urljoin(self._url, ref)), urlsplit(self._url) if (there.scheme, there.netloc) != (here.scheme, here.netloc) or not ( there.path.startswith(here.path)): raise ValueError(f"pathjoin: {ref} is not within {self._url}") return WebApp(self._fetch, there.geturl()) def query(self, params): joiner = "&" if urlsplit(self._url).query else "?" return WebApp(self._fetch, self._url + joiner + urlencode(params)) def _send(self, method, body=None): status, data = self._fetch(self._url, method, body) if status >= 400: raise ValueError(f"{status} on {self._url}: {data[:200]!r}") return data def get(self): return self._send("GET").decode("utf-8", errors="replace") def getBase64(self): return base64.b64encode(self._send("GET")).decode("ascii") def post(self, body): return self._send("POST", body.encode()).decode("utf-8", errors="replace") SLOT = re.compile(r"^[A-Za-z_$][\w$]*$") @dataclass class HostSide: """The guest's host: it sends to the guest, answers its requests, and reads its mail.""" on_request: object # description -> value inbox: list = field(default_factory=list) received: dict = field(default_factory=dict) definitions: list = field(default_factory=list) def send(self, guest, strings, edge_names, values): guest._deliver("package", "HOST", strings=strings, names=edge_names, values=values) def _receive(self, message, values): self.inbox.append(message) self.received.update(zip(message.get("names", []), values)) class Mailbox: """One guest's powers. Method names are EndoGuest's.""" def __init__(self, host): self._host = host self._lock = threading.Lock() self._pets = {"HOST": Ref("Host")} self._messages = [] # (record, values) def _deliver(self, type_, sender, values=(), **record): with self._lock: number = len(self._messages) self._messages.append(( {"number": number, "type": type_, "from": sender, **record}, list(values), )) def _message(self, number): for record, values in self._messages: if record["number"] == number: return record, values raise KeyError(f"no message {number}") def _to_host(self, to): if to != "HOST": raise KeyError(f"no recipient {to}; this guest can write only to HOST") def listMessages(self): with self._lock: return [dict(record) for record, _ in self._messages] def list(self): return sorted(self._pets) def lookup(self, petName): return describe(self._pets[petName]) def request(self, to, description, responseName=None): self._to_host(to) value = self._host.on_request(description) if responseName: self._pets[responseName] = value return describe(value) def send(self, to, strings, edgeNames, petNames): self._to_host(to) values = [self._pets[n] for n in petNames] self._host._receive( {"type": "package", "from": "guest", "strings": strings, "names": edgeNames}, values) def reply(self, messageNumber, strings, edgeNames, petNames): record, _ = self._message(messageNumber) self.send(record["from"], strings, edgeNames, petNames) self._host.inbox[-1]["replyTo"] = messageNumber def adopt(self, messageNumber, edgeName, petName): record, values = self._message(messageNumber) self._pets[petName] = values[record["names"].index(edgeName)] def call(self, target, method, args=None, saveAs=None): """Call `target`'s `method`; {"@name": n} in args is the reference n names.""" obj = self._pets[target] methods = getattr(obj, "METHODS", ()) if method not in methods: raise KeyError(f"{target} ({describe(obj)}) has no method {method}; " f"it has {list(methods)}") args = [self._pets[a["@name"]] if isinstance(a, dict) and set(a) == {"@name"} else a for a in (args or [])] answer = getattr(obj, method)(*args) if not is_ref(answer): return answer if not saveAs: raise ValueError(f"{method} answers a reference: give saveAs, a name to keep it under") self._pets[saveAs] = answer return {"@name": saveAs, **describe(answer)} def define(self, modules, slots): """Propose to the host a vat of `modules`, its params named by `slots`.""" for name in slots: if not SLOT.match(name): raise ValueError(f"define: not a slot name: {json.dumps(name)}") self._host.definitions.append({"modules": modules, "slots": slots}) def dismiss(self, messageNumber): with self._lock: self._messages = [ (r, v) for r, v in self._messages if r["number"] != messageNumber] def _schema(props, required=None): return {"type": "object", "properties": props, "required": list(props) if required is None else required} STR, INT = {"type": "string"}, {"type": "integer"} STRS = {"type": "array", "items": STR} TOOLS = { "listMessages": ("The messages in this guest's inbox.", _schema({})), "list": ("This guest's pet names.", _schema({})), "lookup": ("What a pet name refers to: data, or an object's interface.", _schema({"petName": STR})), "request": ("Ask a recipient for something; the answer is stored under responseName.", _schema({"to": STR, "description": STR, "responseName": STR}, ["to", "description"])), "send": ("Send a message: strings, with the named references between them.", _schema({"to": STR, "strings": STRS, "edgeNames": STRS, "petNames": STRS})), "reply": ("Reply to a message, as send does.", _schema({"messageNumber": INT, "strings": STRS, "edgeNames": STRS, "petNames": STRS})), "adopt": ("Keep a reference from a message under a pet name.", _schema({"messageNumber": INT, "edgeName": STR, "petName": STR})), "dismiss": ("Remove a message from the inbox.", _schema({"messageNumber": INT})), "call": ("Call a method of the object a pet name refers to. In args, " '{"@name": n} passes the reference n names. A reference answered ' "is kept under saveAs. See the endo://guide resource.", _schema({"target": STR, "method": STR, "args": {"type": "array"}, "saveAs": STR}, ["target", "method"])), "define": ("Propose code to your host: a vat's modules (path to source), and its " "params by slot name, each with a label saying what it's for. The host " "reads it and may endow it. See the endo://guide resource.", _schema({"modules": {"type": "object", "additionalProperties": STR}, "slots": {"type": "object", "additionalProperties": { "type": "object", "properties": {"label": STR}, "required": ["label"]}}})), } def handle_rpc(mailbox, msg, resources=None): """One MCP JSON-RPC message in; the reply out, or None for a notification. >>> box = Mailbox(HostSide(on_request=lambda d: 1)) >>> handle_rpc(box, {'jsonrpc': '2.0', 'id': 1, 'method': 'tools/call', ... 'params': {'name': 'list', 'arguments': {}}})['result']['content'][0]['text'] '["HOST"]' >>> handle_rpc(box, {'jsonrpc': '2.0', 'method': 'notifications/initialized'}) """ method, params = msg.get("method"), msg.get("params") or {} if "id" not in msg: return None reply = {"jsonrpc": "2.0", "id": msg["id"]} if method == "initialize": reply["result"] = { "protocolVersion": params.get("protocolVersion", "2025-06-18"), "capabilities": {"tools": {}, **({"resources": {}} if resources else {})}, "serverInfo": {"name": "fake-endo-host", "version": "0"}, } elif method == "ping": reply["result"] = {} elif method == "tools/list": reply["result"] = {"tools": [ {"name": name, "description": desc, "inputSchema": schema} for name, (desc, schema) in TOOLS.items()]} elif method == "resources/list" and resources: reply["result"] = {"resources": [ {"uri": uri, "name": name, "mimeType": "text/markdown"} for uri, (name, _) in resources.items()]} elif method == "resources/read" and params.get("uri") in (resources or {}): uri = params["uri"] reply["result"] = {"contents": [ {"uri": uri, "mimeType": "text/markdown", "text": resources[uri][1]}]} elif method == "tools/call" and params.get("name") in TOOLS: name, args = params["name"], params.get("arguments") or {} logging.info("guest calls %s(%s)", name, json.dumps(args)) try: result = getattr(mailbox, name)(**args) reply["result"] = {"content": [ {"type": "text", "text": json.dumps(result)}]} except (KeyError, ValueError, TypeError) as err: reply["result"] = {"isError": True, "content": [ {"type": "text", "text": str(err)}]} else: reply["error"] = {"code": -32601, "message": f"no method {method}"} return reply