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(connectors): REST tools served as MCP, and the Harness gateway instead of Grid's

bubu-dudu43648b263b92
diff --git a/cli/src/lib/connectors/README.md b/cli/src/lib/connectors/README.md
index 3b24122a8..a1af40e7c 100644
--- a/cli/src/lib/connectors/README.md
+++ b/cli/src/lib/connectors/README.md
@@ -23,11 +23,10 @@ harness connections call github GET https://api.github.com/user
## Which services
-The list is the Grid app's: the connector gateway's `GET /v1/grid/connectors`. Signed in
-(`harness login`), the page follows that live list; signed out or offline it shows the bundled
-snapshot, `assets/catalog.json`; signed out, the services that need the gateway wait for
-`harness login`. `scripts/update-connector-catalog.ts` rebuilds the snapshot and its icons from the
-gateway; `scripts/connector-assets.mjs` turns `assets/` into `generated/` (cli.js carries them; a spec
+The list is the Grid app's, bundled as `assets/catalog.json`. Signed in (`harness login`), the Harness
+connector gateway's `GET /api/connectors` adds which `app` services it signs in to; signed out, those
+wait for `harness login`. `scripts/update-connector-catalog.ts` rebuilds the snapshot and its icons from
+Grid's catalog; `scripts/connector-assets.mjs` turns `assets/` into `generated/` (cli.js carries them; a spec
keeps the two in step). Codes are Grid's; a connection saved under an earlier code (`apollo`,
`supermetrics_marketing`) is read under Grid's (`apollo_io`, `supermetrics`).
@@ -41,12 +40,22 @@ involved. Renewal goes straight to the service's token endpoint. 78 of Grid's 86
every one Grid marks `dcr`, plus Linear, Notion, Amplitude and monday.com, which Grid signs in through
its gateway but whose MCP servers also allow self-registration.
-**`app`: through the Autonomous connector gateway** (`gateway.ts`). These services let no 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 Grid session `harness login` keeps in
-`~/.grid/credentials.toml`. GitHub, Slack, Asana, HubSpot, Gmail, Google Calendar, Google Drive, Figma
-(`figma-api-app`). Signed out, they are listed with Connect disabled and "Needs harness login".
+**`app`: through the Harness connector gateway** (`gateway.ts`; backend `routes/connectors.ts`, the same
+requests as Grid's). These services let no computer register itself, so the OAuth app Autonomous
+registered with them is used: `POST /api/connectors/start`, the browser signs in, then
+`/api/connectors/poll` returns the token once. The gateway holds the app's secret and renews tokens
+(`/api/connectors/refresh`); a grant it no longer holds marks the connection "Reconnect". It asks with
+the Harness sign-in (`~/.harness/auth/session.json`, `lib/controlPlane.ts`). GitHub, Slack, Asana,
+HubSpot, Gmail, Google Calendar, Google Drive, Figma (`figma-api-app`). Signed out, they are listed with
+Connect disabled and "Needs harness login".
+
+**REST tools as MCP** (`rest.ts`). Gmail, Google Drive, Google Calendar and Figma have no MCP server the
+grant can use. As in the Grid app, the gateway sends their `rest_entry` (each tool one HTTPS request
+template) with `transport: rest`, and the bridge is their MCP server: `tools/list` from the entry,
+`tools/call` sent from this computer with the token in the entry's header. Path values are
+percent-encoded, an optional parameter left out is left out, Gmail's message is RFC 2822 (UTF-8, no header
+injection) in base64url, a Drive upload is `multipart/related`, and a failed call is a result the model
+reads (`isError`), in words a person can act on.
**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.
@@ -59,14 +68,16 @@ written atomically under one lock shared by every agent, the bridge and the page
them in `~/.local/share/harness-os/connections`; they are moved here the first time.
- `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}`.
+ `account_name`, `source` (`dcr`/`gateway`/`custom`), `mcp_entry {url, headers}`, or `rest_entry` and
+ `transport` for a REST-backed service.
- `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 (`agents.ts`). Each connection with an MCP server becomes an entry
+Agent configs never hold a token (`agents.ts`). Each connection with tools (an MCP server, or REST tools
+the bridge serves) becomes an entry
pointing at `http://127.0.0.1:51793/<capability>/<code>/mcp`:
| Agent | File | Entry |
diff --git a/cli/src/lib/connectors/agents.ts b/cli/src/lib/connectors/agents.ts
index f917773d5..0f9b0291a 100644
--- a/cli/src/lib/connectors/agents.ts
+++ b/cli/src/lib/connectors/agents.ts
@@ -12,6 +12,7 @@ import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync, mkdi
import { homedir } from 'node:os'
import { delimiter, dirname, join } from 'node:path'
import { CODE, locked, writePrivate, type Store } from './store.js'
+import { transport } from './rest.js'
/** The bridge's fixed address, which every agent entry names. HARNESS_CONNECTIONS_PORT moves it (tests). */
export function bridgePort(env: NodeJS.ProcessEnv = process.env): number {
@@ -135,9 +136,9 @@ export function agents(env: NodeJS.ProcessEnv = process.env): Agent[] {
]
}
-/** Give every installed agent exactly the connections that have MCP tools. */
+/** Give every installed agent exactly the connections that have MCP tools (their own, or REST served as MCP). */
export function sync(vault: Store, env: NodeJS.ProcessEnv = process.env, list: Agent[] = agents(env)): Record<string, string[]> {
- const codes = Object.entries(vault.tokens()).filter(([code, token]) => token.mcp_entry && CODE.test(code)).map(([code]) => code)
+ const codes = Object.entries(vault.tokens()).filter(([code, token]) => transport(token) !== 'none' && CODE.test(code)).map(([code]) => code)
const key = codes.length ? bridgeKey(vault) : ''
const wanted = Object.fromEntries(codes.map(code => [code, bridgeUrl(key, code, bridgePort(env))]))
return locked(vault.root, () => {
diff --git a/cli/src/lib/connectors/bridge.ts b/cli/src/lib/connectors/bridge.ts
index 3b9e57be6..3dd0af939 100644
--- a/cli/src/lib/connectors/bridge.ts
+++ b/cli/src/lib/connectors/bridge.ts
@@ -1,7 +1,8 @@
/**
* The local MCP bridge: agents call http://127.0.0.1:51793/<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, and streams
- * the answer back (event streams included). Runs in the daemon (services/connectors.ts).
+ * the answer back (event streams included). A service reached by REST (no MCP server the grant can use) is
+ * answered here instead, its REST tools served as MCP (rest.ts). Runs in the daemon (services/connectors.ts).
*/
import { timingSafeEqual } from 'node:crypto'
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
@@ -9,6 +10,7 @@ import { Readable } from 'node:stream'
import { label } from './catalog.js'
import { needsRefresh, refreshable, type Store, type Token } from './store.js'
import { refresh } from './renew.js'
+import { answer as answerRest, transport } from './rest.js'
/** Headers an MCP client sends that the service must see. Authorization never comes from the agent. */
const FORWARD = ['accept', 'content-type', 'mcp-session-id', 'mcp-protocol-version', 'last-event-id']
@@ -64,6 +66,24 @@ export function createBridge(vault: Store, options: BridgeOptions): Server {
return fetch(upstream, { method: request.method, headers, body: body ?? undefined, redirect: 'manual', signal: AbortSignal.timeout(300_000) })
}
+ /** A REST-backed connection: this bridge is its MCP server (rest.ts), reading the store per call. */
+ const serveRest = async (code: string, request: IncomingMessage, response: ServerResponse, body: Buffer | null): Promise<void> => {
+ // No event stream to offer: 405 is how an MCP server says so (MCP streamable HTTP).
+ if (request.method !== 'POST') { response.writeHead(405, { Allow: 'POST', 'Content-Length': 0 }).end(); return }
+ let message: unknown
+ try { message = JSON.parse(body?.toString('utf8') ?? '') } catch { message = undefined }
+ const reply = message === undefined
+ ? { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }
+ : await answerRest(message, () => vault.token(code)?.rest_entry ?? null, async () => {
+ const token = vault.token(code)
+ if (!token) throw new Error('That connection is no longer connected. Reconnect it in harness connections and try again.')
+ return needsRefresh(token) ? refresh(vault, code) : token
+ })
+ if (!reply) { response.writeHead(202, { 'Content-Length': 0 }).end(); return }
+ const raw = JSON.stringify(reply)
+ response.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(raw) }).end(raw)
+ }
+
const relay = async (request: IncomingMessage, response: ServerResponse): Promise<void> => {
// Only a process on this computer that knows this user's key gets through; never a web page.
if (request.headers.origin || !['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(request.socket.remoteAddress ?? '')) {
@@ -75,10 +95,13 @@ export function createBridge(vault: Store, options: BridgeOptions): Server {
let body: Buffer | null
try { body = await readBody(request) } catch { fail(response, 413, 'Request is too large.'); return }
const name = vault.token(code)?.label || label(code)
- let token: Token | undefined
+ let stored: Token | undefined
+ try { stored = vault.token(code) } catch (error) { fail(response, 401, `${name}: ${(error as Error).message}`); return }
+ const via = stored ? transport(stored) : 'none'
+ if (!stored || via === 'none') { fail(response, 404, `${name} is not connected. Open harness connections to connect it.`); return }
+ if (via === 'rest') { await serveRest(code, request, response, body); return }
+ let token = stored
try {
- token = vault.token(code)
- if (!token?.mcp_entry) { fail(response, 404, `${name} is not connected. Open harness connections to connect it.`); return }
if (needsRefresh(token)) token = await refresh(vault, code)
} catch (error) { fail(response, 401, `${name}: ${(error as Error).message}`); return }
let answer: Response
diff --git a/cli/src/lib/connectors/connect.ts b/cli/src/lib/connectors/connect.ts
index 2b88cd6e9..3b4bcc87f 100644
--- a/cli/src/lib/connectors/connect.ts
+++ b/cli/src/lib/connectors/connect.ts
@@ -10,10 +10,10 @@ import { LocalSignIn, type SignIn } from './oauth.js'
import { sync } from './agents.js'
/** The sign-in that connects CODE: the gateway's or this computer's own. */
-export function signInFor(vault: Store, code: string, items: Record<string, CatalogItem>, env: NodeJS.ProcessEnv = process.env): SignIn {
+export function signInFor(vault: Store, code: string, items: Record<string, CatalogItem>): SignIn {
const item = items[code]
if (!item) throw new ConnectorError('This service is not available. Run harness login to see every service.')
- return item.auth === 'app' ? new gateway.GatewaySignIn(code, env) : new LocalSignIn(vault, item.mcp_url!)
+ return item.auth === 'app' ? new gateway.GatewaySignIn(code) : new LocalSignIn(vault, item.mcp_url!)
}
export function finish(vault: Store, code: string, token: Token, label?: string, env: NodeJS.ProcessEnv = process.env): void {
@@ -23,7 +23,7 @@ export function finish(vault: Store, code: string, token: Token, label?: string,
}
export async function disconnect(vault: Store, code: string, env: NodeJS.ProcessEnv = process.env): Promise<void> {
- if (vault.token(code)?.source === 'gateway') await gateway.disconnect(code, env)
+ if (vault.token(code)?.source === 'gateway') await gateway.disconnect(code)
vault.disconnect(code)
try { sync(vault, env) } catch { /* As above. */ }
}
@@ -71,10 +71,10 @@ export class Flows {
export type Card = Status & { description: string, auth: string, custom: boolean, reason: string }
/** The cards: every service, then connections no list names (custom servers, or ones Grid dropped). */
-export function cards(vault: Store, offered: Record<string, GatewayRow>, env: NodeJS.ProcessEnv = process.env): { connections: Card[], signed_in: boolean } {
+export function cards(vault: Store, offered: Record<string, GatewayRow>): { connections: Card[], signed_in: boolean } {
const tokens = vault.tokens()
const known = services(offered)
- const signedIn = gateway.session(env) !== null
+ const signedIn = gateway.backend.signedIn()
const result: Card[] = []
for (const [code, item] of Object.entries(known)) {
result.push({ ...vault.status(code, item.label, tokens[code]), name: item.label, description: item.description, auth: item.auth, custom: false,
diff --git a/cli/src/lib/connectors/connectors.spec.ts b/cli/src/lib/connectors/connectors.spec.ts
index da04ea50f..8062071da 100644
--- a/cli/src/lib/connectors/connectors.spec.ts
+++ b/cli/src/lib/connectors/connectors.spec.ts
@@ -4,7 +4,7 @@
*/
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync, chmodSync } from 'node:fs'
-import { request as httpRequest } from 'node:http'
+import { createServer, request as httpRequest } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { FakeGateway, FakeService } from '../../testing/connectorServers.js'
@@ -28,10 +28,13 @@ const closers: (() => void)[] = []
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), 'connectors-'))
- env = { HOME: home, PATH: '', XDG_CONFIG_HOME: join(home, '.config'), GRID_HOME: join(home, '.grid'), CODEX_HOME: join(home, '.codex'), HARNESS_CONNECTIONS_PORT: '51793' }
+ env = { HOME: home, PATH: '', XDG_CONFIG_HOME: join(home, '.config'), CODEX_HOME: join(home, '.codex'), HARNESS_CONNECTIONS_PORT: '51793' }
vault = new Store(join(home, '.harness', 'connections'), env)
+ // Signed out of Harness whatever this computer is, unless a test signs in to a fake gateway.
+ gateway.backend.signedIn = () => false
})
-afterEach(() => { while (closers.length) closers.pop()!(); rmSync(home, { recursive: true, force: true }) })
+const signedInHere = gateway.backend.signedIn
+afterEach(() => { gateway.backend.signedIn = signedInHere; while (closers.length) closers.pop()!(); rmSync(home, { recursive: true, force: true }) })
async function service(): Promise<FakeService> {
const fake = await new FakeService().start()
@@ -177,41 +180,80 @@ describe('agent configs', () => {
})
describe('the connector gateway', () => {
- async function signedIn(): Promise<FakeGateway> {
+ const original = { ...gateway.backend }
+ afterEach(() => { Object.assign(gateway.backend, original) })
+
+ /** Signed in to Harness, the backend being a fake gateway. */
+ async function signedIn(session = 'harness-session'): Promise<FakeGateway> {
const fake = await new FakeGateway().start()
closers.push(() => fake.close())
- mkdirSync(join(home, '.grid'))
- writeFileSync(join(home, '.grid', 'credentials.toml'), `session_token = "grid-session"\napi_url = "${fake.base}"\n\n[device]\nid = "x"\n`)
+ Object.assign(gateway.backend, { signedIn: () => true, base: async () => fake.base, headers: async () => ({ authorization: `Bearer ${session}`, 'x-autonomous-env': 'prod' }) })
return fake
}
it('signs in a service with no self-registration through the gateway, renews and disconnects it', async () => {
const fake = await signedIn()
- expect(Object.keys(await gateway.available(env))).toContain('github')
- const flow = signInFor(vault, 'github', services(await gateway.available(env)), env)
+ expect(Object.keys(await gateway.available())).toContain('github')
+ const flow = signInFor(vault, 'github', services(await gateway.available()))
expect(await flow.prepare()).toMatch(/^https:\/\/github\.com\//)
finish(vault, 'github', await flow.wait(), undefined, env)
- expect(vault.token('github')).toMatchObject({ source: 'gateway', account_name: 'octo', access_token: 'gho-fixture' })
- await refresh(vault, 'github', true).catch(() => undefined)
+ expect(vault.token('github')).toMatchObject({ source: 'gateway', account_name: 'octo', access_token: 'gho-fixture', transport: 'mcp' })
+ expect((await refresh(vault, 'github', true)).access_token).toBe('gho-renewed')
+ await disconnect(vault, 'github', env)
+ expect(fake.calls.map(([path]) => path)).toEqual(['connectors/start', 'connectors/poll', 'connectors/poll', 'connectors/refresh', 'connectors/disconnect'])
+ expect(vault.token('github')).toBeUndefined()
}, 15_000)
+ it('a grant the gateway no longer holds asks for connecting again; a lapsed Harness sign-in says so', async () => {
+ const fake = await signedIn()
+ const due = { access_token: 'gho-old', refresh: true, source: 'gateway' as const, expires_at: Math.floor(Date.now() / 1000) + 60 }
+ vault.save('github', due)
+ fake.fail = { status: 404, code: 'NOT_CONNECTED', message: 'This service is not connected. Connect it again.' }
+ await expect(refresh(vault, 'github')).rejects.toThrow('connected again')
+ expect(vault.token('github')).toMatchObject({ needs_reconnect: true })
+ vault.save('github', due)
+ fake.fail = { status: 503, code: 'CONNECTORS_FAILED', message: 'Connections are unavailable. Try again.' }
+ await expect(refresh(vault, 'github')).rejects.toThrow('Connections are unavailable. Try again.')
+ expect(vault.token('github')!.needs_reconnect).toBeUndefined()
+ fake.fail = { status: 502, code: '', message: '' }
+ await expect(gateway.call('connectors/refresh', {})).rejects.toThrow('Harness answered 502. Try again shortly.')
+ await signedIn('expired')
+ await expect(refresh(vault, 'github')).rejects.toThrow('Your Harness sign-in has expired')
+ expect(await gateway.available()).toEqual({})
+ Object.assign(gateway.backend, { headers: async () => { throw new Error('Not signed in. Run `harness login`.') } })
+ await expect(gateway.call('connectors')).rejects.toThrow('Could not reach Harness')
+ Object.assign(gateway.backend, { signedIn: () => false })
+ await expect(new gateway.GatewaySignIn('github').prepare()).rejects.toThrow('Sign in to Harness first')
+ })
+
+ it('refuses an answer that is not the gateway\'s', async () => {
+ const odd = createServer((request, response) => response.writeHead(200, { 'Content-Type': 'application/json' }).end(request.url === '/api/list' ? '{"success":true,"data":[]}' : 'not json'))
+ await new Promise<void>(resolve => odd.listen(0, '127.0.0.1', resolve))
+ closers.push(() => odd.close())
+ Object.assign(gateway.backend, { signedIn: () => true, base: async () => `http://127.0.0.1:${(odd.address() as { port: number }).port}`, headers: async () => ({}) })
+ await expect(gateway.call('connectors')).rejects.toThrow('Harness sent an unexpected answer.')
+ await expect(gateway.call('list')).rejects.toThrow('Harness sent an unexpected answer.')
+ })
+
it('signed out, lists the gateway services waiting for harness login; signed in, follows the gateway', async () => {
- let page = cards(vault, {}, env)
+ Object.assign(gateway.backend, { signedIn: () => false })
+ let page = cards(vault, {})
const byCode = (list: typeof page.connections) => Object.fromEntries(list.map(card => [card.connector, card]))
expect(page.signed_in).toBe(false)
for (const code of ['github', 'gmail', 'google_calendar', 'google_drive']) expect(byCode(page.connections)[code].reason).toBe('Needs harness login')
expect(byCode(page.connections).linear).toMatchObject({ auth: 'dcr', reason: '' })
await signedIn()
- const offered = await gateway.available(env)
- page = cards(vault, offered, env)
+ const offered = await gateway.available()
+ page = cards(vault, offered)
+ expect(page.signed_in).toBe(true)
const cardsNow = byCode(page.connections)
expect(cardsNow.github.auth).toBe('app')
expect(cardsNow.linear.auth).toBe('dcr')
expect(cardsNow.newsvc).toMatchObject({ name: 'New Service', auth: 'dcr' })
expect(cardsNow.slack).toBeUndefined()
expect(cardsNow['manual-only']).toBeUndefined()
- expect(signInFor(vault, 'newsvc', services(offered), env)).toBeInstanceOf(LocalSignIn)
- expect(signInFor(vault, 'github', services(offered), env)).toBeInstanceOf(gateway.GatewaySignIn)
+ expect(signInFor(vault, 'newsvc', services(offered))).toBeInstanceOf(LocalSignIn)
+ expect(signInFor(vault, 'github', services(offered))).toBeInstanceOf(gateway.GatewaySignIn)
})
})
diff --git a/cli/src/lib/connectors/gateway.ts b/cli/src/lib/connectors/gateway.ts
index 0edfe638a..623173126 100644
--- a/cli/src/lib/connectors/gateway.ts
+++ b/cli/src/lib/connectors/gateway.ts
@@ -1,62 +1,62 @@
/**
- * The Autonomous connector gateway, for services that let no 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, read as lib/localModels.ts reads it for the model catalog.
+ * The Harness connector gateway (backend `routes/connectors.ts`), for services that let no computer
+ * register itself (the `app` path, the same requests as Grid's gateway). 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 asks
+ * with the Harness sign-in `harness login` keeps (~/.harness/auth/session.json), as every other
+ * control-plane call does (lib/controlPlane.ts).
*/
-import { readFileSync } from 'node:fs'
-import { homedir } from 'node:os'
-import { join } from 'node:path'
-import { bearer, cleanUrl, ConnectorError, type Token } from './store.js'
+import { hasAuthSession } from '../authSession.js'
+import { bearer, ConnectorError, type Token } from './store.js'
import type { GatewayRow } from './catalog.js'
+import { cleanRestEntry } from './rest.js'
import type { SignIn } from './oauth.js'
const TIMEOUT_MS = 20_000
-const DEFAULT_API = 'https://api-grid.autonomous.ai'
+/** The gateway's answers that mean the service's own grant is gone: connect it again. */
+const GRANT_GONE = ['INVALID_GRANT', 'NOT_CONNECTED']
export class GatewayError extends ConnectorError {}
-/** [api url, session token] from credentials.toml's top table, or null when signed out. */
-export function session(env: NodeJS.ProcessEnv = process.env): [string, string] | null {
- const home = env.GRID_HOME ? env.GRID_HOME.replace(/^~(?=$|\/)/, env.HOME || homedir()) : join(env.HOME || homedir(), '.grid')
- let top: string
- try { top = readFileSync(join(home, 'credentials.toml'), 'utf8').split(/^\s*\[/m)[0] } catch { return null }
- const value = (name: string): string => {
- const match = new RegExp(`^\\s*${name}\\s*=\\s*("(?:[^"\\\\]|\\\\.)*"|'[^']*')\\s*$`, 'm').exec(top)
- if (!match) return ''
- try { return match[1][0] === '"' ? JSON.parse(match[1]) : match[1].slice(1, -1) } catch { return '' }
- }
- const token = value('session_token')
- if (!token) return null
- const base = value('api_url') || env.GRID_CONTROL_PLANE_URL || DEFAULT_API
- try { cleanUrl(base) } catch { return null }
- return [base.replace(/\/$/, ''), token]
+/**
+ * How this computer reaches the Harness backend. Loaded when first asked: the control plane's module
+ * reads the CLI's whole settings, which the page and the bridge never otherwise need. Tests replace it.
+ */
+export const backend = {
+ signedIn: (): boolean => hasAuthSession(),
+ base: async (): Promise<string> => (await import('../controlPlane.js')).backendHttpBase(),
+ /** Bearer + environment headers, the sign-in renewed first when it is about to expire. */
+ headers: async (): Promise<Record<string, string>> => (await (await import('../controlPlane.js')).controlPlaneAuth()).headers,
}
-export async function call(path: string, body?: unknown, env: NodeJS.ProcessEnv = process.env): Promise<Record<string, unknown>> {
- const found = session(env)
- if (!found) throw new GatewayError('Sign in to Harness first (harness login) to connect this service.')
- const [base, token] = found
+export async function call(path: string, body?: unknown): Promise<Record<string, unknown>> {
+ if (!backend.signedIn()) throw new GatewayError('Sign in to Harness first (harness login) to connect this service.')
let response: Response
try {
- response = await fetch(`${base}/v1/grid/${path}`, {
+ const [base, headers] = await Promise.all([backend.base(), backend.headers()])
+ response = await fetch(`${base}/api/${path}`, {
method: body === undefined ? 'GET' : 'POST', body: body === undefined ? undefined : JSON.stringify(body), redirect: 'error',
- headers: { Authorization: `Bearer ${token}`, Accept: 'application/json', 'Content-Type': 'application/json', 'User-Agent': 'Harness-Connections' },
+ headers: { ...headers, Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }), 'User-Agent': 'Harness-Connections' },
signal: AbortSignal.timeout(TIMEOUT_MS),
})
- } catch { throw new GatewayError('Could not reach the connector service. Check the connection and try again.') }
+ } catch { throw new GatewayError('Could not reach Harness. Check the connection and try again.') }
+ let envelope: { success?: boolean, data?: unknown, error?: { code?: string, message?: string } } | null
+ try { envelope = await response.json() as typeof envelope } catch { envelope = null }
+ const code = envelope?.error?.code ?? ''
+ // Told apart from the account's sign-in by the gateway's code: renew.ts marks the connection for reconnecting.
+ if (GRANT_GONE.includes(code)) throw new GatewayError('invalid_grant')
if (response.status === 401 || response.status === 403) throw new GatewayError('Your Harness sign-in has expired. Run harness login, then try again.')
- if (!response.ok) throw new GatewayError(`The connector service answered ${response.status}. Try again shortly.`)
- let data: unknown
- try { data = await response.json() } catch { data = null }
- if (!data || typeof data !== 'object' || Array.isArray(data)) throw new GatewayError('The connector service sent an unexpected answer.')
+ if (!response.ok || envelope?.success === false) {
+ throw new GatewayError(envelope?.error?.message || `Harness answered ${response.status}. Try again shortly.`)
+ }
+ const data = envelope?.data
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new GatewayError('Harness sent an unexpected answer.')
return data as Record<string, unknown>
}
/** {code: row} the gateway offers this account; empty when signed out or offline. */
-export async function available(env: NodeJS.ProcessEnv = process.env): Promise<Record<string, GatewayRow>> {
+export async function available(): Promise<Record<string, GatewayRow>> {
try {
- const rows = (await call('connectors', undefined, env)).connectors
+ const rows = (await call('connectors')).connectors
if (!Array.isArray(rows)) return {}
return Object.fromEntries(rows.filter((row): row is GatewayRow => row && typeof row === 'object' && typeof row.code === 'string').map(row => [row.code, row]))
} catch { return {} }
@@ -80,6 +80,10 @@ export function tokenFrom(payload: Record<string, unknown>, previous?: Token): T
const headers = mcp.headers && typeof mcp.headers === 'object' ? mcp.headers as Record<string, string> : { Authorization: bearer(token) }
token.mcp_entry = { url: mcp.url, headers }
}
+ // Sent verbatim, the token not filled in: the bridge fills it per call, so a renewal never goes stale.
+ const rest = cleanRestEntry(payload.rest_entry)
+ if (rest) token.rest_entry = rest
+ if (payload.transport === 'mcp' || payload.transport === 'rest' || payload.transport === 'none') token.transport = payload.transport
return token
}
@@ -87,10 +91,10 @@ export class GatewaySignIn implements SignIn {
private pickup = ''
private interval = 2
private expires = 600
- constructor(private readonly code: string, private readonly env: NodeJS.ProcessEnv = process.env) {}
+ constructor(private readonly code: string) {}
async prepare(): Promise<string> {
- const started = await call('connectors/start', { connector: this.code }, this.env)
+ const started = await call('connectors/start', { connector: this.code })
const url = started.authorize_url
if (typeof started.pickup_code !== 'string' || typeof url !== 'string' || !url.startsWith('https://')) {
throw new GatewayError('The connector service could not start this sign-in.')
@@ -104,7 +108,7 @@ export class GatewaySignIn implements SignIn {
async wait(cancelled: () => boolean = () => false): Promise<Token> {
const deadline = Date.now() + this.expires * 1000
while (Date.now() < deadline && !cancelled()) {
- const result = await call('connectors/poll', { pickup_code: this.pickup }, this.env)
+ const result = await call('connectors/poll', { pickup_code: this.pickup })
if (result.status === 'ready') return tokenFrom(result)
if (result.status === 'failed' || result.status === 'expired' || result.status === 'consumed') {
throw new GatewayError(typeof result.error === 'string' && result.error ? result.error : 'The sign-in did not finish. Try again.')
@@ -117,11 +121,11 @@ export class GatewaySignIn implements SignIn {
}
/** The gateway holds the refresh token and the app's secret. A refused session keeps the stored token. */
-export async function refresh(code: string, token: Token, env: NodeJS.ProcessEnv = process.env): Promise<Token> {
- return tokenFrom(await call('connectors/refresh', { connector: code }, env), token)
+export async function refresh(code: string, token: Token): Promise<Token> {
+ return tokenFrom(await call('connectors/refresh', { connector: code }), token)
}
-export async function disconnect(code: string, env: NodeJS.ProcessEnv = process.env): Promise<void> {
- // Forgetting it here is what was asked; the gateway's copy expires on its own.
- await call('connectors/disconnect', { connector: code }, env).catch(() => undefined)
+export async function disconnect(code: string): Promise<void> {
+ // Forgetting it here is what was asked; a gateway that cannot be reached forgets its copy on the next sign-in.
+ await call('connectors/disconnect', { connector: code }).catch(() => undefined)
}
diff --git a/cli/src/lib/connectors/page.ts b/cli/src/lib/connectors/page.ts
index 0447048f8..4280bee84 100644
--- a/cli/src/lib/connectors/page.ts
+++ b/cli/src/lib/connectors/page.ts
@@ -55,7 +55,7 @@ export class PageServer {
async gatewayOffers(): Promise<Record<string, GatewayRow>> {
if (Date.now() - this.offeredAt > GATEWAY_CACHE_MS) {
- this.offered = await gateway.available(this.env)
+ this.offered = await gateway.available()
this.offeredAt = Date.now()
}
return this.offered
@@ -93,7 +93,7 @@ export class PageServer {
this.lastRequest = Date.now()
try {
if (path === '/api/connections') {
- const page = cards(this.vault, await this.gatewayOffers(), this.env)
+ const page = cards(this.vault, await this.gatewayOffers())
const connections = page.connections.map(card => ({ ...card, icon: ICONS[card.connector] ? `/icons/${card.connector}` : '' }))
this.reply(response, 200, { ...page, connections })
} else this.reply(response, 200, this.flows.get(path.slice('/api/flows/'.length)))
@@ -129,7 +129,7 @@ export class PageServer {
try {
if (path === '/api/connect') {
const code = validateCode(data.connector)
- this.reply(response, 200, await this.flows.start(code, signInFor(this.vault, code, services(await this.gatewayOffers()), this.env)))
+ this.reply(response, 200, await this.flows.start(code, signInFor(this.vault, code, services(await this.gatewayOffers()))))
} else if (path === '/api/custom') {
this.reply(response, 200, await addCustom(this.vault, this.flows, data, this.env))
} else if (path === '/api/disconnect') {
diff --git a/cli/src/lib/connectors/rest.spec.ts b/cli/src/lib/connectors/rest.spec.ts
new file mode 100644
index 000000000..48ae038b5
--- /dev/null
+++ b/cli/src/lib/connectors/rest.spec.ts
@@ -0,0 +1,289 @@
+/**
+ * REST tools served as MCP (rest.ts), with the gateway's real Gmail / Drive / Calendar / Figma shapes and a
+ * stubbed fetch: never a real provider.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, rmSync } from 'node:fs'
+import { request as httpRequest } from 'node:http'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { bridgeKey, sync, type Agent } from './agents.js'
+import { createBridge } from './bridge.js'
+import { tokenFrom } from './gateway.js'
+import { answer, cleanRestEntry, encode, invoke, transport, type RestEntry } from './rest.js'
+import { Store, type Token } from './store.js'
+
+const GMAIL = {
+ auth: { in: 'header', name: 'Authorization', format: 'Bearer {access_token}' },
+ tools: [
+ { name: 'gmail_identity', description: 'Who is signed in.', request: { method: 'GET', url: 'https://www.googleapis.com/oauth2/v3/userinfo' } },
+ { name: 'gmail_send', description: 'Send an email.', params: { to: { type: 'string', required: true, description: 'Recipient' }, subject: { type: 'string', required: true }, body: { type: 'string', required: true } },
+ request: { method: 'POST', url: 'https://gmail.googleapis.com/gmail/v1/users/me/messages/send', json: { raw: { $encode: 'rfc2822_base64url', to: '{to}', subject: '{subject}', body: '{body}' } } } },
+ ],
+}
+const DRIVE = {
+ tools: [
+ { name: 'google_drive_read_file', params: { file_id: { type: 'string', required: true } }, request: { method: 'GET', url: 'https://www.googleapis.com/drive/v3/files/{file_id}', query: { alt: 'media' } } },
+ { name: 'google_drive_list_files', params: { query: { type: 'string' }, page_size: { type: 'integer' } },
+ request: { method: 'GET', url: 'https://www.googleapis.com/drive/v3/files', query: { q: '{query}', pageSize: '{page_size}', orderBy: 'modifiedTime desc' } } },
+ { name: 'google_drive_create_file', params: { name: { type: 'string', required: true }, content: { type: 'string', required: true }, content_type: { type: 'string' } },
+ request: { method: 'POST', url: 'https://www.googleapis.com/upload/drive/v3/files', query: { uploadType: 'multipart' }, multipart: { metadata: { name: '{name}' }, content: '{content}', content_type: '{content_type}' } } },
+ ],
+}
+const FIGMA = { auth: { in: 'header', name: 'X-Figma-Token', format: '{access_token}' }, tools: [{ name: 'figma_identity', request: { url: 'https://api.figma.com/v1/me' } }] }
+
+const entryOf = (raw: unknown): RestEntry => cleanRestEntry(raw)!
+const token: Token = { access_token: 'ya29.secret', token_type: 'Bearer', source: 'gateway' }
+
+let fetchMock: ReturnType<typeof vi.fn>
+const sent = () => fetchMock.mock.calls.at(-1) as [URL, RequestInit]
+function reply(status: number, body = '') { fetchMock.mockResolvedValueOnce(new Response(body || null, { status })) }
+
+beforeEach(() => { fetchMock = vi.fn(); vi.stubGlobal('fetch', fetchMock) })
+afterEach(() => { vi.unstubAllGlobals() })
+
+describe('reading a rest_entry', () => {
+ it('keeps the usable tools and fills the defaults', () => {
+ const entry = entryOf({ tools: [...DRIVE.tools, { name: 'downgraded', request: { url: 'http://www.googleapis.com/x' } }, { name: 'bad name!', request: { url: 'https://x.example' } },
+ { name: 'no_url', request: {} }, { name: 'unparsable', request: { url: 'https://' } }, { name: 'with_user', request: { url: 'https://me:[email protected]' } }, 'junk', { name: 'odd', params: { x: 'junk' }, request: { url: 'https://x.example', query: { n: 1 }, multipart: [] } }] })
+ expect(entry.auth).toEqual({ in: 'header', name: 'Authorization', format: 'Bearer {access_token}' })
+ expect(entry.tools.map(tool => tool.name)).toEqual(['google_drive_read_file', 'google_drive_list_files', 'google_drive_create_file', 'odd'])
+ expect(entry.tools[3]).toEqual({ name: 'odd', params: { x: { type: 'string' } }, request: { method: 'GET', url: 'https://x.example' } })
+ expect(entry.tools[0].request).toEqual({ method: 'GET', url: 'https://www.googleapis.com/drive/v3/files/{file_id}', query: { alt: 'media' } })
+ })
+
+ it('is no entry without a usable tool', () => {
+ for (const raw of [undefined, null, [], {}, { tools: {} }, { tools: [{ name: 'x', request: { url: 'http://x.example' } }] }]) expect(cleanRestEntry(raw)).toBeNull()
+ })
+
+ it('arrives from the gateway and survives the store, the token never filled in', () => {
+ const vault = new Store(mkdtempSync(join(tmpdir(), 'rest-store-')))
+ try {
+ const got = tokenFrom({ access_token: 'ya29.secret', refresh: true, rest_entry: GMAIL, transport: 'rest', mcp_entry: null })
+ expect(got).toMatchObject({ transport: 'rest', rest_entry: { auth: GMAIL.auth } })
+ expect(JSON.stringify(got.rest_entry)).not.toContain('ya29')
+ vault.save('gmail', got)
+ expect(vault.token('gmail')!.rest_entry!.tools.map(tool => tool.name)).toEqual(['gmail_identity', 'gmail_send'])
+ expect(vault.status('gmail', 'Gmail', vault.token('gmail')).tools).toBe(true)
+ expect(tokenFrom({ access_token: 'a', transport: 'sideways', rest_entry: 'x' })).not.toHaveProperty('transport')
+ vault.save('plain', { access_token: 'a', transport: 'none' })
+ expect(vault.token('plain')).toMatchObject({ transport: 'none' })
+ expect(vault.status('plain', 'Plain', vault.token('plain')).tools).toBe(false)
+ } finally { rmSync(vault.root, { recursive: true, force: true }) }
+ })
+})
+
+describe('which way agents reach a connection', () => {
+ const mcp = { url: 'https://mcp.example/mcp', headers: {} }
+ const rest = entryOf(GMAIL)
+ it('follows the gateway when what it names came with it, and infers otherwise', () => {
+ expect(transport({ transport: 'none', mcp_entry: mcp })).toBe('none')
+ expect(transport({ transport: 'rest', mcp_entry: mcp, rest_entry: rest })).toBe('rest')
+ expect(transport({ transport: 'rest', mcp_entry: mcp })).toBe('mcp')
+ expect(transport({ mcp_entry: mcp, rest_entry: rest })).toBe('mcp')
+ expect(transport({ transport: 'mcp', rest_entry: rest })).toBe('rest')
+ expect(transport({ access_token: 'a' })).toBe('none')
+ })
+})
+
+describe('encoders', () => {
+ it('writes an RFC 2822 message Gmail accepts, safe from header injection, Vietnamese intact', () => {
+ const raw = encode('rfc2822_base64url', { to: '[email protected]\r\nBcc: [email protected]', cc: '[email protected]', subject: 'Chào bạn', body: 'Xin chào'.repeat(20) })
+ expect(raw).not.toMatch(/[+/=]/)
+ const message = Buffer.from(raw, 'base64url').toString('utf8')
+ const [head, body] = message.split('\r\n\r\n')
+ expect(head.split('\r\n')).toEqual(['To: [email protected] Bcc: [email protected]', 'Cc: [email protected]', `Subject: =?UTF-8?B?${Buffer.from('Chào bạn').toString('base64')}?=`,
+ 'MIME-Version: 1.0', 'Content-Type: text/plain; charset="UTF-8"', 'Content-Transfer-Encoding: base64'])
+ expect(body.split('\r\n').every(line => line.length <= 76)).toBe(true)
+ expect(Buffer.from(body.replace(/\r\n/g, ''), 'base64').toString('utf8')).toBe('Xin chào'.repeat(20))
+ expect(Buffer.from(encode('rfc2822_base64url', { to: 5 }), 'base64url').toString()).toContain('To: \r\nSubject: \r\n')
+ })
+
+ it('base64url, and refuses one it does not know', () => {
+ expect(encode('base64url', { value: 'hi?>' })).toBe(Buffer.from('hi?>').toString('base64url'))
+ expect(encode('base64url', {})).toBe('')
+ expect(() => encode('rot13', {})).toThrow('does not know ("rot13")')
+ })
+})
+
+describe('calling a tool', () => {
+ const gmail = entryOf(GMAIL)
+ const drive = entryOf({ ...DRIVE, auth: GMAIL.auth })
+ const tool = (entry: RestEntry, name: string) => entry.tools.find(item => item.name === name)!
+
+ it('sends Gmail a message with the token in the entry\'s header', async () => {
+ reply(200, '{"id":"m1"}')
+ const result = await invoke(gmail, tool(gmail, 'gmail_send'), token, { to: '[email protected]', subject: 'Hi', body: 'Hello' })
+ expect(result).toEqual({ ok: true, text: '{"id":"m1"}' })
+ const [url, init] = sent()
+ expect(String(url)).toBe('https://gmail.googleapis.com/gmail/v1/users/me/messages/send')
+ expect(init).toMatchObject({ method: 'POST', redirect: 'error', headers: { Authorization: 'Bearer ya29.secret', 'Content-Type': 'application/json' } })
+ const raw = JSON.parse(init.body as string).raw
+ expect(Buffer.from(raw, 'base64url').toString()).toContain('To: [email protected]\r\nSubject: Hi\r\n')
+ })
+
+ it('checks required arguments before anything is sent', async () => {
+ expect(await invoke(gmail, tool(gmail, 'gmail_send'), token, { to: ' ', subject: null })).toEqual({ ok: false, text: 'Missing required arguments: to, subject, body.' })
+ expect((await invoke(drive, tool(drive, 'google_drive_read_file'), token, {})).text).toBe('Missing required argument: file_id.')
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('encodes path values, leaves out empty query values, and fills other auth formats', async () => {
+ reply(200)
+ expect(await invoke(drive, tool(drive, 'google_drive_read_file'), token, { file_id: '../../about?x=1' })).toEqual({ ok: true, text: '{}' })
+ expect(String(sent()[0])).toBe('https://www.googleapis.com/drive/v3/files/..%2F..%2Fabout%3Fx%3D1?alt=media')
+ reply(200, '[]')
+ await invoke(drive, tool(drive, 'google_drive_list_files'), token, { page_size: 5 })
+ expect(String(sent()[0])).toBe('https://www.googleapis.com/drive/v3/files?pageSize=5&orderBy=modifiedTime+desc')
+ const figma = entryOf(FIGMA)
+ reply(200, '{}')
+ await invoke(figma, figma.tools[0], { access_token: 'figd' }, {})
+ expect(sent()[1]).toMatchObject({ method: 'GET', headers: { 'X-Figma-Token': 'figd' } })
+ expect(sent()[1].body).toBeUndefined()
+ })
+
+ it('uploads to Drive as multipart/related', async () => {
+ reply(200, '{"id":"f1"}')
+ await invoke(drive, tool(drive, 'google_drive_create_file'), token, { name: 'notes.txt', content: 'hello', content_type: 'text/markdown' })
+ const [url, init] = sent()
+ expect(String(url)).toBe('https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart')
+ const boundary = /boundary=(.+)$/.exec((init.headers as Record<string, string>)['Content-Type'])![1]
+ expect(init.body).toBe(`--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{"name":"notes.txt"}\r\n--${boundary}\r\nContent-Type: text/markdown\r\n\r\nhello\r\n--${boundary}--`)
+ const bare = entryOf({ tools: [{ name: 'up', params: {}, request: { method: 'post', url: 'https://x.example/u', multipart: { content: 7 } } }] })
+ reply(200)
+ await invoke(bare, bare.tools[0], { access_token: 'a' }, {})
+ expect(sent()[1].method).toBe('POST')
+ expect(sent()[1].body).toMatch(/\r\n\r\n\{\}\r\n--[^\r]+\r\nContent-Type: text\/plain\r\n\r\n\r\n/)
+ })
+
+ it('says what went wrong in words a person can act on', async () => {
+ const identity = tool(gmail, 'gmail_identity')
+ const cases: [number, string, string][] = [
+ [401, '{"error":{"message":"Invalid Credentials"}}', 'The connection needs signing in again: Invalid Credentials'],
+ [403, '{"message":"Insufficient scope"}', "This account doesn't have permission for that. Reconnect it in harness connections and grant the extra access: Insufficient scope"],
+ [404, '{"detail":"No file"}', 'Not found — check the id or key that was used: No file'],
+ [429, '<html>slow down</html>', 'The service is rate-limiting this account. Try again shortly.'],
+ [503, '{"error":"down"}', 'The service had an error (503).'],
+ [418, '[]', 'The service refused the request (418).'],
+ ]
+ for (const [status, body, text] of cases) {
+ reply(status, body)
+ expect(await invoke(gmail, identity, token, {})).toEqual({ ok: false, text })
+ }
+ fetchMock.mockRejectedValueOnce(Object.assign(new Error('getaddrinfo https://www.googleapis.com/?key=x'), { name: 'TypeError' }))
+ expect(await invoke(gmail, identity, token, {})).toEqual({ ok: false, text: "Couldn't reach the service (TypeError)." })
+ })
+
+ it('refuses rather than guesses', async () => {
+ const query = entryOf({ ...GMAIL, auth: { in: 'query' } })
+ expect((await invoke(query, query.tools[0], token, {})).text).toContain('("query")')
+ const odd = entryOf({ tools: [{ name: 'x', request: { method: 'POST', url: 'https://x.example', json: { a: { $encode: 'rot13' } } } }] })
+ expect((await invoke(odd, odd.tools[0], token, {})).text).toContain('does not know ("rot13")')
+ const broken = entryOf({ tools: [{ name: 'y', params: { host: {} }, request: { url: 'https://{host}' } }] })
+ expect((await invoke(broken, broken.tools[0], token, {})).text).toMatch(/^Couldn't build the request: /)
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('fills nested bodies: lists, numbers and objects as given', async () => {
+ const cal = entryOf({ tools: [{ name: 'c', params: {}, request: { method: 'POST', url: 'https://x.example', json: { summary: '{s}', start: { dateTime: '{t}' }, tags: ['{s}', 3], n: 1, none: null } } }] })
+ reply(200, '{}')
+ await invoke(cal, cal.tools[0], {}, { s: 'Họp', t: { at: 1 } })
+ expect(JSON.parse(sent()[1].body as string)).toEqual({ summary: 'Họp', start: { dateTime: '{"at":1}' }, tags: ['Họp', 3], n: 1, none: null })
+ expect(sent()[1].headers).toMatchObject({ Authorization: 'Bearer ' })
+ })
+})
+
+describe('answering MCP', () => {
+ const entry = entryOf(GMAIL)
+ const ask = (message: unknown, fresh: () => Promise<Token> = async () => token, current: RestEntry | null = entry) => answer(message, () => current, fresh)
+
+ it('introduces itself and lists the tools', async () => {
+ expect(await ask({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18' } })).toEqual({ jsonrpc: '2.0', id: 1,
+ result: { protocolVersion: '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'harness-connector-bridge', version: '1' } } })
+ expect((await ask({ id: 2, method: 'initialize' }))!.result).toMatchObject({ protocolVersion: '2025-03-26' })
+ expect(await ask({ id: 3, method: 'ping' })).toEqual({ jsonrpc: '2.0', id: 3, result: {} })
+ const listed = (await ask({ id: 4, method: 'tools/list' }))!.result as { tools: Record<string, unknown>[] }
+ expect(listed.tools[0]).toEqual({ name: 'gmail_identity', description: 'Who is signed in.', inputSchema: { type: 'object', properties: {}, required: [] } })
+ expect(listed.tools[1].inputSchema).toEqual({ type: 'object', properties: { to: { type: 'string', description: 'Recipient' }, subject: { type: 'string' }, body: { type: 'string' } }, required: ['to', 'subject', 'body'] })
+ expect(await ask({ id: 5, method: 'tools/list' }, undefined, null)).toEqual({ jsonrpc: '2.0', id: 5, result: { tools: [] } })
+ expect(((await ask({ id: 6, method: 'tools/list' }, undefined, entryOf({ tools: [{ name: 'n', request: { url: 'https://x.example' } }] })))!.result as { tools: unknown[] }).tools[0]).toMatchObject({ description: '' })
+ })
+
+ it('calls a tool with the fresh token; a failure is a result the model reads', async () => {
+ reply(200, '{"sub":"1"}')
+ expect(await ask({ id: 7, method: 'tools/call', params: { name: 'gmail_identity', arguments: {} } }, async () => ({ access_token: 'renewed' })))
+ .toEqual({ jsonrpc: '2.0', id: 7, result: { content: [{ type: 'text', text: '{"sub":"1"}' }], isError: false } })
+ expect(sent()[1].headers).toMatchObject({ Authorization: 'Bearer renewed' })
+ expect((await ask({ id: 8, method: 'tools/call', params: { name: 'gmail_send' } }))!.result).toEqual({ content: [{ type: 'text', text: 'Missing required arguments: to, subject, body.' }], isError: true })
+ expect((await ask({ id: 9, method: 'tools/call', params: { name: 'gmail_read' } }))!.result).toMatchObject({ content: [{ text: 'This connection has no tool called "gmail_read".' }], isError: true })
+ expect((await ask({ id: 10, method: 'tools/call', params: { name: 'gmail_identity' } }, async () => { throw new Error('Reconnect it.') }))!.result)
+ .toMatchObject({ content: [{ text: 'Reconnect it.' }], isError: true })
+ })
+
+ it('takes no notification as a request and refuses what is not one', async () => {
+ expect(await ask({ jsonrpc: '2.0', method: 'notifications/initialized' })).toBeNull()
+ expect(await ask({ id: null, method: 'ping' })).toBeNull()
+ expect(await ask([1])).toEqual({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid request' } })
+ expect(await ask({ id: 'x', method: 'resources/list' })).toEqual({ jsonrpc: '2.0', id: 'x', error: { code: -32601, message: 'Method not found: resources/list' } })
+ })
+})
+
+describe('through the bridge', () => {
+ let home: string
+ let vault: Store
+ let port: number
+ let key: string
+ const closers: (() => void)[] = []
+
+ beforeEach(async () => {
+ home = mkdtempSync(join(tmpdir(), 'rest-bridge-'))
+ vault = new Store(join(home, 'connections'))
+ vault.save('gmail', tokenFrom({ access_token: 'ya29.secret', rest_entry: GMAIL, transport: 'rest' }))
+ key = bridgeKey(vault)
+ const bridge = createBridge(vault, { key: () => String(vault.file('bridge.json').key) })
+ await new Promise<void>(resolve => bridge.listen(0, '127.0.0.1', resolve))
+ port = (bridge.address() as { port: number }).port
+ closers.push(() => { bridge.close(); bridge.closeAllConnections() })
+ })
+ afterEach(() => { while (closers.length) closers.pop()!(); rmSync(home, { recursive: true, force: true }) })
+
+ function send(method: string, body = ''): Promise<{ status: number, headers: Record<string, unknown>, body: string }> {
+ return new Promise((resolve, reject) => {
+ const request = httpRequest({ host: '127.0.0.1', port, path: `/${key}/gmail/mcp`, method, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) } }, response => {
+ const chunks: Buffer[] = []
+ response.on('data', chunk => chunks.push(chunk)).on('end', () => resolve({ status: response.statusCode!, headers: response.headers, body: Buffer.concat(chunks).toString() }))
+ })
+ request.on('error', reject).end(body)
+ })
+ }
+
+ it('is the MCP server for a REST-backed connection', async () => {
+ const listed = await send('POST', '{"jsonrpc":"2.0","id":1,"method":"tools/list"}')
+ expect(listed.status).toBe(200)
+ expect(listed.headers['content-type']).toBe('application/json')
+ expect(JSON.parse(listed.body).result.tools.map((tool: { name: string }) => tool.name)).toEqual(['gmail_identity', 'gmail_send'])
+ reply(200, '{"email":"[email protected]"}')
+ const called = JSON.parse((await send('POST', '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"gmail_identity"}}')).body)
+ expect(called.result).toEqual({ content: [{ type: 'text', text: '{"email":"[email protected]"}' }], isError: false })
+ expect(sent()[1].headers).toMatchObject({ Authorization: 'Bearer ya29.secret' })
+ expect((await send('POST', '{"jsonrpc":"2.0","method":"notifications/initialized"}')).status).toBe(202)
+ expect(JSON.parse((await send('POST', '{oops')).body).error.code).toBe(-32700)
+ expect(JSON.parse((await send('POST')).body).error.code).toBe(-32700)
+ const stream = await send('GET')
+ expect([stream.status, stream.headers.allow]).toEqual([405, 'POST'])
+ })
+
+ it('says so when the connection went away mid-session', async () => {
+ const renewing = vi.spyOn(vault, 'token')
+ renewing.mockImplementation(code => code === 'gmail' && renewing.mock.calls.length > 2 ? undefined : Store.prototype.token.call(vault, code))
+ const called = JSON.parse((await send('POST', '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"gmail_identity"}}')).body)
+ expect(called.result).toMatchObject({ isError: true, content: [{ text: expect.stringContaining('no longer connected') }] })
+ })
+
+ it('gives agents the connection like any MCP one', () => {
+ const applied: Record<string, string>[] = []
+ const agent = { name: 'fake', installed: () => true, apply: (wanted: Record<string, string>) => { applied.push(wanted); return Object.keys(wanted) } } as unknown as Agent
+ sync(vault, { HOME: home }, [agent])
+ expect(Object.keys(applied[0])).toEqual(['gmail'])
+ })
+})
diff --git a/cli/src/lib/connectors/rest.ts b/cli/src/lib/connectors/rest.ts
new file mode 100644
index 000000000..cf6893c11
--- /dev/null
+++ b/cli/src/lib/connectors/rest.ts
@@ -0,0 +1,256 @@
+/**
+ * A connector's REST surface served to agents as MCP tools, as the Grid app does (connector_bridge.dart,
+ * rest_invoker.dart, rest_encoders.dart, rest_entry.dart). Some services have no MCP server the grant can
+ * use (Gmail with only gmail.send, Google Drive, Calendar, Figma) but a REST API that works with the token:
+ * the gateway sends their `rest_entry` (tools, each one HTTP request template) and the bridge answers
+ * `tools/list` and `tools/call` from it. No service is named here: everything specific is in the entry.
+ */
+import { randomUUID } from 'node:crypto'
+import { ConnectorError, type Token } from './store.js'
+
+export type Transport = 'mcp' | 'rest' | 'none'
+export interface RestAuth { in: string, name: string, format: string }
+export interface RestParam { type: string, required?: boolean, description?: string }
+export interface RestRequest {
+ method: string
+ url: string
+ query?: Record<string, string>
+ json?: unknown
+ multipart?: Record<string, unknown>
+}
+export interface RestTool { name: string, description?: string, params: Record<string, RestParam>, request: RestRequest }
+export interface RestEntry { auth: RestAuth, tools: RestTool[] }
+export interface RestResult { ok: boolean, text: string }
+
+const TIMEOUT_MS = 30_000
+const MAX_TOOLS = 64
+const NAME = /^[A-Za-z0-9_-]{1,64}$/
+/** The transformations a request body may name, and nothing else: an unknown one is refused, not guessed. */
+export const ENCODERS = new Set(['rfc2822_base64url', 'base64url'])
+
+const record = (value: unknown): Record<string, unknown> | null => value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null
+const str = (value: unknown, fallback = ''): string => typeof value === 'string' && value ? value : fallback
+
+function cleanRequest(raw: unknown): RestRequest | null {
+ const entry = record(raw)
+ if (!entry || typeof entry.url !== 'string') return null
+ // https only: the credential rides on this request, and the gateway may not downgrade it.
+ let url: URL
+ try { url = new URL(entry.url) } catch { return null }
+ if (url.protocol !== 'https:' || !url.hostname || url.username || url.password) return null
+ const query: Record<string, string> = {}
+ for (const [name, value] of Object.entries(record(entry.query) ?? {})) if (typeof value === 'string') query[name] = value
+ const request: RestRequest = { method: str(entry.method, 'GET').toUpperCase(), url: entry.url }
+ if (Object.keys(query).length) request.query = query
+ if (entry.json !== undefined && entry.json !== null) request.json = entry.json
+ const multipart = record(entry.multipart)
+ if (multipart) request.multipart = multipart
+ return request
+}
+
+function cleanTool(raw: unknown): RestTool | null {
+ const entry = record(raw)
+ if (!entry || typeof entry.name !== 'string' || !NAME.test(entry.name)) return null
+ const request = cleanRequest(entry.request)
+ if (!request) return null
+ const params: Record<string, RestParam> = {}
+ for (const [name, value] of Object.entries(record(entry.params) ?? {})) {
+ const param = record(value) ?? {}
+ params[name] = { type: str(param.type, 'string'), ...(param.required === true ? { required: true } : {}), ...(str(param.description) ? { description: param.description as string } : {}) }
+ }
+ return { name: entry.name, ...(str(entry.description) ? { description: entry.description as string } : {}), params, request }
+}
+
+/**
+ * A rest_entry as the gateway sends it, or null when it has no usable tool. Lenient, as Grid is: a tool
+ * this version cannot read drops itself and the others still work.
+ */
+export function cleanRestEntry(raw: unknown): RestEntry | null {
+ const entry = record(raw)
+ if (!entry || !Array.isArray(entry.tools)) return null
+ const tools = entry.tools.slice(0, MAX_TOOLS).map(cleanTool).filter((tool): tool is RestTool => tool !== null)
+ if (!tools.length) return null
+ const auth = record(entry.auth) ?? {}
+ return { auth: { in: str(auth.in, 'header'), name: str(auth.name, 'Authorization'), format: str(auth.format, 'Bearer {access_token}') }, tools }
+}
+
+/** How agents reach this connection. The gateway's word wins when the entry it names came with it. */
+export function transport(token: Token): Transport {
+ if (token.transport === 'none') return 'none'
+ if (token.transport === 'rest' && token.rest_entry) return 'rest'
+ if (token.mcp_entry) return 'mcp'
+ return token.rest_entry ? 'rest' : 'none'
+}
+
+export function inputSchema(tool: RestTool): Record<string, unknown> {
+ return {
+ type: 'object',
+ properties: Object.fromEntries(Object.entries(tool.params).map(([name, param]) => [name, { type: param.type, ...(param.description ? { description: param.description } : {}) }])),
+ required: Object.entries(tool.params).filter(([, param]) => param.required).map(([name]) => name),
+ }
+}
+
+/** `{name}` replaced by that argument; one left out becomes empty, never the literal `{cc}`. */
+function substitute(template: string, args: Record<string, unknown>, urlSafe = false): string {
+ return template.replace(/\{(\w+)\}/g, (_, name: string) => {
+ const value = args[name]
+ if (value === undefined || value === null) return ''
+ const raw = typeof value === 'string' ? value : JSON.stringify(value)
+ return urlSafe ? encodeURIComponent(raw) : raw
+ })
+}
+
+const base64Url = (text: string): string => Buffer.from(text, 'utf8').toString('base64url')
+
+/** One header line: CR/LF stripped (header injection), non-ASCII as an RFC 2047 encoded-word. */
+function headerValue(raw: string): string {
+ const clean = raw.replace(/[\r\n]/g, ' ').trim()
+ if (/^[\x20-\x7e]*$/.test(clean)) return clean
+ return `=?UTF-8?B?${Buffer.from(clean, 'utf8').toString('base64')}?=`
+}
+
+/** An RFC 2822 message from to / cc / subject / body, UTF-8 throughout, CRLF line ends. */
+function rfc2822(fields: Record<string, unknown>): string {
+ const field = (name: string): string => typeof fields[name] === 'string' ? fields[name] as string : ''
+ const headers = [
+ `To: ${headerValue(field('to'))}`,
+ ...(field('cc') ? [`Cc: ${headerValue(field('cc'))}`] : []),
+ `Subject: ${headerValue(field('subject'))}`,
+ 'MIME-Version: 1.0', 'Content-Type: text/plain; charset="UTF-8"', 'Content-Transfer-Encoding: base64',
+ ]
+ const body = (Buffer.from(field('body'), 'utf8').toString('base64').match(/.{1,76}/g) ?? []).join('\r\n')
+ return `${headers.join('\r\n')}\r\n\r\n${body}`
+}
+
+export function encode(name: string, fields: Record<string, unknown>): string {
+ if (name === 'rfc2822_base64url') return base64Url(rfc2822(fields))
+ if (name === 'base64url') return base64Url(typeof fields.value === 'string' ? fields.value : '')
+ throw new ConnectorError(`This connection asked for an encoding this version of Harness does not know ("${name}"). Update Harness.`)
+}
+
+/** A body template filled in: strings substituted, a map naming `$encode` handed to that encoder. */
+function fill(template: unknown, args: Record<string, unknown>): unknown {
+ if (typeof template === 'string') return substitute(template, args)
+ if (Array.isArray(template)) return template.map(item => fill(item, args))
+ const map = record(template)
+ if (!map) return template
+ const filled = Object.fromEntries(Object.entries(map).filter(([name]) => name !== '$encode').map(([name, value]) => [name, fill(value, args)]))
+ return typeof map.$encode === 'string' ? encode(map.$encode, filled) : filled
+}
+
+function buildUrl(request: RestRequest, args: Record<string, unknown>): URL {
+ // Path values percent-encoded: a model-written `../` or `?` must not reach another endpoint.
+ const url = new URL(substitute(request.url, args, true))
+ for (const [name, template] of Object.entries(request.query ?? {})) {
+ // An optional parameter left out is absent, not empty: `timeMin=` is a 400 from Google.
+ const value = substitute(template, args)
+ if (value) url.searchParams.set(name, value)
+ }
+ return url
+}
+
+/** RFC 2387 multipart/related: a JSON metadata part, then the content. */
+function multipartBody(boundary: string, filled: unknown): string {
+ const parts = record(filled) ?? {}
+ const contentType = str(parts.content_type, 'text/plain')
+ return `--${boundary}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${JSON.stringify(parts.metadata ?? {})}\r\n`
+ + `--${boundary}\r\nContent-Type: ${contentType}\r\n\r\n${typeof parts.content === 'string' ? parts.content : ''}\r\n--${boundary}--`
+}
+
+function detail(body: string): string {
+ try {
+ const decoded = record(JSON.parse(body))
+ const error = decoded?.error
+ const message = record(error) ? record(error)!.message : (decoded?.message ?? decoded?.detail)
+ if (typeof message === 'string' && message) return `: ${message}`
+ } catch { /* Not JSON: an HTML error page helps nobody in a chat. */ }
+ return '.'
+}
+
+/** A status a person can act on. 401 and 403 mean opposite things: signed out, versus never allowed. */
+function failure(status: number, body: string): string {
+ const more = detail(body)
+ if (status === 401) return `The connection needs signing in again${more}`
+ if (status === 403) return `This account doesn't have permission for that. Reconnect it in harness connections and grant the extra access${more}`
+ if (status === 404) return `Not found — check the id or key that was used${more}`
+ if (status === 429) return `The service is rate-limiting this account. Try again shortly${more}`
+ if (status >= 500) return `The service had an error (${status})${more}`
+ return `The service refused the request (${status})${more}`
+}
+
+/** One tool call: the model's arguments into the tool's HTTP request, with the token in the entry's header. */
+export async function invoke(entry: RestEntry, tool: RestTool, token: Token, args: Record<string, unknown>): Promise<RestResult> {
+ const missing = Object.entries(tool.params).filter(([name, param]) => param.required && (args[name] === undefined || args[name] === null || String(args[name]).trim() === '')).map(([name]) => name)
+ if (missing.length) return { ok: false, text: `Missing required argument${missing.length === 1 ? '' : 's'}: ${missing.join(', ')}.` }
+ // Refused rather than guessed: a credential somewhere the service did not ask for it is worse.
+ if (entry.auth.in !== 'header') return { ok: false, text: `This connection needs a credential placed somewhere this version of Harness does not support ("${entry.auth.in}").` }
+ let url: URL
+ const headers: Record<string, string> = {
+ [entry.auth.name]: substitute(entry.auth.format, { access_token: token.access_token ?? '', token_type: token.token_type ?? 'Bearer' }),
+ Accept: 'application/json', 'User-Agent': 'Harness-Connections',
+ }
+ let body: string | undefined
+ try {
+ url = buildUrl(tool.request, args)
+ if (tool.request.multipart) {
+ const boundary = `harness-${randomUUID()}`
+ headers['Content-Type'] = `multipart/related; boundary=${boundary}`
+ body = multipartBody(boundary, fill(tool.request.multipart, args))
+ } else if (tool.request.json !== undefined) {
+ headers['Content-Type'] = 'application/json'
+ body = JSON.stringify(fill(tool.request.json, args))
+ }
+ } catch (error) {
+ return { ok: false, text: error instanceof ConnectorError ? error.message : `Couldn't build the request: ${(error as Error).message}` }
+ }
+ let response: Response
+ let text: string
+ try {
+ response = await fetch(url, { method: tool.request.method, headers, body, redirect: 'error', signal: AbortSignal.timeout(TIMEOUT_MS) })
+ text = await response.text()
+ } catch (error) {
+ // The kind, not the message: a message can carry the full URL.
+ return { ok: false, text: `Couldn't reach the service (${(error as Error).name}).` }
+ }
+ if (response.ok) return { ok: true, text: text || '{}' }
+ return { ok: false, text: failure(response.status, text) }
+}
+
+/**
+ * One JSON-RPC message for a REST-backed connection; null for a notification (no reply). `entry` is read
+ * per call, `fresh` renews the token first, so a token renewed a moment ago is the one used.
+ */
+export async function answer(message: unknown, entry: () => RestEntry | null, fresh: () => Promise<Token>): Promise<Record<string, unknown> | null> {
+ const payload = record(message)
+ if (!payload) return { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid request' } }
+ const id = payload.id
+ // A notification (notifications/initialized) takes no reply: answering it is a protocol error.
+ if (id === undefined || id === null) return null
+ const params = record(payload.params) ?? {}
+ const reply = (result: unknown) => ({ jsonrpc: '2.0', id, result })
+ const toolError = (text: string) => reply({ content: [{ type: 'text', text }], isError: true })
+ switch (payload.method) {
+ case 'initialize':
+ return reply({
+ // Echo the client's version: disagreeing fails the handshake.
+ protocolVersion: str(params.protocolVersion, '2025-03-26'),
+ capabilities: { tools: {} }, serverInfo: { name: 'harness-connector-bridge', version: '1' },
+ })
+ case 'ping':
+ return reply({})
+ case 'tools/list':
+ return reply({ tools: (entry()?.tools ?? []).map(tool => ({ name: tool.name, description: tool.description ?? '', inputSchema: inputSchema(tool) })) })
+ case 'tools/call': {
+ let token: Token
+ try { token = await fresh() } catch (error) { return toolError((error as Error).message) }
+ const current = entry()
+ const tool = current?.tools.find(item => item.name === params.name)
+ if (!current || !tool) return toolError(`This connection has no tool called "${String(params.name)}".`)
+ const result = await invoke(current, tool, token, record(params.arguments) ?? {})
+ // A failed call is a result with isError, not a JSON-RPC error: the model reads it and can act.
+ return reply({ content: [{ type: 'text', text: result.text }], isError: !result.ok })
+ }
+ default:
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${String(payload.method)}` } }
+ }
+}
diff --git a/cli/src/lib/connectors/store.ts b/cli/src/lib/connectors/store.ts
index 859a7a438..239bb23c3 100644
--- a/cli/src/lib/connectors/store.ts
+++ b/cli/src/lib/connectors/store.ts
@@ -10,6 +10,7 @@ import { closeSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFi
import { homedir } from 'node:os'
import { join } from 'node:path'
import { randomUUID } from 'node:crypto'
+import { cleanRestEntry, transport, type RestEntry, type Transport } from './rest.js'
export const MAX_BYTES = 1024 * 1024
/** A token is renewed this long before it expires, as Grid does. */
@@ -36,6 +37,10 @@ export interface Token {
refresh?: boolean
needs_reconnect?: boolean
mcp_entry?: McpEntry
+ /** A service with no usable MCP server: its REST tools, served as MCP by the bridge (rest.ts). */
+ rest_entry?: RestEntry
+ /** The gateway's word on which of the two agents use. */
+ transport?: Transport
}
export interface Client {
client_id: string
@@ -175,6 +180,9 @@ export function cleanToken(entry: unknown): Token {
const entryRaw = mcp as Record<string, unknown>
result.mcp_entry = { url: cleanUrl(entryRaw.url), headers: cleanHeaders(entryRaw.headers) }
}
+ const rest = cleanRestEntry(raw.rest_entry)
+ if (rest) result.rest_entry = rest
+ if (raw.transport === 'mcp' || raw.transport === 'rest' || raw.transport === 'none') result.transport = raw.transport
if (!result.access_token && !result.mcp_entry) throw new ConnectorError('No access token was supplied.')
return result
}
@@ -290,7 +298,7 @@ export class Store {
return {
...base, state, account: token.account_name ?? '', source: token.source ?? 'dcr',
scopes: (token.scope ?? '').split(/\s+/).filter(Boolean), expires_at: expires || null,
- auto_refresh: refreshable(token), tools: Boolean(token.mcp_entry),
+ auto_refresh: refreshable(token), tools: transport(token) !== 'none',
}
}
}
diff --git a/cli/src/services/connectors.spec.ts b/cli/src/services/connectors.spec.ts
index 64431265a..cd914b447 100644
--- a/cli/src/services/connectors.spec.ts
+++ b/cli/src/services/connectors.spec.ts
@@ -6,17 +6,21 @@ import { join } from 'node:path'
import { fakeCore } from '../testing/fakeCore.js'
import { CONNECTORS_REQUESTS, startConnectors } from './connectors.js'
import { Store } from '../lib/connectors/store.js'
+import * as gateway from '../lib/connectors/gateway.js'
const OWNER = { local: true, owner: true }
describe('the connectors service', () => {
let home: string
let env: NodeJS.ProcessEnv
+ const signedIn = gateway.backend.signedIn
beforeEach(() => {
home = mkdtempSync(join(tmpdir(), 'connectors-service-'))
- env = { HOME: home, PATH: '', GRID_HOME: join(home, '.grid'), HARNESS_CONNECTIONS_PORT: '0', XDG_CONFIG_HOME: join(home, '.config') }
+ env = { HOME: home, PATH: '', HARNESS_CONNECTIONS_PORT: '0', XDG_CONFIG_HOME: join(home, '.config') }
+ // Signed out of Harness whatever this computer is: nothing here reaches the backend.
+ gateway.backend.signedIn = () => false
})
- afterEach(() => rmSync(home, { recursive: true, force: true }))
+ afterEach(() => { gateway.backend.signedIn = signedIn; rmSync(home, { recursive: true, force: true }) })
it('answers exactly the request it declares, and only for the owner', async () => {
const requests = startConnectors(fakeCore(), { env })
diff --git a/cli/src/services/connectors.ts b/cli/src/services/connectors.ts
index 2cb811e66..b3a8911d1 100644
--- a/cli/src/services/connectors.ts
+++ b/cli/src/services/connectors.ts
@@ -41,7 +41,7 @@ export function startConnectors(_core: CoreApi, overrides: Partial<ConnectorsDep
const env = overrides.env ?? process.env
const deps: ConnectorsDeps = {
vault: overrides.vault ?? new Store(undefined, env), port: overrides.port ?? bridgePort(env),
- offered: overrides.offered ?? (() => gateway.available(env)), env, retryMs: overrides.retryMs ?? 5_000,
+ offered: overrides.offered ?? (() => gateway.available()), env, retryMs: overrides.retryMs ?? 5_000,
}
const { vault } = deps
const flows = new Flows(vault, env)
@@ -59,10 +59,10 @@ export function startConnectors(_core: CoreApi, overrides: Partial<ConnectorsDep
const answer = async (payload: Record<string, unknown>): Promise<Record<string, unknown>> => {
switch (payload.action) {
- case 'list': return { ...cards(vault, await gatewayOffers(), env) }
+ case 'list': return { ...cards(vault, await gatewayOffers()) }
case 'connect': {
const code = validateCode(payload.connector)
- return { ...(await flows.start(code, signInFor(vault, code, services(await gatewayOffers()), env))) }
+ return { ...(await flows.start(code, signInFor(vault, code, services(await gatewayOffers())))) }
}
case 'flow': return { ...flows.get(String(payload.flow ?? '')) }
case 'disconnect': {
diff --git a/cli/src/testing/connectorServers.ts b/cli/src/testing/connectorServers.ts
index 1ab309f58..808a6e8a3 100644
--- a/cli/src/testing/connectorServers.ts
+++ b/cli/src/testing/connectorServers.ts
@@ -93,24 +93,33 @@ export class FakeGateway {
async start(): Promise<this> { this.base = `http://127.0.0.1:${await listen(this.server)}`; return this }
close(): void { this.server.close(); this.server.closeAllConnections() }
+ /** An answer in the Harness backend's envelope; `fail` makes the next one a refusal with that code. */
+ fail: { status: number, code: string, message: string } | null = null
+
private async handle(request: IncomingMessage, response: ServerResponse): Promise<void> {
- if (request.headers.authorization !== 'Bearer grid-session') { send(response, 401, {}); return }
+ const ok = (data: unknown) => send(response, 200, { success: true, data })
+ if (request.headers.authorization !== 'Bearer harness-session') { send(response, 401, { success: false, error: { code: 'UNAUTHORIZED', message: 'Sign in.' } }); return }
+ if (this.fail) {
+ const { status, code, message } = this.fail
+ this.fail = null
+ send(response, status, { success: false, error: { code, message } }); return
+ }
if (request.method === 'GET') {
- send(response, 200, { connectors: [
+ ok({ connectors: [
{ code: 'github', label: 'GitHub', auth_type: 'app', mcp_url: 'https://api.githubcopilot.com/mcp/' },
{ code: 'linear', label: 'Linear', auth_type: 'app', mcp_url: 'https://mcp.linear.app/mcp' },
{ code: 'newsvc', label: 'New Service', auth_type: 'dcr', mcp_url: 'https://mcp.newsvc.example/mcp', description: 'Added to Grid after this build.' },
{ code: 'manual-only', label: 'Manual', auth_type: 'pat' },
] }); return
}
- const path = (request.url ?? '').replace('/v1/grid/', '')
+ const path = (request.url ?? '').replace('/api/', '')
const data = JSON.parse(await body(request))
this.calls.push([path, data])
- const token = { access_token: 'gho-fixture', expires_at: Math.floor(Date.now() / 1000) + 3600, refresh: true, account_name: 'octo',
+ const token = { access_token: 'gho-fixture', expires_at: Math.floor(Date.now() / 1000) + 3600, refresh: true, account_name: 'octo', transport: 'mcp', rest_entry: null,
mcp_entry: { url: 'https://api.githubcopilot.com/mcp/', headers: { Authorization: 'Bearer gho-fixture' } } }
- if (path === 'connectors/start') send(response, 200, { authorize_url: 'https://github.com/login/oauth/authorize?state=grid_x', pickup_code: 'pickup-1', poll_interval: 1, expires_in: 60 })
- else if (path === 'connectors/poll') { this.polls += 1; send(response, 200, this.polls < 2 ? { status: 'pending' } : { ...token, status: 'ready', connector: 'github' }) }
- else if (path === 'connectors/refresh') send(response, 200, { ...token, access_token: 'gho-renewed' })
- else send(response, 200, { disconnected: true })
+ if (path === 'connectors/start') ok({ authorize_url: 'https://github.com/login/oauth/authorize?state=harness_x', pickup_code: 'pickup-1', poll_interval: 1, expires_in: 60 })
+ else if (path === 'connectors/poll') { this.polls += 1; ok(this.polls < 2 ? { status: 'pending' } : { ...token, status: 'ready', connector: 'github' }) }
+ else if (path === 'connectors/refresh') ok({ ...token, access_token: 'gho-renewed' })
+ else ok({ disconnected: true })
}
}