jscdocs 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jscdocs/__init__.py +8 -0
- jscdocs/build.py +65 -0
- jscdocs/cli.py +190 -0
- jscdocs/core/__init__.py +1 -0
- jscdocs/core/agent_cli.py +131 -0
- jscdocs/core/agent_config.py +370 -0
- jscdocs/core/config.py +31 -0
- jscdocs/core/crawl.py +170 -0
- jscdocs/core/evaluate.py +97 -0
- jscdocs/core/extract.py +403 -0
- jscdocs/core/fetch.py +100 -0
- jscdocs/core/init.py +382 -0
- jscdocs/core/inventory.py +31 -0
- jscdocs/core/lock.py +125 -0
- jscdocs/core/published.py +125 -0
- jscdocs/core/refresh.py +107 -0
- jscdocs/core/search.py +294 -0
- jscdocs/core/sites.py +55 -0
- jscdocs/core/store.py +233 -0
- jscdocs/core/sync.py +47 -0
- jscdocs/mcp/__init__.py +1 -0
- jscdocs/mcp/server.py +86 -0
- jscdocs/mcp/tools.py +120 -0
- jscdocs-0.2.0.dist-info/METADATA +127 -0
- jscdocs-0.2.0.dist-info/RECORD +28 -0
- jscdocs-0.2.0.dist-info/WHEEL +4 -0
- jscdocs-0.2.0.dist-info/entry_points.txt +3 -0
- jscdocs-0.2.0.dist-info/licenses/LICENSE +21 -0
jscdocs/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""jscdocs: search and read the JSC supercomputer user documentation from AI agents."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
__version__ = version("jscdocs")
|
|
7
|
+
except PackageNotFoundError: # running from a source tree that is not installed
|
|
8
|
+
__version__ = "0.0.0"
|
jscdocs/build.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Build the index from the documentation sites, and write the files that CI publishes.
|
|
2
|
+
|
|
3
|
+
python -m jscdocs.build INDEX fetch all six sites into the index file INDEX
|
|
4
|
+
python -m jscdocs.build INDEX --export DIR then write DIR/schema-<N>/index.sqlite.gz and index.json
|
|
5
|
+
python -m jscdocs.build INDEX --system jureca fetch only JURECA; the others keep their pages
|
|
6
|
+
|
|
7
|
+
This is a tool for this project's CI and for work on the extraction, not a command of jscdocs: installations get
|
|
8
|
+
their index with `jscdocs sync`, which downloads what CI built here. An existing INDEX is updated: a site that
|
|
9
|
+
lost half of its pages since then is left out and reported, and a page that could not be fetched is kept as INDEX
|
|
10
|
+
has it. The exit status is 1, and nothing is exported, when a system could not be updated or the index does not
|
|
11
|
+
hold all six systems, so that an index that lacks a system is never published.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import sys
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from .core import crawl, lock, published, sites, store
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _lacking(index: Path) -> list[str]:
|
|
23
|
+
"""The systems that the index at `index` has no pages of."""
|
|
24
|
+
db = store.connect(index)
|
|
25
|
+
try:
|
|
26
|
+
have = {r[0] for r in db.execute("SELECT name FROM systems")}
|
|
27
|
+
finally:
|
|
28
|
+
db.close()
|
|
29
|
+
return [name for name in sites.SITES if name not in have]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
33
|
+
parser = argparse.ArgumentParser(prog="python -m jscdocs.build",
|
|
34
|
+
description="Build the index from the JSC documentation sites.")
|
|
35
|
+
parser.add_argument("index", type=Path, help="the index file to write or update")
|
|
36
|
+
parser.add_argument("--system", action="append", choices=list(sites.SITES), help="only this system (repeatable)")
|
|
37
|
+
parser.add_argument("--export", type=Path, metavar="DIR", help="write the files to publish into DIR")
|
|
38
|
+
args = parser.parse_args(argv)
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
results = crawl.crawl(args.index, args.system, log=lambda m: print(m, file=sys.stderr))
|
|
42
|
+
except lock.Busy as e:
|
|
43
|
+
print(f"Not building: {e}", file=sys.stderr)
|
|
44
|
+
return 1
|
|
45
|
+
failed = [r.system for r in results if not r.replaced]
|
|
46
|
+
if len(failed) == len(results):
|
|
47
|
+
print(f"No system could be updated; {args.index} was not written.", file=sys.stderr)
|
|
48
|
+
return 1
|
|
49
|
+
kept = [f"{r.system}/{p}" for r in results for p in r.kept_pages]
|
|
50
|
+
missing = [f"{r.system}/{p}" for r in results if r.replaced for p in r.failed_pages if p not in r.kept_pages]
|
|
51
|
+
print(f"Index written to {args.index}" + (f"; not updated: {', '.join(failed)}" if failed else "")
|
|
52
|
+
+ (f"; pages kept from the previous index: {', '.join(kept)}" if kept else "")
|
|
53
|
+
+ (f"; pages not indexed: {', '.join(missing)}" if missing else ""))
|
|
54
|
+
if failed:
|
|
55
|
+
return 1
|
|
56
|
+
if args.export:
|
|
57
|
+
if lacking := _lacking(args.index): # as after --system without a previous index
|
|
58
|
+
print(f"Not exported: {args.index} has no pages of {', '.join(lacking)}.", file=sys.stderr)
|
|
59
|
+
return 1
|
|
60
|
+
print(f"Published index written to {published.export(args.index, args.export)}")
|
|
61
|
+
return 0
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
if __name__ == "__main__":
|
|
65
|
+
sys.exit(main())
|
jscdocs/cli.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""The jscdocs command line: download the index, search it and read from it, and register the MCP server."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import sqlite3
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .core import agent_config, config, evaluate, lock, published, search, sites, store, sync
|
|
12
|
+
from .core import init as initializer
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def _limit(text: str) -> int:
|
|
16
|
+
"""The value of --limit. argparse reports the error and exits, where search() would quietly cap the number."""
|
|
17
|
+
if not text.isdecimal() or not 1 <= int(text) <= search.MAX_LIMIT:
|
|
18
|
+
raise argparse.ArgumentTypeError(f"must be a number from 1 to {search.MAX_LIMIT}")
|
|
19
|
+
return int(text)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
23
|
+
parser = argparse.ArgumentParser(prog="jscdocs", description="Search and read the JSC user documentation.")
|
|
24
|
+
parser.add_argument("--version", action="version", version=f"jscdocs {__version__}")
|
|
25
|
+
sub = parser.add_subparsers(dest="command", metavar="COMMAND")
|
|
26
|
+
|
|
27
|
+
p = sub.add_parser("sync", help="download the published index when it is newer than the index")
|
|
28
|
+
p.add_argument("--force", action="store_true",
|
|
29
|
+
help="download it also when the index is as new, to replace an index that is damaged")
|
|
30
|
+
|
|
31
|
+
p = sub.add_parser("search", help="search the index")
|
|
32
|
+
p.add_argument("query", nargs="+")
|
|
33
|
+
p.add_argument("--system", choices=list(sites.SITES))
|
|
34
|
+
p.add_argument("--limit", type=_limit, default=8, help=f"most sections to show, up to {search.MAX_LIMIT}")
|
|
35
|
+
|
|
36
|
+
p = sub.add_parser("read", help="print a section or page, e.g. jureca/batchsystem#internet-access")
|
|
37
|
+
p.add_argument("ref")
|
|
38
|
+
p.add_argument("--no-subsections", action="store_true", help="only the section's own text")
|
|
39
|
+
p.add_argument("--offset", type=int, default=0)
|
|
40
|
+
|
|
41
|
+
p = sub.add_parser("toc", help="list a system's pages and sections")
|
|
42
|
+
p.add_argument("system", choices=list(sites.SITES))
|
|
43
|
+
p.add_argument("--depth", type=int, default=2)
|
|
44
|
+
|
|
45
|
+
sub.add_parser("status", help="show the index and its systems")
|
|
46
|
+
|
|
47
|
+
p = sub.add_parser("eval", help="measure search quality against a question file")
|
|
48
|
+
p.add_argument("questions", type=Path, help="TOML file, e.g. tests/eval/questions.toml")
|
|
49
|
+
p.add_argument("-v", "--verbose", action="store_true", help="also show questions answered by the first hit")
|
|
50
|
+
|
|
51
|
+
p = sub.add_parser("init", help="register jscdocs as an MCP server for a coding agent",
|
|
52
|
+
description="Register the jscdocs MCP server with Claude Code, Codex, pi or OpenCode, through "
|
|
53
|
+
"the agent's own command where it can, else by editing its configuration file.")
|
|
54
|
+
p.add_argument("agent", choices=agent_config.AGENTS)
|
|
55
|
+
p.add_argument("--project", action="store_true",
|
|
56
|
+
help="register in the current project directory, as a file others can share: the bare "
|
|
57
|
+
"jscdocs-mcp, found on PATH")
|
|
58
|
+
p.add_argument("--index", type=Path, help="the index the server uses (default: $JSCDOCS_INDEX or the cache; "
|
|
59
|
+
"not with --project)")
|
|
60
|
+
p.add_argument("--no-refresh", dest="refresh", action="store_false",
|
|
61
|
+
help="the server never syncs the index on its own")
|
|
62
|
+
p.add_argument("--dry-run", action="store_true", help="show what would change without writing any file")
|
|
63
|
+
p.add_argument("--force", action="store_true", help="replace conflicting fields of the jscdocs entry")
|
|
64
|
+
p.add_argument("--json", action="store_true", help="print the result as JSON")
|
|
65
|
+
return parser
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _sync(path: Path, force: bool) -> int:
|
|
69
|
+
try:
|
|
70
|
+
replaced = sync.sync(path, log=lambda m: print(m, file=sys.stderr), force=force)
|
|
71
|
+
except lock.Busy as e:
|
|
72
|
+
print(f"Not syncing: {e}", file=sys.stderr)
|
|
73
|
+
return 1
|
|
74
|
+
except published.Unavailable as e:
|
|
75
|
+
last = sync.synced_at(path)
|
|
76
|
+
print(f"The published index could not be downloaded ({e}). "
|
|
77
|
+
+ (f"The index at {path} was kept (the documentation as of {last:%Y-%m-%d %H:%M} UTC)." if last
|
|
78
|
+
else f"There is no index at {path} yet."), file=sys.stderr)
|
|
79
|
+
return 1
|
|
80
|
+
except OSError as e:
|
|
81
|
+
print(f"Not syncing: the index at {path} cannot be written ({e}).", file=sys.stderr)
|
|
82
|
+
return 1
|
|
83
|
+
when = f"{sync.synced_at(path):%Y-%m-%d %H:%M} UTC"
|
|
84
|
+
if replaced:
|
|
85
|
+
print(f"Index downloaded to {path} (the documentation as of {when})")
|
|
86
|
+
else:
|
|
87
|
+
print(f"The index at {path} is as new as the published one ({when}).")
|
|
88
|
+
return 0
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _init(args) -> int:
|
|
92
|
+
project_root = None
|
|
93
|
+
try:
|
|
94
|
+
project_root = Path.cwd() if args.project else None
|
|
95
|
+
request = initializer.InitRequest(agent=args.agent, index=args.index, refresh=args.refresh,
|
|
96
|
+
force=args.force, project_root=project_root)
|
|
97
|
+
plan = initializer.plan_init(request)
|
|
98
|
+
if not args.json:
|
|
99
|
+
# Shown before apply, which may run the client; the reason and warnings follow in the notes.
|
|
100
|
+
backend = f"client CLI ({args.agent})" if plan.registration.backend == "cli" else "direct file"
|
|
101
|
+
print(f"Registration: {backend}", flush=True)
|
|
102
|
+
result = plan if args.dry_run else initializer.apply_init(plan)
|
|
103
|
+
data = result.as_dict()
|
|
104
|
+
except (initializer.InitError, OSError, ValueError) as error:
|
|
105
|
+
message = error.strerror if isinstance(error, OSError) else str(error)
|
|
106
|
+
if args.json:
|
|
107
|
+
print(json.dumps({"agent": args.agent, "scope": "project" if args.project else "user",
|
|
108
|
+
"project_root": str(project_root) if project_root is not None else None,
|
|
109
|
+
"ok": False, "error": message}))
|
|
110
|
+
else:
|
|
111
|
+
print(f"jscdocs: {message}", file=sys.stderr)
|
|
112
|
+
return 2 if isinstance(error, ValueError) else 1
|
|
113
|
+
if args.json:
|
|
114
|
+
print(json.dumps(data, indent=2))
|
|
115
|
+
else:
|
|
116
|
+
print(f"{args.agent} setup: {data['scope']} scope" + (" (dry run)" if args.dry_run else ""))
|
|
117
|
+
if data["project_root"] is not None:
|
|
118
|
+
print(f"Project: {data['project_root']}")
|
|
119
|
+
print(f"Config: {data['config']}")
|
|
120
|
+
print(f"Manifest: {data['manifest']}")
|
|
121
|
+
for server in data["servers"]:
|
|
122
|
+
print(f"{server['name']} launch: {json.dumps([server['command'], *server['args']])}")
|
|
123
|
+
if server["forward_env"]:
|
|
124
|
+
print(f" forward environment: {', '.join(server['forward_env'])}")
|
|
125
|
+
for action in data["actions"]:
|
|
126
|
+
print(f"{action['name']}: {action['action']} ({action['path']})")
|
|
127
|
+
for backup in data.get("backups", []):
|
|
128
|
+
print(f"Backup: {backup}")
|
|
129
|
+
for conflict in data["conflicts"]:
|
|
130
|
+
print(f"jscdocs: {conflict}", file=sys.stderr)
|
|
131
|
+
if data.get("error"):
|
|
132
|
+
print(f"jscdocs: {data['error']}", file=sys.stderr)
|
|
133
|
+
for note in data["notes"]:
|
|
134
|
+
print(note)
|
|
135
|
+
return 130 if data.get("interrupted") else 0 if data["ok"] else 1
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
139
|
+
parser = build_parser()
|
|
140
|
+
args = parser.parse_args(argv)
|
|
141
|
+
if args.command is None:
|
|
142
|
+
parser.print_help(sys.stderr)
|
|
143
|
+
return 2
|
|
144
|
+
if args.command == "init":
|
|
145
|
+
return _init(args)
|
|
146
|
+
path = config.index_path()
|
|
147
|
+
|
|
148
|
+
if args.command == "sync":
|
|
149
|
+
return _sync(path, args.force)
|
|
150
|
+
|
|
151
|
+
try:
|
|
152
|
+
db = store.connect(path)
|
|
153
|
+
except store.IndexMissing as e:
|
|
154
|
+
print(f"{e}; run `jscdocs sync` first.", file=sys.stderr)
|
|
155
|
+
return 1
|
|
156
|
+
try:
|
|
157
|
+
if args.command == "search":
|
|
158
|
+
q = " ".join(args.query)
|
|
159
|
+
print(search.render_hits(db, search.search(db, q, args.system, args.limit), q))
|
|
160
|
+
elif args.command == "read":
|
|
161
|
+
print(search.render_read(search.read(db, args.ref, not args.no_subsections, args.offset)))
|
|
162
|
+
elif args.command == "toc":
|
|
163
|
+
print(search.render_toc(search.toc(db, args.system, args.depth)))
|
|
164
|
+
elif args.command == "eval":
|
|
165
|
+
try:
|
|
166
|
+
questions = evaluate.load(args.questions)
|
|
167
|
+
except (OSError, ValueError) as e:
|
|
168
|
+
print(f"Cannot use {args.questions}: {e}", file=sys.stderr)
|
|
169
|
+
return 1
|
|
170
|
+
print(evaluate.render(evaluate.run(db, questions), args.verbose))
|
|
171
|
+
elif args.command == "status":
|
|
172
|
+
last = sync.synced_at(path)
|
|
173
|
+
print(f"Index: {path}" + (f" (synced {last:%Y-%m-%d %H:%M} UTC)" if last else ""))
|
|
174
|
+
if (h := lock.holder(lock.path_for(path))) is not None:
|
|
175
|
+
print(f"A sync that died left its lock file; the next sync removes it ({h.describe()})"
|
|
176
|
+
if lock.stale(h) else f"A sync is running: {h.describe()}")
|
|
177
|
+
print(search.render_systems(search.systems(db)))
|
|
178
|
+
except (search.NotFound, sites.UnknownSystem) as e:
|
|
179
|
+
print(e, file=sys.stderr)
|
|
180
|
+
return 1
|
|
181
|
+
except sqlite3.Error as e:
|
|
182
|
+
print(f"The index at {path} cannot be read ({e}); run `jscdocs sync --force` to download it again.", file=sys.stderr)
|
|
183
|
+
return 1
|
|
184
|
+
finally:
|
|
185
|
+
db.close()
|
|
186
|
+
return 0
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
if __name__ == "__main__":
|
|
190
|
+
sys.exit(main())
|
jscdocs/core/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Everything about JSC's documentation sites and the local index. Front ends call this package only."""
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""The coding agents' own commands for registering an MCP server, which init prefers to editing their files."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Literal
|
|
9
|
+
|
|
10
|
+
from .agent_config import NAME, Agent, AgentConfig, InitError, ServerChange, absolute, normalized_entry
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def find_client(agent: Agent) -> Path | None:
|
|
14
|
+
found = shutil.which(agent)
|
|
15
|
+
return absolute(found) if found else None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class ClientCommand:
|
|
20
|
+
operation: Literal["add", "remove"]
|
|
21
|
+
argv: tuple[str, ...] = field(repr=False)
|
|
22
|
+
cwd: Path
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class RegistrationPlan:
|
|
27
|
+
backend: Literal["cli", "file"]
|
|
28
|
+
reason: str | None
|
|
29
|
+
client: Path | None
|
|
30
|
+
scope: str
|
|
31
|
+
commands: tuple[ClientCommand, ...] = ()
|
|
32
|
+
|
|
33
|
+
def as_dict(self) -> dict:
|
|
34
|
+
return {"backend": self.backend, "reason": self.reason,
|
|
35
|
+
"client": str(self.client) if self.client else None,
|
|
36
|
+
"operations": [{"server": NAME, "operation": command.operation, "scope": self.scope}
|
|
37
|
+
for command in self.commands]}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def plan_registration(adapter: AgentConfig, client: Path | None, selected: ServerChange,
|
|
41
|
+
project_root: Path | None) -> RegistrationPlan:
|
|
42
|
+
scope = "project" if project_root is not None else "user"
|
|
43
|
+
|
|
44
|
+
def fallback(reason):
|
|
45
|
+
return RegistrationPlan("file", reason, client, scope)
|
|
46
|
+
|
|
47
|
+
if client is None:
|
|
48
|
+
return fallback(f"{adapter.agent} executable is absent; native compatibility was not checked")
|
|
49
|
+
if selected.action not in ("added", "updated"):
|
|
50
|
+
return RegistrationPlan("cli", None, client, scope)
|
|
51
|
+
# Only a symlinked config file itself matters; symlinked parent directories (a linked $HOME) do not.
|
|
52
|
+
if adapter.path.is_symlink():
|
|
53
|
+
return fallback("native writer symlink preservation is unverified")
|
|
54
|
+
agent = adapter.agent
|
|
55
|
+
replacement = normalized_entry(agent, selected.replacement)
|
|
56
|
+
allowed = {"command", "args", "env"}
|
|
57
|
+
if agent != "claude":
|
|
58
|
+
allowed.add("enabled")
|
|
59
|
+
if agent in ("claude", "pi", "opencode"):
|
|
60
|
+
allowed.add("type")
|
|
61
|
+
if agent == "pi":
|
|
62
|
+
allowed.update(("cwd", "exposure", "description"))
|
|
63
|
+
if agent == "codex":
|
|
64
|
+
if project_root is not None:
|
|
65
|
+
return fallback("Codex CLI has no persistent project-scope writer")
|
|
66
|
+
if replacement.get("cwd") or replacement.get("env_vars"):
|
|
67
|
+
return fallback("Codex CLI cannot preserve cwd or forward environment variables by name")
|
|
68
|
+
if agent == "claude" and selected.existing is not None and (
|
|
69
|
+
selected.existing.get("url") or selected.existing.get("type", "stdio") != "stdio"):
|
|
70
|
+
return fallback("Claude remote removal may delete OAuth credentials")
|
|
71
|
+
if set(replacement) - allowed or replacement.get("enabled", True) is not True:
|
|
72
|
+
return fallback("native command cannot preserve all selected server fields")
|
|
73
|
+
if replacement.get("type", "stdio") != "stdio":
|
|
74
|
+
return fallback("native command cannot preserve this transport")
|
|
75
|
+
if agent == "pi" and (replacement.get("exposure", "codemode") not in ("codemode", "deferred", "direct", "hidden")
|
|
76
|
+
or "description" in replacement and not isinstance(replacement["description"], str)):
|
|
77
|
+
return fallback("pi CLI cannot preserve these server options")
|
|
78
|
+
if any(not key or "=" in key or "\0" in key or "\0" in value
|
|
79
|
+
for key, value in replacement.get("env", {}).items()):
|
|
80
|
+
return fallback("native command cannot preserve these environment values")
|
|
81
|
+
if not replacement.get("command"):
|
|
82
|
+
return fallback("native command requires a stdio command")
|
|
83
|
+
cwd = project_root if project_root is not None else Path.cwd()
|
|
84
|
+
if agent == "claude":
|
|
85
|
+
payload = {key: value for key, value in replacement.items() if key != "enabled"}
|
|
86
|
+
argv = (str(client), "mcp", "add-json", "-s", scope, NAME,
|
|
87
|
+
json.dumps(payload, ensure_ascii=False, allow_nan=False))
|
|
88
|
+
commands = []
|
|
89
|
+
if selected.existing is not None:
|
|
90
|
+
commands.append(ClientCommand("remove", (str(client), "mcp", "remove", "-s", scope, NAME), cwd))
|
|
91
|
+
commands.append(ClientCommand("add", argv, cwd))
|
|
92
|
+
else:
|
|
93
|
+
argv = [str(client), "mcp", "add", NAME]
|
|
94
|
+
if agent == "opencode" and project_root is None:
|
|
95
|
+
argv.append("--global") # opencode mcp add writes the project's config unless told otherwise
|
|
96
|
+
if agent == "pi":
|
|
97
|
+
if project_root is not None:
|
|
98
|
+
argv.append("--local")
|
|
99
|
+
for name in ("cwd", "exposure", "description"):
|
|
100
|
+
if name in replacement:
|
|
101
|
+
argv.extend([f"--{name}", replacement[name]])
|
|
102
|
+
for key, value in sorted(replacement.get("env", {}).items()):
|
|
103
|
+
argv.extend(["--env", f"{key}={value}"])
|
|
104
|
+
argv.extend(["--", replacement["command"], *replacement.get("args", [])])
|
|
105
|
+
commands = [ClientCommand("add", tuple(argv), cwd)]
|
|
106
|
+
return RegistrationPlan("cli", None, client, scope, tuple(commands))
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class ClientFailure(InitError):
|
|
110
|
+
def __init__(self, message: str, *, unknown: bool = True, interrupted: bool = False):
|
|
111
|
+
super().__init__(message)
|
|
112
|
+
self.unknown = unknown
|
|
113
|
+
self.interrupted = interrupted
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def run_client(agent: Agent, command: ClientCommand) -> None:
|
|
117
|
+
label = f"{agent} mcp {command.operation} {NAME}"
|
|
118
|
+
try:
|
|
119
|
+
result = subprocess.run(list(command.argv), cwd=command.cwd, stdin=subprocess.DEVNULL,
|
|
120
|
+
stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30,
|
|
121
|
+
check=False, shell=False)
|
|
122
|
+
except subprocess.TimeoutExpired:
|
|
123
|
+
raise ClientFailure(f"{label} timed out; registration state is unknown") from None
|
|
124
|
+
except KeyboardInterrupt:
|
|
125
|
+
raise ClientFailure(f"{label} interrupted; registration state is unknown", interrupted=True) from None
|
|
126
|
+
except ValueError:
|
|
127
|
+
raise ClientFailure(f"{label} has unsupported process arguments", unknown=False) from None
|
|
128
|
+
except OSError as error:
|
|
129
|
+
raise ClientFailure(f"{label} could not start (errno {error.errno})", unknown=False) from None
|
|
130
|
+
if result.returncode:
|
|
131
|
+
raise ClientFailure(f"{label} failed with exit code {result.returncode}; registration state is unknown")
|