254 lines
11 KiB
Python
254 lines
11 KiB
Python
"""harness-opencode's MCP adapter (``sidecar/mcp.py``, MCP plugin spec §3):
|
|
the hub's servers kept in a 0600 file of ours and merged into every run's
|
|
``OPENCODE_CONFIG_CONTENT["mcp"]`` (never opencode.json), the listing (the
|
|
user's global config, the project's, ours probed), and the driver loading on
|
|
a sidecar from before ``mcp_base`` (§2.3). Temp HOME / XDG dirs only — the
|
|
real ``~/.config/opencode`` is never read nor written."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
|
|
import pytest
|
|
|
|
PLUGIN = pathlib.Path(__file__).resolve().parents[1]
|
|
SIDECAR = pathlib.Path(os.environ.get("AI_AGENT_SIDECAR")
|
|
or pathlib.Path.home() / "projects/ai-agent/sidecar").resolve()
|
|
if not (SIDECAR / "harness_loader.py").is_file():
|
|
pytest.skip(f"no ai-agent sidecar at {SIDECAR}", allow_module_level=True)
|
|
|
|
_TMP = pathlib.Path(tempfile.mkdtemp(prefix="harness-opencode-mcp-"))
|
|
for k, v in {"SIDECAR_HARNESS_BUILTINS": "0", "SIDECAR_USAGE_BUILTINS": "0",
|
|
"SIDECAR_LOG_DIR": str(_TMP / "logs"), "SIDECAR_OPENCODE_DIR": str(_TMP / "oc"),
|
|
"SIDECAR_AGY_DIR": str(_TMP / "agy"), "PI_MODELS_FILE": str(_TMP / "no-models.json"),
|
|
"SIDECAR_LIVE_PROVIDERS_DIR": str(_TMP / "no-providers"),
|
|
"WORKER_STATE_DIR": str(_TMP / "worker")}.items():
|
|
os.environ.setdefault(k, v)
|
|
if str(SIDECAR) not in sys.path:
|
|
sys.path.insert(0, str(SIDECAR))
|
|
|
|
import harness_loader # noqa: E402
|
|
|
|
HAS_BASE = (SIDECAR / "mcp_base.py").is_file()
|
|
needs_base = pytest.mark.skipif(not HAS_BASE, reason="a sidecar without mcp_base")
|
|
PKG = "sidecar_ext.harness.harness_opencode"
|
|
ACCT = "chatgpt-work"
|
|
|
|
|
|
def _live_dir(root: pathlib.Path) -> pathlib.Path:
|
|
mf = json.loads((PLUGIN / "plugin.json").read_text())
|
|
shutil.copytree(PLUGIN / "sidecar", root / mf["id"] / "sidecar",
|
|
ignore=shutil.ignore_patterns("__pycache__"))
|
|
shutil.copy2(PLUGIN / "plugin.json", root / mf["id"] / "plugin.json")
|
|
(root / "index.json").write_text(json.dumps({"version": 1, "harnesses": {
|
|
"opencode": {"pluginId": mf["id"], "dir": mf["id"], "entry": "driver.py",
|
|
"guestAllowed": False}}}))
|
|
return root
|
|
|
|
|
|
@pytest.fixture
|
|
def oc(tmp_path, monkeypatch):
|
|
"""The plugin loaded, two accounts, every config dir under tmp."""
|
|
monkeypatch.setenv("SIDECAR_LIVE_HARNESSES_DIR", str(_live_dir(tmp_path / "live")))
|
|
monkeypatch.setenv("WORKER_STATE_DIR", str(tmp_path / "state"))
|
|
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))
|
|
monkeypatch.delenv("OPENCODE_CONFIG", raising=False)
|
|
harness_loader.LOADER.reset()
|
|
out = harness_loader.LOADER.reload(start=False)
|
|
assert out["ok"], out
|
|
import config
|
|
cwd = tmp_path / "repo"
|
|
cwd.mkdir()
|
|
monkeypatch.setattr(config, "DEFAULT_CWD", str(cwd))
|
|
cli = sys.modules[f"{PKG}.cli"]
|
|
accounts = {ACCT: tmp_path / "work", "opencode-lab": tmp_path / "lab"}
|
|
monkeypatch.setattr(cli, "OPENCODE_ACCOUNTS", accounts)
|
|
monkeypatch.setattr(config, "OPENCODE_ACCOUNTS", accounts)
|
|
d = harness_loader.get("opencode")
|
|
yield {"d": d, "cli": cli, "mod": sys.modules.get(f"{PKG}.mcp"), "tmp": tmp_path,
|
|
"cwd": cwd}
|
|
harness_loader.LOADER.reset()
|
|
|
|
|
|
@pytest.fixture
|
|
def base(oc, monkeypatch):
|
|
import mcp_base
|
|
monkeypatch.setattr(mcp_base, "enabled", lambda: True)
|
|
monkeypatch.setattr(mcp_base, "refresh_soon", lambda: None)
|
|
monkeypatch.setattr(mcp_base, "_state", {"at": time.time(), "running": False, "logins": {}})
|
|
a = oc["d"].mcp_adapter()
|
|
oc["a"] = a
|
|
oc["mod"] = sys.modules[f"{PKG}.mcp"]
|
|
monkeypatch.setattr(mcp_base, "adapters", lambda: [a])
|
|
return mcp_base
|
|
|
|
|
|
HTTP = {"type": "http", "url": "https://mcp.linear.app/mcp",
|
|
"headers": {"Authorization": "Bearer lin_api_x"}}
|
|
STDIO = {"type": "stdio", "command": "npx", "args": ["-y", "ctx7"], "env": {"KEY": "k1"}}
|
|
|
|
|
|
def _run_config(oc, account):
|
|
env = oc["cli"].run_env(account, {"PATH": "/bin"}, str(oc["cwd"]))
|
|
return json.loads(env["OPENCODE_CONFIG_CONTENT"])
|
|
|
|
|
|
@needs_base
|
|
def test_the_driver_answers_its_adapter(oc, base):
|
|
a = oc["a"]
|
|
assert a is oc["d"].mcp_adapter() and a.harness_id == "opencode"
|
|
assert base.caps_of(a) == {"login": False, "approve": False, "connectors": False,
|
|
"transports": ["http", "sse", "stdio"]}
|
|
assert a.accounts() == [ACCT, "opencode-lab"]
|
|
|
|
|
|
@needs_base
|
|
def test_apply_keeps_servers_in_our_file_and_every_run_gets_them(oc, base):
|
|
a = oc["a"]
|
|
assert "mcp" not in _run_config(oc, ACCT) # nothing yet: same config as before
|
|
out = base.apply(a, ACCT, [{"name": "linear", "config": HTTP, "hash": "h1"},
|
|
{"name": "ctx", "config": STDIO}], [])
|
|
assert out["results"] == {"linear": {"ok": True}, "ctx": {"ok": True}}
|
|
p = oc["mod"].store_path(ACCT)
|
|
assert p == oc["tmp"] / "state" / "opencode-mcp" / f"{ACCT}.json"
|
|
assert os.stat(p).st_mode & 0o777 == 0o600
|
|
assert json.loads(p.read_text()) == {"linear": HTTP, "ctx": STDIO}
|
|
assert base.managed(f"opencode:{ACCT}") == {"linear": "h1", "ctx": base.config_hash(STDIO)}
|
|
assert not (oc["tmp"] / "xdg" / "opencode").exists() # opencode.json never touched
|
|
|
|
mcp = _run_config(oc, ACCT)["mcp"]
|
|
assert mcp == {
|
|
"ctx": {"type": "local", "command": ["npx", "-y", "ctx7"], "environment": {"KEY": "k1"},
|
|
"enabled": True},
|
|
"linear": {"type": "remote", "url": "https://mcp.linear.app/mcp",
|
|
"headers": {"Authorization": "Bearer lin_api_x"}, "enabled": True,
|
|
"oauth": False}}
|
|
assert "mcp" not in _run_config(oc, "opencode-lab") # another account: not its
|
|
assert "mcp" not in oc["cli"].run_config(None, None) # /complete's one-shots: none
|
|
|
|
base.apply(a, ACCT, [], ["linear"])
|
|
assert list(_run_config(oc, ACCT)["mcp"]) == ["ctx"]
|
|
base.apply(a, ACCT, [], ["ctx"])
|
|
assert "mcp" not in _run_config(oc, ACCT)
|
|
|
|
|
|
@needs_base
|
|
def test_the_launch_carries_them(oc, base, monkeypatch):
|
|
"""The driver's own launch path: ``prepare`` → ``run_env``."""
|
|
base.apply(oc["a"], "opencode-lab", [{"name": "ctx", "config": STDIO}], [])
|
|
monkeypatch.setattr(oc["cli"], "OPENCODE_KEYLESS", {"opencode-lab"})
|
|
|
|
class Body:
|
|
account, model, effort, scope, force = "opencode-lab", None, None, None, False
|
|
prompt = "hi"
|
|
p = oc["d"].prepare(Body(), "11111111-2222-4333-8444-555555555555", str(oc["cwd"]),
|
|
harness_loader.context())
|
|
assert "ctx" in json.loads(p["env"]["OPENCODE_CONFIG_CONTENT"])["mcp"]
|
|
|
|
|
|
@needs_base
|
|
def test_a_name_of_the_users_own_is_a_conflict(oc, base):
|
|
g = oc["tmp"] / "xdg" / "opencode"
|
|
g.mkdir(parents=True)
|
|
(g / "opencode.jsonc").write_text('{\n // mine\n "mcp": {"linear": {"type": "remote", '
|
|
'"url": "https://x/mcp",},},\n}\n')
|
|
out = base.apply(oc["a"], ACCT, [{"name": "linear", "config": HTTP}], [])
|
|
assert out["results"]["linear"]["conflict"] is True
|
|
assert oc["mod"].stored(ACCT) == {}
|
|
|
|
|
|
@needs_base
|
|
def test_listing(oc, base, monkeypatch):
|
|
g = oc["tmp"] / "xdg" / "opencode"
|
|
g.mkdir(parents=True)
|
|
(g / "opencode.json").write_text(json.dumps({"mcp": {
|
|
"mine": {"type": "remote", "url": "https://u.example/mcp?token=SECRET"},
|
|
"off": {"type": "local", "command": ["/opt/bin/srv", "--key", "SECRET"],
|
|
"enabled": False},
|
|
"shadowed": {"type": "remote", "url": "https://user.example/mcp"}}}))
|
|
(oc["cwd"] / "opencode.jsonc").write_text(
|
|
'{"mcp": {"shadowed": {"type": "local", "command": ["proj-srv"]}}} // the repo\'s')
|
|
base.apply(oc["a"], ACCT, [{"name": "linear", "config": HTTP},
|
|
{"name": "ctx", "config": STDIO}], [])
|
|
probed = []
|
|
|
|
def fake_probe_all(configs, **kw):
|
|
probed.append(configs)
|
|
return {"linear": ("needs_auth", None), "ctx": ("connected", None)}
|
|
monkeypatch.setattr(base, "probe_all", fake_probe_all)
|
|
got = base.list_login(oc["a"], ACCT)
|
|
rows = {r["name"]: r for r in got["servers"]}
|
|
assert probed == [{"linear": HTTP, "ctx": STDIO}] # ours only: never the user's
|
|
assert rows["mine"] == {"name": "mine", "source": "user", "transport": "http",
|
|
"target": "https://u.example/mcp", "status": "unknown",
|
|
"detail": None, "managed": False}
|
|
assert rows["off"]["status"] == "disabled" and rows["off"]["target"] == "srv"
|
|
assert rows["shadowed"]["source"] == "project" and rows["shadowed"]["transport"] == "stdio"
|
|
assert rows["linear"]["source"] == "hub" and rows["linear"]["managed"]
|
|
assert rows["linear"]["status"] == "needs_auth"
|
|
assert rows["ctx"]["status"] == "connected" and rows["ctx"]["target"] == "npx"
|
|
assert "SECRET" not in json.dumps(got) and "lin_api_x" not in json.dumps(got)
|
|
r = base.report()["logins"][0]
|
|
assert r["key"] == f"opencode:{ACCT}" and r["caps"]["login"] is False
|
|
|
|
|
|
@needs_base
|
|
def test_no_sign_in_here(oc, base):
|
|
from fastapi import HTTPException
|
|
with pytest.raises(HTTPException) as e:
|
|
base.start_login(oc["a"], ACCT, "linear", spawn=lambda *a: pytest.fail("spawned"))
|
|
assert e.value.status_code == 409 and e.value.detail["kind"] == "unsupported"
|
|
|
|
|
|
def test_jsonc(oc):
|
|
mod = sys.modules.get(f"{PKG}.mcp")
|
|
if mod is None:
|
|
from importlib import import_module
|
|
mod = import_module(f"{PKG}.mcp")
|
|
text = '{\n "a": "http://x // not a comment", /* c */ "b": [1, 2,],\n // end\n}'
|
|
assert mod.jsonc_loads(text) == {"a": "http://x // not a comment", "b": [1, 2]}
|
|
assert mod.jsonc_loads('{"q": "a \\" // b"}') == {"q": 'a " // b'}
|
|
|
|
|
|
def test_a_broken_store_never_stops_a_run(oc):
|
|
import pairing
|
|
d = pairing.state_dir() / "opencode-mcp"
|
|
d.mkdir(parents=True, exist_ok=True)
|
|
(d / f"{ACCT}.json").write_text("{not json")
|
|
assert "mcp" not in _run_config(oc, ACCT)
|
|
|
|
|
|
def test_a_sidecar_without_mcp_base_still_loads_the_driver(tmp_path):
|
|
"""Spec §2.3: no ``mcp_base`` → the driver loads, its runs build their
|
|
config, and it has no MCP adapter."""
|
|
live = _live_dir(tmp_path / "live")
|
|
code = f"""
|
|
import json, sys
|
|
sys.path.insert(0, {str(SIDECAR)!r})
|
|
sys.modules["mcp_base"] = None
|
|
import harness_loader
|
|
out = harness_loader.LOADER.reload(start=False)
|
|
assert out["ok"], out
|
|
d = harness_loader.get("opencode")
|
|
cli = sys.modules["{PKG}.cli"]
|
|
cfg = cli.run_config(None, "chatgpt-work")
|
|
d.health_meta()
|
|
print(json.dumps([d.mcp_adapter() is None, "mcp" in cfg]))
|
|
"""
|
|
env = {**os.environ, "SIDECAR_LIVE_HARNESSES_DIR": str(live),
|
|
"SIDECAR_HARNESS_BUILTINS": "0", "SIDECAR_USAGE_BUILTINS": "0",
|
|
"WORKER_STATE_DIR": str(tmp_path / "state"),
|
|
"SIDECAR_OPENCODE_ACCOUNTS": "chatgpt-work=" + str(tmp_path / "acct"),
|
|
"SIDECAR_OPENCODE_MIRROR": "0"}
|
|
p = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True,
|
|
timeout=120, env=env, cwd=str(tmp_path))
|
|
assert p.returncode == 0, p.stderr[-3000:]
|
|
assert json.loads(p.stdout.strip().splitlines()[-1]) == [True, False]
|