feat: Endo-compatible host, downloads folder, Nix tools PATH

- the fake host serves a subset of @endo/agent-mcp-stdio's catalog,
  with its names, schemas and answers; evaluate takes only
  E(name).method(arg, ...), and __getMethodNames__
- demo.py --host endo: a real Endo daemon (endo-but-for-bots, llm),
  its guest served by the package's broker
- a downloads folder: the host writes, Hermes reads at ~/Downloads;
  BindReadOnlyPaths on Linux, a virtiofs share on macOS
- .#demo-tools: Hermes and the checks get their whole PATH from the store
- each run saves its MCP messages and a transcript
- the guide: tools as system calls, names as file descriptors;
  no Linux networking, but WebApps
- grants match a named URL before "download"

Generated-by: Claude Opus 5.5
This commit is contained in:
dckc committed 2026-11-29 23:15:06 -06:00
1 parent 783e4c595f
commit 3f9ba54477
15 files changed
+2398 -282

No files matched your search

+349 -149
View File
@@ -1,49 +1,74 @@
"""A guest's mailbox and pet store, and its methods as an MCP server.
"""A fake Endo host: one guest's mailbox and pet store, as Endo serves it.
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`.
Its tools are a subset of @endo/agent-mcp-stdio's, with that server's
names, descriptions and input schemas (from endo-catalog.json), and its
answers rendered as that server renders them: a string as is, other data
as JSON, a reference as "[remotable]". So a guest can't tell this host
from an Endo daemon's guest, as far as the subset goes, and a test can
swap one for the other.
>>> host = HostSide(on_request=lambda description: Ref('Pen'))
Two things are simpler than Endo: a pet name path has one name, and
`evaluate` takes only a method call, E(name).method(arg, ...), parsed
rather than run.
>>> host = HostSide(on_request=lambda description: Ref('Pen', ('write',)))
>>> 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'])
>>> print(guest.listMessages())
[
{
"number": "0",
"type": "package",
"from": "@host",
"strings": [
"Hello. Please ask me for a pen."
],
"names": []
}
]
>>> guest.request(['@host'], 'a pen', ['pen'])
'"[remotable]"'
>>> print(guest.evaluate('E(p).__getMethodNames__()', ['p'], [['pen']]))
[
"__getMethodNames__",
"write"
]
>>> print(guest.list())
[
"@agent",
"@host",
"@self",
"pen"
]
>>> guest.reply(0, ['Thanks for the ', '!'], ['it'], [['pen']])
'Reply sent'
>>> host.inbox[-1]['strings'], host.inbox[-1]['names']
(['Thanks for the ', '!'], ['it'])
>>> host.received['it']
Ref(interface='Pen')
Ref(interface='Pen', methods=('write',))
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')
>>> guest.request(['@host'], 'https://registry.npmjs.org/', ['npm'])
'"[remotable]"'
>>> guest.evaluate("E(npm).pathjoin('ms')", ['npm'], [['npm']], resultName=['ms'])
'"[remotable]"'
>>> guest.evaluate('E(m).get()', ['m'], [['ms']])
'fetched https://registry.npmjs.org/ms'
>>> guest.call('npm', 'pathjoin', ['https://elsewhere.example/'])
>>> guest.evaluate("E(npm).pathjoin('https://elsewhere.example/')", ['npm'], [['npm']])
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'}})
>>> guest.define("Far('Site', {})", {'site': {'label': 'a WebApp for the site'}})
'Definition sent'
>>> host.definitions[0]['slots']
{'site': {'label': 'a WebApp for the site'}}
"""
import base64
import ast
import json
import logging
import re
@@ -57,30 +82,57 @@ class Ref:
"""A reference, as the pet store holds it: never sent to the guest."""
interface: str
methods: tuple = ()
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
@property
def METHODS(self):
return self.methods
def is_ref(value):
return hasattr(value, "interface")
def render(value):
"""A tool's answer as @endo/agent-mcp-stdio renders it.
>>> render('hi'), render(None), render(Ref('Pen'))
('hi', '', '"[remotable]"')
>>> print(render({'n': 1, 'pen': Ref('Pen')}))
{
"n": 1,
"pen": "[remotable]"
}
"""
if isinstance(value, str):
return value
if value is None:
return ""
return json.dumps(value, indent=2,
default=lambda v: "[remotable]" if is_ref(v) else str(v))
def _name(path):
"""The one name in a pet name path; this host keeps no directories."""
if isinstance(path, str):
return path
if len(path) != 1:
raise ValueError(f"this host keeps only single names, not {'/'.join(path)}")
return path[0]
def _number(messageNumber):
return int(messageNumber)
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."""
pathjoin and query, then fire with get or post. blob is this host's
addition, for bytes, as an Endo ReadableBlob: toybox's fetch device
answers text."""
interface = "WebApp"
METHODS = ("pathjoin", "query", "get", "getBase64", "post")
METHODS = ("pathjoin", "query", "get", "blob", "post")
def __init__(self, fetch, url):
self._fetch, self._url = fetch, url
@@ -105,15 +157,82 @@ class WebApp:
def get(self):
return self._send("GET").decode("utf-8", errors="replace")
def getBase64(self):
return base64.b64encode(self._send("GET")).decode("ascii")
def blob(self):
return Blob(lambda: self._send("GET"))
def post(self, body):
return self._send("POST", body.encode()).decode("utf-8", errors="replace")
class Blob:
"""A ReadableBlob: bytes, read when a reader asks."""
interface = "ReadableBlob"
METHODS = ("text",)
def __init__(self, read):
self._read = read
def bytes(self):
return self._read()
def text(self):
return self._read().decode("utf-8", errors="replace")
class Dir:
"""An EndoMount's write, for one directory: `save(name, data)` writes
there, and nowhere else.
>>> saved = {}
>>> downloads = Dir(lambda name, data: saved.update({name: data}), lambda: sorted(saved))
>>> downloads.write('six.whl', Blob(lambda: b'PK'))
>>> downloads.list(), saved
(['six.whl'], {'six.whl': b'PK'})
>>> downloads.write('../.bashrc', Blob(lambda: b''))
Traceback (most recent call last):
...
ValueError: write: not a file name in this directory: ../.bashrc
"""
interface = "EndoMount"
METHODS = ("write", "list")
def __init__(self, save, names):
self._save, self._names = save, names
def write(self, path, blob):
name = path if isinstance(path, str) else "/".join(path)
if not FILE_NAME.match(name) or name in (".", ".."):
raise ValueError(f"write: not a file name in this directory: {name}")
if not isinstance(blob, Blob):
raise TypeError("Expected a ReadableBlob source")
self._save(name, blob.bytes())
def list(self):
return self._names()
FILE_NAME = re.compile(r"^[\w.+-]+$")
SLOT = re.compile(r"^[A-Za-z_$][\w$]*$")
HELP = """EndoGuest - A confined agent with directory and mail capabilities.
A guest can:
- Manage pet names for values (directory operations)
- Send and receive messages (mail operations)
- Request capabilities from its host
Special names available:
- @self: This guest's own handle
- @host: The host that created this guest
- @agent: This guest's formula identifier
Use help("methodName") for details on specific methods."""
SPECIAL = ("@agent", "@host", "@self")
@dataclass
class HostSide:
@@ -125,7 +244,7 @@ class HostSide:
definitions: list = field(default_factory=list)
def send(self, guest, strings, edge_names, values):
guest._deliver("package", "HOST", strings=strings,
guest._deliver("package", "@host", strings=strings,
names=edge_names, values=values)
def _receive(self, message, values):
@@ -134,177 +253,258 @@ class HostSide:
class Mailbox:
"""One guest's powers. Method names are EndoGuest's."""
"""One guest's tools: @endo/agent-mcp-stdio's, by name and arguments."""
TOOLS = ("help", "has", "list", "listMessages", "send", "reply", "adopt",
"dismiss", "request", "evaluate", "define")
def __init__(self, host):
self._host = host
self._lock = threading.Lock()
self._pets = {"HOST": Ref("Host")}
self._pets = {"@host": Ref("EndoHandle")}
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},
{"number": str(number), "type": type_, "from": sender, **record},
list(values),
))
def _message(self, number):
def _message(self, messageNumber):
for record, values in self._messages:
if record["number"] == number:
if record["number"] == str(_number(messageNumber)):
return record, values
raise KeyError(f"no message {number}")
raise KeyError(f'No such message with number "{messageNumber}"')
def _to_host(self, to):
if to != "HOST":
raise KeyError(f"no recipient {to}; this guest can write only to HOST")
def _lookup(self, path):
name = _name(path)
if name not in self._pets:
raise KeyError(f'Unknown pet name "{name}"')
return self._pets[name]
def _to_host(self, recipient):
if _name(recipient) != "@host":
raise KeyError(f"Unknown recipient {_name(recipient)}")
def help(self, methodName=None):
return HELP
def has(self, petNamePath):
return render(_name(petNamePath) in self._pets or _name(petNamePath) in SPECIAL)
def list(self, petNamePath=None):
if petNamePath:
raise ValueError("this host keeps no directories")
return render(sorted(set(self._pets) | set(SPECIAL)))
def listMessages(self):
with self._lock:
return [dict(record) for record, _ in self._messages]
return render([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)
def request(self, recipient, description, responseName=None):
self._to_host(recipient)
value = self._host.on_request(description)
if responseName:
self._pets[responseName] = value
return describe(value)
self._pets[_name(responseName)] = value
return render(value)
def send(self, to, strings, edgeNames, petNames):
self._to_host(to)
values = [self._pets[n] for n in petNames]
def send(self, recipient, strings, edgeNames, petNames):
self._to_host(recipient)
if len(strings) != len(edgeNames) + 1:
raise ValueError("strings has one more entry than edgeNames")
values = [self._lookup(p) for p in petNames]
self._host._receive(
{"type": "package", "from": "guest", "strings": strings,
"names": edgeNames}, values)
return "Message sent"
def reply(self, messageNumber, strings, edgeNames, petNames):
record, _ = self._message(messageNumber)
self.send(record["from"], strings, edgeNames, petNames)
self._host.inbox[-1]["replyTo"] = messageNumber
self._message(messageNumber)
self.send(["@host"], strings, edgeNames, petNames)
self._host.inbox[-1]["replyTo"] = str(_number(messageNumber))
return "Reply sent"
def adopt(self, messageNumber, edgeName, petName):
record, values = self._message(messageNumber)
self._pets[petName] = values[record["names"].index(edgeName)]
self._pets[_name(petName)] = values[record["names"].index(edgeName)]
return f"Adopted {edgeName} as {_name(petName)}"
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 dismiss(self, messageNumber):
self._message(messageNumber)
with self._lock:
self._messages = [(r, v) for r, v in self._messages
if r["number"] != str(_number(messageNumber))]
return f"Dismissed message {messageNumber}"
def define(self, modules, slots):
"""Propose to the host a vat of `modules`, its params named by `slots`."""
def evaluate(self, source, codeNames, petNamePaths, workerName=None, resultName=None):
"""Evaluate `source` with each of `codeNames` bound to what its path names.
Constrained: `source` may only be E(name).method(arg, ...), each arg
a literal or a code name. Every object answers __getMethodNames__.
"""
if len(codeNames) != len(petNamePaths):
raise ValueError("Evaluator requires one pet name for each code name")
scope = {c: self._lookup(p) for c, p in zip(codeNames, petNamePaths)}
answer = run_send(parse_send(source, scope))
if resultName:
self._pets[_name(resultName)] = answer
return render(answer)
def define(self, source, slots):
"""Propose to the host code `source`, its free variables 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]
self._host.definitions.append({"source": source, "slots": slots})
return "Definition sent"
def _schema(props, required=None):
return {"type": "object", "properties": props,
"required": list(props) if required is None else required}
_LITERALS = {"true": True, "false": False, "null": None}
STR, INT = {"type": "string"}, {"type": "integer"}
STRS = {"type": "array", "items": STR}
@dataclass(frozen=True)
class Send:
"""E(target).method(*args), parsed."""
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"]}}})),
}
target: object
method: str
args: tuple
def handle_rpc(mailbox, msg, resources=None):
def run_send(send):
"""Do `send`.
>>> run_send(Send(Blob(lambda: b'hi'), 'text', ()))
'hi'
>>> run_send(Send(Blob(lambda: b''), '__getMethodNames__', ()))
['__getMethodNames__', 'text']
"""
args = send.args
methods = ("__getMethodNames__", *getattr(send.target, "METHODS", ()))
if send.method == "__getMethodNames__":
return sorted(methods)
if send.method not in methods:
raise TypeError(f"target has no method {json.dumps(send.method)}, "
f"has {sorted(methods)}")
return getattr(send.target, send.method)(*args)
def parse_send(source, scope):
"""Parse E(name).method(arg, ...) against `scope`, as a Send.
Args are JSON-ish literals (strings, numbers, true, false, null, arrays,
objects) or names in scope. Anything else is refused, a send among the
args too: Endo's guarded methods, such as a mount's write, refuse a
promise, so a send's answer must be named first.
>>> parse_send("E(npm).pathjoin('ms', [1, true])", {'npm': 'N'})
Send(target='N', method='pathjoin', args=('ms', [1, True]))
>>> parse_send("E(d).write('x', E(w).blob())", {'d': 'D', 'w': 'W'})
Traceback (most recent call last):
...
ValueError: evaluate supports only E(name).method(arg, ...), not: E(d).write('x', E(w).blob())
>>> parse_send("fetch('https://x/')", {})
Traceback (most recent call last):
...
ValueError: evaluate supports only E(name).method(arg, ...), not: fetch('https://x/')
>>> parse_send("E(a).m(c)", {'a': 1})
Traceback (most recent call last):
...
ValueError: evaluate: c is not in scope
"""
refuse = ValueError(f"evaluate supports only E(name).method(arg, ...), not: {source}")
try:
tree = ast.parse(source.strip().rstrip(";"), mode="eval").body
except SyntaxError:
raise refuse from None
def send(node):
match node:
case ast.Call(func=ast.Attribute(value=ast.Call(
func=ast.Name(id="E"), args=[ast.Name(id=name)], keywords=[]),
attr=method), args=args, keywords=[]):
if name not in scope:
raise ValueError(f"evaluate: {name} is not in scope")
return Send(scope[name], method, tuple(value(a) for a in args))
case _:
raise refuse
def value(node):
match node:
case ast.Constant(value=v) if isinstance(v, (str, int, float)) and not isinstance(v, bool):
return v
case ast.UnaryOp(op=ast.USub(), operand=ast.Constant(value=v)) if type(v) in (int, float):
return -v
case ast.Name(id=n) if n in scope:
return scope[n]
case ast.Name(id=n) if n in _LITERALS:
return _LITERALS[n]
case ast.Name(id=n):
raise ValueError(f"evaluate: {n} is not in scope")
case ast.List(elts=elts):
return [value(e) for e in elts]
case ast.Dict(keys=keys, values=vals) if all(
isinstance(k, ast.Constant) and isinstance(k.value, str) for k in keys):
return {k.value: value(v) for k, v in zip(keys, vals)}
case _:
raise refuse
return send(tree)
def tool_catalog(endo_catalog):
"""The tools this host serves: Endo's entries for those it implements.
>>> catalog = tool_catalog([{'name': 'list', 'description': 'd', 'inputSchema': {}},
... {'name': 'glob', 'description': 'g', 'inputSchema': {}}])
>>> [t['name'] for t in catalog]
['list']
"""
return [t for t in endo_catalog if t["name"] in Mailbox.TOOLS]
def handle_rpc(mailbox, msg, tools):
"""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'})
... 'params': {'name': 'has', 'arguments': {'petNamePath': ['@host']}}}, [
... {'name': 'has'}])['result']['content'][0]['text']
'true'
>>> handle_rpc(box, {'jsonrpc': '2.0', 'id': 2, 'method': 'tools/call',
... 'params': {'name': 'adopt', 'arguments': {'messageNumber': 9,
... 'edgeName': 'x', 'petName': ['x']}}}, [{'name': 'adopt'}])['result']
{'isError': True, 'content': [{'type': 'text', 'text': 'Error: No such message with number "9"'}]}
>>> 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"]}
names = {t["name"] for t in tools}
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"},
"capabilities": {"tools": {"listChanged": False}, "logging": {}},
"serverInfo": {"name": "endo", "version": "fake"},
}
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:
reply["result"] = {"tools": tools}
elif method == "tools/call" and params.get("name") in names:
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)}]}
text = getattr(mailbox, name)(**args)
reply["result"] = {"content": [{"type": "text", "text": text}]}
except (KeyError, ValueError, TypeError) as err:
reply["result"] = {"isError": True, "content": [
{"type": "text", "text": str(err)}]}
{"type": "text", "text": f"Error: {err.args[0] if err.args else err}"}]}
elif method == "tools/call":
reply["error"] = {"code": -32001, "message": "tool-not-permitted"}
else:
reply["error"] = {"code": -32601, "message": f"no method {method}"}
reply["error"] = {"code": -32601, "message": f"Method not found: {method}"}
return reply