Files

269 lines
10 KiB
Python

"""
harness-opencode's MCP adapter (MCP plugin spec §3) — the MCP servers the
hub's ``mcp-servers`` plugin gives each opencode account, through the
sidecar's ``mcp_base``.
**No opencode.json is touched.** opencode V2's ``mcp list`` / ``mcp auth``
talk to the user's own background service (and ignore XDG overrides), so the
hub's servers live in a file of ours — ``<state dir>/opencode-mcp/<account>.json``
(``{name: canonical config}``, 0600: headers can be keys) — and every run of
that account gets them merged into its ``OPENCODE_CONFIG_CONTENT["mcp"]``
(``run_servers``, called by ``cli.run_config``): http / sse → ``{"type":
"remote", "url", "headers", "enabled": true, "oauth": false}`` (no OAuth of
opencode's own: a server that needs a sign-in goes through the hub's
gateway), stdio → ``{"type": "local", "command": [command, *args],
"environment": env, "enabled": true}``.
**Listing**: the user's own servers from the global config
(``$XDG_CONFIG_HOME``/``~/.config/opencode/opencode.json[c]``, then
``$OPENCODE_CONFIG``; source ``user``) and the project's
(``<default cwd>/opencode.json[c]``, source ``project``), status ``unknown``
(``disabled`` when ``enabled: false``) — opencode has no health check we can
run; the hub's (source ``hub``) probed with an MCP ``initialize``
(``mcp_base.probe_http`` / ``probe_stdio``). One row per name, as a run sees
it: the hub's over the project's over the user's.
No sign-in (``caps.login`` False): OAuth servers go through the hub gateway.
``run_servers`` works on any sidecar; the adapter itself only where the
sidecar has ``mcp_base`` (:func:`adapter` answers None otherwise — spec §2.3).
"""
from __future__ import annotations
import json
import os
import pathlib
import re
import threading
import config
try:
import mcp_base
except ImportError: # a sidecar from before the MCP plugin
mcp_base = None
_ACCOUNT_RE = re.compile(r"^[a-z][a-z0-9_-]{0,63}$")
_lock = threading.Lock()
# ── our store ─────────────────────────────────────────────────────────────────
def store_path(account: str) -> pathlib.Path:
import pairing
if not _ACCOUNT_RE.match(account or ""):
raise ValueError(f"bad opencode account {account!r}")
return pairing.state_dir() / "opencode-mcp" / f"{account}.json"
def _read(p: pathlib.Path) -> dict:
try:
v = json.loads(p.read_text(encoding="utf-8"))
return v if isinstance(v, dict) else {}
except (OSError, ValueError):
return {}
def stored(account: str) -> dict[str, dict]:
"""``{name: canonical config}`` the hub gave that account."""
try:
p = store_path(account)
except ValueError:
return {}
return {n: c for n, c in _read(p).items() if isinstance(n, str) and isinstance(c, dict)}
def _write_store(account: str, data: dict) -> None:
import secrets
p = store_path(account)
p.parent.mkdir(parents=True, exist_ok=True)
try:
os.chmod(p.parent, 0o700)
except OSError:
pass
tmp = p.with_name(f".{p.name}.{secrets.token_hex(4)}.tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(json.dumps(data, indent=2) + "\n")
os.replace(tmp, p)
except BaseException:
try:
tmp.unlink()
except OSError:
pass
raise
def to_opencode(cfg: dict) -> dict | None:
"""A canonical config → opencode's ``mcp`` entry (None: not one)."""
t = cfg.get("type")
if t in ("http", "sse") and isinstance(cfg.get("url"), str):
return {"type": "remote", "url": cfg["url"], "headers": dict(cfg.get("headers") or {}),
"enabled": True, "oauth": False}
if t == "stdio" and isinstance(cfg.get("command"), str):
return {"type": "local", "command": [cfg["command"], *(cfg.get("args") or [])],
"environment": dict(cfg.get("env") or {}), "enabled": True}
return None
def run_servers(account: str | None) -> dict:
"""What a run on ``account`` gets as ``OPENCODE_CONFIG_CONTENT["mcp"]``
({} when the hub gave it nothing)."""
if not account:
return {}
out = {}
for name, cfg in sorted(stored(account).items()):
entry = to_opencode(cfg)
if entry is not None:
out[name] = entry
return out
# ── the user's and the project's own servers ─────────────────────────────────
def jsonc_loads(text: str):
"""JSON with ``//`` / ``/* */`` comments and trailing commas (opencode.jsonc)."""
out, i, n = [], 0, len(text)
while i < n:
c = text[i]
if c == '"':
j = i + 1
while j < n and text[j] != '"':
j += 2 if text[j] == "\\" else 1
out.append(text[i:j + 1])
i = j + 1
elif text.startswith("//", i):
j = text.find("\n", i)
i = n if j < 0 else j
elif text.startswith("/*", i):
j = text.find("*/", i + 2)
i = n if j < 0 else j + 2
else:
out.append(c)
i += 1
return json.loads(re.sub(r",(\s*[}\]])", r"\1", "".join(out)))
def _servers_in(path: pathlib.Path) -> dict[str, dict]:
try:
text = path.read_text(encoding="utf-8")
except OSError:
return {}
try:
v = jsonc_loads(text) if path.suffix == ".jsonc" else json.loads(text)
except ValueError:
return {}
mcp = v.get("mcp") if isinstance(v, dict) else None
return {n: c for n, c in mcp.items() if isinstance(c, dict)} if isinstance(mcp, dict) else {}
def global_files() -> list[pathlib.Path]:
base = pathlib.Path(os.environ.get("XDG_CONFIG_HOME") or pathlib.Path.home() / ".config")
out = [base / "opencode" / f for f in ("config.json", "opencode.json", "opencode.jsonc")]
if os.environ.get("OPENCODE_CONFIG"):
out.append(pathlib.Path(os.path.expanduser(os.environ["OPENCODE_CONFIG"])))
return out
def project_files(cwd: str | None = None) -> list[pathlib.Path]:
d = pathlib.Path(cwd or config.DEFAULT_CWD)
return [d / "opencode.json", d / "opencode.jsonc"]
def user_servers() -> dict[str, dict]:
out: dict[str, dict] = {}
for f in global_files():
out.update(_servers_in(f))
return out
def project_servers(cwd: str | None = None) -> dict[str, dict]:
out: dict[str, dict] = {}
for f in project_files(cwd):
out.update(_servers_in(f))
return out
def _own_row(name: str, entry: dict, source: str) -> dict:
remote = entry.get("type") == "remote" or isinstance(entry.get("url"), str)
if remote:
target = mcp_base.redact(str(entry.get("url") or ""))
else:
cmd = entry.get("command")
target = mcp_base.redact(" ".join(map(str, cmd)) if isinstance(cmd, list) else str(cmd or ""))
return mcp_base.row(name, source=source, transport="http" if remote else "stdio",
target=target,
status="disabled" if entry.get("enabled") is False else "unknown")
_Base = mcp_base.McpAdapter if mcp_base is not None else object
class OpencodeMcp(_Base):
harness_id = "opencode"
caps = {"login": False, "approve": False, "connectors": False,
"transports": ("http", "sse", "stdio")}
def accounts(self) -> list[str]:
"""The declared accounts, then the ones a worker runs through the
hub's opencode proxy."""
try:
import opencode_proxy
proxied = list(opencode_proxy.accounts())
except Exception: # noqa: BLE001
proxied = []
return list(dict.fromkeys([*config.OPENCODE_ACCOUNTS, *proxied]))
def config_dir(self, account: str) -> str:
return str(store_path(account).parent)
def cwd(self, account: str) -> str:
return config.DEFAULT_CWD
def own_names(self, account: str) -> set[str]:
"""The user's global names (a conflict) and ours (the scope we write)."""
return set(user_servers()) | set(stored(account))
def write(self, account: str, name: str, cfg: dict) -> None:
if to_opencode(cfg) is None:
raise mcp_base.McpError("not an MCP server opencode can run")
with _lock:
data = stored(account)
data[name] = cfg
try:
_write_store(account, data)
except OSError as e:
raise mcp_base.McpError(f"could not save it: {e.strerror or e}")
def delete(self, account: str, name: str) -> None:
with _lock:
data = stored(account)
if data.pop(name, None) is None:
return
try:
_write_store(account, data)
except OSError as e:
raise mcp_base.McpError(f"could not save it: {e.strerror or e}")
def list_account(self, account: str, managed: dict[str, str]) -> dict:
ours = stored(account)
rows: dict[str, dict] = {}
for name, entry in user_servers().items():
rows[name] = _own_row(name, entry, "user")
for name, entry in project_servers().items():
rows[name] = _own_row(name, entry, "project")
status = mcp_base.probe_all(ours)
for name, cfg in ours.items():
st, detail = status.get(name, ("unknown", None))
target = cfg.get("url") if cfg.get("type") in ("http", "sse") \
else " ".join([str(cfg.get("command") or ""), *map(str, cfg.get("args") or [])])
rows[name] = mcp_base.row(name, source="hub", transport=str(cfg.get("type")),
target=mcp_base.redact(str(target or "")), status=st,
detail=detail, managed=name in managed)
return {"servers": list(rows.values()), "listError": None}
def adapter() -> OpencodeMcp | None:
"""The adapter — None on a sidecar without ``mcp_base``."""
return OpencodeMcp() if mcp_base is not None else None