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.
Python agent-apiagent-frameworkagent-harnessai-agentsai-infrastructurecoding-agentconformance-testingdeepseek-harnessharness-engineeringhermesllmopen-protocolopen-sourceopen-standardpi-coding-agentself-hosteduhpunified-apiunified-harness-protocolunified-interface
refactor(mcp): a database is an ordinary MCP server, because our own URL is what makes it ours
richard-epsillabf04ee11a734
diff --git a/gateway/app.py b/gateway/app.pyindex c5fb6994..bca06c7b 100644--- a/gateway/app.py+++ b/gateway/app.py@@ -2225,11 +2225,71 @@ async def _harness_vertex(harness_id: str) -> dict | None:return await BACKING.graph.get(harness_id, label="Harness")+# ── servers this gateway hosts itself, recognised by ADDRESS ──────────────────────────────────+# A server is ours if its url is one of our own addresses. That is the one thing true of every+# server we host and of no server we do not, so recognising them costs no field on the entry, no+# kind registry and no client-visible flag — and a second first-party server later needs nothing+# but a path under /v1/mcp/.+_HOSTED_MCP_PREFIX = "/v1/mcp/"+# What may follow that prefix: the server's name and nothing else — no second segment, no query,+# no dot-dot. See _hosted_mcp_path.+_HOSTED_MCP_NAME = re.compile(r"^[a-z0-9][a-z0-9_-]*$")+# Where a hosted server's own state lives. A namespace inside the secret store rather than a field+# anywhere: PUT /v1/mcp-secrets/{ref} prefixes every key it writes with `harness-mcp-`, so no+# caller can write into this one.+_HOSTED_SECRET_PREFIX = "harness-hosted-"+++def _own_origins() -> list[str]:+ """Every address a client could legitimately have stored for a server WE host.++ Hosted, that is the public base URL a sandbox reaches us on. Self-hosted, the runner is a+ process beside us and loopback is both correct and the only thing that resolves. Both are+ listed, in preference order, because an instance that gains a public URL later must keep+ serving the entries it wrote before it had one.+ """+ out = []+ if PUBLIC_BASE_URL:+ out.append(PUBLIC_BASE_URL)+ local = os.environ.get("HARNESS_GATEWAY_URL", "").rstrip("/")+ if local and _pool_is_local():+ out.append(local)+ return out+++def _hosted_mcp_path(url: str) -> str | None:+ """The path of a server THIS GATEWAY HOSTS, or None for a server somewhere else."""+ for origin in _own_origins():+ if not url.startswith(origin + _HOSTED_MCP_PREFIX):+ continue+ name = url[len(origin) + len(_HOSTED_MCP_PREFIX):]+ # A NAME under the prefix, not an arbitrary path. `/v1/mcp/../../v1/admin` starts with our+ # prefix and is a different endpoint once any client normalises it — hosted is what earns+ # a minted credential and a pass on _ssrf_check, and neither is owed to a string that only+ # looks like one of our servers. Not ours → the ordinary remote path, which hands it no+ # credential at all because _resolve_mcp_auth refuses this namespace.+ return _HOSTED_MCP_PREFIX + name if _HOSTED_MCP_NAME.match(name) else None+ return None+++def _vault_key(auth) -> str:+ """The secret-store key an entry's auth references, or "" when it references none."""+ return auth[len("vault:"):] if isinstance(auth, str) and auth.startswith("vault:") else ""++async def _resolve_mcp_auth(org: str, auth: str) -> str:"""Resolve an MCP server auth value. 'vault:<key>' → the secret from the org/global vault(token never sits in the graph). Anything else is treated as a literal bearer token."""if isinstance(auth, str) and auth.startswith("vault:"):key = auth[len("vault:"):]+ if key.startswith(_HOSTED_SECRET_PREFIX):+ # A record we hold for a server we host. It is not a bearer token for anybody, and+ # this is the one place a stored secret becomes a literal on an outbound request — so+ # refusing HERE is what makes "the connection string never leaves this process" true+ # for callers that do not exist yet, including an entry that names this ref and points+ # somewhere else on purpose.+ print(f"[mcp] refusing to resolve {key} as a bearer token", flush=True)+ return ""for tenant in _tenants_for(org):v = await _vault_get(tenant, key)if v:@@ -2238,6 +2298,27 @@ async def _resolve_mcp_auth(org: str, auth: str) -> str:return auth or ""+def _mcp_list(v: dict | None) -> list[dict]:+ """Every MCP server on a harness vertex. THE ONE READER: _harness_plugins, _harness_out and+ the $headers pre-scan all come through here, so a harness's tool list cannot mean one thing on+ the page that lists capabilities and another in the turn."""+ try:+ a = json.loads((v or {}).get("mcp_servers") or "[]")+ except Exception: # noqa: BLE001+ a = []+ return [s for s in a if isinstance(s, dict)] if isinstance(a, list) else []+++_MCP_NAME_RE = re.compile(r"[^a-zA-Z0-9_]+")+++def _mcp_name(s: str) -> str:+ """The identifier the agent's CLI will see for a server. The runner's _mcp_name, duplicated:+ the gateway has to ask the same question the runner will answer, and asking it over HTTP is+ not an option at config time."""+ return _MCP_NAME_RE.sub("_", (s or "").strip()).strip("_") or "mcp"++_HDR_REF = re.compile(r"\$headers\.([A-Za-z0-9_-]+)")@@ -2269,6 +2350,7 @@ async def _harness_plugins(harness_id: str, org: str, hdr_vals: dict[str, str] |# the default harnesses, which is what most people actually use, had no image generation# and no document skills while custom ones did.return [], _builtin_default_skills(), [], []+ v = await _mcp_migrate(org, harness_id, v)def _arr(prop):try:@@ -2278,13 +2360,40 @@ async def _harness_plugins(harness_id: str, org: str, hdr_vals: dict[str, str] |return []mcp_out: list[dict] = []- for s in _arr("mcp_servers"):- if not isinstance(s, dict) or str(s.get("enabled")) in ("False", "false", "0"):+ for s in _mcp_list(v):+ if str(s.get("enabled")) in ("False", "false", "0"):continueif not s.get("url"):continue_hvals = hdr_vals or {} # (renamed from hv — that name is now the harness-vertex param)_url = _sub_headers(s["url"], _hvals)+ hosted = _hosted_mcp_path(_url)++ if hosted:+ # A SERVER WE HOST. Two things follow, and neither is about what kind of server it is.+ #+ # The address is re-derived from the origin we serve on NOW, not the one stored: an+ # operator who moves the gateway must not strand every entry written before the move.+ # No _ssrf_check, because that rule's subject is a target a customer named, and a url+ # that already equals one of our own origins is not one however it got typed.+ #+ # The credential is MINTED, not resolved. _resolve_mcp_auth returns a literal that the+ # runner writes into .harness/mcp.json inside a container with bash — right for a+ # third-party bearer token, and never right for a credential to one of our own+ # services. That is the lesson of 2026-07-25, and it is a property of first-party+ # servers rather than of databases. What the sandbox holds is a capability scoped to+ # this harness, this session and the record this entry's auth names, and it expires.+ key = _vault_key(s.get("auth"))+ if not key.startswith(_HOSTED_SECRET_PREFIX):+ print(f"[mcp] '{s.get('name')}' on {harness_id} points here but names no record "+ f"this server holds — not offered this turn.", flush=True)+ continue+ mcp_out.append({"name": s.get("name") or s.get("id") or "mcp",+ "url": _own_origins()[0] + hosted,+ "transport": s.get("transport") or "http",+ "auth": _mint_hosted_cred(harness_id, sid, key)})+ continue+# Same rule the console's Test connection applies. Enforced here too, because this is the# call that actually reaches the network: a URL the policy rejects must never be handed to# a sandbox, whatever is stored on the harness.@@ -2306,15 +2415,6 @@ 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.@@ -5004,8 +5104,9 @@ async def create_response(body: CreateResponseBody, request: Request):# request didn't supply that header, the tool call would fail opaquely (bad auth at the MCP).# Reject up-front instead, naming exactly what's missing and where it's needed.missing: list[str] = []- for _s in _hv_arr("mcp_servers"):- if not isinstance(_s, dict) or str(_s.get("enabled")) in ("False", "false", "0"):+ # Through the one reader, so this scan sees exactly the servers the turn will get.+ for _s in _mcp_list(hv):+ if str(_s.get("enabled")) in ("False", "false", "0"):continue_blob = " ".join([str(_s.get("url") or ""), str(_s.get("auth") or "")," ".join(str(x) for x in (_s.get("headers") or {}).values())])@@ -6648,51 +6749,61 @@ 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+# ── The database, an ordinary MCP server ──────────────────────────────────────────────────────+# A customer's own database, connected 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:+# Its entry in `mcp_servers` is INDISTINGUISHABLE from a third-party one — {id, name, url,+# transport, auth, enabled} and not one field more. Nothing stored says "this one is ours",+# because nothing has to: a server is ours if its url is one of our own addresses+# (_hosted_mcp_path), and that answer is already knowable.+#+# THE ENTRY AND THE CONNECTION LIVE IN DIFFERENT PLACES, on purpose:+# * The ENTRY is configuration. It rides the vertex read every turn already does, is listed,+# renamed, switched off and removed exactly as any other server, and holds nothing about+# which database it reads.+# * THE CONNECTION — engine, host, database, the DSN, how many sample rows may be read — is one+# encrypted record at the key the entry's `auth` references, owned BY THE SERVER. It goes+# through BACKING.secrets with require_encryption=True, so host and database are encrypted at+# rest alongside the credential. It is read 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.#+# The record names the server it is for and the harness it belongs to, and each endpoint refuses a+# record not addressed to it (see _hosted_resolve). `auth` is a client-writable field on an+# ordinary entry and harness ids are public, so that binding — not the shape of a key — is what+# stops one harness pointing at another's connection.+## 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",+_DB_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+# The URL schemes each engine will accept. A MySQL string pasted into a Postgres connection is# caught here, with a sentence, rather than by a driver timing out twenty seconds later.-_DS_SCHEMES = {"postgres": ("postgres", "postgresql"), "mysql": ("mysql", "mariadb")}+_DB_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+_DB_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+_DB_AGENT_MAX_ROWS = 200-def _ds_engine(engine: str) -> str:- e = _DS_ENGINE_ALIASES.get((engine or "").strip().lower())+def _db_engine(engine: str) -> str:+ e = _DB_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]:+def _db_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+ Parsed at attach time so a person can later confirm WHICH database is attached without thecredential ever being read back out of the secret store."""from urllib.parse import urlparsetry:@@ -6700,7 +6811,7 @@ def _ds_parse(engine: str, conn: str) -> tuple[str, str]:except Exception as e: # noqa: BLE001raise 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]:+ if (u.scheme or "").lower() not in _DB_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",@@ -6718,82 +6829,241 @@ def _ds_parse(engine: str, conn: str) -> tuple[str, str]: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")+def _hosted_secret_key(hid: str, entry_id: str) -> str:+ """Where the record for one hosted server on one harness lives. Same charset rule as+ harness-mcp-<ref>.+ The harness id is in it so an operator reading the secret store can tell what a record belongs+ to; the entry id is what allows MORE THAN ONE hosted server per harness — the "at most one+ database" rule only ever existed because a key derived from the harness id alone made two of+ them collide. The key is not a security boundary: the record names its own harness, and that+ is (see _hosted_resolve).+ """+ def safe(s: str) -> str:+ return re.sub(r"[^a-z0-9]+", "-", (s or "").lower()).strip("-")+ return f"{_HOSTED_SECRET_PREFIX}{safe(hid) or 'harness'}-{safe(entry_id) or 'server'}"-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."""++async def _hosted_put_record(org: str, key: str, record: dict) -> None:+ """Write a hosted server's record. ALWAYS encrypted: the connection string is in it, and so+ are the host and the database name, which is strictly more than the vertex ever protected."""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)+ await BACKING.secrets.put(tenant, key, json.dumps(record), 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.+async def _hosted_record(org: str, key: str) -> dict | None:+ """A hosted server's record, or None when there is nothing readable to serve from.- 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:+ Deliberately NOT _resolve_mcp_auth: that helper falls back to treating a value as a literal+ bearer token, and refuses this namespace outright for exactly that reason.+ """+ if not key:return None- return rec if str(rec.get("secret") or "").startswith("vault:") else None+ for tenant in _tenants_for(org):+ raw = await _vault_get(tenant, key)+ if raw:+ try:+ rec = json.loads(raw)+ except Exception: # noqa: BLE001+ return None+ return rec if isinstance(rec, dict) else None+ return 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}+def _hosted_keys(servers: list[dict]) -> set[str]:+ """The records a list of entries references. Read off the entries, because with a per-entry+ key the entry is the only thing that knows where its record is."""+ return {k for k in (_vault_key(s.get("auth")) for s in servers)+ if k.startswith(_HOSTED_SECRET_PREFIX)}++async def _hosted_scrub_removed(org: str, hid: str, before: list[dict], after: list[dict]) -> None:+ """Overwrite the record behind every hosted entry this write removed.-async def _ds_dsn(org: str, rec: dict) -> str:- """The live connection string for a record, resolved from the secret store.+ Dropping the entry and leaving its connection string encrypted on disk would be a surprise of+ the worst kind: removing the tool, or deleting the agent, is the most decisive thing the+ surface offers. Shared by every write that can drop an entry, so they cannot promise+ differently.- 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.+ THE RECORD MUST BE THIS HARNESS'S — the same binding _hosted_resolve refuses a read on. `auth`+ is a client-writable field and harness ids are public, so anyone may name another agent's ref+ on an entry of their own; removing it would otherwise destroy a connection they were never+ given. Losing a database is the louder of the two surprises, so the check belongs on both.+ Positive evidence of foreign ownership is what skips the scrub: a record we cannot read is one+ we overwrite, because leaving a connection string behind is the failure this function exists+ to prevent."""- 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.")+ gone = _hosted_keys(before) - _hosted_keys(after)+ if not gone:+ return+ tenant = org if _vault_tenant_ok(org) else GLOBAL_TENANT+ scrubbed = 0+ for key in sorted(gone):+ rec = await _hosted_record(org, key)+ if rec and str(rec.get("harness") or "") != hid:+ print(f"[mcp] {hid}: not scrubbing {key} — that record belongs to another agent",+ flush=True)+ continue+ with contextlib.suppress(Exception): # an unwritable store must not block the write+ await BACKING.secrets.put(tenant, key, "", require_encryption=True)+ scrubbed += 1+ if scrubbed:+ print(f"[sql] {hid}: disconnected ({scrubbed} record(s) scrubbed)", flush=True)+++async def _mcp_write(hid: str, servers: list[dict]) -> None:+ """Write mcp_servers outside the config PUT — kit launch provisioning the server it needs."""+ await _vg_upsert("Harness", hid, {"mcp_servers": json.dumps(servers),+ "updated_at": str(int(time.time() * 1000))})+++def _connection_out(rec: dict) -> dict:+ """What a caller may see of a connection: which database, and how much of it the agent reads.+ Everything except the credential."""+ return {"engine": str(rec.get("engine") or ""), "host": str(rec.get("host") or ""),+ "database": str(rec.get("database") or ""),+ "sampleRows": bool(rec.get("sample_rows"))}+++# What every refusal below says. One sentence, because from the caller's side "there is no such+# entry", "its record is gone" and "that record is not yours" are the same fact: nothing here is+# connected to read.+_NOT_CONNECTED = "No database is connected to this agent yet."++async def _hosted_resolve(server: str, hid: str, org: str, servers: list[dict], *,+ key: str = "", entry_id: str = "",+ check_enabled: bool = False) -> tuple[dict, dict]:+ """(entry, record) for one server this gateway hosts — the resolution EVERY hosted endpoint+ shares, so the agent's tool and the app's data plane cannot answer differently.-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."""+ THE ENTRY IS FOUND BY WHAT ADDRESSED IT: the record key a turn credential carries, or the+ entry's own id from a route. Never by name, position or a flag — which is what makes renaming,+ reordering and several hosted servers on one harness free.++ THEN THE RECORD MUST BE ADDRESSED TO THIS SERVER AND THIS HARNESS. `auth` is a client-writable+ field on an ordinary entry and harness ids are public, so without the second check a caller+ could write another harness's ref onto their own entry and read a database they were never+ given. One structural check, behind the credential, that survives any write path added later —+ where a write-time validation would only cover the writes that exist today.++ `check_enabled` is for a turn and not for the app: switching a server off is a statement about+ what an AGENT is handed, and a dashboard refresh is not a turn. A token minted before the+ switch stays valid for hours, so the refusal has to be here and not only where turns are built.+ """+ if key:+ entry = next((e for e in servers if _vault_key(e.get("auth")) == key), None)+ elif entry_id:+ entry = next((e for e in servers if str(e.get("id") or "") == entry_id), None)+ else:+ entry = None+ if not entry:+ raise uhp_error(404, "database_not_connected", _NOT_CONNECTED, "harness_id")+ if check_enabled and str(entry.get("enabled")) in ("False", "false", "0"):+ raise uhp_error(404, "database_not_connected", _NOT_CONNECTED, "harness_id")+ rec = await _hosted_record(org, _vault_key(entry.get("auth")))+ if not rec or rec.get("server") != server or rec.get("harness") != hid:+ raise uhp_error(404, "database_not_connected", _NOT_CONNECTED, "harness_id")+ return entry, rec+++async def _harness_for_route(hid: str, org: str) -> dict:+ """The harness a /servers/{sid} route is addressed to: owned by this org, not deleted, and+ converted off any earlier shape first — which is the reason this is a helper rather than the+ three inline lines every other route carries."""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)+ return await _mcp_migrate(org, hid, v)+++# ── migration: two earlier shapes of "the harness's database" ─────────────────────────────────+# Shape 0, everything deployed: a `datasource` prop on the vertex. Shape 1, the refactor this+# replaces: an mcp_servers entry with `managed` and `config`. Both hold {engine, secret, host,+# database, sample_rows, updated_at} beside a BARE DSN at harness-ds-<hid-safe>.+#+# The payload genuinely changes — bare string to a JSON record, at a new key — so this is a+# CONVERTER and not a wrapper. A read-repair projection would force _hosted_record to understand+# two secret shapes forever, which is the accretion the house style forbids.+_DS_PROP_LEGACY = "datasource"+++def _legacy_db_config(c) -> dict | None:+ """An earlier configuration block, or None. Fails closed: a block we cannot read has to mean+ "not connected", and a `secret` that is not a reference is not a fallback to a literal."""+ if not isinstance(c, dict) or c.get("engine") not in sql_plane.ENGINES:+ return None+ return c if str(c.get("secret") or "").startswith("vault:") else None+++async def _mcp_migrate(org: str, hid: str, v: dict | None) -> dict | None:+ """Convert a database connected under either earlier shape into an ordinary hosted entry.++ Once, in place, on the first read that needs it — there is no global harness scan, and a+ customer connected before this change must not have a broken turn while an operator remembers+ to run something. Prints one [migrate] line per harness, so the condition for deleting this+ function is a number you can count rather than a guess.+ """+ if not v:+ return v+ # The HARNESS's org, not the caller's: this writes a record that belongs to the harness, and+ # only the vertex knows whose tenant that is.+ org = str(v.get("org") or org)+ # Parsed ONCE. Two _mcp_list calls return two sets of dicts parsed from the same JSON, so the+ # replacement below would match nothing and leave both entries on the harness.+ servers = _mcp_list(v)+ old_entry = next((e for e in servers if _legacy_db_config(e.get("config"))), None)+ cfg = _legacy_db_config((old_entry or {}).get("config"))+ if not cfg:+ try:+ cfg = _legacy_db_config(json.loads(v.get(_DS_PROP_LEGACY) or "null"))+ except Exception: # noqa: BLE001+ cfg = None+ if not cfg:+ return v++ origins = _own_origins()+ if not origins:+ print(f"[migrate] {hid}: no address to serve its database on — set "+ f"HARNESS_PUBLIC_BASE_URL. Left as it was.", flush=True)+ return v+ old_key = cfg["secret"][len("vault:"):]+ dsn = ""+ for tenant in _tenants_for(org):+ dsn = await _vault_get(tenant, old_key) or ""+ if dsn:+ break+ if not dsn:+ # A harness we cannot migrate must not be a harness we silently disconnect.+ print(f"[migrate] {hid}: its stored credential could not be read — left as it was.",+ flush=True)+ return v++ entry_id = "mcp.database"+ key = _hosted_secret_key(hid, entry_id)+ # Every field taken from the old configuration: nothing re-derived, nothing re-parsed.+ await _hosted_put_record(org, key, {+ "server": "database", "harness": hid, "engine": cfg["engine"], "dsn": dsn,+ "host": cfg.get("host") or "", "database": cfg.get("database") or "",+ "sample_rows": int(cfg.get("sample_rows") or 0),+ "updated_at": int(cfg.get("updated_at") or 0)})+ entry = {"id": entry_id, "name": str((old_entry or {}).get("name") or "database"),+ "url": origins[0] + _HOSTED_MCP_PREFIX + "database", "transport": "http",+ "auth": f"vault:{key}",+ "enabled": str((old_entry or {}).get("enabled", True)) not in ("False", "false", "0")}+ servers = [e for e in servers if e is not old_entry] + [entry]+ await _vg_upsert("Harness", hid, {"mcp_servers": json.dumps(servers), _DS_PROP_LEGACY: ""})+ with contextlib.suppress(Exception): # an unwritable store must not strand the conversion+ tenant = org if _vault_tenant_ok(org) else GLOBAL_TENANT+ await BACKING.secrets.put(tenant, old_key, "", require_encryption=True)+ print(f"[migrate] {hid}: database is now an ordinary MCP server", flush=True)+ return {**v, "mcp_servers": json.dumps(servers), _DS_PROP_LEGACY: ""}def _sql_http(e: Exception) -> HTTPException:@@ -6808,47 +7078,22 @@ def _sql_http(e: Exception) -> HTTPException: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):+class DatabaseTestBody(BaseModel):engine: strconnection_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]:+def _db_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 aconnection string should not leave a half-configured Harness behind."""- eng = _ds_engine(engine)+ eng = _db_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)+ host, db = _db_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@@ -6864,75 +7109,55 @@ def _ds_validate(engine: str, conn: str) -> tuple[str, str, str, str]: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."""+async def _hosted_db_attach(org: str, hid: str, v: dict | None, decl: dict,+ checked: tuple[str, str, str, str], sample_rows: bool) -> None:+ """Provision a database connection: one encrypted record, one ordinary entry.++ THE ONLY THING THAT EVER WRITES A RECORD, and kit launch is its only caller — connecting a+ database is something the kit that reads one drives, not something the tool list exposes.++ Reconnecting after a password change replaces the record ON THE EXISTING ENTRY, reusing that+ entry's key, so no record is left orphaned behind. `name` and `enabled` come from the entry+ being replaced: they belong to whoever configured the harness, and reconnecting is a statement+ about the credential and about nothing else.+ """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))})+ origins = _own_origins()+ if not origins:+ # An entry with no url is not an ordinary entry, so refusing beats storing a broken one.+ raise uhp_error(501, "gateway_address_not_configured",+ "This server has no address an agent could reach it on — set "+ "HARNESS_PUBLIC_BASE_URL.", "database")+ cur = _mcp_list(v)+ prev = next((e for e in cur if str(e.get("id") or "") == decl["id"]), None) or {}+ prev_key = _vault_key(prev.get("auth"))+ key = prev_key if prev_key.startswith(_HOSTED_SECRET_PREFIX) else _hosted_secret_key(hid, decl["id"])+ await _hosted_put_record(org, key, {+ "server": "database", "harness": hid, "engine": engine, "dsn": conn,+ "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": _DB_SAMPLE_ROWS if sample_rows else 0,+ "updated_at": int(time.time() * 1000)})+ entry = {"id": decl["id"], "name": str(prev.get("name") or decl["name"]),+ "url": origins[0] + _HOSTED_MCP_PREFIX + "database", "transport": "http",+ "auth": f"vault:{key}",+ "enabled": str(prev.get("enabled", True)) not in ("False", "false", "0")}+ await _mcp_write(hid, [e for e in cur if str(e.get("id") or "") != decl["id"]] + [entry])# 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.+async def _db_probe(engine: str, conn: str) -> dict:+ """Try a connection string, and say what went wrong if it fails.Same shape as /v1/mcp-test: {ok:true, …} or {ok:false, error} with HTTP 200, because "yourpassword 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)+ # Validated exactly as attaching 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 none.+ engine, conn, host, db = _db_validate(engine, conn)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@@ -6945,38 +7170,75 @@ async def test_datasource(body: DatasourceTestBody, request: Request) -> dict:"tables": [f"{t['schema']}.{t['name']}" for t in schema["tables"][:12]]}+# Two probes rather than one because a DSN is not a URL: /v1/mcp-test takes {url, auth} and this+# takes {engine, connection_string}, and a union body would be worse than two names. Both come in+# an org-scoped and a public flavour so a console that tests either kind has one auth shape.[email protected]("/v1/orgs/{org}/mcp-test/database")+async def test_database(org: str, body: DatabaseTestBody, request: Request) -> dict:+ await _owned_org(request, org)+ return await _db_probe(body.engine, body.connection_string)++[email protected]("/v1/mcp-test/database")+async def test_database_public(body: DatabaseTestBody, request: Request) -> dict:+ await _pub_org_member(request)+ return await _db_probe(body.engine, body.connection_string)++class SqlQueryBody(BaseModel):sql: strmax_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.+# ── the app's data plane: one hosted server, addressed by the entry that names it ─────────────+# A dashboard re-runs every panel's query when someone opens it, and doing that through the agent+# would cost a turn per panel per page-load. Not a second mechanism for the same thing — a browser+# is not an MCP client and must never hold a turn credential — and every statement still passes+# the same read-only gate, row cap and timeout the agent's own tool does.+#+# Addressed by entry id rather than by harness, because "the harness's database" is the same+# assumption that put connection state on the vertex: a harness may have several hosted servers,+# and the caller has to be able to say which. The harness segment carries authorization; the+# server segment names the server.+[email protected]("/v1/harnesses/{hid}/servers/{sid}")+async def get_harness_server(hid: str, sid: str, request: Request) -> dict:+ """One server this gateway hosts, describing itself — including what it is connected to.- 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.+ The server that owns the connection is the one that names it, exactly as tools/list is a+ third-party server describing itself. Connection state does not ride a harness read."""org, _ = await _pub_org_member(request)- rec, dsn = await _ds_for_harness(hid, org)+ v = await _harness_for_route(hid, org)+ entry, rec = await _hosted_resolve("database", hid, org, _mcp_list(v), entry_id=sid)+ return {"id": entry.get("id"), "name": entry.get("name"),+ "enabled": str(entry.get("enabled", True)) not in ("False", "false", "0"),+ "connection": _connection_out(rec)}++[email protected]("/v1/harnesses/{hid}/servers/{sid}/query")+async def run_server_query(hid: str, sid: str, body: SqlQueryBody, request: Request) -> dict:+ """Run one SELECT — what refreshing a dashboard panel does."""+ org, _ = await _pub_org_member(request)+ v = await _harness_for_route(hid, org)+ _entry, rec = await _hosted_resolve("database", hid, org, _mcp_list(v), entry_id=sid)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)+ return await sql_plane.run_query(rec["engine"], rec["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."""[email protected]("/v1/harnesses/{hid}/servers/{sid}/schema")+async def get_server_schema(hid: str, sid: str, request: Request) -> dict:+ """The shape of the connected 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)+ v = await _harness_for_route(hid, org)+ _entry, rec = await _hosted_resolve("database", hid, org, _mcp_list(v), entry_id=sid)try:- return await sql_plane.introspect(rec["engine"], dsn,+ return await sql_plane.introspect(rec["engine"], rec["dsn"],sample_rows=int(rec.get("sample_rows") or 0))except sql_plane.SqlError as e:raise _sql_http(e) from e@@ -6993,13 +7255,13 @@ async def get_harness_schema(hid: str, request: Request) -> dict:# / _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 = [+_DB_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}). "+ "description": (f"Run one read-only SELECT and see the rows (up to {_DB_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"],@@ -7008,60 +7270,34 @@ _SQL_MCP_TOOLS = []-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.+def _mint_hosted_cred(hid: str, sid: str, key: str) -> str:+ """Per-turn credential for a server this gateway hosts: harness.session.record.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+ deliberately a different prefix and a different claim set: this one authorises reading one+ record on one harness and nothing else, so a token lifted out of a sandbox cannot be replayedat 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}"+ body = f"{hid}|{sid}|{key}|{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."""+def _verify_hosted_cred(tok: str) -> tuple[str, str, str] | None:+ """(harness_id, session_id, record key) for a valid unexpired token, else None."""if not tok or not tok.startswith("hrs_"):return Nonetry:b64, sig = tok[4:].rsplit(".", 1)body = base64.urlsafe_b64decode(b64 + "=" * (-len(b64) % 4)).decode()- hid, sid, exp = body.split("|")+ hid, sid, key, exp = body.split("|")except Exception: # noqa: BLE001 — a malformed token is simply invalidreturn Nonegood = 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)}+ return hid, sid, keydef _jsonrpc_result(rid, result: dict) -> JSONResponse:@@ -7072,18 +7308,18 @@ 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):[email protected]("/v1/mcp/database")+async def database_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.+ carries the token that identifies the harness and the record, 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))+ claims = _verify_hosted_cred(_broker_token(request))if not claims:raise HTTPException(401, "invalid or expired turn credential")- hid, _sid = claims+ hid, _sid, key = claimstry:req = json.loads(await request.body() or b"{}")except Exception: # noqa: BLE001@@ -7100,25 +7336,34 @@ async def sql_mcp(request: Request):if rid is None: # a notification (notifications/initialized) — nothing to answerreturn Response(status_code=202)if method == "tools/list":- return _jsonrpc_result(rid, {"tools": _SQL_MCP_TOOLS})+ return _jsonrpc_result(rid, {"tools": _DB_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)+ if v and str(v.get("deleted")) in ("1", "true", "True"):+ v = None # a token outlives the agent it was minted for; the agent's+ # database access must notorg = str((v or {}).get("org") or "")- rec = _ds_record(v)- if not rec:+ try:+ _entry, rec = await _hosted_resolve("database", hid, org, _mcp_list(v),+ key=key, check_enabled=True)+ except HTTPException:+ # Every refusal, in the agent's terms. The last clause is load-bearing: without it a model+ # spends the rest of the turn looking for a way to connect one itself.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,+ out = await sql_plane.introspect(rec["engine"], rec["dsn"],sample_rows=int(rec.get("sample_rows") or 0))+ # WHICH database this is, from the record that owns it. The kit's skill tells the agent+ # to copy this into the dashboard it writes, and the agent has no other way to know.+ out["connection"] = _connection_out(rec)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.@@ -7127,8 +7372,8 @@ async def sql_mcp(request: Request):"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)+ out = await sql_plane.run_query(rec["engine"], rec["dsn"], str(args.get("sql") or ""),+ max_rows=_DB_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@@ -7222,24 +7467,22 @@ _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`).+def _kit_launch_database(kit: dict) -> dict | None:+ """What this kit's LAUNCH DIALOG must collect, from its own kit.json (`harness.launch`).- 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.+ A statement about launch, not an mcp_servers entry: a kit that reads a database is asked for+ one before anything is provisioned, because every panel it builds would otherwise have nothing+ to read. Declaring it is what makes it required, so there is no `required` field to disagree+ with. `engines` narrows the picker and is a list rather than 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:+ d = ((kit.get("harness") or {}).get("launch") or {}).get("database")+ if not isinstance(d, dict):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)}+ declared = [e for e in (d.get("engines") or []) if e in sql_plane.ENGINES]+ return {"engines": declared or list(sql_plane.ENGINES),+ "name": str(d.get("name") or "database"),+ "id": str(d.get("id") or "mcp.database")}def _kit_preference(kit: dict) -> list[tuple[str, str]]:@@ -7468,13 +7711,12 @@ 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 "",- "mcpServers": _parse(v.get("mcp_servers")), "skills": _parse(v.get("skills")),+ # Verbatim: what a client reads is what is stored, for every entry, which is the+ # ordinary contract and the only one there now is.+ "mcpServers": _mcp_list(v), "skills": _parse(v.get("skills")),"disabledTools": [t for t in _parse(v.get("disabled_tools")) if isinstance(t, str)],"additionalHeaders": [h for h in _parse(v.get("additional_headers")) if isinstance(h, str) and h.strip()],"maxStep": int(v.get("max_step")) if str(v.get("max_step") or "").isdigit() else None,@@ -7502,6 +7744,36 @@ _WS_WRITE_MAX = 4 * 1024 * 1024 # an app writing its own state, not an upload_SKILL_INLINE_MAX = 48_000 # keep the vertex `skills` prop safely under the 64k value cap+def _mcp_servers_prepare(incoming: list | None) -> list[dict]:+ """Normalise mcp_servers at config time (the same bar _skills_prepare holds skills to).++ ONE RULE FOR EVERY ENTRY, including the ones this gateway hosts itself. An entry the caller+ did not send is gone — there is no keep-if-omitted exemption, because keeping one requires+ knowing which entries are special, which is the parallel path this replaced. The record behind+ a removed entry is scrubbed rather than orphaned (see _hosted_scrub_removed); a stale tab's+ Save can therefore disconnect a database, and the fix for that is optimistic concurrency for+ ALL entries rather than an exemption for one.+ """+ out: list[dict] = []+ for i, s in enumerate(incoming or []):+ if not isinstance(s, dict):+ raise uhp_error(400, "invalid_mcp_server", f"mcp_servers[{i}]: must be an object.", "mcp_servers")+ if not s.get("url"):+ raise uhp_error(400, "invalid_mcp_server", f"mcp_servers[{i}]: url required.", "mcp_servers")+ out.append(s)+ # Two servers with the same sanitised name are ONE server to every backend — the runner keys+ # them by name and the last wins, so half the tool list would vanish with no error.+ names: dict[str, str] = {}+ for e in out:+ nm = _mcp_name(str(e.get("name") or "mcp"))+ if nm in names:+ raise uhp_error(400, "duplicate_server_name",+ f"'{e.get('name')}' and '{names[nm]}' are the same server to an agent "+ f"— give one of them a different name.", "mcp_servers")+ names[nm] = str(e.get("name") or "")+ return out++async def _skills_prepare(skills: list | None) -> list:"""Validate + normalize harness skills at config time (HRP-008).@@ -7573,6 +7845,7 @@ async def create_harness(org: str, body: HarnessBody, request: Request) -> dict:p = await _owned_org(request, org)member = p.get("member") or request.headers.get("x-harness-member", "")workspace = request.headers.get("x-harness-workspace", "")+ body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)body.skills = await _skills_prepare(body.skills)hid = _rid("chrn")now = str(int(time.time() * 1000))@@ -7593,7 +7866,7 @@ async def list_harnesses(org: str, request: Request,workspace (Space id); `workspace_default=1` lets unstamped legacy records through."""await _owned_org(request, org)rows = await _vg_list_by_org("Harness", org)- items = [_harness_out(r) for r in rows+ items = [_harness_out(await _mcp_migrate(org, str(r.get("id") or ""), r)) for r in rowsif str(r.get("deleted")) not in ("1", "true", "True")]if workspace:items = [i for i in items if _workspace_keep(i.get("workspace") or "", workspace, bool(workspace_default))]@@ -7607,7 +7880,7 @@ async def get_harness(org: str, hid: str, request: Request) -> dict: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 _harness_out(v)+ return _harness_out(await _mcp_migrate(org, hid, v))@app.get("/v1/orgs/{org}/harnesses/{hid}/models")@@ -7650,9 +7923,14 @@ async def update_harness(org: str, hid: str, body: HarnessBody, request: Requestcur = await _vertex_get(hid)if not cur or str(cur.get("org") or "") != org or str(cur.get("deleted")) in ("1", "true", "True"):raise uhp_error(404, "harness_not_found", "No harness with that id.", "harness_id")+ cur = await _mcp_migrate(org, hid, cur)# coalesce-upsert: created_at/org are untouched (only the provided props are set)+ body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)body.skills = await _skills_prepare(body.skills)await _vg_upsert("Harness", hid, {**_harness_props(body), "updated_at": str(int(time.time() * 1000))})+ # AFTER the write: _harness_props can still refuse this save (an unsupported base), and a+ # refused save that had already scrubbed a record would disconnect a database nobody removed.+ await _hosted_scrub_removed(org, hid, _mcp_list(cur), body.mcp_servers)v = await _vertex_get(hid)return _harness_out(v or {"id": hid})@@ -7664,8 +7942,10 @@ 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+ cur = await _mcp_migrate(org, hid, cur)await _vg_upsert("Harness", hid, {"deleted": "1"})+ # a deleted agent must not still be holding a database password+ await _hosted_scrub_removed(org, hid, _mcp_list(cur), [])return {"id": hid, "deleted": True}@@ -7685,6 +7965,7 @@ async def create_harness_public(body: HarnessBody, request: Request) -> dict:org, member = p.get("org", ""), p.get("member", "")if not org:raise uhp_error(401, "invalid_credential", "Missing or invalid API key.")+ body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)body.skills = await _skills_prepare(body.skills)hid = _rid("chrn")now = str(int(time.time() * 1000))@@ -7710,7 +7991,7 @@ async def list_kits(request: Request) -> dict:out = []for kid, kit in sorted(_kits().items()):h = by_kit.get(kid)- out.append({"id": kid, "object": "kit",+ row = {"id": kid, "object": "kit","title": kit.get("title") or kid,"tagline": kit.get("tagline") or "","description": kit.get("description") or "",@@ -7734,32 +8015,40 @@ 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`.- "choices": await _kit_choices(org, kit)})+ "choices": await _kit_choices(org, kit)}+ # Two facts, both about the KIT: that it reads a database, and which engines it takes. What+ # a launched one is pointed AT is deliberately absent — nobody reads their data on this+ # page, and the surface where they do names it from the server that owns the connection.+ decl = _kit_launch_database(kit)+ if decl:+ row["database"] = {"engines": decl["engines"]}+ out.append(row)return {"kits": out}+class KitDatabaseBody(BaseModel):+ """The connection a kit that reads a database is launched with. `sample_rows` defaults 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 names and types and not one row of business data."""+ engine: str+ connection_string: str+ sample_rows: bool = True++class KitLaunchBody(BaseModel):"""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.+ A kit that declares `harness.launch.database` collects the connection HERE, at launch, so the+ first thing the person sees is their own data — and so that connecting a database is something+ the kit that reads one drives rather than something the tool list exposes. Relaunching with a+ connection string is how you reconnect after a password change."""base: str = ""model: str = ""- engine: str = ""- connection_string: str = ""- sample_rows: bool = True+ database: KitDatabaseBody | None = None@app.post("/v1/kits/{kit_id}/launch")@@ -7777,21 +8066,37 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Nonif not kit:raise uhp_error(404, "kit_not_found", f"No starter kit '{kit_id}' in this build.")+ decl = _kit_launch_database(kit)+ db_in = body_in.database if body_in else None+ if db_in and not decl:+ raise uhp_error(400, "connection_not_used",+ f"The '{kit_id}' kit does not read a database.", "database")# 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":- 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)}+ # a corrected form, not a half-configured Harness to find and fix.+ checked = _db_validate(db_in.engine, db_in.connection_string) if db_in else None++ existing = next((r 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"),+ None)+ if decl and not db_in and not existing:+ # Declaring launch.database is what makes it required: every panel this kit builds would+ # have nothing to read, so a launch without a connection is not a partial success.+ raise uhp_error(400, "connection_required",+ "This kit reads a database. Give it a connection string to launch it.",+ "database")++ if existing:+ hid0 = str(existing.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 one the existing connection is left alone.+ if db_in:+ existing = await _mcp_migrate(org, hid0, existing) or existing+ await _hosted_db_attach(org, hid0, existing, decl, checked, db_in.sample_rows)+ existing = await _vertex_get(hid0) or existing+ return {"kit": kit_id, "harnessId": hid0,+ "route": (kit.get("app") or {}).get("route") or "", "created": False,+ "harness": _harness_out(existing)}spec = kit.get("harness") or {}# An explicit choice from the launch dialog wins; no choice means take the recommendation.@@ -7816,6 +8121,7 @@ async def launch_kit(kit_id: str, request: Request, body_in: KitLaunchBody | Nonskills=_kit_skills(kit),mcp_servers=spec.get("mcp_servers") or [],disabled_tools=spec.get("disabled_tools") or [])+ body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)body.skills = await _skills_prepare(body.skills)hid = _rid("chrn")now = str(int(time.time() * 1000))@@ -7826,11 +8132,14 @@ 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+ v = {"id": hid, **props}+ if db_in:+ await _hosted_db_attach(org, hid, v, decl, checked, db_in.sample_rows)+ v = await _vertex_get(hid) or vprint(f"[kits] launched {kit_id} -> {hid}", flush=True)return {"kit": kit_id, "harnessId": hid,"route": (kit.get("app") or {}).get("route") or "", "created": True,- "dataSource": _ds_public(rec)}+ "harness": _harness_out(v)}@app.get("/v1/harnesses")@@ -7843,7 +8152,7 @@ async def list_harnesses_public(request: Request) -> dict:# org — narrowed to its workspace when the key is workspace-scoped — exactly like the# console, so both surfaces always agree.rows = await _vg_list_by_org("Harness", org)- items = [_harness_out(r) for r in rows+ items = [_harness_out(await _mcp_migrate(org, str(r.get("id") or ""), r)) for r in rowsif str(r.get("deleted")) not in ("1", "true", "True")]ws = str(p.get("workspace") or "")if ws:@@ -7858,7 +8167,7 @@ async def get_harness_public(hid: str, request: Request) -> dict: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 _harness_out(v)+ return _harness_out(await _mcp_migrate(org, hid, v))@app.get("/v1/bases")@@ -7956,8 +8265,12 @@ async def update_harness_public(hid: str, body: HarnessBody, request: 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")+ v = await _mcp_migrate(org, hid, v)+ body.mcp_servers = _mcp_servers_prepare(body.mcp_servers)body.skills = await _skills_prepare(body.skills)await _vg_upsert("Harness", hid, {**_harness_props(body), "updated_at": str(int(time.time() * 1000))})+ # AFTER the write: see update_harness.+ await _hosted_scrub_removed(org, hid, _mcp_list(v), body.mcp_servers)return _harness_out(await _vertex_get(hid) or {"id": hid})@@ -7967,6 +8280,8 @@ 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+ v = await _mcp_migrate(org, hid, v)await _vg_upsert("Harness", hid, {"deleted": "1"})+ # a deleted agent must not still be holding a database password+ await _hosted_scrub_removed(org, hid, _mcp_list(v), [])return {"id": hid, "deleted": True}diff --git a/gateway/sql_plane.py b/gateway/sql_plane.pyindex c94ac795..7d8609be 100644--- a/gateway/sql_plane.py+++ b/gateway/sql_plane.py@@ -2,16 +2,18 @@Two callers, one engine, one place the credential is resolved:- * the `sql` MCP tool, so an agent can explore a schema and test a query while it designs a- dashboard;- * `POST /v1/sql/query`, which a dashboard app calls to refresh its panels when someone opens it.+ * the `database` MCP server this gateway hosts, so an agent can explore a schema and test a+ query while it designs a dashboard;+ * `POST /v1/harnesses/{id}/servers/{sid}/query`, which a dashboard app calls to refresh its+ panels when someone opens it.-The second is why this is not simply an MCP server. Opening a dashboard must re-run its queries-without spending an agent turn — a turn per panel per page-load is both slow and billed. Both-paths land here, so the read-only gate and the row cap cannot be true of one and not the other.+The second is why the MCP server is not the whole story. Opening a dashboard must re-run its+queries without spending an agent turn — a turn per panel per page-load is both slow and billed.+Both paths land here, so the read-only gate and the row cap cannot be true of one and not the+other.WHAT NEVER LEAVES THIS PROCESS. The connection string is resolved from the secret store inside-the gateway. The runner never receives it (an agent gets a `datasource` name, never a DSN), and+the gateway. The runner never receives it (an agent gets a per-turn capability, never a DSN), andneither does the browser. That is the same shape MCP bearer tokens already use: config stores`vault:<ref>`, the live value is fetched at the moment of use.diff --git a/gateway/tests/test_database_mcp.py b/gateway/tests/test_database_mcp.pynew file mode 100644index 00000000..071077d1--- /dev/null+++ b/gateway/tests/test_database_mcp.py@@ -0,0 +1,980 @@+"""A database as an ORDINARY MCP server on a harness — the entry, the agent's tool, the app's+data plane, 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 entry 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+import time+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 — and+ # so it is an address this gateway recognises as its own.+ "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]"}++MCP_URL = "https://gateway.example/v1/mcp/database"+ENTRY_ID = "mcp.database"++# The kit that connects one. Connecting a database is something the kit that reads one drives,+# so every attach in this file goes through launch — there is no other way in.+_KIT = {"id": "dash", "title": "Dashboards", "app": {"route": "/kits/dash"},+ "harness": {"name": "Dashboards",+ "mcp_servers": [],+ "launch": {"database": {"engines": ["postgres", "mysql"],+ "name": "database", "id": ENTRY_ID}},+ "recommended": [{"base": "claude-code", "model": "claude-opus-5"}]}}+++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 kit(monkeypatch):+ """This kit, with a fresh id per test so launch's idempotence isn't a shared fixture."""+ kid = f"dash{int(time.time() * 1e6) % 10_000_000}"+ monkeypatch.setattr(app, "_kits", lambda: {kid: {**_KIT, "id": kid}})+ return kid+++def harness(api, kit):+ """A launched-but-unconnected harness of a kit that reads no database."""+ r = api.post("/v1/harnesses", json={"name": "Dashboard", "base": "claude-code"})+ assert r.status_code == 200, r.text+ return r.json()["id"]+++def _attach(api, kit, dsn=PG_DSN, engine="postgres", sample_rows=True):+ """Connect a database the only way there is: launch the kit that reads one."""+ r = api.post(f"/v1/kits/{kit}/launch",+ json={"database": {"engine": engine, "connection_string": dsn,+ "sample_rows": sample_rows}})+ assert r.status_code == 200, r.text+ return r.json()+++def connected(api, kit):+ """A harness with a database connected, and the kit that connected it."""+ return _attach(api, kit)["harnessId"]+++def _db_row(harness_out: dict) -> dict | None:+ """The database entry in a harness's own list of servers, found by its id — there is no field+ that says which one it is, and that is the point."""+ return next((s for s in harness_out.get("mcpServers") or []+ if s.get("id") == ENTRY_ID), None)+++def _vertex(hid: str) -> dict:+ return asyncio.run(app.BACKING.graph.get(hid, label="Harness"))+++def _stored(hid: str) -> list[dict]:+ return json.loads(_vertex(hid).get("mcp_servers") or "[]")+++def _key(hid: str) -> str:+ """The record key the harness's database entry references."""+ return app._vault_key(next(s for s in _stored(hid) if s.get("id") == ENTRY_ID)["auth"])+++def _record(hid: str) -> dict | None:+ return asyncio.run(app._hosted_record(ORG, _key(hid)))+++def _save_config(api, hid: str, servers: list[dict], name="Dashboard"):+ """What the console does when someone presses Save: a whole-config PUT."""+ return api.put(f"/v1/harnesses/{hid}",+ json={"name": name, "base": "claude-code", "mcp_servers": servers})+++def _entry_of(hid: str) -> dict:+ return next(s for s in _stored(hid) if s.get("id") == ENTRY_ID)+++def _make_legacy(hid: str, *, shape: int) -> str:+ """Rewrite a connected harness into an earlier shape, and return the old secret key.++ Shape 0 is what every deployed customer's vertex looks like the moment this build ships: the+ record on its own `datasource` prop, nothing in mcp_servers. Shape 1 is the refactor this+ replaces: an mcp_servers entry carrying `managed` and `config`. Both hold a BARE DSN at+ harness-ds-<hid-safe>.+ """+ rec = _record(hid)+ old_key = "harness-ds-" + hid.lower().replace("_", "-")+ cfg = {"engine": rec["engine"], "secret": f"vault:{old_key}", "host": rec["host"],+ "database": rec["database"], "sample_rows": rec["sample_rows"],+ "updated_at": rec["updated_at"]}+ tenant = app._tenants_for(ORG)[0]+ asyncio.run(app.BACKING.secrets.put(tenant, old_key, rec["dsn"], require_encryption=True))+ asyncio.run(app.BACKING.secrets.put(tenant, _key(hid), "", require_encryption=True))+ if shape == 0:+ asyncio.run(app._vg_upsert("Harness", hid,+ {"datasource": json.dumps(cfg), "mcp_servers": "[]"}))+ else:+ entry = {"id": ENTRY_ID, "name": "database", "enabled": True,+ "managed": "database", "config": cfg}+ asyncio.run(app._vg_upsert("Harness", hid,+ {"datasource": "", "mcp_servers": json.dumps([entry])}))+ return old_key+++# ── the entry, and where the credential is not ───────────────────────────────────++def test_connecting_returns_the_harness_and_never_the_credential(api, kit):+ row = _db_row(_attach(api, kit)["harness"])+ # What a person needs to recognise the server they connected…+ assert row["name"] == "database" and row["enabled"] is True+ assert row["url"] == MCP_URL and row["transport"] == "http"+ # …and nothing else. No user, no password, no host, no database name, no engine.+ body = _seen[-1]+ assert PASSWORD not in body and "postgres:" not in body+ assert "localhost:55432" not in body and "shop" not in body+++def test_the_entry_carries_a_reference_and_not_a_connection_string(api, kit, harness):+ """Read the stored vertex directly: this is the shape a graph dump would show."""+ hid = _attach(api, kit)["harnessId"]+ entry = _entry_of(hid)+ assert entry["auth"].startswith("vault:" + app._HOSTED_SECRET_PREFIX)+ assert PASSWORD not in json.dumps(entry)+ assert PASSWORD not in json.dumps(_vertex(hid))++ # THE WHOLE POINT, asserted: its key set is a third-party entry's key set. Nothing stored+ # distinguishes them, so nothing can branch on the difference.+ assert _save_config(api, harness, [{"id": "mcp.remote", "name": "remote",+ "url": "https://mcp.example.com/mcp",+ "transport": "http", "auth": "vault:harness-mcp-theirs",+ "enabled": True}]).status_code == 200+ assert set(entry) == set(_stored(harness)[0]) == {"id", "name", "url", "transport",+ "auth", "enabled"}+++def test_the_whole_connection_record_is_encrypted_on_disk(api, kit):+ hid = _attach(api, kit)["harnessId"]+ files = list(Path(_DATA, "secrets").rglob(_key(hid)))+ assert files, "the record was not written to the secret store"+ raw = files[0].read_text()+ assert raw.startswith("hrenc1:")+ assert PASSWORD not in raw and "localhost:55432" not in raw and "shop" not in raw+ # And NONE of it is on the vertex — host and database used to sit there in plaintext.+ v = json.dumps(_vertex(hid))+ assert "localhost:55432" not in v and "shop" not in v+++def test_a_harness_lists_its_database_and_a_fresh_one_lists_none(api, kit, harness):+ assert _db_row(api.get(f"/v1/harnesses/{harness}").json()) is None+ hid = _attach(api, kit, MYSQL_DSN, engine="mysql", sample_rows=False)["harnessId"]+ row = _db_row(api.get(f"/v1/harnesses/{hid}").json())+ assert row["url"] == MCP_URL+ # The harness read says nothing about WHICH database. The server that owns the connection is+ # the one that names it.+ got = api.get(f"/v1/harnesses/{hid}/servers/{ENTRY_ID}").json()+ assert got["connection"] == {"engine": "mysql", "host": "localhost:33306",+ "database": "shop", "sampleRows": False}+ assert got["id"] == ENTRY_ID and got["name"] == "database" and got["enabled"] is True+++def test_removing_the_entry_by_saving_the_configuration_scrubs_its_record(api, connected):+ """There is no keep-if-omitted exemption: an entry the caller did not send is gone, and the+ record behind it is scrubbed rather than orphaned."""+ key = _key(connected)+ r = _save_config(api, connected, [])+ assert r.status_code == 200 and _db_row(r.json()) is None+ assert _db_row(api.get(f"/v1/harnesses/{connected}").json()) is None+ assert not asyncio.run(app.BACKING.secrets.get(app._tenants_for(ORG)[0], key))+ # And the queries stop working, rather than working against a database nobody thinks is+ # connected any more.+ q = api.post(f"/v1/harnesses/{connected}/servers/{ENTRY_ID}/query", json={"sql": "SELECT 1"})+ assert q.status_code == 404 and q.json()["error"]["code"] == "database_not_connected"+++def test_a_record_whose_entry_is_gone_is_not_left_on_disk(api, connected):+ """Not only when the whole list is emptied: the scrub is driven off which records the entries+ still reference, so dropping one entry among several scrubs exactly that one."""+ key = _key(connected)+ remote = {"id": "mcp.remote", "name": "remote", "url": "https://mcp.example/mcp",+ "transport": "http", "auth": "vault:harness-mcp-theirs", "enabled": True}+ assert _save_config(api, connected, [remote]).status_code == 200+ assert _stored(connected) == [remote], "the surviving entry was disturbed"+ assert not asyncio.run(app.BACKING.secrets.get(app._tenants_for(ORG)[0], key))++[email protected]("how", ["save", "delete"])+def test_one_harness_cannot_scrub_another_harnesss_record(api, connected, harness, how):+ """`auth` is client-writable and harness ids are public, so anyone may name another agent's+ record on an entry of their own. Removing that entry — or deleting the whole harness — must+ not disconnect a database they were never given: the read is refused by the record naming its+ harness, and so is the scrub."""+ key = _key(connected)+ assert _save_config(api, harness, [{"id": "mcp.x", "name": "x",+ "url": "https://evil.example/mcp", "transport": "http",+ "auth": f"vault:{key}", "enabled": True}],+ name="borrower").status_code == 200+ if how == "save":+ assert _save_config(api, harness, [], name="borrower").status_code == 200+ else:+ assert api.delete(f"/v1/harnesses/{harness}").json()["deleted"] is True++ assert asyncio.run(app.BACKING.secrets.get(app._tenants_for(ORG)[0], key)), \+ "another harness's write destroyed this connection"+ assert _record(connected)["dsn"] == PG_DSN+ # And the harness that actually owns it still resolves its own server.+ assert api.get(f"/v1/harnesses/{connected}/servers/{ENTRY_ID}"+ ).json()["connection"]["database"] == "shop"+++def test_renaming_an_entry_is_not_a_removal(api, connected):+ """The record belongs to the entry that references it, not to an id or a name. Renaming+ either must keep the server working rather than quietly scrub what it reads."""+ key = _key(connected)+ assert _save_config(api, connected, [{**_entry_of(connected), "id": "mcp.other",+ "name": "shop"}]).status_code == 200+ assert asyncio.run(app.BACKING.secrets.get(app._tenants_for(ORG)[0], key))+ got = api.get(f"/v1/harnesses/{connected}/servers/mcp.other").json()+ assert got["name"] == "shop" and got["connection"]["database"] == "shop"+++def test_deleting_the_harness_does_not_leave_the_credential_behind(api, connected):+ """The most decisive thing the UI offers must not leave a production password on disk."""+ key = _key(connected)+ stored = next(iter(Path(_DATA, "secrets").rglob(key)))+ assert PG_DSN == (_record(connected) or {})["dsn"]++ assert api.delete(f"/v1/harnesses/{connected}").json()["deleted"] is True+ # The file may remain (the store has no delete); what it holds must not.+ assert not asyncio.run(app.BACKING.secrets.get(app._tenants_for(ORG)[0], key))+ assert PASSWORD not in stored.read_text()+++def test_another_org_cannot_see_or_use_a_database(client, api, connected):+ other = {**HEADERS, "x-harness-org": "someone-else"}+ for r in (client.get(f"/v1/harnesses/{connected}", headers=other),+ client.get(f"/v1/harnesses/{connected}/servers/{ENTRY_ID}", headers=other),+ client.post(f"/v1/harnesses/{connected}/servers/{ENTRY_ID}/query", headers=other,+ json={"sql": "SELECT 1"}),+ client.get(f"/v1/harnesses/{connected}/servers/{ENTRY_ID}/schema", headers=other)):+ _seen.append(r.text)+ assert r.status_code == 404 and r.json()["error"]["code"] == "harness_not_found"+ # And the entry is still there for the org that owns it — a refused read is not a delete.+ assert _db_row(api.get(f"/v1/harnesses/{connected}").json())+++# ── what saving the configuration may and may not do ─────────────────────────────++def test_a_client_may_rename_and_disable_the_database(api, connected):+ """An ordinary entry, edited the ordinary way."""+ r = _save_config(api, connected, [{**_entry_of(connected), "name": "shop db",+ "enabled": False}])+ assert r.status_code == 200, r.text+ row = _db_row(r.json())+ assert row["name"] == "shop db" and row["enabled"] is False+ # The connection itself is untouched by a rename.+ assert api.get(f"/v1/harnesses/{connected}/servers/{ENTRY_ID}").json()["connection"]["database"] == "shop"+++def test_saving_the_configuration_cannot_change_what_is_connected(api, connected):+ """The connection is not on the entry, so there is nothing on it to rewrite. A caller who+ invents fields naming another engine and another host changes exactly nothing."""+ assert _save_config(api, connected, [{**_entry_of(connected), "managed": "database",+ "config": {"engine": "mysql", "host": "evil:3306",+ "database": "theirs", "sample_rows": 5000,+ "secret": "vault:harness-mcp-mine"}}]).status_code == 200+ assert api.get(f"/v1/harnesses/{connected}/servers/{ENTRY_ID}").json()["connection"] == {+ "engine": "postgres", "host": "localhost:55432", "database": "shop", "sampleRows": True}+ assert _record(connected)["dsn"] == PG_DSN+++def test_the_secret_route_cannot_write_into_the_hosted_namespace(api):+ """The namespace argument, checked: a caller-chosen ref is prefixed, so no ref reaches the+ keys a hosted server's records live under."""+ r = api.put("/v1/mcp-secrets/hosted-chrn-anything-mcp-database", json={"token": "t"})+ assert r.status_code == 200+ assert not r.json()["ref"][len("vault:"):].startswith(app._HOSTED_SECRET_PREFIX)+++def test_two_servers_cannot_share_a_name(api, connected):+ """Sanitised, `my server` and `my-server` are one server to every backend: the runner keys+ them by name and the last wins, so half the tool list would vanish with no error."""+ r = _save_config(api, connected, [{"name": "my server", "url": "https://a.example/mcp"},+ {"name": "my-server", "url": "https://b.example/mcp"}])+ assert r.status_code == 400 and r.json()["error"]["code"] == "duplicate_server_name"+ # Including against the database, which is a server with a name like any other.+ clash = _save_config(api, connected, [_entry_of(connected),+ {"name": "database", "url": "https://c.example/mcp"}])+ assert clash.status_code == 400 and clash.json()["error"]["code"] == "duplicate_server_name"+++def test_a_remote_server_still_needs_a_url(api, harness):+ r = _save_config(api, harness, [{"name": "nowhere"}])+ assert r.status_code == 400 and r.json()["error"]["code"] == "invalid_mcp_server"+++# ── what a bad connection string gets told ───────────────────────────────────────++def _launch(api, kit, engine, conn):+ return api.post(f"/v1/kits/{kit}/launch",+ json={"database": {"engine": engine, "connection_string": conn}})+++def test_an_unsupported_engine_says_what_is_supported(api, kit):+ r = _launch(api, kit, "snowflake", "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, kit):+ r = _launch(api, kit, "postgres", 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, kit, 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 = _launch(api, kit, "postgres", 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/mcp-test/database", 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, kit):+ r = _launch(api, kit, "postgres", "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, kit, 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 = _launch(api, kit, "postgres", 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/mcp-test/database", 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"]+ # The org-scoped twin exists so a console testing either kind of server has one auth shape.+ same = api.post(f"/v1/orgs/{ORG}/mcp-test/database",+ json={"engine": "postgres", "connection_string": PG_DSN})+ assert same.status_code == 200 and same.json()["tables"] == body["tables"]+++@needs_pg+def test_a_wrong_password_is_a_usable_message_and_not_a_stack_trace(api):+ r = api.post("/v1/mcp-test/database",+ 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/mcp-test/database",+ 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 ──────────────────────++def _query(api, hid, sql, **kw):+ return api.post(f"/v1/harnesses/{hid}/servers/{ENTRY_ID}/query", json={"sql": sql, **kw})+++@needs_pg+def test_a_panel_refresh_returns_columns_and_rows(api, connected):+ r = _query(api, connected,+ "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, kit):+ hid = _attach(api, kit, MYSQL_DSN, engine="mysql")["harnessId"]+ r = _query(api, hid, "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, connected):+ r = _query(api, connected, "DELETE FROM orders")+ assert r.status_code == 400 and r.json()["error"]["code"] == "sql_refused"+ # The rows are still there.+ n = _query(api, connected, "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, connected):+ r = _query(api, connected, "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, connected):+ body = _query(api, connected, "SELECT * FROM orders", max_rows=2).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, connected):+ r = _query(api, connected, "SELECT * FROM orders", max_rows=10_000_000)+ assert r.json()["limit_applied"] == sql_plane.DEFAULT_MAX_ROWS+++@needs_pg+def test_disabling_the_database_does_not_stop_a_dashboard_refreshing(api, connected):+ """`enabled` decides what the AGENT is handed for a turn. A dashboard refresh is not a turn:+ it is the app's own data plane, authorised by the caller's own key."""+ assert _save_config(api, connected,+ [{**_entry_of(connected), "enabled": False}]).status_code == 200+ r = _query(api, connected, "SELECT 1 AS one")+ assert r.status_code == 200 and r.json()["columns"] == ["one"]+ assert api.get(f"/v1/harnesses/{connected}/servers/{ENTRY_ID}/schema").status_code == 200+ assert api.get(f"/v1/harnesses/{connected}/servers/{ENTRY_ID}").json()["enabled"] is False+++# ── the schema, and the sample-rows switch ───────────────────────────────────────++@needs_pg+def test_sampling_on_shows_rows_and_sampling_off_shows_none(api, kit):+ hid = _attach(api, kit, sample_rows=True)["harnessId"]+ on = api.get(f"/v1/harnesses/{hid}/servers/{ENTRY_ID}/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"}++ _attach(api, kit, sample_rows=False)+ off = api.get(f"/v1/harnesses/{hid}/servers/{ENTRY_ID}/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"]]+++def test_sample_rows_is_stored_as_a_count_and_not_a_flag(api, kit):+ """The one line that decides how much data leaves the customer's database."""+ hid = _attach(api, kit, sample_rows=True)["harnessId"]+ assert _record(hid)["sample_rows"] == app._DB_SAMPLE_ROWS+ _attach(api, kit, sample_rows=False)+ assert _record(hid)["sample_rows"] == 0+++# ── 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/database", json=body,+ headers={"authorization": f"Bearer {token}"} if token else {})+ _seen.append(r.text)+ return r+++def _cred(hid: str, sid: str = "sess1") -> str:+ return app._mint_hosted_cred(hid, sid, _key(hid))+++def _refused(r) -> bool:+ res = r.json()["result"]+ return res["isError"] is True and "No database is connected" in res["content"][0]["text"]+++def test_the_tool_endpoint_refuses_without_a_valid_credential(client, connected):+ 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 = _cred(connected)+ forged = good[:-1] + ("a" if good[-1] != "a" else "b")+ assert _rpc(client, forged, "tools/list").status_code == 401+++def test_an_expired_credential_is_refused(client, connected, monkeypatch):+ """"and expires" is half the promise. A token minted six hours ago must not work now."""+ monkeypatch.setattr(app, "_BROKER_TTL_S", -1)+ stale = _cred(connected)+ monkeypatch.undo()+ assert _rpc(client, stale, "tools/list").status_code == 401+++def test_a_turn_credential_is_scoped_to_one_harness(client, api, connected):+ """The token IS the authorisation. One minted for another harness must not read this one."""+ other = api.post("/v1/harnesses", json={"name": "Other", "base": "claude-code"}).json()["id"]+ tok = app._mint_hosted_cred(other, "sess1", _key(connected))+ assert _refused(_rpc(client, tok, "tools/call",+ {"name": "query", "arguments": {"sql": "SELECT 1"}}))+++def test_a_credential_naming_another_harnesss_record_is_refused(client, api, kit, connected):+ """The binding that replaces a key derived from the harness id: `auth` is a client-writable+ field on an ordinary entry, so a caller can write someone else's ref onto their own entry.+ The record names its harness, and the endpoint refuses a mismatch."""+ thief = api.post("/v1/harnesses", json={"name": "Thief", "base": "claude-code"}).json()["id"]+ stolen = _key(connected)+ assert _save_config(api, thief, [{"id": ENTRY_ID, "name": "database", "url": MCP_URL,+ "transport": "http", "auth": f"vault:{stolen}",+ "enabled": True}]).status_code == 200+ tok = app._mint_hosted_cred(thief, "sess1", stolen)+ assert _refused(_rpc(client, tok, "tools/call",+ {"name": "query", "arguments": {"sql": "SELECT 1"}}))+ # And the app's data plane, which is a different authorization path to the same record.+ for r in (api.get(f"/v1/harnesses/{thief}/servers/{ENTRY_ID}"),+ api.post(f"/v1/harnesses/{thief}/servers/{ENTRY_ID}/query", json={"sql": "SELECT 1"})):+ assert r.status_code == 404 and r.json()["error"]["code"] == "database_not_connected"+++def test_a_deleted_harness_stops_answering_its_own_turn_credential(client, api, connected):+ """A credential is live for hours; deleting the agent must end its database access now."""+ tok = _cred(connected)+ api.delete(f"/v1/harnesses/{connected}")+ assert _refused(_rpc(client, tok, "tools/call",+ {"name": "query", "arguments": {"sql": "SELECT 1"}}))+++def test_a_disabled_database_is_not_handed_to_the_turn_and_its_endpoint_refuses(client, api, connected):+ """A disabled entry MUST NOT be contacted — and a token minted before it was switched off is+ valid for another six hours, so the endpoint has to refuse too."""+ tok = _cred(connected)+ assert _save_config(api, connected,+ [{**_entry_of(connected), "enabled": False}]).status_code == 200++ v = asyncio.run(app._harness_vertex(connected))+ mcp, *_ = asyncio.run(app._harness_plugins(connected, ORG, hv=v, sid="sess1"))+ assert [m for m in mcp if m["name"] == "database"] == []++ assert _refused(_rpc(client, tok, "tools/call",+ {"name": "query", "arguments": {"sql": "SELECT 1"}}))+++def test_the_tool_list_is_the_two_things_an_agent_needs(client, connected):+ r = _rpc(client, _cred(connected), "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, connected):+ tok = _cred(connected)+ 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/database", 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, kit):+ hid = _attach(api, kit, sample_rows=True)["harnessId"]+ tok = _cred(hid)++ 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"}+ # And it is told WHICH database it is reading, from the record that owns the connection —+ # the kit's skill tells it to copy this into the dashboard it writes.+ assert schema["connection"] == {"engine": "postgres", "host": "localhost:55432",+ "database": "shop", "sampleRows": True}++ 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, kit):+ hid = _attach(api, kit, sample_rows=False)["harnessId"]+ schema = json.loads(_rpc(client, _cred(hid), "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, connected):+ tok = _cred(connected)+ 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, connected):+ tok = _cred(connected)+ 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 _plugins(hid: str, sid: str = "sess-42") -> list[dict]:+ v = asyncio.run(app._harness_vertex(hid))+ mcp, *_ = asyncio.run(app._harness_plugins(hid, ORG, hv=v, sid=sid))+ return mcp+++def test_a_connected_harness_hands_its_turn_a_database_tool_and_no_credential(connected):+ mcp = _plugins(connected)+ entry = next(m for m in mcp if m["name"] == "database")+ assert entry["url"] == MCP_URL+ # What the sandbox receives is a token, and it resolves back to this harness, this session and+ # this record.+ assert app._verify_hosted_cred(entry["auth"]) == (connected, "sess-42", _key(connected))+++def test_no_turn_of_a_connected_harness_carries_a_connection_string(api, connected):+ """The whole plugin list, not one entry: this is the line that says a DSN never reaches a+ sandbox, whatever else the harness has on it."""+ assert _save_config(api, connected,+ [_entry_of(connected),+ {"id": "mcp.remote", "name": "remote", "url": "https://mcp.example/mcp",+ "transport": "http", "auth": "vault:harness-mcp-theirs",+ "enabled": True}]).status_code == 200+ out = json.dumps(_plugins(connected))+ assert PASSWORD not in out and "localhost:55432" not in out+++def test_a_hosted_entry_pointed_elsewhere_hands_that_server_nothing(api, connected):+ """Editing a harness is a strictly weaker permission than knowing the database password, so+ pointing a hosted entry's url at somewhere else must buy exactly nothing."""+ assert _save_config(api, connected,+ [{**_entry_of(connected), "url": "https://evil.example/mcp"}]).status_code == 200+ entry = next(m for m in _plugins(connected) if m["url"] == "https://evil.example/mcp")+ assert "auth" not in entry+ assert PASSWORD not in json.dumps(entry)+++def test_a_remote_entry_naming_a_hosted_record_resolves_to_nothing(connected):+ """The refusal at the funnel every outbound credential passes through, so it holds for callers+ that do not exist yet."""+ assert asyncio.run(app._resolve_mcp_auth(ORG, f"vault:{_key(connected)}")) == ""+++def test_a_url_that_only_looks_like_ours_is_not_treated_as_ours(api, connected):+ """`/v1/mcp/../../v1/admin` starts with our prefix and is a different endpoint the moment any+ client normalises it. Hosted is what earns a minted credential and a pass on the SSRF rule;+ neither is owed to a string that merely begins the right way."""+ for path in ("/v1/mcp/../../v1/admin", "/v1/mcp/database/../../admin", "/v1/mcp/"):+ assert app._hosted_mcp_path("https://gateway.example" + path) is None, path+ assert app._hosted_mcp_path(MCP_URL) == "/v1/mcp/database"++ assert _save_config(api, connected, [{**_entry_of(connected),+ "url": "https://gateway.example/v1/mcp/../../v1/admin"}+ ]).status_code == 200+ entry = next(m for m in _plugins(connected) if "admin" in m["url"])+ assert "auth" not in entry, "a traversal url was handed a minted credential"+++def test_an_entry_here_that_names_no_record_is_not_offered(api, harness):+ """A url of ours with a third-party auth is not a server we can serve: minting for it would+ hand out a capability to a record this harness does not have."""+ assert _save_config(api, harness, [{"id": "mcp.fake", "name": "database", "url": MCP_URL,+ "transport": "http", "auth": "vault:harness-mcp-theirs",+ "enabled": True}]).status_code == 200+ assert _plugins(harness) == []+++def test_a_harness_with_no_database_hands_its_turn_no_database_tool(harness):+ assert [m for m in _plugins(harness) if m["name"] == "database"] == []+++def test_a_hosted_token_is_not_a_model_broker_token_and_the_reverse(connected):+ """Different audiences, so one lifted out of a sandbox cannot be spent at the other."""+ db_tok = _cred(connected)+ llm_tok = app._mint_turn_cred("sess1", "anthropic")+ assert app._verify_turn_cred(db_tok) is None+ assert app._verify_hosted_cred(llm_tok) is None+++# ── a harness connected before the database was an ordinary MCP server ───────────+[email protected]("shape", [0, 1])+def test_a_harness_connected_under_the_old_shape_still_hands_its_turn_the_tool(api, kit, shape):+ """Converted on the first read that needs it, so an already-connected customer has no+ downtime and nobody has to remember to run anything."""+ hid = _attach(api, kit)["harnessId"]+ _make_legacy(hid, shape=shape)++ entry = next(m for m in _plugins(hid) if m["name"] == "database")+ assert entry["url"] == MCP_URL+ assert app._verify_hosted_cred(entry["auth"]) == (hid, "sess-42", _key(hid))+ # And the console lists it, as an entry indistinguishable from any other server.+ row = _db_row(api.get(f"/v1/harnesses/{hid}").json())+ assert set(row) == {"id", "name", "url", "transport", "auth", "enabled"}+++@needs_pg[email protected]("shape", [0, 1])+def test_a_harness_connected_under_the_old_shape_still_refreshes_its_dashboard(api, kit, shape):+ hid = _attach(api, kit)["harnessId"]+ _make_legacy(hid, shape=shape)+ r = _query(api, hid, "SELECT 1 AS one")+ assert r.status_code == 200 and r.json()["columns"] == ["one"]+++def test_the_old_record_is_dropped_the_first_time_the_harness_is_read(api, kit, capsys):+ hid = _attach(api, kit)["harnessId"]+ _make_legacy(hid, shape=0)+ capsys.readouterr()++ assert api.get(f"/v1/harnesses/{hid}").status_code == 200+ v = _vertex(hid)+ assert not v.get("datasource"), "the old record survived a read"+ assert _entry_of(hid)["auth"].startswith("vault:" + app._HOSTED_SECRET_PREFIX)+ assert "[migrate]" in capsys.readouterr().out, "a drain nobody can count is a drain nobody sees"+++def test_a_harness_migrated_on_a_read_is_migrated_only_once(api, kit, capsys):+ hid = _attach(api, kit)["harnessId"]+ _make_legacy(hid, shape=1)+ capsys.readouterr()++ api.get(f"/v1/harnesses/{hid}")+ assert "[migrate]" in capsys.readouterr().out+ api.get(f"/v1/harnesses/{hid}")+ assert "[migrate]" not in capsys.readouterr().out+++def test_migration_moves_the_credential_without_reading_it_wrong(api, kit):+ """The payload changes — a bare string becomes a JSON record at a new key — so this is a+ converter. What must not change is the connection string itself, and the old key must not be+ left holding it."""+ hid = _attach(api, kit)["harnessId"]+ old_key = _make_legacy(hid, shape=0)++ assert api.get(f"/v1/harnesses/{hid}").status_code == 200+ rec = _record(hid)+ assert rec["dsn"] == PG_DSN and rec["harness"] == hid and rec["server"] == "database"+ assert rec["host"] == "localhost:55432" and rec["database"] == "shop"+ assert not asyncio.run(app.BACKING.secrets.get(app._tenants_for(ORG)[0], old_key))+++def test_disconnecting_a_legacy_harness_scrubs_the_credential(api, kit):+ hid = _attach(api, kit)["harnessId"]+ old_key = _make_legacy(hid, shape=1)+ r = _save_config(api, hid, [])+ assert r.status_code == 200 and _db_row(r.json()) is None+ assert not _vertex(hid).get("datasource")+ tenant = app._tenants_for(ORG)[0]+ assert not asyncio.run(app.BACKING.secrets.get(tenant, old_key))+ assert not asyncio.run(app.BACKING.secrets.get(+ tenant, app._hosted_secret_key(hid, ENTRY_ID)))+++# ── launching a kit with a database attached ─────────────────────────────────────++def test_launch_accepts_a_connection_and_a_bad_one_provisions_nothing(api, kit):+ bad = api.post(f"/v1/kits/{kit}/launch",+ json={"database": {"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"] == kit)["launched"] is False++ ok = api.post(f"/v1/kits/{kit}/launch",+ json={"database": {"engine": "postgres", "connection_string": PG_DSN,+ "sample_rows": False}})+ assert ok.status_code == 200, ok.text+ assert ok.json()["created"] is True+ hid = ok.json()["harnessId"]+ assert api.get(f"/v1/harnesses/{hid}/servers/{ENTRY_ID}").json()["connection"] == {+ "engine": "postgres", "host": "localhost:55432", "database": "shop", "sampleRows": False}++ # Launched twice: the same Harness, the connection typed the second time applied to it rather+ # than silently dropped, and no orphaned record left behind by the replacement.+ key_before = _key(hid)+ again = api.post(f"/v1/kits/{kit}/launch",+ json={"database": {"engine": "mysql", "connection_string": MYSQL_DSN}})+ assert again.json()["harnessId"] == hid and again.json()["created"] is False+ assert _key(hid) == key_before+ assert api.get(f"/v1/harnesses/{hid}/servers/{ENTRY_ID}").json()["connection"]["engine"] == "mysql"++ listed = next(k for k in api.get("/v1/kits").json()["kits"] if k["id"] == kit)+ assert listed["database"] == {"engines": ["postgres", "mysql"]}+ # What a launched kit is pointed AT has no successor here: nobody reads their data on this+ # page, and naming it would put connection state back on a harness read.+ assert "connected" not in json.dumps(listed)+++def test_a_kit_that_declares_a_database_will_not_launch_without_one(api, kit):+ r = api.post(f"/v1/kits/{kit}/launch", json={})+ assert r.status_code == 400 and r.json()["error"]["code"] == "connection_required"+ assert next(k for k in api.get("/v1/kits").json()["kits"] if k["id"] == kit)["launched"] is False+++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"}}})+ listed = next(k for k in api.get("/v1/kits").json()["kits"] if k["id"] == "slides")+ assert "database" not in listed+ # …and a connection string offered to it is named rather than quietly dropped.+ r = api.post("/v1/kits/slides/launch",+ json={"database": {"engine": "postgres", "connection_string": PG_DSN}})+ assert r.status_code == 400 and r.json()["error"]["code"] == "connection_not_used"+++def test_a_launched_kits_ordinary_servers_are_stored_verbatim(api, monkeypatch):+ """`harness.mcp_servers` is now exclusively ordinary servers and passes straight through."""+ remote = {"id": "mcp.sis", "name": "sis", "url": "https://sis.example/mcp",+ "transport": "http", "enabled": True}+ monkeypatch.setattr(app, "_kits", lambda: {"k2": {"id": "k2", "title": "K2",+ "app": {"route": "/kits/k2"},+ "harness": {"name": "K2",+ "mcp_servers": [remote]}}})+ r = api.post("/v1/kits/k2/launch", json={})+ assert r.status_code == 200, r.text+ assert _stored(r.json()["harnessId"]) == [remote]+++# ── 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, kit, capsys):+ """Connect, query, fail, disconnect — then read the logs the container would have written."""+ capsys.readouterr()+ hid = _attach(api, kit)["harnessId"]+ _query(api, hid, "SELECT 1")+ api.post("/v1/mcp-test/database",+ json={"engine": "postgres", "connection_string": f"postgresql://u:{PASSWORD}@127.0.0.1:1/x"})+ _save_config(api, hid, [])+ 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.outdiff --git a/gateway/tests/test_sql_datasource.py b/gateway/tests/test_sql_datasource.pydeleted file mode 100644index 321b2f3e..00000000--- a/gateway/tests/test_sql_datasource.py+++ /dev/null@@ -1,551 +0,0 @@-"""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_deleting_the_harness_does_not_leave_the_credential_behind(api, harness):- """The most decisive thing the UI offers must not leave a production password on disk."""- api.put(f"/v1/harnesses/{harness}/datasource",- json={"engine": "postgres", "connection_string": PG_DSN})- stored = next(iter(Path(_DATA, "secrets").rglob(app._ds_secret_key(harness))))- assert PG_DSN == asyncio.run(app.BACKING.secrets.get(app._tenants_for(ORG)[0], app._ds_secret_key(harness)))-- assert api.delete(f"/v1/harnesses/{harness}").json()["deleted"] is True- # The file may remain (the store has no delete); what it holds must not.- assert not asyncio.run(app.BACKING.secrets.get(app._tenants_for(ORG)[0], app._ds_secret_key(harness)))- assert PASSWORD not in stored.read_text()---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.outdiff --git a/ui/src/app/(app)/harnesses/[id]/page.tsx b/ui/src/app/(app)/harnesses/[id]/page.tsxindex 427b62ac..2743b4c1 100644--- a/ui/src/app/(app)/harnesses/[id]/page.tsx+++ b/ui/src/app/(app)/harnesses/[id]/page.tsx@@ -8,11 +8,11 @@ import { SkelPage } from '@/components/Skel';import { useParams, useRouter } from 'next/navigation';import {OOB, oobById, oobDefaultModel, oobModels, useModelCatalog, useBases, getCustom, saveCustom, deleteCustom, createCustom, getSkillFiles, storeMcpSecret,- modelAvailable, disconnectDatasource,- type CustomHarness, type OobHarness } from '@/lib/harness';+ modelAvailable,+ type CustomHarness, type McpServer, type OobHarness } from '@/lib/harness';import { HarnessLogo } from '@/components/HarnessLogo';import { CopyId } from '@/components/CopyId';-import { SkillEditor, McpModal, type McpServer } from '@/components/HarnessEditors';+import { SkillEditor, McpModal, McpRow } from '@/components/HarnessEditors';import { fetchTraceWindow, statsFor, p95Of, avgCreditsOf, type TraceCard } from '@/lib/revamp-data';import { SELF_HOSTED } from '@/lib/edition';@@ -60,22 +60,6 @@ export default function HarnessSettingsPage() {const models = oobModels(base);const upd = (p: Partial<CustomHarness>) => setDraft((d) => (d ? { ...d, ...p } : d));- // Detaching the database is immediate, not part of the form's Save: it is a separate route- // (the credential behind it never passes through this page), and leaving it staged would mean- // a page showing "no database" while every turn still had one.- async function disconnectDb() {- if (!draft || busy) return;- setBusy(true); setErr(null);- try {- await disconnectDatasource(draft.id);- const fresh = { ...draft, dataSource: null };- setDraft(fresh);- setSaved((s) => (s ? { ...s, dataSource: null } : s));- }- catch (e) { setErr(e instanceof Error ? e.message : String(e)); }- finally { setBusy(false); }- }-async function save() {if (!draft || busy) return;setBusy(true); setErr(null);@@ -206,28 +190,9 @@ export default function HarnessSettingsPage() {<section className="form-section"><div><h3>Tools</h3><p>Control inherited tools and add MCP servers for external capabilities.</p></div><div className="field-stack">- <div className="section-actions"><strong>{baseTools.length + (draft?.mcpServers?.length || 0) + (draft?.dataSource ? 1 : 0)} configured tools</strong>- {!readOnly && <button className="button small" type="button" onClick={() => setMcpModal({ idx: null })}><iconify-icon icon="tabler:plus"></iconify-icon>Add MCP</button>}</div>+ <div className="section-actions"><strong>{baseTools.length + (draft?.mcpServers?.length || 0)} configured tools</strong>+ {!readOnly && <button className="button small" type="button" onClick={() => setMcpModal({ idx: null })}><iconify-icon icon="tabler:plus"></iconify-icon>Add tool</button>}</div><div className="capability-list">- {/* The database, when one is connected. The gateway adds this tool per turn rather- than storing it on the config, so that connecting and disconnecting take effect- on the next turn and a stored entry can never point at a database that is gone.- The cost of that is what you are reading this comment because of: it did not- appear on the page that lists what this agent can do, so reviewing the agent- did not reveal that it can read a production database. It appears now, it says- which database, and disconnecting is here rather than somewhere else. */}- {draft?.dataSource && (- <div className="capability-row">- <span className="capability-icon"><iconify-icon icon="tabler:database"></iconify-icon></span>- <div className="capability-copy"><strong>Database</strong>- <span>Reads {draft.dataSource.database} · {draft.dataSource.host} · read-only, one SELECT at a time- {draft.dataSource.sampleRows ? ' · sees example rows' : ' · column names only, no values'}</span></div>- <div className="capability-actions">- <button className="button quiet small" type="button" disabled={readOnly || busy}- onClick={() => void disconnectDb()}>Disconnect</button>- </div>- </div>- )}{baseTools.map((t) => (<div key={t.name} className="capability-row"><span className="capability-icon"><iconify-icon icon="tabler:plug"></iconify-icon></span>@@ -241,18 +206,15 @@ export default function HarnessSettingsPage() {</div></div>))}+ {/* Every MCP server this Harness has, one row each and no exceptions — a database+ a kit connected is one of them. It has to appear here: a capability nobody can+ see on the page that lists capabilities is a capability nobody can audit, and+ reviewing an agent has to reveal that it can read a production database. */}{(draft?.mcpServers || []).map((m, idx) => (- <div key={m.id || idx} className="capability-row">- <span className="capability-icon"><iconify-icon icon="tabler:world-www"></iconify-icon></span>- <div className="capability-copy"><strong>{m.name}</strong><span>Custom MCP · {m.url || 'endpoint'}</span></div>- <div className="capability-actions">- <button className="button quiet small" type="button" onClick={() => setMcpModal({ idx })}>Edit</button>- <button className="button quiet small" type="button" onClick={() => upd({ mcpServers: (draft?.mcpServers || []).filter((_, k) => k !== idx) })}>Delete</button>- <button className="toggle-button" type="button" aria-pressed={m.enabled !== false}- onClick={() => upd({ mcpServers: (draft?.mcpServers || []).map((x, k) => (k === idx ? { ...x, enabled: !(x.enabled !== false) } : x)) })}>- {m.enabled !== false ? 'Enabled' : 'Disabled'}</button>- </div>- </div>+ <McpRow key={m.id || idx} server={m} busy={busy}+ onEdit={() => setMcpModal({ idx })}+ onDelete={() => upd({ mcpServers: (draft?.mcpServers || []).filter((_, k) => k !== idx) })}+ onToggle={() => upd({ mcpServers: (draft?.mcpServers || []).map((x, k) => (k === idx ? { ...x, enabled: !(x.enabled !== false) } : x)) })} />))}</div></div>@@ -416,11 +378,14 @@ export default function HarnessSettingsPage() {{confirmDelete && draft && (<div className="modal-backdrop"><section className="modal" role="dialog" aria-modal="true" onClick={(e) => e.stopPropagation()}>- <div className="modal-header"><div><h2>Delete {draft.name}?</h2><p>Removes this Harness configuration. Existing task history stays readable.</p></div></div>+ <div className="modal-header"><div>+ <h2>Delete {draft.name}?</h2>+ <p>Removes this Harness configuration. Existing task history stays readable.</p>+ </div></div><div className="modal-body"><div className="modal-actions"><button className="button" type="button" onClick={() => setConfirmDelete(false)}>Cancel</button>- <button className="button primary" type="button" style={{ background: 'var(--red)', borderColor: 'var(--red)' }}+ <button className="button primary" type="button" disabled={busy} style={{ background: 'var(--red)', borderColor: 'var(--red)' }}onClick={async () => { await deleteCustom(draft.id); router.push('/harnesses'); }}>Delete</button></div></div>diff --git a/ui/src/app/(app)/kits/page.tsx b/ui/src/app/(app)/kits/page.tsxindex 0e333e45..4ec5aa52 100644--- a/ui/src/app/(app)/kits/page.tsx+++ b/ui/src/app/(app)/kits/page.tsx@@ -16,12 +16,12 @@import { useCallback, useEffect, useState } from 'react';import { authHeaders } from '@/lib/chat';import { harnessFetch } from '@/lib/hfetch';+import { testDatabase } from '@/lib/harness';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;@@ -32,23 +32,13 @@ 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;+ /** Present when the kit reads a database, absent when it does not — declaring it IS the+ * requirement, so there is no separate "required" flag. `engines` narrows the picker to what+ * this kit can actually read. Nothing here describes a database already connected: which one a+ * launched kit reads is the kit app's business, and it names it in its own title bar. */+ database?: { engines: string[] };}-/** 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[] }@@ -98,7 +88,7 @@ export default function KitsPage() {window.open(route, '_blank', 'noopener,noreferrer');}- async function launch(kit: Kit, base?: string, model?: string, db?: DbDraft) {+ async function launch(kit: Kit, base?: string, model?: string, database?: 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.@@ -110,11 +100,13 @@ export default function KitsPage() {headers: authHeaders(),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 }+ // Sent only when a connection string was actually typed: launching a kit that already+ // has one, without touching this field, must leave what it reads alone. The string+ // goes straight to the server on this one request and is held nowhere else.+ ...(database?.connectionString.trim()+ ? { database: { engine: database.engine,+ connection_string: database.connectionString.trim(),+ sample_rows: database.sampleRows } }: {}),}),});@@ -212,19 +204,13 @@ 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 && (+ {/* What the kit reads, from its own declaration — not which database a launched+ one is pointed at. That belongs to the kit's app, which shows it where the+ data is actually being looked at. */}+ {k.database && (<li><iconify-icon icon="tabler:database"></iconify-icon>- Reads your {k.datasource.engines.map((e) => ENGINE_LABEL[e] || e).join(' or ')} database+ Reads your {k.database.engines.map((e) => ENGINE_LABEL[e] || e).join(' or ')} database</li>)}</ul>@@ -250,30 +236,27 @@ export default function KitsPage() {<LaunchDialogkit={picking} bases={bases} busy={busy === picking.id}onClose={() => setPicking(null)}- onLaunch={(base, model, db) => void launch(picking, base, model, db)}+ onLaunch={(base, model, database) => void launch(picking, base, model, database)}/>)}</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, db?: DbDraft) => void;+ onClose: () => void; onLaunch: (base: string, model: string, database: 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,- });+ // Sampling defaults on: the agent designs better 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.database?.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.@@ -291,15 +274,16 @@ function LaunchDialog({ kit, bases, busy, onClose, onLaunch }: {}, [onClose]);const nothingAvailable = !kit.choices.some((c) => c.available);- 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);+ // A kit that reads a database cannot be launched the first time without one — every panel it+ // builds would have nothing to read. Relaunching keeps what it already reads, so a blank field+ // is fine once it has been launched.+ const missing = Boolean(kit.database) && !kit.launched && !db.connectionString.trim();+ const canLaunch = (custom ? Boolean(cBase && cModel) : Boolean(sel)) && !missing;function go() {- const draft = hasDb ? db : undefined;- if (custom) { onLaunch(cBase, cModel, draft); return; }+ if (custom) { onLaunch(cBase, cModel, db); return; }const [base, ...rest] = sel.split('/');- onLaunch(base, rest.join('/'), draft);+ onLaunch(base, rest.join('/'), db);}return (@@ -369,7 +353,20 @@ function LaunchDialog({ kit, bases, busy, onClose, onLaunch }: {</div>)}- {kit.datasource && <DatabaseStep kit={kit} db={db} onChange={setDb} />}+ {/* The one surface that collects a connection string, and it is here because the KIT says+ it needs one — nothing about a database is special anywhere else. Relaunching with the+ field filled in is also how a changed password gets fixed. */}+ {kit.database && (+ <div className="kit-db">+ <h3 className="kit-db-title">+ {kit.launched ? 'Change the database it reads' : 'Connect your database'}+ </h3>+ {kit.launched && (+ <p className="kit-choice-why">Leave this blank to keep reading what it reads today.</p>+ )}+ <DatabaseFields engines={kit.database.engines} value={db} onChange={setDb} />+ </div>+ )}<div className="kit-dialog-actions"><button className="button ghost" type="button" onClick={() => setCustom((v) => !v)}>@@ -386,97 +383,79 @@ function LaunchDialog({ kit, bases, busy, onClose, onLaunch }: {);}-/** The database step of the launch dialog.+// ── Connecting a database ─────────────────────────────────────────────────────────────────────+// Local to this page, not shared: a kit's launch dialog is the only place a connection string is+// ever typed. It used to be shared with the Harness tool modal, back when a database was a kind+// of tool you could add there — it is not, so there is one caller and it lives with it.++/** 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',+};++type DbDraft = { engine: string; connectionString: string; sampleRows: boolean };++/** The fields that connect a database.*- * 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.+ * The connection string is held nowhere but this component's state and the request that carries+ * it: it is not put in the URL, not put in local storage, and nothing ever sends it back.*/-function DatabaseStep({ kit, db, onChange }: {- kit: Kit; db: DbDraft; onChange: (d: DbDraft) => void;+function DatabaseFields({ engines, value, onChange }: {+ engines: string[]; value: DbDraft; onChange: (d: DbDraft) => void;}) {- const [test, setTest] = useState<{ state: 'idle' | 'busy' | 'ok' | 'err'; message: string }>(- { state: 'idle', message: '' });- const engines = kit.datasource?.engines || [];+ const [test, setTest] = useState<null | { busy?: boolean; ok?: boolean; message?: string }>(null);+ // Any edit invalidates the last answer: a status line about a string that is no longer in the+ // box is worse than no status line.+ const set = (p: Partial<DbDraft>) => { onChange({ ...value, ...p }); setTest(null); };+ const kinds = engines.length ? engines : Object.keys(ENGINE_LABEL);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' });- }+ setTest({ busy: true });+ const r = await testDatabase(value.engine, value.connectionString.trim());+ // The table count is the server's own answer, and it is the number that tells someone whether+ // the account they typed can actually see their data.+ setTest(r.ok ? { ok: true, message: `${r.database} · ${r.tableCount} tables` }+ : { ok: false, message: r.error || 'could not connect' });}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>+ <>+ {kinds.length > 1 && (+ <div className="hr-field"><label>Type</label>+ <select value={value.engine} onChange={(e) => set({ engine: e.target.value })}>+ {kinds.map((e) => <option key={e} value={e}>{ENGINE_LABEL[e] || e}</option>)}+ </select></div>)}-- <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 className="hr-field"><label>Connection string</label>+ <input type="text" value={value.connectionString} spellCheck={false} autoComplete="off"+ className="db-conn" placeholder={ENGINE_EXAMPLE[value.engine] || ''}+ onChange={(e) => set({ connectionString: e.target.value })} />+ <span className="hr-meta">Use an account that can only read. Your connection is stored securely and is never shown again.</span></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 className="mcp-test-row">+ <button className="hr-btn" type="button"+ disabled={!value.connectionString.trim() || test?.busy} onClick={() => void runTest()}>+ {test?.busy ? 'Testing…' : 'Test connection'}</button>+ {test && !test.busy && (test.ok+ ? <span className="mcp-test-status ok"><span className="mcp-dot" />Connected · {test.message}</span>+ : <span className="mcp-test-status err"><span className="mcp-dot" />{test.message}</span>)}</div>-- <label className="kit-db-sample">- <input type="checkbox" checked={db.sampleRows}- onChange={(e) => onChange({ ...db, sampleRows: e.target.checked })} />+ <label className="db-sample">+ <input type="checkbox" checked={value.sampleRows}+ onChange={(e) => onChange({ ...value, 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>+ <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.cssindex 2b512d5c..d8172c57 100644--- a/ui/src/app/hr.css+++ b/ui/src/app/hr.css@@ -526,6 +526,12 @@ a { color: inherit; text-decoration: none; }.wbx-conv-msgs { padding-top: 50px; }/* ════════ MCP modal: test connection + tools list ════════ */+/* Used by the kit dialog and by page-level errors, and styled nowhere until now — a refused+ connection read as ordinary body text. */+.hr-error {+ margin: 12px 0 0; padding: 10px 12px; font-size: 12.5px; line-height: 1.5; color: #b91c1c;+ background: #fef2f2; border: 1px solid #fecaca; border-radius: 9px;+}.mcp-test-row { display: flex; align-items: center; gap: 12px; margin: 4px 0 2px; }/* quiet status: a small colored dot + neutral ink text (not a wall of green) */.mcp-test-status { display: inline-flex; align-items: center; gap: 7px; font-size: 12.5px; font-weight: 500; color: var(--ink-2); }@@ -909,37 +915,24 @@ 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. */+/* The database step of a launch dialog — the only place a connection string is typed. Its fields+ borrow the .hr-field vocabulary so this step reads like the rest of the console's forms. */.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);+.kit-db .kit-choice-why { margin-bottom: 12px; }+.kit-db .mcp-test-row { flex-wrap: wrap; }+/* A connection string is read character by character — monospace, and it may wrap the field. */+.hr-field input.db-conn { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12.5px; }+.hr-field select {+ width: 100%; padding: 10px 12px; font: inherit; font-size: 14px; 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; }+.hr-field select:focus { outline: 2px solid var(--brand-soft); border-color: var(--brand); }+.db-sample { display: flex; gap: 9px; margin-top: 14px; cursor: pointer; }+.db-sample input { margin-top: 3px; accent-color: var(--brand); flex: none; }+.db-sample span { display: flex; flex-direction: column; gap: 2px; min-width: 0; }+.db-sample strong { font-size: 13px; font-weight: 600; color: var(--ink); }+.db-sample em { font-style: normal; font-size: 11.5px; line-height: 1.45; color: var(--sidebar-mute); }@media (max-width: 720px) {.kit-grid { grid-template-columns: 1fr; }@@ -948,8 +941,6 @@ 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; }+ .kit-db .mcp-test-row .hr-btn { flex: 1 1 auto; justify-content: center; }}diff --git a/ui/src/app/revamp.css b/ui/src/app/revamp.cssindex 17952718..1b1aae91 100644--- a/ui/src/app/revamp.css+++ b/ui/src/app/revamp.css@@ -753,10 +753,23 @@.tag { display: inline-flex; align-items: center; min-height: 28px; padding: 0 9px; border: 1px solid var(--line); border-radius: 999px; background: var(--surface-subtle); color: #4d4d57; font-size: 11.5px; }.section-actions { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 10px; }.section-actions strong { font-size: 12px; }- .capability-list { display: grid; gap: 8px; }+ .capability-list { display: grid; gap: 8px; container-type: inline-size; }.capability-row { display: grid; grid-template-columns: 30px minmax(0,1fr) auto; gap: 10px; align-items: center; min-height: 48px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 8px; background: #fff; }+ /* The row sits in a column narrower than the viewport — at 768 the settings form still spends+ 210px on its label, leaving the row about 270px — so the viewport is the wrong thing to ask.+ Ask the row's own container, and put the actions under the copy before three buttons crush+ what a tool says about itself into one word per line. */+ @container (max-width: 420px) {+ .capability-row { grid-template-columns: 30px minmax(0,1fr); }+ .capability-actions { grid-column: 2; justify-content: flex-start; }+ }.capability-icon { width: 28px; height: 28px; display: grid; place-items: center; border-radius: 7px; background: var(--surface-subtle); color: var(--muted); }.capability-copy strong, .capability-copy span { display: block; }+ /* A server's name and its endpoint are both single unbreakable tokens, and the second one is+ long. Without this they spill out of the row rather than wrapping inside it, which is what+ a narrow column does to any url. Break anywhere: a wrapped url is readable, a clipped one+ is not, and truncating would hide the very thing this line exists to show. */+ .capability-copy strong, .capability-copy span { overflow-wrap: anywhere; }.capability-copy strong { font-size: 12.5px; }.capability-copy span { margin-top: 3px; color: var(--muted); font-size: 10.5px; }.capability-actions { display: flex; align-items: center; gap: 6px; }@@ -1359,8 +1372,6 @@.run-detail { padding: 0; }.task-detail-shell, .conversation { padding-left: 16px; padding-right: 16px; }.composer { padding-left: 16px; padding-right: 16px; }- .capability-row { grid-template-columns: 30px minmax(0,1fr); }- .capability-actions { grid-column: 2; justify-content: flex-start; }.header-row { grid-template-columns: 1fr; }.session-detail-head, .inspector-head { align-items: stretch; flex-direction: column; }.run-inspector { padding: 18px 16px; }diff --git a/ui/src/components/HarnessEditors.tsx b/ui/src/components/HarnessEditors.tsxindex 1b980656..bc2a958e 100644--- a/ui/src/components/HarnessEditors.tsx+++ b/ui/src/components/HarnessEditors.tsx@@ -1,10 +1,11 @@'use client';// Harness capability editors, shared by the Harness Settings page and the Tasks workbench:-// SkillEditor, Agent Skills folder editor (tree + md/code editor + uploads)-// McpModal , MCP server add/edit with live Test connection+// SkillEditor , Agent Skills folder editor (tree + md/code editor + uploads)+// McpRow , one row of a harness's tool list+// McpModal , add/edit for a row, with a live Test connection// Extracted from workbench/page.tsx (page files must not carry extra named exports).import { useRef, useState } from 'react';-import { testMcp, storeMcpSecret } from '@/lib/harness';+import { testMcp, storeMcpSecret, type McpServer } from '@/lib/harness';import { Svg, Chevron, IcSkill } from 'reifyui';const IcTrash = () => <Svg s={15}><path d="M3 6h18M8 6V4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6M10 11v6M14 11v6" /></Svg>;@@ -316,11 +317,42 @@ export function SkillEditor({ skill, onClose, onSave, nameEditable = false, onNa);}-// ── MCP server add/edit modal: name + endpoint + bearer token, with a live Test connection-// that lists the server's tools (handshake runs server-side via the gateway). ─────────────────-export type McpServer = { id: string; name: string; enabled: boolean; url?: string; auth?: string; transport?: string };+// ── A harness's tool list: ONE row renderer, no kinds ─────────────────────────────────────────+// Every entry is an MCP server named by a URL, and that is the whole story this row tells. A+// database a kit connected is one of them: it has a name, an address and a credential like any+// other, so it gets the same icon, the same subtitle, the same Edit, Delete and toggle. There is+// deliberately no branch here — a branch would need a field to branch on, and inventing that+// field on the entry is what made the database a parallel path in the first place.+export function McpRow({ server, busy, onEdit, onDelete, onToggle }: {+ server: McpServer; busy?: boolean;+ onEdit: () => void; onDelete: () => void; onToggle: () => void;+}) {+ const enabled = server.enabled !== false;+ return (+ <div className="capability-row">+ <span className="capability-icon">+ <iconify-icon icon="tabler:world-www"></iconify-icon>+ </span>+ <div className="capability-copy"><strong>{server.name}</strong>+ <span>Custom MCP · {server.url || 'endpoint'}</span></div>+ <div className="capability-actions">+ <button className="button quiet small" type="button" disabled={busy} onClick={onEdit}>Edit</button>+ <button className="button quiet small" type="button" disabled={busy} onClick={onDelete}>Delete</button>+ <button className="toggle-button" type="button" disabled={busy} aria-pressed={enabled} onClick={onToggle}>+ {enabled ? 'Enabled' : 'Disabled'}</button>+ </div>+ </div>+ );+}++// ── Tool add/edit modal ───────────────────────────────────────────────────────────────────────+// Name + endpoint + bearer token, with a live Test connection that lists the server's tools+// (handshake runs server-side via the gateway). One form, because there is one kind of entry:+// a database a kit connected edits here too, and editing its address away from the gateway+// breaks it exactly the way editing any server's address to the wrong host breaks that one.export function McpModal({ server, declaredHeaders = [], onClose, onSave }: {- server: McpServer | null; declaredHeaders?: string[]; onClose: () => void; onSave: (s: McpServer) => void;+ server: McpServer | null; declaredHeaders?: string[];+ onClose: () => void; onSave: (s: McpServer) => void;}) {const [name, setName] = useState(server?.name || '');const [url, setUrl] = useState(server?.url || '');diff --git a/ui/src/lib/harness.ts b/ui/src/lib/harness.tsindex 8a62d6c0..d212960c 100644--- a/ui/src/lib/harness.ts+++ b/ui/src/lib/harness.ts@@ -26,6 +26,13 @@ export interface OobHarness {skills: string[]; // built-in skills (read-only)}+/** One entry in a Harness's tool list. Every entry, with no exceptions and no kinds: a database+ * a kit connected is one of these and reads back exactly like a server somewhere else. */+export interface McpServer {+ id: string; name: string; enabled: boolean;+ url?: string; auth?: string; transport?: string;+}+export interface CustomHarness {id: string;name: string;@@ -33,7 +40,7 @@ export interface CustomHarness {baseLabel: string;defaultModel: string;systemPrompt: string;- mcpServers: { id: string; name: string; enabled: boolean; url?: string; auth?: string; transport?: string }[];+ mcpServers: McpServer[];// A skill carries its bundle inline as `files`; bundles over the gateway's inline cap are// offloaded server-side and round-trip as {name, enabled, blob}, `blob` is an opaque pointer,// resolved back to files via getSkillFiles() when editing. Either shape is a REAL own skill.@@ -42,12 +49,6 @@ export interface CustomHarness {maxStep?: number | null; // default agent step budget per turn (blank = 40)timeoutSeconds?: number | null; // default per-turn wall-clock cap (blank = server default)additionalHeaders?: string[]; // declared header NAMES callers pass per request (app-level auth)- // The database this Harness reads, if one is connected. Read-only here: it is attached and- // detached through /harnesses/{id}/datasource, never by saving this form, because the value- // behind it is a credential this UI is never given. Present so the tools list can SHOW the- // database tool — the gateway adds that tool per turn rather than storing it, and a capability- // nobody can see on the page that lists capabilities is a capability nobody can audit.- dataSource?: { engine: string; host: string; database: string; sampleRows: boolean; updatedAt: number } | null;createdAt: number;}@@ -284,17 +285,6 @@ export async function getCustom(id: string): Promise<CustomHarness | null> {catch { return null; }}-/** Detach the database a Harness reads, and overwrite the stored credential.- *- * Its own route rather than a field on the harness save: the connection is written once, at- * launch, and this UI is never given the value — so there is nothing here to edit, only- * something to remove. Removing it is also the only off switch the database tool has, and that- * is deliberate: the tool exists for exactly as long as a database is connected, so a second- * enable/disable flag beside it would be a second thing that can disagree with the first. */-export async function disconnectDatasource(id: string): Promise<void> {- await gw('DELETE', `/v1/harnesses/${encodeURIComponent(id)}/datasource`);-}-export async function createCustom(input: Partial<CustomHarness> & { name: string; base: string }): Promise<CustomHarness> {return gw<CustomHarness>('POST', '/v1/harnesses', harnessBody(input));}@@ -344,6 +334,22 @@ export async function testMcp(url: string, auth?: string): Promise<{ ok: booleanreturn r.json();}+/** Probe a database before connecting it: the server opens it, lists what the account can see,+ * and holds on to nothing. Same 200-either-way contract as testMcp — a refused password is an+ * answer, not a failed request — and the same degrade when the request itself does not land. */+export async function testDatabase(engine: string, connectionString: string):+ Promise<{ ok: boolean; error?: string; host?: string; database?: string; tableCount?: number; tables?: string[] }> {+ const p = principal();+ const r = await harnessFetch(`/api/harness/v1/orgs/${encodeURIComponent(p.orgId)}/mcp-test/database`, {+ method: 'POST',+ headers: { 'content-type': 'application/json', 'x-harness-org': p.orgId, 'x-harness-member': p.member },+ body: JSON.stringify({ engine, connection_string: connectionString }),+ cache: 'no-store',+ });+ if (!r.ok) return { ok: false, error: `test failed: ${r.status}` };+ return r.json();+}+/** Store an MCP bearer token in the vault and return a 'vault:<ref>' reference. The token never* lands in the graph, only the ref is persisted on the harness config. */export async function storeMcpSecret(serverId: string, token: string): Promise<string> {