wikihub.py¶
clew/mcp_server/wikihub.py
The wiki hub: an opt-in HTTP thread inside the MCP server (round 3, P4c).
_build
None clew.mcp_server.wikihub.WikiHub._build(self, Target target)
Run one build, then the next queued one.
clew/mcp_server/wikihub.py:327
Source · 25 lines
def _build(self, target: Target) -> None:
"""A FAILED BUILD IS A STATE with its reason, never a crash of the hub.
@brief Build.
@return None.
"""
try:
self.builder(target, self.site_dir(target).parent)
outcome = "built"
self.errors.pop(target.slug, None)
self.publish({"type": "rebuilt", "slug": target.slug})
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
logger.error("wiki build for %s failed: %s", target.slug, exc)
self.errors[target.slug] = str(exc)
outcome = "failed"
with self._lock:
self.state[target.slug] = outcome
queued = next((s for s, v in self.state.items() if v == "queued"), None)
nxt = self.find(queued) if queued else None
if nxt is not None:
with self._lock:
self.state.pop(nxt.slug, None)
self.request_build(nxt)
Activity · 17 steps
Flows
_traced
dict[str, Any] clew.mcp_server.wikihub._traced(Target target, str nodeid)
One test of a target, run traced, with its overlay on the expected flow.
clew/mcp_server/wikihub.py:670
Source · 12 lines
def _traced(target: Target, nodeid: str) -> dict[str, Any]:
"""@brief Traced run. @return Result."""
from ..wiki.command import expected_steps
from ..wiki.tracerun import overlay, trace_test
run = trace_test(Path(target.repo_path), nodeid)
steps = expected_steps(Path(target.db_path), Path(target.repo_path), nodeid)
out = {k: run[k] for k in ("passed", "checkpoints", "failure", "dropped")}
out["overlay"] = overlay(steps, run["otlp"])
return out
Activity · 7 steps
Requirements
attach
None clew.mcp_server.wikihub.attach(Any state, WikiHub|None hub)
Attach the hub to the server's tools and refresh loop, or detach it.
clew/mcp_server/wikihub.py:908
Source · 8 lines
def attach(state: Any, hub: WikiHub | None) -> None:
"""@brief Attach. @return None."""
if not hasattr(state, "tools"):
return
state.wiki_hub = hub
state.tools.wiki_linker = hub.link if hub is not None else None
Activity · 4 steps
Requirements
build_in_subprocess
Path clew.mcp_server.wikihub.build_in_subprocess(Target target, Path out)
Build one target's wiki in a subprocess.
Source · 28 lines
def build_in_subprocess(target: Target, out: Path) -> Path:
"""A SUBPROCESS, so Sphinx's imports, memory and time never land on the MCP event loop, and
its output — which goes to its own pipes — can never reach this process's stdout.
@brief Build a wiki.
@return Site directory.
"""
argv = [
sys.executable,
"-m",
"clew",
"wiki",
"build",
"--index",
target.db_path,
"--repo-root",
target.repo_path,
"--out",
str(out),
]
done = subprocess.run(argv, capture_output=True, text=True, timeout=_BUILD_TIMEOUT, check=False)
if done.returncode != 0:
raise RuntimeError(
(done.stderr or done.stdout).strip()[-2000:] or f"exit {done.returncode}"
)
return out / "html"
Activity · 5 steps
Requirements
do_POST
None clew.mcp_server.wikihub._HubHandler.do_POST(self)
Accept a comment from a served page (2.1).
clew/mcp_server/wikihub.py:394
Source · 16 lines
def do_POST(self) -> None: # noqa: N802 — the http.server spelling
"""THE SAME DOOR AS EVERY PAGE, plus what a write needs: the session cookie (a POST never
carries `?t=`), JSON only — a cross-site form cannot send it without a preflight the hub
never answers — the hub's own origin when the browser sends one, and a size cap read from
the header before any byte of the body. 2.1, owner Q/A 2026-11-24.
@brief POST.
@return None.
"""
refusal = self._post_refusal()
if refusal is not None:
self._json(refusal[0], {"error": refusal[1]})
return
slug = unquote(urlsplit(self.path).path)[len("/api/") : -len("/comment")]
self._comment(slug)
Activity · 6 steps
Requirements
find
Target | None clew.mcp_server.wikihub.WikiHub.find(self, str slug)
The target with a slug, or None.
clew/mcp_server/wikihub.py:302
Source · 4 lines
def find(self, slug: str) -> Target | None:
"""@brief Look up. @return Target."""
return next((t for t in TargetRegistry(self.home).targets() if t.slug == slug), None)
Activity · 1 steps
Flows
link
str | None clew.mcp_server.wikihub._Live.link(self, str repo_path, str name, str rel)
The hub URL of a function's symbol section, announcing it to open pages.
clew/mcp_server/wikihub.py:164
Source · 24 lines
def link(self, repo_path: str, name: str, rel: str) -> str | None:
"""NO TOKEN IN THE URL: it lands in the model's context and in transcripts; the browser
that opened the hub holds the session cookie.
@brief Link a symbol.
@return URL or None.
"""
from ..wiki.symbols import symbol_href
target = next(
(
t
for t in TargetRegistry(self.home).targets() # type: ignore[attr-defined]
if t.repo_path == str(repo_path) and t.name is None
),
None,
)
if target is None:
return None
url = f"http://{self.host}:{self.port}/r/{target.slug}/{symbol_href(name, rel)}"
self.publish({"type": "focus", "slug": target.slug, "url": url})
return url
Activity · 7 steps
Requirements
publish
None clew.mcp_server.wikihub._Live.publish(self, dict event)
Send an event to every open page.
clew/mcp_server/wikihub.py:113
Source · 5 lines
def publish(self, event: dict) -> None:
"""@brief Broadcast. @return None."""
for subscriber in list(self._subscribers):
subscriber.put(event)
Activity · 2 steps
Requirements
Flows
read_wiki_file
str clew.mcp_server.wikihub.read_wiki_file(TargetRegistry registry, str slug, str rel)
One file of a registered target's built wiki, as text — or a sentence saying why not.
clew/mcp_server/wikihub.py:933
Source · 24 lines
def read_wiki_file(registry: TargetRegistry, slug: str, rel: str) -> str:
"""CONFINED to the site, and NEVER EMPTY: an unknown slug, an unbuilt wiki or a missing file
each says so, because an empty resource reads as "nothing here".
@brief Read a wiki file.
@return Text.
"""
target = next((t for t in registry.targets() if t.slug == slug), None)
if target is None:
return f"No indexed repository has the slug {slug!r}; index(action='targets') lists them."
site = wiki_site_dir(target).resolve()
wanted = (site / rel).resolve()
if not wanted.is_relative_to(site):
return f"{rel!r} is outside the wiki."
if not (site / "index.html").is_file() and not wanted.is_file():
return (
f"The wiki of {slug} is not built. Open it on the wiki hub (CLEW_WIKI=1) or run "
f"`clew wiki build --repo-root {target.repo_path}`."
)
if not wanted.is_file():
return f"The wiki of {slug} has no {rel!r}."
return wanted.read_text(encoding="utf-8", errors="replace")
Activity · 12 steps
Requirements
Flows
refreshed
None clew.mcp_server.wikihub._Live.refreshed(self, list[str] slugs)
Rebuild the built wikis of targets the refresh loop just refreshed.
clew/mcp_server/wikihub.py:143
Source · 14 lines
def refreshed(self, slugs: list[str]) -> None:
"""A WIKI NOBODY HAS OPENED IS NOT BUILT on a refresh: only one already built is kept
current, and its open pages are told when the new one is ready.
@brief Rebuild after a refresh.
@return None.
"""
for slug in slugs:
target = self.find(slug) # type: ignore[attr-defined]
if target is None or not Path(target.repo_path).is_dir():
continue
if (self.site_dir(target) / "index.html").is_file(): # type: ignore[attr-defined]
self.request_build(target) # type: ignore[attr-defined]
Activity · 6 steps
Requirements
request_build
None clew.mcp_server.wikihub.WikiHub.request_build(self, Target target)
Start a build for a target unless one is running; one build at a time.
clew/mcp_server/wikihub.py:311
Source · 10 lines
def request_build(self, target: Target) -> None:
"""@brief Build on demand. @return None."""
with self._lock:
if "building" in self.state.values():
if self.state.get(target.slug) != "building":
self.state.setdefault(target.slug, "queued")
return
self.state[target.slug] = "building"
threading.Thread(target=self._build, args=(target,), daemon=True).start()
Activity · 7 steps
Requirements
site_dir
Path clew.mcp_server.wikihub.WikiHub.site_dir(self, Target target)
A target's site directory (built or not).
clew/mcp_server/wikihub.py:284
Source · 4 lines
def site_dir(self, target: Target) -> Path:
"""@brief Site directory. @return Path."""
return wiki_site_dir(target)
Activity · 1 steps
Flows
start
None clew.mcp_server.wikihub.WikiHub.start(self)
Start listening on a daemon thread.
clew/mcp_server/wikihub.py:229
Source · 16 lines
def start(self) -> None:
"""@brief Start. @return None."""
hub = self
class _Handler(_HubHandler):
owner = hub
self._server = ThreadingHTTPServer((self.host, 0), _Handler)
self._server.daemon_threads = True
self.port = int(self._server.server_address[1])
self._thread = threading.Thread(
target=self._server.serve_forever, name="clew-wiki-hub", daemon=True
)
self._thread.start()
logger.info("clew wiki hub listening on %s:%d", self.host, self.port)
Activity · 8 steps
Requirements
start_if_enabled
WikiHub | None clew.mcp_server.wikihub.start_if_enabled(Path home)
Start the hub when CLEW_WIKI=1 , recording its URL under the state root.
clew/mcp_server/wikihub.py:868
Source · 20 lines
def start_if_enabled(home: Path) -> WikiHub | None:
"""THE URL IS RECORDED so `clew wiki open` (and the person) can find the running hub; the file
is CREATED private to the user (0600) — never written and then narrowed — because the URL
carries the token.
@brief Maybe start the hub.
@return Hub or None.
"""
if os.environ.get(WIKI_ENV) != "1":
return None
hub = WikiHub(home)
hub.start()
record = Path(home) / WIKI_RECORD
record.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(record, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as out:
out.write(json.dumps({"url": hub.url, "pid": os.getpid()}))
return hub
Activity · 10 steps
Requirements
stop
None clew.mcp_server.wikihub.WikiHub.stop(self)
Stop listening, ending every open event stream.
clew/mcp_server/wikihub.py:250
Source · 10 lines
def stop(self) -> None:
"""@brief Stop. @return None."""
for subscriber in list(self._subscribers):
subscriber.put(None)
if self._server is not None:
self._server.shutdown()
self._server.server_close()
self._server = None
logger.info("clew wiki hub stopped")
Activity · 7 steps
None clew.mcp_server.wikihub.stop(WikiHub|None hub, Path home)
Stop the hub and remove its URL record.
clew/mcp_server/wikihub.py:894
Source · 8 lines
def stop(hub: WikiHub | None, home: Path) -> None:
"""@brief Stop. @return None."""
if hub is None:
return
hub.stop()
(Path(home) / WIKI_RECORD).unlink(missing_ok=True)
Activity · 4 steps
Requirements
wiki_site_dir
Path clew.mcp_server.wikihub.wiki_site_dir(Target target)
Where a target's built wiki lives: beside its index.
clew/mcp_server/wikihub.py:921
Source · 5 lines
def wiki_site_dir(target: Target) -> Path:
"""@brief Site directory. @return Path."""
return Path(target.db_path).parent / "wiki" / "html"