From a3b46594015ec37776d956b41e34cb273b89f4c6 Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 19:05:39 +0530 Subject: [PATCH 01/13] feat(deploy): many indexes on one host, each with its own MCP endpoint and UI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds deploy/fleet β€” a generator that runs N brains behind one nginx, so each index is reachable at //mcp with an explorer at //ui. Why one setup rather than one per index: `serve` handles a single brain per process, so each index needs its own container β€” but the OpenSearch index name is already per-brain, so they share one cluster. Measured on a 2-vCPU/3.8GB VM: the cluster is 983MB once, while an index costs ~255MB (MCP) + ~71MB (UI). fleet.py generates compose, nginx config and credentials from indexes.yml: ./fleet.py up | add | tokens | status | logs Two bugs this surfaced, both fixed here: 1. `serve` could not sit behind any reverse proxy. The MCP SDK enables DNS-rebinding protection with a localhost-only allow-list, so a proxied request arrives with a foreign Host and is rejected `421 Invalid Host header`. Passing a non-localhost bind address would have silently disabled the protection instead, so serve_http now builds an explicit allow-list from --public-url and the new --allowed-host / OPEN_INDEX_ALLOWED_HOSTS, keeping the check on. `*` opts out for a trusted proxy. 2. A single shared htpasswd let the `sales` UI password open the `support` UI β€” nginx accepts any user present in the file it is given. Credentials are now per-index files, so the UI isolates the same way the bearer tokens do. The UI needs a gate at all because Streamlit ships no authentication; published as-is, anyone reaching the host could read an entire brain. It stays read-only (writes go through MCP or the CLI) and can be dropped per index with ui: false. Verified on the VM: both endpoints per index, cross-index credentials rejected on both doors, data isolation between cluster indexes, Streamlit served under its path prefix with websockets working. docs/multi-index.md covers architecture, capacity, LB setup, access and population. 451 tests pass; mcp_server.py at 100%. Co-Authored-By: Claude Opus 5 (1M context) --- .gitignore | 4 + README.md | 3 +- deploy/fleet/fleet.py | 549 ++++++++++++++++++++++++++++++++++++ deploy/fleet/indexes.yml | 39 +++ docs/multi-index.md | 305 ++++++++++++++++++++ open_index/cli.py | 9 +- open_index/mcp_server.py | 63 ++++- tests/test_mcp_transport.py | 103 +++++++ 8 files changed, 1072 insertions(+), 3 deletions(-) create mode 100755 deploy/fleet/fleet.py create mode 100644 deploy/fleet/indexes.yml create mode 100644 docs/multi-index.md diff --git a/.gitignore b/.gitignore index 48b835e..79f1518 100644 --- a/.gitignore +++ b/.gitignore @@ -26,3 +26,7 @@ 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/nginx/ 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..f4722bd --- /dev/null +++ b/deploy/fleet/fleet.py @@ -0,0 +1,549 @@ +#!/usr/bin/env python3 +"""Run several open-index brains on one host, behind one nginx. + +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. + +nginx maps // to that brain's container, so an agent connects to + //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/nginx 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" +NGINX_DIR = HERE / "nginx" +NGINX_CONF = NGINX_DIR / "default.conf" +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}") + 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") + 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 htpasswd_hash(password: str) -> str: + """An nginx-compatible password hash. + + Uses `openssl passwd -apr1` β€” the format htpasswd has always produced, and + salted, unlike the `{SHA}` scheme nginx also accepts. + """ + result = subprocess.run(["openssl", "passwd", "-apr1", password], + capture_output=True, text=True) + if result.returncode != 0: + die("openssl is required to hash the UI passwords (apt install openssl)") + 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() + 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 β€” see write_htpasswd_files. + if entry.get("ui", True) and not values.get(ui_pw_var(name)): + values[ui_pw_var(name)] = secrets.token_urlsafe(18) + 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 + + +def write_htpasswd_files(config: dict, values: dict) -> None: + """One basic-auth file per index, not one shared file. + + The MCP endpoint carries its own bearer token, but Streamlit has no + authentication whatsoever β€” published as-is, anyone who can reach the host + could read the whole brain. This is that gate. + + It is per-index on purpose: nginx's `auth_basic_user_file` accepts *any* + user in the file it is given, so a single shared file would let the `sales` + credentials open the `support` UI. Separate files keep each index's UI to + its own credentials, matching how the bearer tokens already behave. + """ + directory = NGINX_DIR / "htpasswd.d" + if directory.exists(): + shutil.rmtree(directory) + directory.mkdir(parents=True) + + for entry in config["indexes"]: + if not entry.get("ui", True): + continue + name = entry["name"] + path = directory / name + path.write_text(f"{name}:{htpasswd_hash(values[ui_pw_var(name)])}\n") + path.chmod(0o644) # nginx runs as its own user inside the container + + +# -- 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", "") + 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: + OPEN_INDEX_TOKEN: ${{{env_var(name)}}} + 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. + 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")) + + 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 nginx in +# front doing path routing. + +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)} + + nginx: + image: nginx:1.27-alpine + container_name: oi-nginx + volumes: + - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro + - ./nginx/htpasswd.d:/etc/nginx/htpasswd.d:ro + ports: + - "{config['http_port']}:80" + depends_on: +{chr(10).join(dep for e in config["indexes"] + for dep in ([f" - brain-{e['name']}"] + + ([f" - ui-{e['name']}"] if e.get("ui", True) else [])))} + restart: unless-stopped + +volumes: + opensearch-data: + model-cache: +""" + + +def render_nginx(config: dict) -> str: + blocks = [] + for entry in config["indexes"]: + name = entry["name"] + blocks.append(f""" + # {name} β€” {entry.get('description', '')} + location /{name}/ {{ + # The trailing slash on proxy_pass strips the /{name} prefix, so + # /{name}/mcp reaches the brain as /mcp. + proxy_pass http://brain-{name}:8080/; + + proxy_http_version 1.1; + proxy_set_header Connection ""; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + # Authorization must survive the hop or every request 401s. + proxy_set_header Authorization $http_authorization; + + # Streamable HTTP keeps responses open; buffering would stall them. + proxy_buffering off; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + }} + + # Tolerate a missing trailing slash: /{name} -> /{name}/ + location = /{name} {{ return 308 /{name}/; }}""") + + if entry.get("ui", True): + blocks.append(f""" + # {name} explorer UI. Basic auth because Streamlit has none of its own. + location /{name}/ui {{ + auth_basic "{name} index"; + auth_basic_user_file /etc/nginx/htpasswd.d/{name}; + + # No trailing slash on proxy_pass: Streamlit is configured with + # baseUrlPath={name}/ui and expects to receive the full path. + proxy_pass http://ui-{name}:8501; + + proxy_http_version 1.1; + # Streamlit talks to the browser over a websocket; without the upgrade + # headers the page renders and then hangs "connecting". + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + proxy_buffering off; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + }}""") + + listing = {} + for e in config["indexes"]: + item = {"mcp": f"{config['public_base_url']}/{e['name']}/mcp", + "description": e.get("description", ""), + "read_only": bool(e.get("read_only"))} + if e.get("ui", True): + item["ui"] = f"{config['public_base_url']}/{e['name']}/ui" + listing[e["name"]] = item + + return f"""# GENERATED BY fleet.py β€” do not edit. Change indexes.yml and re-run `fleet.py up`. + +server {{ + listen 80; + server_name _; + + # Uploading a knowledge file through an agent can exceed the 1MB default. + client_max_body_size 64m; +{"".join(blocks)} + + # Load-balancer health probe. Deliberately unauthenticated and free of any + # brain detail. + location = /healthz {{ + access_log off; + return 200 "ok\\n"; + add_header Content-Type text/plain; + }} + + # Directory of what this host serves. Names and URLs only β€” no tokens. + location = / {{ + default_type application/json; + return 200 '{json.dumps(listing, indent=2)}'; + }} +}} +""" + + +# -- brains ------------------------------------------------------------------- + + +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 passwords to build htpasswd, so generate any that + # are missing rather than failing on a half-populated .env. + if values is None: + values = ensure_secrets(config) + NGINX_DIR.mkdir(exist_ok=True) + COMPOSE.write_text(render_compose(config)) + NGINX_CONF.write_text(render_nginx(config)) + write_htpasswd_files(config, values) + print(f" wrote {COMPOSE.name}, nginx/default.conf and nginx/htpasswd.d/") + + +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) + + 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.yml b/deploy/fleet/indexes.yml new file mode 100644 index 0000000..9f56039 --- /dev/null +++ b/deploy/fleet/indexes.yml @@ -0,0 +1,39 @@ +# 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 will reach this host. Used for the connection details printed by +# `fleet.py tokens` and by each container's startup banner β€” set it to the load +# balancer's address, not the VM's, once the LB is in front. +public_base_url: http://20.83.97.30 + +# Host directory holding one subdirectory per brain. +brains_root: /home/azureuser/brains + +# Port nginx publishes on the host. The LB should forward to this. +http_port: 80 + +# 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..03233e1 --- /dev/null +++ b/docs/multi-index.md @@ -0,0 +1,305 @@ +# 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 nginx. + +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 | +| nginx | 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. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ nginx :80 ────────────────┐ + β”‚ /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: /home/azureuser/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 +./fleet.py up +``` + +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 nginx 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 container starts and nginx 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 +> `nginx/default.conf` are regenerated on every run β€” edit the former, never the +> latter two. + +--- + +## 3. Put it behind a load balancer + +nginx publishes on `http_port` (80 by default). Point the LB at that. + +**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. + +**Terminate TLS at the LB.** The brains speak plain HTTP. Once TLS is on, set +`public_base_url: https://...` and re-run `./fleet.py up` so each brain +advertises the right URL. + +**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; a buffering LB +will appear to hang. The bundled nginx sets `proxy_buffering off` β€” 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 credential file, so the `sales` password does not +open the `support` UI. + +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, +the same as nginx already does. + +--- + +## 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 /home/azureuser/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/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/tests/test_mcp_transport.py b/tests/test_mcp_transport.py index 0ffafc5..9336539 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://20.83.97.30/support/mcp") + assert settings.enable_dns_rebinding_protection is True + assert "20.83.97.30" 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 From 534250c80410ab424b699f0aa5a7ac9cdddb507b Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 19:09:19 +0530 Subject: [PATCH 02/13] deploy: point the fleet at the two demo indexes --- deploy/fleet/indexes.yml | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/deploy/fleet/indexes.yml b/deploy/fleet/indexes.yml index 9f56039..320323a 100644 --- a/deploy/fleet/indexes.yml +++ b/deploy/fleet/indexes.yml @@ -23,11 +23,15 @@ http_port: 80 opensearch_heap: 512m indexes: - - name: support - description: Customer support knowledge β€” products, issues, segments. + - name: aviation-mro-index + description: >- + Line and base maintenance for a narrowbody fleet β€” ATA taxonomy, fault + messages, task cards, MEL entries and defect history. SYNTHETIC DEMO DATA. - - name: sales - description: Sales pipeline β€” accounts, deals, contacts. + - name: commercial-lines-index + description: >- + Commercial-lines placement for an SMB brokerage β€” carriers, appetite + rules, class codes, state rules and submission playbooks. SYNTHETIC DEMO DATA. # read_only exposes search/get/navigation but no write tools. Useful for an # index that agents should consult but never modify. From 04ae471b6a7b767edd0b52d5a415e01d3d51c37d Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 19:20:17 +0530 Subject: [PATCH 03/13] fix(opensearch): keep non-text fields out of the fuzzy query MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Surfaced by a real dataset: every search against it failed with Can only use fuzzy queries on keyword and text fields β€” not on [fields.reported_date] which is of type [date] Two causes, both fixed: - `_search_fields` listed every field whose `search` was not "none", regardless of declared type. OpenSearch maps `number` to long and `timestamp` to date, and rejects the *entire* multi_match if either appears β€” so one numeric field in a schema broke all search for that brain. Only string/text fields go into the full-text query now. - `reported_date` was declared `string`, but its date-shaped values were mapped as `date` by dynamic detection, which produced the same rejection for a correctly-declared field. `date_detection` is off; the schema decides the type, not a guess from the first document indexed. The synthetic test brains had no numeric or date-like fields, which is why this survived until real data arrived. Four regression tests cover both. Co-Authored-By: Claude Opus 5 (1M context) --- open_index/storage/opensearch_backend.py | 17 ++++++++ tests/test_opensearch_builders.py | 50 ++++++++++++++++++++++++ 2 files changed, 67 insertions(+) diff --git a/open_index/storage/opensearch_backend.py b/open_index/storage/opensearch_backend.py index cbb8349..cd1c394 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()] 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 From ef00fa39d3991bd1b9b6f51bd65fe12e46a06640 Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 19:27:03 +0530 Subject: [PATCH 04/13] fix(opensearch): recreate the index with our mapping if it goes missing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ensure_schema runs once at open. If the index is dropped afterwards β€” cluster rebuild, manual DELETE, restored snapshot β€” OpenSearch auto-creates it on the next write with dynamic mapping: doc_type becomes text (every aggregation fails) and date-shaped strings become dates (fuzzy search fails). Both surface long after the write that caused them. One existence check on the write path is cheaper than that debugging. Co-Authored-By: Claude Opus 5 (1M context) --- open_index/storage/opensearch_backend.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/open_index/storage/opensearch_backend.py b/open_index/storage/opensearch_backend.py index cd1c394..92fc3bb 100644 --- a/open_index/storage/opensearch_backend.py +++ b/open_index/storage/opensearch_backend.py @@ -390,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 ) @@ -408,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: From dc63a229708645bbb5e30955cf7ddb74f280ed66 Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 19:37:44 +0530 Subject: [PATCH 05/13] deploy(fleet): re-apply brain permissions on every up MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The container writes with umask 022, so any directory it creates loses group write and the operator can no longer drop a CSV in or rsync data across without sudo β€” which is exactly what happened loading the first real dataset. --- deploy/fleet/fleet.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/deploy/fleet/fleet.py b/deploy/fleet/fleet.py index f4722bd..ff017b2 100755 --- a/deploy/fleet/fleet.py +++ b/deploy/fleet/fleet.py @@ -395,6 +395,20 @@ def render_nginx(config: dict) -> str: # -- 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 @@ -464,6 +478,7 @@ def cmd_up(config: dict) -> None: 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"]) From e469ad3041f7f33c1f8dd81a35a701a7a3ed6d6d Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 19:39:31 +0530 Subject: [PATCH 06/13] fix(fleet): never recreate the bind-mounted htpasswd directory rmtree + mkdir swaps the directory inode. nginx has the old one bind-mounted, so it keeps serving an empty directory: the credential files are plainly present on the host while nginx logs 'No such file or directory' and every UI request 403s. Prune by deleting files instead. --- deploy/fleet/fleet.py | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/deploy/fleet/fleet.py b/deploy/fleet/fleet.py index ff017b2..f36cc14 100755 --- a/deploy/fleet/fleet.py +++ b/deploy/fleet/fleet.py @@ -164,18 +164,26 @@ def write_htpasswd_files(config: dict, values: dict) -> None: its own credentials, matching how the bearer tokens already behave. """ directory = NGINX_DIR / "htpasswd.d" - if directory.exists(): - shutil.rmtree(directory) - directory.mkdir(parents=True) + directory.mkdir(parents=True, exist_ok=True) + wanted = set() for entry in config["indexes"]: if not entry.get("ui", True): continue name = entry["name"] + wanted.add(name) path = directory / name path.write_text(f"{name}:{htpasswd_hash(values[ui_pw_var(name)])}\n") path.chmod(0o644) # nginx runs as its own user inside the container + # Prune removed indexes by deleting files, never by replacing the directory. + # This directory is bind-mounted into nginx; recreating it swaps the inode + # and the running container keeps the old, now-empty one β€” the files are + # visibly present on the host while nginx reports "No such file". + for stale in directory.iterdir(): + if stale.name not in wanted: + stale.unlink() + # -- rendering ---------------------------------------------------------------- From 3c18d49e1c716c1c3441ad6bd0af01af754cf856 Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 20:51:16 +0530 Subject: [PATCH 07/13] feat(fleet): HTTPS via Caddy on a real hostname, optional auth, How-to-use tab --- deploy/fleet/caddy/Caddyfile | 54 ++++++++ deploy/fleet/fleet.py | 259 ++++++++++++++++------------------- deploy/fleet/indexes.yml | 11 +- open_index/ui/app.py | 78 ++++++++++- open_index/ui/view.py | 58 ++++++++ tests/test_ui_app.py | 59 +++++++- 6 files changed, 371 insertions(+), 148 deletions(-) create mode 100644 deploy/fleet/caddy/Caddyfile diff --git a/deploy/fleet/caddy/Caddyfile b/deploy/fleet/caddy/Caddyfile new file mode 100644 index 0000000..bea7d72 --- /dev/null +++ b/deploy/fleet/caddy/Caddyfile @@ -0,0 +1,54 @@ +# GENERATED BY fleet.py β€” do not edit. Change indexes.yml and re-run `fleet.py up`. + +20.83.97.30.nip.io { + # Load-balancer probe: unauthenticated, and free of any index detail. + handle /healthz { + respond "ok" 200 + } + + # aviation-mro-index β€” explorer UI. No prefix stripping: Streamlit runs with + # baseUrlPath=aviation-mro-index/ui and expects the full path. + handle /aviation-mro-index/ui* { + reverse_proxy ui-aviation-mro-index:8501 + } + # aviation-mro-index β€” MCP endpoint. handle_path strips the /aviation-mro-index prefix so the + # brain receives /mcp. + handle_path /aviation-mro-index/* { + reverse_proxy brain-aviation-mro-index:8080 { + # Streamable HTTP holds responses open; never buffer them. + flush_interval -1 + } + } + # commercial-lines-index β€” explorer UI. No prefix stripping: Streamlit runs with + # baseUrlPath=commercial-lines-index/ui and expects the full path. + handle /commercial-lines-index/ui* { + reverse_proxy ui-commercial-lines-index:8501 + } + # commercial-lines-index β€” MCP endpoint. handle_path strips the /commercial-lines-index prefix so the + # brain receives /mcp. + handle_path /commercial-lines-index/* { + reverse_proxy brain-commercial-lines-index:8080 { + # Streamable HTTP holds responses open; never buffer them. + flush_interval -1 + } + } + + # Directory of what this host serves. Names and URLs only. + handle { + header Content-Type application/json + respond `{ + "aviation-mro-index": { + "mcp": "https://20.83.97.30.nip.io/aviation-mro-index/mcp", + "description": "Line and base maintenance for a narrowbody fleet \u2014 ATA taxonomy, fault messages, task cards, MEL entries and defect history. SYNTHETIC DEMO DATA.", + "read_only": false, + "ui": "https://20.83.97.30.nip.io/aviation-mro-index/ui" + }, + "commercial-lines-index": { + "mcp": "https://20.83.97.30.nip.io/commercial-lines-index/mcp", + "description": "Commercial-lines placement for an SMB brokerage \u2014 carriers, appetite rules, class codes, state rules and submission playbooks. SYNTHETIC DEMO DATA.", + "read_only": false, + "ui": "https://20.83.97.30.nip.io/commercial-lines-index/ui" + } +}` 200 + } +} diff --git a/deploy/fleet/fleet.py b/deploy/fleet/fleet.py index f36cc14..18353ce 100755 --- a/deploy/fleet/fleet.py +++ b/deploy/fleet/fleet.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 -"""Run several open-index brains on one host, behind one nginx. +"""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. -nginx maps // to that brain's container, so an agent connects to +Caddy maps // to that brain, terminates TLS, and serves each index's UI //mcp Commands: @@ -18,7 +18,7 @@ ./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/nginx config. +truth β€” edit it rather than the generated compose/Caddy config. """ from __future__ import annotations @@ -37,8 +37,8 @@ REPO = HERE.parent.parent CONFIG = HERE / "indexes.yml" COMPOSE = HERE / "docker-compose.generated.yml" -NGINX_DIR = HERE / "nginx" -NGINX_CONF = NGINX_DIR / "default.conf" +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 @@ -66,6 +66,10 @@ def load_config() -> dict: 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 [] @@ -97,16 +101,18 @@ def ui_pw_var(name: str) -> str: return "OPEN_INDEX_UI_PASSWORD_" + name.upper().replace("-", "_") -def htpasswd_hash(password: str) -> str: - """An nginx-compatible password hash. +def caddy_password_hash(password: str) -> str: + """A bcrypt hash in the form Caddy's basicauth expects. - Uses `openssl passwd -apr1` β€” the format htpasswd has always produced, and - salted, unlike the `{SHA}` scheme nginx also accepts. + 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(["openssl", "passwd", "-apr1", password], - capture_output=True, text=True) + 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("openssl is required to hash the UI passwords (apt install openssl)") + die(f"could not hash the UI password via caddy: {result.stderr.strip()}") return result.stdout.strip() @@ -129,6 +135,11 @@ def ensure_secrets(config: dict) -> dict: 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"] @@ -136,9 +147,14 @@ def ensure_secrets(config: dict) -> dict: 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 β€” see write_htpasswd_files. + # exposed; Caddy gets the bcrypt hash via the environment. if entry.get("ui", True) and not values.get(ui_pw_var(name)): - values[ui_pw_var(name)] = secrets.token_urlsafe(18) + 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.", @@ -151,40 +167,6 @@ def ensure_secrets(config: dict) -> dict: return values -def write_htpasswd_files(config: dict, values: dict) -> None: - """One basic-auth file per index, not one shared file. - - The MCP endpoint carries its own bearer token, but Streamlit has no - authentication whatsoever β€” published as-is, anyone who can reach the host - could read the whole brain. This is that gate. - - It is per-index on purpose: nginx's `auth_basic_user_file` accepts *any* - user in the file it is given, so a single shared file would let the `sales` - credentials open the `support` UI. Separate files keep each index's UI to - its own credentials, matching how the bearer tokens already behave. - """ - directory = NGINX_DIR / "htpasswd.d" - directory.mkdir(parents=True, exist_ok=True) - - wanted = set() - for entry in config["indexes"]: - if not entry.get("ui", True): - continue - name = entry["name"] - wanted.add(name) - path = directory / name - path.write_text(f"{name}:{htpasswd_hash(values[ui_pw_var(name)])}\n") - path.chmod(0o644) # nginx runs as its own user inside the container - - # Prune removed indexes by deleting files, never by replacing the directory. - # This directory is bind-mounted into nginx; recreating it swaps the inode - # and the running container keeps the old, now-empty one β€” the files are - # visibly present on the host while nginx reports "No such file". - for stale in directory.iterdir(): - if stale.name not in wanted: - stale.unlink() - - # -- rendering ---------------------------------------------------------------- @@ -199,6 +181,8 @@ def render_compose(config: dict) -> str: 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}: @@ -210,8 +194,7 @@ def render_compose(config: dict) -> str: container_name: oi-brain-{name} command: {command} environment: - OPEN_INDEX_TOKEN: ${{{env_var(name)}}} - OPEN_INDEX_SEARCH_BACKEND: opensearch +{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('-', '_')} @@ -241,6 +224,8 @@ def render_compose(config: dict) -> str: 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 @@ -258,10 +243,22 @@ def render_compose(config: dict) -> str: 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 nginx in -# front doing path routing. +# One shared OpenSearch cluster, one brain container per index, one Caddy in +# front doing path routing and TLS. services: opensearch: @@ -291,111 +288,94 @@ def render_compose(config: dict) -> str: restart: unless-stopped {"".join(services)} - nginx: - image: nginx:1.27-alpine - container_name: oi-nginx + caddy: + image: caddy:2.8-alpine + container_name: oi-caddy volumes: - - ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro - - ./nginx/htpasswd.d:/etc/nginx/htpasswd.d:ro + - ./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: - - "{config['http_port']}:80" - depends_on: -{chr(10).join(dep for e in config["indexes"] - for dep in ([f" - brain-{e['name']}"] - + ([f" - ui-{e['name']}"] if e.get("ui", True) else [])))} - restart: unless-stopped + - "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_nginx(config: dict) -> str: - blocks = [] - for entry in config["indexes"]: - name = entry["name"] - blocks.append(f""" - # {name} β€” {entry.get('description', '')} - location /{name}/ {{ - # The trailing slash on proxy_pass strips the /{name} prefix, so - # /{name}/mcp reaches the brain as /mcp. - proxy_pass http://brain-{name}:8080/; - - proxy_http_version 1.1; - proxy_set_header Connection ""; - proxy_set_header Host $host; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - # Authorization must survive the hop or every request 401s. - proxy_set_header Authorization $http_authorization; - - # Streamable HTTP keeps responses open; buffering would stall them. - proxy_buffering off; - proxy_read_timeout 3600s; - proxy_send_timeout 3600s; - }} - - # Tolerate a missing trailing slash: /{name} -> /{name}/ - location = /{name} {{ return 308 /{name}/; }}""") +def render_caddyfile(config: dict) -> str: + """Caddy config: one site, one route per index, automatic HTTPS. - if entry.get("ui", True): - blocks.append(f""" - # {name} explorer UI. Basic auth because Streamlit has none of its own. - location /{name}/ui {{ - auth_basic "{name} index"; - auth_basic_user_file /etc/nginx/htpasswd.d/{name}; - - # No trailing slash on proxy_pass: Streamlit is configured with - # baseUrlPath={name}/ui and expects to receive the full path. - proxy_pass http://ui-{name}:8501; - - proxy_http_version 1.1; - # Streamlit talks to the browser over a websocket; without the upgrade - # headers the page renders and then hangs "connecting". - proxy_set_header Upgrade $http_upgrade; - proxy_set_header Connection "upgrade"; - proxy_set_header Host $host; - proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; - proxy_set_header X-Forwarded-Proto $scheme; - - proxy_buffering off; - proxy_read_timeout 3600s; - proxy_send_timeout 3600s; - }}""") + 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"{config['public_base_url']}/{e['name']}/mcp", + 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"{config['public_base_url']}/{e['name']}/ui" + item["ui"] = f"{base}/{e['name']}/ui" listing[e["name"]] = item + directory = json.dumps(listing, indent=2).replace("`", "'") - return f"""# GENERATED BY fleet.py β€” do not edit. Change indexes.yml and re-run `fleet.py up`. + 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 + }} + }}""") -server {{ - listen 80; - server_name _; + return f"""# GENERATED BY fleet.py β€” do not edit. Change indexes.yml and re-run `fleet.py up`. - # Uploading a knowledge file through an agent can exceed the 1MB default. - client_max_body_size 64m; +{host} {{ + # Load-balancer probe: unauthenticated, and free of any index detail. + handle /healthz {{ + respond "ok" 200 + }} {"".join(blocks)} - # Load-balancer health probe. Deliberately unauthenticated and free of any - # brain detail. - location = /healthz {{ - access_log off; - return 200 "ok\\n"; - add_header Content-Type text/plain; - }} - - # Directory of what this host serves. Names and URLs only β€” no tokens. - location = / {{ - default_type application/json; - return 200 '{json.dumps(listing, indent=2)}'; - }} + # Directory of what this host serves. Names and URLs only. + handle {{ + header Content-Type application/json + respond `{directory}` 200 + }} }} """ @@ -462,15 +442,14 @@ def run(cmd: list[str], quiet: bool = False, check: bool = True) -> int: def cmd_render(config: dict, values: dict | None = None) -> None: - # Rendering needs the UI passwords to build htpasswd, so generate any that + # 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) - NGINX_DIR.mkdir(exist_ok=True) + CADDY_DIR.mkdir(exist_ok=True) COMPOSE.write_text(render_compose(config)) - NGINX_CONF.write_text(render_nginx(config)) - write_htpasswd_files(config, values) - print(f" wrote {COMPOSE.name}, nginx/default.conf and nginx/htpasswd.d/") + CADDY_FILE.write_text(render_caddyfile(config)) + print(f" wrote {COMPOSE.name} and caddy/Caddyfile") def cmd_up(config: dict) -> None: diff --git a/deploy/fleet/indexes.yml b/deploy/fleet/indexes.yml index 320323a..3b2bcfa 100644 --- a/deploy/fleet/indexes.yml +++ b/deploy/fleet/indexes.yml @@ -10,14 +10,21 @@ # Where agents will reach this host. Used for the connection details printed by # `fleet.py tokens` and by each container's startup banner β€” set it to the load # balancer's address, not the VM's, once the LB is in front. -public_base_url: http://20.83.97.30 +# nip.io resolves .nip.io to , which gives Caddy a real hostname to +# obtain a Let's Encrypt certificate for β€” a bare IP cannot have one. +public_base_url: https://20.83.97.30.nip.io # Host directory holding one subdirectory per brain. brains_root: /home/azureuser/brains -# Port nginx publishes on the host. The LB should forward to this. +# 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 +# These indexes hold synthetic demo data and are deliberately open: no bearer +# token on the MCP endpoints, no password on the UIs. Set true to gate both. +auth: false + # 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 diff --git a/open_index/ui/app.py b/open_index/ui/app.py index e181efb..20e208b 100644 --- a/open_index/ui/app.py +++ b/open_index/ui/app.py @@ -407,6 +407,76 @@ def render_analytics(brain: Brain) -> None: } for e in events], hide_index=True, use_container_width=True) +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,8 +517,10 @@ 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"] + # "How to use" sits rightmost on purpose: it is the reference people return + # to, not the page they should land on. + tab_explore, tab_map, tab_analytics, tab_jobs, tab_help = st.tabs( + [name for name, _ in view.TAB_GUIDE] ) with tab_explore: render_explore(brain, options) @@ -458,6 +530,8 @@ def main() -> None: render_analytics(brain) with tab_jobs: render_jobs(brain) + with tab_help: + render_how_to_use(brain) main() diff --git a/open_index/ui/view.py b/open_index/ui/view.py index e3ba929..345c1d1 100644 --- a/open_index/ui/view.py +++ b/open_index/ui/view.py @@ -262,6 +262,64 @@ 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."), +] + +# What each tab is for. Ordered as they appear. +TAB_GUIDE = [ + ("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."), + ("How to use", + "This page."), +] + + 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_ui_app.py b/tests/test_ui_app.py index d5e8f6b..631956e 100644 --- a/tests/test_ui_app.py +++ b/tests/test_ui_app.py @@ -55,10 +55,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 ------------------------------ @@ -198,3 +194,58 @@ 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_how_to_use_is_the_rightmost_tab(populated): + assert [t.label for t in populated.tabs][-1] == "How to use" + + +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") From faf030643795bd8832da16584eae3c350ae761f4 Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 21:05:36 +0530 Subject: [PATCH 08/13] test(ui): raise the AppTest timeout Each of these boots a real Streamlit script run; 60s flaked once under the full suite and would be likelier to on a CI runner. --- tests/test_ui_app.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_ui_app.py b/tests/test_ui_app.py index 631956e..6f83597 100644 --- a/tests/test_ui_app.py +++ b/tests/test_ui_app.py @@ -22,7 +22,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 From 6a040e780b308bbee48a3d66ee64264ac65932f5 Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 22:32:22 +0530 Subject: [PATCH 09/13] feat(ui): help tab first as "?", new Schema tab MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The help page moves from rightmost to leftmost and is relabelled "?". Streamlit selects the first tab, so a first-time visitor now lands on the explanation of what this index is and how to connect to it, rather than having to go looking for it. - New Schema tab between "?" and Explore: every doc_type with its fields β€” type, how it is searched, ranking weight, required β€” and its relationship vocabulary. Declared and observed edges are merged into one table, so a declared edge with zero uses and an undeclared edge in heavy use are both visible; either is worth noticing before writing to the index. - TAB_GUIDE is now the single source of tab order: the page builds its tabs from it and the "what each tab does" section reads from it, so the two cannot drift. A test asserts the rendered tabs match it. 468 tests pass; ui/view.py at 100%. Co-Authored-By: Claude Opus 5 (1M context) --- open_index/ui/app.py | 61 ++++++++++++++++++++++++++++++++++--- open_index/ui/view.py | 71 +++++++++++++++++++++++++++++++++++++++++-- tests/test_ui_app.py | 11 +++++-- tests/test_ui_view.py | 63 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 196 insertions(+), 10 deletions(-) diff --git a/open_index/ui/app.py b/open_index/ui/app.py index 20e208b..5615ede 100644 --- a/open_index/ui/app.py +++ b/open_index/ui/app.py @@ -407,6 +407,55 @@ 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. @@ -517,11 +566,15 @@ def main() -> None: st.markdown(view.ROW_CSS, unsafe_allow_html=True) options = render_sidebar(brain) - # "How to use" sits rightmost on purpose: it is the reference people return - # to, not the page they should land on. - tab_explore, tab_map, tab_analytics, tab_jobs, tab_help = st.tabs( + # Streamlit opens the first tab, so "?" leftmost means a first-time 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: @@ -530,8 +583,6 @@ def main() -> None: render_analytics(brain) with tab_jobs: render_jobs(brain) - with tab_help: - render_how_to_use(brain) main() diff --git a/open_index/ui/view.py b/open_index/ui/view.py index 345c1d1..a612249 100644 --- a/open_index/ui/view.py +++ b/open_index/ui/view.py @@ -299,8 +299,20 @@ def mcp_client_config(url: str, server_name: str = "open-index") -> str: "Define a new concept, when no existing doc_type fits."), ] -# What each tab is for. Ordered as they appear. +# The tab label for the help page. Leftmost, so it is what a first-time visitor +# lands on, and a bare question mark so it reads as help rather than content. +HELP_TAB = "?" + +# 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 " @@ -315,11 +327,64 @@ def mcp_client_config(url: str, server_name: str = "open-index") -> str: "the questions this index cannot yet answer."), ("Jobs", "Connectors that pull entities in on a schedule, with their last run."), - ("How to use", - "This page."), ] +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 + + 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_ui_app.py b/tests/test_ui_app.py index 6f83597..844f915 100644 --- a/tests/test_ui_app.py +++ b/tests/test_ui_app.py @@ -201,8 +201,15 @@ def test_row_css_inherits_colour_through_the_label_element(): # -- How to use ---------------------------------------------------------------- -def test_how_to_use_is_the_rightmost_tab(populated): - assert [t.label for t in populated.tabs][-1] == "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 == "?" + + +def test_schema_sits_between_help_and_explore(populated): + labels = [t.label for t in populated.tabs] + assert labels[:3] == ["?", "Schema", "Explore"] def test_tab_guide_matches_the_tabs_actually_rendered(populated): diff --git a/tests/test_ui_view.py b/tests/test_ui_view.py index eca21f6..15a58fc 100644 --- a/tests/test_ui_view.py +++ b/tests/test_ui_view.py @@ -226,3 +226,66 @@ 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] == ["?", "Schema", "Explore"] From a93a02c1052703d6a006aaa7f3ad1fe26ba72adf Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 22:42:13 +0530 Subject: [PATCH 10/13] =?UTF-8?q?feat(ui):=20make=20the=20map=20readable?= =?UTF-8?q?=20=E2=80=94=20whole-index=20view,=20legend,=20tooltips?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The map was unreadable: long entity names drawn beside every dot overlapped each other, and anchoring on a few entities is the wrong default for someone who has never seen the index and has no entity in mind. - New build_overview_graph: every entity of the selected doc_types, coloured by type, with the edges that run between them. Only edges with both ends in scope are drawn β€” a half-edge to a filtered-out type is a line to nowhere. - Doc-type filter at the top; a legend beside the canvas showing each type's colour and how many nodes it contributes. The legend is built from the drawn graph, not the schema, so it describes what is actually on screen. - Node labels are truncated to 22 chars; the full name, type, id and a few fields move to the hover tooltip. Edge labels are dropped past 60 edges β€” overlapping relationship text on every line was the main offender β€” and the relationship stays on the edge's tooltip. - Clicking a node focuses on it and its neighbours, with a way back, instead of silently accumulating anchors. - Canvas narrowed to 950px so it fits beside the legend column. Nodes are capped at 250, keeping the highest-degree ones, and the page says so when the cap bites rather than presenting a subset as the whole index. 486 tests pass; ui/view.py at 100%. Co-Authored-By: Claude Opus 5 (1M context) --- open_index/graph.py | 56 ++++++++++++++++++++++ open_index/ui/app.py | 106 +++++++++++++++++++++++++----------------- open_index/ui/view.py | 63 ++++++++++++++++++++++++- tests/test_graph.py | 64 +++++++++++++++++++++++++ tests/test_ui_app.py | 28 +++++++---- tests/test_ui_view.py | 70 ++++++++++++++++++++++++++++ 6 files changed, 333 insertions(+), 54 deletions(-) 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/ui/app.py b/open_index/ui/app.py index 5615ede..67a19e9 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.", - ) - 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.", + chosen = st.multiselect( + "Doc types shown", populated, default=populated, + help="Uncheck a type to drop it and its edges from the map.", ) - 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,20 +309,29 @@ def render_graph(brain: Brain, graph: ContextGraph) -> None: palette = view.graph_theme(_theme_type()) + # Edge labels are dropped once there are many of them: overlapping text on + # every line is what made the map unreadable. The relationship is still on + # the hover tooltip, which is where you look when you care about one edge. + label_edges = len(graph.edges) <= view.MAX_LABELLED_EDGES + 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}", + Node(id=n.id, label=view.truncate_label(n.label), color=n.color, + size=22 if n.is_anchor else 14, shape="dot", + title=view.node_tooltip(n.id, n.label, n.doc_type, + {k: v for k, v in (n.data or {}).items() + if k not in ("id", "doc_type", "related_to")}), # 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, + font={"color": palette["node_label"], "size": 14, "strokeWidth": palette["stroke_width"], "face": "sans-serif"}) for n in graph.nodes ] edges = [ - Edge(source=e.source, target=e.target, label=e.meaning, + Edge(source=e.source, target=e.target, + label=e.meaning if label_edges else "", + title=view.edge_tooltip(e.source, e.target, e.meaning), color=palette["edge"], - font={"color": palette["edge_label"], "size": 12, + font={"color": palette["edge_label"], "size": 11, "strokeWidth": palette["stroke_width"], "align": "middle", "face": "sans-serif"}) for e in graph.edges @@ -335,8 +355,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() diff --git a/open_index/ui/view.py b/open_index/ui/view.py index a612249..971c092 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 @@ -385,6 +387,65 @@ def schema_relationship_rows(brain, doc_type_name: str) -> list[dict]: return rows +# Node labels are drawn next to the dot, so a long one overlaps its neighbours +# and the map becomes unreadable. The full text lives in the hover tooltip. +MAX_NODE_LABEL = 22 + +# Cap on nodes drawn at once. Past this a force layout stops settling and the +# picture stops being readable regardless. +MAX_GRAPH_NODES = 250 + +# Above this many edges, their labels are hidden: overlapping relationship text +# on every line is the main thing that made the map unreadable. +MAX_LABELLED_EDGES = 60 + + +def truncate_label(text: str, limit: int = MAX_NODE_LABEL) -> str: + """Shorten a node label, breaking on a word boundary where one is close.""" + text = " ".join(str(text).split()) + if len(text) <= limit: + return text + cut = text[:limit].rsplit(" ", 1) + head = cut[0] if len(cut) > 1 and len(cut[0]) >= limit - 8 else text[:limit] + return head.rstrip(" ,;:β€”-") + "…" + + +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_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_ui_app.py b/tests/test_ui_app.py index 844f915..94a00f6 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 @@ -84,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 ------------------------------------------------------------------ diff --git a/tests/test_ui_view.py b/tests/test_ui_view.py index 15a58fc..9651c69 100644 --- a/tests/test_ui_view.py +++ b/tests/test_ui_view.py @@ -289,3 +289,73 @@ def test_declared_but_unused_relationships_show_zero(brain): 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] == ["?", "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_short_labels_are_left_alone(): + assert view.truncate_label("Checkout") == "Checkout" + + +def test_long_labels_are_truncated_with_an_ellipsis(): + long = "N412NL 2026-05-18 β€” Same WING A.ICE VLV OPEN L message five weeks after" + out = view.truncate_label(long) + assert len(out) <= view.MAX_NODE_LABEL + 1 + assert out.endswith("…") + + +def test_truncation_collapses_whitespace(): + assert view.truncate_label("a b") == "a b" + + +def test_truncation_does_not_end_on_punctuation(): + assert not view.truncate_label("Wing anti-ice valve, left side").rstrip("…").endswith(",") + + +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 From 34b8fa37ab8605d5b7d64a32e6aea19be65cb62f Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 23:28:53 +0530 Subject: [PATCH 11/13] feat(ui): label the help tab "How to use?" rather than "?" A bare question mark is a small target and reads as an afterthought. Since this is the tab the page opens on, it should say what it is. --- open_index/ui/app.py | 2 +- open_index/ui/view.py | 4 ++-- tests/test_ui_app.py | 4 ++-- tests/test_ui_view.py | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/open_index/ui/app.py b/open_index/ui/app.py index 67a19e9..a13462c 100644 --- a/open_index/ui/app.py +++ b/open_index/ui/app.py @@ -586,7 +586,7 @@ def main() -> None: st.markdown(view.ROW_CSS, unsafe_allow_html=True) options = render_sidebar(brain) - # Streamlit opens the first tab, so "?" leftmost means a first-time visitor + # 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] diff --git a/open_index/ui/view.py b/open_index/ui/view.py index 971c092..a99741f 100644 --- a/open_index/ui/view.py +++ b/open_index/ui/view.py @@ -302,8 +302,8 @@ def mcp_client_config(url: str, server_name: str = "open-index") -> str: ] # The tab label for the help page. Leftmost, so it is what a first-time visitor -# lands on, and a bare question mark so it reads as help rather than content. -HELP_TAB = "?" +# 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. diff --git a/tests/test_ui_app.py b/tests/test_ui_app.py index 94a00f6..1b9a865 100644 --- a/tests/test_ui_app.py +++ b/tests/test_ui_app.py @@ -212,12 +212,12 @@ def test_row_css_inherits_colour_through_the_label_element(): 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 == "?" + 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] == ["?", "Schema", "Explore"] + assert labels[:3] == ["How to use?", "Schema", "Explore"] def test_tab_guide_matches_the_tabs_actually_rendered(populated): diff --git a/tests/test_ui_view.py b/tests/test_ui_view.py index 9651c69..81525d4 100644 --- a/tests/test_ui_view.py +++ b/tests/test_ui_view.py @@ -288,7 +288,7 @@ def test_declared_but_unused_relationships_show_zero(brain): 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] == ["?", "Schema", "Explore"] + assert [n for n, _ in view.TAB_GUIDE][:3] == ["How to use?", "Schema", "Explore"] # -- map readability ----------------------------------------------------------- From 8ce9636161e02bf95204367b9ffdba7ea6b8cdc2 Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 23:32:18 +0530 Subject: [PATCH 12/13] =?UTF-8?q?fix(ui):=20no=20labels=20on=20the=20map?= =?UTF-8?q?=20=E2=80=94=20identity=20comes=20from=20hover?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Truncating node labels was not enough. Entity names here are long and arbitrary ("N412NL 2026-04-12 β€” Crew reported WING A.ICE VLV OPEN L on climb out of PDX"), and drawn beside every dot they overlap each other and their own edges however short they are cut. On 156 nodes the canvas was still unreadable. The canvas now carries shape and colour only: dots coloured by doc_type, the legend explaining the colours, and the full detail β€” name, type, id, fields, and for edges the relationship β€” on hover. Edge labels go the same way, which also removes the node-count threshold that used to switch them off. label="" rather than None: None serialises to null and vis draws that literally. Node and edge payloads moved into ui/view.py so this is asserted behaviourally rather than by reading app.py's source β€” importing app.py runs main(). 486 tests pass; ui/view.py at 100%. Co-Authored-By: Claude Opus 5 (1M context) --- open_index/ui/app.py | 29 ++------------------- open_index/ui/view.py | 59 ++++++++++++++++++++++++++++++------------- tests/test_ui_view.py | 41 ++++++++++++++++++++++-------- 3 files changed, 73 insertions(+), 56 deletions(-) diff --git a/open_index/ui/app.py b/open_index/ui/app.py index a13462c..127b69e 100644 --- a/open_index/ui/app.py +++ b/open_index/ui/app.py @@ -309,33 +309,8 @@ def render_graph(brain: Brain, graph: ContextGraph) -> None: palette = view.graph_theme(_theme_type()) - # Edge labels are dropped once there are many of them: overlapping text on - # every line is what made the map unreadable. The relationship is still on - # the hover tooltip, which is where you look when you care about one edge. - label_edges = len(graph.edges) <= view.MAX_LABELLED_EDGES - - nodes = [ - Node(id=n.id, label=view.truncate_label(n.label), color=n.color, - size=22 if n.is_anchor else 14, shape="dot", - title=view.node_tooltip(n.id, n.label, n.doc_type, - {k: v for k, v in (n.data or {}).items() - if k not in ("id", "doc_type", "related_to")}), - # 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": 14, - "strokeWidth": palette["stroke_width"], "face": "sans-serif"}) - for n in graph.nodes - ] - edges = [ - Edge(source=e.source, target=e.target, - label=e.meaning if label_edges else "", - title=view.edge_tooltip(e.source, e.target, e.meaning), - color=palette["edge"], - font={"color": palette["edge_label"], "size": 11, - "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( diff --git a/open_index/ui/view.py b/open_index/ui/view.py index a99741f..fcc949d 100644 --- a/open_index/ui/view.py +++ b/open_index/ui/view.py @@ -387,28 +387,10 @@ def schema_relationship_rows(brain, doc_type_name: str) -> list[dict]: return rows -# Node labels are drawn next to the dot, so a long one overlaps its neighbours -# and the map becomes unreadable. The full text lives in the hover tooltip. -MAX_NODE_LABEL = 22 - # Cap on nodes drawn at once. Past this a force layout stops settling and the # picture stops being readable regardless. MAX_GRAPH_NODES = 250 -# Above this many edges, their labels are hidden: overlapping relationship text -# on every line is the main thing that made the map unreadable. -MAX_LABELLED_EDGES = 60 - - -def truncate_label(text: str, limit: int = MAX_NODE_LABEL) -> str: - """Shorten a node label, breaking on a word boundary where one is close.""" - text = " ".join(str(text).split()) - if len(text) <= limit: - return text - cut = text[:limit].rsplit(" ", 1) - head = cut[0] if len(cut) > 1 and len(cut[0]) >= limit - 8 else text[:limit] - return head.rstrip(" ,;:β€”-") + "…" - def node_tooltip(entity_id: str, name: str, doc_type: str, fields: Optional[dict] = None) -> str: @@ -446,6 +428,47 @@ def legend_rows(brain, graph) -> list[dict]: ] +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_ui_view.py b/tests/test_ui_view.py index 81525d4..c6dc3d1 100644 --- a/tests/test_ui_view.py +++ b/tests/test_ui_view.py @@ -297,23 +297,42 @@ def test_help_tab_is_first_in_the_guide(): # unreadable; the full text moves to the hover tooltip. -def test_short_labels_are_left_alone(): - assert view.truncate_label("Checkout") == "Checkout" +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_long_labels_are_truncated_with_an_ellipsis(): - long = "N412NL 2026-05-18 β€” Same WING A.ICE VLV OPEN L message five weeks after" - out = view.truncate_label(long) - assert len(out) <= view.MAX_NODE_LABEL + 1 - assert out.endswith("…") +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_truncation_collapses_whitespace(): - assert view.truncate_label("a b") == "a b" +def test_node_colour_comes_from_the_doc_type(brain): + from open_index.graph import build_overview_graph -def test_truncation_does_not_end_on_punctuation(): - assert not view.truncate_label("Wing anti-ice valve, left side").rstrip("…").endswith(",") + 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(): From 51e90c30250cd9b0c5045380f12e1677d0a373b3 Mon Sep 17 00:00:00 2001 From: Dipesh Mittal Date: Sun, 9 Aug 2026 23:54:30 +0530 Subject: [PATCH 13/13] chore(fleet): make the repo copy deployment-agnostic MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Prep for merging to main. Three things were specific to the sandbox host or generated, and neither belongs in a shared repo: - indexes.yml carried this deployment's hostname, its two index names, and auth: false. Anyone cloning would have inherited a config pointing at someone else's box with authentication disabled. It is now indexes.example.yml with safe defaults (auth on, localhost, generic names), and indexes.yml is gitignored per-deployment config like .env. fleet.py says how to create it. - caddy/Caddyfile is generated on every run and was tracked, so it carried the sandbox hostname into git. Gitignored, alongside the compose file already was. - docs and one test referenced the sandbox IP and the azureuser home; the test now uses a TEST-NET-3 documentation address. Also brought docs/multi-index.md up to date with the nginx β†’ Caddy switch: TLS is now obtained automatically rather than terminated at a load balancer, so that section was describing work nobody needs to do any more. 486 tests pass. Co-Authored-By: Claude Opus 5 (1M context) --- .gitignore | 4 ++ deploy/fleet/caddy/Caddyfile | 54 ------------------ deploy/fleet/fleet.py | 3 +- .../{indexes.yml => indexes.example.yml} | 36 ++++++------ docs/multi-index.md | 57 ++++++++++++------- tests/test_mcp_transport.py | 4 +- 6 files changed, 61 insertions(+), 97 deletions(-) delete mode 100644 deploy/fleet/caddy/Caddyfile rename deploy/fleet/{indexes.yml => indexes.example.yml} (51%) diff --git a/.gitignore b/.gitignore index 79f1518..80a7c32 100644 --- a/.gitignore +++ b/.gitignore @@ -29,4 +29,8 @@ 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/deploy/fleet/caddy/Caddyfile b/deploy/fleet/caddy/Caddyfile deleted file mode 100644 index bea7d72..0000000 --- a/deploy/fleet/caddy/Caddyfile +++ /dev/null @@ -1,54 +0,0 @@ -# GENERATED BY fleet.py β€” do not edit. Change indexes.yml and re-run `fleet.py up`. - -20.83.97.30.nip.io { - # Load-balancer probe: unauthenticated, and free of any index detail. - handle /healthz { - respond "ok" 200 - } - - # aviation-mro-index β€” explorer UI. No prefix stripping: Streamlit runs with - # baseUrlPath=aviation-mro-index/ui and expects the full path. - handle /aviation-mro-index/ui* { - reverse_proxy ui-aviation-mro-index:8501 - } - # aviation-mro-index β€” MCP endpoint. handle_path strips the /aviation-mro-index prefix so the - # brain receives /mcp. - handle_path /aviation-mro-index/* { - reverse_proxy brain-aviation-mro-index:8080 { - # Streamable HTTP holds responses open; never buffer them. - flush_interval -1 - } - } - # commercial-lines-index β€” explorer UI. No prefix stripping: Streamlit runs with - # baseUrlPath=commercial-lines-index/ui and expects the full path. - handle /commercial-lines-index/ui* { - reverse_proxy ui-commercial-lines-index:8501 - } - # commercial-lines-index β€” MCP endpoint. handle_path strips the /commercial-lines-index prefix so the - # brain receives /mcp. - handle_path /commercial-lines-index/* { - reverse_proxy brain-commercial-lines-index:8080 { - # Streamable HTTP holds responses open; never buffer them. - flush_interval -1 - } - } - - # Directory of what this host serves. Names and URLs only. - handle { - header Content-Type application/json - respond `{ - "aviation-mro-index": { - "mcp": "https://20.83.97.30.nip.io/aviation-mro-index/mcp", - "description": "Line and base maintenance for a narrowbody fleet \u2014 ATA taxonomy, fault messages, task cards, MEL entries and defect history. SYNTHETIC DEMO DATA.", - "read_only": false, - "ui": "https://20.83.97.30.nip.io/aviation-mro-index/ui" - }, - "commercial-lines-index": { - "mcp": "https://20.83.97.30.nip.io/commercial-lines-index/mcp", - "description": "Commercial-lines placement for an SMB brokerage \u2014 carriers, appetite rules, class codes, state rules and submission playbooks. SYNTHETIC DEMO DATA.", - "read_only": false, - "ui": "https://20.83.97.30.nip.io/commercial-lines-index/ui" - } -}` 200 - } -} diff --git a/deploy/fleet/fleet.py b/deploy/fleet/fleet.py index 18353ce..7cf073f 100755 --- a/deploy/fleet/fleet.py +++ b/deploy/fleet/fleet.py @@ -59,7 +59,8 @@ def load_config() -> dict: except ImportError: die("pyyaml is required: pip install pyyaml (or: apt install python3-yaml)") if not CONFIG.exists(): - die(f"no {CONFIG}") + 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") diff --git a/deploy/fleet/indexes.yml b/deploy/fleet/indexes.example.yml similarity index 51% rename from deploy/fleet/indexes.yml rename to deploy/fleet/indexes.example.yml index 3b2bcfa..e29c29d 100644 --- a/deploy/fleet/indexes.yml +++ b/deploy/fleet/indexes.example.yml @@ -7,38 +7,36 @@ # # After editing, run: ./fleet.py up -# Where agents will reach this host. Used for the connection details printed by -# `fleet.py tokens` and by each container's startup banner β€” set it to the load -# balancer's address, not the VM's, once the LB is in front. -# nip.io resolves .nip.io to , which gives Caddy a real hostname to -# obtain a Let's Encrypt certificate for β€” a bare IP cannot have one. -public_base_url: https://20.83.97.30.nip.io +# 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: /home/azureuser/brains +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 -# These indexes hold synthetic demo data and are deliberately open: no bearer -# token on the MCP endpoints, no password on the UIs. Set true to gate both. -auth: false +# 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: aviation-mro-index - description: >- - Line and base maintenance for a narrowbody fleet β€” ATA taxonomy, fault - messages, task cards, MEL entries and defect history. SYNTHETIC DEMO DATA. - - - name: commercial-lines-index - description: >- - Commercial-lines placement for an SMB brokerage β€” carriers, appetite - rules, class codes, state rules and submission playbooks. SYNTHETIC DEMO DATA. + - 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. diff --git a/docs/multi-index.md b/docs/multi-index.md index 03233e1..b80a63e 100644 --- a/docs/multi-index.md +++ b/docs/multi-index.md @@ -10,7 +10,8 @@ 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 nginx. +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`. @@ -32,7 +33,7 @@ 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 | -| nginx | 3 MB | once, shared | +| Caddy | 3 MB | once, shared | | brain container (MCP) | ~255 MB | **per index** | | ui container | ~71 MB | **per index** | @@ -45,7 +46,7 @@ from every container. Note the UI figure grows once someone runs a semantic search there β€” the model loads lazily. ``` - β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ nginx :80 ────────────────┐ + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ Caddy :80/:443 ───────────────┐ β”‚ /support/mcp β†’ brain-support (token) │──▢ ┐ LB ──▢ β”‚ /support/ui β†’ ui-support (basic) │──▢ β”‚ β”‚ /sales/mcp β†’ brain-sales (token) │──▢ β”œβ”€β–Ά OpenSearch @@ -61,7 +62,7 @@ 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: /home/azureuser/brains # one subdirectory per index +brains_root: ./brains # one subdirectory per index http_port: 80 opensearch_heap: 512m @@ -80,12 +81,16 @@ 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 nginx config, and starts everything. It is idempotent β€” run it +the compose and Caddy config, and starts everything. It is idempotent β€” run it again after any edit. **Adding an index later** is one command: @@ -94,20 +99,29 @@ again after any edit. ./fleet.py add marketing --description "Campaigns and positioning" ``` -Existing indexes keep running; only the new container starts and nginx reloads. +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 -> `nginx/default.conf` are regenerated on every run β€” edit the former, never the -> latter two. +> `caddy/Caddyfile` are regenerated on every run and gitignored β€” edit the +> former, never the latter two. --- -## 3. Put it behind a load balancer +## 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. -nginx publishes on `http_port` (80 by default). Point the LB at that. +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. @@ -115,10 +129,6 @@ detail, so it is safe as an LB probe. **Directory:** `GET /` returns JSON listing every index and its URL. Names only β€” no tokens. -**Terminate TLS at the LB.** The brains speak plain HTTP. Once TLS is on, set -`public_base_url: https://...` and re-run `./fleet.py up` so each brain -advertises the right URL. - **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: @@ -132,9 +142,9 @@ A `421 Invalid Host header` means exactly this β€” the Host that arrived is not 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; a buffering LB -will appear to hang. The bundled nginx sets `proxy_buffering off` β€” configure the -same on the LB, with an idle timeout of at least a few minutes. +**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. --- @@ -201,15 +211,20 @@ 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 credential file, so the `sales` password does not -open the `support` UI. +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, -the same as nginx already does. +which Caddy already handles on its own hop. --- @@ -226,7 +241,7 @@ directory is mounted), then: cd deploy/fleet D="docker compose -f docker-compose.generated.yml --env-file .env" -cp issues.csv /home/azureuser/brains/support/ +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 diff --git a/tests/test_mcp_transport.py b/tests/test_mcp_transport.py index 9336539..290d42e 100644 --- a/tests/test_mcp_transport.py +++ b/tests/test_mcp_transport.py @@ -210,9 +210,9 @@ def no_uvicorn(name, *args, **kwargs): def test_public_url_host_is_allowed(): from open_index.mcp_server import build_transport_security - settings = build_transport_security(public_url="http://20.83.97.30/support/mcp") + settings = build_transport_security(public_url="http://203.0.113.10/support/mcp") assert settings.enable_dns_rebinding_protection is True - assert "20.83.97.30" in settings.allowed_hosts + assert "203.0.113.10" in settings.allowed_hosts def test_both_with_and_without_port_are_allowed():