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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(cli): machine MCP servers, local stdio servers the person attaches to the agents Harness starts on a machine (#1872) (#1881)
daniel-auto22089dc4e493
diff --git a/cli/src/agentClient/mcpServers.spec.ts b/cli/src/agentClient/mcpServers.spec.tsnew file mode 100644index 000000000..9845a67da--- /dev/null+++ b/cli/src/agentClient/mcpServers.spec.ts@@ -0,0 +1,46 @@+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import { readMachineMcp } from '../lib/machineMcp.js'+import { mcpServersCommand } from './mcpServers.js'++function run(argv: string[], env: NodeJS.ProcessEnv = {}, dataDir = mkdtempSync(join(tmpdir(), 'mcp-servers-'))) {+ const out: string[] = []+ const err: string[] = []+ const code = mcpServersCommand(argv, { dataDir, env, out: (l) => out.push(l), err: (l) => err.push(l) })+ return { code, out: out.join('\n'), err: err.join('\n'), dataDir }+}++describe('harness mcp-servers (#1872)', () => {+ it('adds, lists and removes a server for the person', () => {+ const added = run(['add', 'lamp', '--engine', 'claude', '--engine', 'codex', '--', 'lamp-mcp', '--lamp', 'lamp-75c9'])+ expect(added.code).toBe(0)+ expect(added.out).toBe('lamp added: agents started from now on get it (claude, codex).')+ expect(readMachineMcp(added.dataDir).servers.lamp).toEqual({ command: 'lamp-mcp', args: ['--lamp', 'lamp-75c9'], engines: ['claude', 'codex'], projects: [] })+ expect(run([], {}, added.dataDir).out).toBe('lamp\tlamp-mcp --lamp lamp-75c9\tengines claude,codex\tprojects every folder')+ expect(run(['remove', 'lamp'], {}, added.dataDir).code).toBe(0)+ expect(readMachineMcp(added.dataDir).servers).toEqual({})+ })++ it('refuses an agent outright, even when it says the person said yes', () => {+ for (const env of [{ CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 's' }, { CODEX_THREAD_ID: 't' }, { AI_AGENT: 'cursor' }]) {+ const tried = run(['add', 'lamp', '--person-said-yes', '--', 'lamp-mcp'], env)+ expect(tried.code).toBe(5)+ expect(tried.err).toMatch(/may not change this machine's MCP servers/)+ expect(readMachineMcp(tried.dataDir).servers).toEqual({})+ }+ // Listing is fine for anyone on this machine.+ expect(run(['list'], { CODEX_THREAD_ID: 't' }).code).toBe(0)+ })++ it('refuses what it cannot keep, and says the usage for what it cannot read', () => {+ expect(run(['add', 'harness', '--', 'x']).err).toMatch(/not harness/)+ expect(run(['add', 'lamp', '--engine', 'hermes', '--', 'x']).err).toBe('hermes: this Harness attaches machine MCP servers to claude and codex only, so far.')+ // No tool approval is kept: the flag is not one.+ expect(run(['add', 'lamp', '--approve-tools', '--', 'x']).code).toBe(2)+ expect(run(['add', 'lamp', 'lamp-mcp']).code).toBe(2)+ expect(run(['add', 'lamp', '--']).code).toBe(2)+ expect(run(['remove', 'nothing']).code).toBe(1)+ })+})diff --git a/cli/src/agentClient/mcpServers.ts b/cli/src/agentClient/mcpServers.tsnew file mode 100644index 000000000..acc38f37c--- /dev/null+++ b/cli/src/agentClient/mcpServers.ts@@ -0,0 +1,102 @@+/**+ * `harness mcp-servers`: the person's machine MCP servers (lib/machineMcp.ts, #1872), local stdio servers attached to+ * every agent Harness starts on this machine, such as a paired lamp's `lamp-mcp`.+ *+ * harness mcp-servers list them+ * harness mcp-servers add NAME [--engine E]… [--project P]… -- COMMAND [ARG…]+ * harness mcp-servers remove NAME+ *+ * Written straight to this machine's data dir, where every launch reads it: nothing is sent anywhere. An agent may not+ * change it, even with the person's yes: an entry runs a command inside every later agent on this machine. No tool+ * approval and no environment are kept (lib/machineMcp.ts): each engine asks for the tools, and only the command and+ * its arguments reach the agent's command line.+ */+import { env } from '../config/env.js'+import { MACHINE_MCP_ENGINES, machineMcpPath, machineMcpServer, MACHINE_MCP_MOST_SERVERS, readMachineMcp, writeMachineMcp } from '../lib/machineMcp.js'+import { outsideCaller } from './model.js'++/** A refusal, as the agent verbs exit (commands.ts `EXIT.refused`): not a failure to retry. */+const REFUSED = 5++export const MCP_SERVERS_USAGE = `Usage: harness mcp-servers [list [--json]]+ harness mcp-servers add NAME [--engine ${MACHINE_MCP_ENGINES.join('|')}]… [--project P]… -- COMMAND [ARG…]+ harness mcp-servers remove NAME++Local MCP servers for the agents Harness starts on this machine (${MACHINE_MCP_ENGINES.join(', ')}), beside their own:+for example a paired lamp's lamp-mcp. Kept in this machine's data dir only, read at each start and relaunch.+ --engine E only for this engine (repeatable); every one by default+ --project P only in Harness project P's folder, ~/harnesses/P (repeatable); every folder by default;+ a renamed project stops matching until you add it again with the new name++Each agent asks you before it uses a server's tools, as for any other server. COMMAND and its arguments are on the+agent's command line, which other users of this computer can read: put no secret there; a server reads one from its own+config or from the environment Harness starts in. Only you change these: an agent is refused, since a server runs a+command inside every later agent.`++export interface McpServersDeps {+ dataDir?: string+ /** Who runs it, by what its shell says (model.ts `outsideCaller`): an agent may list, never change. */+ env?: NodeJS.ProcessEnv+ out?: (line: string) => void+ err?: (line: string) => void+}++export function mcpServersCommand(argv: readonly string[], deps: McpServersDeps = {}): number {+ const out = deps.out ?? console.log+ const err = deps.err ?? console.error+ const dataDir = deps.dataDir ?? env.ADAPTER_DATA_DIR+ if (argv.includes('--help') || argv.includes('-h')) { out(MCP_SERVERS_USAGE); return 0 }+ const [verb = 'list', ...rest] = argv+ const { servers, why } = readMachineMcp(dataDir)+ if (verb === 'list') {+ if (why) err(`Not read, so no agent gets these: ${why}`)+ if (rest.includes('--json')) { out(JSON.stringify(servers, null, 2)); return why ? 1 : 0 }+ if (rest.length) { err(MCP_SERVERS_USAGE); return 2 }+ const names = Object.keys(servers)+ if (!names.length && !why) out(`No machine MCP servers (${machineMcpPath(dataDir)}).`)+ for (const name of names) {+ const s = servers[name]+ out(`${name}\t${[s.command, ...s.args].join(' ')}\tengines ${(s.engines.length ? s.engines : MACHINE_MCP_ENGINES).join(',')}`+ + `\tprojects ${s.projects.length ? s.projects.join(',') : 'every folder'}`)+ }+ return why ? 1 : 0+ }+ if (verb !== 'add' && verb !== 'remove') { err(MCP_SERVERS_USAGE); return 2 }+ const agent = outsideCaller(deps.env ?? process.env, '')+ if (agent) {+ err(`${agent.name} may not change this machine's MCP servers: a server runs a command inside every later agent here. `+ + 'Tell the person the exact harness mcp-servers command to run themselves.')+ return REFUSED+ }+ if (why) { err(`Fix or remove it first: ${why}`); return 1 }+ if (verb === 'remove') {+ const [name, ...extra] = rest+ if (!name || extra.length) { err(MCP_SERVERS_USAGE); return 2 }+ if (!servers[name]) { err(`No machine MCP server named ${name}.`); return 1 }+ delete servers[name]+ writeMachineMcp(servers, dataDir)+ out(`${name} removed: agents started from now on don't get it.`)+ return 0+ }+ const dash = rest.indexOf('--')+ if (dash < 1 || dash === rest.length - 1) { err(MCP_SERVERS_USAGE); return 2 }+ const [name, ...options] = rest.slice(0, dash)+ const [command, ...args] = rest.slice(dash + 1)+ const engines: string[] = []+ const projects: string[] = []+ for (let i = 0; i < options.length; i++) {+ const option = options[i]+ if ((option === '--engine' || option === '--project') && i + 1 < options.length) (option === '--engine' ? engines : projects).push(options[++i])+ else { err(MCP_SERVERS_USAGE); return 2 }+ }+ const noPath = engines.filter((engine) => !(MACHINE_MCP_ENGINES as readonly string[]).includes(engine))+ if (noPath.length) { err(`${noPath.join(', ')}: this Harness attaches machine MCP servers to ${MACHINE_MCP_ENGINES.join(' and ')} only, so far.`); return 2 }+ const entry = machineMcpServer(name, { command, args, engines, projects })+ if (typeof entry === 'string') { err(entry); return 2 }+ if (!servers[name] && Object.keys(servers).length >= MACHINE_MCP_MOST_SERVERS) { err(`At most ${MACHINE_MCP_MOST_SERVERS} machine MCP servers.`); return 1 }+ const replaced = !!servers[name]+ servers[name] = entry+ writeMachineMcp(servers, dataDir)+ out(`${name} ${replaced ? 'replaced' : 'added'}: agents started from now on get it (${(engines.length ? engines : MACHINE_MCP_ENGINES).join(', ')}).`)+ return 0+}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex d0cc4d09e..1aa5254f5 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -178,6 +178,7 @@ Machine:harness mcp the agent verbs as an MCP server on stdin/stdout, for agents that use MCPharness help agents the agent commands, states, exit codes and rules on one screenharness settings [<name> on|off] what agents may do (agents-start-agents, agents-tell-agents, pull-request-line, agent-messages): your account's experiments in Settings ▸ Experimental, each off by default+ harness mcp-servers [add|remove] local MCP servers (a paired lamp's lamp-mcp) for the agents Harness starts here: yours alone to changeharness machines delete <id> remove ANOTHER machine (refuses this one; use \`harness logout\`)harness e2e plan which coding tools have a new version out (the grid-switch e2e trigger)harness e2e grid-switch move a fresh agent subscription -> grid -> back home with its tool + MCP; leaves a review bundle@@ -2678,6 +2679,7 @@ import { agentsHelp, helpFor } from './agentClient/help.js'import { openUrlCommand } from './agentClient/openUrl.js'import { harnessRunner, mcpCommand } from './agentClient/mcp.js'import { settingsCommand } from './agentClient/settings.js'+import { mcpServersCommand } from './agentClient/mcpServers.js'// ── arg parse ──────────────────────────────────────────────────────────────────────────────────// `hn` is the terminal client's short name (like tmux, fzf): the same CLI, entered at `tui`. A call@@ -2732,6 +2734,9 @@ switch (cmd) {case 'settings':settingsCommand(rest, { port: daemonPort() }).then(code => { process.exitCode = code }).catch(onError)break+ case 'mcp-servers':+ process.exitCode = mcpServersCommand(rest)+ breakcase 'mcp': {const pane = process.env.TMUX_PANEmcpCommand({ run: harnessRunner(SCRIPT_PATH), inPane: !!pane && !!paneOwner(pane) }).then(code => { process.exitCode = code }).catch(onError)diff --git a/cli/src/core/agents/create.spec.ts b/cli/src/core/agents/create.spec.tsindex 4ef7d5b5a..b529e14e9 100644--- a/cli/src/core/agents/create.spec.ts+++ b/cli/src/core/agents/create.spec.ts@@ -832,6 +832,19 @@ describe('creating an agent', () => {expect(deps.watchNewPane).toHaveBeenCalledWith('claude', pending, expect.anything(), ['claude'], undefined, undefined)})+ it('carries the person\'s machine MCP servers before what Harness tells the agent (#1872)', async () => {+ const { writeMachineMcp } = await import('../../lib/machineMcp.js')+ const { rmSync } = await import('node:fs')+ const { env } = await import('../../config/env.js')+ writeMachineMcp({ lamp: { command: 'lamp-mcp', args: [], engines: ['claude'], projects: [] } })+ try {+ const { create } = setup()+ await create(request({ agent: 'reviewer', startedBy: 'agent' }))+ expect((vi.mocked(buildEngineLaunchArgv).mock.calls[0][1] as Record<string, unknown>).extraArgs).toEqual([+ '--agent', 'reviewer', `--mcp-config=${JSON.stringify({ mcpServers: { lamp: { type: 'stdio', command: 'lamp-mcp', args: [] } } })}`, '--settings', '{"attribution":{}}'])+ } finally { rmSync(join(env.ADAPTER_DATA_DIR, 'mcp-servers.json'), { force: true }) }+ })+it('started by another agent: its pull request line after every other argument, and who started it on the row', async () => {const { create } = setup()const cwd = folder()diff --git a/cli/src/core/agents/create.ts b/cli/src/core/agents/create.tsindex 0c03c6b5a..71a65ceda 100644--- a/cli/src/core/agents/create.ts+++ b/cli/src/core/agents/create.ts@@ -30,6 +30,7 @@ import {} from '../../lib/engineLaunch.js'import { setUpWithin } from '../../lib/setUpWithin.js'import { agentLaunchArgs, joinedInstructions } from '../../lib/agentAttribution.js'+import { machineMcpLaunchArgs } from '../../lib/machineMcp.js'import { writeGridConfigDir } from '../../lib/gridConfigDir.js'import { describeGridLaunch, gridConfigHandOff, gridConflictingEnvToClear, type GridLaunchAnswer, type GridLaunchMachine, type GridLaunchRequest, type GridWebSearchStatus } from '../../lib/gridLaunchWire.js'import { profileEnvironment } from '../../lib/engineHomes.js'@@ -367,7 +368,10 @@ export function createAgentCreator({catch (error) { return { ok: false, error: 'SWARM_SKILL_FAILED', detail: String(error) } }}const told = agentLaunchArgs(engine, startedBy, { cwd, profile: codexHome, environment: native?.environment, ...(swarmInstructions ? { swarmInstructions } : {}) })- const extraArgs = joinedInstructions(engine, [...(gridLaunch?.args ?? relay?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, native ? native.opencodeMajor : opencode ? await opencode.opencodeMajorVersion() : null) : []), ...told])+ // The person's machine MCP servers (lib/machineMcp.ts, #1872), beside the grid's and their own: read at each launch,+ // as every relaunch reads them again (`buildLaunchOverrides`).+ const machineMcp = machineMcpLaunchArgs(engine, cwd)+ const extraArgs = joinedInstructions(engine, [...(gridLaunch?.args ?? relay?.args ?? []), ...dshArgs, ...(agent ? namedAgentArgs(engine, agent, native ? native.opencodeMajor : opencode ? await opencode.opencodeMajorVersion() : null) : []), ...machineMcp, ...told])// The first prompt is a launch option only — never part of `extraArgs`, which the registry row// carries into a relaunch (engineLaunch.ts, `firstPrompt`).const firstPrompt = promptdiff --git a/cli/src/lib/launchOverrides.spec.ts b/cli/src/lib/launchOverrides.spec.tsindex c7ed078ab..2b510e95d 100644--- a/cli/src/lib/launchOverrides.spec.ts+++ b/cli/src/lib/launchOverrides.spec.ts@@ -13,6 +13,7 @@ import { gridLaunchInProcess } from '../testing/gridLaunchInProcess.js'import { AGENT_ATTRIBUTION_LINE, HARNESS_INSTRUCTIONS } from './agentAttribution.js'import { prepareSwarmSkill } from './swarmSkills.js'import { swarmGitHubLaunch } from './swarmGitHub.js'+import { writeMachineMcp } from './machineMcp.js'const GRID: GridLaunchOverride = {networkId: 'grid-abc',@@ -404,6 +405,29 @@ describe('buildLaunchOverrides — every harness is told how to use Harness', ()})})+describe('buildLaunchOverrides — machine MCP servers (#1872)', () => {+ afterEach(() => rmSync(join(env.ADAPTER_DATA_DIR, 'mcp-servers.json'), { force: true }))++ it('carries the person\'s servers on every relaunch, beside a grid\'s own, before what Harness tells the agent', async () => {+ writeMachineMcp({ lamp: { command: 'lamp-mcp', args: ['--lamp', 'lamp-75c9'], engines: [], projects: [] } })+ setAgentSettingsForTest(env.ADAPTER_DATA_DIR, { agentsStartAgents: true })+ const own = await buildLaunchOverrides(deps({ readAttribution: () => null }).d, 'claude', { startedBy: null, cwd: '/w' }, 'a')+ expect(own).toMatchObject({ ok: true, overrides: { extraArgs: [+ `--mcp-config=${JSON.stringify({ mcpServers: { lamp: { type: 'stdio', command: 'lamp-mcp', args: ['--lamp', 'lamp-75c9'] } } })}`,+ '--append-system-prompt', HARNESS_INSTRUCTIONS] } })+ const grid = await buildLaunchOverrides(deps({ readAttribution: () => null }).d, 'claude', { startedBy: null, gridLaunch: GRID, cwd: null }, 'a')+ expect(grid.ok).toBe(true)+ if (!grid.ok) return+ // On a grid too, as its own `--mcp-config=`: a grid's web tools, when it has them, keep theirs.+ expect(grid.overrides.extraArgs.some((arg) => arg.startsWith('--mcp-config={"mcpServers":{"lamp"'))).toBe(true)+ const codex = await buildLaunchOverrides(deps({ readAttribution: () => null }).d, 'codex', { startedBy: null, cwd: null }, 'a')+ expect(codex.ok && codex.overrides.extraArgs).toEqual(expect.arrayContaining(['mcp_servers.lamp.command="lamp-mcp"', 'mcp_servers.lamp.args=["--lamp","lamp-75c9"]']))+ expect(JSON.stringify(codex)).not.toContain('approval_mode')+ const hermes = await buildLaunchOverrides(deps({ readAttribution: () => null }).d, 'hermes', { startedBy: null, cwd: null }, 'a')+ expect(JSON.stringify(hermes)).not.toContain('lamp-mcp')+ })+})+describe('buildLaunchOverrides — opencode v2', () => {const v2 = () => deps({ machine: () => ({ hermesSystemManaged: false, opencodeMajor: 2 }) }).ddiff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex 92fb1e5b8..1bdac9e9b 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -36,6 +36,7 @@ import type { DshLaunchAnswer } from '../dsh/launchWire.js'import { scmLaunchEnv } from '../scm/scmProjects.js'import type { ScmLaunchRecord } from '../scm/types.js'import { agentLaunchArgs, joinedInstructions, type StartedBy } from './agentAttribution.js'+import { machineMcpLaunchArgs } from './machineMcp.js'import type { CreationAuthority } from './agentCreationReceipt.js'import type { publishGridConfigDir } from './publishedGridConfig.js'import { nativeHookLocations } from '../engines/kit/nativeLocations.js'@@ -302,6 +303,9 @@ export async function prepareLaunchOverrides(if (source.agent && supportsNamedAgent(engine, opencodeMajor)) {overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...namedAgentArgs(engine, source.agent, opencodeMajor)] }}+ // The person's machine MCP servers (lib/machineMcp.ts, #1872), in the slot `agent_create` gave them, read again.+ const machineMcp = machineMcpLaunchArgs(engine, source.cwd ?? null)+ if (machineMcp.length) overrides = { ...overrides, extraArgs: [...overrides.extraArgs, ...machineMcp] }// What Harness tells the agent rides every relaunch, in the slot `agent_create` gave it: last. Read again each// time, with the person's switches and settings as they are now.let swarmInstructions: string | undefineddiff --git a/cli/src/lib/machineMcp.spec.ts b/cli/src/lib/machineMcp.spec.tsnew file mode 100644index 000000000..eb509c0ef--- /dev/null+++ b/cli/src/lib/machineMcp.spec.ts@@ -0,0 +1,80 @@+import { chmodSync, mkdtempSync, readFileSync, statSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, expect, it, vi } from 'vitest'+import { machineMcpArgs, machineMcpFor, machineMcpLaunchArgs, parseMachineMcp, readMachineMcp, writeMachineMcp, type MachineMcpServers } from './machineMcp.js'++const lamp = (over: Partial<MachineMcpServers[string]> = {}): MachineMcpServers[string] =>+ ({ command: 'lamp-mcp', args: ['--lamp', 'lamp-75c9'], engines: [], projects: [], ...over })++describe('machine MCP servers (#1872)', () => {+ it('attaches a stdio server to Claude Code in the one-token form, beside the person\'s own', () => {+ const args = machineMcpArgs('claude', { lamp: lamp() })+ expect(args).toEqual([`--mcp-config=${JSON.stringify({ mcpServers: { lamp: { type: 'stdio', command: 'lamp-mcp', args: ['--lamp', 'lamp-75c9'] } } })}`])+ // Variadic `--mcp-config <configs...>` would swallow a first prompt after a two-token form; never strict, and no tool+ // is approved ahead of the engine's own question.+ expect(args.some((arg) => arg === '--mcp-config' || arg === '--strict-mcp-config' || arg.startsWith('--allowedTools'))).toBe(false)+ })++ it('attaches it to Codex as -c mcp_servers.<name>, with no approval mode', () => {+ expect(machineMcpArgs('codex', { lamp: lamp({ args: ['--lamp', 'lamp "x"'] }) })).toEqual([+ '-c', 'mcp_servers.lamp.command="lamp-mcp"',+ '-c', 'mcp_servers.lamp.args=["--lamp","lamp \\"x\\""]',+ ])+ })++ it('adds nothing for an engine with no path yet, and says which servers it skipped', () => {+ expect(machineMcpArgs('hermes', { lamp: lamp() })).toEqual([])+ expect(machineMcpArgs('claude', {})).toEqual([])+ expect(machineMcpFor({ lamp: lamp({ engines: ['claude', 'hermes'] }) }, 'hermes', '/x', '/home/p')).toEqual({ servers: {}, noPath: ['lamp'] })+ // An entry for every engine means every engine with a path: nothing to say at a Hermes launch.+ expect(machineMcpFor({ lamp: lamp() }, 'hermes', '/x', '/home/p')).toEqual({ servers: {}, noPath: [] })+ })++ it('chooses by engine and by Harness project folder', () => {+ const servers = { lamp: lamp({ engines: ['codex'] }), desk: lamp({ projects: ['desk'] }) }+ const names = (engine: string, cwd: string | null) => Object.keys(machineMcpFor(servers, engine, cwd, '/home/p').servers)+ expect(names('claude', '/home/p/harnesses/desk/src')).toEqual(['desk'])+ expect(names('codex', '/home/p/harnesses/other')).toEqual(['lamp'])+ expect(names('codex', '/home/p/harnesses/desk')).toEqual(['lamp', 'desk'])+ expect(names('claude', '/home/p/harnesses/desk-2')).toEqual([])+ expect(names('claude', null)).toEqual([])+ })++ it('refuses an entry out of shape, keeps a later Harness\'s engine names, and reads a file whole or not at all', () => {+ for (const [servers, says] of [+ [{ harness: lamp() }, /not harness/], [{ 'Lamp-1': lamp() }, /a name is/], [{ lamp: { ...lamp(), command: '' } }, /command/],+ [{ lamp: { ...lamp(), engines: ['nonesuch'] } }, /engine names/], [{ lamp: { ...lamp(), projects: ['../x'] } }, /project names/],+ ] as const) {+ const parsed = parseMachineMcp(JSON.stringify({ servers: { ok: lamp(), ...servers } }))+ expect(parsed.ok).toBe(false)+ expect(parsed.ok ? '' : parsed.why).toMatch(says)+ }+ const later = parseMachineMcp(JSON.stringify({ servers: { lamp: { ...lamp(), engines: ['copilot'], approveTools: true, env: { A: 'b' } } } }))+ expect(later).toEqual({ ok: true, servers: { lamp: lamp({ engines: ['copilot'] }) } })+ expect(parseMachineMcp('{not json').ok).toBe(false)+ expect(parseMachineMcp(JSON.stringify({ servers: Object.fromEntries(Array.from({ length: 9 }, (_, i) => [`s${i}`, lamp()])) })).ok).toBe(false)+ })++ it('writes the file whole and the person\'s alone, and a launch reads it; one others could write, or that does not parse, adds nothing', () => {+ const dir = mkdtempSync(join(tmpdir(), 'machine-mcp-'))+ const file = join(dir, 'mcp-servers.json')+ expect(machineMcpLaunchArgs('claude', '/x', dir)).toEqual([])+ writeMachineMcp({ lamp: lamp() }, dir)+ expect(statSync(file).mode & 0o777).toBe(0o600)+ expect(readMachineMcp(dir).servers.lamp.command).toBe('lamp-mcp')+ expect(machineMcpLaunchArgs('codex', '/x', dir)[1]).toBe('mcp_servers.lamp.command="lamp-mcp"')+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ if (process.platform !== 'win32') {+ chmodSync(file, 0o664)+ expect(readMachineMcp(dir).why).toMatch(/writable by others \(mode 664\): chmod 600 it/)+ expect(machineMcpLaunchArgs('codex', '/x', dir)).toEqual([])+ chmodSync(file, 0o600)+ }+ writeFileSync(file, readFileSync(file, 'utf8').replace('"lamp-mcp"', '""'))+ expect(readMachineMcp(dir).why).toMatch(/command/)+ expect(machineMcpLaunchArgs('codex', '/x', dir)).toEqual([])+ expect(warn.mock.calls.at(-1)?.[0]).toMatch(/^\[agent\] machine MCP servers not added · /)+ warn.mockRestore()+ })+})diff --git a/cli/src/lib/machineMcp.ts b/cli/src/lib/machineMcp.tsnew file mode 100644index 000000000..3c2e96476--- /dev/null+++ b/cli/src/lib/machineMcp.ts@@ -0,0 +1,189 @@+/**+ * Machine MCP servers (#1872): local stdio MCP servers the person attaches to the agents Harness starts on this machine,+ * such as a paired lamp's `lamp-mcp` (autonomous-ai/lampOS `sdk/mcp`). Kept in `<data dir>/mcp-servers.json` on this+ * machine alone: never synced, never sent to the backend or another machine. Only the person changes it through+ * `harness mcp-servers` (agentClient/mcpServers.ts refuses an agent outright: an entry runs a command inside every later+ * agent).+ *+ * {"servers": {"lamp": {"command": "lamp-mcp", "args": [], "engines": ["claude", "codex"], "projects": []}}}+ *+ * What it does not carry, after harness-reviewer's read: no tool approval (a file the agent's own user can write cannot+ * hold the person's consent, so each engine asks for these tools as for any server), and no environment (only `command`+ * and `args` reach the agent's command line, which other users of the computer can read; a server reads any secret from+ * its own config).+ *+ * Read at every launch, the create and each relaunch (core/agents/create.ts, lib/launchOverrides.ts, beside+ * `agentLaunchArgs`), so a change reaches the next start and a resumed agent keeps its servers. Added beside the+ * person's own servers and a grid's web tools, never in their place. A file that does not parse, or that others could+ * write, adds nothing: it is never half-read.+ */+import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { homedir } from 'node:os'+import { dirname, isAbsolute, join, relative } from 'node:path'+import { env } from '../config/env.js'+import { ENGINES } from '../engines/types.js'++export const MACHINE_MCP_FILE = 'mcp-servers.json'+/** Engines with a launch path for a machine server in this Harness, read off each binary (below). Another engine in a+ * file is kept and skipped at its launch with a line in the log, so a later Harness's file still reads. Hermes takes+ * its servers only through the managed-scope overlay a grid launch owns (lib/gridWebMcp.ts): a follow-up. */+export const MACHINE_MCP_ENGINES = ['claude', 'codex'] as const+/** A bare word: Codex's `-c mcp_servers.<name>…` path takes a TOML bare key, and every engine names the tools by it+ * (`mcp__<name>__…`), so one spelling reads the same everywhere. */+export const MACHINE_MCP_NAME = /^[a-z][a-z0-9_]{0,31}$/+/** The grid's own server is `harness` (lib/gridWebMcp.ts `HARNESS_MCP_SERVER_NAME`): never shadowed. */+const RESERVED = new Set(['harness'])+export const MACHINE_MCP_MOST_SERVERS = 8+export const MACHINE_MCP_MOST_BYTES = 64 * 1024+const MOST_ARGS = 32++export interface MachineMcpServer {+ command: string+ args: string[]+ /** Empty: every engine in [MACHINE_MCP_ENGINES]. */+ engines: string[]+ /** Harness project names (`~/harnesses/<name>`), matched by the launch folder; empty: every folder. */+ projects: string[]+}++export type MachineMcpServers = Record<string, MachineMcpServer>++export const machineMcpPath = (dataDir: string = env.ADAPTER_DATA_DIR): string => join(dataDir, MACHINE_MCP_FILE)++const isStrings = (value: unknown, most: number): value is string[] =>+ Array.isArray(value) && value.length <= most && value.every((each) => typeof each === 'string' && each.length <= 4096)++/** One entry as stored, or why it is not one. Keys this Harness does not know are left out. */+export function machineMcpServer(name: string, raw: unknown): MachineMcpServer | string {+ if (!MACHINE_MCP_NAME.test(name) || RESERVED.has(name)) return `${name}: a name is a-z, then a-z, 0-9 or _, at most 32, and not harness`+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return `${name}: an entry is an object`+ const entry = raw as Record<string, unknown>+ if (typeof entry.command !== 'string' || !entry.command.trim() || entry.command.length > 4096) return `${name}: command is the program to run`+ const args = entry.args ?? []+ if (!isStrings(args, MOST_ARGS)) return `${name}: args is a list of at most ${MOST_ARGS} strings`+ const engines = entry.engines ?? []+ if (!isStrings(engines, ENGINES.length) || !engines.every((each) => (ENGINES as readonly string[]).includes(each))) {+ return `${name}: engines are Harness's engine names`+ }+ const projects = entry.projects ?? []+ if (!isStrings(projects, 64) || !projects.every((each) => /^[A-Za-z0-9._-]{1,100}$/.test(each) && !each.startsWith('.'))) {+ return `${name}: projects are Harness project names`+ }+ return { command: entry.command, args, engines, projects }+}++/** The servers in [text], or why the file is not read: all of it, or none. */+export function parseMachineMcp(text: string): { ok: true; servers: MachineMcpServers } | { ok: false; why: string } {+ if (Buffer.byteLength(text) > MACHINE_MCP_MOST_BYTES) return { ok: false, why: `${MACHINE_MCP_FILE} is over ${MACHINE_MCP_MOST_BYTES} bytes` }+ let value: unknown+ try { value = JSON.parse(text) } catch (error) { return { ok: false, why: `${MACHINE_MCP_FILE} is not JSON: ${error instanceof Error ? error.message : error}` } }+ const servers = (value as { servers?: unknown } | null)?.servers+ if (typeof servers !== 'object' || servers === null || Array.isArray(servers)) return { ok: false, why: `${MACHINE_MCP_FILE} is {"servers": {NAME: {...}}}` }+ const names = Object.keys(servers)+ if (names.length > MACHINE_MCP_MOST_SERVERS) return { ok: false, why: `at most ${MACHINE_MCP_MOST_SERVERS} servers` }+ const read: MachineMcpServers = {}+ for (const name of names) {+ const entry = machineMcpServer(name, (servers as Record<string, unknown>)[name])+ if (typeof entry === 'string') return { ok: false, why: entry }+ read[name] = entry+ }+ return { ok: true, servers: read }+}++/** Why a file others could change is not read: on POSIX, group- or world-writable, or another user's. */+function looseFile(file: string): string | null {+ if (process.platform === 'win32') return null+ const stat = lstatSync(file)+ if (!stat.isFile()) return `${file} is not a plain file`+ if (typeof process.getuid === 'function' && stat.uid !== process.getuid()) return `${file} belongs to another user`+ if (stat.mode & 0o022) return `${file} is writable by others (mode ${(stat.mode & 0o777).toString(8)}): chmod 600 it`+ return null+}++/** This machine's servers: none when there is no file; for a file that is not read, none and why. */+export function readMachineMcp(dataDir: string = env.ADAPTER_DATA_DIR): { servers: MachineMcpServers; why?: string } {+ const file = machineMcpPath(dataDir)+ if (!existsSync(file)) return { servers: {} }+ let text: string+ try {+ const loose = looseFile(file)+ if (loose) return { servers: {}, why: loose }+ text = readFileSync(file, 'utf8')+ } catch (error) { return { servers: {}, why: `${file}: ${error instanceof Error ? error.message : error}` } }+ const parsed = parseMachineMcp(text)+ return parsed.ok ? { servers: parsed.servers } : { servers: {}, why: `${file}: ${parsed.why}` }+}++/** Replaced whole, mode 0600 (a 0600 temporary file renamed over it), so a launch never reads half a change. */+export function writeMachineMcp(servers: MachineMcpServers, dataDir: string = env.ADAPTER_DATA_DIR): void {+ const file = machineMcpPath(dataDir)+ const text = `${JSON.stringify({ servers }, null, 2)}\n`+ const parsed = parseMachineMcp(text)+ if (!parsed.ok) throw new Error(parsed.why)+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })+ const tmp = `${file}.${process.pid}.tmp`+ writeFileSync(tmp, text, { mode: 0o600 })+ renameSync(tmp, file)+}++/** Whether [cwd] is in one of [projects]' folders (`~/harnesses/<name>`, as Harness makes them). */+function inProjects(projects: readonly string[], cwd: string | null | undefined, home: string): boolean {+ if (!projects.length) return true+ if (!cwd) return false+ return projects.some((project) => {+ const below = relative(join(home, 'harnesses', project), cwd)+ return below === '' || (!below.startsWith('..') && !isAbsolute(below))+ })+}++/** The servers [engine] gets for a launch in [cwd], and the names of those it would get but has no path for here. */+export function machineMcpFor(servers: MachineMcpServers, engine: string, cwd: string | null | undefined, home: string = homedir()):+ { servers: MachineMcpServers; noPath: string[] } {+ const chosen: MachineMcpServers = {}+ const noPath: string[] = []+ const hasPath = (MACHINE_MCP_ENGINES as readonly string[]).includes(engine)+ for (const [name, server] of Object.entries(servers)) {+ const engines: readonly string[] = server.engines.length ? server.engines : MACHINE_MCP_ENGINES+ if (!engines.includes(engine) || !inProjects(server.projects, cwd, home)) continue+ if (hasPath) chosen[name] = server+ else noPath.push(name)+ }+ return { servers: chosen, noPath }+}++/**+ * The argv that attaches [servers] to [engine]'s launch: `command` and `args` only.+ *+ * Claude Code (2.1.312, 2026-10-28): `--mcp-config <configs...>` takes JSON strings as well as files, and is variadic,+ * so it is given in the one-token `=` form: tried on the binary, `--mcp-config <json> hello` read `hello` as a config+ * file, and `--mcp-config=<json> hello` did not; a server given this way answered a real `claude -p` call. A second+ * `--mcp-config` beside a grid's is taken. Never `--strict-mcp-config`: the person's own servers stay.+ *+ * Codex (codex-cli 0.137.0, 2026-10-28): `-c mcp_servers.<name>.command=<TOML>` and `.args=<TOML array>`, read back by+ * `codex mcp list --json` as a stdio server with the arguments exactly as given.+ */+export function machineMcpArgs(engine: string, servers: MachineMcpServers): string[] {+ const names = Object.keys(servers)+ if (!names.length) return []+ if (engine === 'claude') {+ const mcpServers = Object.fromEntries(names.map((name) => [name, { type: 'stdio', command: servers[name].command, args: servers[name].args }]))+ return [`--mcp-config=${JSON.stringify({ mcpServers })}`]+ }+ if (engine === 'codex') {+ return names.flatMap((name) => [+ '-c', `mcp_servers.${name}.command=${JSON.stringify(servers[name].command)}`,+ '-c', `mcp_servers.${name}.args=${JSON.stringify(servers[name].args)}`,+ ])+ }+ return []+}++/** This machine's servers for one launch of [engine] in [cwd], as argv. A file that is not read, and a server the+ * engine has no path for, are each said in the daemon's log and add nothing. */+export function machineMcpLaunchArgs(engine: string, cwd: string | null | undefined, dataDir: string = env.ADAPTER_DATA_DIR): string[] {+ const { servers, why } = readMachineMcp(dataDir)+ if (why) console.warn(`[agent] machine MCP servers not added · ${why}`)+ const { servers: chosen, noPath } = machineMcpFor(servers, engine, cwd)+ if (noPath.length) console.warn(`[agent] machine MCP servers not added · ${engine} has no machine MCP path in this Harness yet (${noPath.join(', ')})`)+ return machineMcpArgs(engine, chosen)+}diff --git a/docs/design/2026-10-28-machine-mcp-servers.md b/docs/design/2026-10-28-machine-mcp-servers.mdnew file mode 100644index 000000000..13e6dd5fe--- /dev/null+++ b/docs/design/2026-10-28-machine-mcp-servers.md@@ -0,0 +1,96 @@+# Machine MCP servers++Issue: #1872. From lampOS (autonomous-ai/lampOS#3997): the lamp as a tool for every agent Harness starts.++## What it helps someone do++A person attaches a local stdio MCP server to every agent Harness starts on their machine, once, instead of adding it+to each engine by hand. The first use is a paired lamp's `lamp-mcp` (lampOS `sdk/mcp`). It serves the lamp as tools+(`lamp_state`, `lamp_gesture`, `lamp_light`, `lamp_say`, `lamp_look`, `lamp_move`, `lamp_express`, `lamp_stop`) and+talks to the lamp directly over the home network. So "run the tests and light the lamp green if they pass" works for an+agent Harness started in a project folder it made.++```sh+harness mcp-servers add lamp --engine claude --engine codex -- lamp-mcp+harness mcp-servers # list+harness mcp-servers remove lamp+```++## How it works++- **Where it's stored:** `<data dir>/mcp-servers.json` on that machine, mode 0600, written whole (a 0600 temporary+ file renamed over it) by `harness mcp-servers` (`agentClient/mcpServers.ts`). A launch refuses a file that is group-+ or world-writable, or another user's, and logs `[agent] machine MCP servers not added · <file> is writable by others+ (mode 664): chmod 600 it`. The schema and the launch arguments are in+ `lib/machineMcp.ts`.+- **Entries:**+ - `command` and `args`.+ - `engines`: Harness engine names; empty means every engine with a path. A name the build has no path for is kept,+ and skipped at that engine's launch with one log line (`… · hermes has no machine MCP path in this Harness yet+ (lamp)`). So a later Harness's file still reads.+ - `projects`: Harness project names, matched at each launch by the launch folder being under `~/harnesses/<name>`;+ empty means every folder. A renamed project stops matching until the entry names the new one.+- **Not carried, after harness-reviewer's read of #1872:**+ - **No tool approval:** a file the agent's own user can write can't hold the person's consent. Each engine asks for+ a machine server's tools as it does for any server, and the person's "always allow" stays in that engine.+ - **No environment:** only `command` and `args` reach the agent's command line, which other users of the computer+ can read (`ps`). A server gets the agent's environment, and reads any secret from its own config.+ - An entry's other keys are left out when it's read.+- **Names:** a bare word, `[a-z][a-z0-9_]{0,31}`, so Codex's `-c` path and every engine's tool prefix (`mcp__lamp__…`)+ read the same. `harness`, the grid's server, is refused.+- **When it's read:** at every launch, where `agentLaunchArgs` already runs: create (`core/agents/create.ts`) and every+ relaunch (`lib/launchOverrides.ts`). A change reaches the next start, and a resumed agent keeps its servers.+- **Claude Code** (2.1.312, read off the binary 2026-10-28):+ - `--mcp-config=<json>` in the one-token form. `--mcp-config <configs...>` is variadic: on the binary,+ `--mcp-config <json> hello` read `hello` as a config file, and the `=` form did not.+ - A second `--mcp-config` beside a grid's is taken.+ - Never `--strict-mcp-config`, so the person's own servers stay.+ - Tried with a real `claude -p --model haiku`: the model called the test server's `add` tool through it, and the+ server logged the call.+- **Codex** (codex-cli 0.137.0, read off the binary 2026-10-28):+ - `-c mcp_servers.<name>.command|args`. `codex mcp list --json` reads these back as a stdio server, with quotes and+ spaces intact. A real turn was not run: Codex isn't signed in on the test laptop.+- **Not yet:**+ - Hermes takes servers only through the `HERMES_MANAGED_DIR` overlay, which a grid launch already owns+ (`lib/gridWebMcp.ts`). It needs the two merged into one directory, and the overlay skipped on an admin-pinned+ machine. That's a follow-up.+ - Copilot, OpenCode and Grok each have a grid path to extend the same way.+ - Other engines have no MCP path at launch.++## Who may change it++Only the person. An agent (`model.ts` `outsideCaller`: Claude Code, Codex, `AI_AGENT`) is refused with exit 5, with no+`--person-said-yes` way round, because an entry runs a command inside every later agent on the machine. Listing is open+to anyone on the machine. The lamp holds its own limits: a Harness-started agent gets exactly the grants the lamp's+owner gave that computer, a body lease the person always wins back, and the lamp's rates and quiet hours.++## Design++- **Growth:** at most 8 servers and a 64 KiB file. `remove` deletes an entry. Nothing else accumulates.+- **Concurrency:** one writer at a time in practice (the person's CLI). Each write replaces the file atomically, so a+ launch reads the old file or the new one, never half of one. Two concurrent `add`s are last-writer-wins, said by+ `list`.+- **Read cost:** one small local file read per launch, no network.+- **Scale:** 10x the entries is past the cap. The cap is the limit, and it is said when reached.+- **Compatibility:** with no file, every launch is exactly as before, and the golden launch specs are unchanged. An older+ Harness ignores the file. The file has no version field: an unknown key in an entry is ignored, and a bad value+ refuses the whole file.+- **Migration and rollback:** none needed. Removing the file, or the version, restores today's launches.+- **Audience:** this machine only. The file is never synced, sent to the backend or shown to another machine, and the+ daemon reads it locally.+- **Identity:** the servers run as the agent's process, under the machine user who started Harness. No login of the+ owner is used or passed.+- **Failure:**+ - A file that doesn't parse, or that others could write, adds nothing. The daemon log says why at each launch (`[agent] machine MCP servers not+ added · …`), `harness mcp-servers` says it, and `add` and `remove` refuse until it's fixed.+ - A missing command, or a server that crashes, is reported by the engine as a failed MCP server, and the agent still+ starts.+- **Platforms:** macOS, Linux and Windows read the same file. The engine resolves the command on its own PATH.++## Tests++- `lib/machineMcp.spec.ts`: argv per engine, the choice by engine and project, refusals, and whole-or-nothing reads.+- `agentClient/mcpServers.spec.ts`: add, list and remove, and the agent refusal.+- `core/agents/create.spec.ts` and `lib/launchOverrides.spec.ts`: the servers reach create and every relaunch, beside a+ grid's, before Harness's instructions.+- The golden launch specs pass unchanged.