Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(os): Connectors sign in from this computer and reach every agent through a local bridge

bubu-dudu30d9e245c52f
diff --git a/os/README.md b/os/README.md
index d3abfdc15..971c4cc1c 100644
--- a/os/README.md
+++ b/os/README.md
@@ -79,15 +79,13 @@ for requirements and remaining work.
## Connected accounts
-Run `harness connections` to open the local Connections page. Connect GitHub,
-Notion, Linear, Asana or Figma with a personal token, then any local agent can
-use the account through the same CLI. Tokens stay outside projects and agent
-configuration. No Intern hardware or device registration is required.
-
-This preview includes manual-token connections. Browser OAuth and automatic
-token renewal are not available yet. Existing installations receive the feature
-through the OS update channel after publication; no reinstall is needed. See
-[Connections](connectors/README.md) for the exact scope and validation limits.
+Run `harness connections` to open the local Connectors page and sign in to a
+service in the browser. 21 services (Linear, Notion, Canva, Atlassian, GitLab,
+Figma…) sign in directly from this computer; GitHub, Slack, Google, Microsoft
+365 and a few others sign in through the Harness account. Claude Code, Codex
+and OpenCode then get each service as an MCP server on a local bridge, which
+adds the credential and renews it before it expires. Tokens stay outside
+projects and agent configuration. See [Connections](connectors/README.md).
## Design
diff --git a/os/connectors/README.md b/os/connectors/README.md
index 59f9fb407..cdc0a0d11 100644
--- a/os/connectors/README.md
+++ b/os/connectors/README.md
@@ -1,87 +1,109 @@
# Harness connections
-An OS-owned CLI and on-demand local settings page. No new engine integration,
-MCP server, desktop release, always-on daemon or third-party Python dependency.
-
-## Provenance
-
-`connector.py` and `../tests/test_connector_upstream.py` are adapted from
-[Autonomous Intern](https://github.com/autonomous-ai/Physical-AI-Operating-System)
-at `57faee5d8e7ee094701120c9bff4ce6ef8001fb2`:
-
-- `skills/connectors/scripts/connector.py`
-- `skills/connectors/tests/test_connector.py`
-
-Licensed under Apache-2.0; see LICENSE. Harness changes: per-user paths, private
-atomic storage shared across agents, JSON discovery, expiry
-handling, Figma/Linear personal-token headers, response size checks and local
-connection management. The small service guide adapts Intern's connector
-instructions; it omits Intern hardware, MQTT and agent-runtime setup.
-
-Provider-specific authentication was checked against
-[Figma](https://developers.figma.com/docs/rest-api/personal-access-tokens/),
-[Linear](https://linear.app/developers/graphql) and their account identity
-endpoints. Provider account tests remain a separate acceptance requirement.
+Connect a service once on this computer; every local agent (Claude Code, Codex,
+OpenCode) can then use it. Modelled on the Grid app's connectors: the same token
+format, the same two sign-in paths and the same local bridge. Python standard
+library only; no always-on process.
## Commands
```sh
-harness connections # opens local settings; exits immediately
-harness connections list --json # no secrets; shared by all local agents
-harness connections info github
+harness connections # open the Connectors page; exits immediately
+harness connections connect linear # sign in from a terminal instead
+harness connections list --json # no secrets; shared by all local agents
+harness connections info linear
+harness connections refresh [linear] # renew tokens that are due (or this one now)
+harness connections sync # write the agents' MCP entries again
+harness connections disconnect linear
harness connections call github GET https://api.github.com/user
-harness connections disconnect github
```
-State is under `$XDG_DATA_HOME/harness-os/connections`, normally
-`~/.local/share/harness-os/connections`: directory 0700, files 0600. The
-per-service JSON shape stays compatible with Intern. Credentials are not copied
-into projects or agent config. This avoids routine token exposure; it is not a
-sandbox against an agent running arbitrary code as the same Unix user.
-
-The page binds only 127.0.0.1, requires an unpredictable per-process capability
-for every API request, validates Host/Origin, serves no CORS access and does not
-log requests. Its capability is delivered in a URL fragment and retained only
-in that browser tab's session storage so refreshing the page works.
-Nothing is loaded from a CDN. The process exits after 15 minutes without
-authenticated requests; reopening the CLI reuses a live instance or starts one.
-
-## Architecture
-
-Connections belong to the local user on an ordinary computer running Harness.
-Connect an account once, then Claude Code, Codex, OpenCode, pi or another agent
-can use the same CLI and service instructions. Agents name a connection; the CLI
-reads its credentials. Changing agents does not require reconnecting accounts.
-Another computer or Unix user has a separate connection store.
-
-Intern is the source of the reusable connector code. There is no Intern device,
-MQTT connection, device key, hardware registration or additional agent runtime.
-No provider app secret belongs in an OS image, project or agent configuration.
-The settings page runs only when needed and does not require a cloud account for
-manual token connections.
-
-## Browser sign-in — not implemented yet
-
-Manual tokens work for GitHub, Notion, Linear, Asana and Figma. Browser OAuth and
-automatic renewal are not enabled. Expired credentials remain saved but cannot
-be used; the CLI asks the user to reconnect. A `backend.json` from an earlier
-development draft is ignored and cannot enable Intern device authentication.
-
-The remaining integration must deliver the result of browser consent to the
-local connection request, without an Intern device record. For providers that
-require a confidential OAuth client, its secret stays on the authorization
-server. The computer receives the user's authorized credentials and stores them
-locally. Credential delivery must be short-lived, single-use and bound to the
-requesting client; renewal must handle concurrent agents and rotated tokens.
-Disconnecting local access and revoking access at the provider are different
-operations and must be described accurately.
-
-The existing Intern server code was reviewed read-only. Its provider integration
-can inform this work, but its hardware delivery mechanism is not an OS
-requirement. No private backend implementation or configuration is included.
-Do not add device enrollment or require a different product account to bridge
-that gap. Complete real browser sign-in, renewal, disconnect and cross-agent
-acceptance before enabling OAuth-only services such as Gmail, Calendar and Drive.
+## Two ways to sign in
+
+`catalog.json` lists every service with its `auth`.
+
+**`dcr`: this computer signs in on its own.** The service's MCP server publishes
+OAuth metadata (RFC 9728/8414) with a registration endpoint, so Harness
+registers a public client for this computer (RFC 7591, `clients.json`), opens
+the service's consent page with PKCE S256 and receives the code on
+`http://127.0.0.1:51789-51792/callback`. No client secret ships with Harness and
+no Autonomous server is involved. Renewal goes straight to the service's token
+endpoint. 21 services, checked against their live metadata on 2026-10-08:
+
+Ahrefs, Airtable, Amplitude, Apollo.io, Atlassian (Jira, Confluence), Attio,
+Canva, ClickUp, Datadog, Figma, GitLab, Intercom, Klaviyo, Linear, monday.com,
+Notion, Sentry, Stripe, Supabase, Supermetrics, Vercel.
+
+**`app`: through the Autonomous connector gateway.** These services do not let
+a computer register itself, so the OAuth app Autonomous registered with them is
+used: `POST /v1/grid/connectors/start`, the browser signs in, then
+`/connectors/poll` returns the token once. The gateway holds the app's secret and
+renews tokens (`/connectors/refresh`). It needs the Harness sign-in
+(`harness login` keeps the Grid session in `~/.grid/credentials.toml`); signed
+out, the page says so instead of offering Connect. A service the gateway does
+not offer to this account shows "Not available yet".
+
+GitHub, Slack, Asana, HubSpot, PagerDuty, Gmail, Google Calendar, Google Drive,
+BigQuery, Microsoft 365.
+
+**Add custom** takes any remote MCP server URL: one that asks for sign-in uses the
+`dcr` path, one with static headers (a personal token) is saved as given.
+
+## Storage
+
+`$XDG_DATA_HOME/harness-os/connections` (normally
+`~/.local/share/harness-os/connections`): directory 0700, files 0600, written
+atomically under one lock shared by every agent and the bridge.
+
+- `tokens.json`: per connection, Grid's format: `access_token`,
+ `refresh_token`, `expires_at`, `scope`, `account_name`, `source`
+ (`dcr`/`gateway`/`custom`) and `mcp_entry {url, headers}`.
+- `clients.json`: this computer's registered OAuth clients, by issuer.
+- `bridge.json`: the bridge capability; `projections.json`: which agent entries
+ Harness wrote; `page.json`: the running page.
+
+## Agents and the bridge
+
+Agent configs never hold a token. Each connection with an MCP server becomes an
+entry pointing at `http://127.0.0.1:51793/<capability>/<code>/mcp`:
+
+| Agent | File | Entry |
+| --- | --- | --- |
+| Claude Code | `~/.claude.json` | `mcpServers.<code> = {type: http, url}` |
+| Codex | `~/.codex/config.toml` | `[mcp_servers.<code>] url = …` |
+| OpenCode | `~/.config/opencode/opencode.json` | `mcp.<code> = {type: remote, url, enabled}` |
+
+Only names recorded in `projections.json` are changed or removed; a server the
+user added keeps its name and contents, and a config that is not plain JSON is
+left alone.
+
+`harness-connections.socket` listens on 127.0.0.1:51793; systemd starts
+`bridge.py` on the first request and it exits after ten quiet minutes. The
+bridge checks the capability, refuses browser requests (any `Origin`), renews a
+token within five minutes of expiry (once, under the lock, so concurrent agents
+and rotating refresh tokens are safe), forwards the MCP request with the stored
+headers and streams the answer, event streams included. A token the service
+rejects is renewed once; a revoked grant marks the connection "Reconnect" and the
+agent gets that message, never the service's own sign-in challenge. Because the
+address never changes, a renewed token needs no agent config change and running
+agents keep working.
+
+## Page
+
+`connections.py serve` binds 127.0.0.1 only, requires an unpredictable
+per-process capability for every API request, validates Host/Origin, serves no
+CORS access and does not log requests. The capability is delivered in a URL
+fragment and kept in that tab's session storage. Nothing is loaded from a CDN.
+It exits after 15 minutes without requests or sign-ins in progress.
+
+## Provenance
+
+`connector.py` (`call`) and `../tests/test_connector_upstream.py` are adapted from
+[Autonomous Intern](https://github.com/autonomous-ai/Physical-AI-Operating-System)
+at `57faee5d8e7ee094701120c9bff4ce6ef8001fb2` (`skills/connectors/scripts/connector.py`,
+`skills/connectors/tests/test_connector.py`), Apache-2.0; see LICENSE. Harness
+changes: per-user paths, the shared token store, official-host allowlist per
+service, response size checks and redaction.
## Local review
@@ -90,8 +112,5 @@ CONNECTOR_CONFIGS_DIR=/tmp/harness-connections-review \
python3 os/connectors/connections.py serve
```
-Open the printed local URL. This creates only isolated review state; enter a
-real token only when intentionally testing that account. Unit tests use mocked
-provider responses and disposable credentials. Packaging includes the CLI,
-page, guide and license in the normal OS package, so installed machines receive
-it via an OS update without an ISO. No update has been published by this change.
+Open the printed local URL. Unit tests run every path against fake OAuth, MCP
+and gateway servers; real provider sign-in remains a manual acceptance step.
diff --git a/os/connectors/agents.py b/os/connectors/agents.py
new file mode 100644
index 000000000..1dd072534
--- /dev/null
+++ b/os/connectors/agents.py
@@ -0,0 +1,160 @@
+"""Connected services, given to each agent as an MCP server on the local bridge.
+
+Agent configs hold only a 127.0.0.1 bridge address; the bridge adds the
+credential to each request (Grid's design). A renewed token therefore needs no
+config change, and an agent that is already running keeps working.
+
+Only entries Harness made are changed or removed: their names are recorded in
+projections.json, so a server the user added by hand is never touched.
+"""
+import json
+import os
+from pathlib import Path
+import re
+import secrets
+import shutil
+import tempfile
+
+import connection_store as store
+
+PORT = int(os.environ.get("HARNESS_CONNECTIONS_PORT", "51793"))
+NAME = re.compile(r"[a-z0-9][a-z0-9_-]{0,47}")
+
+
+def bridge_key(vault):
+ """The capability in every bridge address, so only this user's agents can use it."""
+ with store.locked(vault.root):
+ data = vault.file("bridge.json")
+ if not isinstance(data.get("key"), str) or len(data["key"]) < 32:
+ data = {"key": secrets.token_urlsafe(32)}
+ store.write_private(vault.root / "bridge.json", data)
+ return data["key"]
+
+
+def bridge_url(key, code):
+ return f"http://127.0.0.1:{PORT}/{key}/{code}/mcp"
+
+
+def home():
+ return Path(os.environ.get("HOME") or Path.home())
+
+
+def write_file(path, raw):
+ """Replace a config atomically, keeping its permissions."""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ mode = path.stat().st_mode & 0o777 if path.exists() else 0o600
+ fd, name = tempfile.mkstemp(prefix="." + path.name + ".", dir=path.parent)
+ try:
+ with os.fdopen(fd, "w") as handle:
+ handle.write(raw)
+ os.chmod(name, mode)
+ os.replace(name, path)
+ finally:
+ Path(name).unlink(missing_ok=True)
+
+
+class JsonAgent:
+ """An agent whose MCP servers are one JSON object in its config."""
+
+ def __init__(self, name, binary, path, key, entry):
+ self.name, self.binary, self.path, self.key, self.entry = name, binary, path, key, entry
+
+ def installed(self):
+ return self.path().exists() or shutil.which(self.binary) is not None
+
+ def apply(self, wanted, owned):
+ path = self.path()
+ try:
+ data = json.loads(path.read_text()) if path.exists() else {}
+ except (OSError, ValueError):
+ return owned # A config with comments or a syntax error is left exactly as it is.
+ if not isinstance(data, dict):
+ return owned
+ servers = data.get(self.key)
+ if not isinstance(servers, dict):
+ servers = {}
+ result = set()
+ for name in set(owned) - set(wanted):
+ servers.pop(name, None)
+ for name, url in wanted.items():
+ if name in servers and name not in owned:
+ continue # The user's own server with this name.
+ servers[name] = self.entry(url)
+ result.add(name)
+ if servers:
+ data[self.key] = servers
+ else:
+ data.pop(self.key, None)
+ write_file(path, json.dumps(data, indent=2) + "\n")
+ return sorted(result)
+
+
+class CodexAgent:
+ name, binary = "codex", "codex"
+
+ def path(self):
+ return Path(os.environ.get("CODEX_HOME") or home() / ".codex") / "config.toml"
+
+ def installed(self):
+ return self.path().exists() or shutil.which(self.binary) is not None
+
+ @staticmethod
+ def header(name):
+ return re.compile(r'^\s*\[\s*mcp_servers\s*\.\s*(?:' + name + '|"' + name + r'")\s*(?:\.[^\]]*)?\]\s*$')
+
+ def apply(self, wanted, owned):
+ path = self.path()
+ try:
+ lines = path.read_text().splitlines() if path.exists() else []
+ except OSError:
+ return owned
+ drop = set(owned)
+ kept, skipping = [], False
+ for line in lines:
+ if line.lstrip().startswith("["):
+ skipping = any(self.header(re.escape(name)).match(line) for name in drop)
+ if not skipping:
+ kept.append(line)
+ while kept and not kept[-1].strip():
+ kept.pop()
+ result = []
+ for name, url in sorted(wanted.items()):
+ if any(self.header(re.escape(name)).match(line) for line in kept):
+ continue # The user's own server with this name.
+ kept += ["", f"[mcp_servers.{name}]", "url = " + json.dumps(url)]
+ result.append(name)
+ write_file(path, "\n".join(kept).lstrip("\n") + "\n" if kept else "")
+ return result
+
+
+def agents():
+ config = Path(os.environ.get("XDG_CONFIG_HOME") or home() / ".config")
+ return [
+ JsonAgent("claude", "claude", lambda: home() / ".claude.json", "mcpServers",
+ lambda url: {"type": "http", "url": url}),
+ CodexAgent(),
+ JsonAgent("opencode", "opencode", lambda: config / "opencode/opencode.json", "mcp",
+ lambda url: {"type": "remote", "url": url, "enabled": True}),
+ ]
+
+
+def sync(vault):
+ """Give every installed agent exactly the connections that have MCP tools."""
+ tokens = vault.tokens()
+ wanted = {code: None for code, token in tokens.items() if token.get("mcp_entry") and NAME.fullmatch(code)}
+ if wanted:
+ key = bridge_key(vault)
+ wanted = {code: bridge_url(key, code) for code in wanted}
+ with store.locked(vault.root):
+ record = vault.file("projections.json")
+ changed = {}
+ for agent in agents():
+ owned = [n for n in record.get(agent.name, []) if isinstance(n, str) and NAME.fullmatch(n)]
+ if not owned and not wanted:
+ continue
+ if not agent.installed():
+ continue
+ changed[agent.name] = agent.apply(wanted, owned)
+ record.update(changed)
+ store.write_private(vault.root / "projections.json", record)
+ return changed
diff --git a/os/connectors/bridge.py b/os/connectors/bridge.py
new file mode 100644
index 000000000..e6416e9ea
--- /dev/null
+++ b/os/connectors/bridge.py
@@ -0,0 +1,205 @@
+"""The local MCP bridge: agents call http://127.0.0.1:PORT/<key>/<code>/mcp and
+the bridge forwards to the service's MCP server with the stored credential,
+renewing it first when it is about to expire.
+
+systemd starts it on the first connection (harness-connections.socket) and it
+exits after a quiet spell, so it costs nothing while no agent uses a service.
+"""
+import hmac
+import http.client
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
+import os
+import socket
+import sys
+import threading
+import time
+import urllib.parse
+
+import connection_store as store
+import renew
+
+IDLE_SECONDS = 600
+# Headers an MCP client sends that the service must see. Authorization never
+# comes from the agent: the bridge sets it.
+FORWARD = ("accept", "content-type", "mcp-session-id", "mcp-protocol-version", "last-event-id")
+RETURN = ("content-type", "mcp-session-id", "mcp-protocol-version", "cache-control")
+MAX_BODY = 16 * 1024 * 1024
+
+
+class Bridge(ThreadingHTTPServer):
+ daemon_threads = True
+
+ def __init__(self, vault, listener=None, port=0):
+ self.vault = vault
+ self.active = 0
+ self.lock = threading.Lock()
+ self.last = time.monotonic()
+ if listener is None:
+ super().__init__(("127.0.0.1", port), Handler)
+ else:
+ super().__init__(listener.getsockname()[:2], Handler, bind_and_activate=False)
+ self.socket = listener
+ self.timeout = 5
+
+ def key(self):
+ return self.vault.file("bridge.json").get("key", "")
+
+ def busy(self, delta):
+ with self.lock:
+ self.active += delta
+ self.last = time.monotonic()
+
+ def serve_until_idle(self, idle=IDLE_SECONDS):
+ while self.active or time.monotonic() - self.last < idle:
+ self.handle_request()
+
+
+class Handler(BaseHTTPRequestHandler):
+ protocol_version = "HTTP/1.1"
+ server_version = "Harness"
+
+ def log_message(self, *_args):
+ pass # Never log request bodies, accounts or bridge addresses.
+
+ def fail(self, status, message):
+ # A JSON-RPC shaped error, so the agent shows the reason to the user.
+ raw = json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32001, "message": message}}).encode()
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(raw)))
+ # A refused request's body may be unread: never parse it as the next request.
+ self.send_header("Connection", "close")
+ self.close_connection = True
+ self.end_headers()
+ self.wfile.write(raw)
+
+ def target(self):
+ parts = urllib.parse.urlsplit(self.path).path.strip("/").split("/")
+ if len(parts) != 3 or parts[2] != "mcp":
+ return None
+ key = self.server.key()
+ if not key or not hmac.compare_digest(parts[0].encode(), key.encode()):
+ return None
+ return parts[1]
+
+ def handle_one(self):
+ self.server.busy(1)
+ try:
+ self.relay()
+ except (BrokenPipeError, ConnectionResetError):
+ pass
+ finally:
+ self.server.busy(-1)
+
+ do_GET = do_POST = do_DELETE = handle_one
+
+ def relay(self):
+ # Only a process on this computer that knows this user's key gets through.
+ if self.headers.get("Origin") or self.client_address[0] not in ("127.0.0.1", "::1"):
+ self.fail(403, "Forbidden.")
+ return
+ code = self.target()
+ if code is None:
+ self.fail(404, "Unknown connection address. Run harness connections sync.")
+ return
+ if self.headers.get("Transfer-Encoding"):
+ self.fail(411, "Send the request with a Content-Length.")
+ return
+ length = int(self.headers.get("Content-Length") or 0)
+ if length < 0 or length > MAX_BODY:
+ self.fail(413, "Request is too large.")
+ return
+ body = self.rfile.read(length) if length else None
+ name = store.SERVICES.get(code, code)
+ try:
+ token = self.server.vault.token(code)
+ if not token or not token.get("mcp_entry"):
+ self.fail(404, f"{name} is not connected. Open harness connections to connect it.")
+ return
+ if store.needs_refresh(token):
+ token = renew.refresh(self.server.vault, code)
+ except store.StoreError as error:
+ self.fail(401, f"{name}: {error}")
+ return
+ response, connection = self.forward(token, body)
+ if response.status == 401 and store.refreshable(token):
+ # A token the service revoked early: renew once and try again.
+ connection.close()
+ try:
+ token = renew.refresh(self.server.vault, code, force=True)
+ except store.StoreError as error:
+ self.fail(401, f"{name}: {error}")
+ return
+ response, connection = self.forward(token, body)
+ try:
+ if response.status == 401:
+ # Never pass the service's own sign-in challenge to the agent:
+ # signing in happens in Harness, not in each agent.
+ self.fail(401, f"{name} needs to be connected again. Open harness connections.")
+ return
+ self.stream(response)
+ finally:
+ connection.close()
+
+ def forward(self, token, body):
+ entry = token["mcp_entry"]
+ upstream = urllib.parse.urlsplit(entry["url"])
+ query = urllib.parse.urlsplit(self.path).query
+ path = (upstream.path or "/") + ("?" + upstream.query if upstream.query else "") + \
+ (("&" if upstream.query else "?") + query if query else "")
+ headers = {k: v for k, v in self.headers.items() if k.lower() in FORWARD}
+ headers.update(entry.get("headers") or {})
+ headers["User-Agent"] = "Harness-Connections"
+ if body is not None:
+ headers["Content-Length"] = str(len(body))
+ if upstream.scheme == "https":
+ connection = http.client.HTTPSConnection(upstream.hostname, upstream.port or 443, timeout=300)
+ else:
+ connection = http.client.HTTPConnection(upstream.hostname, upstream.port or 80, timeout=300)
+ connection.request(self.command, path, body=body, headers=headers)
+ return connection.getresponse(), connection
+
+ def stream(self, response):
+ """The service's answer as it arrives: MCP replies may be an event stream."""
+ self.send_response(response.status)
+ for name, value in response.getheaders():
+ if name.lower() in RETURN:
+ self.send_header(name, value)
+ length = response.getheader("Content-Length")
+ if length is not None:
+ self.send_header("Content-Length", length)
+ self.end_headers()
+ self.wfile.write(response.read())
+ return
+ self.send_header("Transfer-Encoding", "chunked")
+ self.end_headers()
+ while True:
+ chunk = response.read1(65536) if hasattr(response, "read1") else response.read(65536)
+ if not chunk:
+ break
+ self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk))
+ self.wfile.flush()
+ self.wfile.write(b"0\r\n\r\n")
+
+
+def systemd_listener():
+ """The socket systemd passed (LISTEN_FDS), or None when run by hand."""
+ if os.environ.get("LISTEN_PID") != str(os.getpid()) or os.environ.get("LISTEN_FDS") != "1":
+ return None
+ return socket.socket(fileno=3)
+
+
+def main(argv):
+ vault = store.Store()
+ listener = systemd_listener()
+ port = int(argv[0]) if argv else 0
+ with Bridge(vault, listener, port) as server:
+ if listener is None:
+ print(f"Bridge on 127.0.0.1:{server.server_address[1]}", flush=True)
+ server.serve_until_idle()
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))
diff --git a/os/connectors/catalog.json b/os/connectors/catalog.json
new file mode 100644
index 000000000..290ac9446
--- /dev/null
+++ b/os/connectors/catalog.json
@@ -0,0 +1,36 @@
+{
+ "_note": "auth: dcr = this computer registers its own OAuth client with the service's MCP server (RFC 7591) and signs in through 127.0.0.1; app = the service has no self-registration, so sign-in goes through the Autonomous connector gateway with the Harness account. Checked against each MCP server's OAuth metadata on 2026-10-08.",
+ "connectors": [
+ {"code": "ahrefs", "label": "Ahrefs", "auth": "dcr", "mcp_url": "https://api.ahrefs.com/mcp/mcp", "color": "#ff8800", "description": "SEO data: backlinks, keywords, rankings and site audits from your Ahrefs account."},
+ {"code": "airtable", "label": "Airtable", "auth": "dcr", "mcp_url": "https://mcp.airtable.com/mcp", "color": "#fcb400", "description": "Bases, tables and records in your Airtable workspace: read them and add to them."},
+ {"code": "amplitude", "label": "Amplitude", "auth": "dcr", "mcp_url": "https://mcp.amplitude.com/mcp", "color": "#1e61f0", "description": "Product analytics: charts, funnels and user behaviour from your Amplitude projects."},
+ {"code": "apollo", "label": "Apollo.io", "auth": "dcr", "mcp_url": "https://mcp.apollo.io/mcp", "color": "#ebf212", "description": "Contacts, accounts and sequences in your Apollo.io workspace."},
+ {"code": "asana", "label": "Asana", "auth": "app", "color": "#f06a6a", "description": "Tasks, projects and workloads across your Asana workspaces."},
+ {"code": "atlassian", "label": "Atlassian", "auth": "dcr", "mcp_url": "https://mcp.atlassian.com/v1/mcp", "color": "#0c66e4", "description": "Jira issues and Confluence pages across your Atlassian sites."},
+ {"code": "attio", "label": "Attio", "auth": "dcr", "mcp_url": "https://mcp.attio.com/mcp", "color": "#a8a8a8", "description": "Records, lists and notes in your Attio CRM."},
+ {"code": "canva", "label": "Canva", "auth": "dcr", "mcp_url": "https://mcp.canva.com/mcp", "color": "#7d2ae8", "description": "Designs, brand templates and assets in your Canva account, so the agent can find them and make new ones."},
+ {"code": "clickup", "label": "ClickUp", "auth": "dcr", "mcp_url": "https://mcp.clickup.com/mcp", "color": "#7b68ee", "description": "Tasks, docs and spaces in your ClickUp workspace."},
+ {"code": "datadog", "label": "Datadog", "auth": "dcr", "mcp_url": "https://mcp.datadoghq.com/api/unstable/mcp-server/mcp", "color": "#632ca6", "description": "Logs, metrics, monitors and incidents from your Datadog organisation."},
+ {"code": "figma", "label": "Figma", "auth": "dcr", "mcp_url": "https://mcp.figma.com/mcp", "color": "#f24e1e", "description": "Files, frames and design context from your Figma account."},
+ {"code": "github", "label": "GitHub", "auth": "app", "color": "#6e7681", "description": "Repositories, issues and pull requests on GitHub, including code search."},
+ {"code": "gitlab", "label": "GitLab", "auth": "dcr", "mcp_url": "https://gitlab.com/api/v4/mcp", "color": "#fc6d26", "description": "Projects, issues, merge requests and pipelines on GitLab.com."},
+ {"code": "gmail", "label": "Gmail", "auth": "app", "color": "#ea4335", "description": "Read, search and draft email in your Gmail account."},
+ {"code": "google_bigquery", "label": "BigQuery", "auth": "app", "color": "#4285f4", "description": "Datasets and SQL queries in your Google BigQuery projects."},
+ {"code": "google_calendar", "label": "Google Calendar", "auth": "app", "color": "#1a73e8", "description": "Events and availability in your Google Calendar."},
+ {"code": "google_drive", "label": "Google Drive", "auth": "app", "color": "#0f9d58", "description": "Files and folders in your Google Drive."},
+ {"code": "hubspot", "label": "HubSpot", "auth": "app", "color": "#ff7a59", "description": "Contacts, companies and deals in your HubSpot CRM."},
+ {"code": "intercom", "label": "Intercom", "auth": "dcr", "mcp_url": "https://mcp.intercom.com/mcp", "color": "#1f8ded", "description": "Conversations, contacts and help articles in your Intercom workspace."},
+ {"code": "klaviyo", "label": "Klaviyo", "auth": "dcr", "mcp_url": "https://mcp.klaviyo.com/mcp", "color": "#3d3d3d", "description": "Campaigns, flows, lists and metrics in your Klaviyo account."},
+ {"code": "linear", "label": "Linear", "auth": "dcr", "mcp_url": "https://mcp.linear.app/mcp", "color": "#5e6ad2", "description": "Issues, projects and cycles in your Linear workspace."},
+ {"code": "microsoft_365", "label": "Microsoft 365", "auth": "app", "color": "#d83b01", "description": "Outlook mail and calendar, OneDrive and SharePoint files in your Microsoft 365 account."},
+ {"code": "mondaydotcom", "label": "monday.com", "auth": "dcr", "mcp_url": "https://mcp.monday.com/mcp", "color": "#ff3d57", "description": "Boards, items and updates in your monday.com account."},
+ {"code": "notion", "label": "Notion", "auth": "dcr", "mcp_url": "https://mcp.notion.com/mcp", "color": "#9b9a97", "description": "Pages and databases in your Notion workspace: search, read and write."},
+ {"code": "pagerduty", "label": "PagerDuty", "auth": "app", "color": "#06ac38", "description": "Incidents, services and on-call schedules in PagerDuty."},
+ {"code": "sentry", "label": "Sentry", "auth": "dcr", "mcp_url": "https://mcp.sentry.dev/mcp", "color": "#8d5494", "description": "Issues, errors and releases from your Sentry organisation."},
+ {"code": "slack", "label": "Slack", "auth": "app", "color": "#e01e5a", "description": "Channels, messages and people in your Slack workspace."},
+ {"code": "stripe", "label": "Stripe", "auth": "dcr", "mcp_url": "https://mcp.stripe.com", "color": "#635bff", "description": "Customers, payments, invoices and subscriptions in your Stripe account."},
+ {"code": "supabase", "label": "Supabase", "auth": "dcr", "mcp_url": "https://mcp.supabase.com/mcp", "color": "#3ecf8e", "description": "Projects, databases, tables and edge functions in your Supabase organisation."},
+ {"code": "supermetrics_marketing", "label": "Supermetrics", "auth": "dcr", "mcp_url": "https://mcp.supermetrics.com/mcp", "color": "#5e2bff", "description": "Marketing data from your ad, analytics and social accounts through Supermetrics."},
+ {"code": "vercel", "label": "Vercel", "auth": "dcr", "mcp_url": "https://mcp.vercel.com", "color": "#a3a3a3", "description": "Projects, deployments and logs on Vercel."}
+ ]
+}
diff --git a/os/connectors/connection_store.py b/os/connectors/connection_store.py
index b30362f96..3ec1aa709 100644
--- a/os/connectors/connection_store.py
+++ b/os/connectors/connection_store.py
@@ -1,20 +1,26 @@
-"""Per-user Intern-format credentials. No engine-specific copies or cloud sync."""
+"""Per-user connection store: one private tokens.json shared by every local agent.
+
+The token format follows Grid's ~/.grid/connectors/tokens.json, keyed by
+connector code. Agents never read it: MCP clients reach a service through the
+local bridge, and `harness connections call` reads a credential for one request.
+"""
import contextlib
import fcntl
import json
import os
from pathlib import Path
+import re
import stat
import tempfile
import time
+import urllib.parse
import urllib.request
-SERVICES = {
- "gmail": "Gmail", "google_calendar": "Google Calendar", "google_drive": "Google Drive",
- "github": "GitHub", "notion": "Notion", "linear": "Linear", "asana": "Asana",
- "figma": "Figma", "figma-api": "Figma API", "facebook": "Facebook", "ahrefs": "Ahrefs",
-}
-MAX_BYTES = 65536
+CATALOG_FILE = Path(__file__).parent / "catalog.json"
+MAX_BYTES = 1024 * 1024
+# A token is renewed this long before it expires, as Grid does.
+REFRESH_MARGIN = 300
+CODE = re.compile(r"[a-z0-9][a-z0-9_-]{0,47}")
class StoreError(Exception):
@@ -26,8 +32,17 @@ def directory():
return Path(os.environ.get("CONNECTOR_CONFIGS_DIR", str(base / "harness-os/connections")))
+def load_catalog():
+ with open(CATALOG_FILE) as handle:
+ return {item["code"]: item for item in json.load(handle)["connectors"]}
+
+
+CATALOG = load_catalog()
+SERVICES = {code: item["label"] for code, item in CATALOG.items()}
+
+
def validate_code(code):
- if code not in SERVICES:
+ if not isinstance(code, str) or not CODE.fullmatch(code):
raise StoreError("Unknown connection.")
return code
@@ -101,92 +116,169 @@ def locked(root):
fcntl.flock(fd, fcntl.LOCK_UN)
-def clean_entry(entry):
+def text(value, limit=8192):
+ if value is None:
+ return ""
+ if not isinstance(value, str) or len(value) > limit or any(ord(c) < 32 or ord(c) == 127 for c in value):
+ raise StoreError("Invalid connection fields.")
+ return value
+
+
+def clean_headers(headers):
+ if headers in (None, {}):
+ return {}
+ if not isinstance(headers, dict) or len(headers) > 20:
+ raise StoreError("Invalid connection headers.")
+ result = {}
+ for name, value in headers.items():
+ if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9-]{1,64}", name):
+ raise StoreError("Invalid connection headers.")
+ result[name] = text(value)
+ return result
+
+
+def clean_url(url):
+ url = text(url, 2048)
+ parsed = urllib.parse.urlsplit(url)
+ local = parsed.scheme == "http" and parsed.hostname in ("127.0.0.1", "localhost", "::1")
+ if not (parsed.scheme == "https" or local) or not parsed.hostname or parsed.username or parsed.password:
+ raise StoreError("Use an https:// address for the server.")
+ return url
+
+
+def clean_token(entry):
+ """A tokens.json entry, as Grid writes it, with nothing unexpected kept."""
if not isinstance(entry, dict):
raise StoreError("Invalid connection.")
result = {}
- for key in ("access_token", "api_key", "refresh_token", "token_type", "client_id", "user_email", "auth_type"):
- value = entry.get(key, "")
- if not isinstance(value, str) or len(value) > 8192 or any(ord(c) < 32 or ord(c) == 127 for c in value):
- raise StoreError("Invalid connection fields.")
+ for key in ("access_token", "refresh_token", "token_type", "scope", "account_name", "source", "issuer", "label"):
+ value = text(entry.get(key))
if value:
result[key] = value
- if result.get("auth_type", "oauth") not in ("pat", "oauth"):
- raise StoreError("Unsupported authentication type.")
- if not (result.get("access_token") or result.get("api_key")):
- raise StoreError("No access token was supplied.")
+ if result.get("source", "dcr") not in ("dcr", "gateway", "custom"):
+ raise StoreError("Unsupported connection source.")
for key in ("expires_at", "obtained_at"):
value = entry.get(key, 0)
if type(value) is not int or value < 0:
raise StoreError("Invalid connection expiry.")
- result[key] = value
- scopes = entry.get("scopes", [])
- if not isinstance(scopes, list) or len(scopes) > 100 or any(not isinstance(s, str) or len(s) > 1024 for s in scopes):
- raise StoreError("Invalid connection permissions.")
- result["scopes"] = scopes
- result["refresh"] = entry.get("refresh") is True
- creds = entry.get("credentials", {})
- if not isinstance(creds, dict):
- raise StoreError("Invalid connection metadata.")
- result["credentials"] = {k: v for k, v in creds.items() if k in ("page_id", "email") and isinstance(v, str) and len(v) < 1024}
+ if value:
+ result[key] = value
+ for key in ("refresh", "needs_reconnect"):
+ if entry.get(key) is True:
+ result[key] = True
+ mcp = entry.get("mcp_entry")
+ if mcp:
+ if not isinstance(mcp, dict):
+ raise StoreError("Invalid connection server.")
+ result["mcp_entry"] = {"url": clean_url(mcp.get("url")), "headers": clean_headers(mcp.get("headers"))}
+ if not (result.get("access_token") or result.get("mcp_entry")):
+ raise StoreError("No access token was supplied.")
return result
+def bearer(token):
+ """The Authorization value for a token, its scheme normalised as Grid does."""
+ scheme = token.get("token_type") or "Bearer"
+ return ("Bearer" if scheme.lower() == "bearer" else scheme) + " " + token["access_token"]
+
+
+def needs_refresh(token, now=None):
+ expires = token.get("expires_at", 0)
+ now = time.time() if now is None else now
+ return bool(expires) and expires - REFRESH_MARGIN <= now and refreshable(token) and not token.get("needs_reconnect")
+
+
+def refreshable(token):
+ if token.get("source") == "gateway":
+ return token.get("refresh") is True
+ return bool(token.get("refresh_token"))
+
+
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None
class Store:
+ """tokens.json (credentials), clients.json (registered OAuth clients, by issuer)."""
+
def __init__(self, root=None):
self.root = directory() if root is None else Path(root)
- def path(self, code):
- return self.root / (validate_code(code) + "_access_tokens.json")
-
- def load(self, code):
+ def file(self, name):
if self.root.is_symlink():
raise StoreError("Connection storage must not be a symlink.")
- data = read_private(self.path(code))
- if data is None:
- return None
- entries = data.get("connectors")
- if not isinstance(entries, dict):
- raise StoreError("Invalid connection settings.")
- entry = entries.get(code)
- return clean_entry(entry)
+ return read_private(self.root / name) or {}
+
+ def tokens(self):
+ data = self.file("tokens.json")
+ result = {}
+ for code, entry in data.items():
+ if isinstance(code, str) and CODE.fullmatch(code):
+ result[code] = clean_token(entry)
+ return result
+
+ def token(self, code):
+ return self.tokens().get(validate_code(code))
+
+ def put(self, code, entry):
+ """Save one connection, replacing it. Call under locked()."""
+ validate_code(code)
+ data = self.file("tokens.json")
+ data[code] = clean_token(entry)
+ write_private(self.root / "tokens.json", data)
def save(self, code, entry):
- path = self.path(code)
- entry = clean_entry(entry)
with locked(self.root):
- write_private(path, {"connectors": {code: entry}})
+ self.put(code, entry)
def disconnect(self, code):
- path = self.path(code)
+ validate_code(code)
with locked(self.root):
- path.unlink(missing_ok=True)
+ data = self.file("tokens.json")
+ if data.pop(code, None) is not None:
+ write_private(self.root / "tokens.json", data)
- def ready(self, code):
+ def client(self, issuer):
+ entry = self.file("clients.json").get(issuer)
+ return entry if isinstance(entry, dict) else None
+
+ def save_client(self, issuer, client):
with locked(self.root):
- entry = self.load(code)
- if not entry:
- raise StoreError("Not connected. Open harness connections to connect an account.")
- expires = entry["expires_at"]
- if expires and expires <= time.time():
- raise StoreError("This account has expired. Reconnect it in Connections.")
- return entry
-
- def status(self, code):
- entry = self.load(code)
- if not entry:
- return {"connector": code, "name": SERVICES[code], "state": "not_connected", "scopes": []}
- expires = entry["expires_at"]
- return {
- "connector": code, "name": SERVICES[code],
- "state": "expired" if expires and expires <= time.time() else "connected",
- "account": entry.get("user_email") or entry["credentials"].get("email", ""),
- "auth_type": entry.get("auth_type", "oauth"), "scopes": entry["scopes"],
- "expires_at": expires or None,
- "auto_refresh": False, # Browser authorization and renewal are not enabled yet.
- }
+ data = self.file("clients.json")
+ data[issuer] = client
+ write_private(self.root / "clients.json", data)
+
+ def label(self, code):
+ if code in CATALOG:
+ return CATALOG[code]["label"]
+ token = self.token(code)
+ return (token or {}).get("label") or code
+
+ def status(self, code, token=None):
+ token = token if token is not None else self.token(code)
+ base = {"connector": code, "name": self.label(code)}
+ if not token:
+ return dict(base, state="not_connected")
+ expires = token.get("expires_at", 0)
+ expired = bool(expires) and expires <= time.time()
+ state = "reconnect" if token.get("needs_reconnect") or (expired and not refreshable(token)) else "connected"
+ return dict(base, state=state, account=token.get("account_name", ""), source=token.get("source", "dcr"),
+ scopes=(token.get("scope") or "").split(), expires_at=expires or None,
+ auto_refresh=refreshable(token), tools=bool(token.get("mcp_entry")))
+
+ def ready(self, code):
+ """A usable token for one request, renewed first when it is about to expire."""
+ token = self.token(code)
+ if not token:
+ raise StoreError("Not connected. Open harness connections to connect an account.")
+ if needs_refresh(token):
+ import renew
+ token = renew.refresh(self, code)
+ expires = token.get("expires_at", 0)
+ if token.get("needs_reconnect") or (expires and expires <= time.time()):
+ raise StoreError("This account has expired. Reconnect it in Connections.")
+ if not token.get("access_token"):
+ raise StoreError("This connection has no account token.")
+ return token
+
diff --git a/os/connectors/connections.py b/os/connectors/connections.py
index bf562fce1..1ee983ed3 100644
--- a/os/connectors/connections.py
+++ b/os/connectors/connections.py
@@ -1,107 +1,165 @@
#!/usr/bin/env python3
-"""On-demand, loopback-only Connections page for Harness OS."""
+"""On-demand, loopback-only Connectors page and commands for Harness OS.
+
+harness connections open the Connectors page
+harness connections connect CODE sign in from the terminal
+harness connections disconnect CODE
+harness connections refresh [CODE] renew tokens that are due (or CODE now)
+harness connections sync give agents their connections again
+harness connections list|info|call see connector.py
+"""
import argparse
import contextlib
import hmac
-from http.server import BaseHTTPRequestHandler, HTTPServer
-import io
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
-import os
-from pathlib import Path
import re
import secrets
import shutil
import subprocess
import sys
+import threading
import time
import urllib.request
+from pathlib import Path
-import connector
+import agents
import connection_store as store
+import connector
+import gateway
+import oauth
+import renew
ASSETS = Path(__file__).parent / "web"
+GATEWAY_CACHE_SECONDS = 60
def identity_proof(key, nonce):
return hmac.new(key.encode(), ("harness-connections-v1:" + nonce).encode(), "sha256").hexdigest()
-# Read-only identity checks. API keys are not saved until the check succeeds.
-# OAuth-only services stay unavailable until browser authorization and renewal
-# work for a local Harness user. Intern hardware enrollment is not part of this.
-MANUAL = {
- "github": ("GET", "https://api.github.com/user", [], "https://github.com/settings/tokens"),
- "notion": ("GET", "https://api.notion.com/v1/users/me", [], "https://www.notion.so/profile/integrations"),
- "linear": ("POST", "https://api.linear.app/graphql", ["--json", '{"query":"{ viewer { id name email } }"}'],
- "https://linear.app/settings/api"),
- "asana": ("GET", "https://app.asana.com/api/1.0/users/me", [], "https://app.asana.com/0/my-apps"),
- "figma": ("GET", "https://api.figma.com/v1/me", [], "https://developers.figma.com/docs/rest-api/personal-access-tokens/"),
-}
-
-
-def catalog(vault):
+def custom_code(name, taken):
+ base = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")[:40] or "server"
+ code = base if base not in store.CATALOG else "custom-" + base
+ n = 2
+ while code in taken:
+ code, n = f"{base}-{n}", n + 1
+ return store.validate_code(code)
+
+
+def sign_in_for(vault, code):
+ """The sign-in that connects CODE: the gateway's or this computer's own."""
+ item = store.CATALOG.get(code)
+ if item is None:
+ raise store.StoreError("Unknown connection.")
+ if item["auth"] == "app":
+ return gateway.SignIn(code)
+ return oauth.SignIn(vault, item["mcp_url"])
+
+
+def finish(vault, code, token, label=None):
+ if label:
+ token["label"] = label
+ token["source"] = "custom"
+ vault.save(code, token)
+ with contextlib.suppress(store.StoreError, OSError):
+ agents.sync(vault)
+
+
+def disconnect(vault, code):
+ token = vault.token(code)
+ if token and token.get("source") == "gateway":
+ gateway.disconnect(code)
+ vault.disconnect(code)
+ with contextlib.suppress(store.StoreError, OSError):
+ agents.sync(vault)
+
+
+class Flows:
+ """Browser sign-ins in progress, each finishing on its own thread."""
+
+ def __init__(self, vault):
+ self.vault, self.items, self.lock = vault, {}, threading.Lock()
+
+ def start(self, code, sign_in, label=None):
+ authorize = sign_in.prepare()
+ flow = secrets.token_urlsafe(12)
+ record = {"connector": code, "state": "pending", "error": "", "cancel": False}
+ with self.lock:
+ # One sign-in per service: a newer one replaces a forgotten tab.
+ for other in self.items.values():
+ if other["connector"] == code and other["state"] == "pending":
+ other["cancel"] = True
+ self.items[flow] = record
+
+ def run():
+ try:
+ token = sign_in.wait(lambda: record["cancel"])
+ finish(self.vault, code, token, label)
+ record["state"] = "connected"
+ except (store.StoreError, OSError) as error:
+ record.update(state="failed", error=str(error) if isinstance(error, store.StoreError)
+ else "The sign-in did not finish. Try again.")
+ threading.Thread(target=run, daemon=True).start()
+ return {"flow": flow, "authorize_url": authorize}
+
+ def get(self, flow):
+ with self.lock:
+ record = self.items.get(flow)
+ if not record:
+ raise store.StoreError("This sign-in has ended. Try again.")
+ return {"connector": record["connector"], "state": record["state"], "error": record["error"]}
+
+
+def catalog(vault, offered=None):
+ """The page's cards: every service, connected first, then custom servers."""
+ tokens = vault.tokens()
+ signed_in = gateway.session() is not None
+ offered = offered or {}
items = []
- for code in store.SERVICES:
- if code == "figma-api" and not vault.path(code).exists():
+ for code, item in store.CATALOG.items():
+ card = vault.status(code, tokens.get(code) or {})
+ card.update(description=item["description"], color=item["color"], auth=item["auth"], custom=False, reason="")
+ if item["auth"] == "app" and card["state"] == "not_connected":
+ if not signed_in:
+ card["reason"] = "Sign in to Harness first (harness login)."
+ elif offered and code not in offered:
+ card["reason"] = "Not available yet."
+ items.append(card)
+ for code, token in tokens.items():
+ if code in store.CATALOG:
continue
- try:
- item = vault.status(code)
- except store.StoreError:
- item = {"connector": code, "name": store.SERVICES[code], "state": "unreadable", "scopes": []}
- item["manual"] = code in MANUAL
- item["manage_url"] = MANUAL[code][3] if code in MANUAL else None
- items.append(item)
- return items
-
-
-def connect_token(vault, code, token):
- if code not in MANUAL:
- raise store.StoreError("Browser sign-in is not available for this service yet.")
- entry = store.clean_entry({"auth_type": "pat", "api_key": token, "obtained_at": int(time.time())})
- method, url, args, _ = MANUAL[code]
- output, error = io.StringIO(), io.StringIO()
- with contextlib.redirect_stdout(output), contextlib.redirect_stderr(error):
- status = connector.cmd_call(code, method, url, args, entry_override=entry)
- if status:
- raise store.StoreError("Could not verify this token. Check its permissions and your connection, then try again.")
- try:
- result = json.loads(output.getvalue())
- if not isinstance(result, dict):
- raise ValueError()
- if code == "linear":
- if result.get("errors"):
- raise ValueError()
- account = result["data"]["viewer"]
- elif code == "asana":
- account = result["data"]
- else:
- account = result
- if not isinstance(account, dict) or not (account.get("id") or account.get("gid")):
- raise ValueError()
- identity = account.get("email") or account.get("login") or account.get("name") or account.get("handle") or ""
- if not isinstance(identity, str):
- raise ValueError()
- entry["user_email"] = identity[:512]
- except (ValueError, KeyError, TypeError):
- raise store.StoreError("The service did not confirm this account. The token was not saved.")
- vault.save(code, entry)
- return vault.status(code)
-
-
-class PageServer(HTTPServer):
+ card = vault.status(code, token)
+ card.update(description=token.get("mcp_entry", {}).get("url", ""), color="#59634b", auth="custom", custom=True, reason="")
+ items.append(card)
+ return {"connections": items, "signed_in": signed_in}
+
+
+class PageServer(ThreadingHTTPServer):
allow_reuse_address = False
+ daemon_threads = True
def __init__(self, vault=None, port=0, idle_seconds=900):
self.vault = vault or store.Store()
+ self.flows = Flows(self.vault)
self.key = secrets.token_urlsafe(32)
self.idle_seconds = idle_seconds
self.last_request = time.monotonic()
+ self.offered, self.offered_at = {}, 0.0
super().__init__(("127.0.0.1", port), PageHandler)
self.origin = "http://127.0.0.1:" + str(self.server_address[1])
self.timeout = 1
+ def gateway_offers(self):
+ if time.monotonic() - self.offered_at > GATEWAY_CACHE_SECONDS:
+ self.offered, self.offered_at = gateway.available(), time.monotonic()
+ return self.offered
+
+ def busy(self):
+ return any(f["state"] == "pending" for f in self.flows.items.values())
+
def serve_until_idle(self):
- while time.monotonic() - self.last_request < self.idle_seconds:
+ while self.busy() or time.monotonic() - self.last_request < self.idle_seconds:
self.handle_request()
@@ -110,7 +168,7 @@ class PageHandler(BaseHTTPRequestHandler):
def setup(self):
super().setup()
- self.connection.settimeout(5)
+ self.connection.settimeout(15)
def log_message(self, *_args):
pass # Do not log account names, request bodies or session credentials.
@@ -146,12 +204,19 @@ class PageHandler(BaseHTTPRequestHandler):
return
self.reply(200, {"proof": identity_proof(self.server.key, nonce)})
return
- if self.path == "/api/connections":
+ if self.path == "/api/connections" or self.path.startswith("/api/flows/"):
if not self.authenticated():
self.reply(403, {"error": "Open harness connections again to continue."})
return
self.server.last_request = time.monotonic()
- self.reply(200, {"connections": catalog(self.server.vault)})
+ try:
+ if self.path == "/api/connections":
+ offered = self.server.gateway_offers()
+ self.reply(200, catalog(self.server.vault, offered))
+ else:
+ self.reply(200, self.server.flows.get(self.path.removeprefix("/api/flows/")))
+ except store.StoreError as error:
+ self.reply(400, {"error": str(error)})
return
files = {"/": ("index.html", "text/html; charset=utf-8"),
"/style.css": ("style.css", "text/css; charset=utf-8"),
@@ -175,13 +240,17 @@ class PageHandler(BaseHTTPRequestHandler):
data = json.loads(self.rfile.read(length))
if not isinstance(data, dict):
raise ValueError()
- code = store.validate_code(data.get("connector"))
self.server.last_request = time.monotonic()
+ vault = self.server.vault
if self.path == "/api/connect":
- result = connect_token(self.server.vault, code, data.get("token"))
+ code = store.validate_code(data.get("connector"))
+ result = self.server.flows.start(code, sign_in_for(vault, code))
+ elif self.path == "/api/custom":
+ result = self.custom(data)
elif self.path == "/api/disconnect":
- self.server.vault.disconnect(code)
- result = self.server.vault.status(code)
+ code = store.validate_code(data.get("connector"))
+ disconnect(vault, code)
+ result = {"connector": code, "state": "not_connected"}
else:
self.reply(404, {"error": "Not found."})
return
@@ -193,6 +262,20 @@ class PageHandler(BaseHTTPRequestHandler):
except (OSError, TimeoutError):
self.reply(503, {"error": "Connection unavailable. Try again."})
+ def custom(self, data):
+ """Add custom: a remote MCP server, signed in like any other when it asks."""
+ name = store.text(data.get("name"), 64).strip()
+ url = store.clean_url((data.get("url") or "").strip())
+ headers = store.clean_headers(data.get("headers") or {})
+ if not name:
+ raise store.StoreError("Give the server a name.")
+ vault = self.server.vault
+ code = custom_code(name, set(vault.tokens()) | set(store.CATALOG))
+ if headers:
+ finish(vault, code, {"mcp_entry": {"url": url, "headers": headers}, "obtained_at": int(time.time())}, label=name)
+ return {"connector": code, "state": "connected"}
+ return self.server.flows.start(code, oauth.SignIn(vault, url), label=name)
+
def running_page(vault):
data = store.read_private(vault.root / "page.json")
@@ -224,9 +307,16 @@ def forget_page(vault, identity):
path.unlink(missing_ok=True)
-def open_page():
- browser = shutil.which("hn-browser")
+def browse(url):
+ browser = shutil.which("hn-browser") or shutil.which("xdg-open")
if not browser:
+ return False
+ subprocess.Popen([browser, url], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ return True
+
+
+def open_page():
+ if not shutil.which("hn-browser"):
raise store.StoreError("Open this page on a Harness computer, or run 'connections.py serve' for local review.")
vault = store.Store()
with store.locked(vault.root):
@@ -243,33 +333,73 @@ def open_page():
time.sleep(0.1)
if not url:
raise store.StoreError("Could not open Connections.")
- subprocess.Popen([browser, url], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ browse(url)
print("Connections opened in the browser.")
+def connect_here(code):
+ """Sign in from the terminal: the same flow as the page, waited for here."""
+ vault = store.Store()
+ sign_in = sign_in_for(vault, store.validate_code(code))
+ url = sign_in.prepare()
+ if url:
+ print("Opening the sign-in page. If it does not open, visit:\n" + url, flush=True)
+ browse(url)
+ finish(vault, code, sign_in.wait())
+ print(f"{store.SERVICES[code]} connected. Agents can use it now.")
+ return 0
+
+
+def serve(argv):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("serve")
+ parser.add_argument("--port", type=int, default=0)
+ parser.add_argument("--background", action="store_true")
+ args = parser.parse_args(argv)
+ with PageServer(port=args.port) as server:
+ identity = {"port": server.server_address[1], "key": server.key}
+ store.write_private(server.vault.root / "page.json", identity)
+ try:
+ if not args.background:
+ print(server.origin + "/#" + server.key, flush=True)
+ server.serve_until_idle()
+ finally:
+ with contextlib.suppress(store.StoreError, OSError):
+ forget_page(server.vault, identity)
+ return 0
+
+
def main(argv):
try:
if not argv or argv == ["open"]:
open_page()
return 0
- if argv[0] != "serve":
- return connector.main(argv)
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("serve")
- parser.add_argument("--port", type=int, default=0)
- parser.add_argument("--background", action="store_true")
- args = parser.parse_args(argv)
- with PageServer(port=args.port) as server:
- identity = {"port": server.server_address[1], "key": server.key}
- store.write_private(server.vault.root / "page.json", identity)
- try:
- if not args.background:
- print(server.origin + "/#" + server.key, flush=True)
- server.serve_until_idle()
- finally:
- with contextlib.suppress(store.StoreError, OSError):
- forget_page(server.vault, identity)
- return 0
+ command = argv[0]
+ if command == "serve":
+ return serve(argv)
+ if command == "connect" and len(argv) == 2:
+ return connect_here(argv[1])
+ if command == "disconnect" and len(argv) == 2:
+ disconnect(store.Store(), store.validate_code(argv[1]))
+ print("Disconnected on this computer. Revoke access at the provider to remove it elsewhere.")
+ return 0
+ if command == "sync" and len(argv) == 1:
+ changed = agents.sync(store.Store())
+ print("Agents updated: " + (", ".join(sorted(changed)) or "none installed"))
+ return 0
+ if command == "refresh" and len(argv) <= 2:
+ vault = store.Store()
+ if len(argv) == 2:
+ renew.refresh(vault, store.validate_code(argv[1]), force=True)
+ return 0
+ failed = renew.refresh_due(vault)
+ for code, error in failed.items():
+ print(f"{code}: {error}", file=sys.stderr)
+ return 3 if failed else 0
+ if command == "bridge":
+ import bridge
+ return bridge.main(argv[1:])
+ return connector.main(argv)
except (store.StoreError, OSError) as error:
print(str(error) if isinstance(error, store.StoreError) else "Could not open Connections.", file=sys.stderr)
return 1
diff --git a/os/connectors/connector.py b/os/connectors/connector.py
index 189c77f23..398ced0c6 100644
--- a/os/connectors/connector.py
+++ b/os/connectors/connector.py
@@ -9,10 +9,13 @@ the response body. Tokens stay out of routine tool output. This is not a
security boundary against arbitrary code running as the same Unix user.
Usage:
- harness connections Open account settings
+ harness connections Open the Connectors page
+ harness connections connect <code> Sign in from the terminal
harness connections list [--json]
harness connections info <code>
harness connections disconnect <code>
+ harness connections refresh [<code>] Renew tokens that are due
+ harness connections sync Give agents their connections again
harness connections call <code> <METHOD> <url> [options]
Options for `call`:
@@ -48,24 +51,25 @@ MAX_RESPONSE_BYTES = 8 * 1024 * 1024
# Official API hosts per connector. A credential is only ever sent to one of
# these (exact host or a subdomain of it). A connector that is not listed is
# refused: the helper never sends a credential to a host it cannot vouch for.
+# Services signed in through the connector gateway hold an ordinary OAuth token
+# for their REST API. A service signed in from this computer (MCP OAuth) holds a
+# token for its MCP server instead: agents use it through their MCP tools.
OFFICIAL_HOSTS = {
"gmail": ("googleapis.com",),
"google_calendar": ("googleapis.com",),
"google_drive": ("googleapis.com",),
- "facebook": ("graph.facebook.com",),
- "figma": ("api.figma.com",),
- "figma-api": ("api.figma.com",),
+ "google_bigquery": ("googleapis.com",),
"github": ("api.github.com",),
- "ahrefs": ("api.ahrefs.com",),
- "notion": ("api.notion.com",),
- "linear": ("api.linear.app",),
+ "slack": ("slack.com",),
"asana": ("app.asana.com",),
+ "hubspot": ("api.hubapi.com",),
+ "pagerduty": ("api.pagerduty.com",),
+ "microsoft_365": ("graph.microsoft.com",),
}
-GOOGLE_CODES = ("gmail", "google_calendar", "google_drive")
# Connectors whose API only accepts the credential as a query parameter on
-# some endpoints (Facebook feed-post DELETE, debug_token).
-TOKEN_PARAM_CODES = ("facebook",)
+# some endpoints. None of the current services need it.
+TOKEN_PARAM_CODES = ()
# Files that may be uploaded with `--form K=@path`: media and documents only,
# never from a directory that holds credentials or device configuration.
@@ -105,70 +109,52 @@ def load_json(path):
raise Failure(3, f"cannot read {path.name}: {type(e).__name__}")
-def load_entry(code):
- """Return the stored entry for a connector, or None when it is not linked."""
- return store.Store(CONFIGS_DIR).load(code)
-
-
-def account_of(entry):
- creds = entry.get("credentials") or {}
- if entry.get("auth_type") == "pat" and creds.get("email"):
- return creds["email"]
- return entry.get("user_email") or creds.get("email") or ""
+def vault():
+ return store.Store(CONFIGS_DIR)
def cmd_list(as_json=False):
"""Discover the same per-user connections regardless of the current agent."""
- found = 0
- problems = []
- records = []
- for code in store.SERVICES:
- try:
- entry = load_entry(code)
- if entry:
- records.append(store.Store(CONFIGS_DIR).status(code))
- except (Failure, store.StoreError) as e:
- problems.append(str(e))
- continue
- if entry:
- found += 1
- if not as_json:
- print(describe(code, entry))
- for p in problems:
- print(f"verification failed: {p}", file=sys.stderr)
- if problems:
+ try:
+ tokens = vault().tokens()
+ except store.StoreError as e:
+ print(f"verification failed: {e}", file=sys.stderr)
return 3
+ records = [vault().status(code, token) for code, token in sorted(tokens.items())]
if as_json:
print(json.dumps(records))
- elif not found:
+ elif not records:
print("no connectors linked")
+ for record in [] if as_json else records:
+ print(describe(record))
return 0
-def describe(code, entry):
- parts = [account_of(entry), entry.get("auth_type") or "oauth"]
- state = "expired" if entry.get("expires_at") and entry["expires_at"] <= time.time() else "connected"
- return f"{code}: {state} (" + ", ".join(p for p in parts if p) + ")"
+def describe(record):
+ how = "MCP tools" if record["tools"] else "harness connections call"
+ parts = [record.get("account"), how]
+ return f"{record['connector']}: {record['state']} (" + ", ".join(p for p in parts if p) + ")"
def cmd_info(code):
- entry = load_entry(code)
- if not entry:
+ token = vault().token(code)
+ if not token:
raise Failure(3, f"{code}: not connected")
- expires = int(entry.get("expires_at") or 0)
+ record = vault().status(code, token)
+ expires = int(token.get("expires_at") or 0)
info = {
"connector": code,
- "auth_type": entry.get("auth_type") or "oauth",
- "account": account_of(entry),
- "scopes": entry.get("scopes") or [],
- "auto_refresh": store.Store(CONFIGS_DIR).status(code)["auto_refresh"],
+ "name": record["name"],
+ "state": record["state"],
+ "account": record.get("account", ""),
+ "signed_in_through": "Harness account" if token.get("source") == "gateway" else "this computer",
+ "scopes": record["scopes"],
+ "agent_tools": record["tools"],
+ "rest_call": code in OFFICIAL_HOSTS and token.get("source") == "gateway",
+ "auto_refresh": record["auto_refresh"],
"expires": "not reported" if not expires else fmt_time(expires),
- "expired": bool(expires) and expires < time.time(),
- "obtained": fmt_time(entry.get("obtained_at")),
+ "obtained": fmt_time(token.get("obtained_at")),
}
- page_id = (entry.get("credentials") or {}).get("page_id")
- if page_id:
- info["page_id"] = page_id
print(json.dumps(info, indent=2))
return 0
@@ -281,10 +267,10 @@ def cmd_call(code, method, url, args, *, entry_override=None):
if opts["token_param"] and code not in TOKEN_PARAM_CODES:
raise Failure(2, f"--token-param is only for {', '.join(TOKEN_PARAM_CODES)}")
- entry = entry_override if entry_override is not None else store.Store(CONFIGS_DIR).ready(code)
- if code in GOOGLE_CODES and entry.get("auth_type") == "pat":
- raise Failure(3, f"{code}: linked with an app password; Google REST APIs reject it — use IMAP/SMTP (see SKILL.md)")
- token = entry.get("access_token") or entry.get("api_key")
+ entry = entry_override if entry_override is not None else vault().ready(code)
+ if entry.get("source") not in (None, "gateway"):
+ raise Failure(3, f"{code}: this account's token is for its MCP server; use the agent's {code} tools")
+ token = entry.get("access_token")
if not token:
raise Failure(3, f"{code}: linked but no usable credential stored")
@@ -296,17 +282,12 @@ def cmd_call(code, method, url, args, *, entry_override=None):
)
headers = {"Accept": "application/json", "User-Agent": "Harness-Connections"}
- if code == "notion":
- headers["Notion-Version"] = "2022-06-28"
for k, v in opts["header"]:
- if k.lower() in ("authorization", "host", "proxy-authorization", "cookie", "x-figma-token"):
+ if k.lower() in ("authorization", "host", "proxy-authorization", "cookie"):
raise Failure(2, f"do not pass {k}; the helper sets it (or it is not allowed)")
headers[k] = v
if not opts["token_param"]:
- if code in ("figma", "figma-api") and entry.get("auth_type") == "pat":
- headers["X-Figma-Token"] = token
- else:
- headers["Authorization"] = token if code == "linear" and entry.get("auth_type") == "pat" else "Bearer " + token
+ headers["Authorization"] = store.bearer(entry)
body = None
if opts["json"] is not None:
@@ -378,7 +359,7 @@ def main(argv):
if len(argv) >= 4 and argv[0] == "call":
return cmd_call(argv[1], argv[2], argv[3], argv[4:])
if len(argv) == 2 and argv[0] == "disconnect":
- store.Store(CONFIGS_DIR).disconnect(argv[1])
+ vault().disconnect(argv[1])
print("Disconnected on this computer. Revoke access at the provider to remove it elsewhere.")
return 0
print(__doc__.split("\n\n", 2)[2], file=sys.stderr)
diff --git a/os/connectors/gateway.py b/os/connectors/gateway.py
new file mode 100644
index 000000000..2bc42614c
--- /dev/null
+++ b/os/connectors/gateway.py
@@ -0,0 +1,148 @@
+"""The Autonomous connector gateway, for services that do not let a computer
+register itself (Grid's `app` path). The gateway holds the service's OAuth app;
+this computer starts a sign-in, polls for its one-time result and stores the
+token like any other. It needs the Grid session `harness login` keeps in
+~/.grid/credentials.toml, as the Harness CLI's model catalog does.
+"""
+import json
+import os
+from pathlib import Path
+import re
+import time
+import urllib.error
+import urllib.request
+
+import connection_store as store
+
+TIMEOUT = 20
+DEFAULT_API = "https://api-grid.autonomous.ai"
+_OPENER = urllib.request.build_opener(store.NoRedirect, urllib.request.ProxyHandler({}))
+
+
+class GatewayError(store.StoreError):
+ pass
+
+
+def credentials_path():
+ configured = os.environ.get("GRID_HOME")
+ home = Path(configured).expanduser() if configured else Path.home() / ".grid"
+ return home / "credentials.toml"
+
+
+def session():
+ """(api_url, session_token) from the top table of credentials.toml, or None."""
+ try:
+ top = re.split(r"^\s*\[", credentials_path().read_text(), maxsplit=1, flags=re.M)[0]
+ except OSError:
+ return None
+
+ def value(name):
+ match = re.search(rf'^\s*{name}\s*=\s*("(?:[^"\\]|\\.)*"|\'[^\']*\')\s*$', top, re.M)
+ if not match:
+ return ""
+ raw = match.group(1)
+ try:
+ return json.loads(raw) if raw[0] == '"' else raw[1:-1]
+ except ValueError:
+ return ""
+
+ token = value("session_token")
+ if not token:
+ return None
+ base = value("api_url") or os.environ.get("GRID_CONTROL_PLANE_URL") or DEFAULT_API
+ store.clean_url(base)
+ return base.rstrip("/"), token
+
+
+def call(path, body=None):
+ found = session()
+ if not found:
+ raise GatewayError("Sign in to Harness first (harness login) to connect this service.")
+ base, token = found
+ request = urllib.request.Request(f"{base}/v1/grid/{path}", method="POST" if body is not None else "GET",
+ data=json.dumps(body).encode() if body is not None else None, headers={
+ "Authorization": "Bearer " + token, "Accept": "application/json",
+ "Content-Type": "application/json", "User-Agent": "Harness-Connections"})
+ try:
+ with _OPENER.open(request, timeout=TIMEOUT) as response:
+ data = json.loads(response.read(store.MAX_BYTES))
+ except urllib.error.HTTPError as error:
+ with error:
+ if error.code in (401, 403):
+ raise GatewayError("Your Harness sign-in has expired. Run harness login, then try again.")
+ raise GatewayError(f"The connector service answered {error.code}. Try again shortly.")
+ except (urllib.error.URLError, OSError, ValueError):
+ raise GatewayError("Could not reach the connector service. Check the connection and try again.")
+ if not isinstance(data, dict):
+ raise GatewayError("The connector service sent an unexpected answer.")
+ return data
+
+
+def available():
+ """{code: row} the gateway offers to this account; empty when signed out or offline."""
+ try:
+ rows = call("connectors").get("connectors")
+ except GatewayError:
+ return {}
+ return {row["code"]: row for row in rows or [] if isinstance(row, dict) and isinstance(row.get("code"), str)}
+
+
+def token_from(payload, previous=None):
+ access = payload.get("access_token")
+ if not isinstance(access, str) or not access:
+ raise GatewayError("The connector service did not return a token.")
+ expires = payload.get("expires_at")
+ token = {"access_token": access, "token_type": payload.get("token_type") or "Bearer",
+ "refresh_token": payload.get("refresh_token") or "",
+ "expires_at": expires if type(expires) is int and expires > 0 else 0,
+ "scope": payload.get("scope") if isinstance(payload.get("scope"), str) else "",
+ "account_name": payload.get("account_name") or (previous or {}).get("account_name", ""),
+ "source": "gateway", "obtained_at": int(time.time())}
+ if payload.get("refresh") is True or (payload.get("refresh") is None and token["refresh_token"]):
+ token["refresh"] = True
+ mcp = payload.get("mcp_entry")
+ if isinstance(mcp, dict) and mcp.get("url"):
+ token["mcp_entry"] = {"url": mcp["url"], "headers": mcp.get("headers") or {"Authorization": store.bearer(token)}}
+ return token
+
+
+class SignIn:
+ def __init__(self, code):
+ self.code = code
+
+ def prepare(self):
+ started = call("connectors/start", {"connector": self.code})
+ self.pickup = started.get("pickup_code")
+ url = started.get("authorize_url")
+ if not isinstance(self.pickup, str) or not isinstance(url, str) or not url.startswith("https://"):
+ raise GatewayError("The connector service could not start this sign-in.")
+ self.interval = min(max(int(started.get("poll_interval") or 2), 1), 60)
+ self.expires = min(max(int(started.get("expires_in") or 600), 30), 3600)
+ return url
+
+ def wait(self, cancelled=lambda: False):
+ deadline = time.monotonic() + self.expires
+ while time.monotonic() < deadline and not cancelled():
+ result = call("connectors/poll", {"pickup_code": self.pickup})
+ status = result.get("status")
+ if status == "ready":
+ return token_from(result)
+ if status in ("failed", "expired", "consumed"):
+ raise GatewayError(result.get("error") or "The sign-in did not finish. Try again.")
+ if status != "pending":
+ raise GatewayError("The connector service sent an unexpected answer.")
+ time.sleep(self.interval)
+ raise GatewayError("The sign-in was not finished in time.")
+
+
+def refresh(code, token):
+ # The gateway holds the refresh token and the app's secret. A refused session
+ # keeps the stored token, as Grid does: signing in again fixes it.
+ return token_from(call("connectors/refresh", {"connector": code}), previous=token)
+
+
+def disconnect(code):
+ try:
+ call("connectors/disconnect", {"connector": code})
+ except GatewayError:
+ pass # Forgetting it here is what was asked; the gateway copy expires on its own.
diff --git a/os/connectors/oauth.py b/os/connectors/oauth.py
new file mode 100644
index 000000000..adcbe6fb3
--- /dev/null
+++ b/os/connectors/oauth.py
@@ -0,0 +1,288 @@
+"""Sign in to an MCP server from this computer: MCP OAuth with dynamic client
+registration (RFC 7591), PKCE S256 and a 127.0.0.1 redirect — Grid's `dcr` path.
+
+No client secret ships with Harness: each computer registers its own public
+client with the service and keeps it in clients.json.
+"""
+import base64
+import hashlib
+from http.server import BaseHTTPRequestHandler, HTTPServer
+import json
+import re
+import secrets
+import threading
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+
+import connection_store as store
+
+TIMEOUT = 15
+SIGN_IN_SECONDS = 300
+# Grid's preferred loopback ports, then any free one.
+PORTS = (51789, 51790, 51791, 51792)
+_OPENER = urllib.request.build_opener(store.NoRedirect, urllib.request.ProxyHandler({}))
+
+
+class SignInError(store.StoreError):
+ pass
+
+
+def http(url, data=None, headers=None, method=None):
+ """(status, headers, body) without following redirects or raising on HTTP errors."""
+ request = urllib.request.Request(url, data=data, method=method, headers={
+ "User-Agent": "Harness-Connections", "Accept": "application/json", **(headers or {})})
+ try:
+ with _OPENER.open(request, timeout=TIMEOUT) as response:
+ return response.status, response.headers, response.read(store.MAX_BYTES)
+ except urllib.error.HTTPError as error:
+ with error:
+ return error.code, error.headers, error.read(store.MAX_BYTES)
+ except (urllib.error.URLError, OSError, ValueError):
+ raise SignInError("Could not reach the service. Check the connection and try again.")
+
+
+def json_of(body):
+ try:
+ data = json.loads(body)
+ except ValueError:
+ return None
+ return data if isinstance(data, dict) else None
+
+
+def well_known(base, name, path=""):
+ parsed = urllib.parse.urlsplit(base)
+ return f"{parsed.scheme}://{parsed.netloc}/.well-known/{name}{path.rstrip('/')}"
+
+
+def probe(url):
+ """What signing in to this MCP server takes: {'kind': 'open'} or OAuth metadata."""
+ url = store.clean_url(url)
+ initialize = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
+ "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "Harness", "version": "1"}}}).encode()
+ status, headers, _ = http(url, initialize, {"Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream"})
+ if 200 <= status < 300:
+ return {"kind": "open"}
+ if status not in (401, 403):
+ raise SignInError(f"The server answered {status}. Check the address.")
+ challenge = headers.get("WWW-Authenticate", "")
+ match = re.search(r'resource_metadata="([^"]+)"', challenge)
+ path = urllib.parse.urlsplit(url).path
+ candidates = [match.group(1)] if match else []
+ candidates += [well_known(url, "oauth-protected-resource", path), well_known(url, "oauth-protected-resource")]
+ resource, issuer, scopes = url, None, []
+ for candidate in candidates:
+ status, _, body = http(candidate)
+ meta = json_of(body) if status == 200 else None
+ if meta and isinstance(meta.get("authorization_servers"), list) and meta["authorization_servers"]:
+ issuer = meta["authorization_servers"][0]
+ resource = meta.get("resource") or url
+ scopes = [s for s in meta.get("scopes_supported") or [] if isinstance(s, str)]
+ break
+ issuer = issuer or "{0.scheme}://{0.netloc}".format(urllib.parse.urlsplit(url))
+ issuer_path = urllib.parse.urlsplit(issuer).path
+ for candidate in (well_known(issuer, "oauth-authorization-server", issuer_path),
+ well_known(issuer, "openid-configuration", issuer_path),
+ issuer.rstrip("/") + "/.well-known/openid-configuration"):
+ status, _, body = http(candidate)
+ meta = json_of(body) if status == 200 else None
+ if meta and meta.get("authorization_endpoint") and meta.get("token_endpoint"):
+ for key in ("authorization_endpoint", "token_endpoint", "registration_endpoint"):
+ if meta.get(key):
+ store.clean_url(meta[key])
+ return {
+ "kind": "oauth", "issuer": issuer, "resource": resource, "scopes": scopes,
+ "authorization_endpoint": meta["authorization_endpoint"], "token_endpoint": meta["token_endpoint"],
+ "registration_endpoint": meta.get("registration_endpoint"),
+ "s256": "S256" in (meta.get("code_challenge_methods_supported") or ["S256"]),
+ "auth_methods": meta.get("token_endpoint_auth_methods_supported") or ["client_secret_basic"],
+ }
+ raise SignInError("This server does not say how to sign in.")
+
+
+class Callback(HTTPServer):
+ """One sign-in's redirect target on 127.0.0.1."""
+
+ def __init__(self, port):
+ self.result = None
+ self.done = threading.Event()
+ super().__init__(("127.0.0.1", port), CallbackHandler)
+ self.timeout = 1
+
+ @property
+ def redirect_uri(self):
+ return f"http://127.0.0.1:{self.server_address[1]}/callback"
+
+
+class CallbackHandler(BaseHTTPRequestHandler):
+ def log_message(self, *_args):
+ pass
+
+ def do_GET(self):
+ parsed = urllib.parse.urlsplit(self.path)
+ if parsed.path != "/callback":
+ self.send_error(404)
+ return
+ query = dict(urllib.parse.parse_qsl(parsed.query))
+ self.server.result = query
+ ok = "code" in query
+ page = ("<!doctype html><meta charset=utf-8><title>Harness</title>"
+ "<body style='font:16px ui-monospace,monospace;background:#11140f;color:#e7e8de;padding:48px'>"
+ + ("<h1>Connected.</h1><p>You can close this tab and return to Harness.</p><script>setTimeout(()=>window.close(),800)</script>"
+ if ok else "<h1>Not connected.</h1><p>Return to Harness and try again.</p>")).encode()
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html; charset=utf-8")
+ self.send_header("Content-Length", str(len(page)))
+ self.send_header("Cache-Control", "no-store")
+ self.end_headers()
+ self.wfile.write(page)
+ self.server.done.set()
+
+
+def listen():
+ for port in PORTS + (0,):
+ try:
+ return Callback(port)
+ except OSError:
+ continue
+ raise SignInError("Could not open a local sign-in address.")
+
+
+def pkce():
+ verifier = secrets.token_urlsafe(48)
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
+ return verifier, challenge
+
+
+def register(vault, meta, redirect_uri):
+ """This computer's OAuth client for the issuer, registered once and reused."""
+ known = vault.client(meta["issuer"])
+ if known and known.get("redirect_uri") == redirect_uri and known.get("client_id"):
+ return known
+ if not meta.get("registration_endpoint"):
+ raise SignInError("This service does not let a computer register itself.")
+ status, _, body = http(meta["registration_endpoint"], json.dumps({
+ "client_name": "Harness", "redirect_uris": [redirect_uri],
+ "grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"],
+ "token_endpoint_auth_method": "none", "application_type": "native",
+ }).encode(), {"Content-Type": "application/json"})
+ data = json_of(body)
+ if status not in (200, 201) or not data or not isinstance(data.get("client_id"), str):
+ raise SignInError("The service refused to register Harness on this computer.")
+ secret = data.get("client_secret") if isinstance(data.get("client_secret"), str) else ""
+ method = data.get("token_endpoint_auth_method") or ("client_secret_basic" if secret else "none")
+ client = {"client_id": data["client_id"], "client_secret": secret, "token_endpoint_auth_method": method,
+ "authorization_endpoint": meta["authorization_endpoint"], "token_endpoint": meta["token_endpoint"],
+ "redirect_uri": redirect_uri, "registered_at": int(time.time())}
+ vault.save_client(meta["issuer"], client)
+ return client
+
+
+def token_request(client, form):
+ headers = {"Content-Type": "application/x-www-form-urlencoded"}
+ form = dict(form, client_id=client["client_id"])
+ if client.get("client_secret"):
+ if client.get("token_endpoint_auth_method") == "client_secret_post":
+ form["client_secret"] = client["client_secret"]
+ else:
+ pair = f"{urllib.parse.quote(client['client_id'])}:{urllib.parse.quote(client['client_secret'])}"
+ headers["Authorization"] = "Basic " + base64.b64encode(pair.encode()).decode()
+ status, _, body = http(client["token_endpoint"], urllib.parse.urlencode(form).encode(), headers)
+ data = json_of(body) or {}
+ if status != 200 or not isinstance(data.get("access_token"), str):
+ error = data.get("error") if isinstance(data.get("error"), str) else ""
+ raise SignInError("invalid_grant" if error == "invalid_grant" else "The service did not issue a token.")
+ return data
+
+
+def token_from(data, mcp_url, issuer, previous=None):
+ now = int(time.time())
+ expires_in = data.get("expires_in")
+ token = {
+ "access_token": data["access_token"], "token_type": data.get("token_type") or "Bearer",
+ "refresh_token": data.get("refresh_token") or (previous or {}).get("refresh_token", ""),
+ "expires_at": now + int(expires_in) if isinstance(expires_in, (int, float)) and expires_in > 0 else 0,
+ "scope": data.get("scope") if isinstance(data.get("scope"), str) else (previous or {}).get("scope", ""),
+ "source": "dcr", "issuer": issuer, "obtained_at": now,
+ "account_name": (previous or {}).get("account_name", ""),
+ }
+ token["mcp_entry"] = {"url": mcp_url, "headers": {"Authorization": store.bearer(token)}}
+ if token["refresh_token"]:
+ token["refresh"] = True
+ return token
+
+
+class SignIn:
+ """One browser sign-in: prepare() returns the address to open, wait() the token."""
+
+ def __init__(self, vault, mcp_url):
+ self.vault, self.mcp_url = vault, store.clean_url(mcp_url)
+ self.server = None
+
+ def prepare(self):
+ self.meta = probe(self.mcp_url)
+ if self.meta["kind"] == "open":
+ return None
+ if not self.meta["s256"]:
+ raise SignInError("This service does not support a secure sign-in from a computer.")
+ self.server = listen()
+ try:
+ self.client = register(self.vault, self.meta, self.server.redirect_uri)
+ except BaseException:
+ self.server.server_close()
+ raise
+ self.verifier, challenge = pkce()
+ self.state = secrets.token_urlsafe(24)
+ query = {"response_type": "code", "client_id": self.client["client_id"], "redirect_uri": self.server.redirect_uri,
+ "state": self.state, "code_challenge": challenge, "code_challenge_method": "S256"}
+ if self.meta.get("resource"):
+ query["resource"] = self.meta["resource"]
+ if self.meta.get("scopes"):
+ query["scope"] = " ".join(self.meta["scopes"])
+ separator = "&" if "?" in self.client["authorization_endpoint"] else "?"
+ return self.client["authorization_endpoint"] + separator + urllib.parse.urlencode(query)
+
+ def wait(self, cancelled=lambda: False):
+ if self.server is None:
+ return {"mcp_entry": {"url": self.mcp_url, "headers": {}}, "source": "dcr", "obtained_at": int(time.time())}
+ try:
+ deadline = time.monotonic() + SIGN_IN_SECONDS
+ while not self.server.done.is_set():
+ if time.monotonic() > deadline or cancelled():
+ raise SignInError("The sign-in was not finished in time.")
+ self.server.handle_request()
+ finally:
+ self.server.server_close()
+ result = self.server.result or {}
+ if not secrets.compare_digest(result.get("state", ""), self.state):
+ raise SignInError("The sign-in could not be confirmed. Try again.")
+ if "code" not in result:
+ raise SignInError("The sign-in was cancelled." if result.get("error") == "access_denied"
+ else "The service did not complete the sign-in.")
+ form = {"grant_type": "authorization_code", "code": result["code"],
+ "redirect_uri": self.server.redirect_uri, "code_verifier": self.verifier}
+ if self.meta.get("resource"):
+ form["resource"] = self.meta["resource"]
+ return token_from(token_request(self.client, form), self.mcp_url, self.meta["issuer"])
+
+
+def refresh(vault, token):
+ """A renewed dcr token, through this computer's registered client."""
+ client = vault.client(token.get("issuer", ""))
+ if not client or not token.get("refresh_token"):
+ raise SignInError("invalid_grant")
+ mcp_url = token["mcp_entry"]["url"]
+ form = {"grant_type": "refresh_token", "refresh_token": token["refresh_token"]}
+ form["resource"] = mcp_url
+ try:
+ data = token_request(client, form)
+ except SignInError as error:
+ if str(error) != "invalid_grant":
+ # A service may reject the resource parameter on refresh; ask once more without it.
+ del form["resource"]
+ data = token_request(client, form)
+ else:
+ raise
+ return token_from(data, mcp_url, token["issuer"], previous=token)
diff --git a/os/connectors/renew.py b/os/connectors/renew.py
new file mode 100644
index 000000000..a3aaa5e4e
--- /dev/null
+++ b/os/connectors/renew.py
@@ -0,0 +1,41 @@
+"""Renewing tokens before they expire, once across every agent and the bridge."""
+import connection_store as store
+import gateway
+import oauth
+
+
+def refresh(vault, code, force=False):
+ """The connection's token, renewed if it is due (or forced). A revoked grant
+ marks the connection for reconnecting instead of failing every request."""
+ with store.locked(vault.root):
+ token = vault.token(code)
+ if not token:
+ raise store.StoreError("Not connected. Open harness connections to connect an account.")
+ # Another process may have renewed it while this one waited for the lock.
+ if not (force and store.refreshable(token)) and not store.needs_refresh(token):
+ return token
+ try:
+ renewed = gateway.refresh(code, token) if token.get("source") == "gateway" else oauth.refresh(vault, token)
+ except store.StoreError as error:
+ if str(error) != "invalid_grant":
+ raise
+ token["needs_reconnect"] = True
+ vault.put(code, token)
+ raise store.StoreError("This account needs to be connected again in Connections.")
+ for key in ("label", "account_name"):
+ if token.get(key) and not renewed.get(key):
+ renewed[key] = token[key]
+ vault.put(code, renewed)
+ return vault.token(code)
+
+
+def refresh_due(vault):
+ """Renew every connection that is due; {code: error} for the ones that failed."""
+ failed = {}
+ for code, token in vault.tokens().items():
+ if store.needs_refresh(token):
+ try:
+ refresh(vault, code)
+ except store.StoreError as error:
+ failed[code] = str(error)
+ return failed
diff --git a/os/connectors/web/index.html b/os/connectors/web/index.html
index d44a75c00..26be57bc2 100644
--- a/os/connectors/web/index.html
+++ b/os/connectors/web/index.html
@@ -2,26 +2,50 @@
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
-<title>Connections · Harness</title>
+<title>Connectors · Harness</title>
<link rel="stylesheet" href="/style.css">
<script src="/page.js" defer></script>
<body>
<main>
- <header><span class="brand">harness<span> / connections</span></span></header>
- <h1>Connect once.<br>Work with any agent.</h1>
- <p class="intro">Your connected accounts, available to agents on this computer.</p>
+ <header>
+ <h1>Connectors</h1>
+ <p class="intro">Connect your agents to tools outside this computer: a tracker, a design tool, a web service.</p>
+ </header>
+ <div class="toolbar">
+ <input id="search" type="search" placeholder="Search connectors" autocomplete="off" spellcheck="false" aria-label="Search connectors">
+ <button id="reload" class="icon" type="button" title="Refresh" aria-label="Refresh">↻</button>
+ <button id="add" class="primary" type="button">+ Add custom</button>
+ </div>
+ <div class="pills" role="tablist">
+ <button id="browse" class="pill selected" type="button" role="tab" aria-selected="true">Browse</button>
+ <button id="connected" class="pill" type="button" role="tab" aria-selected="false">Connected</button>
+ </div>
<p id="notice" role="status" aria-live="polite"></p>
- <div id="connections" aria-label="Connected services"></div>
- <footer>Connections stay on this computer. You choose what each service can access.</footer>
+ <div id="sections"></div>
+ <footer>Accounts stay on this computer and are shared by every agent you run here. Disconnecting stops Harness from using an account; revoke it in the service's settings to remove it everywhere.</footer>
</main>
-<dialog id="connect-dialog">
- <form id="connect-form">
- <h2 id="service-name">Connect</h2>
- <p>Use a token from your account. <a id="manage-link" target="_blank" rel="noreferrer">Manage permissions ↗</a></p>
- <label for="token">Access token</label>
- <input id="token" type="password" autocomplete="off" spellcheck="false" required maxlength="8192">
- <p id="connect-error" role="status" aria-live="polite"></p>
- <div class="actions"><button type="button" id="cancel">Cancel</button><button class="primary" id="save" type="submit">Connect</button></div>
+<dialog id="custom-dialog">
+ <form id="custom-form">
+ <h2>Add custom</h2>
+ <p>A remote MCP server. If it asks you to sign in, Harness opens the service's sign-in page.</p>
+ <label for="custom-name">Name</label>
+ <input id="custom-name" required maxlength="64" autocomplete="off" spellcheck="false">
+ <label for="custom-url">Remote MCP server URL</label>
+ <input id="custom-url" type="url" required maxlength="2048" placeholder="https://example.com/mcp" autocomplete="off" spellcheck="false">
+ <details>
+ <summary>Advanced</summary>
+ <label for="custom-headers">Headers (Name: value, one per line)</label>
+ <textarea id="custom-headers" rows="3" placeholder="Authorization: Bearer …" spellcheck="false"></textarea>
+ </details>
+ <p id="custom-error" class="error" role="status" aria-live="polite"></p>
+ <div class="actions"><button type="button" id="custom-cancel">Cancel</button><button class="primary" id="custom-save" type="submit">Continue</button></div>
+ </form>
+</dialog>
+<dialog id="confirm-dialog">
+ <form id="confirm-form">
+ <h2 id="confirm-title">Disconnect</h2>
+ <p>Agents on this computer stop using this account. To revoke it everywhere, use the service's settings.</p>
+ <div class="actions"><button type="button" id="confirm-cancel">Cancel</button><button class="danger" type="submit">Disconnect</button></div>
</form>
</dialog>
</body>
diff --git a/os/connectors/web/page.js b/os/connectors/web/page.js
index 975ec45ef..15f5bbf07 100644
--- a/os/connectors/web/page.js
+++ b/os/connectors/web/page.js
@@ -2,14 +2,13 @@
let key = location.hash.slice(1) || sessionStorage.getItem("harness-connections") || "";
if (key) sessionStorage.setItem("harness-connections", key);
history.replaceState(null, "", location.pathname);
-const list = document.querySelector("#connections");
-const notice = document.querySelector("#notice");
-const dialog = document.querySelector("#connect-dialog");
-const form = document.querySelector("#connect-form");
-const input = document.querySelector("#token");
-const save = document.querySelector("#save");
-const error = document.querySelector("#connect-error");
-let selected = null;
+const $ = (selector) => document.querySelector(selector);
+const sections = $("#sections");
+const notice = $("#notice");
+const search = $("#search");
+let items = [];
+let view = "browse";
+const pending = new Map(); // connector -> flow id
async function request(path, body) {
const response = await fetch(path, {
@@ -23,71 +22,176 @@ async function request(path, body) {
}
function node(tag, text, className) {
const element = document.createElement(tag);
- element.textContent = text;
+ if (text) element.textContent = text;
if (className) element.className = className;
return element;
}
-function connect(item) {
- selected = item.connector;
- document.querySelector("#service-name").textContent = "Connect " + item.name;
- document.querySelector("#manage-link").href = item.manage_url;
- error.textContent = "";
- input.value = "";
- dialog.showModal();
- input.focus();
+function mark(item) {
+ const tile = node("span", (item.name || "?").trim().charAt(0).toUpperCase(), "mark");
+ tile.style.background = item.color || "#59634b";
+ return tile;
+}
+function card(item) {
+ const connected = item.state === "connected";
+ const box = node("article", "", "card" + (connected ? " on" : ""));
+ const head = node("div", "", "card-head");
+ head.append(mark(item), node("h3", item.name));
+ if (connected) head.append(node("span", item.account || "Signed in", "badge"));
+ if (item.state === "reconnect") head.append(node("span", "Reconnect", "badge warn"));
+ const actions = node("div", "", "card-actions");
+ const waiting = pending.has(item.connector);
+ if (waiting) {
+ actions.append(node("span", "Waiting for sign-in…", "hint"));
+ } else if (item.state !== "not_connected") {
+ if (item.state === "reconnect" && !item.custom) actions.append(button("Reconnect", () => connect(item)));
+ actions.append(button("×", () => confirmDisconnect(item), "icon", "Disconnect " + item.name));
+ } else if (item.reason) {
+ actions.append(node("span", item.reason, "hint"));
+ } else {
+ actions.append(button("+", () => connect(item), "icon plus", "Connect " + item.name));
+ }
+ head.append(actions);
+ box.append(head);
+ const about = connected && !item.tools ? item.description + " Agents use it with harness connections call." : item.description;
+ box.append(node("p", about, "about"));
+ return box;
+}
+function button(text, action, className, label) {
+ const element = node("button", text, className);
+ element.type = "button";
+ if (label) {element.title = label; element.setAttribute("aria-label", label);}
+ element.addEventListener("click", action);
+ return element;
+}
+function render() {
+ const query = search.value.trim().toLowerCase();
+ const match = (item) => !query || (item.name + " " + item.description).toLowerCase().includes(query);
+ const on = items.filter((item) => item.state !== "not_connected" && match(item));
+ const off = items.filter((item) => item.state === "not_connected" && match(item));
+ sections.replaceChildren();
+ const group = (title, list, empty) => {
+ const section = node("section", "", "group");
+ const heading = node("h2", title + " ");
+ heading.append(node("span", String(list.length), "count"));
+ section.append(heading);
+ const grid = node("div", "", "grid");
+ for (const item of list) grid.append(card(item));
+ if (!list.length) grid.append(node("p", empty, "empty"));
+ section.append(grid);
+ sections.append(section);
+ };
+ group("Connected", on, query ? "No connected service matches." : "Nothing connected yet. Choose a service below.");
+ if (view === "browse") group("Available", off, "No service matches.");
}
async function refresh() {
const result = await request("/api/connections");
- list.replaceChildren();
- for (const item of result.connections) {
- const row = node("section", "", "service");
- const info = node("div", "");
- info.append(node("h2", item.name));
- const connected = item.state === "connected";
- const state = connected ? (item.account || "Connected") : ({
- expired: "Reconnect this account", unreadable: "Connection settings need attention",
- not_connected: item.manual ? "Not connected" : "Browser sign-in is not available yet"
- }[item.state]);
- info.append(node("div", state, "detail" + (connected ? " connected" : "")));
- if (connected) info.append(node("div",
- item.scopes.length ? "Permissions: " + item.scopes.join(", ") : "Permissions managed at the provider", "detail"));
- row.append(info);
- const actions = node("div", "", "service-actions");
- if (item.manual && item.state !== "connected") {
- const button = node("button", item.state === "not_connected" ? "Connect" : "Reconnect");
- button.addEventListener("click", () => connect(item));
- actions.append(button);
+ items = result.connections.sort((a, b) => a.name.localeCompare(b.name));
+ render();
+}
+async function follow(item, flow) {
+ pending.set(item.connector, flow);
+ render();
+ try {
+ for (;;) {
+ await new Promise((done) => setTimeout(done, 1000));
+ const status = await request("/api/flows/" + flow);
+ if (status.state === "connected") {notice.textContent = item.name + " connected. Your agents can use it now."; break;}
+ if (status.state === "failed") {notice.textContent = item.name + ": " + status.error; break;}
}
- if (item.state !== "not_connected") {
- const disconnect = node("button", "Disconnect");
- disconnect.addEventListener("click", async () => {
- disconnect.disabled = true;
- try {
- await request("/api/disconnect", {connector: item.connector});
- notice.textContent = item.name + " disconnected here. To revoke the token everywhere, use the service’s settings.";
- await refresh();
- } catch (e) {notice.textContent = e.message; disconnect.disabled = false;}
- });
- actions.append(disconnect);
- } else if (!item.manual) actions.append(node("span", "Unavailable", "unavailable"));
- row.append(actions);
- list.append(row);
+ } catch (e) {notice.textContent = e.message;}
+ pending.delete(item.connector);
+ await refresh().catch((e) => {notice.textContent = e.message;});
+}
+function blankTab() {
+ const tab = window.open("about:blank", "_blank");
+ // The service's page must not be able to reach back into this one.
+ if (tab) tab.opener = null;
+ return tab;
+}
+async function connect(item) {
+ notice.textContent = "";
+ // Open the tab inside the click, so the browser allows it; the address follows.
+ const tab = blankTab();
+ try {
+ const result = await request("/api/connect", {connector: item.connector});
+ if (result.authorize_url && tab) tab.location.href = result.authorize_url;
+ else if (tab) tab.close();
+ if (result.authorize_url && !tab) notice.textContent = "Allow pop-ups for this page to sign in to " + item.name + ".";
+ await follow(item, result.flow);
+ } catch (e) {
+ if (tab) tab.close();
+ notice.textContent = item.name + ": " + e.message;
}
}
-document.querySelector("#cancel").addEventListener("click", () => dialog.close());
-dialog.addEventListener("close", () => {input.value = ""; selected = null;});
-form.addEventListener("submit", async (event) => {
+let disconnecting = null;
+function confirmDisconnect(item) {
+ disconnecting = item;
+ $("#confirm-title").textContent = "Disconnect " + item.name + "?";
+ $("#confirm-dialog").showModal();
+}
+$("#confirm-cancel").addEventListener("click", () => $("#confirm-dialog").close());
+$("#confirm-form").addEventListener("submit", async (event) => {
event.preventDefault();
- save.disabled = true;
- save.textContent = "Connecting…";
- error.textContent = "";
+ $("#confirm-dialog").close();
+ const item = disconnecting;
try {
- await request("/api/connect", {connector: selected, token: input.value.trim()});
- dialog.close();
- notice.textContent = "Connected. Your agents can use this account now.";
+ await request("/api/disconnect", {connector: item.connector});
+ notice.textContent = item.name + " disconnected on this computer.";
await refresh();
- } catch (e) {error.textContent = e.message;}
- finally {input.value = ""; save.disabled = false; save.textContent = "Connect";}
+ } catch (e) {notice.textContent = e.message;}
});
+function headers(text) {
+ const result = {};
+ for (const line of text.split("\n").map((l) => l.trim()).filter(Boolean)) {
+ const at = line.indexOf(":");
+ if (at < 1) throw new Error("Write each header as Name: value.");
+ result[line.slice(0, at).trim()] = line.slice(at + 1).trim();
+ }
+ return result;
+}
+$("#add").addEventListener("click", () => {
+ $("#custom-form").reset();
+ $("#custom-error").textContent = "";
+ $("#custom-dialog").showModal();
+ $("#custom-name").focus();
+});
+$("#custom-cancel").addEventListener("click", () => $("#custom-dialog").close());
+$("#custom-form").addEventListener("submit", async (event) => {
+ event.preventDefault();
+ const save = $("#custom-save");
+ const name = $("#custom-name").value.trim();
+ let extra;
+ try {extra = headers($("#custom-headers").value);} catch (e) {$("#custom-error").textContent = e.message; return;}
+ const tab = Object.keys(extra).length ? null : blankTab();
+ save.disabled = true;
+ try {
+ const result = await request("/api/custom", {name, url: $("#custom-url").value.trim(), headers: extra});
+ $("#custom-dialog").close();
+ if (result.flow) {
+ if (result.authorize_url && tab) tab.location.href = result.authorize_url;
+ else if (tab) tab.close();
+ await follow({connector: "custom:" + name, name}, result.flow);
+ } else {
+ if (tab) tab.close();
+ notice.textContent = name + " added. Your agents can use it now.";
+ await refresh();
+ }
+ } catch (e) {
+ if (tab) tab.close();
+ $("#custom-error").textContent = e.message;
+ } finally {save.disabled = false;}
+});
+function show(next) {
+ view = next;
+ for (const id of ["browse", "connected"]) {
+ $("#" + id).classList.toggle("selected", id === next);
+ $("#" + id).setAttribute("aria-selected", String(id === next));
+ }
+ render();
+}
+$("#browse").addEventListener("click", () => show("browse"));
+$("#connected").addEventListener("click", () => show("connected"));
+$("#reload").addEventListener("click", () => refresh().catch((e) => {notice.textContent = e.message;}));
+search.addEventListener("input", render);
if (!key) notice.textContent = "Open “harness connections” from the terminal to manage your accounts.";
-else refresh().catch(e => {notice.textContent = e.message;});
+else refresh().catch((e) => {notice.textContent = e.message;});
diff --git a/os/connectors/web/style.css b/os/connectors/web/style.css
index 7628e4b2a..087d844f5 100644
--- a/os/connectors/web/style.css
+++ b/os/connectors/web/style.css
@@ -1,20 +1,42 @@
-:root{color-scheme:dark;font:16px/1.6 ui-monospace,SFMono-Regular,Consolas,monospace;color:#e7e8de;background:#11140f}
+:root{color-scheme:dark;font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;color:#e8e8e8;background:#141414}
*{box-sizing:border-box}
body{margin:0}
-main{max-width:880px;margin:auto;padding:48px 32px}
-a{color:inherit;text-underline-offset:4px}
-.brand{text-decoration:none;font-weight:700}.brand span{color:#a1a593;font-weight:400}
-header{margin-bottom:64px}h1{font-size:clamp(28px,4vw,40px);line-height:1.3;letter-spacing:-.04em;font-weight:400;margin:0 0 20px}
-.intro,footer{color:#a1a593}#notice{min-height:26px;color:#d9f69c;margin:28px 0 12px}
-.service{border-top:1px solid #353c2b;display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:20px;padding:20px 0}
-.service h2{font:inherit;margin:0}.detail{font-size:13px;color:#a1a593;overflow-wrap:anywhere}.detail.connected{color:#d9f69c}
-button,input{font:inherit}button{min-height:40px;background:transparent;color:inherit;border:1px solid #59634b;padding:6px 16px;cursor:pointer;white-space:nowrap}
-button:hover{border-color:#d9f69c}button:focus-visible,a:focus-visible,input:focus-visible{outline:2px solid #d9f69c;outline-offset:4px}
-button:disabled{opacity:.5;cursor:wait}.primary{color:#11140f;background:#d9f69c;border-color:#d9f69c}
-.unavailable{color:#818a76;font-size:13px;text-align:right}footer{border-top:1px solid #353c2b;padding-top:24px;margin-top:16px;font-size:13px}
-.service-actions{display:flex;gap:8px;flex-wrap:wrap;justify-content:flex-end}
-dialog{width:min(520px,calc(100% - 32px));border:1px solid #59634b;background:#191e15;color:inherit;padding:32px}
-dialog::backdrop{background:#000b}dialog h2{margin:0;font-size:22px;font-weight:400}dialog p{font-size:14px;color:#a1a593}
-label{display:block;margin:24px 0 8px}input{width:100%;padding:12px;background:#11140f;color:inherit;border:1px solid #59634b}
-.actions{display:flex;justify-content:flex-end;gap:12px;margin-top:24px}#connect-error{color:#f1ac95;min-height:24px}
-@media(max-width:540px){main{padding:28px 20px}header{margin-bottom:40px}.service{gap:12px}.unavailable{max-width:110px}button{padding:6px 10px}}
+main{max-width:1240px;margin:auto;padding:28px 24px 48px}
+header{border-bottom:1px solid #2a2a2a;padding-bottom:14px;margin-bottom:18px}
+h1{font-size:26px;font-weight:700;margin:0 0 4px}.intro{margin:0;color:#a3a3a3}
+.toolbar{display:flex;gap:10px;align-items:center}
+#search{flex:1;min-width:0;height:38px;padding:0 14px;background:#1f1f1f;border:1px solid #2a2a2a;border-radius:8px;color:inherit;font:inherit}
+button,input,textarea{font:inherit}
+button{min-height:36px;border-radius:8px;border:1px solid #333;background:#1f1f1f;color:inherit;padding:6px 14px;cursor:pointer;white-space:nowrap}
+button:hover{border-color:#5b6bff}button:disabled{opacity:.5;cursor:wait}
+button:focus-visible,input:focus-visible,textarea:focus-visible,summary:focus-visible{outline:2px solid #6b7bff;outline-offset:2px}
+.primary{background:#2f45d8;border-color:#3d55ff;color:#fff;font-weight:600}.primary:hover{background:#3a51ea}
+.danger{background:#5c1f1f;border-color:#8a2c2c;color:#fff}
+.icon{min-width:36px;padding:4px 10px}
+.pills{display:flex;gap:8px;margin:16px 0 4px}
+.pill{border-radius:8px;background:#1f1f1f;border-color:#1f1f1f;color:#bdbdbd;font-weight:600}
+.pill.selected{background:#2f45d8;border-color:#3d55ff;color:#fff}
+#notice{min-height:22px;color:#9fe0a8;margin:10px 0}
+.group h2{font-size:12px;letter-spacing:.08em;text-transform:uppercase;color:#a3a3a3;margin:18px 0 10px}
+.count{color:#6f6f6f;margin-left:4px}
+.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(300px,1fr));gap:12px}
+.card{background:#1f1f1f;border:1px solid #262626;border-radius:12px;padding:16px;min-height:118px}
+.card.on{border-color:#2d3a2d}
+.card-head{display:flex;align-items:center;gap:10px}
+.card-head h3{font-size:16px;margin:0;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.mark{flex:none;width:26px;height:26px;border-radius:6px;display:grid;place-items:center;color:#fff;font-weight:800;font-size:14px}
+.badge{font-size:12px;color:#9fb0ff;background:#1d2450;border-radius:6px;padding:1px 8px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:160px}
+.badge.warn{color:#ffd28a;background:#4a3511}
+.card-actions{margin-left:auto;display:flex;gap:6px;align-items:center}
+.plus{color:#8fa0ff;background:#1d2450;border-color:#1d2450;font-size:18px;line-height:1}
+.hint{font-size:12px;color:#8a8a8a;text-align:right}
+.about{margin:12px 0 0;color:#bdbdbd;font-size:14px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
+.empty{color:#8a8a8a;margin:0}
+footer{color:#7a7a7a;font-size:13px;border-top:1px solid #2a2a2a;margin-top:28px;padding-top:16px}
+dialog{width:min(520px,calc(100% - 32px));border:1px solid #333;border-radius:12px;background:#1b1b1b;color:inherit;padding:24px}
+dialog::backdrop{background:#000b}dialog h2{margin:0 0 6px;font-size:20px}dialog p{font-size:14px;color:#a3a3a3;margin:0}
+label{display:block;margin:16px 0 6px;font-size:14px}
+dialog input,textarea{width:100%;padding:10px 12px;background:#141414;color:inherit;border:1px solid #333;border-radius:8px}
+details{margin-top:14px}summary{cursor:pointer;color:#a3a3a3;font-size:14px}
+.actions{display:flex;justify-content:flex-end;gap:10px;margin-top:20px}.error{color:#f1ac95;min-height:22px;margin-top:10px}
+@media(max-width:560px){main{padding:20px 16px}.toolbar{flex-wrap:wrap}#search{flex-basis:100%}.grid{grid-template-columns:1fr}}
diff --git a/os/packaging/fedora/AGENTS.md b/os/packaging/fedora/AGENTS.md
index fa4de9b51..32d820d18 100644
--- a/os/packaging/fedora/AGENTS.md
+++ b/os/packaging/fedora/AGENTS.md
@@ -33,7 +33,7 @@ and running agents. Read `guide.md` and the shipped TUI reference before advisin
- `harness connections` manages this computer's service accounts. Read
`/usr/share/harness-os/connections.md` before using them. All local agents
- share the helper; credentials do not synchronize to other computers.
+ get them as MCP servers; credentials do not synchronize to other computers.
- Fedora's NetworkManager owns networking. `hn-os wifi` opens the root-owned
network form through sudo; passwords stay in its masked input. Explicit login
diff --git a/os/root/usr/lib/systemd/user/harness-connections.service b/os/root/usr/lib/systemd/user/harness-connections.service
new file mode 100644
index 000000000..aa852b6c1
--- /dev/null
+++ b/os/root/usr/lib/systemd/user/harness-connections.service
@@ -0,0 +1,9 @@
+[Unit]
+Description=Connected services for local agents
+Requires=harness-connections.socket
+
+[Service]
+# Adds the stored credential to each agent's MCP request, renewing it first
+# when it is about to expire. Exits after ten quiet minutes.
+ExecStart=/usr/bin/python3 /usr/lib/harness-os/connections/bridge.py
+Restart=on-failure
diff --git a/os/root/usr/lib/systemd/user/harness-connections.socket b/os/root/usr/lib/systemd/user/harness-connections.socket
new file mode 100644
index 000000000..db9cae88f
--- /dev/null
+++ b/os/root/usr/lib/systemd/user/harness-connections.socket
@@ -0,0 +1,8 @@
+[Unit]
+Description=Connected services for local agents
+PartOf=harness-os.target
+
+[Socket]
+# The fixed address agent configs name. Nothing runs until an agent uses it.
+ListenStream=127.0.0.1:51793
+FreeBind=true
diff --git a/os/root/usr/lib/systemd/user/harness-os.target b/os/root/usr/lib/systemd/user/harness-os.target
index a8c0d0212..6d766ba76 100644
--- a/os/root/usr/lib/systemd/user/harness-os.target
+++ b/os/root/usr/lib/systemd/user/harness-os.target
@@ -9,5 +9,5 @@ Requires=graphical-session.target
PartOf=graphical-session.target
# Portals can keep the standard target needed after our screen stops.
PropagatesStopTo=graphical-session.target
-Wants=hn-screen.service harness-install.service harness-idle.service harness-update.timer harness-gpu-check.timer
+Wants=hn-screen.service harness-install.service harness-idle.service harness-update.timer harness-gpu-check.timer harness-connections.socket
After=graphical-session-pre.target
diff --git a/os/root/usr/share/harness-os/AGENTS.md b/os/root/usr/share/harness-os/AGENTS.md
index f6fc7993a..220f15ba9 100644
--- a/os/root/usr/share/harness-os/AGENTS.md
+++ b/os/root/usr/share/harness-os/AGENTS.md
@@ -12,7 +12,8 @@ is required.
- For connected services, read `/usr/share/harness-os/connections.md`.
`harness connections list --json` discovers this user's connected accounts.
- Use the shared helper from any agent; keep credentials out of conversations.
+ They appear as MCP servers in Claude Code, Codex and OpenCode; keep
+ credentials out of conversations.
- `Super+u` starts the update inside hn. `harness updates` opens its screen;
click Update to start the same action. No confirmation or password is needed.
diff --git a/os/root/usr/share/harness-os/connections.md b/os/root/usr/share/harness-os/connections.md
index 6d58cec65..198382ca1 100644
--- a/os/root/usr/share/harness-os/connections.md
+++ b/os/root/usr/share/harness-os/connections.md
@@ -1,16 +1,31 @@
# Connected accounts
-Use `harness connections list --json` to discover accounts on this computer.
-Every agent running as this user reads the same connection store. A connection
-on another computer does not grant access here. Do not copy tokens between
-machines or into agent configuration.
+The user connects services once, in `harness connections`. Every agent running
+as this user gets the same accounts. A connection on another computer does not
+grant access here. Never copy tokens between machines, into chat or into
+project files, and never read the files under
+`~/.local/share/harness-os/connections`.
-Open `harness connections` when the user needs to connect or disconnect an
-account. Secrets belong in that local form, never in chat, shell arguments or
-project files. Read `harness connections info CODE` for account identity,
-reported permissions and expiry. Unknown permissions are not unlimited access.
+`harness connections list --json` lists this computer's connections. Open
+`harness connections` when the user needs to connect or disconnect an account;
+`harness connections connect CODE` does the same sign-in from a terminal.
-Call the connected service with:
+## MCP tools (most services)
+
+Connected services with an MCP server appear as MCP servers named by their code
+(`linear`, `notion`, `canva`, `github`…) in Claude Code, Codex and OpenCode.
+Their address is the local bridge (`http://127.0.0.1:51793/…`), which adds the
+credential and renews it before it expires. Use their tools like any other.
+An agent started before a connection was made sees it after it is restarted.
+
+If a tool answers that the service needs to be connected again, ask the user to
+reconnect it in `harness connections`. Do not try to sign in from the agent.
+
+## REST calls (services signed in through the Harness account)
+
+GitHub, Slack, Asana, HubSpot, PagerDuty, Google (Gmail, Calendar, Drive,
+BigQuery) and Microsoft 365 are signed in through the Harness account. Besides
+their MCP tools, their REST APIs can be called without seeing the token:
```sh
harness connections call CODE METHOD https://OFFICIAL-API-HOST/PATH
@@ -18,39 +33,27 @@ harness connections call CODE METHOD https://OFFICIAL-API-HOST/PATH
Options: `--query KEY=VALUE`, `--header NAME:VALUE`, `--json BODY` (or
`--json -` for stdin), `--data KEY=VALUE`, `--form KEY=VALUE`. Form uploads
-use `KEY=@/path/to/file`. Name the connection; do not read its credential file
-or construct authorization headers yourself. Normal agent approval rules apply.
-Connecting an account is not approval to send messages, publish, delete or
-change permissions. Ask when the requested action lacks authorization.
-
-Read the service's current API reference when an endpoint or schema is unknown.
-Check the command exit code, response body and a read-back before reporting a
-write as successful. GraphQL can return errors with HTTP 200. A 401 means
-reconnect; a 403 can mean insufficient permissions or inaccessible content;
-rate limits and unavailable services are not empty results. Do not automatically
-repeat a write after a timeout: check whether it succeeded first.
-
-## Service entry points
-
-| Connection | Read-only starting request | Notes |
-| --- | --- | --- |
-| github | `GET https://api.github.com/user` | Repositories: `GET /user/repos`; repository/organization access depends on the token. |
-| notion | `GET https://api.notion.com/v1/users/me` | Search: `POST /v1/search` with `--json '{"page_size":10}'`. The helper defaults to Notion-Version 2022-06-28; set a version header explicitly when using a newer schema. |
-| linear | `POST https://api.linear.app/graphql` with `--json '{"query":"{ viewer { id name } }"}'` | Read the `errors` array, not only the exit status. Personal keys and OAuth use different auth headers; the helper selects them. |
-| asana | `GET https://app.asana.com/api/1.0/users/me` | Discover workspaces before projects/tasks. |
-| figma | `GET https://api.figma.com/v1/me` | Requires current_user:read for the connection check. File access depends on the token's scopes. |
-| gmail | `GET https://gmail.googleapis.com/gmail/v1/users/me/profile` | OAuth sign-in is not enabled in this build. Google app passwords do not work with this REST helper. |
-| google_calendar | `GET https://www.googleapis.com/calendar/v3/users/me/calendarList` | Separate connection and permissions from Gmail. OAuth sign-in pending. |
-| google_drive | `GET https://www.googleapis.com/drive/v3/files` with `--query pageSize=10` | Separate connection and permissions. OAuth sign-in pending. |
-| facebook | `GET https://graph.facebook.com/me` | Connection setup pending. Page actions need the correct page token and permissions. |
-| ahrefs | `GET https://api.ahrefs.com/v3/subscription-info/limits-and-usage` | Connection setup pending; API access depends on the service plan. |
-
-Manual tokens can be connected for GitHub, Notion, Linear, Asana and Figma.
-Browser sign-in and automatic renewal are not enabled in this build; expired
-accounts must be reconnected. No Intern device, device key or hardware
-registration is required. These tools are shared by agents running as the same
-local user on an ordinary computer with Harness installed.
+use `KEY=@/path/to/file`. Normal agent approval rules apply. Connecting an
+account is not approval to send messages, publish, delete or change
+permissions. Ask when the requested action lacks authorization.
+
+| Connection | Read-only starting request |
+| --- | --- |
+| github | `GET https://api.github.com/user` |
+| slack | `GET https://slack.com/api/auth.test` |
+| asana | `GET https://app.asana.com/api/1.0/users/me` |
+| hubspot | `GET https://api.hubapi.com/crm/v3/objects/contacts?limit=10` |
+| pagerduty | `GET https://api.pagerduty.com/users/me` |
+| gmail | `GET https://gmail.googleapis.com/gmail/v1/users/me/profile` |
+| google_calendar | `GET https://www.googleapis.com/calendar/v3/users/me/calendarList` |
+| google_drive | `GET https://www.googleapis.com/drive/v3/files` with `--query pageSize=10` |
+| google_bigquery | `GET https://bigquery.googleapis.com/bigquery/v2/projects` |
+| microsoft_365 | `GET https://graph.microsoft.com/v1.0/me` |
+
+Check the exit code, response body and a read-back before reporting a write as
+successful. A 401 means reconnect; a 403 can mean insufficient permissions;
+rate limits and unavailable services are not empty results. Do not repeat a
+write after a timeout: check whether it succeeded first.
`harness connections disconnect CODE` removes local access for future requests.
-An in-flight request cannot be recalled. This does not revoke the token at its
-provider or remove it on other computers. Use the provider's settings for that.
+It does not revoke the account at its provider; use the provider's settings.
diff --git a/os/tests/connections_vm.py b/os/tests/connections_vm.py
index d81cf12d7..3d485029c 100644
--- a/os/tests/connections_vm.py
+++ b/os/tests/connections_vm.py
@@ -20,13 +20,15 @@ with tempfile.TemporaryDirectory(prefix='connections-native-') as temporary:
return subprocess.check_output(['harness', 'connections', *args], env=env, text=True, timeout=10)
assert json.loads(cli('list', '--json')) == []
vault = connection_store.Store(root)
- vault.save('github', {'auth_type': 'pat', 'api_key': 'native-fixture-not-a-real-token', 'user_email': '[email protected]'})
+ vault.save('github', {'access_token': 'native-fixture-not-a-real-token', 'source': 'gateway',
+ 'account_name': '[email protected]'})
for _ in range(3):
# Separate command processes use the same credentials, independent of an engine.
info = json.loads(cli('info', 'github'))
assert info['account'] == '[email protected]', info
assert 'native-fixture-not-a-real-token' not in json.dumps(info)
- assert not (root / 'backend.json').exists()
+ # The bridge's socket is waiting for agents; nothing runs until one calls it.
+ subprocess.run(['systemctl', '--user', 'is-active', '--quiet', 'harness-connections.socket'], check=True)
process = subprocess.Popen(['harness', 'connections', 'serve', '--background'], env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
@@ -58,10 +60,12 @@ print('Installed Connections CLI, shared local credentials and authenticated dis
vm.command('printf %s ' + shlex.quote(encoded) + ' | base64 -d | python3', timeout=30)
vm.command('harness connections', timeout=15)
try:
- wait_installer_screen(vm, r'Connect once', 'connections-page', timeout=30)
- vm.keys('tab')
+ wait_installer_screen(vm, r'Connectors', 'connections-page', timeout=30)
+ # Search, Refresh, then Add custom: the dialog for a remote MCP server.
+ for _ in range(3):
+ vm.keys('tab')
vm.keys('ret')
- wait_installer_screen(vm, r'Access token', 'connections-token-form', timeout=15)
+ wait_installer_screen(vm, r'Remote MCP server URL', 'connections-add-custom', timeout=15)
vm.keys('esc')
finally:
# Use Chromium's own close-window shortcut. Harness deliberately does
@@ -75,4 +79,4 @@ print('Installed Connections CLI, shared local credentials and authenticated dis
vm.command('pkill -INT -u "$(id -u)" -f ' + shlex.quote(pattern) + '; '
'for n in $(seq 1 30); do ! pgrep -u "$(id -u)" -f ' + shlex.quote(pattern) +
' >/dev/null && exit 0; sleep .1; done; exit 1', timeout=10)
- return {'status': 'passed', 'scope': 'Installed CLI, shared fixture credentials, local API boundary, browser and keyboard token form; no provider authentication'}
+ return {'status': 'passed', 'scope': 'Installed CLI, shared fixture credentials, bridge socket, local API boundary, browser page and Add custom dialog; no provider authentication'}
diff --git a/os/tests/test_connections.py b/os/tests/test_connections.py
index fcee83e27..1452c2879 100644
--- a/os/tests/test_connections.py
+++ b/os/tests/test_connections.py
@@ -1,168 +1,426 @@
-"""Connections lifecycle and loopback boundary checks; no provider accounts."""
+"""Connections: local MCP OAuth sign-in, the connector gateway, the bridge,
+agent configs and the page — against fake services, never a real provider."""
+import base64
import contextlib
+import hashlib
import http.client
-import io
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import json
import os
from pathlib import Path
-import stat
import subprocess
import sys
import tempfile
import threading
import time
import unittest
+import urllib.parse
+import urllib.request
from unittest.mock import patch
SOURCE = Path(__file__).resolve().parents[1] / "connectors"
sys.path.insert(0, str(SOURCE))
+import agents
+import bridge
import connection_store as store
import connections
-import connector
+import gateway
+import oauth
+import renew
-TOKEN = "fixture-access-token-not-real"
+class Service(ThreadingHTTPServer):
+ """An MCP server with its own OAuth server: MCP auth, RFC 7591, PKCE, rotation."""
+ daemon_threads = True
-class Response:
- status = 200
+ def __init__(self):
+ super().__init__(("127.0.0.1", 0), ServiceHandler)
+ self.base = f"http://127.0.0.1:{self.server_port}"
+ self.access, self.refresh = None, None
+ self.registered, self.challenge, self.seen, self.revoked = [], {}, [], False
+ threading.Thread(target=self.serve_forever, kwargs={"poll_interval": .02}, daemon=True).start()
- def __init__(self, body):
- self.body = json.dumps(body).encode()
- def read(self, limit=-1):
- return self.body[:limit]
+class ServiceHandler(BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
- def __enter__(self):
- return self
+ def send(self, status, body=None, headers=None):
+ raw = json.dumps(body).encode() if body is not None else b""
+ self.send_response(status)
+ for name, value in (headers or {}).items():
+ self.send_header(name, value)
+ if body is not None:
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(raw)))
+ self.end_headers()
+ self.wfile.write(raw)
- def __exit__(self, *args):
- return False
+ def form(self):
+ return dict(urllib.parse.parse_qsl(self.rfile.read(int(self.headers["Content-Length"])).decode()))
+ def do_GET(self):
+ s, url = self.server, urllib.parse.urlsplit(self.path)
+ if url.path == "/.well-known/oauth-protected-resource/mcp":
+ self.send(200, {"resource": s.base + "/mcp", "authorization_servers": [s.base], "scopes_supported": ["read"]})
+ elif url.path == "/.well-known/oauth-authorization-server":
+ self.send(200, {"issuer": s.base, "authorization_endpoint": s.base + "/authorize",
+ "token_endpoint": s.base + "/token", "registration_endpoint": s.base + "/register",
+ "code_challenge_methods_supported": ["S256"]})
+ elif url.path == "/authorize":
+ query = dict(urllib.parse.parse_qsl(url.query))
+ assert query["code_challenge_method"] == "S256" and query["resource"] == s.base + "/mcp", query
+ s.challenge["code-1"] = query["code_challenge"]
+ target = query["redirect_uri"] + "?" + urllib.parse.urlencode({"code": "code-1", "state": query["state"]})
+ self.send(302, headers={"Location": target})
+ else:
+ self.send(404, {})
-class Credentials(unittest.TestCase):
+ def do_POST(self):
+ s, url = self.server, urllib.parse.urlsplit(self.path)
+ if url.path == "/register":
+ data = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
+ s.registered.append(data)
+ self.send(201, {"client_id": "client-1", "redirect_uris": data["redirect_uris"]})
+ elif url.path == "/token":
+ form = self.form()
+ if form["grant_type"] == "authorization_code":
+ verifier = base64.urlsafe_b64encode(hashlib.sha256(form["code_verifier"].encode()).digest()).rstrip(b"=").decode()
+ if s.challenge.get(form["code"]) != verifier or form["client_id"] != "client-1":
+ self.send(400, {"error": "invalid_grant"})
+ return
+ s.access, s.refresh = "access-1", "refresh-1"
+ elif form.get("refresh_token") != s.refresh or s.revoked:
+ self.send(400, {"error": "invalid_grant"})
+ return
+ else:
+ n = int(s.access.split("-")[1]) + 1
+ s.access, s.refresh = f"access-{n}", f"refresh-{n}"
+ self.send(200, {"access_token": s.access, "token_type": "bearer", "expires_in": 3600,
+ "refresh_token": s.refresh, "scope": "read"})
+ elif url.path == "/mcp":
+ body = self.rfile.read(int(self.headers.get("Content-Length") or 0))
+ s.seen.append({"auth": self.headers.get("Authorization"), "session": self.headers.get("Mcp-Session-Id"),
+ "body": body})
+ if self.headers.get("Authorization") != f"Bearer {s.access}":
+ self.send(401, {"error": "invalid_token"}, {
+ "WWW-Authenticate": f'Bearer resource_metadata="{s.base}/.well-known/oauth-protected-resource/mcp"'})
+ return
+ if "stream=1" in url.query:
+ self.send_response(200)
+ self.send_header("Content-Type", "text/event-stream")
+ self.send_header("Mcp-Session-Id", "session-1")
+ self.end_headers()
+ for n in range(3):
+ self.wfile.write(f'data: {{"n": {n}}}\n\n'.encode())
+ self.wfile.flush()
+ self.close_connection = True
+ return
+ self.send(200, {"jsonrpc": "2.0", "id": 1, "result": {"ok": True}}, {"Mcp-Session-Id": "session-1"})
+ else:
+ self.send(404, {})
+
+
+class Gateway(ThreadingHTTPServer):
+ daemon_threads = True
+
+ def __init__(self):
+ super().__init__(("127.0.0.1", 0), GatewayHandler)
+ self.polls, self.calls = 0, []
+ threading.Thread(target=self.serve_forever, kwargs={"poll_interval": .02}, daemon=True).start()
+
+
+class GatewayHandler(BaseHTTPRequestHandler):
+ def log_message(self, *_):
+ pass
+
+ def send(self, status, body):
+ raw = json.dumps(body).encode()
+ self.send_response(status)
+ self.send_header("Content-Type", "application/json")
+ self.send_header("Content-Length", str(len(raw)))
+ self.end_headers()
+ self.wfile.write(raw)
+
+ def do_GET(self):
+ if self.headers.get("Authorization") != "Bearer grid-session":
+ self.send(401, {})
+ else:
+ self.send(200, {"connectors": [{"code": "github", "label": "GitHub", "auth_type": "app"}]})
+
+ def do_POST(self):
+ if self.headers.get("Authorization") != "Bearer grid-session":
+ self.send(401, {})
+ return
+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
+ path = self.path.removeprefix("/v1/grid/")
+ self.server.calls.append((path, body))
+ token = {"access_token": "gho-fixture", "expires_at": int(time.time()) + 3600, "refresh": True,
+ "account_name": "octo", "mcp_entry": {"url": "https://api.githubcopilot.com/mcp/",
+ "headers": {"Authorization": "Bearer gho-fixture"}}}
+ if path == "connectors/start":
+ self.send(200, {"authorize_url": "https://github.com/login/oauth/authorize?state=grid_x",
+ "pickup_code": "pickup-1", "poll_interval": 1, "expires_in": 60})
+ elif path == "connectors/poll":
+ self.server.polls += 1
+ self.send(200, {"status": "pending"} if self.server.polls < 2 else dict(token, status="ready", connector="github"))
+ elif path == "connectors/refresh":
+ self.send(200, dict(token, access_token="gho-renewed"))
+ else:
+ self.send(200, {"disconnected": True})
+
+
+class Case(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
- self.root = Path(folder.name) / "connections"
- self.vault = store.Store(self.root)
- self.entry = {"auth_type": "oauth", "access_token": TOKEN, "refresh_token": "fixture-refresh",
- "refresh": True, "expires_at": int(time.time()) + 3600, "scopes": ["read"]}
-
- def test_private_atomic_storage_shared_across_agent_processes_and_disconnect(self):
- self.vault.save("github", self.entry)
- self.assertEqual(stat.S_IMODE(self.root.stat().st_mode), 0o700)
- self.assertEqual(stat.S_IMODE(self.vault.path("github").stat().st_mode), 0o600)
- for engine in ("codex", "claude", "opencode"):
+ self.home = Path(folder.name)
+ self.vault = store.Store(self.home / "connections")
+ env = patch.dict(os.environ, {"HOME": str(self.home), "XDG_CONFIG_HOME": str(self.home / ".config"),
+ "GRID_HOME": str(self.home / ".grid"), "CODEX_HOME": str(self.home / ".codex")})
+ env.start()
+ self.addCleanup(env.stop)
+
+ def service(self):
+ service = Service()
+ self.addCleanup(service.server_close)
+ self.addCleanup(service.shutdown)
+ return service
+
+ def sign_in(self, service, browse=True):
+ sign_in = oauth.SignIn(self.vault, service.base + "/mcp")
+ url = sign_in.prepare()
+ if browse:
+ # The browser: the service redirects it to this computer's 127.0.0.1 callback.
+ threading.Thread(target=lambda: urllib.request.urlopen(url, timeout=5).read(), daemon=True).start()
+ return sign_in.wait()
+
+
+class LocalSignIn(Case):
+ def test_mcp_oauth_registers_this_computer_once_with_pkce_and_saves_a_renewable_token(self):
+ service = self.service()
+ token = self.sign_in(service)
+ connections.finish(self.vault, "linear", token)
+ saved = self.vault.token("linear")
+ self.assertEqual(saved["source"], "dcr")
+ self.assertEqual(saved["refresh_token"], "refresh-1")
+ self.assertEqual(saved["mcp_entry"], {"url": service.base + "/mcp", "headers": {"Authorization": "Bearer access-1"}})
+ self.assertTrue(store.refreshable(saved))
+ registration = service.registered[0]
+ self.assertEqual(registration["token_endpoint_auth_method"], "none")
+ self.assertTrue(registration["redirect_uris"][0].startswith("http://127.0.0.1:"))
+ for name in ("tokens.json", "clients.json"):
+ self.assertEqual((self.vault.root / name).stat().st_mode & 0o777, 0o600)
+ # A second sign-in reuses this computer's client instead of registering again.
+ self.sign_in(service)
+ self.assertEqual(len(service.registered), 1)
+
+ def test_a_callback_for_another_sign_in_is_refused(self):
+ service = self.service()
+ sign_in = oauth.SignIn(self.vault, service.base + "/mcp")
+ url = sign_in.prepare()
+ forged = url.replace("state=", "state=forged")
+ threading.Thread(target=lambda: urllib.request.urlopen(forged, timeout=5).read(), daemon=True).start()
+ with self.assertRaisesRegex(store.StoreError, "could not be confirmed"):
+ sign_in.wait()
+ self.assertEqual(self.vault.tokens(), {})
+
+ def test_a_server_without_sign_in_is_saved_as_it_is(self):
+ with patch.object(oauth, "probe", return_value={"kind": "open"}):
+ sign_in = oauth.SignIn(self.vault, "https://open.example/mcp")
+ self.assertIsNone(sign_in.prepare())
+ token = sign_in.wait()
+ self.assertEqual(token["mcp_entry"], {"url": "https://open.example/mcp", "headers": {}})
+
+
+class Bridge(Case):
+ def setUp(self):
+ super().setUp()
+ self.service_ = self.service()
+ connections.finish(self.vault, "linear", self.sign_in(self.service_))
+ self.key = agents.bridge_key(self.vault)
+ self.bridge = bridge.Bridge(self.vault)
+ threading.Thread(target=self.bridge.serve_forever, kwargs={"poll_interval": .02}, daemon=True).start()
+ self.addCleanup(self.bridge.server_close)
+ self.addCleanup(self.bridge.shutdown)
+
+ def call(self, path, headers=None, query=""):
+ client = http.client.HTTPConnection("127.0.0.1", self.bridge.server_port, timeout=5)
+ try:
+ body = b'{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
+ client.request("POST", path + query, body=body, headers={"Content-Type": "application/json",
+ "Accept": "application/json, text/event-stream",
+ "Authorization": "Bearer agent-supplied", **(headers or {})})
+ response = client.getresponse()
+ return response.status, dict(response.getheaders()), response.read()
+ finally:
+ client.close()
+
+ def test_the_agent_gets_the_service_without_ever_holding_its_token(self):
+ status, headers, raw = self.call(f"/{self.key}/linear/mcp")
+ self.assertEqual(status, 200, raw)
+ self.assertEqual(json.loads(raw)["result"], {"ok": True})
+ self.assertEqual(headers["Mcp-Session-Id"], "session-1")
+ self.assertEqual(self.service_.seen[-1]["auth"], "Bearer access-1", "the bridge's credential, not the agent's")
+ status, headers, raw = self.call(f"/{self.key}/linear/mcp", query="?stream=1")
+ self.assertEqual(status, 200)
+ self.assertEqual(raw.count(b"data:"), 3)
+
+ def test_strangers_and_web_pages_are_refused(self):
+ before = len(self.service_.seen)
+ self.assertEqual(self.call("/wrong-key/linear/mcp")[0], 404)
+ self.assertEqual(self.call(f"/{self.key}/linear/mcp", {"Origin": "https://evil.example"})[0], 403)
+ self.assertEqual(self.call(f"/{self.key}/notion/mcp")[0], 404)
+ self.assertEqual(len(self.service_.seen), before)
+
+ def test_a_token_about_to_expire_is_renewed_before_the_request(self):
+ token = self.vault.token("linear")
+ token["expires_at"] = int(time.time()) + 60
+ self.vault.save("linear", token)
+ self.assertEqual(self.call(f"/{self.key}/linear/mcp")[0], 200)
+ self.assertEqual(self.service_.seen[-1]["auth"], "Bearer access-2")
+ saved = self.vault.token("linear")
+ self.assertEqual((saved["access_token"], saved["refresh_token"]), ("access-2", "refresh-2"))
+ self.assertGreater(saved["expires_at"], time.time() + 3000)
+
+ def test_a_token_the_service_revoked_early_is_renewed_once(self):
+ self.service_.access = "rotated-by-the-service"
+ self.service_.refresh = "refresh-1"
+ self.service_.access = "access-7"
+ self.assertEqual(self.call(f"/{self.key}/linear/mcp")[0], 200)
+ self.assertEqual(self.vault.token("linear")["access_token"], "access-8")
+
+ def test_a_revoked_grant_asks_for_reconnecting_instead_of_a_sign_in_challenge(self):
+ token = self.vault.token("linear")
+ token["expires_at"] = int(time.time()) + 60
+ self.vault.save("linear", token)
+ self.service_.revoked = True
+ status, headers, raw = self.call(f"/{self.key}/linear/mcp")
+ self.assertEqual(status, 401)
+ self.assertNotIn("WWW-Authenticate", headers)
+ self.assertIn("connected again", json.loads(raw)["error"]["message"])
+ self.assertEqual(self.vault.status("linear")["state"], "reconnect")
+
+
+class AgentConfigs(Case):
+ def test_each_agent_gets_bridge_addresses_and_keeps_its_own_servers(self):
+ claude = self.home / ".claude.json"
+ claude.write_text(json.dumps({"numStartups": 3, "mcpServers": {"notion": {"command": "my-notion"}}}))
+ codex = self.home / ".codex/config.toml"
+ codex.parent.mkdir()
+ codex.write_text('model = "gpt-5"\n\n[mcp_servers.mine]\ncommand = "mine"\n')
+ opencode = self.home / ".config/opencode/opencode.json"
+ opencode.parent.mkdir(parents=True)
+ opencode.write_text(json.dumps({"model": "opencode/muse"}))
+ for code in ("linear", "notion"):
+ self.vault.save(code, {"access_token": "secret-" + code, "source": "dcr",
+ "mcp_entry": {"url": f"https://mcp.{code}.example/mcp",
+ "headers": {"Authorization": "Bearer secret-" + code}}})
+ self.vault.save("github", {"access_token": "secret-github", "source": "gateway"}) # REST only: no tools
+ changed = agents.sync(self.vault)
+ key = agents.bridge_key(self.vault)
+ self.assertEqual(changed, {"claude": ["linear"], "codex": ["linear", "notion"], "opencode": ["linear", "notion"]})
+ data = json.loads(claude.read_text())
+ self.assertEqual(data["numStartups"], 3)
+ self.assertEqual(data["mcpServers"]["notion"], {"command": "my-notion"}, "the user's own server")
+ self.assertEqual(data["mcpServers"]["linear"], {"type": "http", "url": f"http://127.0.0.1:51793/{key}/linear/mcp"})
+ text = codex.read_text()
+ self.assertTrue(text.startswith('model = "gpt-5"\n\n[mcp_servers.mine]\ncommand = "mine"\n'), text)
+ self.assertIn(f'[mcp_servers.notion]\nurl = "http://127.0.0.1:51793/{key}/notion/mcp"', text)
+ self.assertEqual(json.loads(opencode.read_text())["mcp"]["linear"]["type"], "remote")
+ for path in (claude, codex, opencode):
+ self.assertNotIn("secret-", path.read_text())
+
+ self.vault.disconnect("linear")
+ self.vault.disconnect("notion")
+ agents.sync(self.vault)
+ self.assertEqual(json.loads(claude.read_text())["mcpServers"], {"notion": {"command": "my-notion"}})
+ self.assertEqual(codex.read_text(), 'model = "gpt-5"\n\n[mcp_servers.mine]\ncommand = "mine"\n')
+ self.assertEqual(json.loads(opencode.read_text()), {"model": "opencode/muse"})
+
+ def test_a_config_it_cannot_read_safely_is_left_alone(self):
+ opencode = self.home / ".config/opencode/opencode.json"
+ opencode.parent.mkdir(parents=True)
+ opencode.write_text('{ // a comment\n "model": "x" }')
+ self.vault.save("linear", {"access_token": "a", "mcp_entry": {"url": "https://mcp.example/mcp"}})
+ agents.sync(self.vault)
+ self.assertEqual(opencode.read_text(), '{ // a comment\n "model": "x" }')
+
+
+class ConnectorGateway(Case):
+ def gateway(self, signed_in=True):
+ server = Gateway()
+ self.addCleanup(server.server_close)
+ self.addCleanup(server.shutdown)
+ if signed_in:
+ grid = self.home / ".grid"
+ grid.mkdir()
+ (grid / "credentials.toml").write_text(
+ f'session_token = "grid-session"\napi_url = "http://127.0.0.1:{server.server_port}"\n\n[device]\nid = "x"\n')
+ return server
+
+ def test_a_service_without_self_registration_signs_in_through_the_gateway(self):
+ server = self.gateway()
+ self.assertIn("github", gateway.available())
+ sign_in = connections.sign_in_for(self.vault, "github")
+ self.assertTrue(sign_in.prepare().startswith("https://github.com/"))
+ connections.finish(self.vault, "github", sign_in.wait())
+ saved = self.vault.token("github")
+ self.assertEqual((saved["source"], saved["account_name"], saved["access_token"]), ("gateway", "octo", "gho-fixture"))
+ renew.refresh(self.vault, "github", force=True)
+ self.assertEqual(self.vault.token("github")["access_token"], "gho-renewed")
+ self.assertEqual(self.vault.token("github")["account_name"], "octo")
+ connections.disconnect(self.vault, "github")
+ self.assertIsNone(self.vault.token("github"))
+ self.assertEqual(server.calls[-1], ("connectors/disconnect", {"connector": "github"}))
+
+ def test_signed_out_the_page_says_how_to_connect_these_services(self):
+ self.gateway(signed_in=False)
+ cards = {c["connector"]: c for c in connections.catalog(self.vault)["connections"]}
+ self.assertIn("harness login", cards["github"]["reason"])
+ self.assertEqual(cards["linear"]["reason"], "")
+ with self.assertRaisesRegex(store.StoreError, "harness login"):
+ connections.sign_in_for(self.vault, "slack").prepare()
+
+
+class Storage(Case):
+ def test_private_storage_shared_by_separate_agent_processes(self):
+ self.vault.save("linear", {"access_token": "fixture-secret", "refresh_token": "fixture-refresh",
+ "mcp_entry": {"url": "https://mcp.linear.app/mcp"}, "account_name": "me"})
+ env = dict(os.environ, CONNECTOR_CONFIGS_DIR=str(self.vault.root))
+ for _ in range(2):
result = subprocess.run([sys.executable, str(SOURCE / "connections.py"), "list", "--json"],
- env={**os.environ, "CONNECTOR_CONFIGS_DIR": str(self.root), "HARNESS_ENGINE": engine},
- capture_output=True, text=True, timeout=10)
+ env=env, capture_output=True, text=True, timeout=10)
self.assertEqual(result.returncode, 0, result.stderr)
- self.assertEqual(json.loads(result.stdout)[0]["connector"], "github")
- self.assertNotIn(TOKEN, result.stdout + result.stderr)
- self.vault.disconnect("github")
- with self.assertRaisesRegex(store.StoreError, "Not connected"):
- store.Store(self.root).ready("github")
- self.assertFalse(list(self.root.glob(".incoming-*")))
-
- def test_symlinks_broad_permissions_and_path_traversal_cannot_read_credentials(self):
- self.vault.save("github", self.entry)
- path = self.vault.path("github")
+ self.assertEqual(json.loads(result.stdout)[0]["connector"], "linear")
+ self.assertNotIn("fixture-", result.stdout + result.stderr)
+
+ def test_symlinks_and_broad_permissions_cannot_read_credentials(self):
+ self.vault.save("linear", {"access_token": "a", "mcp_entry": {"url": "https://mcp.linear.app/mcp"}})
+ path = self.vault.root / "tokens.json"
path.chmod(0o644)
with self.assertRaises(store.StoreError):
- self.vault.load("github")
+ self.vault.tokens()
path.chmod(0o600)
- alias = self.root / "notion_access_tokens.json"
- alias.symlink_to(path)
+ link = self.home / "link"
+ link.symlink_to(self.vault.root)
with self.assertRaises(store.StoreError):
- self.vault.load("notion")
- for code in ("../github", "/etc/passwd", "new"):
+ store.Store(link).tokens()
+ for code in ("../outside", "UPPER", ""):
with self.assertRaises(store.StoreError):
- self.vault.path(code)
- symlink = self.root.parent / "alias"
- symlink.symlink_to(self.root)
- with self.assertRaises(store.StoreError):
- store.Store(symlink).save("github", self.entry)
-
- def test_expired_tokens_stop_without_contacting_a_device_backend(self):
- self.vault.save("github", dict(self.entry, expires_at=1))
- # A leftover development config must not turn on Intern device renewal.
- store.write_private(self.root / "backend.json", {
- "base_url": "https://backend.invalid/api/v1/ai/v1",
- "api_key": "fixture-device", "device_id": "fixture-device-id",
- })
- old = self.vault.path("github").read_bytes()
- self.assertEqual(self.vault.status("github")["state"], "expired")
- self.assertFalse(self.vault.status("github")["auto_refresh"])
- with patch("urllib.request.OpenerDirector.open") as request:
- with self.assertRaisesRegex(store.StoreError, "expired"):
- self.vault.ready("github")
- request.assert_not_called()
- self.assertEqual(self.vault.path("github").read_bytes(), old)
-
- def test_valid_tokens_need_no_backend_or_device_registration(self):
- self.vault.save("github", self.entry)
- self.assertFalse((self.root / "backend.json").exists())
- self.assertEqual(self.vault.ready("github")["access_token"], TOKEN)
- # Even an unreadable old backend config cannot affect local connections.
- (self.root / "backend.json").symlink_to(self.root / "missing-config")
- self.assertEqual(self.vault.status("github")["state"], "connected")
- self.assertFalse(self.vault.status("github")["auto_refresh"])
- self.assertEqual(self.vault.ready("github")["access_token"], TOKEN)
-
- def test_provider_headers_and_failed_identity_do_not_save_token(self):
- cases = [
- ("github", {"id": 42, "login": "fixture"}, "Authorization", "Bearer " + TOKEN),
- ("notion", {"id": "bot"}, "Authorization", "Bearer " + TOKEN),
- ("linear", {"data": {"viewer": {"id": "user", "email": "[email protected]"}}}, "Authorization", TOKEN),
- ("asana", {"data": {"gid": "user", "name": "Fixture"}}, "Authorization", "Bearer " + TOKEN),
- ("figma", {"id": "user", "email": "[email protected]"}, "X-figma-token", TOKEN),
- ]
- for code, body, header, value in cases:
- seen = []
- def respond(req, timeout):
- seen.append(req)
- return Response(body)
- with patch.object(connector._OPENER, "open", side_effect=respond):
- connections.connect_token(self.vault, code, TOKEN)
- self.assertEqual(seen[0].get_header(header), value)
- self.assertIsNone(seen[0].get_header("X-device-id"))
- self.assertEqual(self.vault.status(code)["state"], "connected")
- self.vault.disconnect("linear")
- with patch.object(connector._OPENER, "open", return_value=Response({"errors": [{"message": "bad key"}]})):
- with self.assertRaises(store.StoreError):
- connections.connect_token(self.vault, "linear", TOKEN)
- self.assertIsNone(self.vault.load("linear"))
-
- def test_cli_rejects_oversized_response_and_redacts_both_credentials(self):
- self.vault.save("github", self.entry)
- for body, expected in [("x" * 128, 1), (TOKEN + " fixture-refresh", 0)]:
- output, error = io.StringIO(), io.StringIO()
- with patch.object(connector, "CONFIGS_DIR", self.root), patch.object(connector, "MAX_RESPONSE_BYTES", 100), \
- patch.object(connector._OPENER, "open", return_value=Response(body)), \
- contextlib.redirect_stdout(output), contextlib.redirect_stderr(error):
- status = connector.main(["call", "github", "GET", "https://api.github.com/user"])
- self.assertEqual(status, expected)
- self.assertNotIn(TOKEN, output.getvalue() + error.getvalue())
- self.assertNotIn("fixture-refresh", output.getvalue() + error.getvalue())
-
-
-class BrowserBoundary(unittest.TestCase):
+ self.vault.save(code, {"access_token": "a"})
+
+
+class Page(Case):
def setUp(self):
- folder = tempfile.TemporaryDirectory()
- self.addCleanup(folder.cleanup)
- self.vault = store.Store(Path(folder.name) / "connections")
+ super().setUp()
self.server = connections.PageServer(self.vault)
- self.thread = threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": .02}, daemon=True)
- self.thread.start()
- self.addCleanup(self.close)
-
- def close(self):
- self.server.shutdown()
- self.thread.join(timeout=2)
- self.server.server_close()
+ threading.Thread(target=self.server.serve_forever, kwargs={"poll_interval": .02}, daemon=True).start()
+ self.addCleanup(self.server.server_close)
+ self.addCleanup(self.server.shutdown)
def request(self, path, method="GET", body=None, headers=None):
- client = http.client.HTTPConnection(*self.server.server_address, timeout=3)
+ client = http.client.HTTPConnection(*self.server.server_address, timeout=5)
try:
client.request(method, path, body=json.dumps(body) if body is not None else None, headers=headers or {})
response = client.getresponse()
@@ -177,31 +435,17 @@ class BrowserBoundary(unittest.TestCase):
for headers in ({}, {**self.auth(), "Host": "evil.invalid"}, {**self.auth(), "Sec-Fetch-Site": "cross-site"}):
self.assertEqual(self.request("/api/connections", headers=headers)[0], 403)
headers = {**self.auth(), "Origin": "https://evil.invalid"}
- self.assertEqual(self.request("/api/disconnect", "POST", {"connector": "github"}, headers)[0], 403)
- self.assertEqual(self.request("/api/disconnect?connector=github", headers=self.auth())[0], 404)
+ self.assertEqual(self.request("/api/connect", "POST", {"connector": "linear"}, headers)[0], 403)
+ self.assertEqual(self.request("/api/flows/x")[0], 403)
self.assertEqual(self.request("/../connection_store.py")[0], 404)
def test_reuse_requires_server_proof_without_sending_the_capability(self):
identity = {"port": self.server.server_port, "key": self.server.key}
store.write_private(self.vault.root / "page.json", identity)
self.assertEqual(connections.running_page(self.vault), self.server.origin + "/#" + self.server.key)
- # An impostor on this port knows the request but not the saved secret.
identity["key"] = "fixture-secret-not-known-to-this-server"
store.write_private(self.vault.root / "page.json", identity)
self.assertIsNone(connections.running_page(self.vault))
- with patch("urllib.request.OpenerDirector.open", return_value=Response({"connections": []})) as request:
- self.assertIsNone(connections.running_page(self.vault))
- probe = request.call_args.args[0]
- self.assertIsNone(probe.get_header("X-harness-connections"))
- self.assertNotIn(identity["key"], probe.full_url + repr(probe.headers))
- with patch("urllib.request.OpenerDirector.open", return_value=Response({"proof": connections.identity_proof(identity["key"], "0" * 64)})):
- self.assertIsNone(connections.running_page(self.vault), "An old proof cannot answer a new challenge")
-
- def test_identity_probe_cannot_keep_an_unused_page_alive(self):
- before = self.server.last_request
- self.assertEqual(self.request("/api/identity", headers={"X-Harness-Probe": "0" * 64})[0], 200)
- self.assertEqual(self.server.last_request, before)
- self.assertEqual(self.request("/api/identity", headers={"X-Harness-Probe": "bad"})[0], 400)
def test_page_cleanup_preserves_a_newer_server(self):
identity = {"port": self.server.server_port, "key": self.server.key}
@@ -212,32 +456,43 @@ class BrowserBoundary(unittest.TestCase):
connections.forget_page(self.vault, identity)
self.assertFalse(path.exists())
- def test_real_http_connect_list_disconnect_without_token_response_or_static_leak(self):
- with patch.object(connector._OPENER, "open", return_value=Response({"id": 1, "login": "fixture"})):
- status, _, raw = self.request("/api/connect", "POST", {"connector": "github", "token": TOKEN}, self.auth())
- self.assertEqual(status, 200, raw)
- self.assertNotIn(TOKEN.encode(), raw)
+ def test_connect_in_the_browser_then_list_and_disconnect_without_any_token_in_responses(self):
+ service = self.service()
+ with patch.dict(store.CATALOG["linear"], {"mcp_url": service.base + "/mcp"}):
+ status, _, raw = self.request("/api/connect", "POST", {"connector": "linear"}, self.auth())
+ self.assertEqual(status, 200, raw)
+ started = json.loads(raw)
+ urllib.request.urlopen(started["authorize_url"], timeout=5).read()
+ for _ in range(100):
+ flow = json.loads(self.request("/api/flows/" + started["flow"], headers=self.auth())[2])
+ if flow["state"] != "pending":
+ break
+ time.sleep(.05)
+ self.assertEqual(flow["state"], "connected", flow)
status, headers, raw = self.request("/api/connections", headers=self.auth())
- self.assertEqual(status, 200)
self.assertEqual(headers["Cache-Control"], "no-store")
- self.assertNotIn(TOKEN.encode(), raw)
- status, headers, _ = self.request("/")
- self.assertEqual(status, 200)
- self.assertIn("frame-ancestors 'none'", headers["Content-Security-Policy"])
- status, _, raw = self.request("/api/disconnect", "POST", {"connector": "github"}, self.auth())
- self.assertEqual(status, 200)
+ cards = {c["connector"]: c for c in json.loads(raw)["connections"]}
+ self.assertEqual(cards["linear"]["state"], "connected")
+ self.assertTrue(cards["linear"]["tools"])
+ self.assertNotIn(b"access-1", raw)
+ self.assertNotIn(b"refresh-1", raw)
+ status, _, raw = self.request("/api/disconnect", "POST", {"connector": "linear"}, self.auth())
self.assertEqual(json.loads(raw)["state"], "not_connected")
- self.assertIsNone(self.vault.load("github"))
-
- def test_bad_request_and_unverified_services_do_not_create_accounts(self):
- for body in ({"connector": "../outside", "token": TOKEN}, {"connector": "gmail", "token": TOKEN},
- {"connector": "github", "token": ["bad"]}):
- status, _, raw = self.request("/api/connect", "POST", body, self.auth())
- self.assertEqual(status, 400, raw)
- self.assertFalse(self.root_exists())
+ self.assertIsNone(self.vault.token("linear"))
- def root_exists(self):
- return self.vault.root.exists()
+ def test_add_custom_with_headers_and_bad_requests(self):
+ body = {"name": "My Tools", "url": "https://tools.example/mcp", "headers": {"Authorization": "Bearer pat-fixture"}}
+ status, _, raw = self.request("/api/custom", "POST", body, self.auth())
+ self.assertEqual(status, 200, raw)
+ code = json.loads(raw)["connector"]
+ self.assertEqual(code, "my-tools")
+ card = [c for c in json.loads(self.request("/api/connections", headers=self.auth())[2])["connections"]
+ if c["connector"] == code][0]
+ self.assertEqual((card["name"], card["custom"], card["state"]), ("My Tools", True, "connected"))
+ for bad in ({"name": "x", "url": "http://tools.example/mcp"}, {"name": "", "url": "https://t.example"},
+ {"name": "x", "url": "https://t.example", "headers": {"Bad Header": "v"}}):
+ self.assertEqual(self.request("/api/custom", "POST", bad, self.auth())[0], 400, bad)
+ self.assertEqual(self.request("/api/connect", "POST", {"connector": "../x"}, self.auth())[0], 400)
if __name__ == "__main__":
diff --git a/os/tests/test_connector_upstream.py b/os/tests/test_connector_upstream.py
index 916d400f5..fded6d613 100644
--- a/os/tests/test_connector_upstream.py
+++ b/os/tests/test_connector_upstream.py
@@ -49,15 +49,17 @@ class ConnectorHelperTests(unittest.TestCase):
self.addCleanup(self.temp.cleanup)
self.dir = Path(self.temp.name)
self.write('google_calendar', {
- 'auth_type': 'oauth', 'access_token': TOKEN, 'refresh_token': 'r', 'refresh': True,
- 'expires_at': int(time.time()) + 3600, 'user_email': '[email protected]',
- 'scopes': ['https://www.googleapis.com/auth/calendar.events'],
+ 'access_token': TOKEN, 'refresh_token': 'r', 'refresh': True, 'source': 'gateway',
+ 'expires_at': int(time.time()) + 3600, 'account_name': '[email protected]',
+ 'scope': 'https://www.googleapis.com/auth/calendar.events',
})
self.mod = load_module(self.dir)
def write(self, code, entry):
- path = self.dir / f'{code}_access_tokens.json'
- path.write_text(json.dumps({'connectors': {code: entry}}))
+ path = self.dir / 'tokens.json'
+ tokens = json.loads(path.read_text()) if path.exists() else {}
+ tokens[code] = entry
+ path.write_text(json.dumps(tokens))
path.chmod(0o600)
def run_main(self, *argv):
@@ -69,11 +71,11 @@ class ConnectorHelperTests(unittest.TestCase):
def test_list_names_connector_without_secret(self):
code, out, _ = self.run_main('list')
self.assertEqual(code, 0)
- self.assertIn('google_calendar: connected ([email protected], oauth)', out)
+ self.assertIn('google_calendar: connected ([email protected], harness connections call)', out)
self.assertNotIn(TOKEN, out)
def test_list_reports_unreadable_file_as_verification_failure(self):
- (self.dir / 'google_calendar_access_tokens.json').write_text('{not json')
+ (self.dir / 'tokens.json').write_text('{not json')
code, _, err = self.run_main('list')
self.assertEqual(code, 3)
self.assertIn('verification failed', err)
@@ -82,9 +84,11 @@ class ConnectorHelperTests(unittest.TestCase):
code, out, _ = self.run_main('info', 'google_calendar')
self.assertEqual(code, 0)
info = json.loads(out)
- self.assertFalse(info['auto_refresh'], 'Refresh metadata alone does not enable automatic renewal')
- self.assertFalse(info['expired'])
+ self.assertTrue(info['auto_refresh'], 'The gateway renews a token it issued with a refresh token')
+ self.assertEqual(info['state'], 'connected')
+ self.assertTrue(info['rest_call'])
self.assertNotIn(TOKEN, out)
+ self.assertNotIn('"r"', out)
def test_call_sends_header_and_encodes_query(self):
seen = {}
@@ -136,34 +140,19 @@ class ConnectorHelperTests(unittest.TestCase):
self.assertEqual(code, 2)
self.assertIn('Authorization', err)
- def test_google_app_password_is_refused(self):
- self.write('gmail', {'auth_type': 'pat', 'api_key': 'app-pass', 'credentials': {'email': '[email protected]'}})
- code, _, err = self.run_main('call', 'gmail', 'GET', 'https://gmail.googleapis.com/gmail/v1/users/me/messages')
+ def test_an_mcp_server_token_is_not_sent_to_a_rest_api(self):
+ self.write('github', {'access_token': TOKEN, 'source': 'dcr', 'mcp_entry': {'url': 'https://mcp.example/mcp'}})
+ with patch.object(self.mod._OPENER, 'open') as opener:
+ code, _, err = self.run_main('call', 'github', 'GET', 'https://api.github.com/user')
self.assertEqual(code, 3)
- self.assertIn('IMAP', err)
+ self.assertIn('MCP server', err)
+ opener.assert_not_called()
def test_not_connected(self):
code, _, err = self.run_main('call', 'google_drive', 'GET', 'https://www.googleapis.com/drive/v3/files')
self.assertEqual(code, 3)
self.assertIn('not connected', err.lower())
- def test_token_param_uses_query_not_header(self):
- self.write('facebook', {'api_key': TOKEN, 'credentials': {'page_id': '123'}})
- seen = {}
-
- def fake_urlopen(req, timeout):
- seen['url'] = req.full_url
- seen['auth'] = req.get_header('Authorization')
- return FakeResponse('{"success": true}')
-
- with patch.object(self.mod._OPENER, 'open', fake_urlopen):
- code, out, _ = self.run_main('call', 'facebook', 'DELETE', 'https://graph.facebook.com/v19.0/1_2',
- '--token-param', 'access_token')
- self.assertEqual(code, 0)
- self.assertIsNone(seen['auth'])
- self.assertIn('access_token=' + TOKEN, seen['url'])
- self.assertNotIn(TOKEN, out)
-
def test_response_echoing_token_is_scrubbed(self):
with patch.object(self.mod._OPENER, 'open', lambda req, timeout: FakeResponse(TOKEN)):
code, out, _ = self.run_main('call', 'google_calendar', 'GET', 'https://www.googleapis.com/x')
@@ -183,7 +172,7 @@ class ConnectorHelperTests(unittest.TestCase):
code, _, _ = self.run_main('call', 'google_calendar', 'GET', url)
self.assertEqual(code, 4, url)
- def test_token_param_only_for_facebook(self):
+ def test_token_param_is_refused(self):
code, _, err = self.run_main('call', 'google_calendar', 'GET', 'https://www.googleapis.com/x',
'--token-param', 'access_token')
self.assertEqual(code, 2)
@@ -195,7 +184,7 @@ class ConnectorHelperTests(unittest.TestCase):
self.assertIsNone(handler.redirect_request(req, None, 302, 'Found', {}, 'https://attacker.example/'))
def test_upload_refuses_credentials_and_non_media(self):
- token_file = self.dir / 'google_calendar_access_tokens.json'
+ token_file = self.dir / 'tokens.json'
alias = self.dir / 'innocent.jpg'
alias.symlink_to(token_file)
for raw in (str(token_file), str(alias), '/root/config/config.json'):
diff --git a/os/tests/test_package.py b/os/tests/test_package.py
index 352802e58..be61e40d8 100644
--- a/os/tests/test_package.py
+++ b/os/tests/test_package.py
@@ -26,6 +26,11 @@ class PackageIdentity(unittest.TestCase):
config = destination / 'etc/skel/.config/opencode'
self.assertTrue((destination / 'usr/lib/harness-os/connections/connections.py').is_file())
self.assertTrue((destination / 'usr/lib/harness-os/connections/web/index.html').is_file())
+ for name in ('bridge.py', 'catalog.json', 'oauth.py', 'gateway.py', 'agents.py', 'renew.py'):
+ self.assertTrue((destination / 'usr/lib/harness-os/connections' / name).is_file(), name)
+ socket = (destination / 'usr/lib/systemd/user/harness-connections.socket').read_text()
+ self.assertIn('ListenStream=127.0.0.1:51793', socket)
+ self.assertIn('harness-connections.socket', (destination / 'usr/lib/systemd/user/harness-os.target').read_text())
self.assertTrue((destination / 'usr/share/licenses/harness-os-connections/LICENSE').is_file())
self.assertIn('harness connections', (destination / 'usr/share/harness-os/connections.md').read_text())
self.assertIn('/usr/lib/harness-os/connections/connections.py', (destination / 'usr/bin/harness').read_text())
diff --git a/os/tools/fedora_payload.py b/os/tools/fedora_payload.py
index f35197b5b..9f4263f9c 100644
--- a/os/tools/fedora_payload.py
+++ b/os/tools/fedora_payload.py
@@ -62,7 +62,8 @@ def stage(source, runtime, destination, commit, runtime_commit, agent=None):
['session', 'session-settings.py', 'runtime-path', 'wait-runtime', 'virtio-2d', 'open-wifi', 'open-updates', 'screen-action', 'screenshot', 'lock', 'files']],
*['usr/lib/systemd/user/' + name for name in
['harness-os.target', 'hn-screen.service', 'harness-daemon.service', 'harness-idle.service',
- 'harness-update.service', 'harness-update.timer']],
+ 'harness-update.service', 'harness-update.timer', 'harness-connections.socket',
+ 'harness-connections.service']],
]
for name in paths:
target = destination / name