jscdocs 0.2.0__tar.gz

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.
@@ -0,0 +1,15 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ .pytest_cache/
7
+ .ruff_cache/
8
+ .venv/
9
+
10
+ # Local planning notes
11
+ docs/design.md
12
+ zenv.json
13
+
14
+ # macOS Finder metadata
15
+ .DS_Store
jscdocs-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
jscdocs-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.5
2
+ Name: jscdocs
3
+ Version: 0.2.0
4
+ Summary: Search and read the JSC supercomputer user documentation from AI agents: an MCP server and CLI for JURECA, JUWELS, JUSUF, JUPITER, JEDI and JUDAC
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Keywords: ai-agents,documentation,hpc,jupiter,jureca,jusuf,juwels,mcp
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Environment :: Console
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Operating System :: POSIX
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Documentation
16
+ Requires-Python: >=3.12
17
+ Requires-Dist: beautifulsoup4>=4.12
18
+ Requires-Dist: mcp<3,>=2.3
19
+ Requires-Dist: tomlkit<1,>=0.13
20
+ Description-Content-Type: text/markdown
21
+
22
+ # jscdocs
23
+
24
+ jscdocs lets AI agents search and read the user documentation of the JSC supercomputers JURECA, JUWELS, JUSUF, JUPITER, JEDI and JUDAC. It keeps a local index of the documentation at [apps.fz-juelich.de/jsc/hps](https://apps.fz-juelich.de/jsc/hps/jureca/) and serves it through an MCP server (`jscdocs-mcp`) and a command-line tool (`jscdocs`). This page is for people who want to use it with Claude Code or another MCP client.
25
+
26
+ An agent with jscdocs answers questions such as "what is the maximum walltime of JURECA's `dc-gpu` partition?" from the official documentation of that system, and cites the section it used.
27
+
28
+ ## Install
29
+
30
+ jscdocs needs Python 3.12 or later. Install it from a clone of this repository:
31
+
32
+ ```sh
33
+ pip install . # or: uv tool install .
34
+ ```
35
+
36
+ Then get the index once:
37
+
38
+ ```sh
39
+ jscdocs sync
40
+ ```
41
+
42
+ This downloads the index that this project builds from the documentation every week, a file of about 1.5 MB. It takes a few seconds. jscdocs itself never fetches the documentation sites: the published index is the only source, so `jscdocs sync` needs to reach `gitlab.jsc.fz-juelich.de`.
43
+
44
+ ## Register the server with your coding agent
45
+
46
+ `jscdocs init` registers the MCP server with Claude Code, Codex, pi or OpenCode, for all your projects. Restart the agent afterwards:
47
+
48
+ ```sh
49
+ jscdocs init claude
50
+ jscdocs init codex --dry-run # show what would change
51
+ jscdocs init pi --index $PROJECT/$USER/jscdocs/index.sqlite
52
+ jscdocs init opencode --project # in the current project only, as a file others can share
53
+ ```
54
+
55
+ Init uses the agent's own `mcp add` command where that can write the whole entry, and edits the agent's configuration file otherwise. It keeps your other servers and settings, and it never starts the server or downloads anything. [docs/init.md](docs/init.md) describes the options, the files it writes and how it handles entries you edited.
56
+
57
+ In Claude Code the tools appear as `mcp__jscdocs__search_docs`, `mcp__jscdocs__read_docs` and `mcp__jscdocs__list_docs`. Any other MCP client, such as Cursor or your own agent, starts `jscdocs-mcp` as a stdio server, for example with `claude mcp add --scope user jscdocs -- jscdocs-mcp` in Claude Code.
58
+
59
+ | Tool | What it does |
60
+ |---|---|
61
+ | `search_docs` | Finds sections for a query, optionally on one system, with snippets and section URLs |
62
+ | `read_docs` | Reads a section (`jureca/batchsystem#internet-access`), a whole page, or a URL from a search, as Markdown |
63
+ | `list_docs` | Lists the indexed systems, or one system's table of contents |
64
+
65
+ All three tools only read the index. The server tells the agent to pass the system a question is about, to cite section URLs, and to treat the documentation as data, not as instructions.
66
+
67
+ ## Keeping the index current
68
+
69
+ The server keeps the index current by itself. When it starts, and on tool calls at most every ten minutes, it checks the index's age. If the index is missing or more than seven days old, the server syncs it in the background, as `jscdocs sync` does, and keeps answering from the old index meanwhile. Results carry the date on which the documentation was fetched and warn when the index is more than two weeks old.
70
+
71
+ A sync asks for the published index, and what it does next depends on the answer:
72
+
73
+ | The published index | What the sync does |
74
+ |---|---|
75
+ | Is newer than the local index | Downloads it and replaces the local index |
76
+ | Is not newer | Nothing. The server asks again an hour later |
77
+ | Cannot be downloaded | Keeps the local index, if there is one, and says why. The server tries again an hour later |
78
+
79
+ A download is tried twice at most, and each try waits at most ten seconds for the server. A sync that cannot succeed therefore fails within seconds when the server refuses the connection or reports an error, and after about 20 seconds when the server does not answer at all. Without a local index, the tools then tell the agent that the index could not be downloaded and why.
80
+
81
+ A lock file next to the index (`index.sqlite.lock`) lets only one process replace it at a time, so several sessions, or several login nodes sharing one index, do not download it several times.
82
+
83
+ To sync by hand, run:
84
+
85
+ ```sh
86
+ jscdocs sync # download the published index if it is newer
87
+ jscdocs sync --force # download it in any case, to replace an index that is damaged
88
+ ```
89
+
90
+ ## Command line
91
+
92
+ The CLI gives the same answers as the tools:
93
+
94
+ ```sh
95
+ jscdocs search "scratch quota" --system juwels
96
+ jscdocs read jureca/batchsystem#internet-access
97
+ jscdocs toc jupiter
98
+ jscdocs status # index location, sync time, systems
99
+ ```
100
+
101
+ ## Configuration
102
+
103
+ | Variable | Default | Meaning |
104
+ |---|---|---|
105
+ | `JSCDOCS_INDEX` | `~/.cache/jscdocs/index.sqlite` | Where the index lives |
106
+ | `JSCDOCS_REFRESH_HOURS` | `168` (seven days) | Index age after which the server syncs it; `0` turns automatic syncs off (as does `jscdocs-mcp --no-refresh`) |
107
+ | `JSCDOCS_INDEX_URL` | This project's package registry on JSC's GitLab | Where the published index is downloaded from, for a mirror or a fork that publishes its own |
108
+
109
+ ## On the JSC clusters
110
+
111
+ jscdocs runs on the login nodes as it does on a laptop. `$HOME` is small and shared across the systems, so consider pointing `JSCDOCS_INDEX` at a project directory and using that one index from every login node:
112
+
113
+ ```sh
114
+ export JSCDOCS_INDEX=$PROJECT/$USER/jscdocs/index.sqlite
115
+ ```
116
+
117
+ Compute nodes have no internet access on most partitions. The tools work there from an existing index, but the server cannot refresh it.
118
+
119
+ ## Search quality
120
+
121
+ `jscdocs eval tests/eval/questions.toml` scores search against questions with known answers. The index uses keyword search (SQLite FTS5 with BM25). It finds the right page in the top three results for about nine in ten questions. It misses questions phrased in words the documentation does not use, such as "VS Code" for "VSCode", so the server asks the agent to rephrase in the documentation's terms when results do not fit.
122
+
123
+ ## Licence
124
+
125
+ The code is MIT-licensed. The JSC documentation it indexes is licensed [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) by the system administrators at Forschungszentrum Juelich.
126
+
127
+ The Python package contains no documentation. The index does: it holds the documentation's text, converted to Markdown and split into sections. An index is therefore under CC BY-NC-SA 4.0 and not under the MIT licence. The published index names the licence and the source in its manifest, every index names them in its `meta` table, and every result names its source page. Keep the attribution when you quote the documentation or pass an index on, share it only under the same licence, and do not use it commercially.
@@ -0,0 +1,106 @@
1
+ # jscdocs
2
+
3
+ jscdocs lets AI agents search and read the user documentation of the JSC supercomputers JURECA, JUWELS, JUSUF, JUPITER, JEDI and JUDAC. It keeps a local index of the documentation at [apps.fz-juelich.de/jsc/hps](https://apps.fz-juelich.de/jsc/hps/jureca/) and serves it through an MCP server (`jscdocs-mcp`) and a command-line tool (`jscdocs`). This page is for people who want to use it with Claude Code or another MCP client.
4
+
5
+ An agent with jscdocs answers questions such as "what is the maximum walltime of JURECA's `dc-gpu` partition?" from the official documentation of that system, and cites the section it used.
6
+
7
+ ## Install
8
+
9
+ jscdocs needs Python 3.12 or later. Install it from a clone of this repository:
10
+
11
+ ```sh
12
+ pip install . # or: uv tool install .
13
+ ```
14
+
15
+ Then get the index once:
16
+
17
+ ```sh
18
+ jscdocs sync
19
+ ```
20
+
21
+ This downloads the index that this project builds from the documentation every week, a file of about 1.5 MB. It takes a few seconds. jscdocs itself never fetches the documentation sites: the published index is the only source, so `jscdocs sync` needs to reach `gitlab.jsc.fz-juelich.de`.
22
+
23
+ ## Register the server with your coding agent
24
+
25
+ `jscdocs init` registers the MCP server with Claude Code, Codex, pi or OpenCode, for all your projects. Restart the agent afterwards:
26
+
27
+ ```sh
28
+ jscdocs init claude
29
+ jscdocs init codex --dry-run # show what would change
30
+ jscdocs init pi --index $PROJECT/$USER/jscdocs/index.sqlite
31
+ jscdocs init opencode --project # in the current project only, as a file others can share
32
+ ```
33
+
34
+ Init uses the agent's own `mcp add` command where that can write the whole entry, and edits the agent's configuration file otherwise. It keeps your other servers and settings, and it never starts the server or downloads anything. [docs/init.md](docs/init.md) describes the options, the files it writes and how it handles entries you edited.
35
+
36
+ In Claude Code the tools appear as `mcp__jscdocs__search_docs`, `mcp__jscdocs__read_docs` and `mcp__jscdocs__list_docs`. Any other MCP client, such as Cursor or your own agent, starts `jscdocs-mcp` as a stdio server, for example with `claude mcp add --scope user jscdocs -- jscdocs-mcp` in Claude Code.
37
+
38
+ | Tool | What it does |
39
+ |---|---|
40
+ | `search_docs` | Finds sections for a query, optionally on one system, with snippets and section URLs |
41
+ | `read_docs` | Reads a section (`jureca/batchsystem#internet-access`), a whole page, or a URL from a search, as Markdown |
42
+ | `list_docs` | Lists the indexed systems, or one system's table of contents |
43
+
44
+ All three tools only read the index. The server tells the agent to pass the system a question is about, to cite section URLs, and to treat the documentation as data, not as instructions.
45
+
46
+ ## Keeping the index current
47
+
48
+ The server keeps the index current by itself. When it starts, and on tool calls at most every ten minutes, it checks the index's age. If the index is missing or more than seven days old, the server syncs it in the background, as `jscdocs sync` does, and keeps answering from the old index meanwhile. Results carry the date on which the documentation was fetched and warn when the index is more than two weeks old.
49
+
50
+ A sync asks for the published index, and what it does next depends on the answer:
51
+
52
+ | The published index | What the sync does |
53
+ |---|---|
54
+ | Is newer than the local index | Downloads it and replaces the local index |
55
+ | Is not newer | Nothing. The server asks again an hour later |
56
+ | Cannot be downloaded | Keeps the local index, if there is one, and says why. The server tries again an hour later |
57
+
58
+ A download is tried twice at most, and each try waits at most ten seconds for the server. A sync that cannot succeed therefore fails within seconds when the server refuses the connection or reports an error, and after about 20 seconds when the server does not answer at all. Without a local index, the tools then tell the agent that the index could not be downloaded and why.
59
+
60
+ A lock file next to the index (`index.sqlite.lock`) lets only one process replace it at a time, so several sessions, or several login nodes sharing one index, do not download it several times.
61
+
62
+ To sync by hand, run:
63
+
64
+ ```sh
65
+ jscdocs sync # download the published index if it is newer
66
+ jscdocs sync --force # download it in any case, to replace an index that is damaged
67
+ ```
68
+
69
+ ## Command line
70
+
71
+ The CLI gives the same answers as the tools:
72
+
73
+ ```sh
74
+ jscdocs search "scratch quota" --system juwels
75
+ jscdocs read jureca/batchsystem#internet-access
76
+ jscdocs toc jupiter
77
+ jscdocs status # index location, sync time, systems
78
+ ```
79
+
80
+ ## Configuration
81
+
82
+ | Variable | Default | Meaning |
83
+ |---|---|---|
84
+ | `JSCDOCS_INDEX` | `~/.cache/jscdocs/index.sqlite` | Where the index lives |
85
+ | `JSCDOCS_REFRESH_HOURS` | `168` (seven days) | Index age after which the server syncs it; `0` turns automatic syncs off (as does `jscdocs-mcp --no-refresh`) |
86
+ | `JSCDOCS_INDEX_URL` | This project's package registry on JSC's GitLab | Where the published index is downloaded from, for a mirror or a fork that publishes its own |
87
+
88
+ ## On the JSC clusters
89
+
90
+ jscdocs runs on the login nodes as it does on a laptop. `$HOME` is small and shared across the systems, so consider pointing `JSCDOCS_INDEX` at a project directory and using that one index from every login node:
91
+
92
+ ```sh
93
+ export JSCDOCS_INDEX=$PROJECT/$USER/jscdocs/index.sqlite
94
+ ```
95
+
96
+ Compute nodes have no internet access on most partitions. The tools work there from an existing index, but the server cannot refresh it.
97
+
98
+ ## Search quality
99
+
100
+ `jscdocs eval tests/eval/questions.toml` scores search against questions with known answers. The index uses keyword search (SQLite FTS5 with BM25). It finds the right page in the top three results for about nine in ten questions. It misses questions phrased in words the documentation does not use, such as "VS Code" for "VSCode", so the server asks the agent to rephrase in the documentation's terms when results do not fit.
101
+
102
+ ## Licence
103
+
104
+ The code is MIT-licensed. The JSC documentation it indexes is licensed [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) by the system administrators at Forschungszentrum Juelich.
105
+
106
+ The Python package contains no documentation. The index does: it holds the documentation's text, converted to Markdown and split into sections. An index is therefore under CC BY-NC-SA 4.0 and not under the MIT licence. The published index names the licence and the source in its manifest, every index names them in its `meta` table, and every result names its source page. Keep the attribution when you quote the documentation or pass an index on, share it only under the same licence, and do not use it commercially.
@@ -0,0 +1,42 @@
1
+ [project]
2
+ name = "jscdocs"
3
+ version = "0.2.0"
4
+ description = "Search and read the JSC supercomputer user documentation from AI agents: an MCP server and CLI for JURECA, JUWELS, JUSUF, JUPITER, JEDI and JUDAC"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.12"
9
+ dependencies = ["beautifulsoup4>=4.12", "mcp>=2.3,<3", "tomlkit>=0.13,<1"]
10
+ keywords = ["mcp", "hpc", "documentation", "ai-agents", "jureca", "juwels", "jusuf", "jupiter"]
11
+ classifiers = [
12
+ "Development Status :: 3 - Alpha",
13
+ "Environment :: Console",
14
+ "Intended Audience :: Science/Research",
15
+ "Operating System :: POSIX",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Topic :: Documentation",
20
+ ]
21
+
22
+ [project.scripts]
23
+ jscdocs = "jscdocs.cli:main"
24
+ jscdocs-mcp = "jscdocs.mcp.server:main"
25
+
26
+ [build-system]
27
+ requires = ["hatchling"]
28
+ build-backend = "hatchling.build"
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["src/jscdocs"]
32
+
33
+ [tool.hatch.build.targets.sdist]
34
+ # Code, licence and README only. tests/fixtures hold JSC documentation (CC BY-NC-SA 4.0), which the package must
35
+ # not contain; an installation downloads the published index, which carries that licence.
36
+ include = ["/src/jscdocs", "/README.md", "/LICENSE", "/pyproject.toml"] # rooted: a bare README.md matches at any depth
37
+ exclude = [".zenv"] # the local environment; its packages' LICENSE files would match license-files
38
+
39
+ [dependency-groups]
40
+ dev = [
41
+ "pytest>=9",
42
+ ]
@@ -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"
@@ -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())
@@ -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())
@@ -0,0 +1 @@
1
+ """Everything about JSC's documentation sites and the local index. Front ends call this package only."""