diff --git a/.gitignore b/.gitignore index 48b835e..80a7c32 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,11 @@ dist/ .coverage coverage.xml htmlcov/ + +# Generated by deploy/fleet/fleet.py β€” indexes.yml is the source of truth. +deploy/fleet/docker-compose.generated.yml +deploy/fleet/caddy/ +deploy/fleet/nginx/ +# Per-deployment config: hostnames, which indexes this host serves, whether auth +# is on. Copy indexes.example.yml to start. +deploy/fleet/indexes.yml diff --git a/README.md b/README.md index 932a2ab..09db139 100644 --- a/README.md +++ b/README.md @@ -243,7 +243,8 @@ building legal, marketing, support, or other specialized agents on Open Index. ## Using the brain from a cloud agent (production) -πŸ“– **[Full deployment guide β†’ `docs/deployment.md`](./docs/deployment.md)** β€” local, +πŸ“– **[Full deployment guide β†’ `docs/deployment.md`](./docs/deployment.md)** Β· +**[Many indexes on one host β†’ `docs/multi-index.md`](./docs/multi-index.md)** β€” local, remote (with and without Docker), TLS/proxying, and exactly what to paste into Claude Code, Claude Desktop, or Cursor. diff --git a/deploy/fleet/fleet.py b/deploy/fleet/fleet.py new file mode 100755 index 0000000..7cf073f --- /dev/null +++ b/deploy/fleet/fleet.py @@ -0,0 +1,552 @@ +#!/usr/bin/env python3 +"""Run several open-index brains on one host, behind one Caddy. + +Each index gets its own brain container (its own doc_types, entities, token and +read/write policy) but they all share one OpenSearch cluster, with one cluster +index per brain. That sharing is the point: the cluster is the expensive part +(~1GB), so adding an index costs ~250MB rather than another cluster. + +Caddy maps // to that brain, terminates TLS, and serves each index's UI + //mcp + +Commands: + ./fleet.py up render config, create missing brains, start + ./fleet.py add append an index to indexes.yml, then up + ./fleet.py tokens print connection details for every index + ./fleet.py render write the generated files without starting + ./fleet.py status what is running + ./fleet.py logs [name] tail logs + +Everything is regenerated from indexes.yml, so that file is the source of +truth β€” edit it rather than the generated compose/Caddy config. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import secrets +import shutil +import subprocess +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +REPO = HERE.parent.parent +CONFIG = HERE / "indexes.yml" +COMPOSE = HERE / "docker-compose.generated.yml" +CADDY_DIR = HERE / "caddy" +CADDY_FILE = CADDY_DIR / "Caddyfile" +ENV_FILE = HERE / ".env" + +# The uid the container runs as (see Dockerfile). Bind-mounted brain directories +# must be writable by it or indexing fails on the first write. +CONTAINER_UID = 10001 + +NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,38}[a-z0-9]$") + + +def die(message: str) -> None: + print(f"error: {message}", file=sys.stderr) + sys.exit(1) + + +def load_config() -> dict: + try: + import yaml + except ImportError: + die("pyyaml is required: pip install pyyaml (or: apt install python3-yaml)") + if not CONFIG.exists(): + die(f"no {CONFIG.name} β€” copy the example and edit it:\n" + f" cp {CONFIG.with_name('indexes.example.yml').name} {CONFIG.name}") + config = yaml.safe_load(CONFIG.read_text()) or {} + + config.setdefault("public_base_url", "http://localhost") + config.setdefault("brains_root", str(Path.home() / "brains")) + config.setdefault("http_port", 80) + config.setdefault("opensearch_heap", "512m") + # Auth on by default. Turning it off is a deliberate choice for a public + # demo whose data is synthetic β€” it opens both the UI and, unless the index + # is read_only, the write tools to anyone who has the URL. + config.setdefault("auth", True) + config["public_base_url"] = config["public_base_url"].rstrip("/") + + indexes = config.get("indexes") or [] + if not indexes: + die("indexes.yml lists no indexes") + + seen = set() + for entry in indexes: + name = entry.get("name", "") + # The name becomes a URL path, a container name and an OpenSearch index, + # so keep it to the intersection of what all three accept. + if not NAME_RE.match(name): + die(f"invalid index name {name!r} β€” use lowercase letters, digits and " + "hyphens (2-40 chars, not starting or ending with a hyphen)") + if name in seen: + die(f"duplicate index name {name!r}") + seen.add(name) + return config + + +# -- tokens ------------------------------------------------------------------- + + +def env_var(name: str) -> str: + return "OPEN_INDEX_TOKEN_" + name.upper().replace("-", "_") + + +def ui_pw_var(name: str) -> str: + return "OPEN_INDEX_UI_PASSWORD_" + name.upper().replace("-", "_") + + +def caddy_password_hash(password: str) -> str: + """A bcrypt hash in the form Caddy's basicauth expects. + + Produced by Caddy itself (`caddy hash-password`) rather than a Python bcrypt + dependency β€” the image is already being pulled for the proxy. + """ + result = subprocess.run( + docker() + ["run", "--rm", "caddy:2.8-alpine", + "caddy", "hash-password", "--plaintext", password], + capture_output=True, text=True) + if result.returncode != 0: + die(f"could not hash the UI password via caddy: {result.stderr.strip()}") + return result.stdout.strip() + + +def load_env() -> dict: + if not ENV_FILE.exists(): + return {} + values = {} + for line in ENV_FILE.read_text().splitlines(): + line = line.strip() + if line and not line.startswith("#") and "=" in line: + key, _, value = line.partition("=") + values[key.strip()] = value.strip() + return values + + +def ensure_secrets(config: dict) -> dict: + """One MCP token and one UI password per index, generated once. + + Both are only created when missing, so re-running `up` never rotates a + credential behind your back and invalidates clients. + """ + values = load_env() + if not config.get("auth", True): + # Nothing to generate, and nothing to leave lying around either. + ENV_FILE.write_text("# auth: false in indexes.yml β€” no credentials in use.\n") + ENV_FILE.chmod(0o600) + return values + created = [] + for entry in config["indexes"]: + name = entry["name"] + if not values.get(env_var(name)): + values[env_var(name)] = secrets.token_hex(32) + created.append(f"{name} (token)") + # The UI has no auth of its own, so it gets a password whenever it is + # exposed; Caddy gets the bcrypt hash via the environment. + if entry.get("ui", True) and not values.get(ui_pw_var(name)): + password = secrets.token_urlsafe(18) + values[ui_pw_var(name)] = password + # Caddy needs the hash, we keep the plaintext so `tokens` can print + # something a human can actually type. + values["UI_HASH_" + name.upper().replace("-", "_")] = \ + caddy_password_hash(password) + created.append(f"{name} (ui password)") + + lines = ["# Generated by fleet.py. One bearer token and one UI password per index.", + "# Deleting a line regenerates that credential on the next `up`.", ""] + lines += [f"{k}={v}" for k, v in sorted(values.items())] + ENV_FILE.write_text("\n".join(lines) + "\n") + ENV_FILE.chmod(0o600) + if created: + print(f" generated: {', '.join(created)}") + return values + + +# -- rendering ---------------------------------------------------------------- + + +def render_compose(config: dict) -> str: + heap = config["opensearch_heap"] + root = config["brains_root"].rstrip("/") + base = config["public_base_url"] + + services = [] + for entry in config["indexes"]: + name = entry["name"] + command = ('["serve", "--host", "0.0.0.0", "--port", "8080"' + + (', "--read-only"' if entry.get("read_only") else "") + "]") + note = entry.get("description", "") + token_env = (f" OPEN_INDEX_TOKEN: ${{{env_var(name)}}}\n" + if config.get("auth", True) else "") + services.append(f""" + # {name}{f' β€” {note}' if note else ''} + brain-{name}: + image: open-index:local + build: + context: ../.. + args: + EXTRAS: serve,opensearch,ui,semantic + container_name: oi-brain-{name} + command: {command} + environment: +{token_env} OPEN_INDEX_SEARCH_BACKEND: opensearch + OPEN_INDEX_OPENSEARCH_HOSTS: http://opensearch:9200 + # One cluster index per brain β€” this is what lets them share a cluster. + OPEN_INDEX_OPENSEARCH_INDEX: open_index_{name.replace('-', '_')} + # What the startup banner and `mcp-config` advertise, including the path + # prefix nginx serves this brain on. + OPEN_INDEX_PUBLIC_URL: {base}/{name}/mcp + OPEN_INDEX_EMBEDDING_CACHE: /home/openindex/model-cache + volumes: + - {root}/{name}:/brain + - model-cache:/home/openindex/model-cache + depends_on: + opensearch: + condition: service_healthy + restart: unless-stopped +""".rstrip("\n")) + + if entry.get("ui", True): + services.append(f""" + ui-{name}: + image: open-index:local + container_name: oi-ui-{name} + command: ["ui", "--port", "8501"] + environment: + OPEN_INDEX_SEARCH_BACKEND: opensearch + OPEN_INDEX_OPENSEARCH_HOSTS: http://opensearch:9200 + OPEN_INDEX_OPENSEARCH_INDEX: open_index_{name.replace('-', '_')} + OPEN_INDEX_EMBEDDING_CACHE: /home/openindex/model-cache + # Streamlit must know it lives under a path prefix, or every asset and the + # websocket resolve to / and the page loads blank behind the proxy. + OPEN_INDEX_PUBLIC_URL: {base}/{name}/mcp + OPEN_INDEX_READ_ONLY: "{str(bool(entry.get("read_only"))).lower()}" + STREAMLIT_SERVER_BASE_URL_PATH: {name}/ui + STREAMLIT_SERVER_HEADLESS: "true" + STREAMLIT_SERVER_ADDRESS: 0.0.0.0 + # The browser's Origin is the proxy's, not Streamlit's; its XSRF check + # rejects that and the session never connects. + STREAMLIT_SERVER_ENABLE_XSRF_PROTECTION: "false" + STREAMLIT_SERVER_ENABLE_CORS: "false" + STREAMLIT_BROWSER_GATHER_USAGE_STATS: "false" + volumes: + - {root}/{name}:/brain + - model-cache:/home/openindex/model-cache + depends_on: + opensearch: + condition: service_healthy + restart: unless-stopped +""".rstrip("\n")) + + caddy_deps = "".join( + f" - brain-{e['name']}\n" + + (f" - ui-{e['name']}\n" if e.get("ui", True) else "") + for e in config["indexes"]) or " []\n" + caddy_env = "" + if config.get("auth", True): + for e in config["indexes"]: + if e.get("ui", True): + var = "UI_HASH_" + e["name"].upper().replace("-", "_") + caddy_env += f" {var}: ${{{var}}}\n" + caddy_env = caddy_env or " PLACEHOLDER: \"\"\n" + + return f"""# GENERATED BY fleet.py β€” do not edit. Change indexes.yml and re-run `fleet.py up`. +# +# One shared OpenSearch cluster, one brain container per index, one Caddy in +# front doing path routing and TLS. + +services: + opensearch: + image: opensearchproject/opensearch:2.17.0 + container_name: oi-opensearch + environment: + - discovery.type=single-node + - bootstrap.memory_lock=true + - OPENSEARCH_JAVA_OPTS=-Xms{heap} -Xmx{heap} + - DISABLE_SECURITY_PLUGIN=true + - DISABLE_INSTALL_DEMO_CONFIG=true + - cluster.routing.allocation.disk.threshold_enabled=false + ulimits: + memlock: {{ soft: -1, hard: -1 }} + nofile: {{ soft: 65536, hard: 65536 }} + volumes: + - opensearch-data:/usr/share/opensearch/data + ports: + # Loopback only β€” the brains reach it over the compose network. + - "127.0.0.1:9200:9200" + healthcheck: + test: ["CMD-SHELL", "curl -fs http://localhost:9200/_cluster/health || exit 1"] + interval: 10s + timeout: 5s + retries: 30 + start_period: 30s + restart: unless-stopped +{"".join(services)} + + caddy: + image: caddy:2.8-alpine + container_name: oi-caddy + volumes: + - ./caddy/Caddyfile:/etc/caddy/Caddyfile:ro + # Certificates and ACME account state. Losing this means re-issuing on + # every restart, which will hit Let's Encrypt rate limits. + - caddy-data:/data + - caddy-config:/config + ports: + - "80:80" # ACME HTTP-01 challenge + redirect to HTTPS + - "443:443" + environment: +{caddy_env} depends_on: +{caddy_deps} restart: unless-stopped + +volumes: + opensearch-data: + model-cache: + caddy-data: + caddy-config: +""" + + +def render_caddyfile(config: dict) -> str: + """Caddy config: one site, one route per index, automatic HTTPS. + + Caddy rather than nginx because it obtains and renews the TLS certificate + itself from Let's Encrypt β€” with a real hostname (nip.io resolves any + .nip.io to that ip) that removes the whole certbot dance. It also + upgrades websockets and streams SSE without extra directives, which the MCP + transport and Streamlit both need. + """ + from urllib.parse import urlparse + + base = config["public_base_url"] + host = urlparse(base).netloc or base + auth = config.get("auth", True) + + listing = {} + for e in config["indexes"]: + item = {"mcp": f"{base}/{e['name']}/mcp", + "description": e.get("description", ""), + "read_only": bool(e.get("read_only"))} + if e.get("ui", True): + item["ui"] = f"{base}/{e['name']}/ui" + listing[e["name"]] = item + directory = json.dumps(listing, indent=2).replace("`", "'") + + blocks = [] + for entry in config["indexes"]: + name = entry["name"] + guard = "" + if auth: + guard = (f"\n\t\tbasicauth {{\n" + f"\t\t\t{name} {{env.UI_HASH_{name.upper().replace('-', '_')}}}\n" + f"\t\t}}") + if entry.get("ui", True): + blocks.append(f""" + # {name} β€” explorer UI. No prefix stripping: Streamlit runs with + # baseUrlPath={name}/ui and expects the full path.{guard} + handle /{name}/ui* {{ + reverse_proxy ui-{name}:8501 + }}""") + blocks.append(f""" + # {name} β€” MCP endpoint. handle_path strips the /{name} prefix so the + # brain receives /mcp. + handle_path /{name}/* {{ + reverse_proxy brain-{name}:8080 {{ + # Streamable HTTP holds responses open; never buffer them. + flush_interval -1 + }} + }}""") + + return f"""# GENERATED BY fleet.py β€” do not edit. Change indexes.yml and re-run `fleet.py up`. + +{host} {{ + # Load-balancer probe: unauthenticated, and free of any index detail. + handle /healthz {{ + respond "ok" 200 + }} +{"".join(blocks)} + + # Directory of what this host serves. Names and URLs only. + handle {{ + header Content-Type application/json + respond `{directory}` 200 + }} +}} +""" + + +# -- brains ------------------------------------------------------------------- + + +def reapply_permissions(name: str, brains_root: Path) -> None: + """Give the container ownership and keep group write for the host user. + + Re-applied on every `up`, not just at creation: the container writes with + umask 022, so any directory it creates (a new entities//, the + files an agent writes back) loses group write and the operator can no longer + drop a CSV in or rsync data across without sudo. + """ + path = brains_root / name + run(["sudo", "chown", "-R", f"{CONTAINER_UID}:{os.getgid()}", str(path)], quiet=True) + run(["sudo", "chmod", "-R", "g+rwX", str(path)], quiet=True) + run(["sudo", "chmod", "g+s", str(path)], quiet=True) + + +def ensure_brain(name: str, brains_root: Path) -> bool: + """Create and permission a brain directory if it doesn't exist yet.""" + path = brains_root / name + if (path / "brain.yaml").exists(): + return False + + # Ownership has to be set before the container writes anything: it runs as + # uid 10001 and cannot create files in a directory owned by the host user. + path.mkdir(parents=True, exist_ok=True) + run(["sudo", "chown", "-R", f"{CONTAINER_UID}:{os.getgid()}", str(path)]) + run(["sudo", "chmod", "-R", "g+rwX", str(path)]) + run(["sudo", "chmod", "g+s", str(path)]) + run(docker() + ["run", "--rm", "--entrypoint", "open-index", + "-v", f"{path}:/brain", "open-index:local", + "init", name, "/brain"], quiet=True) + print(f" created brain: {path}") + return True + + +# -- docker ------------------------------------------------------------------- + + +def docker() -> list[str]: + """`docker` if the user can reach the daemon, otherwise `sudo docker`.""" + probe = subprocess.run(["docker", "info"], capture_output=True) + return ["docker"] if probe.returncode == 0 else ["sudo", "docker"] + + +def compose_cmd() -> list[str]: + return docker() + ["compose", "-f", str(COMPOSE), "--env-file", str(ENV_FILE)] + + +def run(cmd: list[str], quiet: bool = False, check: bool = True) -> int: + result = subprocess.run(cmd, capture_output=quiet) + if check and result.returncode != 0: + if quiet and result.stderr: + sys.stderr.write(result.stderr.decode()) + die(f"command failed: {' '.join(cmd)}") + return result.returncode + + +# -- commands ----------------------------------------------------------------- + + +def cmd_render(config: dict, values: dict | None = None) -> None: + # Rendering needs the UI hashes for the Caddy env, so generate any that + # are missing rather than failing on a half-populated .env. + if values is None: + values = ensure_secrets(config) + CADDY_DIR.mkdir(exist_ok=True) + COMPOSE.write_text(render_compose(config)) + CADDY_FILE.write_text(render_caddyfile(config)) + print(f" wrote {COMPOSE.name} and caddy/Caddyfile") + + +def cmd_up(config: dict) -> None: + names = [e["name"] for e in config["indexes"]] + values = ensure_secrets(config) + cmd_render(config, values) + + # The image must exist before `init` can run in it. + print(" building image ...") + run(docker() + ["build", "-q", "-t", "open-index:local", str(REPO)], quiet=True) + + brains_root = Path(config["brains_root"]) + brains_root.mkdir(parents=True, exist_ok=True) + for name in names: + ensure_brain(name, brains_root) + reapply_permissions(name, brains_root) + + print(" starting ...") + run(compose_cmd() + ["up", "-d", "--remove-orphans"]) + print() + cmd_tokens(config) + + +def cmd_add(config: dict, name: str, description: str) -> None: + if not NAME_RE.match(name): + die(f"invalid index name {name!r}") + if any(e["name"] == name for e in config["indexes"]): + die(f"index {name!r} already exists") + entry = f"\n - name: {name}\n" + if description: + entry += f" description: {description}\n" + CONFIG.write_text(CONFIG.read_text().rstrip() + "\n" + entry) + print(f" added {name!r} to indexes.yml") + cmd_up(load_config()) + + +def cmd_tokens(config: dict) -> None: + values = load_env() + base = config["public_base_url"] + print("Indexes on this host:\n") + for entry in config["indexes"]: + name = entry["name"] + mode = "read-only" if entry.get("read_only") else "read+write" + print(f" {name} ({mode})") + print(f" url: {base}/{name}/mcp") + print(f" token: {values.get(env_var(name), '(not generated yet)')}") + print() + first = config["indexes"][0]["name"] + print("Add one to an agent (from this directory):") + print(f" source .env") + print(f" open-index mcp-config --url {base}/{first}/mcp " + f"--token ${env_var(first)} > .mcp.json") + + +def cmd_status(config: dict) -> None: + run(compose_cmd() + ["ps", "--format", + " {{.Name}}\t{{.Status}}"], check=False) + + +def cmd_logs(config: dict, name: str | None) -> None: + target = [f"brain-{name}"] if name else [] + run(compose_cmd() + ["logs", "--tail", "60"] + target, check=False) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + sub = parser.add_subparsers(dest="command", required=True) + sub.add_parser("up", help="render, create missing brains, start everything") + sub.add_parser("render", help="write the generated files only") + sub.add_parser("tokens", help="print connection details for every index") + sub.add_parser("status", help="what is running") + p_add = sub.add_parser("add", help="add an index and start it") + p_add.add_argument("name") + p_add.add_argument("--description", default="") + p_logs = sub.add_parser("logs", help="tail logs") + p_logs.add_argument("name", nargs="?") + + args = parser.parse_args() + if shutil.which("docker") is None: + die("docker is not installed on this host") + + config = load_config() + if args.command == "up": + cmd_up(config) + elif args.command == "render": + cmd_render(config) + elif args.command == "tokens": + cmd_tokens(config) + elif args.command == "status": + cmd_status(config) + elif args.command == "add": + cmd_add(config, args.name, args.description) + elif args.command == "logs": + cmd_logs(config, args.name) + + +if __name__ == "__main__": + main() diff --git a/deploy/fleet/indexes.example.yml b/deploy/fleet/indexes.example.yml new file mode 100644 index 0000000..e29c29d --- /dev/null +++ b/deploy/fleet/indexes.example.yml @@ -0,0 +1,48 @@ +# The indexes served by this host. +# +# Each entry becomes one brain, reachable at //mcp with +# an explorer UI at //ui. +# They share a single OpenSearch cluster (one index per brain), which is what +# makes adding an index cheap: a ~250MB container, not another cluster. +# +# After editing, run: ./fleet.py up + +# Where agents reach this host β€” the load balancer's address once one is in +# front, not the VM's. Caddy obtains a Let's Encrypt certificate for this name, +# so it must resolve here; a bare IP cannot hold a certificate. With no DNS, +# nip.io is the shortcut: .nip.io resolves to . +# https://203.0.113.10.nip.io no DNS needed +# https://index.example.com your own record +public_base_url: https://localhost + +# Host directory holding one subdirectory per brain. +brains_root: ./brains + +# Caddy publishes 80 (ACME challenge + redirect) and 443. A load balancer in +# front should forward both, or terminate TLS itself and forward 80. +http_port: 80 + +# A bearer token per MCP endpoint and a password per UI, generated on first run +# and scoped so one index's credentials never open another's. Only set this to +# false when the data is genuinely public β€” it also opens the write tools. +auth: true + +# Heap for the shared OpenSearch container. Keep total under the box's RAM: +# roughly opensearch_heap * 2 + 330MB per index (brain + ui) + 500MB for the OS. +opensearch_heap: 512m + +indexes: + - name: support + description: Customer support knowledge β€” products, issues, segments. + + - name: sales + description: Sales pipeline β€” accounts, deals, contacts. + + # read_only exposes search/get/navigation but no write tools. Useful for an + # index that agents should consult but never modify. + # ui: false drops the explorer container for this index (~71MB) when nobody + # needs to browse it by hand. + # - name: policies + # description: Company policies, reference only. + # read_only: true + # ui: false diff --git a/docs/multi-index.md b/docs/multi-index.md new file mode 100644 index 0000000..b80a63e --- /dev/null +++ b/docs/multi-index.md @@ -0,0 +1,320 @@ +# Many indexes on one host + +Serving several independent brains from one machine, each with its own MCP +endpoint and its own explorer UI: + +``` +https:///support/mcp https:///support/ui +https:///sales/mcp https:///sales/ui +https:///policies/mcp https:///policies/ui +``` + +Each index is a separate brain β€” its own doc_types, entities, credentials and +read/write policy. They share one OpenSearch cluster and one Caddy, which +terminates TLS for all of them. + +Isolation is enforced at both doors: an index's bearer token opens only its own +`/mcp`, and its UI password opens only its own `/ui`. + +--- + +## 1. Do I need one Docker setup per index? + +No. One setup, several containers. + +`open-index serve` serves exactly one brain per process, so each index does need +its own container. But the expensive part is the **search cluster**, and that is +shared: the OpenSearch index name is derived per brain +(`OPEN_INDEX_OPENSEARCH_INDEX`), so many brains live in one cluster without +seeing each other's data. + +Measured on a 2-vCPU / 3.8GB VM running two indexes, each with MCP and UI: + +| Component | Memory | Per what | +|---|---|---| +| OpenSearch | 983 MB | once, shared | +| Caddy | 3 MB | once, shared | +| brain container (MCP) | ~255 MB | **per index** | +| ui container | ~71 MB | **per index** | + +So the first index costs ~1.3GB and each additional one ~326MB. On a 3.8GB box +that is roughly 4–6 indexes with UIs, or 6–8 without. + +Two ways to fit more: set `ui: false` on indexes nobody browses, or move +embeddings to an API (`OPEN_INDEX_EMBEDDING_*`), which drops the local model +from every container. Note the UI figure grows once someone runs a semantic +search there β€” the model loads lazily. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Caddy :80/:443 ───────────────┐ + β”‚ /support/mcp β†’ brain-support (token) │──▢ ┐ + LB ──▢ β”‚ /support/ui β†’ ui-support (basic) │──▢ β”‚ + β”‚ /sales/mcp β†’ brain-sales (token) │──▢ β”œβ”€β–Ά OpenSearch + β”‚ /sales/ui β†’ ui-sales (basic) │──▢ β”˜ one index each + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +--- + +## 2. Set it up + +Everything is generated from one file, `deploy/fleet/indexes.yml`: + +```yaml +public_base_url: https://brain.acme.com # what agents will connect to +brains_root: ./brains # one subdirectory per index +http_port: 80 +opensearch_heap: 512m + +indexes: + - name: support + description: Customer support knowledge. + - name: sales + description: Sales pipeline. + - name: policies + description: Reference only. + read_only: true # search/read tools, no writes + ui: false # no explorer for this one (saves ~71MB) +``` + +Then: + +```bash +cd deploy/fleet +cp indexes.example.yml indexes.yml # then edit it +./fleet.py up +``` + +`indexes.yml` is per-deployment and gitignored, like `.env` β€” hostnames, which +indexes this host serves, and whether auth is on differ per environment. + +That builds the image, creates any missing brain directories (with the +permissions the container needs), generates a per-index bearer token, renders +the compose and Caddy config, and starts everything. It is idempotent β€” run it +again after any edit. + +**Adding an index later** is one command: + +```bash +./fleet.py add marketing --description "Campaigns and positioning" +``` + +Existing indexes keep running; only the new containers start and Caddy reloads. + +Other commands: `./fleet.py tokens` (connection details), `status`, `logs +`, `render` (write config without starting). + +> `indexes.yml` is the source of truth. `docker-compose.generated.yml` and +> `caddy/Caddyfile` are regenerated on every run and gitignored β€” edit the +> former, never the latter two. + +--- + +## 3. TLS, and putting it behind a load balancer + +Caddy publishes 80 and 443 and **obtains its own Let's Encrypt certificate** for +whatever `public_base_url` names β€” no certbot, no renewal cron. The only +requirement is that the name resolves to this host and port 80 is reachable for +the ACME challenge. + +If you have no DNS record, `nip.io` is the shortcut: `203.0.113.10.nip.io` +resolves to `203.0.113.10`, and a certificate can be issued for it. A bare IP +cannot hold one. + +Point a load balancer at 443 (or at 80 if it terminates TLS itself). + +**Health check:** `GET /healthz` β†’ `200 ok`. Unauthenticated and free of brain +detail, so it is safe as an LB probe. + +**Directory:** `GET /` returns JSON listing every index and its URL. Names only β€” +no tokens. + +**Forward the `Host` header.** open-index validates it (DNS-rebinding +protection) and accepts loopback plus whatever `public_base_url` names. If your +LB rewrites Host to something else, add it: + +```bash +open-index serve --allowed-host lb.internal --allowed-host brain.acme.com +# or OPEN_INDEX_ALLOWED_HOSTS=lb.internal,brain.acme.com +``` + +A `421 Invalid Host header` means exactly this β€” the Host that arrived is not on +the list. `--allowed-host '*'` disables the check, which is only reasonable when +the proxy in front already validates Host. + +**Don't buffer responses.** Streamable HTTP keeps responses open and the UI uses +websockets; a buffering LB will appear to hang. Caddy streams by default β€” +configure the same on the LB, with an idle timeout of at least a few minutes. + +--- + +## 4. Access an index + +Each index has its own token, so a client holding the `support` token cannot +read or write `sales`. + +```bash +cd deploy/fleet && ./fleet.py tokens +``` + +Point an agent at one: + +```bash +source deploy/fleet/.env +open-index mcp-config --url https://brain.acme.com/support/mcp \ + --token $OPEN_INDEX_TOKEN_SUPPORT > .mcp.json +``` + +which writes: + +```json +{ + "mcpServers": { + "open-index": { + "type": "http", + "url": "https://brain.acme.com/support/mcp", + "headers": { "Authorization": "Bearer " } + } + } +} +``` + +Registering several indexes in one agent β€” give each a distinct server name so +the agent can tell them apart: + +```bash +open-index mcp-config --url https://brain.acme.com/support/mcp --token $OPEN_INDEX_TOKEN_SUPPORT --name support +open-index mcp-config --url https://brain.acme.com/sales/mcp --token $OPEN_INDEX_TOKEN_SALES --name sales +``` + +Check an endpoint by hand: + +```bash +curl -i -X POST https://brain.acme.com/support/mcp \ + -H "Authorization: Bearer $OPEN_INDEX_TOKEN_SUPPORT" \ + -H "Content-Type: application/json" \ + -H "Accept: application/json, text/event-stream" \ + -d '{"jsonrpc":"2.0","id":"1","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}' +``` + +`401` = token missing or wrong. `404` = wrong path (the index name is +case-sensitive). `421` = Host header not allowed, see above. + +### The explorer UI + +Each index also gets a read-only explorer at `//ui`, behind HTTP basic +auth β€” username is the index name, password from `./fleet.py tokens`: + +``` +https://brain.acme.com/support/ui support / +``` + +The password exists because **Streamlit has no authentication of its own**. +Published without a gate, anyone who could reach the host could read the entire +brain. Each index has its own credentials, so the `sales` password does not open +the `support` UI. + +Set `auth: false` at the top of `indexes.yml` to drop both the tokens and the UI +passwords β€” reasonable when the data is genuinely public, but note it opens the +write tools too, so pair it with `read_only: true` unless you want strangers +writing to the index. + +The UI is deliberately read-only β€” writes go through MCP or the CLI so every +change is validated. Turn it off per index with `ui: false`. + +If the page loads but hangs "connecting", the proxy in front is not forwarding +websockets: the LB needs the `Upgrade`/`Connection` headers and buffering off, +which Caddy already handles on its own hop. + +--- + +## 5. Populate an index + +Everything below targets one index. Substitute the index name. + +### Bulk import a spreadsheet + +Export the sheet to CSV, drop it where the container can see it (the brain +directory is mounted), then: + +```bash +cd deploy/fleet +D="docker compose -f docker-compose.generated.yml --env-file .env" + +cp issues.csv ./brains/support/ +$D exec -T brain-support open-index import /brain/issues.csv \ + --brain /brain --doc-type issue \ + --asserted-by import:2026-08-crm --confidence 0.8 +``` + +Check first with `--dry-run`, which validates and writes nothing. + +Notes that save time: + +- **Define the doc_type before importing.** `open-index add-doc-type issue + --brain /brain --storage file`, then edit + `doc_types/issue.yaml` to describe the columns. Import fails per-row on an + unknown doc_type. +- **Bare ids are qualified**: an `id` column containing `checkout` becomes + `issue:checkout`. +- **Relationships come from a `related_to` column**, semicolon-separated, each + `target|meaning`: + `product:checkout|is a common issue of; team:payments|owned by`. + Those edges are what make this a graph rather than a table β€” a spreadsheet + imported without them is just rows. +- **Bad rows are skipped, not fatal.** The command reports each one and exits + non-zero, so CI notices, but the good rows still land. +- `--asserted-by` / `--confidence` attribute the whole batch once, so later + readers can tell imported rows from agent-inferred ones. + +### Let an agent write to it + +Point the agent at that index's URL (section 4) and ask. It calls +`navigation_guidelines` first β€” the guide is injected into the MCP handshake, so +it knows your doc_types and relationship vocabulary before its first turn. Use +`put_entities` for batches rather than one call per row. + +### Pull from another system on a schedule + +Add a connector under `/connectors/*.py` and run +`open-index ingest ` (or `open-index run` from cron). See +[deployment.md](./deployment.md#6-the-other-direction-connectors-that-pull-from-an-mcp-server). + +### After a bulk change + +```bash +$D exec -T brain-support open-index validate --brain /brain +$D exec -T brain-support open-index index --brain /brain +``` + +`validate` catches malformed ids and wrong relationship targets. `index` +reconciles file-backed entities from disk. + +--- + +## 6. Operations + +**Back up** two things per index: the brain directory (doc_types + file-backed +entities β€” usually git) and the OpenSearch data volume, which is the *only* home +for `storage: index` entities. Losing the volume means re-ingesting them. + +**Logs:** `./fleet.py logs support`, or `docker compose ... logs -f`. + +**Restart safety:** every container is `restart: unless-stopped`, so the stack +comes back after a reboot. The embedding model is cached in a named volume, so a +restart doesn't re-download it. + +**Removing an index:** delete its entry from `indexes.yml`, run `./fleet.py up` +(the container is removed via `--remove-orphans`), then delete the brain +directory and the cluster index if you want the data gone: + +```bash +curl -X DELETE http://127.0.0.1:9200/open_index_support +``` + +**Rotating a token:** delete that index's line from `deploy/fleet/.env` and run +`./fleet.py up` β€” a new token is generated. Clients must be updated. + +**Capacity:** watch `docker stats`. If OpenSearch starts evicting or the box +swaps, either raise `opensearch_heap` and the VM size together, or move +embeddings to an API so each brain container drops to well under 100MB. diff --git a/open_index/cli.py b/open_index/cli.py index 6eefe74..4359b23 100644 --- a/open_index/cli.py +++ b/open_index/cli.py @@ -452,6 +452,12 @@ def serve( help="Externally reachable URL, when behind a proxy/tunnel/load balancer. " "Only used to print correct connection details.", ), + allowed_host: Optional[list[str]] = typer.Option( + None, "--allowed-host", envvar="OPEN_INDEX_ALLOWED_HOSTS", + help="Host header(s) to accept, when behind a proxy or load balancer. " + "Repeatable. The host from --public-url is added automatically. " + "Use '*' to disable the check entirely (trusted proxy only).", + ), read_only: bool = typer.Option( False, "--read-only", help="Opt out of default read+write mode and expose only read tools.", @@ -502,7 +508,8 @@ def serve( typer.echo("") serve_http(str(root), host=host, port=port, token=token, read_only=read_only, - warn_unauthenticated=False) + warn_unauthenticated=False, public_url=public_url, + allowed_hosts=list(allowed_host or [])) if __name__ == "__main__": # pragma: no cover - module entry point diff --git a/open_index/graph.py b/open_index/graph.py index 2555bb2..fd3e57b 100644 --- a/open_index/graph.py +++ b/open_index/graph.py @@ -69,6 +69,62 @@ def _label_for(brain: Brain, entity) -> str: return entity.label_for(label_field) +def build_overview_graph( + brain: Brain, + doc_types: Optional[list[str]] = None, + limit: int = 250, +) -> ContextGraph: + """Every entity of the given doc_types, with the edges that run between them. + + The anchor-and-expand view answers "what is around this one thing?". This + answers the other question β€” "what does this index look like?" β€” which is + what you want when you have never seen the index before and have no entity + in mind to anchor on. + + Only edges whose *both* ends are in scope are drawn: a dangling half-edge to + a filtered-out doc_type would render as an unexplained line to nowhere. + + `limit` caps the node count, keeping the most-connected entities. A force + layout with thousands of nodes is neither readable nor quick, and the + best-connected ones are the ones worth seeing. Callers should report when + the cap bit β€” silently showing a subset reads as "this is everything". + """ + entities = brain.backend.all_entities(doc_types) + + degree: dict[str, int] = {e.id: 0 for e in entities} + for entity in entities: + for rel in entity.related_to: + degree[entity.id] = degree.get(entity.id, 0) + 1 + if rel.target in degree: + degree[rel.target] = degree.get(rel.target, 0) + 1 + + if len(entities) > limit: + entities = sorted(entities, key=lambda e: (-degree.get(e.id, 0), e.id))[:limit] + + in_scope = {e.id for e in entities} + graph = ContextGraph(anchors=[]) + for entity in entities: + graph.nodes.append(GraphNode( + id=entity.id, + label=_label_for(brain, entity), + doc_type=entity.doc_type, + color=_color_for(brain, entity.doc_type), + depth=0, + data=entity.to_json(), + )) + + seen: set[tuple[str, str, str]] = set() + for entity in entities: + for source, target, meaning in brain.backend.relationships_from(entity.id): + if target not in in_scope: + continue + key = (source, target, meaning) + if key not in seen: + seen.add(key) + graph.edges.append(GraphEdge(source, target, meaning)) + return graph + + def build_graph(brain: Brain, anchors: str | list[str], depth: int = 1) -> ContextGraph: """Build the map around one or more anchor entities. diff --git a/open_index/mcp_server.py b/open_index/mcp_server.py index b93619f..32e1c9c 100644 --- a/open_index/mcp_server.py +++ b/open_index/mcp_server.py @@ -432,10 +432,68 @@ async def wrapped(scope, receive, send): return wrapped +def _host_of(url: str) -> Optional[str]: + """The host[:port] part of a URL, or None if it isn't parseable.""" + from urllib.parse import urlparse + + parsed = urlparse(url if "://" in url else f"http://{url}") + return parsed.netloc or None + + +def build_transport_security( + public_url: Optional[str] = None, allowed_hosts: Optional[list[str]] = None +): + """Host allow-list for the MCP SDK's DNS-rebinding protection. + + The SDK enables that protection whenever the app is built for a localhost + bind, with a hardcoded localhost-only allow-list. Anything reaching the + server through a reverse proxy or load balancer therefore arrives with a + foreign `Host` header and is rejected with `421 Invalid Host header` β€” the + server looks up, and every proxied request fails. + + Rather than switch the protection off (which is what passing a non-localhost + bind address to the SDK quietly does), state which hosts are legitimate: + loopback, plus whatever `--public-url` and `--allowed-host` name. + + A literal `*` disables the check β€” for a brain behind a trusted proxy that + already validates Host. Returns settings, or None when the SDK's own default + is appropriate. + """ + from mcp.server.transport_security import TransportSecuritySettings + + entries = [e.strip() for e in (allowed_hosts or []) if e.strip()] + if "*" in entries: + return TransportSecuritySettings(enable_dns_rebinding_protection=False) + + if public_url: + derived = _host_of(public_url) + if derived: + entries.append(derived) + + hosts = {"127.0.0.1:*", "localhost:*", "[::1]:*", "127.0.0.1", "localhost", "[::1]"} + origins = {"http://127.0.0.1:*", "http://localhost:*", "http://[::1]:*"} + for entry in entries: + bare = entry.split(":", 1)[0] if not entry.startswith("[") else entry + # Both forms: proxies drop the port when it is the scheme default, so + # "example.com" and "example.com:8080" must both pass. + hosts.update({entry, bare, f"{bare}:*"}) + for scheme in ("http", "https"): + origins.update({f"{scheme}://{entry}", f"{scheme}://{bare}", + f"{scheme}://{bare}:*"}) + + return TransportSecuritySettings( + enable_dns_rebinding_protection=True, + allowed_hosts=sorted(hosts), + allowed_origins=sorted(origins), + ) + + def serve_http( brain_dir: str, host: str = "0.0.0.0", port: int = 8080, token: Optional[str] = None, read_only: bool = False, warn_unauthenticated: bool = True, + public_url: Optional[str] = None, + allowed_hosts: Optional[list[str]] = None, ) -> None: """Run the MCP server over streamable HTTP so remote/cloud agents can connect by URL. Register `http://:/mcp` as a remote MCP server in the @@ -452,7 +510,10 @@ def serve_http( brain = Brain.open(brain_dir) server = build_server(brain, read_only=read_only) - app = server.streamable_http_app() + app = server.streamable_http_app( + transport_security=build_transport_security(public_url, allowed_hosts), + host=host, + ) if token: app = _bearer_auth_middleware(app, token) elif warn_unauthenticated: diff --git a/open_index/storage/opensearch_backend.py b/open_index/storage/opensearch_backend.py index cbb8349..92fc3bb 100644 --- a/open_index/storage/opensearch_backend.py +++ b/open_index/storage/opensearch_backend.py @@ -100,6 +100,11 @@ def mapping(dimension: int = 384) -> dict: return { "settings": {"index": {"knn": True}}, "mappings": { + # A field declared `string` whose values look like dates would + # otherwise be mapped as `date` by dynamic detection, and then + # rejected by fuzzy search. The schema decides the type here, + # not a guess from the first document indexed. + "date_detection": False, "properties": { "id": {"type": "keyword"}, "doc_type": {"type": "keyword"}, @@ -137,6 +142,11 @@ def _base_mapping(self) -> dict: """Mapping without the embedding field (for keyword-only brains).""" return { "mappings": { + # A field declared `string` whose values look like dates would + # otherwise be mapped as `date` by dynamic detection, and then + # rejected by fuzzy search. The schema decides the type here, + # not a guess from the first document indexed. + "date_detection": False, "properties": { "id": {"type": "keyword"}, "doc_type": {"type": "keyword"}, @@ -261,6 +271,13 @@ def _search_fields(self, doc_types: Optional[list[str]]) -> list[str]: continue if f.name == label: name_boost = max(name_boost, f.boost) + # Only text-ish fields belong in a fuzzy full-text query. + # OpenSearch maps a `number` field to long and a timestamp to + # date, and rejects the whole query with + # "Can only use fuzzy queries on keyword and text fields" if + # either is listed β€” so one numeric field breaks all search. + if f.type not in ("string", "text"): + continue boosts[f.name] = max(boosts.get(f.name, 1.0), f.boost) fields = [f"name^{name_boost:g}"] fields += [f"fields.{name}^{b:g}" for name, b in boosts.items()] @@ -373,9 +390,27 @@ def ensure_schema(self, doc_types: dict[str, DocType]) -> None: "is the cluster running? (search.backend: opensearch)" ) from exc + def _ensure_index_exists(self) -> None: + """Recreate the index with our mapping if it has gone missing. + + `ensure_schema` runs once when the brain is opened. If the index is + dropped after that β€” a cluster rebuild, a manual DELETE, a restored + snapshot β€” OpenSearch would auto-create it on the next write using + *dynamic* mapping, silently typing `doc_type` as text and breaking every + aggregation, and typing date-shaped strings as dates and breaking fuzzy + search. Both fail long after the write that caused them, so it is worth + one existence check on the write path. + """ + if self._client.indices.exists(index=self.index): + return + logger.warning("index %s was missing; recreating it with the schema mapping", + self.index) + self._client.indices.create(index=self.index, body=self._mapping()) + def upsert_entity(self, entity: Entity, doc_type: Optional[DocType] = None) -> None: if doc_type is not None: self._doc_types[doc_type.doc_type] = doc_type + self._ensure_index_exists() self._client.index( index=self.index, id=entity.id, body=self._doc_with_embedding(entity), refresh=True ) @@ -391,6 +426,7 @@ def upsert_many(self, items: list[tuple[Entity, Optional[DocType]]]) -> None: for _entity, doc_type in items: if doc_type is not None: self._doc_types[doc_type.doc_type] = doc_type + self._ensure_index_exists() payload: list[dict] = [] for entity, _doc_type in items: diff --git a/open_index/ui/app.py b/open_index/ui/app.py index e181efb..127b69e 100644 --- a/open_index/ui/app.py +++ b/open_index/ui/app.py @@ -22,7 +22,7 @@ import streamlit as st from open_index.brain import Brain -from open_index.graph import ContextGraph, build_graph +from open_index.graph import ContextGraph, build_graph, build_overview_graph from open_index.ui import view st.set_page_config(page_title="Open Index", page_icon="🧠", layout="wide") @@ -237,48 +237,59 @@ def render_entity(brain: Brain, entity_id: str) -> None: # --------------------------------------------------------------------------- # def render_map(brain: Brain) -> None: + """The whole index at a glance: every entity, coloured by doc_type. + + Anchoring on one entity is the wrong default for someone who has never seen + the index β€” they have no entity in mind. This shows the shape of the whole + thing and lets them subtract from it. + """ summary = view.summarize(brain) populated = [r.name for r in summary.doc_types if r.count] if not populated: st.info("No entities to map yet. Add some and run `open-index index`.") return - chosen_types = st.multiselect( - "Doc types to include", populated, default=populated, - help="Narrow the map to the concepts you care about.", + chosen = st.multiselect( + "Doc types shown", populated, default=populated, + help="Uncheck a type to drop it and its edges from the map.", ) - scope = chosen_types or populated - - # Auto-anchor rather than waiting for a selection. The old UI drew nothing - # until you picked entities, which looked like a broken canvas. - auto = view.default_anchors(brain, scope) - catalog = {f"{e.name} ({e.id})": e.id - for e in brain.backend.all_entities(scope)} - auto_labels = [label for label, eid in catalog.items() if eid in auto] - - picked = st.multiselect( - "Anchors", list(catalog), default=auto_labels, - help="Starting points. Click any node in the map to expand it.", - ) - anchors = [catalog[label] for label in picked] - - expanded = st.session_state.get("expanded", set()) - if expanded: - cols = st.columns([4, 1]) - cols[0].caption(f"expanded: {', '.join(sorted(expanded))}") - if cols[1].button("β†Ί reset"): - st.session_state["expanded"] = set() + scope = chosen or populated + + focus = st.session_state.get("map_focus") + if focus: + cols = st.columns([5, 1]) + cols[0].caption(f"Focused on `{focus}` and its immediate neighbours.") + if cols[1].button("↩ show all"): + st.session_state["map_focus"] = None st.rerun() - - anchors = list(dict.fromkeys(anchors + list(expanded))) - if not anchors: - st.info("Select at least one anchor above.") - return - - graph = build_graph(brain, anchors, depth=1) - st.caption(f"{len(graph.nodes)} nodes Β· {len(graph.edges)} edges β€” " - "click a node to expand its relationships") - render_graph(brain, graph) + graph = build_graph(brain, [focus], depth=1) + else: + graph = build_overview_graph(brain, scope, limit=view.MAX_GRAPH_NODES) + + total = sum(r.count for r in summary.doc_types if r.name in scope) + if not focus and len(graph.nodes) < total: + st.warning( + f"Showing the {len(graph.nodes)} most-connected of {total} entities. " + "Narrow the doc types above to see the rest." + ) + + canvas, legend = st.columns([4, 1]) + with canvas: + st.caption(f"{len(graph.nodes)} nodes Β· {len(graph.edges)} edges β€” " + "hover for detail, click a node to focus on it") + render_graph(brain, graph) + with legend: + st.markdown("**Legend**") + for row in view.legend_rows(brain, graph): + st.markdown( + f"{_dot(row['color'])} `{_esc(row['doc_type'])}`" + f" {row['count']}", + unsafe_allow_html=True, + ) + if graph.edges: + st.markdown("---") + st.caption("Edges are `related_to` links. Hover one to see which " + "relationship it is.") # streamlit-agraph doesn't paint on its first render inside a tab (the canvas # mounts with zero size). One forced rerun remounts it with the tab active. @@ -298,24 +309,8 @@ def render_graph(brain: Brain, graph: ContextGraph) -> None: palette = view.graph_theme(_theme_type()) - nodes = [ - Node(id=n.id, label=n.label, color=n.color, - size=22 if n.is_anchor else 16, shape="dot", - title=f"{n.doc_type} Β· {n.id}", - # strokeWidth 0 removes vis's white halo, which on a dark canvas - # turns every label into heavy outlined text. - font={"color": palette["node_label"], "size": 15, - "strokeWidth": palette["stroke_width"], "face": "sans-serif"}) - for n in graph.nodes - ] - edges = [ - Edge(source=e.source, target=e.target, label=e.meaning, - color=palette["edge"], - font={"color": palette["edge_label"], "size": 12, - "strokeWidth": palette["stroke_width"], "align": "middle", - "face": "sans-serif"}) - for e in graph.edges - ] + nodes = [Node(**spec) for spec in view.graph_node_specs(graph)] + edges = [Edge(**spec) for spec in view.graph_edge_specs(graph, palette["edge"])] busy = len(graph.nodes) > view.BUSY_GRAPH_NODES config = Config( @@ -335,8 +330,8 @@ def render_graph(brain: Brain, graph: ContextGraph) -> None: _left, middle, _right = st.columns([1, 20, 1]) with middle: clicked = agraph(nodes=nodes, edges=edges, config=config) - if clicked and clicked not in st.session_state.get("expanded", set()): - st.session_state.setdefault("expanded", set()).add(clicked) + if clicked and clicked != st.session_state.get("map_focus"): + st.session_state["map_focus"] = clicked st.rerun() @@ -407,6 +402,125 @@ def render_analytics(brain: Brain) -> None: } for e in events], hide_index=True, use_container_width=True) +def render_schema(brain: Brain) -> None: + """Every doc_type and the shape of it β€” the reference before you write.""" + summary = view.summarize(brain) + if not summary.has_schema: + st.info("No doc_types defined yet.") + st.caption("A doc_type is a concept this index tracks, plus the fields it " + "stores. Create one with `open-index add-doc-type`, or ask an " + "agent to call `create_doc_type`.") + return + + st.caption( + f"{len(summary.doc_types)} doc_types Β· {summary.total_entities:,} entities. " + "Every entity id is `:`, and any entity can link to any " + "other through `related_to`." + ) + + for row in summary.doc_types: + doc_type = brain.config.doc_type(row.name) + noun = "entity" if row.count == 1 else "entities" + with st.expander(f"{row.name} Β· {row.count:,} {noun}", + expanded=len(summary.doc_types) <= 3): + if row.description: + st.markdown(row.description) + st.caption( + f"{_dot(row.color)} source of truth: " + + ("**files** β€” JSON under `entities/`, git-trackable" + if row.storage == "file" + else "**search index** β€” DB-owned, not written to files"), + unsafe_allow_html=True, + ) + + fields = view.schema_field_rows(doc_type) + if fields: + st.markdown("**Fields**") + st.table(fields) + else: + st.caption("No fields declared.") + + relationships = view.schema_relationship_rows(brain, row.name) + if relationships: + st.markdown("**Relationships**") + st.table(relationships) + st.caption("Declared edges are validated against their target " + "doc_type. Undeclared ones still work β€” they just " + "aren't checked.") + else: + st.caption("No relationships declared or in use for this type.") + + +def render_how_to_use(brain: Brain) -> None: + """Connecting an agent, the tools it gets, and what the other tabs are for. + + Deliberately the rightmost tab: it is the page people come back to, not the + one they start on. + """ + summary = view.summarize(brain) + mcp_url = os.environ.get("OPEN_INDEX_PUBLIC_URL", "") + read_only = os.environ.get("OPEN_INDEX_READ_ONLY", "").lower() in ("1", "true", "yes") + + st.markdown(f"### Connect an agent to `{_esc(summary.name)}`") + st.caption( + "This index speaks MCP, so any MCP-capable agent can query it β€” and, " + "unless the endpoint is read-only, keep it current." + ) + + if mcp_url: + st.markdown("**1. Point your agent at this URL**") + st.code(view.mcp_client_config(mcp_url, server_name=summary.name), language="json") + st.caption("Paste into `.mcp.json` (Claude Code), `.cursor/mcp.json` (Cursor), " + "or any MCP client's server config. Or generate it:") + st.code(f"open-index mcp-config --url {mcp_url} --name {summary.name} > .mcp.json", + language="bash") + else: + st.info("This explorer isn't configured with a public MCP URL " + "(`OPEN_INDEX_PUBLIC_URL`), so the connection block can't be shown.") + st.code("open-index mcp-config --brain > .mcp.json", language="bash") + + st.markdown("**2. Ask it something**") + st.caption("No briefing needed β€” the navigation guide below is injected into the " + "MCP handshake, so the agent knows this index's doc_types and " + "relationship vocabulary before its first turn.") + + st.divider() + st.markdown("### Tools the agent gets") + + st.markdown("**Reading**") + for name, what in view.READ_TOOLS: + st.markdown(f"- `{name}` β€” {what}") + + st.markdown("**Writing**") + if read_only: + st.info("This endpoint is **read-only** β€” the write tools below are not " + "registered on it. Serve without `--read-only` to enable them.") + for name, what in view.WRITE_TOOLS: + st.markdown(f"- `{name}` β€” {what}") + st.caption("Entity ids are always `:`. Writes are validated " + "against the doc_type schema, and land in the search index (and on " + "disk, for `storage: file` types).") + + st.divider() + st.markdown("### What each tab does") + for name, what in view.TAB_GUIDE: + st.markdown(f"- **{name}** β€” {what}") + + st.divider() + st.markdown("### What's in this index right now") + st.caption(f"{summary.total_entities:,} entities across " + f"{len(summary.doc_types)} doc_types.") + if summary.doc_types: + st.table([{"doc_type": r.name, "entities": r.count, + "source of truth": "files (git)" if r.storage == "file" else "search index", + "what it holds": r.description or "β€”"} + for r in summary.doc_types]) + + with st.expander("The full navigation guide the agent receives"): + st.code(brain.navigation_guidelines(include_writes=not read_only), + language="markdown") + + def render_jobs(brain: Brain) -> None: from open_index.connectors.runner import discover_connectors from open_index.scheduling import RunState @@ -447,9 +561,15 @@ def main() -> None: st.markdown(view.ROW_CSS, unsafe_allow_html=True) options = render_sidebar(brain) - tab_explore, tab_map, tab_analytics, tab_jobs = st.tabs( - ["Explore", "Map", "Analytics", "Jobs"] + # Streamlit opens the first tab, so the help page leftmost means a visitor + # lands on the explanation rather than having to find it. + tab_help, tab_schema, tab_explore, tab_map, tab_analytics, tab_jobs = st.tabs( + [name for name, _ in view.TAB_GUIDE] ) + with tab_help: + render_how_to_use(brain) + with tab_schema: + render_schema(brain) with tab_explore: render_explore(brain, options) with tab_map: diff --git a/open_index/ui/view.py b/open_index/ui/view.py index e3ba929..fcc949d 100644 --- a/open_index/ui/view.py +++ b/open_index/ui/view.py @@ -207,7 +207,9 @@ def semantic_weight_for(mode: str) -> Optional[float]: # does `f"{width}px"`, so a CSS string like "100%" becomes the invalid value # "100%px", the canvas fails to size, and the graph is stranded in a corner # instead of centred. -GRAPH_WIDTH = 1200 +# Sized to sit beside the legend column rather than to fill the page: at the +# old full-page width the canvas overflowed its column once the legend arrived. +GRAPH_WIDTH = 950 GRAPH_HEIGHT = 650 # Past this many nodes a force layout keeps drifting, so we slow it down rather @@ -262,6 +264,211 @@ def semantic_weight_for(mode: str) -> Optional[float]: """ +def mcp_client_config(url: str, server_name: str = "open-index") -> str: + """The JSON block to paste into an agent, as displayed in the How to use tab.""" + import json + + from open_index.mcp_config import normalize_mcp_url + + return json.dumps( + {"mcpServers": {server_name: {"type": "http", "url": normalize_mcp_url(url)}}}, + indent=2, + ) + + +# What each tool does, in the order an agent would reach for them. Kept here +# rather than in the page so the list can be asserted against the tools the MCP +# server actually registers β€” a stale tool list in the docs is worse than none. +READ_TOOLS = [ + ("navigation_guidelines()", + "The whole guide to this index: every doc_type, its fields, the " + "relationship vocabulary in use, and worked examples. Injected into the " + "MCP handshake, so an agent starts oriented."), + ("search_brain(query, doc_types, limit)", + "Free-text search, hybrid keyword + semantic. `doc_types` narrows it."), + ("get_entity(entity_id)", + "One entity with its outgoing AND incoming edges β€” the incoming direction " + "answers \"what else points at this?\"."), +] + +WRITE_TOOLS = [ + ("put_entity(doc_type, id, name, fields, related_to)", + "Add or update one entity. Upsert β€” the same id replaces it."), + ("put_entities([...])", + "A whole batch in one call, with optional shared provenance. Use this " + "rather than calling put_entity in a loop."), + ("create_doc_type(doc_type, description, fields, relationships, storage)", + "Define a new concept, when no existing doc_type fits."), +] + +# The tab label for the help page. Leftmost, so it is what a first-time visitor +# lands on, and phrased as the question they are actually asking. +HELP_TAB = "How to use?" + +# What each tab is for, in the order they appear. This list *is* the tab order β€” +# the page builds its tabs from it, so the two cannot drift apart. +TAB_GUIDE = [ + (HELP_TAB, + "This page: how to connect an agent, what tools it gets, and what " + "everything else here does."), + ("Schema", + "Every doc_type in this index and the shape of it β€” each field's type, how " + "it is searched, its ranking weight, and the relationship vocabulary that " + "connects types to each other. Read this before writing to the index."), + ("Explore", + "Search the index, or browse by doc_type. Open an entity to see its fields, " + "its attribution, and every relationship in both directions β€” click through " + "to walk the graph."), + ("Map", + "The same relationships drawn. It auto-anchors on the most-connected " + "entities so it shows something immediately; click any node to expand it, " + "and narrow by doc_type to cut the noise."), + ("Analytics", + "What has been asked of this index, by which client (CLI, agent, this UI) " + "and how often. Zero-result searches are the interesting number: they are " + "the questions this index cannot yet answer."), + ("Jobs", + "Connectors that pull entities in on a schedule, with their last run."), +] + + +def schema_field_rows(doc_type) -> list[dict]: + """One row per field, as the Schema tab tabulates them. + + `search` and `boost` are the two that change behaviour rather than just + describing it, so they are spelled out rather than shown as raw enum values. + """ + searchable = { + "syntactic": "keyword match", + "semantic": "meaning (vector)", + "none": "not searched", + } + rows = [] + for f in doc_type.fields: + rows.append({ + "field": f.name, + "type": f.type, + "searched by": searchable.get(f.search, f.search), + "weight": f"{f.boost:g}Γ—" if f.search != "none" else "β€”", + "required": "yes" if f.required else "", + "notes": f.description or "", + }) + return rows + + +def schema_relationship_rows(brain, doc_type_name: str) -> list[dict]: + """Declared and observed edges for one doc_type, merged. + + Declared is the vocabulary the schema intends; observed is what the entities + actually use. Showing both together is the point β€” a declared edge with zero + uses and an undeclared edge in heavy use are both worth noticing. + """ + doc_type = brain.config.doc_type(doc_type_name) + observed = brain.observed_relationships(doc_type_name) + rows = [] + seen = set() + + for spec in (doc_type.relationships if doc_type else []): + seen.add(spec.name) + rows.append({ + "relationship": spec.name, + "points at": spec.target_doc_type or "any", + "declared": "yes", + "in use": observed.get(spec.name, 0), + }) + for meaning, count in sorted(observed.items(), key=lambda kv: -kv[1]): + if meaning not in seen: + rows.append({ + "relationship": meaning, + "points at": "β€”", + "declared": "no", + "in use": count, + }) + return rows + + +# Cap on nodes drawn at once. Past this a force layout stops settling and the +# picture stops being readable regardless. +MAX_GRAPH_NODES = 250 + + +def node_tooltip(entity_id: str, name: str, doc_type: str, + fields: Optional[dict] = None) -> str: + """What hovering a node shows: the full name, its type, and a few fields. + + vis renders this as plain text, so it is newline-separated rather than HTML. + """ + lines = [name, f"{doc_type} Β· {entity_id}"] + for key, value in list((fields or {}).items()): + if value in (None, "") or key == "name": + continue + text = " ".join(str(value).split()) + lines.append(f"{key}: {text[:90]}{'…' if len(text) > 90 else ''}") + if len(lines) >= 7: # a tooltip taller than the graph helps nobody + break + return "\n".join(lines) + + +def edge_tooltip(source: str, target: str, meaning: str) -> str: + return f"{source}\n β€”[{meaning or 'related'}]β†’\n{target}" + + +def legend_rows(brain, graph) -> list[dict]: + """Doc types present in a drawn graph, with their colour and node count. + + Built from the graph rather than the schema so it describes what is on + screen: a doc_type filtered out, or cut by the node cap, should not appear. + """ + counts: dict[str, int] = {} + for node in graph.nodes: + counts[node.doc_type] = counts.get(node.doc_type, 0) + 1 + return [ + {"doc_type": name, "count": counts[name], "color": color_for(brain, name)} + for name in sorted(counts, key=lambda n: (-counts[n], n)) + ] + + +def graph_node_specs(graph, anchor_size: int = 20, size: int = 13) -> list[dict]: + """Node payloads for the map renderer. + + Nothing is labelled on the canvas. Entity names are long and arbitrary β€” + drawn beside every dot they overlap each other and their own edges, and no + amount of truncation fixes a dense graph. The picture carries shape and + colour; identity comes from the tooltip, and the legend explains the colours. + + `label` is an empty string rather than None: None serialises to null and vis + draws that literally. + """ + specs = [] + for node in graph.nodes: + fields = {k: v for k, v in (node.data or {}).items() + if k not in ("id", "doc_type", "related_to")} + specs.append({ + "id": node.id, + "label": "", + "color": node.color, + "shape": "dot", + "size": anchor_size if node.is_anchor else size, + "title": node_tooltip(node.id, node.label, node.doc_type, fields), + }) + return specs + + +def graph_edge_specs(graph, color: str) -> list[dict]: + """Edge payloads. Unlabelled for the same reason as nodes β€” the relationship + is on the tooltip.""" + return [ + { + "source": edge.source, + "target": edge.target, + "label": "", + "title": edge_tooltip(edge.source, edge.target, edge.meaning), + "color": color, + } + for edge in graph.edges + ] + + def graph_theme(theme_type: Optional[str]) -> dict: """Label and edge colours for the map, given Streamlit's active theme. diff --git a/tests/test_graph.py b/tests/test_graph.py index 8a3fed3..f8d9671 100644 --- a/tests/test_graph.py +++ b/tests/test_graph.py @@ -58,3 +58,67 @@ def test_multiple_anchors(brain): def test_anchor_property(brain): g = build_graph(brain, ["product:checkout"], depth=1) assert g.anchor == "product:checkout" + + +# -- whole-index overview ------------------------------------------------------ + + +def test_overview_includes_every_entity_in_scope(brain): + from open_index.graph import build_overview_graph + + graph = build_overview_graph(brain, ["product"]) + assert {n.id for n in graph.nodes} == { + e.id for e in brain.backend.all_entities(["product"])} + + +def test_overview_only_draws_edges_with_both_ends_in_scope(brain): + """A half-edge to a filtered-out type would render as a line to nowhere.""" + from open_index.graph import build_overview_graph + + graph = build_overview_graph(brain, ["product"]) + ids = {n.id for n in graph.nodes} + assert all(e.source in ids and e.target in ids for e in graph.edges) + + +def test_overview_keeps_edges_between_included_types(brain): + from open_index.graph import build_overview_graph + + graph = build_overview_graph(brain, ["product", "issue"]) + assert graph.edges, "productβ†’issue edges should survive when both are in scope" + + +def test_overview_colours_nodes_by_doc_type(brain): + from open_index.graph import build_overview_graph + + graph = build_overview_graph(brain) + by_type = {n.doc_type: n.color for n in graph.nodes} + assert len(set(by_type.values())) > 1, "doc_types should be visually distinct" + + +def test_overview_cap_keeps_the_most_connected(brain): + """When the cap bites, it must keep the hubs β€” a random subset of a graph + is far less informative than its best-connected part.""" + from open_index.graph import build_overview_graph + from open_index.ui.view import edge_counts + + kept = {n.id for n in build_overview_graph(brain, limit=3).nodes} + assert len(kept) == 3 + + degree = edge_counts(brain) + dropped = {e.id for e in brain.backend.all_entities()} - kept + assert min(degree.get(i, 0) for i in kept) >= max(degree.get(i, 0) for i in dropped) + + +def test_overview_of_an_empty_scope(brain): + from open_index.graph import build_overview_graph + + graph = build_overview_graph(brain, ["nonexistent-type"]) + assert graph.nodes == [] and graph.edges == [] + + +def test_overview_deduplicates_edges(brain): + from open_index.graph import build_overview_graph + + graph = build_overview_graph(brain) + keys = [(e.source, e.target, e.meaning) for e in graph.edges] + assert len(keys) == len(set(keys)) diff --git a/tests/test_mcp_transport.py b/tests/test_mcp_transport.py index 0ffafc5..290d42e 100644 --- a/tests/test_mcp_transport.py +++ b/tests/test_mcp_transport.py @@ -198,3 +198,106 @@ def no_uvicorn(name, *args, **kwargs): monkeypatch.setattr(builtins, "__import__", no_uvicorn) with pytest.raises(SystemExit, match="open-index\\[serve\\]"): serve_http(str(brain.config.root)) + + +# -- proxy / load-balancer host validation ------------------------------------ +# +# The SDK turns on DNS-rebinding protection with a localhost-only allow-list, so +# every request arriving through a reverse proxy is rejected with +# "421 Invalid Host header". These pin the allow-list we build instead. + + +def test_public_url_host_is_allowed(): + from open_index.mcp_server import build_transport_security + + settings = build_transport_security(public_url="http://203.0.113.10/support/mcp") + assert settings.enable_dns_rebinding_protection is True + assert "203.0.113.10" in settings.allowed_hosts + + +def test_both_with_and_without_port_are_allowed(): + """A proxy drops the port when it is the scheme default; a direct client + sends it. Both must pass or one of the two paths breaks.""" + from open_index.mcp_server import build_transport_security + + hosts = build_transport_security(public_url="https://brain.acme.com/mcp").allowed_hosts + assert "brain.acme.com" in hosts + assert "brain.acme.com:*" in hosts + + +def test_explicit_host_and_port_survives(): + from open_index.mcp_server import build_transport_security + + hosts = build_transport_security( + public_url="https://brain.acme.com:8443/mcp").allowed_hosts + assert "brain.acme.com:8443" in hosts + assert "brain.acme.com" in hosts + + +def test_loopback_is_always_allowed(): + """Health checks and on-box debugging must keep working.""" + from open_index.mcp_server import build_transport_security + + hosts = build_transport_security(public_url="https://brain.acme.com/mcp").allowed_hosts + assert {"127.0.0.1", "127.0.0.1:*", "localhost", "localhost:*"} <= set(hosts) + + +def test_extra_allowed_hosts_are_honoured(): + from open_index.mcp_server import build_transport_security + + hosts = build_transport_security(allowed_hosts=["lb.internal", "other:9000"]).allowed_hosts + assert "lb.internal" in hosts and "other:9000" in hosts + + +def test_wildcard_disables_the_check(): + """Explicit opt-out for a trusted proxy that already validates Host.""" + from open_index.mcp_server import build_transport_security + + assert build_transport_security( + allowed_hosts=["*"]).enable_dns_rebinding_protection is False + + +def test_origins_cover_http_and_https(): + from open_index.mcp_server import build_transport_security + + origins = build_transport_security(public_url="https://brain.acme.com/mcp").allowed_origins + assert "https://brain.acme.com" in origins + assert "http://brain.acme.com" in origins + + +def test_blank_entries_are_ignored(): + from open_index.mcp_server import build_transport_security + + settings = build_transport_security(allowed_hosts=["", " "]) + assert settings.enable_dns_rebinding_protection is True + + +def test_serve_http_passes_the_allow_list_through(brain, monkeypatch): + """The settings must actually reach streamable_http_app.""" + import uvicorn + + captured = {} + monkeypatch.setattr(uvicorn, "run", lambda app, host, port: None) + + from open_index import mcp_server + + real = mcp_server.build_server + + def spy(b, read_only=False): + server = real(b, read_only=read_only) + original = server.streamable_http_app + + def wrapper(**kwargs): + captured.update(kwargs) + return original(**kwargs) + + server.streamable_http_app = wrapper + return server + + monkeypatch.setattr(mcp_server, "build_server", spy) + mcp_server.serve_http(str(brain.config.root), host="0.0.0.0", + public_url="https://brain.acme.com/mcp", + warn_unauthenticated=False) + + assert captured["host"] == "0.0.0.0" + assert "brain.acme.com" in captured["transport_security"].allowed_hosts diff --git a/tests/test_opensearch_builders.py b/tests/test_opensearch_builders.py index e8eec6f..9b6dde2 100644 --- a/tests/test_opensearch_builders.py +++ b/tests/test_opensearch_builders.py @@ -153,3 +153,53 @@ def test_reserved_keys_cover_the_metadata_fields(): from open_index.storage.opensearch_backend import _RESERVED_KEYS assert {"provenance", "valid_from", "valid_to"} <= _RESERVED_KEYS + + +# -- fuzzy search must not be handed non-text fields --------------------------- +# +# OpenSearch rejects the entire query with "Can only use fuzzy queries on keyword +# and text fields" if a numeric or date field is listed in multi_match. One +# `number` field in the schema therefore broke *all* search β€” found with a real +# dataset, not caught by the earlier synthetic ones. + + +def test_numeric_fields_are_kept_out_of_the_fuzzy_query(): + dt = DocType(doc_type="defect", fields=[ + FieldSpec(name="name", type="string", boost=6), + FieldSpec(name="symptom", type="text"), + FieldSpec(name="manhours", type="number"), + ]) + fields = _backend_with_types([dt])._search_fields(None) + joined = " ".join(fields) + assert "fields.symptom" in joined + assert "manhours" not in joined, "a numeric field would break the whole query" + + +def test_boolean_and_timestamp_fields_are_excluded_too(): + dt = DocType(doc_type="t", fields=[ + FieldSpec(name="name", type="string"), + FieldSpec(name="active", type="boolean"), + FieldSpec(name="seen_at", type="timestamp"), + ]) + joined = " ".join(_backend_with_types([dt])._search_fields(None)) + assert "active" not in joined and "seen_at" not in joined + + +def test_text_fields_keep_their_boosts(): + dt = DocType(doc_type="t", fields=[ + FieldSpec(name="title", type="string", boost=6), + FieldSpec(name="body", type="text", boost=2), + FieldSpec(name="count", type="number", boost=9), + ]) + fields = _backend_with_types([dt])._search_fields(None) + assert "fields.title^6" in fields + assert "fields.body^2" in fields + assert not any("count" in f for f in fields) + + +def test_date_detection_is_disabled_in_the_mapping(): + """A `string` field holding e.g. 2026-04-12 would otherwise be mapped as a + date, and then rejected by fuzzy search.""" + assert OpenSearchBackend.mapping()["mappings"]["date_detection"] is False + backend = _backend_with_types([DocType(doc_type="t")]) + assert backend._base_mapping()["mappings"]["date_detection"] is False diff --git a/tests/test_ui_app.py b/tests/test_ui_app.py index d5e8f6b..1b9a865 100644 --- a/tests/test_ui_app.py +++ b/tests/test_ui_app.py @@ -5,6 +5,7 @@ structure you had to hunt for, and a map that opened blank. """ +import os import shutil from pathlib import Path @@ -22,7 +23,9 @@ def _run(brain_dir, monkeypatch): monkeypatch.setenv("OPEN_INDEX_DIR", str(brain_dir)) - return AppTest.from_file(str(APP), default_timeout=60).run() + # Generous timeout: each of these boots a real Streamlit script run, and on + # a loaded machine (the full suite, or a CI runner) 60s flaked once. + return AppTest.from_file(str(APP), default_timeout=180).run() @pytest.fixture @@ -55,10 +58,6 @@ def test_empty_brain_runs_without_exceptions(empty): assert not empty.exception, [e.value for e in empty.exception] -def test_tabs(populated): - assert [t.label for t in populated.tabs] == ["Explore", "Map", "Analytics", "Jobs"] - - # -- structure is visible without hunting for it ------------------------------ @@ -86,20 +85,27 @@ def test_empty_brain_sidebar_explains_what_to_do(empty): # -- the map no longer opens blank -------------------------------------------- -def test_map_preselects_anchors(populated): - """The original complaint: nothing rendered until you made a selection.""" - anchors = next(m for m in populated.multiselect if m.label == "Anchors") - assert anchors.value, "map opened with no anchors selected" - - -def test_map_anchor_options_are_entity_labels(populated): - anchors = next(m for m in populated.multiselect if m.label == "Anchors") - assert all("(" in option and ")" in option for option in anchors.options) +def test_map_draws_without_any_selection(populated): + """The original complaint: nothing rendered until you made a selection. The + map now opens on the whole index, so there is always something to see.""" + populated.tabs[3].run() # Map + assert not populated.exception def test_map_doc_type_filter_defaults_to_everything(populated): - types = next(m for m in populated.multiselect if m.label == "Doc types to include") + types = next(m for m in populated.multiselect if m.label == "Doc types shown") assert set(types.value) == set(types.options) + assert types.options, "every populated doc_type should be filterable" + + +def test_map_filter_lists_only_populated_doc_types(populated, tmp_path): + """A doc_type with no entities would be a dead checkbox.""" + from open_index.brain import Brain + from open_index.schema import DocType + + types = next(m for m in populated.multiselect if m.label == "Doc types shown") + counts = Brain.open(os.environ["OPEN_INDEX_DIR"]).counts() + assert all(counts.get(name, 0) > 0 for name in types.options) # -- explore ------------------------------------------------------------------ @@ -198,3 +204,65 @@ def test_row_css_inherits_colour_through_the_label_element(): """Streamlit wraps button labels in

