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: give an agent on a Local model web search through the `harness` MCP server

Kelvin7a1660d6fe44
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 206578a05..b204cbf88 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -8,6 +8,8 @@ import { decodeTerminalLocal, TerminalBinaryKind } from './lib/terminalBinary.js
import { registry, type RegisteredSession } from './lib/registry.js'
import * as mediaPreview from './lib/mediaPreview.js'
import { randomUUID } from 'node:crypto'
+import { fakeGridAnswers, installFakeGrid, type FakeGrid } from './lib/__fixtures__/fakeGrid.js'
+import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'
const wsMock = vi.hoisted(() => {
const instances: MockWebSocket[] = []
@@ -1123,6 +1125,75 @@ describe('agent_retarget clearGrid', () => {
})
})
+/**
+ * The desktop's retarget names a Local model and nothing else; the daemon resolves everything from
+ * its own signed-in `grid`. This is that resolution through the real frame handler, against the
+ * plan-driven fake `grid` — the seam `gridEnsure.spec.ts` established.
+ */
+describe('agent_retarget onto a Local model resolves web tools', () => {
+ const { gridName: GRID_NAME, networkId, baseUrl: BASE_URL, mcpUrl: MCP_URL, token: TOKEN, plan } = fakeGridAnswers()
+
+ let fake: FakeGrid | null = null
+ afterEach(async () => {
+ fake?.dispose()
+ fake = null
+ clearGridMcpUrlCache()
+ wsMock.instances.length = 0
+ vi.restoreAllMocks()
+ })
+
+ async function retargetOntoLocalModel(model: string) {
+ const seen: Array<{ agentId: string; grid: unknown }> = []
+ const socket = new BackendSocket('token')
+ socket.onRetargetAgent = async (input) => { seen.push(input); return { ok: true } }
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+ // The grid name is the backend's, pushed on connect; the daemon holds it in memory only.
+ ws.message({ t: 'down', connId: 'web-1', frame: { type: 'machine_meta', payload: { name: 'mac', gridName: GRID_NAME } } })
+ ws.message({ t: 'down', connId: 'web-1', frame: { type: 'agent_retarget', payload: { requestId: 'r', agentId: 'a1', gridModel: model } } })
+ await vi.waitFor(() => expect(parseSent(ws).some((item) => (item.frame as { type?: string } | undefined)?.type === 'agent_retarget_result')).toBe(true), { timeout: 10_000 })
+ const reply = parseSent(ws)
+ .map((item) => item.frame as { type?: string; payload?: Record<string, unknown> } | undefined)
+ .find((frame) => frame?.type === 'agent_retarget_result')
+ await socket.stop()
+ return { seen, reply }
+ }
+
+ it('yields a launch override whose MCP URL is exactly the printed url, asking `mcp config` before `info --env`', async () => {
+ fake = installFakeGrid(plan)
+ const { seen, reply } = await retargetOntoLocalModel('GLM-4.7-Flash')
+ expect(reply?.payload).toMatchObject({ retargeted: true })
+ expect(seen).toEqual([{
+ agentId: 'a1',
+ grid: {
+ networkId,
+ networkName: GRID_NAME,
+ baseUrl: BASE_URL,
+ apiKey: TOKEN,
+ model: 'GLM-4.7-Flash',
+ mcpUrl: MCP_URL,
+ },
+ }])
+ expect(fake.verbs()).toEqual(['mcp', 'info', 'ls'])
+ expect(fake.calls()[0]).toEqual(['--remote', 'mcp', 'config', GRID_NAME, '--json'])
+ })
+
+ it('still retargets, with no MCP URL, when the binary is too old for `mcp config`', async () => {
+ const warned: string[] = []
+ vi.spyOn(console, 'warn').mockImplementation((...parts: unknown[]) => { warned.push(parts.map(String).join(' ')) })
+ fake = installFakeGrid({ ...plan, mcp: { exit: 2, stderr: "grid: error: invalid choice: 'mcp'\n" } })
+ const { seen, reply } = await retargetOntoLocalModel('GLM-4.7-Flash')
+ expect(reply?.payload).toMatchObject({ retargeted: true })
+ expect(seen).toHaveLength(1)
+ expect(seen[0]!.grid).toMatchObject({ baseUrl: BASE_URL, apiKey: TOKEN, model: 'GLM-4.7-Flash' })
+ expect(seen[0]!.grid).not.toHaveProperty('mcpUrl')
+ // The reason reaches the daemon log, and nothing else — the retarget error path is untouched.
+ expect(warned.join('\n')).toMatch(/web tools unavailable .* older than/)
+ expect(reply?.payload).not.toHaveProperty('error')
+ })
+})
+
describe('Autonomous direct isolation from existing relay/browser behavior', () => {
it('permits offline PAKE only for the exact live direct pending connection', async () => {
const backend = new BackendSocket('direct-offline-test')
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 0b70dffdf..e6cc88264 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -51,6 +51,7 @@ import { AuthSessionError, AuthSessionManager, clearAuthSession, readAuthSession
import { handOffToGrid } from './lib/gridHandoff.js'
import { ensureHarnessGrid } from './lib/gridEnsure.js'
import { passThroughToGridLogout } from './lib/gridLogout.js'
+import { clearGridMcpUrlCache } from './lib/gridMcpUrl.js'
import { warnIfGridSignInRemains } from './lib/gridCredentials.js'
import { ENGINE_CLI_COMMANDS, ENGINES, engineBin, enginePathOverride } from './lib/engineBin.js'
import type { AgentEngine } from './engines/types.js'
@@ -4270,6 +4271,9 @@ async function runForeground(session: AuthSession): Promise<void> {
backend.onRevoked = () => {
console.log('[cli] this computer was removed from the machine — clearing credentials and stopping')
clearAuthSession()
+ // The web-tools cache lives exactly as long as the sign-in. `harness logout` and `reset` stop
+ // the daemon outright; this is the one sign-out the daemon learns of from inside.
+ clearGridMcpUrlCache()
void shutdown('revoked')
}
diff --git a/cli/src/engines/codex/normalizer.spec.ts b/cli/src/engines/codex/normalizer.spec.ts
index 47be58033..1e4c2c572 100644
--- a/cli/src/engines/codex/normalizer.spec.ts
+++ b/cli/src/engines/codex/normalizer.spec.ts
@@ -84,6 +84,51 @@ describe('Codex rollout normalizer', () => {
])
})
+ it('renders the harness web tools as the native WebSearch / WebFetch cards', () => {
+ // Codex spells an MCP tool `mcp__<server>__<tool>` (its `non_prefixed_mcp_tool_names` feature is
+ // off by default on 0.154.0), and a rollout may also split the pair into `name` + `namespace`
+ // — both shapes were read off real rollouts on this machine.
+ const normalizer = new CodexNormalizer('live')
+ const events = [
+ line('response_item', { type: 'function_call', call_id: 'ws-1', name: 'mcp__harness__web_search', arguments: '{"query":"BTC price","num_results":5}' }),
+ line('response_item', { type: 'function_call_output', call_id: 'ws-1', output: '{"results":[]}' }),
+ line('response_item', { type: 'function_call', call_id: 'wr-1', name: 'web_read', namespace: 'mcp__harness', arguments: '{"urls":["https://a.example/"]}' }),
+ line('response_item', { type: 'function_call_output', call_id: 'wr-1', output: '{"results":[]}' }),
+ ].flatMap((raw) => normalizer.ingest(raw))
+
+ expect(events).toEqual([
+ { type: 'tool_start', payload: { id: 'ws-1', tool: 'WebSearch', input: { query: 'BTC price', num_results: 5 } } },
+ { type: 'tool_end', payload: { id: 'ws-1', tool: 'WebSearch', output: '{"results":[]}', isError: false, summary: '{"results":[]}' } },
+ { type: 'tool_start', payload: { id: 'wr-1', tool: 'WebFetch', input: { urls: ['https://a.example/'], url: 'https://a.example/' } } },
+ { type: 'tool_end', payload: { id: 'wr-1', tool: 'WebFetch', output: '{"results":[]}', isError: false, summary: '{"results":[]}' } },
+ ])
+ })
+
+ it('unwraps a code-mode call to the harness web tools the same way', () => {
+ // In code mode every tool is a JS identifier on `tools`, MCP tools included:
+ // `await tools.mcp__harness__web_search({...})` (the binary's own tool-listing prose, 0.154.0).
+ const normalizer = new CodexNormalizer('live')
+ const events = [
+ line('response_item', {
+ type: 'custom_tool_call',
+ call_id: 'web-2',
+ name: 'exec',
+ input: 'const r = await tools.mcp__harness__web_search({query:"ETH price", num_results: 3}); text(r)',
+ }),
+ line('response_item', {
+ type: 'custom_tool_call',
+ call_id: 'web-3',
+ name: 'exec',
+ input: 'const r = await tools.mcp__harness__web_read({urls:["https://a.example/", \'https://b.example/\']}); text(r)',
+ }),
+ ].flatMap((raw) => normalizer.ingest(raw))
+
+ expect(events).toEqual([
+ { type: 'tool_start', payload: { id: 'web-2', tool: 'WebSearch', input: { query: 'ETH price' } } },
+ { type: 'tool_start', payload: { id: 'web-3', tool: 'WebFetch', input: { url: 'https://a.example/, https://b.example/' } } },
+ ])
+ })
+
it('normalizes update_plan and hides internal deferred-tool discovery', () => {
const normalizer = new CodexNormalizer('live')
const events = [
diff --git a/cli/src/engines/codex/normalizer.ts b/cli/src/engines/codex/normalizer.ts
index 32f10c29d..8b77f781d 100644
--- a/cli/src/engines/codex/normalizer.ts
+++ b/cli/src/engines/codex/normalizer.ts
@@ -406,7 +406,7 @@ export class CodexNormalizer implements EngineNormalizer {
}
if (ORCHESTRATION_TOOLS.has(name)) return []
- const descriptor = codexToolDescriptor(name, item.arguments ?? item.input)
+ const descriptor = codexToolDescriptor(name, item.arguments ?? item.input, string(item.namespace))
this.toolNames.set(id, descriptor.tool)
return [{ type: 'tool_start', payload: { id, tool: descriptor.tool, input: descriptor.input } }]
}
diff --git a/cli/src/engines/codex/subagent.ts b/cli/src/engines/codex/subagent.ts
index ebdf126bd..584a1a18a 100644
--- a/cli/src/engines/codex/subagent.ts
+++ b/cli/src/engines/codex/subagent.ts
@@ -1,6 +1,7 @@
import { readFileSync } from 'fs'
import { join } from 'path'
import type { SessionEvent } from '../../lib/normalize.js'
+import { harnessWebTool, harnessWebToolKind, webReadUrl } from '../../lib/harnessWebTools.js'
import { resolveCodexRollout } from './rollout.js'
type JsonObject = Record<string, unknown>
@@ -59,10 +60,28 @@ function jsStringProperty(source: string, key: string): string {
return quoted.slice(1, -1).replace(/\\'/g, "'").replace(/\\\\/g, '\\')
}
+/**
+ * The strings of a JS array-literal property — `urls: ["a", 'b']` → `['a', 'b']`. Enough for a
+ * code-mode call read back out of its source, which is the only reason this exists.
+ */
+function jsStringArrayProperty(source: string, key: string): string[] {
+ const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ const match = new RegExp(`(?:\\b${escapedKey}\\b|["']${escapedKey}["'])\\s*:\\s*\\[([^\\]]*)\\]`).exec(source)
+ if (!match) return []
+ return [...match[1].matchAll(/"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'/g)]
+ .map((m) => m[1] ?? m[2] ?? '')
+ .filter(Boolean)
+}
+
function wrappedExecDescriptor(source: string): { tool: string; input: unknown } | null {
const match = /\btools\.([a-zA-Z0-9_$]+)\s*\(/.exec(source)
if (!match) return null
const wrappedTool = match[1]
+ // The harness web tools, called by their MCP identifier — `tools.mcp__harness__web_search(...)`.
+ // The card wants the query or the urls, read back out of the source like `web__run`'s `q`.
+ const webTool = harnessWebToolKind(wrappedTool)
+ if (webTool === 'WebSearch') return { tool: webTool, input: { query: jsStringProperty(source, 'query') } }
+ if (webTool === 'WebFetch') return { tool: webTool, input: { url: webReadUrl(jsStringArrayProperty(source, 'urls')) } }
switch (wrappedTool) {
case 'web__run':
return { tool: 'WebSearch', input: { query: jsStringProperty(source, 'q') } }
@@ -91,13 +110,23 @@ export function isCodexInternalToolCall(name: string, rawInput: unknown): boolea
&& !/\btools\.[a-zA-Z0-9_$]+\s*\(/.test(rawInput)
}
-/** Codex rollout function name -> the existing Claude-style tool vocabulary used by web/device. */
-export function codexToolDescriptor(name: string, rawInput: unknown): { tool: string; input: unknown } {
+/**
+ * Codex rollout function name -> the existing Claude-style tool vocabulary used by web/device.
+ *
+ * `namespace` is the rollout item's own field. Codex records an MCP call as
+ * `name: "mcp__harness__web_search"`, or — measured on 0.154.0 rollouts — as `name: "web_search"`
+ * beside `namespace: "mcp__harness"`; the two are joined only to recognise the harness web tools,
+ * and every other name is passed through exactly as before.
+ */
+export function codexToolDescriptor(name: string, rawInput: unknown, namespace = ''): { tool: string; input: unknown } {
if (name === 'exec' && typeof rawInput === 'string') {
const wrapped = wrappedExecDescriptor(rawInput)
if (wrapped) return wrapped
}
const args = parseObject(rawInput)
+ // The harness web tools, on a Local model: the native cards, as every other engine's web tool gets.
+ const webTool = harnessWebTool(namespace ? `${namespace}__${name}` : name, args)
+ if (webTool) return webTool
switch (name) {
case 'exec_command':
case 'shell':
@@ -179,7 +208,8 @@ export function readChildRollout(file: string): CodexSubagentInfo | null {
? payload.name
: (payloadType === 'tool_search_call' ? 'tool_search' : 'tool')
if (isCodexInternalToolCall(name, payload.arguments ?? payload.input)) continue
- const descriptor = codexToolDescriptor(name, payload.arguments ?? payload.input)
+ const namespace = typeof payload.namespace === 'string' ? payload.namespace : ''
+ const descriptor = codexToolDescriptor(name, payload.arguments ?? payload.input, namespace)
calls.push({ id, tool: descriptor.tool, input: descriptor.input })
continue
}
diff --git a/cli/src/lib/__fixtures__/fakeGrid.ts b/cli/src/lib/__fixtures__/fakeGrid.ts
new file mode 100644
index 000000000..ba51f5d18
--- /dev/null
+++ b/cli/src/lib/__fixtures__/fakeGrid.ts
@@ -0,0 +1,136 @@
+/**
+ * A plan-driven fake `grid`, for specs that drive the daemon's `grid` subprocess seam.
+ *
+ * The real binary talks to a control plane, so the questions worth asking in a unit test are all
+ * about which argv this daemon sends and what it believes about the answer. This fake answers each
+ * verb from a JSON plan the test writes beside it, and appends every invocation to a log the test
+ * reads back. Injected through `HARNESS_GRID_BIN`, which `gridExec.ts` prefers over the managed
+ * runtime and PATH alike.
+ *
+ * One fake rather than one per spec: the verb-keyed plan, the `--remote` stripping and the
+ * multi-turn answers are the parts that drift when copied, and a fake that means something slightly
+ * different in each file is worse than none.
+ */
+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+const FAKE_GRID = `#!/usr/bin/env node
+const fs = require('fs')
+const log = process.env.FAKE_GRID_LOG
+const plan = JSON.parse(fs.readFileSync(process.env.FAKE_GRID_PLAN, 'utf8'))
+const args = process.argv.slice(2).filter((a) => a !== '--remote')
+const verb = args[0] || ''
+const calls = fs.existsSync(log) ? JSON.parse(fs.readFileSync(log, 'utf8')) : []
+calls.push(process.argv.slice(2))
+fs.writeFileSync(log, JSON.stringify(calls))
+const step = plan[verb]
+if (!step) { process.exit(0) }
+// A verb may answer differently on successive calls (\`ls\` before and after a create), so its
+// answer can be a LIST of turns; the last turn repeats once the list runs out.
+const turn = Array.isArray(step) ? (step[calls.filter((c) => c.includes(verb)).length - 1] ?? step[step.length - 1]) : step
+if (turn.stdout) process.stdout.write(turn.stdout)
+if (turn.stderr) process.stderr.write(turn.stderr)
+process.exit(turn.exit ?? 0)
+`
+
+/** What one invocation of a verb prints and how it exits. */
+export interface FakeGridTurn { stdout?: string; stderr?: string; exit?: number }
+
+/** Keyed by the FIRST argument after `--remote` is stripped — `mcp` for `grid mcp config …`. */
+export type FakeGridPlan = Record<string, FakeGridTurn | FakeGridTurn[]>
+
+export interface FakeGrid {
+ /** Every argv the fake was run with, oldest first, `--remote` included. */
+ calls: () => string[][]
+ /** The verbs called, in order, with `--remote` stripped — `['mcp', 'info', 'ls']`. */
+ verbs: () => string[]
+ /** Delete the fake and unset the variables that point at it. */
+ dispose: () => void
+}
+
+/**
+ * Put a fake `grid` answering `plan` in front of this process, and hand back its call log.
+ *
+ * Sets `HARNESS_GRID_BIN` (and the fake's own plan/log variables) on `process.env`; `dispose`
+ * undoes all of it, so a spec's `afterEach` has one call to make.
+ */
+export function installFakeGrid(plan: FakeGridPlan): FakeGrid {
+ const root = mkdtempSync(join(tmpdir(), 'fake-grid-'))
+ const bin = join(root, 'grid')
+ writeFileSync(bin, FAKE_GRID)
+ chmodSync(bin, 0o755)
+ const planFile = join(root, 'plan.json')
+ writeFileSync(planFile, JSON.stringify(plan))
+ const log = join(root, 'calls.json')
+ process.env.HARNESS_GRID_BIN = bin
+ process.env.FAKE_GRID_PLAN = planFile
+ process.env.FAKE_GRID_LOG = log
+ const calls = (): string[][] => {
+ try {
+ return JSON.parse(readFileSync(log, 'utf8')) as string[][]
+ } catch {
+ return []
+ }
+ }
+ return {
+ calls,
+ verbs: () => calls().map((argv) => argv.find((arg) => arg !== '--remote') ?? ''),
+ dispose: () => {
+ rmSync(root, { recursive: true, force: true })
+ delete process.env.HARNESS_GRID_BIN
+ delete process.env.FAKE_GRID_PLAN
+ delete process.env.FAKE_GRID_LOG
+ },
+ }
+}
+
+/**
+ * A JWT whose payload says `exp`, signed by nobody — enough for a reader that decodes the middle
+ * segment offline, which is all the daemon does with the token `grid mcp config` prints.
+ */
+export function fakeJwt(claims: Record<string, unknown>): string {
+ const segment = (value: unknown): string => Buffer.from(JSON.stringify(value)).toString('base64url')
+ return `${segment({ alg: 'none', typ: 'JWT' })}.${segment(claims)}.signature`
+}
+
+/** One signed-in account's grid, as the real `grid` would describe it — values read off a live
+ * control plane, shared so the specs that resolve a retarget all mean the same grid. */
+export interface FakeGridAnswers {
+ gridName: string
+ networkId: string
+ /** The relay root, as `grid info --env` prints `OPENAI_BASE_URL`. */
+ baseUrl: string
+ /** The control plane's web-tools mount, trailing slash and all. */
+ mcpUrl: string
+ /** The per-grid access token — the inference key AND the MCP bearer. */
+ token: string
+ /** The plan answering `info --env`, `mcp config --json` and `ls --json` for this grid. */
+ plan: FakeGridPlan
+}
+
+const DAY_S = 24 * 60 * 60
+
+/**
+ * The answers for a grid whose token expires `expiresInDays` from now (300 by default — well
+ * outside the daemon's 30-day renewal margin, so a spec that wants the cached path gets it).
+ */
+export function fakeGridAnswers(expiresInDays = 300): FakeGridAnswers {
+ const gridName = 'someone-7f3a91c4'
+ const networkId = 'grid-3378218621364f16'
+ const baseUrl = `https://grid.autonomous.ai/${networkId}/relay/v1`
+ const mcpUrl = 'https://api-grid.autonomous.ai/v1/grid/web-mcp/'
+ const token = fakeJwt({ exp: Math.floor(Date.now() / 1000) + expiresInDays * DAY_S, sub: 'someone' })
+ return {
+ gridName,
+ networkId,
+ baseUrl,
+ mcpUrl,
+ token,
+ plan: {
+ info: { stdout: `export OPENAI_BASE_URL="${baseUrl}"\nexport OPENAI_API_KEY="${token}"\n` },
+ mcp: { stdout: JSON.stringify({ server: 'grid-web', url: mcpUrl, authorization: `Bearer ${token}` }, null, 2) },
+ ls: { stdout: JSON.stringify([{ grid: gridName, id: networkId, type: 'permissioned-public' }]) },
+ },
+ }
+}
diff --git a/cli/src/lib/gridAssignment.spec.ts b/cli/src/lib/gridAssignment.spec.ts
index 329431214..4eadb1ad5 100644
--- a/cli/src/lib/gridAssignment.spec.ts
+++ b/cli/src/lib/gridAssignment.spec.ts
@@ -336,7 +336,7 @@ describe('web tools do not disturb the probe', () => {
it('never reads the control plane as the place an agent is running', () => {
// Codex is the one at risk: its endpoint comes out of argv, which now also carries
- // `mcp_servers.grid_web.url=…`. Reading that as the endpoint would report an agent as running on
+ // `mcp_servers.harness.url=…`. Reading that as the endpoint would report an agent as running on
// the control plane, and the app would offer to move it off a grid it is already on.
expect(classify('codex', WITH_MCP)?.baseUrl).toBe(RELAY_V1)
})
diff --git a/cli/src/lib/gridEnsure.spec.ts b/cli/src/lib/gridEnsure.spec.ts
index bd6352778..30e6535b3 100644
--- a/cli/src/lib/gridEnsure.spec.ts
+++ b/cli/src/lib/gridEnsure.spec.ts
@@ -4,55 +4,22 @@
* asking here are all about which argv this module sends and what it believes about the answer.
*/
import { afterEach, describe, expect, it } from 'vitest'
-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
+import { installFakeGrid, type FakeGrid, type FakeGridPlan, type FakeGridTurn as Turn } from './__fixtures__/fakeGrid.js'
-const dirs: string[] = []
+let fake: FakeGrid | null = null
afterEach(() => {
- for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })
+ fake?.dispose()
+ fake = null
+ // One test below points HARNESS_GRID_BIN at nothing by hand, with no fake to dispose of.
delete process.env.HARNESS_GRID_BIN
})
-/**
- * A `grid` whose behaviour is data: a JSON script the test writes beside it decides what each verb
- * answers, and every invocation is appended to a log the test reads back.
- */
-const FAKE_GRID = `#!/usr/bin/env node
-const fs = require('fs')
-const log = process.env.FAKE_GRID_LOG
-const plan = JSON.parse(fs.readFileSync(process.env.FAKE_GRID_PLAN, 'utf8'))
-const args = process.argv.slice(2).filter((a) => a !== '--remote')
-const verb = args[0] || ''
-const calls = fs.existsSync(log) ? JSON.parse(fs.readFileSync(log, 'utf8')) : []
-calls.push(process.argv.slice(2))
-fs.writeFileSync(log, JSON.stringify(calls))
-const step = plan[verb]
-if (!step) { process.exit(0) }
-// \`ls\` may answer differently before and after a create, so its answer can be a LIST of turns.
-const turn = Array.isArray(step) ? (step[calls.filter((c) => c.includes(verb)).length - 1] ?? step[step.length - 1]) : step
-if (turn.stdout) process.stdout.write(turn.stdout)
-if (turn.stderr) process.stderr.write(turn.stderr)
-process.exit(turn.exit ?? 0)
-`
-
-interface Turn { stdout?: string; stderr?: string; exit?: number }
-
-function fakeGrid(plan: Record<string, Turn | Turn[]>): { calls: () => string[][] } {
- const root = mkdtempSync(join(tmpdir(), 'grid-ensure-'))
- dirs.push(root)
- const bin = join(root, 'grid')
- writeFileSync(bin, FAKE_GRID)
- chmodSync(bin, 0o755)
- const planFile = join(root, 'plan.json')
- writeFileSync(planFile, JSON.stringify(plan))
- const log = join(root, 'calls.json')
- process.env.HARNESS_GRID_BIN = bin
- process.env.FAKE_GRID_PLAN = planFile
- process.env.FAKE_GRID_LOG = log
- return {
- calls: () => JSON.parse(readFileSync(log, 'utf8')) as string[][],
- }
+/** The fake `grid` from `__fixtures__/fakeGrid.ts`, remembered so `afterEach` can dispose of it. */
+function fakeGrid(plan: FakeGridPlan): FakeGrid {
+ fake = installFakeGrid(plan)
+ return fake
}
const VERSION_OK: Turn = { stdout: 'grid 0.3.46\n' }
diff --git a/cli/src/lib/gridLaunch.spec.ts b/cli/src/lib/gridLaunch.spec.ts
index d128d79a3..918f0782c 100644
--- a/cli/src/lib/gridLaunch.spec.ts
+++ b/cli/src/lib/gridLaunch.spec.ts
@@ -100,8 +100,8 @@ describe('the launch each engine gets', () => {
ANTHROPIC_AUTH_TOKEN: WIRE.apiKey,
ANTHROPIC_MODEL: 'GLM-4.7-Flash',
},
- // The built-in search no grid can run — see "takes Claude Code's built-in WebSearch away".
- args: ['--disallowedTools=WebSearch'],
+ // The built-in web tools no grid can run — see "takes Claude Code's built-in web tools away".
+ args: ['--disallowedTools=WebSearch,WebFetch'],
})
// Setting it too makes Claude Code warn that auth may not work, and it decides nothing.
expect(launchOf('claude').env).not.toHaveProperty('ANTHROPIC_API_KEY')
@@ -319,6 +319,17 @@ describe('gridEnvVarNames', () => {
expect(gridEnvVarNames('pi')).toContain('PI_CODING_AGENT_DIR')
})
+ it('covers every variable a launch WITH web tools sets, so returning to the own login clears them all', () => {
+ // This is what `cli.ts` hands `tmux clearEnv` on a clearGrid retarget. A variable a web-tools
+ // launch set but this list missed would leave the pane holding an MCP credential after the agent
+ // was told it is back on its subscription model.
+ for (const engine of gridCapableEngines()) {
+ const launch = launchOf(engine, WITH_MCP)
+ const set = [...Object.keys(launch.env), ...(launch.configDir ? [launch.configDir.envVar] : [])]
+ for (const name of set) expect(gridEnvVarNames(engine), `${engine} sets ${name}`).toContain(name)
+ }
+ })
+
it('is empty for an engine that cannot be pointed at a grid', () => {
expect(gridEnvVarNames('amp')).toEqual([])
})
@@ -490,7 +501,7 @@ describe('web tools (grid ADR 0041)', () => {
})
it('hands Claude Code the server as a --mcp-config JSON string', () => {
- expect(claudeMcpJson().mcpServers['grid-web'])
+ expect(claudeMcpJson().mcpServers['harness'])
.toEqual({ type: 'http', url: MCP_URL, headers: { Authorization: 'Bearer ${GRID_API_KEY}' } })
})
@@ -505,7 +516,7 @@ describe('web tools (grid ADR 0041)', () => {
// expands `${VAR}` in a header exactly as Claude Code does, and sends `${env:VAR}` and
// `{env:VAR}` through verbatim — so the opencode spelling would have put the literal string on
// the wire and failed authentication with nothing naming why.
- expect(copilotMcpJson().mcpServers['grid-web'])
+ expect(copilotMcpJson().mcpServers['harness'])
.toEqual({ type: 'http', url: MCP_URL, headers: { Authorization: 'Bearer ${GRID_API_KEY}' } })
// One document, not two that merely look alike — this is what makes the shared builder honest.
const at = launchOf('copilot', WITH_MCP).args.indexOf('--additional-mcp-config')
@@ -522,16 +533,16 @@ describe('web tools (grid ADR 0041)', () => {
})
it("points Codex at it through env_http_headers, which carries the WHOLE header value", () => {
- expect(codexArg('mcp_servers.grid-web.url')).toBe(`mcp_servers.grid-web.url="${MCP_URL}"`)
- expect(codexArg('mcp_servers.grid-web.env_http_headers.Authorization'))
- .toBe('mcp_servers.grid-web.env_http_headers.Authorization="GRID_MCP_AUTHORIZATION"')
+ expect(codexArg('mcp_servers.harness.url')).toBe(`mcp_servers.harness.url="${MCP_URL}"`)
+ expect(codexArg('mcp_servers.harness.env_http_headers.Authorization'))
+ .toBe('mcp_servers.harness.env_http_headers.Authorization="GRID_MCP_AUTHORIZATION"')
// Bearer included — `bearer_token_env_var` takes a bare token, this one does not, and ADR 0041
// D-d calls confusing the two a silent 401.
expect(launchOf('codex', WITH_MCP).env.GRID_MCP_AUTHORIZATION).toBe(`Bearer ${WIRE.apiKey}`)
})
it('declares it in the config file opencode already gets', () => {
- expect(opencodeConfig().mcp['grid-web'])
+ expect(opencodeConfig().mcp['harness'])
.toEqual({
type: 'remote',
url: MCP_URL,
@@ -550,7 +561,7 @@ describe('web tools (grid ADR 0041)', () => {
// Emitted as JSON on purpose: it is a subset of YAML, and Hermes parses this with a YAML loader.
expect(JSON.parse(file!.content)).toEqual({
mcp_servers: {
- 'grid-web': {
+ 'harness': {
url: MCP_URL,
headers: { Authorization: 'Bearer ${GRID_API_KEY}' },
},
@@ -566,20 +577,24 @@ describe('web tools (grid ADR 0041)', () => {
expect(Object.keys(JSON.parse(file.content))).toEqual(['mcp_servers'])
})
- it('calls the server the same thing in every harness', () => {
- // The tools are named after it — an agent sees `mcp__grid-web__web_search` — so a harness that
+ it('calls the server `harness` in every harness — the user never reads "grid"', () => {
+ // The tools are named after it — an agent sees `mcp__harness__web_search` — so a harness that
// spells it differently gets differently-named tools, and a prompt or skill naming one silently
- // misses on the other. Codex is where this is easy to get wrong: its config keys are dotted TOML
- // paths, which look like they could not carry a `-`. They can.
- expect(Object.keys(claudeMcpJson().mcpServers)).toEqual(['grid-web'])
- expect(Object.keys(copilotMcpJson().mcpServers)).toEqual(['grid-web'])
- expect(Object.keys(opencodeConfig().mcp)).toEqual(['grid-web'])
+ // misses on the other. The name is also what `/mcp` and a permission prompt show, which is why
+ // it is the product's name and not the grid's.
+ expect(Object.keys(claudeMcpJson().mcpServers)).toEqual(['harness'])
+ expect(Object.keys(copilotMcpJson().mcpServers)).toEqual(['harness'])
+ expect(Object.keys(opencodeConfig().mcp)).toEqual(['harness'])
expect(Object.keys(JSON.parse(launchOf('hermes', WITH_MCP).configDir!.files[0]!.content).mcp_servers))
- .toEqual(['grid-web'])
- for (const arg of launchOf('codex', WITH_MCP).args) {
- expect(arg, 'codex renamed the server, and with it every tool').not.toContain('grid_web')
+ .toEqual(['harness'])
+ expect(codexArg('mcp_servers.harness.url')).toBeDefined()
+ const grok = launchOf('grok', WITH_MCP).configDir!.files[0]!.content
+ expect(grok).toContain('[mcp_servers.harness]')
+ for (const engine of ['claude', 'codex', 'copilot', 'opencode', 'hermes', 'grok'] as const) {
+ const launch = launchOf(engine, WITH_MCP)
+ const written = [...launch.args, ...(launch.configDir?.files ?? []).map((f) => f.content)].join('\n')
+ expect(written, engine).not.toContain('grid-web')
}
- expect(codexArg('mcp_servers.grid-web.url')).toBeDefined()
})
it('never writes the key to disk or to an argv', () => {
@@ -608,25 +623,41 @@ describe('web tools (grid ADR 0041)', () => {
}
})
- it("takes Claude Code's built-in WebSearch away on every grid launch, web tools or not", () => {
- // `WebSearch` is an Anthropic SERVER tool (`web_search_20250305`) that no grid runs: the grid
- // answers it with a 400, and a model offered it reaches for it before `mcp__grid-web__web_search`.
+ it("takes Claude Code's built-in web tools away on every grid launch, web tools or not", () => {
+ // `WebSearch` is an Anthropic SERVER tool (`web_search_20250305`) that no grid runs, and
+ // `WebFetch` summarises through a haiku call on the same base URL, which the relay answers
+ // `503 no_providers_available`. Both are dead on a grid, with or without a replacement, and a
+ // model offered a dead tool reaches for it first.
for (const override of [OVERRIDE, WITH_MODEL, WITH_MCP]) {
- expect(launchOf('claude', override).args).toContain('--disallowedTools=WebSearch')
+ expect(launchOf('claude', override).args).toContain('--disallowedTools=WebSearch,WebFetch')
}
// ONE token. The flag is variadic, so the two-token form would swallow any positional after it as
// another tool name — measured on Claude Code 2.1.268, it then sent no request at all.
expect(launchOf('claude', WITH_MCP).args).not.toContain('--disallowedTools')
+ expect(launchOf('claude', WITH_MCP).args).not.toContain('--disallowedTools=WebSearch')
+ })
+
+ it("turns Codex's native web search off on every grid launch, web tools or not", () => {
+ // The native tool is an API-side feature of OpenAI's Responses endpoint. Verified on codex-cli
+ // 0.154.0 with `--strict-config`: the key is `web_search`, the variants `disabled`, `cached`,
+ // `indexed`, `live`, and `web_search_mode` is refused as unknown.
+ for (const override of [OVERRIDE, WITH_MODEL, WITH_MCP]) {
+ const args = launchOf('codex', override).args
+ const at = args.indexOf('web_search="disabled"')
+ expect(at, 'codex was not told to disable web_search').toBeGreaterThan(0)
+ expect(args[at - 1]).toBe('-c')
+ }
})
it('adds no web tools when the desktop sends no mcpUrl', () => {
// An older desktop, and the no-regression promise: no server it did not ask for. Claude's one flag
// is not a web tool but the removal of one no grid can run — see the test above.
- expect(launchOf('claude', WITH_MODEL).args).toEqual(['--disallowedTools=WebSearch'])
+ expect(launchOf('claude', WITH_MODEL).args).toEqual(['--disallowedTools=WebSearch,WebFetch'])
expect(launchOf('claude', WITH_MODEL).env.GRID_API_KEY).toBeUndefined()
+ expect(launchOf('grok', WITH_MODEL).configDir!.files[0]!.content).not.toContain('mcp_servers')
expect(launchOf('copilot', WITH_MODEL).args).toEqual([])
expect(launchOf('copilot', WITH_MODEL).env.GRID_API_KEY).toBeUndefined()
- expect(codexArg('mcp_servers.grid-web.url', WITH_MODEL)).toBeUndefined()
+ expect(codexArg('mcp_servers.harness.url', WITH_MODEL)).toBeUndefined()
expect(launchOf('codex', WITH_MODEL).env.GRID_MCP_AUTHORIZATION).toBeUndefined()
expect(opencodeConfig(WITH_MODEL).mcp).toBeUndefined()
// Hermes had no config directory at all before web tools, so it goes back to having none.
diff --git a/cli/src/lib/gridLaunch.ts b/cli/src/lib/gridLaunch.ts
index 12e57aa63..9e1097385 100644
--- a/cli/src/lib/gridLaunch.ts
+++ b/cli/src/lib/gridLaunch.ts
@@ -46,11 +46,11 @@ import { homedir } from 'node:os'
import { join } from 'node:path'
import type { AgentEngine } from '../engines/types.js'
import {
- CLAUDE_DISALLOW_WEB_SEARCH_ARG,
+ CLAUDE_DISALLOW_WEB_TOOLS_ARG,
+ CODEX_DISABLE_WEB_SEARCH_ARGS,
mcpServersConfig,
codexMcpArgs,
GRID_MCP_AUTH_VAR,
- GRID_MCP_SERVER_NAME,
GROK_CONFIG_FILE,
GROK_GRID_HOME_LINKS,
GROK_HOME_VAR,
@@ -60,6 +60,7 @@ import {
hermesManagedConfig,
mcpAuthorizationHeader,
} from './gridWebMcp.js'
+import { HARNESS_MCP_SERVER_NAME } from './harnessWebTools.js'
/** Where Pi keeps the skills the user manages, handed back through our own settings.json. */
function userPiSkillsDir(): string {
@@ -299,7 +300,7 @@ function opencodeGridConfig(
...(override.mcpUrl
? {
mcp: {
- [GRID_MCP_SERVER_NAME]: {
+ [HARNESS_MCP_SERVER_NAME]: {
type: 'remote',
url: override.mcpUrl,
enabled: true,
@@ -521,8 +522,9 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
},
args: [
// On every grid launch, web tools or not: the built-in search is an Anthropic server tool
- // that no grid runs. See `CLAUDE_DISALLOW_WEB_SEARCH_ARG`.
- CLAUDE_DISALLOW_WEB_SEARCH_ARG,
+ // that no grid runs, and the built-in fetch summarises through a model the grid does not
+ // serve. See `CLAUDE_DISALLOW_WEB_TOOLS_ARG`.
+ CLAUDE_DISALLOW_WEB_TOOLS_ARG,
...(override.mcpUrl ? ['--mcp-config', mcpServersConfig(override.mcpUrl, GRID_KEY_VAR)] : []),
],
}),
@@ -549,6 +551,9 @@ const GRID_ENGINE_CONTRACTS: Partial<Record<AgentEngine, GridEngineContract>> =
'-c', 'model_providers.grid.wire_api="responses"',
// The relay streams HTTP SSE, not WebSocket.
'-c', 'model_providers.grid.supports_websockets=false',
+ // On every grid launch, web tools or not: the native search is a Responses-API feature no
+ // grid serves. See `CODEX_DISABLE_WEB_SEARCH_ARGS`.
+ ...CODEX_DISABLE_WEB_SEARCH_ARGS,
...(override.mcpUrl ? codexMcpArgs(override.mcpUrl) : []),
...(override.model ? ['-m', override.model] : []),
],
diff --git a/cli/src/lib/gridMcpUrl.spec.ts b/cli/src/lib/gridMcpUrl.spec.ts
new file mode 100644
index 000000000..7b4146115
--- /dev/null
+++ b/cli/src/lib/gridMcpUrl.spec.ts
@@ -0,0 +1,140 @@
+/**
+ * `resolveGridMcpUrl` against the plan-driven fake `grid` — which argv it sends, what it keeps, and
+ * what it never keeps. The token `grid mcp config --json` prints is the one thing this module must
+ * read and then forget, so every test that hands it one also asserts it went nowhere.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { fakeGridAnswers, fakeJwt, installFakeGrid, type FakeGrid, type FakeGridPlan } from './__fixtures__/fakeGrid.js'
+import { clearGridMcpUrlCache, MCP_URL_RENEW_MARGIN_MS, resolveGridMcpUrl } from './gridMcpUrl.js'
+
+/** The grid's name and its web-tools mount (trailing slash and all — the mount answers 307
+ * without it). The token varies per test here, so each one builds its own `mcp config` answer. */
+const { gridName: GRID, mcpUrl: URL } = fakeGridAnswers()
+const NOW = Date.UTC(2026, 8, 15, 12, 0, 0)
+const DAY_MS = 24 * 60 * 60 * 1000
+const secondsAt = (ms: number): number => Math.floor(ms / 1000)
+
+/** What `grid mcp config <grid> --json` prints for `token`. */
+function mcpConfig(token: string): string {
+ return JSON.stringify({ server: 'grid-web', url: URL, authorization: `Bearer ${token}` }, null, 2)
+}
+
+let fake: FakeGrid | null = null
+let warned: string[] = []
+
+function install(plan: FakeGridPlan): FakeGrid {
+ fake = installFakeGrid(plan)
+ return fake
+}
+
+beforeEach(() => {
+ warned = []
+ vi.spyOn(console, 'warn').mockImplementation((...parts: unknown[]) => { warned.push(parts.map(String).join(' ')) })
+})
+
+afterEach(() => {
+ fake?.dispose()
+ fake = null
+ clearGridMcpUrlCache()
+ vi.restoreAllMocks()
+})
+
+describe('resolveGridMcpUrl', () => {
+ it('asks `grid mcp config <grid> --json` and hands back the url exactly as printed', async () => {
+ const token = fakeJwt({ exp: secondsAt(NOW + 300 * DAY_MS) })
+ const grid = install({ mcp: { stdout: mcpConfig(token) } })
+ expect(await resolveGridMcpUrl(GRID, NOW)).toBe(URL)
+ expect(grid.calls()).toEqual([['--remote', 'mcp', 'config', GRID, '--json']])
+ })
+
+ it('does not call again while the entry is fresh', async () => {
+ const token = fakeJwt({ exp: secondsAt(NOW + 300 * DAY_MS) })
+ const grid = install({ mcp: { stdout: mcpConfig(token) } })
+ await resolveGridMcpUrl(GRID, NOW)
+ expect(await resolveGridMcpUrl(GRID, NOW + DAY_MS)).toBe(URL)
+ expect(grid.calls()).toHaveLength(1)
+ })
+
+ it('calls again once the token is within 30 days of expiry, which is when `mcp config` renews it', async () => {
+ const token = fakeJwt({ exp: secondsAt(NOW + 300 * DAY_MS) })
+ const grid = install({ mcp: { stdout: mcpConfig(token) } })
+ await resolveGridMcpUrl(GRID, NOW)
+ const justInside = NOW + 300 * DAY_MS - MCP_URL_RENEW_MARGIN_MS + 1000
+ expect(await resolveGridMcpUrl(GRID, justInside)).toBe(URL)
+ expect(grid.calls()).toHaveLength(2)
+ })
+
+ it('calls every time when the token cannot be decoded', async () => {
+ const grid = install({ mcp: { stdout: mcpConfig('not-a-jwt') } })
+ expect(await resolveGridMcpUrl(GRID, NOW)).toBe(URL)
+ expect(await resolveGridMcpUrl(GRID, NOW)).toBe(URL)
+ expect(grid.calls()).toHaveLength(2)
+ })
+
+ it('treats a boolean or missing exp as undecodable rather than as the epoch', async () => {
+ // `exp: true` would read as 1 through a careless numeric check — 1970, renew forever.
+ const grid = install({ mcp: { stdout: mcpConfig(fakeJwt({ exp: true })) } })
+ await resolveGridMcpUrl(GRID, NOW)
+ await resolveGridMcpUrl(GRID, NOW)
+ expect(grid.calls()).toHaveLength(2)
+ })
+
+ it('is emptied by sign-out', async () => {
+ const token = fakeJwt({ exp: secondsAt(NOW + 300 * DAY_MS) })
+ const grid = install({ mcp: { stdout: mcpConfig(token) } })
+ await resolveGridMcpUrl(GRID, NOW)
+ clearGridMcpUrlCache()
+ await resolveGridMcpUrl(GRID, NOW)
+ expect(grid.calls()).toHaveLength(2)
+ })
+
+ it('is keyed by grid name, so a re-minted name never hits a stale entry', async () => {
+ const token = fakeJwt({ exp: secondsAt(NOW + 300 * DAY_MS) })
+ const grid = install({ mcp: { stdout: mcpConfig(token) } })
+ await resolveGridMcpUrl(GRID, NOW)
+ await resolveGridMcpUrl('someone-0badf00d', NOW)
+ expect(grid.calls().map((argv) => argv[3])).toEqual([GRID, 'someone-0badf00d'])
+ })
+
+ it('answers undefined, logs the reason, and caches nothing when the binary is too old', async () => {
+ // argparse exits 2 on the unknown subcommand, before any handler runs — `GRID_CLI_OUTDATED`.
+ const grid = install({ mcp: { exit: 2, stderr: 'grid: error: argument command: invalid choice: \'mcp\'\n' } })
+ expect(await resolveGridMcpUrl(GRID, NOW)).toBeUndefined()
+ expect(await resolveGridMcpUrl(GRID, NOW)).toBeUndefined()
+ expect(grid.calls()).toHaveLength(2)
+ expect(warned.join('\n')).toMatch(/older than/)
+ })
+
+ it('answers undefined with grid\'s own words when the sign-in is missing or the grid unknown', async () => {
+ install({ mcp: { exit: 1, stderr: 'Not logged in. Run `grid login` first.\n' } })
+ expect(await resolveGridMcpUrl(GRID, NOW)).toBeUndefined()
+ expect(warned.join('\n')).toContain('Not logged in')
+ })
+
+ it('answers undefined when the output is not a usable address', async () => {
+ for (const url of ['', 'v1/grid/web-mcp/', 'file:///etc/passwd']) {
+ clearGridMcpUrlCache()
+ fake?.dispose()
+ install({ mcp: { stdout: JSON.stringify({ server: 'grid-web', url, authorization: 'Bearer x' }) } })
+ expect(await resolveGridMcpUrl(GRID, NOW), url).toBeUndefined()
+ }
+ })
+
+ it('answers undefined when there is no `grid` at all, and never throws', async () => {
+ process.env.HARNESS_GRID_BIN = '/definitely/not/a/grid'
+ expect(await resolveGridMcpUrl(GRID, NOW)).toBeUndefined()
+ delete process.env.HARNESS_GRID_BIN
+ })
+
+ it('never lets the token reach a log line', async () => {
+ const token = fakeJwt({ exp: secondsAt(NOW + 5 * DAY_MS), sub: 'someone' })
+ install({ mcp: { stdout: mcpConfig(token) } })
+ const logged: string[] = []
+ for (const method of ['log', 'error', 'info', 'debug'] as const) {
+ vi.spyOn(console, method).mockImplementation((...parts: unknown[]) => { logged.push(parts.map(String).join(' ')) })
+ }
+ await resolveGridMcpUrl(GRID, NOW)
+ await resolveGridMcpUrl(GRID, NOW) // inside the margin: a second call, a second chance to leak
+ for (const line of [...logged, ...warned]) expect(line).not.toContain(token)
+ })
+})
diff --git a/cli/src/lib/gridMcpUrl.ts b/cli/src/lib/gridMcpUrl.ts
new file mode 100644
index 000000000..c95b80e8e
--- /dev/null
+++ b/cli/src/lib/gridMcpUrl.ts
@@ -0,0 +1,143 @@
+/**
+ * Where the grid's web tools are, remembered until the token behind them is due for renewal.
+ *
+ * One more `grid` subprocess on the seam `gridExec.ts` owns: `grid mcp config <grid> --json` prints
+ * `{ server, url, authorization }`, and the daemon wants exactly one of the three. The URL is the
+ * control plane's web-tools mount — a per-account address that does not change between calls — and
+ * `authorization` is the SAME per-grid token `grid info --env` prints as the inference key, which
+ * `gridModels.ts` reads on every retarget anyway. So the token is decoded for its `exp`, and then
+ * dropped: it is never stored here, never logged, and never travels anywhere `gridLaunch.ts` does
+ * not already carry it.
+ *
+ * ## Why a cache, and why keyed on `exp`
+ *
+ * `grid mcp config` renews the token when it is within [MCP_URL_RENEW_MARGIN_MS] of `exp` and
+ * persists the renewal (autonomous-grid `cli/mcp_config.py`, `EXPIRY_MARGIN_SECONDS`); `info --env`
+ * never renews. Nothing else on the harness path renews either, so this call is what keeps a
+ * harness user's grid token alive — and re-running it inside that margin ALWAYS renews. The margin
+ * here equals the CLI's own on purpose: a smaller one would re-run without renewing and re-run
+ * again tomorrow; a larger one would renew earlier than the CLI would have. Outside the margin the
+ * call is pure overhead, which is what the entry saves.
+ *
+ * An entry is only ever a URL and a deadline, in daemon memory, keyed by grid name — so a grid
+ * re-minted under a new name cannot hit a stale entry — and a failure is never cached: the next
+ * retarget asks again, because the condition (no sign-in, an old binary) may have been fixed since.
+ *
+ * ## Sign-out
+ *
+ * Every harness sign-out path stops the daemon (`logout`, `reset`, and `onRevoked` in `cli.ts`), so
+ * the process's memory goes with it. [clearGridMcpUrlCache] exists for the one in-process path —
+ * revocation — and so the contract "dropped on sign-out" is a call a test can make rather than a
+ * property of process lifetime.
+ *
+ * The one sign-out that is NOT a harness sign-out, `harness grid logout`, is a passthrough in a
+ * separate process and leaves a running daemon's entry where it is. That is harmless by
+ * construction: an entry is only a URL, and the next retarget's `info --env` fails without a
+ * credential, so `resolveGridTarget` answers null and no launch is built to carry it.
+ */
+import { gridJson, type GridResult } from './gridExec.js'
+
+/**
+ * How close to `exp` still counts as "ask again". ↔ `EXPIRY_MARGIN_SECONDS` in autonomous-grid's
+ * `cli/mcp_config.py` (30 days); see the module comment for why the two must agree.
+ */
+export const MCP_URL_RENEW_MARGIN_MS = 30 * 24 * 60 * 60 * 1000
+
+/** How much of `grid`'s stderr a log line carries. The reason is in its first sentence. */
+const MAX_LOGGED_REASON_CHARS = 300
+
+/** The two fields of `grid mcp config --json` read here (`server` is not). `url` is kept;
+ * `authorization` is read for `exp` and dropped. */
+interface McpConfigDocument {
+ url?: unknown
+ authorization?: unknown
+}
+
+interface CachedMcpUrl {
+ mcpUrl: string
+ /** The token's `exp`, in ms. Always a real instant — an undecodable token is never cached. */
+ expMs: number
+}
+
+const cache = new Map<string, CachedMcpUrl>()
+
+/** Forget every entry. Called on the daemon's in-process sign-out path; see the module comment. */
+export function clearGridMcpUrlCache(): void {
+ cache.clear()
+}
+
+/**
+ * The `exp` claim of the JWT in a `Bearer …` header, in ms, or null when it cannot be read.
+ *
+ * Offline and unverified, exactly as the grid CLI's own `credentials.token_expiry` reads it: this
+ * decides only WHEN to ask again, never whether the token is trusted. `true` is excluded explicitly
+ * — a boolean `exp` would otherwise read as 1, epoch 1970, and re-run forever.
+ */
+function tokenExpiryMs(authorization: unknown): number | null {
+ if (typeof authorization !== 'string') return null
+ const token = authorization.replace(/^Bearer\s+/i, '').trim()
+ const payload = token.split('.')[1]
+ if (!payload) return null
+ try {
+ const claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')) as { exp?: unknown }
+ const exp = claims.exp
+ return typeof exp === 'number' && Number.isFinite(exp) ? exp * 1000 : null
+ } catch {
+ return null
+ }
+}
+
+/** An address an engine can be handed, or null. Same rule as `gridLaunch.ts`'s `urlProblem`. */
+function usableMcpUrl(value: unknown): string | null {
+ if (typeof value !== 'string' || !value.trim()) return null
+ try {
+ const parsed = new URL(value)
+ return parsed.protocol === 'https:' || parsed.protocol === 'http:' ? value : null
+ } catch {
+ return null
+ }
+}
+
+/**
+ * One line saying why `grid mcp config` gave no answer, for the daemon log.
+ *
+ * `gridExec` already turns an old or missing binary into a sentence naming the remedy, and that
+ * beats argparse's `invalid choice: 'mcp'`. For a plain failure the sentence is grid's own — its
+ * first line of stderr ("Not logged in", "no grid named …") — and NEVER stdout: on success stdout
+ * is the document carrying the token, and a failure that somehow printed one would land it here.
+ */
+function failureReason(result: GridResult): string {
+ if (result.code !== 'GRID_FAILED') return result.message
+ return result.stderr.trim().split('\n')[0]?.slice(0, MAX_LOGGED_REASON_CHARS) || result.message
+}
+
+/**
+ * The grid's web-tools MCP URL, or undefined when it cannot be obtained.
+ *
+ * Undefined is a degraded answer, not a failure: the caller retargets without web tools and the
+ * reason is on the daemon log. Never throws. `now` is a parameter so a spec can move the clock
+ * without faking timers.
+ */
+export async function resolveGridMcpUrl(gridName: string, now: number = Date.now()): Promise<string | undefined> {
+ const cached = cache.get(gridName)
+ if (cached && cached.expMs - now >= MCP_URL_RENEW_MARGIN_MS) return cached.mcpUrl
+
+ const { value, result } = await gridJson<McpConfigDocument>(['--remote', 'mcp', 'config', gridName])
+ if (result.code !== 'OK' || !value) {
+ console.warn(`[grid] web tools unavailable for ${gridName} · ${failureReason(result)}`)
+ return undefined
+ }
+ const mcpUrl = usableMcpUrl(value.url)
+ if (!mcpUrl) {
+ console.warn(`[grid] web tools unavailable for ${gridName} · \`grid mcp config\` printed no usable url`)
+ return undefined
+ }
+ const expMs = tokenExpiryMs(value.authorization)
+ if (expMs === null) {
+ // Safe, slow, and loud: the next retarget asks again, and the log says why.
+ console.warn(`[grid] web tools for ${gridName} · token expiry unreadable, not caching`)
+ return mcpUrl
+ }
+ cache.set(gridName, { mcpUrl, expMs })
+ return mcpUrl
+}
diff --git a/cli/src/lib/gridModels.spec.ts b/cli/src/lib/gridModels.spec.ts
new file mode 100644
index 000000000..0221a2d02
--- /dev/null
+++ b/cli/src/lib/gridModels.spec.ts
@@ -0,0 +1,72 @@
+/**
+ * `resolveGridTarget` against the plan-driven fake `grid`: the order of its calls, and what the
+ * resolved target carries. There was no spec for this module before web tools gave it a second
+ * subprocess whose ORDER matters — `mcp config` renews the token, `info --env` reads it.
+ */
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { fakeGridAnswers, installFakeGrid, type FakeGrid, type FakeGridPlan } from './__fixtures__/fakeGrid.js'
+import { clearGridMcpUrlCache } from './gridMcpUrl.js'
+import { resolveGridTarget } from './gridModels.js'
+
+const { gridName: GRID, networkId, baseUrl: BASE_URL, mcpUrl: MCP_URL, token: TOKEN, plan } = fakeGridAnswers()
+
+let fake: FakeGrid | null = null
+function install(overrides: FakeGridPlan = {}): FakeGrid {
+ fake = installFakeGrid({ ...plan, ...overrides })
+ return fake
+}
+
+afterEach(() => {
+ fake?.dispose()
+ fake = null
+ clearGridMcpUrlCache()
+ vi.restoreAllMocks()
+})
+
+describe('resolveGridTarget', () => {
+ it('fills mcpUrl with the printed url, calling `mcp config` BEFORE `info --env`', async () => {
+ const grid = install()
+ const target = await resolveGridTarget(GRID, 'GLM-4.7-Flash')
+ expect(target).toEqual({
+ networkId,
+ networkName: GRID,
+ baseUrl: BASE_URL,
+ apiKey: TOKEN,
+ model: 'GLM-4.7-Flash',
+ mcpUrl: MCP_URL,
+ })
+ // `mcp config` may renew the token and persist it; `info --env` then reads the renewed one. The
+ // other order can hand inference an older token than the one the web tools hold.
+ expect(grid.verbs()).toEqual(['mcp', 'info', 'ls'])
+ expect(grid.calls()[0]).toEqual(['--remote', 'mcp', 'config', GRID, '--json'])
+ })
+
+ it('still resolves, without mcpUrl, when the binary is too old for `mcp config`', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ install({ mcp: { exit: 2, stderr: "grid: error: invalid choice: 'mcp'\n" } })
+ const target = await resolveGridTarget(GRID, 'GLM-4.7-Flash')
+ expect(target).toMatchObject({ baseUrl: BASE_URL, apiKey: TOKEN, model: 'GLM-4.7-Flash' })
+ expect(target).not.toHaveProperty('mcpUrl')
+ })
+
+ it('does not call `mcp config` again on a second retarget with a fresh entry', async () => {
+ const grid = install()
+ await resolveGridTarget(GRID, 'GLM-4.7-Flash')
+ const again = await resolveGridTarget(GRID, 'DeepSeek-V4-Flash-0731')
+ expect(again?.mcpUrl).toBe(MCP_URL)
+ expect(grid.verbs()).toEqual(['mcp', 'info', 'ls', 'info', 'ls'])
+ })
+
+ it('still answers null, untouched, when `info --env` fails', async () => {
+ // The retarget error path is not this feature's to change: no endpoint → GRID_UNAVAILABLE, as today.
+ install({ info: { exit: 1, stderr: 'no access token locally\n' } })
+ expect(await resolveGridTarget(GRID, 'GLM-4.7-Flash')).toBeNull()
+ })
+
+ it('asks nothing of `grid` without a grid name or a model', async () => {
+ const grid = install()
+ expect(await resolveGridTarget(null, 'GLM-4.7-Flash')).toBeNull()
+ expect(await resolveGridTarget(GRID, ' ')).toBeNull()
+ expect(grid.calls()).toEqual([])
+ })
+})
diff --git a/cli/src/lib/gridModels.ts b/cli/src/lib/gridModels.ts
index 2f53027c3..0adb413f4 100644
--- a/cli/src/lib/gridModels.ts
+++ b/cli/src/lib/gridModels.ts
@@ -6,6 +6,7 @@
* a person, and what an agent is told to ask for.
*/
import { gridExec, gridJson } from './gridExec.js'
+import { resolveGridMcpUrl } from './gridMcpUrl.js'
/** A row of `grid models --json`. `node` names the machine serving it — on a private grid, one of
* the user's own. */
@@ -95,6 +96,19 @@ async function relayModelIds(gridName: string): Promise<string[]> {
/** `grid info --env` prints shell exports; these are the two that matter. */
const ENV_LINE = /^export\s+(OPENAI_BASE_URL|OPENAI_API_KEY)=(.*)$/gm
+/** What `resolveGridTarget` answers: the launch override an engine is built from. */
+export interface GridTarget {
+ networkId: string
+ networkName: string
+ baseUrl: string
+ /** A live credential — see the function comment. */
+ apiKey: string
+ model: string
+ /** The control plane's web-tools MCP endpoint. Absent when it could not be obtained; the agent
+ * then runs on the grid with no web tools, and the daemon log says why. */
+ mcpUrl?: string
+}
+
/**
* Everything an engine needs to be pointed at `gridName`, resolved on THIS machine.
*
@@ -105,12 +119,17 @@ const ENV_LINE = /^export\s+(OPENAI_BASE_URL|OPENAI_API_KEY)=(.*)$/gm
* ⚠️ The returned `apiKey` is a live credential. It goes into the engine's ENVIRONMENT and never into
* argv or a log line — `gridLaunch.ts` is what enforces that, and this value must keep travelling
* through it rather than around it.
+ *
+ * Web tools ride on the same credential: the control plane's MCP server accepts the inference token,
+ * so `mcpUrl` is the only thing added here, and it is added FIRST. `grid mcp config` renews the token
+ * when it is within a month of expiry and persists the renewal; `info --env` never renews, so asked
+ * in the other order it could hand inference an older token than the one the web tools hold — both
+ * valid, and a mismatch nobody would think to look for. A missing `mcpUrl` degrades rather than
+ * refuses: inference is the feature, web search is an accessory (`gridMcpUrl.ts`).
*/
-export async function resolveGridTarget(
- gridName: string | null,
- model: string,
-): Promise<{ networkId: string; networkName: string; baseUrl: string; apiKey: string; model: string } | null> {
+export async function resolveGridTarget(gridName: string | null, model: string): Promise<GridTarget | null> {
if (!gridName?.trim() || !model.trim()) return null
+ const mcpUrl = await resolveGridMcpUrl(gridName)
const info = await gridExec(['--remote', 'info', gridName, '--env'])
if (info.code !== 'OK') return null
const { baseUrl, apiKey } = readEnvExports(info.stdout)
@@ -125,6 +144,7 @@ export async function resolveGridTarget(
baseUrl,
apiKey,
model,
+ ...(mcpUrl ? { mcpUrl } : {}),
}
}
diff --git a/cli/src/lib/gridWebMcp.ts b/cli/src/lib/gridWebMcp.ts
index a2e1c06a6..1c05e1a98 100644
--- a/cli/src/lib/gridWebMcp.ts
+++ b/cli/src/lib/gridWebMcp.ts
@@ -43,15 +43,7 @@
* authentication with nothing naming why.
*/
-/**
- * What the server is called in the harness's own listing — an agent sees
- * `mcp__grid-web__web_search`.
- *
- * ↔ `SERVER_NAME` in autonomous-grid's `cli/mcp_config.py`. Same name on purpose: a person who has
- * run `grid mcp config` by hand and an agent launched from the desktop should be looking at one
- * server, not two that do the same thing under different names.
- */
-export const GRID_MCP_SERVER_NAME = 'grid-web'
+import { HARNESS_MCP_SERVER_NAME } from './harnessWebTools.js'
/**
* The variable Codex reads its header out of.
@@ -90,7 +82,7 @@ export function mcpAuthorizationHeader(apiKey: string): string {
export function mcpServersConfig(mcpUrl: string, keyVar: string): string {
return JSON.stringify({
mcpServers: {
- [GRID_MCP_SERVER_NAME]: {
+ [HARNESS_MCP_SERVER_NAME]: {
type: 'http',
url: mcpUrl,
headers: { Authorization: `Bearer \${${keyVar}}` },
@@ -100,50 +92,87 @@ export function mcpServersConfig(mcpUrl: string, keyVar: string): string {
}
/**
- * Claude Code's own `WebSearch`, taken off every Claude agent launched onto a grid.
- *
- * It is the one web tool Claude Code does not run itself. Invoking it sends a second Messages request
- * carrying the `web_search_20250305` SERVER tool, which Anthropic's API executes and nothing else
- * does — and a grid is not Anthropic's API. The grid refuses it outright (autonomous-grid's CLI seat
- * rejects every typed tool on the Anthropic wire, `_reject_server_tools` in `shared/agent/cli_seat.py`)
- * and the pane prints `API Error: 400 Unsupported tool type: web_search_20250305`. The cost is not the
- * one failed call: the model reaches for its built-in search FIRST, spends turns on the refusal, then
- * scrapes pages with `WebFetch` — while `mcp__grid-web__web_search`, the search the grid actually
- * serves, sits unused in the same tool list.
- *
- * On every grid launch, not only one carrying an MCP url: the refusal does not depend on whether web
- * tools were wired, and a tool that can only fail is a trap either way. Moving the agent back to its
- * own login rebuilds its argv without this, so the built-in search returns with the login it works
- * against. A bare tool name here REMOVES the tool from what the model is offered rather than refusing
- * the call, which is the point — a call-time refusal would still let the model reach for it first.
- * `WebFetch` is left alone: it fetches from this machine and is not a server tool.
+ * Claude Code's own `WebSearch` and `WebFetch`, taken off every Claude agent launched onto a grid.
+ *
+ * Neither works without Anthropic's API behind the base URL, for two different reasons:
+ *
+ * * `WebSearch` is not a tool Claude Code runs. Invoking it sends a second Messages request carrying
+ * the `web_search_20250305` SERVER tool, which Anthropic's API executes and nothing else does. The
+ * grid refuses it outright (autonomous-grid's CLI seat rejects every typed tool on the Anthropic
+ * wire, `_reject_server_tools` in `shared/agent/cli_seat.py`) and the pane prints `API Error: 400
+ * Unsupported tool type: web_search_20250305`.
+ * * `WebFetch` DOES fetch the page from this machine — and then summarises it through a haiku call
+ * on the SAME base URL. The grid's relay serves only the models its nodes run and answers any
+ * other name `503 no_providers_available` (grid-src `private_server/relay.py`; only the reserved
+ * `auto` is routed), so the fetch succeeds and the tool still fails. An earlier version of this
+ * comment left `WebFetch` enabled on the belief that a local fetch made it safe; it does not.
+ *
+ * The cost is not the failed calls: a model offered a familiar dead tool reaches for it FIRST, spends
+ * turns on the refusal, and only then finds `mcp__harness__web_search`, the search the grid actually
+ * serves, in the same tool list. So both are removed on every grid launch, not only one carrying an
+ * MCP url — the refusal does not depend on whether a replacement was wired, and a tool that can only
+ * fail is a trap either way. Moving the agent back to its own login rebuilds its argv without this,
+ * so the built-in tools return with the login they work against. A bare tool name here REMOVES the
+ * tool from what the model is offered rather than refusing the call, which is the point — a
+ * call-time refusal would still let the model reach for it first.
*
* ⚠️ **The `=` is load-bearing.** The flag is VARIADIC, so the two-token form swallows every argument
* after it up to the next flag. Nothing positional follows a grid's args today —
* `buildEngineCommandArgv` appends them last — but that is an ordering this should not depend on.
+ * The comma form is the one `claude --help` documents ("Comma or space-separated list", 2.1.272);
+ * it keeps the whole list in that one token.
*
* Measured 2026-09-11 against a Messages listener on loopback, Claude Code 2.1.268: the main request
- * offered 21 tools with `WebSearch` among them, and 20 with this flag — `WebSearch` gone, `WebFetch`
- * still there, the prompt after the flag intact. The two-token form read that same prompt as a second
- * tool name ("Permission deny rule … matches no known tool") and sent no Messages request at all.
+ * offered 21 tools with `WebSearch` among them, and 20 with `--disallowedTools=WebSearch` — the prompt
+ * after the flag intact. The two-token form read that same prompt as a second tool name ("Permission
+ * deny rule … matches no known tool") and sent no Messages request at all. Measured again 2026-09-15
+ * on 2.1.272 with this exact token: the request carried neither `WebSearch` nor `WebFetch`, and every
+ * other tool — a plugin's 26 MCP tools included — was still offered.
+ */
+export const CLAUDE_DISALLOW_WEB_TOOLS_ARG = '--disallowedTools=WebSearch,WebFetch'
+
+/**
+ * Codex's native `web_search`, turned off on every Codex agent launched onto a grid.
+ *
+ * The native tool is a feature of OpenAI's Responses API — the request carries a `web_search` tool
+ * spec the endpoint executes — and a grid's relay is not that endpoint. Same trap as Claude Code's:
+ * a model offered it reaches for it before the MCP tool that works. Codex's own config knob for it
+ * is `web_search`, set through the same `-c` overrides the provider block already uses.
+ *
+ * Verified on codex-cli 0.154.0 rather than read off a page: `--strict-config -c web_search="…"` is
+ * accepted, its variants are `disabled`, `cached`, `indexed`, `live`, and `web_search_mode` — the
+ * spelling one might guess from the binary's strings — is refused as an unknown field. The runtime
+ * type is a `Constrained<WebSearchMode>` that "must always support Disabled", so no admin policy
+ * (`allowed_web_search_modes`) can refuse this value.
+ *
+ * The value is quoted as JSON because a `-c` value is parsed as TOML, like every override beside it.
+ *
+ * Claude Code and Codex are the only engines that lose a native web tool, checked rather than
+ * assumed (2026-09-15):
+ *
+ * * opencode's `websearch` is its own MCP call to Exa or Parallel (`packages/core/src/tool/
+ * websearch.ts`) and `webfetch` converts the page locally — neither goes through the model
+ * provider, so both keep working on a grid and there is nothing to take away.
+ * * Hermes' `web_search` / `web_extract` run on its own search-provider keys, not on inference.
+ * * Copilot CLI and Grok document no knob for their web tools; inventing one would be this module
+ * guessing at another program's internals, which its refusals exist to avoid.
*/
-export const CLAUDE_DISALLOW_WEB_SEARCH_ARG = '--disallowedTools=WebSearch'
+export const CODEX_DISABLE_WEB_SEARCH_ARGS: readonly string[] = ['-c', 'web_search="disabled"']
/**
* The same server as Codex `-c` overrides, which is how its provider is configured too — so this
* needs no config file either. Values are quoted as JSON because a `-c` value is parsed as TOML.
*
- * ⚠️ The name keeps its HYPHEN here, like everywhere else. A dotted `-c` path looks like it would
- * need `grid_web` — TOML bare keys do allow `-`, and `codex mcp add` writes `[mcp_servers.grid-web]`
- * itself. Renaming it for this one harness would rename its TOOLS too: an agent would see
- * `mcp__grid_web__web_search` on Codex and `mcp__grid-web__web_search` everywhere else, so a prompt
- * or skill naming one would silently miss on the other. Measured against codex 0.144.6, which reads
- * the hyphenated key back from `-c` without complaint.
+ * The name is spelled exactly as [HARNESS_MCP_SERVER_NAME] here, like everywhere else — a dotted `-c`
+ * path takes a TOML bare key, and any respelling for this one harness would rename its TOOLS too:
+ * an agent would see one `mcp__…__web_search` on Codex and another everywhere else, so a prompt or
+ * skill naming one would silently miss on the other. (When the name carried a hyphen, codex 0.144.6
+ * read it back from `-c` without complaint; a bare word needs no such care.)
*/
export function codexMcpArgs(mcpUrl: string): string[] {
return [
- '-c', `mcp_servers.${GRID_MCP_SERVER_NAME}.url=${JSON.stringify(mcpUrl)}`,
- '-c', `mcp_servers.${GRID_MCP_SERVER_NAME}.env_http_headers.Authorization=${JSON.stringify(GRID_MCP_AUTH_VAR)}`,
+ '-c', `mcp_servers.${HARNESS_MCP_SERVER_NAME}.url=${JSON.stringify(mcpUrl)}`,
+ '-c', `mcp_servers.${HARNESS_MCP_SERVER_NAME}.env_http_headers.Authorization=${JSON.stringify(GRID_MCP_AUTH_VAR)}`,
]
}
@@ -153,7 +182,7 @@ export function codexMcpArgs(mcpUrl: string): string[] {
* a **managed-scope overlay**: `HERMES_MANAGED_DIR` names a directory whose `config.yaml` is
* `_deep_merge`d over the user's (`hermes_cli/managed_scope.get_managed_dir`,
* `hermes_cli/config._merge_managed_overlay`). That merge recurses dict-over-dict, so pinning
- * `mcp_servers.grid-web` leaves every server the user configured for themselves in place — the same
+ * `mcp_servers.harness` leaves every server the user configured for themselves in place — the same
* promise `--strict-mcp-config`'s absence makes for Claude Code.
*
* Two things were checked before choosing it over `HERMES_HOME`, which also redirects config:
@@ -193,7 +222,7 @@ export const HERMES_MANAGED_CONFIG_FILE = 'config.yaml'
export function hermesManagedConfig(mcpUrl: string, keyVar: string): string {
return `${JSON.stringify({
mcp_servers: {
- [GRID_MCP_SERVER_NAME]: {
+ [HARNESS_MCP_SERVER_NAME]: {
url: mcpUrl,
// Hermes interpolates `${VAR}` Cursor-style against the process environment
// (`tools/mcp_tool_config._ENV_VAR_PATTERN`), so the key stays out of this file too.
@@ -300,8 +329,9 @@ export const GROK_GRID_HOME_LINKS: readonly string[] = ['sessions']
* under `[model."Auto"]` answered through the router with `auth_mode=null` and no probe. What must
* NOT happen is no block at all: that is the path back to the session token and the 401.
*
- * ⚠️ The MCP server name keeps its HYPHEN, as it does for Codex and for the same reason — Grok
- * namespaces MCP tools as `<server>__<tool>`, so renaming it here would rename its tools too.
+ * ⚠️ The MCP server name is spelled exactly as [HARNESS_MCP_SERVER_NAME], as it is for Codex and for
+ * the same reason — Grok namespaces MCP tools as `<server>__<tool>`, so respelling it here would
+ * rename its tools too.
*
* The MCP key is referenced the same way: Grok interpolates `${VAR}` in `headers` against the process
* environment, measured on the wire.
@@ -319,7 +349,7 @@ export function grokGridConfig(
+ `base_url = ${JSON.stringify(baseUrl)}\n`
+ `env_key = ${JSON.stringify(keyVar)}\n`
if (mcpUrl) {
- config += `\n[mcp_servers.${GRID_MCP_SERVER_NAME}]\n`
+ config += `\n[mcp_servers.${HARNESS_MCP_SERVER_NAME}]\n`
+ `url = ${JSON.stringify(mcpUrl)}\n`
+ `headers = { Authorization = ${JSON.stringify(`Bearer \${${keyVar}}`)} }\n`
}
diff --git a/cli/src/lib/harnessWebTools.spec.ts b/cli/src/lib/harnessWebTools.spec.ts
new file mode 100644
index 000000000..abf6c97d3
--- /dev/null
+++ b/cli/src/lib/harnessWebTools.spec.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest'
+import { HARNESS_MCP_SERVER_NAME, harnessWebTool, harnessWebToolKind, webReadUrl } from './harnessWebTools.js'
+
+describe('harnessWebTool', () => {
+ it('derives the tool names from the server name, so a rename cannot leave the cards behind', () => {
+ expect(harnessWebToolKind(`mcp__${HARNESS_MCP_SERVER_NAME}__web_search`)).toBe('WebSearch')
+ expect(harnessWebToolKind(`mcp__${HARNESS_MCP_SERVER_NAME}__web_read`)).toBe('WebFetch')
+ })
+
+ it('answers null for every other tool, MCP or not', () => {
+ for (const name of ['WebSearch', 'mcp__github__get_issue', 'mcp__grid-web__web_search', 'web_search', '', undefined]) {
+ expect(harnessWebToolKind(name), String(name)).toBeNull()
+ expect(harnessWebTool(name, { query: 'x' }), String(name)).toBeNull()
+ }
+ })
+
+ it('keeps web_search input as it is — the card already reads `query`', () => {
+ expect(harnessWebTool('mcp__harness__web_search', { query: 'BTC price', num_results: 5 }))
+ .toEqual({ tool: 'WebSearch', input: { query: 'BTC price', num_results: 5 } })
+ })
+
+ it('gives web_read the `url` the WebFetch card reads, keeping `urls` beside it', () => {
+ expect(harnessWebTool('mcp__harness__web_read', { urls: ['https://a.example/', 'https://b.example/'], max_chars: 6000 }))
+ .toEqual({ tool: 'WebFetch', input: { urls: ['https://a.example/', 'https://b.example/'], max_chars: 6000, url: 'https://a.example/, https://b.example/' } })
+ })
+
+ it('leaves a `url` that is already there alone', () => {
+ // A future server, or a replay, may already speak the card's shape; nothing here may overwrite it.
+ expect(harnessWebTool('mcp__harness__web_read', { url: 'https://c.example/', urls: ['https://a.example/'] }))
+ .toEqual({ tool: 'WebFetch', input: { url: 'https://c.example/', urls: ['https://a.example/'] } })
+ })
+
+ it('adds no `url` when the list holds nothing usable', () => {
+ expect(harnessWebTool('mcp__harness__web_read', { urls: ['', ' ', 42] }))
+ .toEqual({ tool: 'WebFetch', input: { urls: ['', ' ', 42] } })
+ expect(harnessWebTool('mcp__harness__web_read', { urls: 'https://a.example/' }))
+ .toEqual({ tool: 'WebFetch', input: { urls: 'https://a.example/' } })
+ })
+
+ it('tolerates an input that is not an object, and never mutates the one it is given', () => {
+ expect(harnessWebTool('mcp__harness__web_search', undefined)).toEqual({ tool: 'WebSearch', input: {} })
+ expect(harnessWebTool('mcp__harness__web_read', ['https://a.example/'])).toEqual({ tool: 'WebFetch', input: {} })
+ const given = { urls: ['https://a.example/'] }
+ harnessWebTool('mcp__harness__web_read', given)
+ expect(given).toEqual({ urls: ['https://a.example/'] })
+ })
+})
+
+describe('webReadUrl', () => {
+ it('joins the usable strings and drops the rest', () => {
+ expect(webReadUrl(['https://a.example/', '', null, 7, ' https://b.example/'])).toBe('https://a.example/, https://b.example/')
+ expect(webReadUrl([])).toBe('')
+ })
+})
diff --git a/cli/src/lib/harnessWebTools.ts b/cli/src/lib/harnessWebTools.ts
new file mode 100644
index 000000000..c50d8f19e
--- /dev/null
+++ b/cli/src/lib/harnessWebTools.ts
@@ -0,0 +1,76 @@
+/**
+ * The web-tools MCP server an agent on a Local model is given: what it is called, and how a call to
+ * it renders.
+ *
+ * Its own module because two halves of the daemon that otherwise never meet both need the name.
+ * The launch side (`gridWebMcp.ts`, `gridLaunch.ts`) writes it into each engine's MCP config; the
+ * transcript side (`normalize.ts`, the Codex normalizer) reads it back out of a tool name to pick a
+ * card. One constant, derived both ways, so a rename cannot leave the cards behind — and neither
+ * side has to import the other.
+ */
+
+/**
+ * What the server is called in the harness's own listing — an agent sees
+ * `mcp__harness__web_search`, `/mcp` lists `harness`, a permission prompt names `harness`.
+ *
+ * ⚠️ Deliberately NOT `SERVER_NAME` in autonomous-grid's `cli/mcp_config.py` (`grid-web`). The grid
+ * is an implementation detail of a Local model; the user's vocabulary is "Subscription" and
+ * "Local", and a tool called `mcp__grid-web__…` in a permission prompt is the one place the word
+ * would otherwise reach them. The cost is real and accepted: a person who ALSO ran `grid mcp config`
+ * by hand for their own dotfile sees two servers offering the same two tools. That person has
+ * chosen to know about the grid; everyone else has not.
+ */
+export const HARNESS_MCP_SERVER_NAME = 'harness'
+
+/** The two tools the server offers, as the control plane names them (grid-apis `web_mcp.py`). */
+const WEB_SEARCH_TOOL = 'web_search'
+const WEB_READ_TOOL = 'web_read'
+
+/**
+ * How an engine spells a tool from this server: Claude Code's `mcp__<server>__<tool>`, which Codex
+ * uses too (its `non_prefixed_mcp_tool_names` feature is off by default on 0.154.0).
+ */
+const mcpToolName = (tool: string): string => `mcp__${HARNESS_MCP_SERVER_NAME}__${tool}`
+
+/** The canonical card the desktop and web already render, and the input shape it reads. */
+export interface HarnessWebToolCard {
+ tool: 'WebSearch' | 'WebFetch'
+ input: Record<string, unknown>
+}
+
+/** Which native card a tool name from this server maps to, or null for any other tool. */
+export function harnessWebToolKind(name: string | undefined): HarnessWebToolCard['tool'] | null {
+ if (name === mcpToolName(WEB_SEARCH_TOOL)) return 'WebSearch'
+ if (name === mcpToolName(WEB_READ_TOOL)) return 'WebFetch'
+ return null
+}
+
+/**
+ * `web_read`'s list of pages as the one `url` the WebFetch card reads. One rule, used both for a
+ * structured call and for a code-mode call read back out of its source (`codex/subagent.ts`).
+ */
+export function webReadUrl(urls: readonly unknown[]): string {
+ return urls.filter((u): u is string => typeof u === 'string' && u.trim() !== '').join(', ')
+}
+
+/**
+ * The native card for a call to this server's tools, or null for any other tool.
+ *
+ * The user sees an agent searching the web, not which road it took: on a Local model the search is
+ * `mcp__harness__web_search` and on a Subscription model it is `WebSearch`, and the transcript
+ * should not look different for it. Mapping here means the server name never reaches a card even
+ * if something upstream slips.
+ *
+ * `web_search` takes `{query, num_results}` and already carries the `query` the WebSearch card
+ * reads. `web_read` takes `{urls: [...]}` (up to five) while the WebFetch card reads `url`, so the
+ * list is joined into one; the original key is kept alongside, as every engine normalizer does, so
+ * an expanded card still shows what the tool was actually given.
+ */
+export function harnessWebTool(name: string | undefined, input: unknown): HarnessWebToolCard | null {
+ const tool = harnessWebToolKind(name)
+ if (!tool) return null
+ const args = input && typeof input === 'object' && !Array.isArray(input) ? { ...(input as Record<string, unknown>) } : {}
+ if (tool === 'WebSearch') return { tool, input: args }
+ const url = typeof args.url !== 'string' && Array.isArray(args.urls) ? webReadUrl(args.urls) : ''
+ return { tool, input: url ? { ...args, url } : args }
+}
diff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.ts
index 057973fd5..b81629958 100644
--- a/cli/src/lib/launchOverrides.spec.ts
+++ b/cli/src/lib/launchOverrides.spec.ts
@@ -30,7 +30,7 @@ describe('buildLaunchOverrides — a relaunch comes back where the agent was', (
if (!result.ok) return
expect(result.overrides.env).toMatchObject({ ANTHROPIC_AUTH_TOKEN: 'gridkey-abc123', ANTHROPIC_MODEL: 'gpt-5' })
expect(result.overrides.env.ANTHROPIC_BASE_URL).toMatch(/^https:\/\/grid\.example\/grid-abc\/relay/)
- expect(result.overrides.extraArgs).toEqual(expect.arrayContaining(['--disallowedTools=WebSearch']))
+ expect(result.overrides.extraArgs).toEqual(expect.arrayContaining(['--disallowedTools=WebSearch,WebFetch']))
// Everything the launch does not set itself, so an inherited key cannot outrank the grid.
for (const name of GRID_CONFLICTING_ENV_VARS) {
expect(result.overrides.clearEnv.includes(name)).toBe(!(name in result.overrides.env))
diff --git a/cli/src/lib/normalize.spec.ts b/cli/src/lib/normalize.spec.ts
index 372614495..7171a4b56 100644
--- a/cli/src/lib/normalize.spec.ts
+++ b/cli/src/lib/normalize.spec.ts
@@ -199,3 +199,57 @@ describe('foldTranscript', () => {
expect(out).toEqual({ history: [], live: [], turnOpen: false })
})
})
+
+/**
+ * On a Local model the web tools are served by the `harness` MCP server, so a Claude Code transcript
+ * records `mcp__harness__web_search` where a Subscription model records `WebSearch`. The user sees an
+ * agent searching the web, not which road it took — so the cards are the native ones.
+ */
+describe('harness web tools render as the native cards', () => {
+ const assistantToolUse = (id: string, name: string, input: Record<string, unknown>): string =>
+ JSON.stringify({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'tool_use', id, name, input }] } })
+ const toolResult = (toolUseId: string, text: string): string =>
+ JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: toolUseId, content: text }] } })
+
+ it('maps mcp__harness__web_search to WebSearch, keeping its query', () => {
+ const state = newTurnState()
+ const events = [
+ userPrompt('what is the BTC price'),
+ assistantToolUse('t1', 'mcp__harness__web_search', { query: 'BTC price', num_results: 5 }),
+ toolResult('t1', '{"results":[]}'),
+ ].flatMap((line) => lineToEvents(line, state))
+ expect(events.find((e) => e.type === 'tool_start')).toEqual({
+ type: 'tool_start',
+ payload: { id: 't1', tool: 'WebSearch', input: { query: 'BTC price', num_results: 5 } },
+ })
+ expect(events.find((e) => e.type === 'tool_end')).toMatchObject({ payload: { id: 't1', tool: 'WebSearch', summary: 'Fetched' } })
+ })
+
+ it('maps mcp__harness__web_read to WebFetch, giving the card the `url` it reads', () => {
+ const state = newTurnState()
+ const events = [
+ userPrompt('read these'),
+ assistantToolUse('t2', 'mcp__harness__web_read', { urls: ['https://a.example/', 'https://b.example/'], max_chars: 6000 }),
+ toolResult('t2', '{"results":[]}'),
+ ].flatMap((line) => lineToEvents(line, state))
+ expect(events.find((e) => e.type === 'tool_start')).toEqual({
+ type: 'tool_start',
+ payload: {
+ id: 't2',
+ tool: 'WebFetch',
+ // The original key stays beside the one the card reads, so an expanded card shows the real input.
+ input: { urls: ['https://a.example/', 'https://b.example/'], max_chars: 6000, url: 'https://a.example/, https://b.example/' },
+ },
+ })
+ expect(events.find((e) => e.type === 'tool_end')).toMatchObject({ payload: { id: 't2', tool: 'WebFetch' } })
+ })
+
+ it('leaves every other MCP tool alone', () => {
+ const state = newTurnState()
+ const events = [
+ userPrompt('hi'),
+ assistantToolUse('t3', 'mcp__github__get_issue', { number: 1 }),
+ ].flatMap((line) => lineToEvents(line, state))
+ expect(events.find((e) => e.type === 'tool_start')).toMatchObject({ payload: { tool: 'mcp__github__get_issue', input: { number: 1 } } })
+ })
+})
diff --git a/cli/src/lib/normalize.ts b/cli/src/lib/normalize.ts
index de1c247eb..9af042604 100644
--- a/cli/src/lib/normalize.ts
+++ b/cli/src/lib/normalize.ts
@@ -13,6 +13,8 @@
* renders identically to one sent from the web (mirror-all).
*/
+import { harnessWebTool } from './harnessWebTools.js'
+
// ── Event shapes (match the server’s SessionEvent contract SessionEvent + live turn frames) ──────
export interface SubagentSummary {
@@ -244,7 +246,14 @@ function mapContentItem(item: unknown): RawContentBlock {
}
let toolInput = c.input as Record<string, unknown> | undefined
- const toolName = c.name as string | undefined
+ let toolName = c.name as string | undefined
+ // On a Local model the web tools come from the `harness` MCP server; the transcript should not
+ // look different for it, so they take the native cards here, at the one raw→normalized point.
+ const webTool = type === 'tool_use' ? harnessWebTool(toolName, toolInput) : null
+ if (webTool) {
+ toolName = webTool.tool
+ toolInput = webTool.input
+ }
if (type === 'tool_use' && toolInput) {
if ((toolName === 'Write' || toolName === 'WriteFile') && typeof toolInput.content === 'string' && toolInput.content.length > 500) {
toolInput = smartWriteInput(toolInput)