Files
opencyber/scripts/generate-tool-docs.py
mitkox 8dd13cefdf Start OpenCyber 0.5.0 private beta
Reviewed source snapshot with MCP 2.x, bounded execution and durable approvals,
private beta onboarding, and immutable candidate qualification gates.

Signed-off-by: mitkox <[email protected]>
2026-10-26 00:24:46 +02:00

203 lines
7.6 KiB
Python

#!/usr/bin/env python3
"""Generate docs/TOOLS.md from the catalog, the contract registry, and the server.
The documentation must not drift from the code. This script is the only writer
of docs/TOOLS.md; ``--check`` fails CI when the committed file is stale.
"""
from __future__ import annotations
import argparse
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
sys.path.insert(0, str(ROOT / "scripts"))
from lib.generated import StaleGeneratedFile, ensure_generated_file # noqa: E402
from opencyber import __version__ # noqa: E402
from opencyber.catalog import CATALOG, HARDWARE_CATEGORIES, category_counts # noqa: E402
from opencyber.catalog_identity import load_manifest # noqa: E402
from opencyber.contracts import CONTRACTS, native_groups # noqa: E402
OUTPUT = ROOT / "docs" / "TOOLS.md"
GENERATE_COMMAND = "make docs-tools"
def _native_descriptions() -> dict[str, str]:
"""Read native descriptions from the registration that advertises them."""
from opencyber.server import mcp
return {
name: (getattr(tool, "description", "") or "")
for name, tool in mcp._tool_manager._tools.items()
}
def _distribution(entries: list[str]) -> str:
return ", ".join(f"`{entry}`" for entry in sorted(set(entries))) or "none"
def render() -> str:
counts = category_counts()
native_groups_map = native_groups()
fixed_total = len(CONTRACTS) - len(CATALOG)
manifest = load_manifest()
digest = (manifest or {}).get("catalog_sha256") or "not recorded"
shapes = [CONTRACTS[name].shape.value for name in CONTRACTS]
effects = [effect.value for contract in CONTRACTS.values() for effect in contract.effects]
descriptions = _native_descriptions()
lines = [
"<!-- Generated by scripts/generate-tool-docs.py. Do not edit by hand. -->",
"",
"# Tool reference",
"",
f"OpenCyber Harness {__version__} exposes **{len(CATALOG) + fixed_total} MCP tools**:",
f"{len(CATALOG)} executable-backed tools and {fixed_total} native tools.",
"",
f"Contract digest: `{digest}`. A running server reports the digest it",
"actually advertises with `oc_catalog`, so a stale container or a modified",
"registration is detectable. Pass `expected_catalog_digest` to `oc_catalog`",
"to pin the contract a client was built against.",
"",
"Every tool returns the envelope documented in [CONTRACTS.md](CONTRACTS.md):",
"`ok`, `contract`, `coverage`, `limitations`, `provenance`, and an `evidence`",
"digest. Refusals carry a registered `error` object instead of a transport",
"error; see [ERRORS.md](ERRORS.md) and [LIMITS.md](LIMITS.md).",
"",
"Regenerate after changing `src/opencyber/catalog.py`, the contract registry,",
"or a tool registration:",
"",
"```sh",
"make docs-tools",
"```",
"",
"In full mode every tool is advertised individually. Compact mode",
"(`OPENCYBER_MCP_MODE=compact`) advertises the native tools and dispatches",
"executable tools through `oc_execute`. `OPENCYBER_TOOL_CATEGORIES` narrows",
"the advertised executable set; it has no effect in compact mode.",
"",
"## Contract summary",
"",
"| Task shape | Tools |",
"| --- | ---: |",
]
for shape in sorted(set(shapes)):
lines.append(f"| `{shape}` | {shapes.count(shape)} |")
lines.extend(["", "| Effect | Tools |", "| --- | ---: |"])
for effect in sorted(set(effects)):
lines.append(f"| `{effect}` | {effects.count(effect)} |")
lines.extend(
[
"",
"## Executable-backed tools",
"",
"These tools share one schema: `engagement_id`, `arguments` (an explicit",
"argv list), `working_directory`, and `stdin`. They never invoke a shell.",
"Every call runs under a named deadline and per-stream output cap; see",
"`OPENCYBER_TOOL_TIMEOUT_S` and `OPENCYBER_TOOL_MAX_OUTPUT_BYTES` in",
"[CONFIGURATION.md](CONFIGURATION.md).",
"",
"| Category | Tools |",
"| --- | ---: |",
]
)
for category, count in counts.items():
marker = " (hardware)" if category in HARDWARE_CATEGORIES else ""
lines.append(f"| {category}{marker} | {count} |")
lines.extend(["", f"**Total: {len(CATALOG)}**", ""])
for category in sorted(counts):
lines.extend(
[
f"### {category}",
"",
"| Tool | Executable | Description |",
"| --- | --- | --- |",
]
)
for spec in sorted((item for item in CATALOG if item.category == category), key=lambda item: item.name):
description = spec.description.replace("|", "\\|")
lines.append(f"| `{spec.name}` | `{spec.executable}` | {description} |")
lines.append("")
lines.extend(
[
"## Native tools",
"",
"These tools are implemented in Python. Offline PCAP triage invokes tshark",
"with fixed arguments; other native capabilities may also invoke their",
"documented helper programs.",
"",
"| Group | Tools |",
"| --- | ---: |",
]
)
for group, names in native_groups_map.items():
lines.append(f"| {group} | {len(names)} |")
lines.extend(["", f"**Total: {fixed_total}**", ""])
for group, names in native_groups_map.items():
lines.extend(
[
f"### {group}",
"",
"| Tool | Shape | Effects | Scope | Description |",
"| --- | --- | --- | --- | --- |",
]
)
for name in names:
contract = CONTRACTS[name]
description = descriptions.get(name, "").replace("|", "\\|")
lines.append(
f"| `{name}` | {contract.shape.value} | "
f"{_distribution([effect.value for effect in contract.effects])} | "
f"{contract.scope.value} | {description} |"
)
lines.append("")
lines.extend(
[
"## Exact contracts",
"",
"This page lists names, executables, descriptions, and declared authority.",
"For live JSON schemas, call `oc_catalog(include_contracts=true)` or run:",
"",
"```sh",
"docker exec opencyber opencyber-mcp --catalog-json",
"```",
"",
"`--catalog-json` exports the executable-backed catalog. The complete",
"advertised contract, including native input and output schemas, is",
"recorded in `src/opencyber/data/catalog.json`.",
"",
]
)
return "\n".join(lines)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true", help="fail if docs/TOOLS.md is stale")
parser.add_argument("--output", type=Path, default=OUTPUT, help="write to this path")
args = parser.parse_args()
rendered = render()
try:
wrote = ensure_generated_file(args.output, rendered, check=args.check, generate_command=GENERATE_COMMAND)
except StaleGeneratedFile as error:
print(str(error), file=sys.stderr)
return 1
if args.check:
print(f"{args.output.relative_to(ROOT)} is current")
else:
print(f"{'wrote' if wrote else 'unchanged'} {args.output.relative_to(ROOT)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())