, which otherwise keeps its own colour and ignores the inherit on the button.""" assert "> button p{color:inherit" in view.ROW_CSS + + +# -- How to use ---------------------------------------------------------------- + + +def test_help_is_the_first_tab_so_it_opens_on_load(populated): + """Streamlit selects the first tab, so a first-time visitor lands on the + explanation instead of having to find it.""" + assert [t.label for t in populated.tabs][0] == view.HELP_TAB == "How to use?" + + +def test_schema_sits_between_help_and_explore(populated): + labels = [t.label for t in populated.tabs] + assert labels[:3] == ["How to use?", "Schema", "Explore"] + + +def test_tab_guide_matches_the_tabs_actually_rendered(populated): + """A stale list of what-each-tab-does is worse than none.""" + assert [t.label for t in populated.tabs] == [n for n, _ in view.TAB_GUIDE] + + +def test_documented_tools_match_the_registered_mcp_tools(brain): + """The tab must not advertise a tool the server does not expose, nor miss one.""" + pytest.importorskip("mcp") + import asyncio as _asyncio + + from open_index.mcp_server import build_server + + server = build_server(brain) + registered = {t.name for t in + _asyncio.new_event_loop().run_until_complete(server.list_tools())} + documented = {name.split("(")[0] for name, _ in view.READ_TOOLS + view.WRITE_TOOLS} + assert documented == registered, ( + f"docs vs server mismatch: only-in-docs={documented - registered}, " + f"only-on-server={registered - documented}") + + +def test_read_only_tools_are_the_documented_read_set(brain): + pytest.importorskip("mcp") + import asyncio as _asyncio + + from open_index.mcp_server import build_server + + server = build_server(brain, read_only=True) + registered = {t.name for t in + _asyncio.new_event_loop().run_until_complete(server.list_tools())} + assert {n.split("(")[0] for n, _ in view.READ_TOOLS} == registered + + +def test_connection_block_is_valid_json_with_the_url(): + import json + + block = json.loads(view.mcp_client_config("https://x.example.com/demo/mcp", "demo")) + assert block["mcpServers"]["demo"]["url"] == "https://x.example.com/demo/mcp" + assert block["mcpServers"]["demo"]["type"] == "http" + + +def test_connection_block_appends_the_mcp_path(): + import json + + block = json.loads(view.mcp_client_config("https://x.example.com/demo")) + assert block["mcpServers"]["open-index"]["url"].endswith("/mcp") diff --git a/tests/test_ui_view.py b/tests/test_ui_view.py index eca21f6..c6dc3d1 100644 --- a/tests/test_ui_view.py +++ b/tests/test_ui_view.py @@ -226,3 +226,155 @@ def test_every_theme_defines_the_full_palette(): keys = {"node_label", "edge_label", "edge", "stroke_width"} for theme in ("dark", "light"): assert keys <= set(view.graph_theme(theme)) + + +# -- Schema tab ---------------------------------------------------------------- + + +def test_schema_field_rows_describe_search_behaviour(brain): + dt = brain.config.doc_type("issue") + rows = {r["field"]: r for r in view.schema_field_rows(dt)} + assert rows["name"]["searched by"] == "keyword match" + assert rows["description"]["searched by"] == "meaning (vector)" + assert rows["name"]["weight"] == "6Γ—" + + +def test_unsearched_fields_show_no_weight(brain): + from open_index.schema import DocType, FieldSpec + + dt = DocType(doc_type="t", fields=[FieldSpec(name="blob", search="none", boost=9)]) + row = view.schema_field_rows(dt)[0] + assert row["searched by"] == "not searched" + assert row["weight"] == "β€”", "a weight on an unsearched field is misleading" + + +def test_required_fields_are_marked(brain): + from open_index.schema import DocType, FieldSpec + + dt = DocType(doc_type="t", fields=[FieldSpec(name="owner", required=True)]) + assert view.schema_field_rows(dt)[0]["required"] == "yes" + + +def test_relationship_rows_merge_declared_and_observed(brain): + rows = {r["relationship"]: r for r in view.schema_relationship_rows(brain, "product")} + assert "has common issue" in rows + assert rows["has common issue"]["declared"] == "yes" + assert rows["has common issue"]["points at"] == "issue" + assert rows["has common issue"]["in use"] > 0 + + +def test_undeclared_relationships_in_use_are_still_listed(brain): + """An edge nobody declared but everything uses is worth seeing.""" + from open_index.models import Entity, Relationship + + brain.put_entity(Entity( + id="product:improvised", doc_type="product", name="Improvised", + related_to=[Relationship(target="issue:no-results", + relationship_edge_meaning="totally made up")])) + rows = {r["relationship"]: r for r in view.schema_relationship_rows(brain, "product")} + assert rows["totally made up"]["declared"] == "no" + assert rows["totally made up"]["in use"] == 1 + + +def test_declared_but_unused_relationships_show_zero(brain): + from open_index.schema import DocType, RelationshipSpec + + brain.create_doc_type(DocType( + doc_type="unused_rel", + relationships=[RelationshipSpec(name="never used", target_doc_type="issue")])) + row = view.schema_relationship_rows(brain, "unused_rel")[0] + assert row["declared"] == "yes" and row["in use"] == 0 + + +def test_help_tab_is_first_in_the_guide(): + assert view.TAB_GUIDE[0][0] == view.HELP_TAB + assert [n for n, _ in view.TAB_GUIDE][:3] == ["How to use?", "Schema", "Explore"] + + +# -- map readability ----------------------------------------------------------- +# +# Long entity names drawn next to their dot were the main thing making the map +# unreadable; the full text moves to the hover tooltip. + + +def test_nodes_carry_no_label(brain): + """Entity names are long and arbitrary; drawn beside every dot they overlap + each other. Identity comes from the tooltip instead.""" + from open_index.graph import build_overview_graph + + specs = view.graph_node_specs(build_overview_graph(brain)) + assert specs + assert all(s["label"] == "" for s in specs) + # Empty string, not None: None serialises to null and vis draws that. + assert all(s["label"] is not None for s in specs) + + +def test_every_node_carries_its_identity_on_hover(brain): + from open_index.graph import build_overview_graph + + specs = {s["id"]: s for s in view.graph_node_specs(build_overview_graph(brain))} + spec = specs["product:checkout"] + assert "Checkout" in spec["title"] + assert "product:checkout" in spec["title"] + + +def test_edges_carry_no_label_but_name_the_relationship(brain): + from open_index.graph import build_overview_graph + + specs = view.graph_edge_specs(build_overview_graph(brain), "#ccc") + assert specs + assert all(s["label"] == "" for s in specs) + assert any("has common issue" in s["title"] for s in specs) + + +def test_node_colour_comes_from_the_doc_type(brain): + from open_index.graph import build_overview_graph + + graph = build_overview_graph(brain) + by_id = {n.id: n.color for n in graph.nodes} + assert all(s["color"] == by_id[s["id"]] for s in view.graph_node_specs(graph)) + + +def test_node_tooltip_carries_the_full_name_and_type(): + tip = view.node_tooltip("issue:x", "A very long name that got truncated", + "issue", {"severity": "high"}) + assert "A very long name that got truncated" in tip + assert "issue:x" in tip + assert "severity: high" in tip + + +def test_node_tooltip_skips_empty_fields_and_caps_length(): + tip = view.node_tooltip("t:x", "N", "t", + {f"f{i}": "v" for i in range(20)} | {"blank": ""}) + assert "blank" not in tip + assert len(tip.splitlines()) <= 7 + + +def test_edge_tooltip_names_the_relationship(): + tip = view.edge_tooltip("a:1", "b:2", "depends on") + assert "depends on" in tip and "a:1" in tip and "b:2" in tip + + +def test_edge_tooltip_handles_an_unlabelled_edge(): + assert "related" in view.edge_tooltip("a:1", "b:2", "") + + +def test_legend_describes_what_is_on_screen(brain): + from open_index.graph import build_overview_graph + + graph = build_overview_graph(brain, ["product", "issue"]) + rows = view.legend_rows(brain, graph) + assert {r["doc_type"] for r in rows} <= {"product", "issue"} + assert all(r["color"].startswith("#") for r in rows) + assert sum(r["count"] for r in rows) == len(graph.nodes) + + +def test_legend_is_ordered_by_count(brain): + from open_index.graph import build_overview_graph + + rows = view.legend_rows(brain, build_overview_graph(brain)) + assert [r["count"] for r in rows] == sorted([r["count"] for r in rows], reverse=True) + + +def test_graph_width_fits_beside_the_legend(): + assert view.GRAPH_WIDTH <= 1000