Skip to content

HarnessRouter Community Edition: the self-hosted, Apache-2.0 edition of the unified interface for agent harnesses. Run Codex, Claude Code, Hermes, PI, DSH, and more through one API, with sessions, streaming, files, cancellation, and failure handling. Implements the Unified Harness Protocol (UHP), an open standard. Your keys, your infrastructure.

feat(sql): a harness can read a database, and nothing that touches it ever sees the credential

richard-epsilla8c9bd09e0a35
diff --git a/.env.example b/.env.example
index 1a45176e..49c30367 100644
--- a/.env.example
+++ b/.env.example
@@ -23,6 +23,12 @@ HR_SECRET_GLOBAL_HARNESS_POLICY_CLAUDE={"chain":["anthropic"]}
# PORT=3000
# HR_DATA_DIR=/data
+# Required only to connect a database to an agent. Connection strings are encrypted at rest
+# under a key derived from this passphrase; without it the server refuses to store one rather
+# than writing your database credential to disk in plaintext. Keep it — changing it means
+# reconnecting every database.
+# HR_SECRET_KEY=a-long-random-passphrase
+
# Everything else is configured for self-hosting by the entrypoint: local SQLite storage,
# no auth, no metering, a loopback runner, and direct key hand-off to the agent. You should
# not need to set them, and they are documented in the README if you want to.
diff --git a/README.md b/README.md
index 1aaee6d2..8d9b0493 100644
--- a/README.md
+++ b/README.md
@@ -64,6 +64,43 @@ A *connection* names a provider and its credential; a *policy* says which connec
uses. Any OpenAI-compatible endpoint works — aggregators, local models, or your own inference
server — by setting `provider: "openai-api"` and a `base_url`.
+<details>
+<summary>Connecting a database</summary>
+
+An agent can be given a PostgreSQL or MySQL database to read — that is how the dashboard kit
+works. Two things to know before you connect one.
+
+**Set `HR_SECRET_KEY`.** Connection strings are encrypted at rest under a key derived from it,
+and without it the server refuses to store one rather than writing your production credential to
+disk in plaintext:
+
+```bash
+HR_SECRET_KEY=a-long-random-passphrase
+```
+
+Keep it. Change it and the stored connections can no longer be decrypted, and you reconnect them.
+
+**Use a read-only database account.** Every statement is checked and only `SELECT` is allowed —
+non-`SELECT`, multiple statements and data-modifying CTEs are refused, and on PostgreSQL the
+query additionally runs in a `READ ONLY` transaction. That check is a parser, and a parser is a
+thing that can be wrong. An account that has been granted `SELECT` and nothing else is a second
+defence that does not depend on ours being right:
+
+```sql
+CREATE USER dashboards WITH PASSWORD '…';
+GRANT CONNECT ON DATABASE shop TO dashboards;
+GRANT USAGE ON SCHEMA public TO dashboards;
+GRANT SELECT ON ALL TABLES IN SCHEMA public TO dashboards;
+```
+
+The connection string is resolved inside the gateway at the moment a query runs. The agent's
+sandbox never receives it — it gets a tool that runs `SELECT`s — and neither does the browser.
+
+**Sample rows** are a per-connection switch, on by default: the agent sees a few real rows per
+table so it can tell a status column from a category one. Turn it off and it sees table and
+column names and types and no values at all.
+</details>
+
<details>
<summary>Choosing backends, and building with a browser</summary>
diff --git a/gateway/app.py b/gateway/app.py
index a3fb6ddd..15732c19 100644
--- a/gateway/app.py
+++ b/gateway/app.py
@@ -23,6 +23,7 @@ import uuid
import zipfile
import base64
+import contextlib
import functools
import hashlib
import mimetypes
@@ -40,6 +41,7 @@ from starlette.background import BackgroundTask
from pydantic import BaseModel
import backing # pluggable graph/blob/secret stores (vg | local)
+import sql_plane # the read-only SQL data plane (gate, row cap, introspection)
import control_store # durable transactional control state (idempotency / lease / monotonic cancel)
POOL_ENDPOINT = os.environ.get("POOL_MGMT_ENDPOINT", "").rstrip("/")
@@ -733,15 +735,29 @@ async def _resolve_chain(org: str | None, backend: str, explicit: str | None) ->
for tenant in _tenants_for(org):
v = await _vault_get(tenant, f"harness-policy-{backend}")
if v:
- try:
- names = json.loads(v)
- if isinstance(names, list) and names:
- return [str(n) for n in names]
- except Exception: # noqa: BLE001
- pass
+ names = _policy_chain(v)
+ if names:
+ return names
return []
+def _policy_chain(raw: str) -> list[str]:
+ """The connection names in a policy document.
+
+ TWO shapes are one document, and both must be read here or a working install stops working:
+ `{"chain": ["anthropic"]}` is the form the README, the docker run line and .env.example have
+ always published, so it is what is sitting in operators' .env files; the bare `["anthropic"]`
+ is what PUT /v1/orgs/{org}/policy/{backend} writes. Only the second parsed, which meant the
+ documented quickstart produced a gateway that could serve no model and said nothing about why.
+ """
+ try:
+ doc = json.loads(raw)
+ except Exception: # noqa: BLE001 — a corrupt policy is no policy, not a crash
+ return []
+ names = doc.get("chain") if isinstance(doc, dict) else doc
+ return [str(n) for n in names if str(n).strip()] if isinstance(names, list) else []
+
+
_AUTH_FIELDS = ("api_key", "base_url", "aws_region", "aws_access_key_id", "aws_secret_access_key",
"aws_session_token", "aws_bearer_token", "gcp_project", "gcp_region",
"gcp_sa_json", "wire_api")
@@ -2236,12 +2252,13 @@ def _sub_headers(value: str, hdr_vals: dict[str, str]) -> str:
async def _harness_plugins(harness_id: str, org: str, hdr_vals: dict[str, str] | None = None,
- hv: dict | None = None) -> tuple[list[dict], list[dict], list[str], list[str]]:
+ hv: dict | None = None, sid: str = "") -> tuple[list[dict], list[dict], list[str], list[str]]:
"""Resolve a harness's ENABLED MCP servers + skills for a turn. MCP auth refs are resolved
from the vault here so the runner never sees vault keys, only the live token (or none).
`hv` (HR-INF-010): the already-read harness vertex — the SOLE caller (_resp_execute) always
threads it, so we DON'T re-read. Using the same snapshot as agent_doc means both degrade
- together if the read failed (hv is None → empty plugins), never inconsistently (review #5)."""
+ together if the read failed (hv is None → empty plugins), never inconsistently (review #5).
+ `sid`: the session this turn belongs to, used to scope the database tool's credential to it."""
if not harness_id:
return [], [], [], []
v = hv
@@ -2289,6 +2306,15 @@ async def _harness_plugins(harness_id: str, org: str, hdr_vals: dict[str, str] |
entry["headers"] = {k: _sub_headers(str(vv), _hvals) for k, vv in s["headers"].items()}
mcp_out.append(entry)
+ # The database this harness is connected to, as a tool the agent can call. Added here rather
+ # than stored on the config so it cannot go stale: connect a database and the next turn has
+ # the tool, disconnect it and the next turn does not. What the sandbox receives is a URL and
+ # a token scoped to this harness and this session — never the connection string.
+ if _ds_record(v):
+ sql_mcp = _sql_mcp_server(harness_id, sid)
+ if sql_mcp:
+ mcp_out.append(sql_mcp)
+
# Skill manifest = the harness's own skills MERGED with its base builtin's defaults (a custom
# harness inherits the doc skills installed on its base; an own entry overrides by name, and an
# own entry with enabled:false suppresses an inherited one). Builtins have no base → own only.
@@ -4310,7 +4336,7 @@ async def _resp_execute(translator: _RespTranslator, *, org: str, member: str, s
# HR-INF-010: the caller (create_response) already read this harness's vertex — thread it in
# instead of re-reading it twice more here. Beyond cutting reads, a same-request snapshot means
# _harness_plugins and agent_doc can't observe a mid-turn config edit inconsistently.
- mcp_servers, skills, skills_suppressed, tools_disabled = await _harness_plugins(harness_id, org, hdr_vals, hv=hv)
+ mcp_servers, skills, skills_suppressed, tools_disabled = await _harness_plugins(harness_id, org, hdr_vals, hv=hv, sid=sid)
if mcp_servers or skills or skills_suppressed or tools_disabled:
rec["plugins"] = {"mcp": [m.get("name") for m in mcp_servers], "skills": [s.get("name") for s in skills],
"skills_off": skills_suppressed, "tools_off": tools_disabled}
@@ -6490,8 +6516,6 @@ def _ssrf_check(url: str) -> str | None:
return "MCP endpoints must be http or https"
return None if u.hostname else "url has no host"
- import ipaddress
- import socket
from urllib.parse import urlparse
try:
u = urlparse(url)
@@ -6499,11 +6523,26 @@ def _ssrf_check(url: str) -> str | None:
return "invalid url"
if u.scheme != "https":
return "only https MCP endpoints are allowed"
- host = u.hostname or ""
- if not host:
+ if not u.hostname:
return "url has no host"
+ return _internal_target(u.hostname, u.port or 443)
+
+
+def _internal_target(host: str, port: int) -> str | None:
+ """Does this hostname resolve somewhere a caller must not be able to point this server?
+
+ Every DNS answer is resolved and classified — loopback, link-local (which is where cloud
+ metadata lives), RFC1918, IPv6 private, reserved — so a name cannot rebind to an internal
+ target between the check and the connection.
+
+ Shared by MCP URLs and database hosts because it is one question, not two: both are a target
+ a customer names and this server then opens a socket to. A second copy of this rule would be
+ a second thing to remember to fix.
+ """
+ import ipaddress
+ import socket
try:
- infos = socket.getaddrinfo(host, u.port or 443, proto=socket.IPPROTO_TCP)
+ infos = socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP)
except Exception: # noqa: BLE001
return "host does not resolve"
for info in infos:
@@ -6609,6 +6648,502 @@ async def test_mcp_public(body: McpTestBody, request: Request) -> dict:
return await _mcp_list_tools(body.url, token)
+# ── SQL datasources ───────────────────────────────────────────────────────────────────────────
+# A customer's own database, attached to one Harness: the agent explores it to decide what a
+# dashboard should show, and the dashboard re-runs its queries when someone opens it.
+#
+# THE RECORD AND THE CREDENTIAL LIVE IN DIFFERENT PLACES, on purpose:
+# * The RECORD — engine, which secret holds the connection string, whether sample rows may be
+# read — is one property on the Harness vertex, beside mcp_servers and skills. It is harness
+# configuration, and it rides the vertex read that every turn already does.
+# * The CONNECTION STRING is a secret. It goes through BACKING.secrets with
+# require_encryption=True, exactly as MCP bearer tokens do, and the record keeps only a
+# `vault:<key>` reference. It is resolved here, inside the gateway, at the moment of use:
+# the runner never receives it, the browser never receives it, and neither does the agent —
+# an agent is given a tool that runs SELECTs, not a credential.
+#
+# Everything a statement passes through — the read-only gate, the row cap, the timeout — is in
+# sql_plane.py, so the app's refresh and the agent's tool cannot diverge.
+_DS_PROP = "datasource"
+
+# Both spellings of each engine, resolved once here so nothing downstream has to know that
+# "postgresql" and "postgres" are the same thing.
+_DS_ENGINE_ALIASES = {"postgres": "postgres", "postgresql": "postgres", "pg": "postgres",
+ "mysql": "mysql", "mariadb": "mysql"}
+# The URL schemes each engine will accept. A MySQL string pasted into a Postgres datasource is
+# caught here, with a sentence, rather than by a driver timing out twenty seconds later.
+_DS_SCHEMES = {"postgres": ("postgres", "postgresql"), "mysql": ("mysql", "mariadb")}
+# Rows per table the agent sees when sampling is ON. Enough to tell an id from a status string
+# and a cents column from a dollars one; not enough to be an export of anyone's customer list.
+_DS_SAMPLE_ROWS = 5
+# The cap on an agent's own SELECT. Far below the app's, because an agent is checking that a
+# query works before it writes it into a panel — 5000 rows of that is tokens, not information.
+_DS_AGENT_MAX_ROWS = 200
+
+
+def _ds_engine(engine: str) -> str:
+ e = _DS_ENGINE_ALIASES.get((engine or "").strip().lower())
+ if not e:
+ raise uhp_error(400, "unsupported_engine",
+ "This connects to PostgreSQL and MySQL databases.", "engine")
+ return e
+
+
+def _ds_parse(engine: str, conn: str) -> tuple[str, str]:
+ """(host, database) from a connection string, with the string itself validated.
+
+ Parsed at save time so a person can later confirm WHICH database is attached without the
+ credential ever being read back out of the secret store."""
+ from urllib.parse import urlparse
+ try:
+ u = urlparse((conn or "").strip())
+ except Exception as e: # noqa: BLE001
+ raise uhp_error(400, "invalid_connection_string",
+ "That does not parse as a connection string.", "connection_string") from e
+ if (u.scheme or "").lower() not in _DS_SCHEMES[engine]:
+ want = "postgresql://user:password@host:5432/database" if engine == "postgres" \
+ else "mysql://user:password@host:3306/database"
+ raise uhp_error(400, "invalid_connection_string",
+ f"A {'PostgreSQL' if engine == 'postgres' else 'MySQL'} connection string "
+ f"looks like {want}", "connection_string")
+ if not u.hostname:
+ raise uhp_error(400, "invalid_connection_string",
+ "That connection string has no host.", "connection_string")
+ db = (u.path or "/").lstrip("/")
+ if not db:
+ raise uhp_error(400, "invalid_connection_string",
+ "That connection string names no database — add /yourdatabase to the end.",
+ "connection_string")
+ host = u.hostname + (f":{u.port}" if u.port else "")
+ return host, db
+
+
+def _ds_secret_key(hid: str) -> str:
+ """One secret per harness, named after it. Same charset rule as harness-mcp-<ref>."""
+ return "harness-ds-" + (re.sub(r"[^a-z0-9]+", "-", (hid or "").lower()).strip("-") or "harness")
+
+
+async def _ds_store_secret(org: str, hid: str, conn: str) -> str:
+ """Put the connection string in the secret store; return the reference the record keeps."""
+ tenant = org if _vault_tenant_ok(org) else GLOBAL_TENANT
+ key = _ds_secret_key(hid)
+ try:
+ await BACKING.secrets.put(tenant, key, conn, require_encryption=True)
+ except backing.SecretsNotConfigured as e:
+ # 501 rather than 500: nothing is broken. This instance has not been given a key to
+ # encrypt with, and refusing is the correct behaviour — the message names the variable
+ # that fixes it, because a stack trace would not.
+ raise uhp_error(501, "secrets_not_configured", str(e), "connection_string") from e
+ return f"vault:{key}"
+
+
+def _ds_record(v: dict | None) -> dict | None:
+ """The datasource on a harness vertex, or None.
+
+ Never raises: a record we cannot read has to mean "not connected", because the alternative is
+ a harness nobody can open."""
+ try:
+ rec = json.loads((v or {}).get(_DS_PROP) or "null")
+ except Exception: # noqa: BLE001
+ return None
+ if not isinstance(rec, dict) or rec.get("engine") not in sql_plane.ENGINES:
+ return None
+ return rec if str(rec.get("secret") or "").startswith("vault:") else None
+
+
+def _ds_public(rec: dict | None) -> dict | None:
+ """What a browser may see. Everything except the credential and where it is kept."""
+ if not rec:
+ return None
+ try:
+ updated = int(rec.get("updated_at") or 0)
+ except Exception: # noqa: BLE001
+ updated = 0
+ return {"engine": rec.get("engine"), "host": rec.get("host") or "",
+ "database": rec.get("database") or "",
+ "sampleRows": bool(rec.get("sample_rows")), "updatedAt": updated}
+
+
+async def _ds_dsn(org: str, rec: dict) -> str:
+ """The live connection string for a record, resolved from the secret store.
+
+ Deliberately NOT _resolve_mcp_auth: that helper falls back to treating the value as a literal
+ token, which for a datasource would mean a connection string sitting in the harness config in
+ plaintext. Here a non-reference is not a fallback, it is a record we refuse to use.
+ """
+ ref = str(rec.get("secret") or "")
+ if not ref.startswith("vault:"):
+ raise uhp_error(500, "datasource_unreadable",
+ "This connection is stored in a form this server will not use.")
+ key = ref[len("vault:"):]
+ for tenant in _tenants_for(org):
+ v = await _vault_get(tenant, key)
+ if v:
+ return v
+ raise uhp_error(502, "datasource_unreadable",
+ "The stored credential for this database could not be read. Connect it again.")
+
+
+async def _ds_for_harness(hid: str, org: str) -> tuple[dict, str]:
+ """(record, connection string) for a harness's datasource, or a 404 that says what to do."""
+ v = await _vertex_get(hid)
+ if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):
+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")
+ rec = _ds_record(v)
+ if not rec:
+ raise uhp_error(404, "datasource_not_connected",
+ "No database is connected to this agent yet.", "harness_id")
+ return rec, await _ds_dsn(org, rec)
+
+
+def _sql_http(e: Exception) -> HTTPException:
+ """One rule for turning a SQL failure into a response.
+
+ Refused means we stopped it before it reached the database — that is the caller's statement,
+ so 400. Anything else means the database itself answered with a failure, upstream of us, so
+ 502. Both carry the sentence the caller can act on ('column "revenu" does not exist').
+ """
+ if isinstance(e, sql_plane.SqlRefused):
+ return uhp_error(400, "sql_refused", str(e), "sql")
+ return uhp_error(502, "sql_failed", str(e), "sql")
+
+
+class DatasourceBody(BaseModel):
+ """Connect a database to a harness. `sample_rows` defaults ON — see put_datasource."""
+ engine: str
+ connection_string: str
+ sample_rows: bool = True
+
+
+class DatasourceTestBody(BaseModel):
+ engine: str
+ connection_string: str
+
+
[email protected]("/v1/harnesses/{hid}/datasource")
+async def put_datasource(hid: str, body: DatasourceBody, request: Request) -> dict:
+ """Attach (or replace) the database this harness reads.
+
+ `sample_rows` is the one privacy decision in the whole kit, so it is stored per harness and
+ defaults to ON: with it on the agent sees a few real rows per table and can tell a status
+ column from a category one; with it off it sees table and column names and types and not a
+ single row of business data. Nothing else about the record changes either way.
+ """
+ org, _ = await _pub_org_member(request)
+ v = await _vertex_get(hid)
+ if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):
+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")
+ rec = await _ds_write(org, hid, _ds_validate(body.engine, body.connection_string),
+ body.sample_rows)
+ return {"harnessId": hid, "dataSource": _ds_public(rec)}
+
+
+def _ds_validate(engine: str, conn: str) -> tuple[str, str, str, str]:
+ """(engine, connection string, host, database) — or the 400 that says what is wrong with it.
+
+ Pure, so kit launch can check what it was given BEFORE it provisions anything: a typo in a
+ connection string should not leave a half-configured Harness behind."""
+ eng = _ds_engine(engine)
+ c = (conn or "").strip()
+ if not c:
+ raise uhp_error(400, "invalid_connection_string",
+ "A connection string is required.", "connection_string")
+ host, db = _ds_parse(eng, c)
+ # A connection string is a target this server opens a socket to on a caller's say-so, which is
+ # the same thing an MCP URL is — so it passes the same check, for the same reason, with the
+ # same exemption: self-hosted, the "internal" network is the operator's own machine and a
+ # database on localhost is the normal case rather than an attack.
+ if not _pool_is_local():
+ hostname, _, port = host.partition(":")
+ blocked = _internal_target(hostname, int(port) if port.isdigit() else
+ (5432 if eng == "postgres" else 3306))
+ if blocked:
+ raise uhp_error(400, "unreachable_host",
+ f"This server cannot connect to {hostname}: {blocked}.",
+ "connection_string")
+ return eng, c, host, db
+
+
+async def _ds_write(org: str, hid: str, checked: tuple[str, str, str, str],
+ sample_rows: bool) -> dict:
+ """Store the credential, write the record. The one place a datasource is attached, so a
+ database connected at launch is stored exactly as one connected later."""
+ engine, conn, host, db = checked
+ ref = await _ds_store_secret(org, hid, conn)
+ rec = {"engine": engine, "secret": ref, "host": host, "database": db,
+ # Stored as the row COUNT introspection will take, not as a boolean, so the one place
+ # that decides how much data leaves the customer's database is this line.
+ "sample_rows": _DS_SAMPLE_ROWS if sample_rows else 0,
+ "updated_at": int(time.time() * 1000)}
+ await _vg_upsert("Harness", hid, {_DS_PROP: json.dumps(rec),
+ "updated_at": str(int(time.time() * 1000))})
+ # host and database only. The credential is not printed, here or anywhere.
+ print(f"[sql] {hid}: connected {engine} {host}/{db} "
+ f"(sample rows {'on' if sample_rows else 'off'})", flush=True)
+ return rec
+
+
+async def _ds_forget(org: str, hid: str, v: dict | None) -> bool:
+ """Drop the record AND overwrite the stored credential. True if there was one.
+
+ Shared by disconnecting a database and by deleting the harness itself, because they are the
+ same promise: after either, this server is no longer holding that password. Deleting the
+ agent and leaving its production credential encrypted on disk would be a surprise of the
+ worst kind — the person did the most decisive thing the UI offers.
+ """
+ rec = _ds_record(v)
+ if rec:
+ tenant = org if _vault_tenant_ok(org) else GLOBAL_TENANT
+ with contextlib.suppress(Exception): # an unwritable store must not block the delete
+ await BACKING.secrets.put(tenant, _ds_secret_key(hid), "", require_encryption=True)
+ print(f"[sql] {hid}: disconnected", flush=True)
+ # Cleared unconditionally: a record we could not parse is exactly the one worth clearing.
+ await _vg_upsert("Harness", hid, {_DS_PROP: "", "updated_at": str(int(time.time() * 1000))})
+ return bool(rec)
+
+
[email protected]("/v1/harnesses/{hid}/datasource")
+async def get_datasource(hid: str, request: Request) -> dict:
+ org, _ = await _pub_org_member(request)
+ v = await _vertex_get(hid)
+ if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):
+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")
+ return {"harnessId": hid, "dataSource": _ds_public(_ds_record(v))}
+
+
[email protected]("/v1/harnesses/{hid}/datasource")
+async def delete_datasource(hid: str, request: Request) -> dict:
+ """Disconnect the database. The record goes and so does the stored credential."""
+ org, _ = await _pub_org_member(request)
+ v = await _vertex_get(hid)
+ if not v or v.get("org") != org or str(v.get("deleted")) in ("1", "true", "True"):
+ raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")
+ return {"harnessId": hid, "dataSource": None,
+ "disconnected": await _ds_forget(org, hid, v)}
+
+
[email protected]("/v1/datasource-test")
+async def test_datasource(body: DatasourceTestBody, request: Request) -> dict:
+ """Try a connection string before saving it, and say what went wrong if it fails.
+
+ Same shape as /v1/mcp-test: {ok:true, …} or {ok:false, error} with HTTP 200, because "your
+ password is wrong" is a successful test that reports a failure, not a failed request.
+ """
+ await _pub_org_member(request)
+ # Validated exactly as saving would validate it, so a string this button accepts is a string
+ # the save accepts. A test that does not predict what happens next is worse than no test.
+ engine, conn, host, db = _ds_validate(body.engine, body.connection_string)
+ try:
+ # Not SELECT 1: reaching the database proves the credential, and reading the catalog
+ # proves the account can see tables — which is the failure people actually hit when they
+ # follow the advice to use a read-only account and grant it nothing.
+ schema = await sql_plane.introspect(engine, conn, sample_rows=0, timeout=15.0)
+ except sql_plane.SqlError as e:
+ return {"ok": False, "engine": engine, "host": host, "database": db, "error": str(e)}
+ return {"ok": True, "engine": engine, "host": host, "database": db,
+ "tableCount": schema["table_count"],
+ "tables": [f"{t['schema']}.{t['name']}" for t in schema["tables"][:12]]}
+
+
+class SqlQueryBody(BaseModel):
+ sql: str
+ max_rows: int | None = None
+
+
[email protected]("/v1/harnesses/{hid}/sql/query")
+async def run_harness_query(hid: str, body: SqlQueryBody, request: Request) -> dict:
+ """Run one SELECT against this harness's database.
+
+ This is the route a dashboard calls to refresh a panel, which is why it exists at all:
+ opening a dashboard re-runs every panel's query, and doing that through the agent would cost
+ a turn per panel per page-load. The statement still passes the same read-only gate, row cap
+ and timeout the agent's own tool does.
+ """
+ org, _ = await _pub_org_member(request)
+ rec, dsn = await _ds_for_harness(hid, org)
+ want = int(body.max_rows or sql_plane.DEFAULT_MAX_ROWS)
+ max_rows = max(1, min(want, sql_plane.DEFAULT_MAX_ROWS))
+ try:
+ return await sql_plane.run_query(rec["engine"], dsn, body.sql or "", max_rows=max_rows)
+ except sql_plane.SqlError as e:
+ raise _sql_http(e) from e
+
+
[email protected]("/v1/harnesses/{hid}/sql/schema")
+async def get_harness_schema(hid: str, request: Request) -> dict:
+ """The shape of this harness's database: tables, columns, types — and a few rows per table
+ when the person left sample rows on. `sampled` in the response says which they got."""
+ org, _ = await _pub_org_member(request)
+ rec, dsn = await _ds_for_harness(hid, org)
+ try:
+ return await sql_plane.introspect(rec["engine"], dsn,
+ sample_rows=int(rec.get("sample_rows") or 0))
+ except sql_plane.SqlError as e:
+ raise _sql_http(e) from e
+
+
+# ── the agent's side: an MCP server this gateway hosts ────────────────────────────────────────
+# An agent designing a dashboard needs two things: the schema, and the ability to run a candidate
+# query and see rows or the error. It must never need the credential.
+#
+# This is a built-in MCP server rather than a built-in tool because THERE IS NO BUILT-IN TOOL
+# MECHANISM to use: every base runs a third-party CLI (Claude Code, Codex, hermes) with its own
+# fixed tool set, and the only channel this server has for adding a capability to all three is the
+# MCP config the runner already writes for each of them (_write_mcp_config_claude / _codex_mcp_toml
+# / _hermes_mcp_section). Hosting the server here rather than as a separate process is what keeps
+# the credential in the gateway: the sandbox is handed a URL and a per-turn token, resolves nothing
+# itself, and a token that leaks buys one session's read access to one database and expires with it.
+_SQL_MCP_TOOLS = [
+ {"name": "schema",
+ "description": ("Tables and columns in the connected database, with types. Call this first: "
+ "it is the only way to learn what can be charted."),
+ "inputSchema": {"type": "object", "properties": {}, "additionalProperties": False}},
+ {"name": "query",
+ "description": (f"Run one read-only SELECT and see the rows (up to {_DS_AGENT_MAX_ROWS}). "
+ "Use it to check a query works before putting it in a dashboard panel. "
+ "Only SELECT is accepted; anything that would modify data is refused."),
+ "inputSchema": {"type": "object", "required": ["sql"],
+ "properties": {"sql": {"type": "string", "description": "One SELECT statement."}},
+ "additionalProperties": False}},
+]
+
+
+def _sql_mcp_url() -> str:
+ """Where a sandbox reaches this server, or "" when we cannot know.
+
+ Hosted, the sandbox is a remote container and the answer is the public base URL the model
+ broker already uses. Self-hosted, the runner is a process in this container and loopback is
+ both correct and the only thing that resolves.
+ """
+ if PUBLIC_BASE_URL:
+ return f"{PUBLIC_BASE_URL}/v1/mcp/sql"
+ local = os.environ.get("HARNESS_GATEWAY_URL", "").rstrip("/")
+ return f"{local}/v1/mcp/sql" if local and _pool_is_local() else ""
+
+
+def _mint_sql_cred(hid: str, sid: str) -> str:
+ """Per-turn credential for the SQL MCP server: harness.session.exp.hmac.
+
+ The same HMAC construction as the model broker's turn credential (_mint_turn_cred) and
+ deliberately a different prefix and a different claim: this one authorises reading one
+ harness's database and nothing else, so a token lifted out of a sandbox cannot be replayed
+ at the broker, and one lifted from the broker cannot read a database.
+ """
+ exp = str(int(time.time()) + _BROKER_TTL_S)
+ body = f"{hid}|{sid}|{exp}"
+ sig = hmac.new((INTERNAL_KEY or "dev-insecure").encode(), body.encode(), hashlib.sha256).hexdigest()
+ return f"hrs_{base64.urlsafe_b64encode(body.encode()).decode().rstrip('=')}.{sig}"
+
+
+def _verify_sql_cred(tok: str) -> tuple[str, str] | None:
+ """(harness_id, session_id) for a valid unexpired token, else None."""
+ if not tok or not tok.startswith("hrs_"):
+ return None
+ try:
+ b64, sig = tok[4:].rsplit(".", 1)
+ body = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4)).decode()
+ hid, sid, exp = body.split("|")
+ except Exception: # noqa: BLE001 — a malformed token is simply invalid
+ return None
+ good = hmac.new((INTERNAL_KEY or "dev-insecure").encode(), body.encode(), hashlib.sha256).hexdigest()
+ if not hmac.compare_digest(sig, good) or int(exp) < int(time.time()):
+ return None
+ return hid, sid
+
+
+def _sql_mcp_server(hid: str, sid: str) -> dict | None:
+ """The MCP server entry to hand this turn, or None when there is nowhere to point it."""
+ url = _sql_mcp_url()
+ if not url:
+ print(f"[sql] {hid} has a database but no address a sandbox could reach this gateway on "
+ f"— set HARNESS_PUBLIC_BASE_URL. The agent gets no database tools this turn.",
+ flush=True)
+ return None
+ # No _ssrf_check here: that rule exists to stop a CUSTOMER-supplied URL pointing this server at
+ # something internal. This URL is our own, and self-hosted it is loopback by design.
+ return {"name": "database", "url": url, "transport": "http", "auth": _mint_sql_cred(hid, sid)}
+
+
+def _jsonrpc_result(rid, result: dict) -> JSONResponse:
+ return JSONResponse({"jsonrpc": "2.0", "id": rid, "result": result})
+
+
+def _tool_text(text: str, is_error: bool = False) -> dict:
+ return {"content": [{"type": "text", "text": text}], "isError": is_error}
+
+
[email protected]("/v1/mcp/sql")
+async def sql_mcp(request: Request):
+ """The MCP endpoint the agent's CLI talks to. Streamable HTTP, stateless.
+
+ Stateless — no mcp-session-id — because there is nothing to keep between calls: every request
+ carries the token that identifies the harness, and the connection is opened and closed per
+ query. That also means any replica can serve any call.
+ """
+ claims = _verify_sql_cred(_broker_token(request))
+ if not claims:
+ raise HTTPException(401, "invalid or expired turn credential")
+ hid, _sid = claims
+ try:
+ req = json.loads(await request.body() or b"{}")
+ except Exception: # noqa: BLE001
+ raise HTTPException(400, "malformed JSON-RPC request") from None
+ method, rid, params = req.get("method") or "", req.get("id"), req.get("params") or {}
+
+ if method == "initialize":
+ return _jsonrpc_result(rid, {
+ # Echo the client's protocol version when it names one: every CLI in play speaks a
+ # different revision and this server's two tools are identical in all of them.
+ "protocolVersion": str(params.get("protocolVersion") or "2024-11-05"),
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": "database", "version": "1"}})
+ if rid is None: # a notification (notifications/initialized) — nothing to answer
+ return Response(status_code=202)
+ if method == "tools/list":
+ return _jsonrpc_result(rid, {"tools": _SQL_MCP_TOOLS})
+ if method != "tools/call":
+ return JSONResponse({"jsonrpc": "2.0", "id": rid,
+ "error": {"code": -32601, "message": f"method not found: {method}"}})
+
+ v = await _harness_vertex(hid)
+ org = str((v or {}).get("org") or "")
+ rec = _ds_record(v)
+ if not rec:
+ return _jsonrpc_result(rid, _tool_text(
+ "No database is connected to this agent. Ask the person to connect one, then try "
+ "again — you cannot connect it yourself.", True))
+ name = params.get("name") or ""
+ args = params.get("arguments") or {}
+ try:
+ dsn = await _ds_dsn(org, rec)
+ if name == "schema":
+ out = await sql_plane.introspect(rec["engine"], dsn,
+ sample_rows=int(rec.get("sample_rows") or 0))
+ if not out.get("sampled"):
+ # Said plainly, because an agent that does not know sampling is off will read the
+ # absence of rows as an empty database and design a dashboard for one.
+ out["note"] = ("Sample rows are turned off for this connection, so you see the "
+ "shape of the data and none of its values. Use the query tool to "
+ "check a specific figure.")
+ return _jsonrpc_result(rid, _tool_text(json.dumps(out, ensure_ascii=False)))
+ if name == "query":
+ out = await sql_plane.run_query(rec["engine"], dsn, str(args.get("sql") or ""),
+ max_rows=_DS_AGENT_MAX_ROWS)
+ return _jsonrpc_result(rid, _tool_text(json.dumps(out, ensure_ascii=False)))
+ except sql_plane.SqlError as e:
+ # The database's own sentence, back to the agent as a tool error so it can fix the query
+ # itself. This is the loop that makes the tool worth having.
+ return _jsonrpc_result(rid, _tool_text(str(e), True))
+ except HTTPException as e:
+ return _jsonrpc_result(rid, _tool_text(_uhp_message(e), True))
+ return _jsonrpc_result(rid, _tool_text(f"No tool named {name!r} on this server.", True))
+
+
+def _uhp_message(e: HTTPException) -> str:
+ d = e.detail
+ return str(d.get("message")) if isinstance(d, dict) and d.get("__uhp__") else str(d)
+
+
# ── Starter Kits ──────────────────────────────────────────────────────────────────────────────
# A kit is a whole product in a folder: the Harness it needs, and a UI that talks to that Harness
# as its backend. Both are baked into the image from HarnessRouter/starter-kit (see
@@ -6687,6 +7222,26 @@ _KIT_BASE_PREFERENCE: tuple[tuple[str, str], ...] = (
)
+def _kit_datasource(kit: dict) -> dict | None:
+ """Whether this kit reads a database, from its own kit.json (`harness.datasource`).
+
+ Declared per kit rather than assumed, so the launch dialog asks for a connection only where
+ one is used. The shape is deliberately open — `engines` is a list, not a flag — so adding a
+ warehouse later is a change to this server and to a kit's manifest, and to nothing else.
+ """
+ spec = (kit.get("harness") or {}).get("datasource")
+ if not spec:
+ return None
+ if spec is True: # the short form: "yes, whatever this build supports"
+ spec = {}
+ if not isinstance(spec, dict):
+ print(f"[kits] {kit.get('id')}: harness.datasource is not an object — ignored", flush=True)
+ return None
+ declared = [e for e in (spec.get("engines") or []) if e in sql_plane.ENGINES]
+ return {"required": bool(spec.get("required", True)),
+ "engines": declared or list(sql_plane.ENGINES)}
+
+
def _kit_preference(kit: dict) -> list[tuple[str, str]]:
"""A kit's recommended pairings, or the default order when it names none."""
out: list[tuple[str, str]] = []
@@ -6913,6 +7468,9 @@ def _harness_out(v: dict) -> dict:
# The starter kit that provisioned this Harness, when one did. The kit's app uses it
# to find its own Harness instead of asking the user to choose from a list.
"kit": v.get("kit") or None,
+ # The database this harness reads, if one is connected — engine, host and database
+ # name, never the credential. An app uses it to know whether to offer a connect step.
+ "dataSource": _ds_public(_ds_record(v)),
"baseLabel": v.get("base_label") or v.get("base"),
"defaultModel": v.get("default_model") or "",
"systemPrompt": v.get("system_prompt") or "",
@@ -7106,6 +7664,7 @@ async def delete_harness(org: str, hid: str, request: Request) -> dict:
cur = await _vertex_get(hid)
if not cur or str(cur.get("org") or "") != org:
raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")
+ await _ds_forget(org, hid, cur) # a deleted agent must not still be holding a database password
await _vg_upsert("Harness", hid, {"deleted": "1"})
return {"id": hid, "deleted": True}
@@ -7168,6 +7727,12 @@ async def list_kits(request: Request) -> dict:
# about their setup that is not true.
"runningOn": ({"base": str(h.get("base") or ""),
"model": str(h.get("default_model") or "")} if h else None),
+ # Whether this kit reads a database, and which engines it accepts — declared
+ # by the kit itself, so the launch dialog asks for a connection only where one
+ # is actually used, and a kit added later needs no change here.
+ "datasource": _kit_datasource(kit),
+ # And what a launched one is actually connected to (never the credential).
+ "connected": _ds_public(_ds_record(h)) if h else None,
# What to run it on: this kit's own recommended pairings, each marked with
# whether the caller's integrations can serve it. The launch dialog renders
# these directly and preselects the one flagged `recommended`.
@@ -7176,9 +7741,18 @@ async def list_kits(request: Request) -> dict:
class KitLaunchBody(BaseModel):
- """What to run the kit on. Both optional: no body at all means "use the recommendation"."""
+ """What to run the kit on, and what it runs against.
+
+ Every field is optional and no body at all means "use the recommendation, connect nothing".
+ A kit that reads a database (kit.json `harness.datasource`) collects the connection at launch
+ so the first thing the person sees is their own data — the fields are the same three the
+ datasource route takes, and they are stored through exactly the same path.
+ """
base: str = ""
model: str = ""
+ engine: str = ""
+ connection_string: str = ""
+ sample_rows: bool = True
@app.post("/v1/kits/{kit_id}/launch")
@@ -7196,10 +7770,21 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Non
if not kit:
raise uhp_error(404, "kit_not_found", f"No starter kit '{kit_id}' in this build.")
+ # Checked before anything is provisioned: a typo in a connection string should cost the person
+ # a corrected form, not a half-configured Harness they now have to find and fix.
+ ds = _ds_validate(body_in.engine, body_in.connection_string) \
+ if (body_in and body_in.connection_string.strip()) else None
+
for r in await _vg_list_by_org("Harness", org):
if str(r.get("kit") or "") == kit_id and str(r.get("deleted") or "0") != "1":
- return {"kit": kit_id, "harnessId": r.get("id"),
- "route": (kit.get("app") or {}).get("route") or "", "created": False}
+ hid0 = str(r.get("id") or "")
+ # Someone who typed a connection string and pressed Launch means "connect this",
+ # whether or not the Harness already existed — which is also how you reconnect after
+ # a password change. Without a connection string the existing one is left alone.
+ rec0 = await _ds_write(org, hid0, ds, body_in.sample_rows) if ds else _ds_record(r)
+ return {"kit": kit_id, "harnessId": hid0,
+ "route": (kit.get("app") or {}).get("route") or "", "created": False,
+ "dataSource": _ds_public(rec0)}
spec = kit.get("harness") or {}
# An explicit choice from the launch dialog wins; no choice means take the recommendation.
@@ -7234,9 +7819,11 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Non
"kit": kit_id,
"custom": "1", "created_at": now, "updated_at": now, "deleted": "0"}
await _vg_upsert("Harness", hid, props)
+ rec = await _ds_write(org, hid, ds, body_in.sample_rows) if ds else None
print(f"[kits] launched {kit_id} -> {hid}", flush=True)
return {"kit": kit_id, "harnessId": hid,
- "route": (kit.get("app") or {}).get("route") or "", "created": True}
+ "route": (kit.get("app") or {}).get("route") or "", "created": True,
+ "dataSource": _ds_public(rec)}
@app.get("/v1/harnesses")
@@ -7373,5 +7960,6 @@ async def delete_harness_public(hid: str, request: Request) -> dict:
v = await _vertex_get(hid)
if not v or v.get("org") != org:
raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")
+ await _ds_forget(org, hid, v) # a deleted agent must not still be holding a database password
await _vg_upsert("Harness", hid, {"deleted": "1"})
return {"id": hid, "deleted": True}
diff --git a/gateway/backing.py b/gateway/backing.py
index 39143c07..f07d71b4 100644
--- a/gateway/backing.py
+++ b/gateway/backing.py
@@ -64,7 +64,15 @@ class BlobStore(Protocol):
class SecretStore(Protocol):
async def get(self, tenant: str, name: str) -> str | None: ...
- async def put(self, tenant: str, name: str, value: str) -> None: ...
+
+ async def put(self, tenant: str, name: str, value: str, *,
+ require_encryption: bool = False) -> None:
+ """`require_encryption=True` is the caller saying "this is a customer credential, not a
+ provider key injected by the operator" — a database connection string, for instance. A
+ store that cannot encrypt must raise SecretsNotConfigured rather than write it in the
+ clear. Part of the interface, not of one implementation: a datasource must be refused
+ the same way whichever backing is configured."""
+ ...
class WorkspaceFiles(Protocol):
diff --git a/gateway/tests/test_sql_datasource.py b/gateway/tests/test_sql_datasource.py
new file mode 100644
index 00000000..97d4af8b
--- /dev/null
+++ b/gateway/tests/test_sql_datasource.py
@@ -0,0 +1,538 @@
+"""Attaching a customer's database to a harness — the routes, the agent's tool, and the one rule
+that matters more than any of them: the connection string never comes back out.
+
+Every request in this file goes through the real app with local backing (SQLite + encrypted files
+in a temp dir), so what is asserted is what a caller would actually receive.
+
+THE CREDENTIAL CHECK IS NOT ONE TEST. `_seen` records every response body and every line the
+gateway printed, and the last test asserts the password appears in none of them — so a route added
+later that leaks it fails this file even if nobody writes a test for that route.
+
+Tests that need a real database are skipped when one is not reachable; the gate, the record and
+the refusal paths run everywhere. Two are seeded on the test VM:
+ ssh -f -N -L 55432:localhost:55432 -L 33306:localhost:33306 [email protected]
+"""
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import socket
+import sys
+import tempfile
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+# Set BEFORE importing app: the backing, the internal key and the encryption passphrase are all
+# read at import time, exactly as they are in a running container.
+_DATA = tempfile.mkdtemp(prefix="hr-sqltest-")
+os.environ.update({
+ "HR_BACKING": "local", "HR_DATA_DIR": _DATA,
+ "HR_SECRET_KEY": "test-passphrase-not-a-real-one",
+ "HARNESS_INTERNAL_KEY": "test-internal-key",
+ "HARNESS_GLOBAL_TENANT": "global",
+ # A base URL, so the MCP server is offered to a turn the way it would be in production.
+ "HARNESS_PUBLIC_BASE_URL": "https://gateway.example",
+ # Self-hosted: the runner is beside the gateway, and a database on localhost is the normal
+ # case rather than an attack. The hosted rule is exercised on its own below.
+ "HR_POOL_AUTH": "none",
+})
+
+import app # noqa: E402
+import backing # noqa: E402
+import sql_plane # noqa: E402
+from fastapi.testclient import TestClient # noqa: E402
+
+PG_DSN = "postgresql://postgres:devpass@localhost:55432/shop"
+MYSQL_DSN = "mysql://root:devpass@localhost:33306/shop"
+PASSWORD = "devpass"
+
+ORG = "testorg"
+HEADERS = {"x-harness-internal": "test-internal-key", "x-harness-org": ORG,
+ "x-harness-member": "[email protected]"}
+
+
+def _reachable(port: int) -> bool:
+ with socket.socket() as s:
+ s.settimeout(1.0)
+ return s.connect_ex(("127.0.0.1", port)) == 0
+
+
+needs_pg = pytest.mark.skipif(not _reachable(55432), reason="no PostgreSQL on localhost:55432")
+needs_mysql = pytest.mark.skipif(not _reachable(33306), reason="no MySQL on localhost:33306")
+
+# Every response body and every printed line this file produces. See the module docstring.
+_seen: list[str] = []
+
+
[email protected](scope="module")
+def client(capsys=None):
+ with TestClient(app.app) as c:
+ yield c
+
+
+class Rec:
+ """A client whose every response body is recorded before it is returned."""
+
+ def __init__(self, c: TestClient):
+ self.c = c
+
+ def _do(self, method: str, path: str, **kw):
+ r = getattr(self.c, method)(path, headers=HEADERS, **kw)
+ _seen.append(r.text)
+ return r
+
+ def get(self, path, **kw):
+ return self._do("get", path, **kw)
+
+ def post(self, path, **kw):
+ return self._do("post", path, **kw)
+
+ def put(self, path, **kw):
+ return self._do("put", path, **kw)
+
+ def delete(self, path, **kw):
+ return self._do("delete", path, **kw)
+
+
[email protected](scope="module")
+def api(client):
+ return Rec(client)
+
+
+def harness(api):
+ r = api.post("/v1/harnesses", json={"name": "Dashboard", "base": "claude-code"})
+ assert r.status_code == 200, r.text
+ return r.json()["id"]
+
+
+# ── the record, and where the credential is not ──────────────────────────────────
+
+def test_connecting_returns_the_database_but_never_the_credential(api, harness):
+ r = api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN, "sample_rows": True})
+ assert r.status_code == 200, r.text
+ ds = r.json()["dataSource"]
+ # What a person needs to recognise the connection they made…
+ assert ds == {"engine": "postgres", "host": "localhost:55432", "database": "shop",
+ "sampleRows": True, "updatedAt": ds["updatedAt"]}
+ # …and nothing else. No user, no password, no reference to where the secret is kept.
+ assert PASSWORD not in r.text and "postgres:" not in r.text and "secret" not in r.text
+
+
+def test_the_harness_record_carries_a_reference_and_not_a_connection_string(harness, api):
+ """Read the stored vertex directly: this is the shape a graph dump would show."""
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ v = asyncio.run(app.BACKING.graph.get(harness, label="Harness"))
+ rec = json.loads(v["datasource"])
+ assert rec["secret"] == f"vault:{app._ds_secret_key(harness)}"
+ assert PASSWORD not in json.dumps(rec)
+ assert PASSWORD not in json.dumps(v)
+
+
+def test_the_stored_secret_is_encrypted_on_disk(harness, api):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ files = list(Path(_DATA, "secrets").rglob(app._ds_secret_key(harness)))
+ assert files, "the credential was not written to the secret store"
+ raw = files[0].read_text()
+ assert raw.startswith("hrenc1:") and PASSWORD not in raw
+
+
+def test_a_harness_reports_its_datasource_and_a_fresh_one_reports_none(api, harness):
+ assert api.get(f"/v1/harnesses/{harness}").json()["dataSource"] is None
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "mysql", "connection_string": MYSQL_DSN, "sample_rows": False})
+ got = api.get(f"/v1/harnesses/{harness}").json()["dataSource"]
+ assert got["engine"] == "mysql" and got["database"] == "shop" and got["sampleRows"] is False
+
+
+def test_disconnecting_removes_the_record(api, harness):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ r = api.delete(f"/v1/harnesses/{harness}/datasource")
+ assert r.status_code == 200 and r.json() == {"harnessId": harness, "dataSource": None,
+ "disconnected": True}
+ assert api.get(f"/v1/harnesses/{harness}/datasource").json()["dataSource"] is None
+ # And the queries stop working, rather than working against a database nobody thinks is
+ # attached any more.
+ q = api.post(f"/v1/harnesses/{harness}/sql/query", json={"sql": "SELECT 1"})
+ assert q.status_code == 404 and q.json()["error"]["code"] == "datasource_not_connected"
+
+
+def test_another_org_cannot_see_or_use_a_datasource(client, harness, api):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ other = {**HEADERS, "x-harness-org": "someone-else"}
+ for r in (client.get(f"/v1/harnesses/{harness}/datasource", headers=other),
+ client.post(f"/v1/harnesses/{harness}/sql/query", headers=other, json={"sql": "SELECT 1"}),
+ client.get(f"/v1/harnesses/{harness}/sql/schema", headers=other)):
+ _seen.append(r.text)
+ assert r.status_code == 404 and r.json()["error"]["code"] == "harness_not_found"
+
+
+# ── what a bad connection string gets told ───────────────────────────────────────
+
+def test_an_unsupported_engine_says_what_is_supported(api, harness):
+ r = api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "snowflake", "connection_string": "snowflake://x/y"})
+ assert r.status_code == 400
+ assert r.json()["error"]["message"] == "This connects to PostgreSQL and MySQL databases."
+
+
+def test_the_wrong_kind_of_connection_string_is_caught_before_the_driver_is(api, harness):
+ r = api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": MYSQL_DSN})
+ assert r.status_code == 400
+ msg = r.json()["error"]["message"]
+ assert "PostgreSQL connection string looks like" in msg
+ # The example must not be the string they just sent back at them — that is how a password
+ # ends up in a UI error banner.
+ assert PASSWORD not in msg
+
+
+def test_a_hosted_instance_refuses_to_be_pointed_at_an_internal_address(api, harness, monkeypatch):
+ """Self-hosted, a database on localhost is the operator's own and allowed. Hosted, a customer
+ naming an internal host is the same abuse an MCP URL would be, and gets the same answer."""
+ monkeypatch.setattr(app, "_pool_is_local", lambda: False)
+ r = api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ assert r.status_code == 400 and r.json()["error"]["code"] == "unreachable_host"
+ # And the button that tests a connection refuses it too, rather than passing what the save
+ # would then reject.
+ t = api.post("/v1/datasource-test", json={"engine": "postgres", "connection_string": PG_DSN})
+ assert t.status_code == 400 and t.json()["error"]["code"] == "unreachable_host"
+
+
+def test_a_connection_string_with_no_database_says_so(api, harness):
+ r = api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": "postgresql://u:p@host:5432"})
+ assert r.status_code == 400 and "names no database" in r.json()["error"]["message"]
+
+
+def test_no_key_to_encrypt_with_is_a_sentence_naming_the_variable(api, harness, monkeypatch):
+ """The 501 the operator of a keyless instance must see. Not a 500, and not a plaintext write."""
+ monkeypatch.delenv("HR_SECRET_KEY", raising=False)
+ monkeypatch.setattr(app.BACKING, "secrets", backing.FileSecretStore(os.path.join(_DATA, "nokey")))
+ r = api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ assert r.status_code == 501
+ err = r.json()["error"]
+ assert err["code"] == "secrets_not_configured" and "HR_SECRET_KEY" in err["message"]
+ assert not list(Path(_DATA, "nokey").rglob("*")), "a credential was written anyway"
+
+
+# ── testing a connection before saving one ───────────────────────────────────────
+
+@needs_pg
+def test_test_connection_reports_the_tables_it_can_see(api):
+ r = api.post("/v1/datasource-test", json={"engine": "postgres", "connection_string": PG_DSN})
+ assert r.status_code == 200
+ body = r.json()
+ assert body["ok"] and body["database"] == "shop" and body["tableCount"] >= 3
+ assert "public.orders" in body["tables"]
+
+
+@needs_pg
+def test_a_wrong_password_is_a_usable_message_and_not_a_stack_trace(api):
+ r = api.post("/v1/datasource-test",
+ json={"engine": "postgres",
+ "connection_string": "postgresql://postgres:wrongpass@localhost:55432/shop"})
+ assert r.status_code == 200
+ body = r.json()
+ assert body["ok"] is False
+ assert "password" in body["error"].lower() or "authentication" in body["error"].lower()
+ assert "wrongpass" not in body["error"], "the failure echoed the password back"
+
+
+def test_an_unreachable_host_fails_the_test_rather_than_the_request(api):
+ r = api.post("/v1/datasource-test",
+ json={"engine": "postgres",
+ "connection_string": f"postgresql://u:{PASSWORD}@127.0.0.1:1/shop"})
+ # ok:false with HTTP 200 — "nothing is listening there" is a successful test reporting a
+ # failure, and the dialog renders body.error rather than a status code.
+ assert r.status_code == 200 and r.json()["ok"] is False and r.json()["error"]
+ assert PASSWORD not in r.text
+
+
+# ── running a query, which is what opening a dashboard does ──────────────────────
+
+@needs_pg
+def test_a_panel_refresh_returns_columns_and_rows(api, harness):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ r = api.post(f"/v1/harnesses/{harness}/sql/query",
+ json={"sql": "SELECT status, count(*) AS n FROM orders GROUP BY status ORDER BY n DESC"})
+ assert r.status_code == 200, r.text
+ body = r.json()
+ assert body["columns"] == ["status", "n"] and body["row_count"] >= 1
+ assert body["truncated"] is False
+
+
+@needs_mysql
+def test_the_same_query_shape_works_on_mysql(api, harness):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "mysql", "connection_string": MYSQL_DSN})
+ r = api.post(f"/v1/harnesses/{harness}/sql/query",
+ json={"sql": "SELECT name, price FROM products ORDER BY price DESC"})
+ assert r.status_code == 200, r.text
+ assert r.json()["columns"] == ["name", "price"] and r.json()["row_count"] >= 1
+
+
+@needs_pg
+def test_a_write_is_refused_before_it_reaches_the_database(api, harness):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ r = api.post(f"/v1/harnesses/{harness}/sql/query", json={"sql": "DELETE FROM orders"})
+ assert r.status_code == 400 and r.json()["error"]["code"] == "sql_refused"
+ # The rows are still there.
+ n = api.post(f"/v1/harnesses/{harness}/sql/query", json={"sql": "SELECT count(*) FROM orders"})
+ assert int(n.json()["rows"][0][0]) > 0
+
+
+@needs_pg
+def test_a_bad_column_comes_back_as_the_databases_own_sentence(api, harness):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ r = api.post(f"/v1/harnesses/{harness}/sql/query", json={"sql": "SELECT revenu FROM orders"})
+ assert r.status_code == 502 and r.json()["error"]["code"] == "sql_failed"
+ assert "revenu" in r.json()["error"]["message"]
+
+
+@needs_pg
+def test_the_row_cap_is_applied_and_declared(api, harness):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ r = api.post(f"/v1/harnesses/{harness}/sql/query",
+ json={"sql": "SELECT * FROM orders", "max_rows": 2})
+ body = r.json()
+ assert body["row_count"] <= 2 and body["limit_applied"] == 2
+
+
+@needs_pg
+def test_a_caller_cannot_ask_for_more_than_the_engine_allows(api, harness):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ r = api.post(f"/v1/harnesses/{harness}/sql/query",
+ json={"sql": "SELECT * FROM orders", "max_rows": 10_000_000})
+ assert r.json()["limit_applied"] == sql_plane.DEFAULT_MAX_ROWS
+
+
+# ── the schema, and the sample-rows switch ───────────────────────────────────────
+
+@needs_pg
+def test_sampling_on_shows_rows_and_sampling_off_shows_none(api, harness):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN, "sample_rows": True})
+ on = api.get(f"/v1/harnesses/{harness}/sql/schema").json()
+ assert on["sampled"] is True
+ assert all("sample" in t for t in on["tables"])
+ assert {t["name"] for t in on["tables"]} >= {"customers", "orders", "products"}
+
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN, "sample_rows": False})
+ off = api.get(f"/v1/harnesses/{harness}/sql/schema").json()
+ assert off["sampled"] is False
+ # The shape is still there; not one value of anyone's data is.
+ assert {t["name"] for t in off["tables"]} == {t["name"] for t in on["tables"]}
+ assert all("sample" not in t for t in off["tables"])
+ assert [c["name"] for c in off["tables"][0]["columns"]]
+
+
+# ── the agent's tool ─────────────────────────────────────────────────────────────
+
+def _rpc(client, token, method, params=None, rid=1):
+ body = {"jsonrpc": "2.0", "id": rid, "method": method, "params": params or {}}
+ r = client.post("/v1/mcp/sql", json=body,
+ headers={"authorization": f"Bearer {token}"} if token else {})
+ _seen.append(r.text)
+ return r
+
+
+def test_the_tool_endpoint_refuses_without_a_valid_credential(client, harness):
+ assert _rpc(client, None, "tools/list").status_code == 401
+ assert _rpc(client, "hrs_not-a-real-token", "tools/list").status_code == 401
+ # A token whose signature does not match this instance's key.
+ good = app._mint_sql_cred(harness, "sess1")
+ forged = good[:-1] + ("a" if good[-1] != "a" else "b")
+ assert _rpc(client, forged, "tools/list").status_code == 401
+
+
+def test_a_turn_credential_is_scoped_to_one_harness(client, api, harness):
+ """The token IS the authorisation. One minted for another harness must not read this one."""
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ other = api.post("/v1/harnesses", json={"name": "Other", "base": "claude-code"}).json()["id"]
+ r = _rpc(client, app._mint_sql_cred(other, "sess1"), "tools/call",
+ {"name": "query", "arguments": {"sql": "SELECT 1"}})
+ assert r.json()["result"]["isError"] is True
+ assert "No database is connected" in r.json()["result"]["content"][0]["text"]
+
+
+def test_the_tool_list_is_the_two_things_an_agent_needs(client, harness):
+ r = _rpc(client, app._mint_sql_cred(harness, "sess1"), "tools/list")
+ tools = r.json()["result"]["tools"]
+ assert [t["name"] for t in tools] == ["schema", "query"]
+ assert all(t["inputSchema"]["type"] == "object" for t in tools)
+
+
+def test_initialize_and_the_initialized_notification(client, harness):
+ tok = app._mint_sql_cred(harness, "sess1")
+ r = _rpc(client, tok, "initialize", {"protocolVersion": "2025-06-18"})
+ res = r.json()["result"]
+ assert res["protocolVersion"] == "2025-06-18" and res["capabilities"]["tools"] == {}
+ # A notification has no id and must be answered with no body.
+ n = client.post("/v1/mcp/sql", headers={"authorization": f"Bearer {tok}"},
+ json={"jsonrpc": "2.0", "method": "notifications/initialized"})
+ assert n.status_code == 202
+
+
+@needs_pg
+def test_the_agent_can_read_the_schema_and_run_a_select(client, api, harness):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN, "sample_rows": True})
+ tok = app._mint_sql_cred(harness, "sess1")
+
+ schema = json.loads(_rpc(client, tok, "tools/call",
+ {"name": "schema"}).json()["result"]["content"][0]["text"])
+ assert {t["name"] for t in schema["tables"]} >= {"customers", "orders", "products"}
+
+ out = _rpc(client, tok, "tools/call",
+ {"name": "query", "arguments": {"sql": "SELECT count(*) AS n FROM customers"}})
+ res = out.json()["result"]
+ assert res.get("isError") is not True
+ assert json.loads(res["content"][0]["text"])["columns"] == ["n"]
+
+
+@needs_pg
+def test_the_agent_is_told_when_sampling_is_off_rather_than_seeing_an_empty_database(client, api, harness):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN, "sample_rows": False})
+ schema = json.loads(_rpc(client, app._mint_sql_cred(harness, "s"), "tools/call",
+ {"name": "schema"}).json()["result"]["content"][0]["text"])
+ assert schema["sampled"] is False and "turned off" in schema["note"]
+ assert all("sample" not in t for t in schema["tables"])
+
+
+@needs_pg
+def test_the_agent_gets_the_error_back_and_can_fix_it(client, api, harness):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ tok = app._mint_sql_cred(harness, "sess1")
+ bad = _rpc(client, tok, "tools/call",
+ {"name": "query", "arguments": {"sql": "SELECT revenu FROM orders"}})
+ res = bad.json()["result"]
+ assert res["isError"] is True and "revenu" in res["content"][0]["text"]
+
+ refused = _rpc(client, tok, "tools/call",
+ {"name": "query", "arguments": {"sql": "DROP TABLE orders"}})
+ assert refused.json()["result"]["isError"] is True
+ assert "only select" in refused.json()["result"]["content"][0]["text"].lower()
+
+
+def test_an_unknown_tool_and_an_unknown_method_are_answered_not_crashed(client, harness):
+ tok = app._mint_sql_cred(harness, "sess1")
+ r = _rpc(client, tok, "tools/call", {"name": "drop_everything"})
+ assert r.json()["result"]["isError"] is True
+ m = _rpc(client, tok, "resources/list")
+ assert m.json()["error"]["code"] == -32601
+
+
+# ── how the tool reaches a turn ──────────────────────────────────────────────────
+
+def test_a_connected_harness_hands_its_turn_a_database_tool_and_no_credential(api, harness):
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ v = asyncio.run(app._harness_vertex(harness))
+ mcp, _skills, _off, _tools = asyncio.run(app._harness_plugins(harness, ORG, hv=v, sid="sess-42"))
+ entry = next(m for m in mcp if m["name"] == "database")
+ assert entry["url"] == "https://gateway.example/v1/mcp/sql"
+ assert PASSWORD not in json.dumps(entry)
+ # What the sandbox receives is a token, and it resolves back to this harness and this session.
+ assert app._verify_sql_cred(entry["auth"]) == (harness, "sess-42")
+
+
+def test_a_harness_with_no_database_hands_its_turn_no_database_tool(api, harness):
+ v = asyncio.run(app._harness_vertex(harness))
+ mcp, *_ = asyncio.run(app._harness_plugins(harness, ORG, hv=v, sid="sess-42"))
+ assert [m for m in mcp if m["name"] == "database"] == []
+
+
+def test_a_sql_token_is_not_a_model_broker_token_and_the_reverse(harness):
+ """Different audiences, so one lifted out of a sandbox cannot be spent at the other."""
+ sql_tok = app._mint_sql_cred(harness, "sess1")
+ llm_tok = app._mint_turn_cred("sess1", "anthropic")
+ assert app._verify_turn_cred(sql_tok) is None
+ assert app._verify_sql_cred(llm_tok) is None
+
+
+# ── launching a kit with a database attached ─────────────────────────────────────
+
+def test_launch_accepts_a_connection_and_a_bad_one_provisions_nothing(api, monkeypatch):
+ kit = {"id": "dash", "title": "Dashboards", "app": {"route": "/kits/dash"},
+ "harness": {"name": "Dashboards", "datasource": {"required": True},
+ "recommended": [{"base": "claude-code", "model": "claude-opus-5"}]}}
+ monkeypatch.setattr(app, "_kits", lambda: {"dash": kit})
+
+ bad = api.post("/v1/kits/dash/launch",
+ json={"engine": "postgres", "connection_string": "not-a-connection-string"})
+ assert bad.status_code == 400
+ # Nothing was provisioned on the way to that error.
+ assert next(k for k in api.get("/v1/kits").json()["kits"] if k["id"] == "dash")["launched"] is False
+
+ ok = api.post("/v1/kits/dash/launch",
+ json={"engine": "postgres", "connection_string": PG_DSN, "sample_rows": False})
+ assert ok.status_code == 200, ok.text
+ assert ok.json()["created"] is True
+ assert ok.json()["dataSource"] == {"engine": "postgres", "host": "localhost:55432",
+ "database": "shop", "sampleRows": False,
+ "updatedAt": ok.json()["dataSource"]["updatedAt"]}
+ # Launched twice: the same Harness, and the connection typed the second time is applied to it
+ # rather than silently dropped.
+ again = api.post("/v1/kits/dash/launch",
+ json={"engine": "mysql", "connection_string": MYSQL_DSN})
+ assert again.json()["harnessId"] == ok.json()["harnessId"]
+ assert again.json()["created"] is False
+ assert again.json()["dataSource"]["engine"] == "mysql"
+
+ listed = next(k for k in api.get("/v1/kits").json()["kits"] if k["id"] == "dash")
+ assert listed["datasource"] == {"required": True, "engines": ["postgres", "mysql"]}
+ assert listed["connected"]["engine"] == "mysql"
+
+
+def test_a_kit_that_reads_no_database_declares_none(api, monkeypatch):
+ monkeypatch.setattr(app, "_kits", lambda: {"slides": {"id": "slides", "title": "Slides",
+ "app": {"route": "/kits/slides"},
+ "harness": {"name": "Slides"}}})
+ assert next(k for k in api.get("/v1/kits").json()["kits"]
+ if k["id"] == "slides")["datasource"] is None
+
+
+# ── the whole file, checked at once ──────────────────────────────────────────────
+
+def test_the_password_appears_in_no_response_this_file_produced():
+ """Every body recorded above, in one assertion. A new route that leaks the credential fails
+ here even if nobody thought to test that route."""
+ assert _seen, "nothing was recorded — the recording client stopped being used"
+ leaked = [t for t in _seen if PASSWORD in t]
+ assert not leaked, f"{len(leaked)} response(s) contained the password: {leaked[:1]}"
+
+
+def test_the_password_appears_in_nothing_the_gateway_printed(api, harness, capsys):
+ """Connect, query, fail — then read the logs the container would have written."""
+ capsys.readouterr()
+ api.put(f"/v1/harnesses/{harness}/datasource",
+ json={"engine": "postgres", "connection_string": PG_DSN})
+ api.post(f"/v1/harnesses/{harness}/sql/query", json={"sql": "SELECT 1"})
+ api.post("/v1/datasource-test",
+ json={"engine": "postgres", "connection_string": f"postgresql://u:{PASSWORD}@127.0.0.1:1/x"})
+ api.delete(f"/v1/harnesses/{harness}/datasource")
+ out = capsys.readouterr()
+ assert PASSWORD not in out.out and PASSWORD not in out.err
+ # And it did log something identifying, so this is not passing on an empty string.
+ assert "[sql]" in out.out
diff --git a/ui/src/app/(app)/kits/page.tsx b/ui/src/app/(app)/kits/page.tsx
index bdaa8eb3..ae5d1263 100644
--- a/ui/src/app/(app)/kits/page.tsx
+++ b/ui/src/app/(app)/kits/page.tsx
@@ -21,6 +21,7 @@ interface Choice {
base: string; model: string; baseLabel: string;
available: boolean; recommended: boolean;
}
+interface Datasource { engine: string; host: string; database: string; sampleRows: boolean }
interface Kit {
id: string; title: string; tagline: string; description: string;
icon: string; accent: string; route: string;
@@ -28,7 +29,23 @@ interface Kit {
skills: string[];
runningOn: { base: string; model: string } | null;
choices: Choice[];
+ /** Set when this kit reads a database, listing the kinds it accepts. Null when it does not. */
+ datasource: { required: boolean; engines: string[] } | null;
+ /** What a launched kit is actually reading. Never carries the credential. */
+ connected: Datasource | null;
}
+
+/** What to call each kind of database in front of a person. */
+const ENGINE_LABEL: Record<string, string> = {
+ postgres: 'PostgreSQL',
+ mysql: 'MySQL / MariaDB',
+};
+
+/** Placeholder for a connection string, per kind — the format is the question people ask. */
+const ENGINE_EXAMPLE: Record<string, string> = {
+ postgres: 'postgresql://user:password@host:5432/database',
+ mysql: 'mysql://user:password@host:3306/database',
+};
interface BaseModel { id: string; available: boolean }
interface Base { id: string; label: string; models: BaseModel[] }
@@ -78,7 +95,7 @@ export default function KitsPage() {
window.open(route, '_blank', 'noopener,noreferrer');
}
- async function launch(kit: Kit, base?: string, model?: string) {
+ async function launch(kit: Kit, base?: string, model?: string, db?: DbDraft) {
// Open the tab NOW, on the click, and navigate it when the launch returns. Opening it after
// the await is a popup the browser is entitled to block, because by then it is no longer a
// user gesture.
@@ -88,7 +105,15 @@ export default function KitsPage() {
const r = await harnessFetch(`/api/harness/v1/kits/${kit.id}/launch`, {
method: 'POST',
headers: authHeaders(),
- body: JSON.stringify(base ? { base, model: model || '' } : {}),
+ body: JSON.stringify({
+ ...(base ? { base, model: model || '' } : {}),
+ // Sent only when the person filled the database step in. The connection string goes
+ // straight to the server and is never held anywhere else.
+ ...(db?.connectionString.trim()
+ ? { engine: db.engine, connection_string: db.connectionString.trim(),
+ sample_rows: db.sampleRows }
+ : {}),
+ }),
});
if (!r.ok) throw new Error((await r.json().catch(() => null))?.detail || `${r.status}`);
const { route } = await r.json();
@@ -173,6 +198,21 @@ export default function KitsPage() {
Installs {k.skills.join(', ')}
</li>
)}
+ {/* A launched kit reports the database it actually reads; one that has not been
+ launched reports what it will ask for. Neither is a guess. */}
+ {k.connected && (
+ <li>
+ <iconify-icon icon="tabler:database"></iconify-icon>
+ Reading {k.connected.database}
+ <span className="kit-fact-dim"> · {k.connected.host}</span>
+ </li>
+ )}
+ {!k.connected && k.datasource && (
+ <li>
+ <iconify-icon icon="tabler:database"></iconify-icon>
+ Reads your {k.datasource.engines.map((e) => ENGINE_LABEL[e] || e).join(' or ')} database
+ </li>
+ )}
</ul>
<footer className="kit-actions">
@@ -196,22 +236,30 @@ export default function KitsPage() {
<LaunchDialog
kit={picking} bases={bases} busy={busy === picking.id}
onClose={() => setPicking(null)}
- onLaunch={(base, model) => void launch(picking, base, model)}
+ onLaunch={(base, model, db) => void launch(picking, base, model, db)}
/>
)}
</div></section>
);
}
+interface DbDraft { engine: string; connectionString: string; sampleRows: boolean }
+
function LaunchDialog({ kit, bases, busy, onClose, onLaunch }: {
kit: Kit; bases: Base[]; busy: boolean;
- onClose: () => void; onLaunch: (base: string, model: string) => void;
+ onClose: () => void; onLaunch: (base: string, model: string, db?: DbDraft) => void;
}) {
const recommended = kit.choices.find((c) => c.recommended) || null;
const [sel, setSel] = useState<string>(recommended ? `${recommended.base}/${recommended.model}` : '');
const [custom, setCustom] = useState(false);
const [cBase, setCBase] = useState(bases[0]?.id || '');
const [cModel, setCModel] = useState('');
+ // Sampling defaults on: the agent designs better dashboards when it can see what a column
+ // actually contains. Off is one click away, and it is a real switch — off means the agent
+ // receives table and column names and not one value.
+ const [db, setDb] = useState<DbDraft>({
+ engine: kit.datasource?.engines[0] || 'postgres', connectionString: '', sampleRows: true,
+ });
// Models are per base, so changing the agent has to re-pick the model rather than keep one the
// new agent cannot run. First available, not first listed — an unavailable default is a trap.
@@ -229,12 +277,15 @@ function LaunchDialog({ kit, bases, busy, onClose, onLaunch }: {
}, [onClose]);
const nothingAvailable = !kit.choices.some((c) => c.available);
- const canLaunch = custom ? Boolean(cBase && cModel) : Boolean(sel);
+ const needsDb = Boolean(kit.datasource?.required) && !kit.connected;
+ const hasDb = db.connectionString.trim().length > 0;
+ const canLaunch = (custom ? Boolean(cBase && cModel) : Boolean(sel)) && (!needsDb || hasDb);
function go() {
- if (custom) { onLaunch(cBase, cModel); return; }
+ const draft = hasDb ? db : undefined;
+ if (custom) { onLaunch(cBase, cModel, draft); return; }
const [base, ...rest] = sel.split('/');
- onLaunch(base, rest.join('/'));
+ onLaunch(base, rest.join('/'), draft);
}
return (
@@ -304,6 +355,8 @@ function LaunchDialog({ kit, bases, busy, onClose, onLaunch }: {
</div>
)}
+ {kit.datasource && <DatabaseStep kit={kit} db={db} onChange={setDb} />}
+
<div className="kit-dialog-actions">
<button className="button ghost" type="button" onClick={() => setCustom((v) => !v)}>
{custom ? 'Back to recommended' : 'Choose a different one'}
@@ -318,3 +371,98 @@ function LaunchDialog({ kit, bases, busy, onClose, onLaunch }: {
</div>
);
}
+
+/** The database step of the launch dialog.
+ *
+ * Shown only for a kit that declares it reads one (kit.json `harness.datasource`), so no other
+ * kit grows a field it has no use for. The connection string is sent to the server and held
+ * nowhere else: it is not stored in this component's URL, not put in local storage, and the
+ * server never sends it back — a saved connection reads back as its host and database only.
+ */
+function DatabaseStep({ kit, db, onChange }: {
+ kit: Kit; db: DbDraft; onChange: (d: DbDraft) => void;
+}) {
+ const [test, setTest] = useState<{ state: 'idle' | 'busy' | 'ok' | 'err'; message: string }>(
+ { state: 'idle', message: '' });
+ const engines = kit.datasource?.engines || [];
+
+ async function runTest() {
+ setTest({ state: 'busy', message: '' });
+ try {
+ const r = await harnessFetch('/api/harness/v1/datasource-test', {
+ method: 'POST',
+ headers: authHeaders(),
+ body: JSON.stringify({ engine: db.engine, connection_string: db.connectionString.trim() }),
+ });
+ const body = await r.json().catch(() => null);
+ if (!r.ok) { setTest({ state: 'err', message: body?.detail || `${r.status}` }); return; }
+ if (!body?.ok) { setTest({ state: 'err', message: body?.error || 'could not connect' }); return; }
+ // The table count is the server's answer, not an estimate — and it is the number that tells
+ // someone whether the account they used can actually see their data.
+ setTest({ state: 'ok', message: `${body.database} · ${body.tableCount} tables` });
+ } catch {
+ setTest({ state: 'err', message: 'could not reach the server' });
+ }
+ }
+
+ return (
+ <div className="kit-db">
+ <h3 className="kit-db-title">
+ {kit.connected ? 'Change the database it reads' : 'Connect your database'}
+ </h3>
+ {kit.connected && (
+ <p className="kit-choice-why">
+ Currently reading {kit.connected.database} on {kit.connected.host}. Leave this blank to
+ keep it.
+ </p>
+ )}
+
+ <div className="kit-db-fields">
+ {engines.length > 1 && (
+ <label className="kit-field kit-db-engine">
+ <span>Type</span>
+ <select value={db.engine}
+ onChange={(e) => { onChange({ ...db, engine: e.target.value }); setTest({ state: 'idle', message: '' }); }}>
+ {engines.map((e) => <option key={e} value={e}>{ENGINE_LABEL[e] || e}</option>)}
+ </select>
+ </label>
+ )}
+ <label className="kit-field kit-db-conn">
+ <span>Connection string</span>
+ <input type="text" value={db.connectionString} spellCheck={false} autoComplete="off"
+ placeholder={ENGINE_EXAMPLE[db.engine] || ''}
+ onChange={(e) => { onChange({ ...db, connectionString: e.target.value }); setTest({ state: 'idle', message: '' }); }} />
+ </label>
+ </div>
+
+ <div className="kit-db-test">
+ <button className="button" type="button"
+ disabled={!db.connectionString.trim() || test.state === 'busy'} onClick={() => void runTest()}>
+ {test.state === 'busy' ? 'Testing…' : 'Test connection'}
+ </button>
+ {test.state === 'ok' && (
+ <span className="kit-test-status ok"><span className="kit-test-dot" />Connected · {test.message}</span>
+ )}
+ {test.state === 'err' && (
+ <span className="kit-test-status err"><span className="kit-test-dot" />{test.message}</span>
+ )}
+ </div>
+
+ <label className="kit-db-sample">
+ <input type="checkbox" checked={db.sampleRows}
+ onChange={(e) => onChange({ ...db, sampleRows: e.target.checked })} />
+ <span>
+ <strong>Let it see a few example rows</strong>
+ <em>
+ With this on the agent reads a handful of rows per table, so it can tell what a column
+ holds. With it off it sees table and column names and no values at all.
+ </em>
+ </span>
+ </label>
+
+ <p className="kit-choice-why">
+ Use an account that can only read. Your connection is encrypted and is never shown again.
+ </p>
+ </div>
+ );
+}
diff --git a/ui/src/app/hr.css b/ui/src/app/hr.css
index 7ff95add..c028370e 100644
--- a/ui/src/app/hr.css
+++ b/ui/src/app/hr.css
@@ -895,6 +895,38 @@ body.hr-resizing iframe { pointer-events: none; }
.kit-dialog-actions { display: flex; align-items: center; gap: 8px; margin-top: 20px; }
.kit-dialog-spacer { flex: 1; }
+/* The database step: only kits that read one show it. */
+.kit-db { margin-top: 20px; padding-top: 18px; border-top: 1px solid var(--line); }
+.kit-db-title { margin: 0 0 8px; font-size: 13px; font-weight: 650; color: var(--ink); }
+/* Type beside the string on a wide dialog, stacked when there is no room for both. */
+.kit-db-fields { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 10px; }
+.kit-db-engine { flex: 0 1 170px; }
+.kit-db-conn { flex: 1 1 240px; min-width: 0; }
+.kit-field input[type="text"] {
+ width: 100%; padding: 9px 11px; font: inherit; font-size: 12.5px; color: var(--ink);
+ background: var(--surface); border: 1px solid var(--line); border-radius: 9px;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+}
+.kit-field input[type="text"]:focus { outline: none; border-color: var(--accent); }
+.kit-field input::placeholder { color: var(--muted); opacity: .7; }
+
+.kit-db-test { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; margin-top: 12px; }
+.kit-test-status {
+ display: inline-flex; align-items: center; gap: 7px; min-width: 0;
+ font-size: 12.5px; font-weight: 500; color: var(--ink-2);
+}
+.kit-test-dot { width: 7px; height: 7px; border-radius: 999px; background: var(--muted); flex: none; }
+.kit-test-status.ok .kit-test-dot { background: #16a34a; }
+.kit-test-status.err { color: #b91c1c; }
+.kit-test-status.err .kit-test-dot { background: #dc2626; }
+
+.kit-db-sample { display: flex; gap: 9px; margin-top: 14px; cursor: pointer; }
+.kit-db-sample input { margin-top: 3px; accent-color: var(--accent); flex: none; }
+.kit-db-sample span { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
+.kit-db-sample strong { font-size: 13px; font-weight: 600; color: var(--ink); }
+.kit-db-sample em { font-style: normal; font-size: 11.5px; line-height: 1.45; color: var(--muted); }
+.kit-db .kit-choice-why { margin-top: 12px; }
+
@media (max-width: 720px) {
.kit-grid { grid-template-columns: 1fr; }
.kit-dialog { padding: 20px; }
@@ -902,5 +934,8 @@ body.hr-resizing iframe { pointer-events: none; }
.kit-dialog-actions { flex-wrap: wrap; }
.kit-dialog-spacer { display: none; }
.kit-dialog-actions .button { flex: 1 1 auto; justify-content: center; }
+ /* One field per line: a connection string needs the whole width to be readable. */
+ .kit-db-engine, .kit-db-conn { flex: 1 1 100%; }
+ .kit-db-test .button { flex: 1 1 auto; justify-content: center; }
}