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.

harness mcp: the agent verbs as an MCP server (#1185)

Dee67f3d4283cb1
diff --git a/cli/e2e/agentClient.e2e.ts b/cli/e2e/agentClient.e2e.ts
index 462f219eb..23c5bda8d 100644
--- a/cli/e2e/agentClient.e2e.ts
+++ b/cli/e2e/agentClient.e2e.ts
@@ -7,6 +7,7 @@
* Signed in to the fake backend, which answers the account's tabs: none has Agent Messages on.
*/
import { spawn } from 'node:child_process'
+import { createInterface } from 'node:readline'
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
@@ -33,6 +34,32 @@ function harness(d: IsolatedDaemon, pane: string, args: string[], extra: Record<
})
}
+/** `harness mcp` as an MCP client starts it: requests in on stdin, answers by id from stdout. */
+function mcp(d: IsolatedDaemon, extra: Record<string, string> = {}) {
+ const child = spawn(process.execPath, ['--import', 'tsx', 'src/cli.ts', 'mcp'], {
+ cwd: CLI_ROOT, env: { ...d.env, TMUX_PANE: '', ...extra }, stdio: ['pipe', 'pipe', 'pipe'],
+ })
+ const waiting = new Map<number, (reply: Record<string, any>) => void>()
+ createInterface({ input: child.stdout }).on('line', (line) => {
+ const reply = JSON.parse(line)
+ waiting.get(reply.id)?.(reply)
+ })
+ let next = 1
+ return {
+ request(method: string, params: Record<string, unknown> = {}): Promise<Record<string, any>> {
+ const id = next++
+ child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`)
+ return new Promise((done) => waiting.set(id, done))
+ },
+ notify(method: string): void { child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', method })}\n`) },
+ async call(name: string, args: Record<string, unknown>): Promise<{ text: string; isError: boolean }> {
+ const reply = await this.request('tools/call', { name, arguments: args })
+ return { text: reply.result.content.map((c: { text: string }) => c.text).join('\n'), isError: reply.result.isError === true }
+ },
+ close(): void { child.stdin.end() },
+ }
+}
+
describe('Harness for agents, end to end', () => {
let daemon: IsolatedDaemon | undefined
let backend: FakeBackend | undefined
@@ -187,4 +214,46 @@ describe('Harness for agents, end to end', () => {
expect(closed.code, closed.err).toBe(0)
client.close()
})
+
+ it('an agent that uses MCP does the same through harness mcp', async () => {
+ const d = await IsolatedDaemon.create()
+ daemon = d
+ onTestFailed(() => { console.log(`---- daemon log\n${d.log().split('\n').slice(-150).join('\n')}`) })
+ await d.start()
+ const client = await LocalClient.connect(d)
+ const personDir = join(d.projectsDir, 'person')
+ mkdirSync(personDir, { recursive: true })
+ const theirs = await client.request('agent_create', { engine: 'claude', cwd: personDir, bypassPermission: true, name: 'theirs' }, 90_000)
+ expect(theirs.error, JSON.stringify(theirs)).toBeUndefined()
+ // An editor's agent: nothing in its environment says whose session it is, so the server does.
+ const server = mcp(d)
+ const hello = await server.request('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'cursor', version: '1' } })
+ expect(hello.result).toMatchObject({ protocolVersion: '2025-06-18', serverInfo: { name: 'harness' } })
+ expect(hello.result.instructions).toContain('Never give work to, or close, a harness you did not start')
+ server.notify('notifications/initialized')
+ const tools = (await server.request('tools/list')).result.tools.map((t: { name: string }) => t.name)
+ expect(tools).toEqual(['harness_list', 'harness_start', 'harness_wait', 'harness_read', 'harness_close'])
+
+ const dir = join(d.projectsDir, 'mcp-kid')
+ mkdirSync(dir, { recursive: true })
+ const started = await server.call('harness_start', { task: 'hello from mcp', folder: dir, name: 'mcpkid' })
+ expect(started.isError, started.text).toBe(false)
+ expect(started.text).toContain('Created mcpkid on this computer')
+ const ledger = readFileSync(join(d.dataDir, 'agent-client', 'started.jsonl'), 'utf8').trim().split('\n').map((line) => JSON.parse(line))
+ expect(ledger).toEqual([expect.objectContaining({ by: expect.objectContaining({ agentId: expect.stringMatching(/^agent:cursor:mcp-\d+$/), name: 'Cursor' }) })])
+ const waited = await server.call('harness_wait', { names: ['mcpkid'], timeout_seconds: 120 })
+ expect(waited).toEqual({ text: 'mcpkid: idle · read it: harness show mcpkid', isError: false })
+ const read = await server.call('harness_read', { name: 'mcpkid' })
+ expect(read.text).toContain('asked: [from Cursor outside Harness · ')
+ expect(read.text).toContain('hello from mcp')
+ const listed = await server.call('harness_list', {})
+ expect(listed.text.split('\n')[0]).toBe('You are Cursor, outside Harness.')
+ expect(listed.text).toMatch(/\nmcpkid +Claude Code +\w+ +you /)
+ const refused = await server.call('harness_close', { name: 'theirs' })
+ expect(refused).toEqual({ text: 'You did not start theirs, so you may not close it. Only the person can.', isError: true })
+ const closed = await server.call('harness_close', { name: 'mcpkid' })
+ expect(closed).toEqual({ text: 'Closed mcpkid. Its conversation is kept.', isError: false })
+ server.close()
+ client.close()
+ })
})
diff --git a/cli/src/agentClient/mcp.spec.ts b/cli/src/agentClient/mcp.spec.ts
new file mode 100644
index 000000000..a9288dead
--- /dev/null
+++ b/cli/src/agentClient/mcp.spec.ts
@@ -0,0 +1,131 @@
+import { PassThrough } from 'node:stream'
+import { describe, expect, it } from 'vitest'
+import { agentOfClient, answer, callerEnv, INSTRUCTIONS, mcpCommand, PROTOCOL_VERSIONS, result, type McpDeps, type Ran } from './mcp.js'
+
+/** A runner that records what it was asked and answers [ran]. */
+function runner(ran: Partial<Ran> = {}) {
+ const calls: Array<{ argv: string[]; env: NodeJS.ProcessEnv }> = []
+ const run = async (argv: string[], env: NodeJS.ProcessEnv): Promise<Ran> => { calls.push({ argv, env }); return { code: 0, out: 'ok\n', err: '', ...ran } }
+ return { calls, run }
+}
+const deps = (over: Partial<McpDeps> = {}): McpDeps => ({ run: runner().run, env: {}, cwd: '/work/here', session: 'mcp-1', ...over })
+const call = (name: string, args: Record<string, unknown> = {}, id = 1) => ({ jsonrpc: '2.0', id, method: 'tools/call', params: { name, arguments: args } })
+
+describe('harness mcp', () => {
+ it('answers initialize in the client\'s protocol version when it knows it, with what to use Harness for', async () => {
+ const state: { client?: string } = {}
+ const known = await answer({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18', clientInfo: { name: 'cursor-vscode' } } }, deps(), state)
+ expect(known).toMatchObject({ jsonrpc: '2.0', id: 1, result: { protocolVersion: '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'harness' }, instructions: INSTRUCTIONS } })
+ expect(state.client).toBe('cursor-vscode')
+ const newer = await answer({ jsonrpc: '2.0', id: 2, method: 'initialize', params: { protocolVersion: '2099-01-01' } }, deps())
+ expect((newer!.result as Record<string, unknown>).protocolVersion).toBe(PROTOCOL_VERSIONS[0])
+ expect(await answer({ jsonrpc: '2.0', id: 3, method: 'ping' }, deps())).toEqual({ jsonrpc: '2.0', id: 3, result: {} })
+ })
+
+ it('lists send only to a harness in its own pane: an agent outside Harness has nothing to be answered at', async () => {
+ const names = async (inPane: boolean) => ((await answer({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, deps({ inPane })))!.result as { tools: Array<{ name: string; argv?: unknown }> }).tools
+ const outside = await names(false)
+ expect(outside.map((t) => t.name)).toEqual(['harness_list', 'harness_start', 'harness_wait', 'harness_read', 'harness_close'])
+ expect(outside.every((t) => t.argv === undefined)).toBe(true)
+ expect((await names(true)).map((t) => t.name)).toContain('harness_send')
+ expect(await answer(call('harness_send', { to: 'x', text: 'y' }), deps())).toMatchObject({ error: { code: -32602 } })
+ })
+
+ it('runs each tool as its verb', async () => {
+ const r = runner()
+ const d = deps({ run: r.run, inPane: true })
+ await answer(call('harness_list'), d)
+ await answer(call('harness_list', { all: true }), d)
+ await answer(call('harness_start', { task: 'review it\nall of it', folder: 'app', name: 'reviewer' }), d)
+ await answer(call('harness_start', { task: 'train', folder: '/abs', name: 'gpu', agent: 'codex', machine: 'mini' }), d)
+ await answer(call('harness_start', { task: 'x', folder: '~/p', name: 'n' }), d)
+ await answer(call('harness_wait', { names: ['a', ' b ', ''] }), d)
+ await answer(call('harness_wait', { names: ['a'], any: true, timeout_seconds: 9999 }), d)
+ await answer(call('harness_wait', { names: ['a'], timeout_seconds: 1.5 }), d)
+ await answer(call('harness_read', { name: 'a' }), d)
+ await answer(call('harness_read', { name: 'a', chars: 99.9 }), d)
+ await answer(call('harness_send', { to: 'a', text: 'also the footer' }), d)
+ await answer(call('harness_close', { name: 'a' }), d)
+ await answer(call('harness_close', { name: 'a', now: true }), d)
+ expect(r.calls.map((c) => c.argv)).toEqual([
+ ['ps'], ['ps', '--all'],
+ ['new', 'claude', '/work/here/app', '--name', 'reviewer', '--task', 'review it\nall of it'],
+ ['new', 'codex', '@mini', '/abs', '--name', 'gpu', '--task', 'train'],
+ ['new', 'claude', '~/p', '--name', 'n', '--task', 'x'],
+ ['wait', 'a,b', '--timeout', '120s'], ['wait', 'a', '--any', '--timeout', '600s'], ['wait', 'a', '--timeout', '2s'],
+ ['show', 'a'], ['show', 'a', '--chars', '99'],
+ ['send', 'a', 'also the footer'],
+ ['close', 'a'], ['close', 'a', '--now'],
+ ])
+ })
+
+ it('says whose session it is when the agent did not, and leaves a harness pane and a named session alone', () => {
+ expect(callerEnv(deps({ env: { PATH: '/bin' } }), 'cursor-vscode')).toEqual({ PATH: '/bin', AI_AGENT: 'cursor', HARNESS_AGENT_SESSION: 'mcp-1' })
+ expect(callerEnv(deps({ env: { AI_AGENT: 'amp_1_agent' } }))).toEqual({ AI_AGENT: 'amp_1_agent', HARNESS_AGENT_SESSION: 'mcp-1' })
+ expect(callerEnv(deps({ env: {} }))).toMatchObject({ AI_AGENT: 'mcp-client' })
+ expect(callerEnv(deps({ env: {}, session: undefined }))).toMatchObject({ HARNESS_AGENT_SESSION: `mcp-${process.ppid}` })
+ expect(callerEnv(deps({ env: { CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 's' } }), 'claude-code')).toEqual({ CLAUDECODE: '1', CLAUDE_CODE_SESSION_ID: 's' })
+ expect(callerEnv(deps({ env: { CODEX_THREAD_ID: 't' } }))).toEqual({ CODEX_THREAD_ID: 't' })
+ expect(callerEnv(deps({ env: { TMUX_PANE: '%1' }, inPane: true }))).toEqual({ TMUX_PANE: '%1' })
+ })
+
+ it('knows the agents MCP clients are by the names they give', () => {
+ expect(['claude-code', 'codex-mcp-client', 'Cursor-VSCode', 'claude-ai', 'claude-desktop', 'my agent_2', '', ' '].map(agentOfClient))
+ .toEqual(['claude-code', 'codex', 'cursor', 'claude-desktop', 'claude-desktop', 'my-agent-2', 'mcp-client', 'mcp-client'])
+ })
+
+ it('answers with what the verb printed; a failure is an error, and a wait that ends without an answer is not', () => {
+ expect(result('harness_list', { code: 0, out: 'rows\n', err: '' })).toEqual({ content: [{ type: 'text', text: 'rows' }] })
+ expect(result('harness_close', { code: 0, out: '', err: '' })).toEqual({ content: [{ type: 'text', text: 'Done.' }] })
+ expect(result('harness_close', { code: 1, out: '', err: 'You did not start x, so you may not close it.\n' }))
+ .toEqual({ content: [{ type: 'text', text: 'You did not start x, so you may not close it.' }], isError: true })
+ expect(result('harness_read', { code: 2, out: '', err: '' })).toEqual({ content: [{ type: 'text', text: 'harness exited 2' }], isError: true })
+ expect(result('harness_wait', { code: 3, out: 'a: needs-input\n', err: '' })).toEqual({ content: [{ type: 'text', text: 'a: needs-input' }] })
+ expect(result('harness_wait', { code: 4, out: 'a: stopped\n', err: '' }).isError).toBeUndefined()
+ expect(result('harness_wait', { code: 124, out: 'a: working\n', err: '' })).toEqual({ content: [{ type: 'text', text: 'a: working\nStill working. Call harness_wait again to keep waiting.' }] })
+ expect(result('harness_wait', { code: 124, out: '', err: '' }).content[0].text).toBe('Still working. Call harness_wait again to keep waiting.')
+ // Elsewhere those exits are failures.
+ expect(result('harness_read', { code: 3, out: '', err: 'x' }).isError).toBe(true)
+ })
+
+ it('refuses what is not a request it knows, and answers no notification', async () => {
+ expect(await answer({ jsonrpc: '2.0', method: 'notifications/initialized' }, deps())).toBeNull()
+ expect(await answer({ jsonrpc: '2.0', method: 'notifications/unknown' }, deps())).toBeNull()
+ expect(await answer({ jsonrpc: '2.0', id: 4, method: 'resources/list' }, deps())).toEqual({ jsonrpc: '2.0', id: 4, error: { code: -32601, message: 'Method not found: resources/list' } })
+ expect(await answer({ jsonrpc: '2.0', id: 5 }, deps())).toEqual({ jsonrpc: '2.0', id: 5, error: { code: -32600, message: 'Invalid request' } })
+ expect(await answer({ jsonrpc: '2.0' }, deps())).toBeNull()
+ expect(await answer({ jsonrpc: '2.0', id: 6, method: 'tools/call', params: { name: 'harness_nope' } }, deps())).toMatchObject({ error: { code: -32602, message: 'Unknown tool: harness_nope' } })
+ // Arguments that are not an object are none.
+ const r = runner()
+ await answer({ jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name: 'harness_list', arguments: 'x' } }, deps({ run: r.run }))
+ expect(r.calls[0].argv).toEqual(['ps'])
+ })
+
+ it('serves newline-delimited JSON-RPC, calls side by side, until its input ends', async () => {
+ const input = new PassThrough(), output = new PassThrough()
+ const written: string[] = []
+ output.on('data', (chunk) => written.push(...String(chunk).split('\n').filter(Boolean)))
+ let release: () => void = () => {}
+ const slow = new Promise<void>((done) => { release = done })
+ const run = async (argv: string[]): Promise<Ran> => {
+ if (argv[0] === 'wait') await slow
+ if (argv[0] === 'show') throw new Error('boom')
+ return { code: 0, out: argv[0], err: '' }
+ }
+ const served = mcpCommand({ run, env: {}, session: 's' }, input, output)
+ input.write(`${JSON.stringify(call('harness_wait', { names: ['a'] }, 1))}\n\nnot json\n`)
+ input.write(`${JSON.stringify(call('harness_list', {}, 2))}\n`)
+ input.write(`${JSON.stringify(call('harness_read', { name: 'a' }, 3))}\n`)
+ await new Promise((done) => setTimeout(done, 20))
+ // The list and the failure answered while the wait still waits.
+ expect(written.map((line) => JSON.parse(line))).toEqual([
+ { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } },
+ { jsonrpc: '2.0', id: 2, result: { content: [{ type: 'text', text: 'ps' }] } },
+ { jsonrpc: '2.0', id: 3, error: { code: -32603, message: 'boom' } },
+ ])
+ release()
+ input.end()
+ expect(await served).toBe(0)
+ expect(JSON.parse(written.at(-1)!)).toEqual({ jsonrpc: '2.0', id: 1, result: { content: [{ type: 'text', text: 'wait' }] } })
+ })
+})
diff --git a/cli/src/agentClient/mcp.ts b/cli/src/agentClient/mcp.ts
new file mode 100644
index 000000000..785a3ac77
--- /dev/null
+++ b/cli/src/agentClient/mcp.ts
@@ -0,0 +1,224 @@
+/**
+ * `harness mcp`: the agent verbs as an MCP server on stdin and stdout (docs/design/2026-10-11-agent-client.md), for
+ * agents that reach their tools through MCP rather than a shell: Claude Desktop, Cursor, Windsurf, and Claude Code or
+ * Codex with the Harness plugin. One server is one agent's session.
+ *
+ * Each call runs the verb as `harness` itself, in a process of its own with this server's environment, so what an
+ * agent may do is decided where it is for the shell's verbs (`agentOrigin`, `close`), and the answer is the text the
+ * verb prints. The server tells the verbs whose session it is when the agent's own environment does not
+ * (`outsideCaller`): one caller per server, never the person.
+ *
+ * Newline-delimited JSON-RPC 2.0, as MCP's stdio transport is. Nothing but protocol goes to stdout.
+ */
+import { spawn } from 'node:child_process'
+import { isAbsolute, resolve } from 'node:path'
+import { createInterface } from 'node:readline'
+import { VERSION } from '../version.js'
+import { AGENT_SESSION_ENV } from './model.js'
+import { EXIT } from './commands.js'
+
+/** Newest first: the client's own when it is one of these, else the newest. */
+export const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'] as const
+
+/** What an agent is told once, as it connects: when Harness is the right tool, and whose harnesses are whose. */
+export const INSTRUCTIONS = `Harness runs coding agents (Claude Code, Codex) in sessions of their own, on this computer or the person's other machines. The person can watch and join every one in the Harness app.
+
+Start a harness (harness_start) for work that can run beside yours, needs another agent's view (a review, a second opinion from Codex), takes long, or belongs in its own folder. Do small, quick work yourself.
+
+List first (harness_list). Send follow-ups for the same work to the harness you started for it, not a new one. Never give work to, or close, a harness you did not start: those are the person's.
+
+Name every harness. Then wait for it (harness_wait), read its answer (harness_read), and close it when you are done (harness_close). Never ask a harness to publish, deploy, delete or push.`
+
+/** How long `harness_wait` waits when not told: within what MCP clients allow a call. */
+const WAIT_DEFAULT_S = 120
+const WAIT_MAX_S = 600
+
+interface Tool {
+ name: string
+ description: string
+ inputSchema: Record<string, unknown>
+ annotations?: Record<string, unknown>
+ /** The `harness` words for these arguments. */
+ argv: (args: Record<string, unknown>, cwd: string) => string[]
+}
+
+const str = (value: unknown): string => (typeof value === 'string' ? value.trim() : '')
+const schema = (properties: Record<string, unknown>, required: string[] = []) => ({ type: 'object', properties, required, additionalProperties: false })
+
+export const TOOLS: Tool[] = [
+ {
+ name: 'harness_list',
+ description: 'The harnesses on this machine: name, agent, state (working, idle, needs-input), who started each ("you" for yours), when it was last active, its folder, and what it is about.',
+ inputSchema: schema({ all: { type: 'boolean', description: 'Also the ones stopped in the last week.' } }),
+ annotations: { readOnlyHint: true },
+ argv: (a) => ['ps', ...(a.all === true ? ['--all'] : [])],
+ },
+ {
+ name: 'harness_start',
+ description: 'Start a new harness: an agent in a session of its own, working on [task] in [folder]. Returns at once; wait for it with harness_wait and read its answer with harness_read.',
+ inputSchema: schema({
+ task: { type: 'string', description: 'The whole task, as you would write it to a colleague: what to do, where, and what to answer with.' },
+ folder: { type: 'string', description: 'The folder to work in: an absolute path, or one relative to where this server runs.' },
+ name: { type: 'string', description: 'A short name to call it by (e.g. "reviewer"). Always give one.' },
+ agent: { type: 'string', enum: ['claude', 'codex'], description: 'Claude Code (default) or Codex.' },
+ machine: { type: 'string', description: 'Another of the person\'s machines, by name, to run it there.' },
+ }, ['task', 'folder', 'name']),
+ argv: (a, cwd) => {
+ const folder = str(a.folder)
+ return ['new', str(a.agent) || 'claude', ...(str(a.machine) ? [`@${str(a.machine)}`] : []), isAbsolute(folder) || folder.startsWith('~') ? folder : resolve(cwd, folder || '.'),
+ '--name', str(a.name), '--task', typeof a.task === 'string' ? a.task : '']
+ },
+ },
+ {
+ name: 'harness_wait',
+ description: `Wait until harnesses stop working, then say each one's state. Waits up to timeout_seconds (${WAIT_DEFAULT_S} by default); if they are still working then, call it again.`,
+ inputSchema: schema({
+ names: { type: 'array', items: { type: 'string' }, minItems: 1, description: 'The harnesses to wait for.' },
+ any: { type: 'boolean', description: 'Return when the first one is done, not all.' },
+ timeout_seconds: { type: 'number', minimum: 1, maximum: WAIT_MAX_S },
+ }, ['names']),
+ annotations: { readOnlyHint: true },
+ argv: (a) => {
+ const names = Array.isArray(a.names) ? a.names.map(str).filter(Boolean) : []
+ const seconds = typeof a.timeout_seconds === 'number' && a.timeout_seconds > 0 ? Math.min(Math.ceil(a.timeout_seconds), WAIT_MAX_S) : WAIT_DEFAULT_S
+ return ['wait', names.join(','), ...(a.any === true ? ['--any'] : []), '--timeout', `${seconds}s`]
+ },
+ },
+ {
+ name: 'harness_read',
+ description: 'A harness\'s state and its last turn: what it was asked and what it answered.',
+ inputSchema: schema({ name: { type: 'string' }, chars: { type: 'number', minimum: 1, description: 'How much of the answer (4000 characters by default).' } }, ['name']),
+ annotations: { readOnlyHint: true },
+ argv: (a) => ['show', str(a.name), ...(typeof a.chars === 'number' && a.chars > 0 ? ['--chars', String(Math.floor(a.chars))] : [])],
+ },
+ {
+ name: 'harness_send',
+ description: 'Send a message to a harness you started, while it works: a follow-up, a correction, more context.',
+ inputSchema: schema({ to: { type: 'string', description: 'The harness\'s name.' }, text: { type: 'string' } }, ['to', 'text']),
+ argv: (a) => ['send', str(a.to), typeof a.text === 'string' ? a.text : ''],
+ },
+ {
+ name: 'harness_close',
+ description: 'Close a harness you started, once it is done. Its conversation is kept: the person can resume it. Refused while it works, unless now is true.',
+ inputSchema: schema({ name: { type: 'string' }, now: { type: 'boolean', description: 'Close it even while it works.' } }, ['name']),
+ annotations: { destructiveHint: true },
+ argv: (a) => ['close', str(a.name), ...(a.now === true ? ['--now'] : [])],
+ },
+]
+
+export interface Ran { code: number; out: string; err: string }
+export type Runner = (argv: string[], env: NodeJS.ProcessEnv) => Promise<Ran>
+
+/** `harness <argv>` as this process was started: the same script and Node options, so sources and bundle alike. */
+export function harnessRunner(scriptPath: string): Runner {
+ return (argv, env) => new Promise((done) => {
+ const child = spawn(process.execPath, [...process.execArgv, scriptPath, ...argv], { env, stdio: ['ignore', 'pipe', 'pipe'] })
+ let out = '', err = ''
+ child.stdout.on('data', (chunk) => { out += chunk })
+ child.stderr.on('data', (chunk) => { err += chunk })
+ child.on('error', (error) => done({ code: 1, out, err: err || error.message }))
+ child.on('close', (code) => done({ code: code ?? 1, out, err }))
+ })
+}
+
+export interface McpDeps {
+ run: Runner
+ env?: NodeJS.ProcessEnv
+ cwd?: string
+ /** This server's session: one a server, as its parent is the agent that started it. */
+ session?: string
+ /** Messages reach only a harness's pane, and an agent outside Harness has none to answer from. */
+ inPane?: boolean
+}
+
+type Message = { jsonrpc?: string; id?: string | number | null; method?: string; params?: Record<string, unknown> }
+
+/** The answer to one JSON-RPC message, or null for a notification. */
+export async function answer(message: Message, deps: McpDeps, state: { client?: string } = {}): Promise<Record<string, unknown> | null> {
+ const id = message.id
+ const isRequest = id !== undefined && id !== null
+ const reply = (result: unknown) => ({ jsonrpc: '2.0', id, result })
+ const fail = (code: number, text: string) => ({ jsonrpc: '2.0', id: isRequest ? id : null, error: { code, message: text } })
+ if (typeof message.method !== 'string') return isRequest ? fail(-32600, 'Invalid request') : null
+ const tools = TOOLS.filter((tool) => tool.name !== 'harness_send' || deps.inPane)
+ switch (message.method) {
+ case 'initialize': {
+ const asked = str(message.params?.protocolVersion)
+ const info = message.params?.clientInfo as { name?: unknown } | undefined
+ state.client = str(info?.name)
+ return reply({
+ protocolVersion: (PROTOCOL_VERSIONS as readonly string[]).includes(asked) ? asked : PROTOCOL_VERSIONS[0],
+ capabilities: { tools: {} },
+ serverInfo: { name: 'harness', title: 'Harness', version: VERSION },
+ instructions: INSTRUCTIONS,
+ })
+ }
+ case 'ping': return reply({})
+ case 'tools/list': return reply({ tools: tools.map(({ argv: _argv, ...tool }) => tool) })
+ case 'tools/call': {
+ const tool = tools.find((t) => t.name === message.params?.name)
+ if (!tool) return fail(-32602, `Unknown tool: ${String(message.params?.name)}`)
+ const args = (message.params?.arguments && typeof message.params.arguments === 'object' ? message.params.arguments : {}) as Record<string, unknown>
+ const ran = await deps.run(tool.argv(args, deps.cwd ?? process.cwd()), callerEnv(deps, state.client))
+ return reply(result(tool.name, ran))
+ }
+ default:
+ return isRequest ? fail(-32601, `Method not found: ${message.method}`) : null
+ }
+}
+
+/**
+ * The environment a verb runs with: this server's, and whose session it is when the agent did not say (Claude Code's
+ * and Codex's shells do; an MCP server's environment may not). `AI_AGENT` names the agent, as its client said.
+ */
+export function callerEnv(deps: McpDeps, client = ''): NodeJS.ProcessEnv {
+ const env = { ...(deps.env ?? process.env) }
+ if (deps.inPane || (env.CLAUDECODE === '1' && env.CLAUDE_CODE_SESSION_ID) || env.CODEX_THREAD_ID) return env
+ if (!env.AI_AGENT) env.AI_AGENT = agentOfClient(client)
+ env[AGENT_SESSION_ENV] = deps.session ?? `mcp-${process.ppid}`
+ return env
+}
+
+/** The agent an MCP client is, by the name it gives in `initialize` (seen: Claude Code's, Codex's), as `AI_AGENT` names it. */
+export function agentOfClient(client: string): string {
+ const name = client.trim().toLowerCase()
+ if (name === 'claude-code') return 'claude-code'
+ if (name.startsWith('codex')) return 'codex'
+ if (name.startsWith('cursor')) return 'cursor'
+ if (name === 'claude-ai' || name === 'claude-desktop') return 'claude-desktop'
+ return name.replace(/[^\w.-]+/g, '-').replace(/_/g, '-').slice(0, 40) || 'mcp-client'
+}
+
+/** A verb's exit as a tool's result: its text, and an error only when it failed. Waiting that ends on the person, a
+ * stop or the clock is an answer, not a failure. */
+export function result(tool: string, ran: Ran): { content: Array<{ type: 'text'; text: string }>; isError?: boolean } {
+ const text = [ran.out.trim(), ran.err.trim()].filter(Boolean).join('\n')
+ if (tool === 'harness_wait' && ran.code === EXIT.timeout) {
+ return { content: [{ type: 'text', text: `${text ? `${text}\n` : ''}Still working. Call harness_wait again to keep waiting.` }] }
+ }
+ const answered = ran.code === EXIT.ok || (tool === 'harness_wait' && (ran.code === EXIT.needsInput || ran.code === EXIT.stopped))
+ return answered ? { content: [{ type: 'text', text: text || 'Done.' }] } : { content: [{ type: 'text', text: text || `harness exited ${ran.code}` }], isError: true }
+}
+
+/** Serve MCP on stdin and stdout until stdin closes. */
+export async function mcpCommand(deps: McpDeps, input: NodeJS.ReadableStream = process.stdin, output: NodeJS.WritableStream = process.stdout): Promise<number> {
+ const state: { client?: string } = {}
+ const lines = createInterface({ input, crlfDelay: Infinity })
+ const pending = new Set<Promise<void>>()
+ for await (const line of lines) {
+ if (!line.trim()) continue
+ let message: Message
+ try { message = JSON.parse(line) } catch {
+ output.write(`${JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } })}\n`)
+ continue
+ }
+ // Calls run side by side: a wait must not hold up a list.
+ const job = answer(message, deps, state)
+ .then((reply) => { if (reply) output.write(`${JSON.stringify(reply)}\n`) })
+ .catch((error) => { output.write(`${JSON.stringify({ jsonrpc: '2.0', id: message.id ?? null, error: { code: -32603, message: String((error as Error)?.message ?? error) } })}\n`) })
+ .finally(() => pending.delete(job))
+ pending.add(job)
+ }
+ await Promise.all(pending)
+ return 0
+}
diff --git a/cli/src/agentClient/model.spec.ts b/cli/src/agentClient/model.spec.ts
index aafaec464..055427050 100644
--- a/cli/src/agentClient/model.spec.ts
+++ b/cli/src/agentClient/model.spec.ts
@@ -50,9 +50,14 @@ describe('a harness as the agent verbs show it', () => {
.toEqual({ machineId: 'm', agentId: 'claude-code:S1', name: 'Claude Code', engine: 'claude', outside: true })
expect(outsideCaller({ CODEX_THREAD_ID: 'T1' }, 'm')).toEqual({ machineId: 'm', agentId: 'codex:T1', name: 'Codex', engine: 'codex', outside: true })
// An agent that names only itself is one caller for every session of it.
- expect(outsideCaller({ AI_AGENT: 'cursor_1-2_agent' }, 'm')).toEqual({ machineId: 'm', agentId: 'agent:cursor', name: 'cursor', engine: 'cursor', outside: true })
+ expect(outsideCaller({ AI_AGENT: 'cursor_1-2_agent' }, 'm')).toEqual({ machineId: 'm', agentId: 'agent:cursor', name: 'Cursor', engine: 'cursor', outside: true })
+ expect(outsideCaller({ AI_AGENT: 'claude-desktop' }, 'm')).toMatchObject({ name: 'Claude Desktop', engine: 'claude-desktop' })
+ expect(outsideCaller({ AI_AGENT: 'codex' }, 'm')).toMatchObject({ name: 'Codex', engine: 'codex' })
+ expect(outsideCaller({ AI_AGENT: 'newagent' }, 'm')).toMatchObject({ name: 'newagent' })
expect(outsideCaller({ CLAUDECODE: '1' }, 'm')).toMatchObject({ agentId: 'agent:claude-code', name: 'Claude Code', engine: 'claude' })
expect(outsideCaller({ CLAUDECODE: '0', CLAUDE_CODE_SESSION_ID: 'S1' }, 'm')).toBeNull()
+ // What runs `harness` for it and knows its session says so (`harness mcp`).
+ expect(outsideCaller({ AI_AGENT: 'cursor', HARNESS_AGENT_SESSION: 'mcp-42' }, 'm')).toMatchObject({ agentId: 'agent:cursor:mcp-42', name: 'Cursor' })
expect(outsideCaller({ AI_AGENT: ' ' }, 'm')).toBeNull()
})
diff --git a/cli/src/agentClient/model.ts b/cli/src/agentClient/model.ts
index 0b5cdbd56..490e1d4c0 100644
--- a/cli/src/agentClient/model.ts
+++ b/cli/src/agentClient/model.ts
@@ -92,9 +92,18 @@ export function outsideCaller(env: NodeJS.ProcessEnv, machineId: string): Caller
// "claude-code_2-1-296_agent": the agent's name, then its version.
const named = (env.AI_AGENT?.trim() || (env.CLAUDECODE === '1' ? 'claude-code' : '')).split('_')[0].slice(0, 40)
if (!named) return null
- return { machineId, agentId: `agent:${named}`, name: named === 'claude-code' ? 'Claude Code' : named, engine: named === 'claude-code' ? 'claude' : named, outside: true }
+ // A wrapper that knows the session when the agent does not say it: `harness mcp`, one server a session.
+ const session = env[AGENT_SESSION_ENV]?.trim().slice(0, 80)
+ const engine = named === 'claude-code' ? 'claude' : named
+ return { machineId, agentId: `agent:${named}${session ? `:${session}` : ''}`, name: AGENT_NAMES[named] ?? engineName(engine), engine, outside: true }
}
+/** Agents that are not an engine Harness runs, by the name they give. */
+const AGENT_NAMES: Record<string, string> = { 'claude-desktop': 'Claude Desktop', windsurf: 'Windsurf', cline: 'Cline', zed: 'Zed' }
+
+/** Set beside AI_AGENT by what runs `harness` for an agent and knows its session (`harness mcp`): one caller a session. */
+export const AGENT_SESSION_ENV = 'HARNESS_AGENT_SESSION'
+
export interface RowContext {
machineId: string
machine: string
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 28cad60e2..16848e566 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -143,6 +143,7 @@ Machine:
harness show <name> a harness's state and last turn: what it was asked and what it answered
harness wait <name>[,<name>] wait until they stop working (--any, --timeout 30m); exit 3 = needs the person
harness close <name> [--now] save a harness's screen and stop it; an agent closes only what it started
+ harness mcp the agent verbs as an MCP server on stdin/stdout, for agents that use MCP
harness machines delete <id> remove ANOTHER machine (refuses this one; use \`harness logout\`)
harness remote from a Harness terminal tile: open a terminal on another of your machines and move this tile to it
harness version print the installed version (v${VERSION})
@@ -2447,8 +2448,9 @@ async function logsExportCommand(json: boolean): Promise<void> {
}
import { orchestratorCommand } from './orchestrator/command.js'
-import { sendCommand } from './messages/command.js'
+import { paneOwner, sendCommand } from './messages/command.js'
import { agentOrigin, closeCommand, psCommand, showCommand, waitCommand } from './agentClient/commands.js'
+import { harnessRunner, mcpCommand } from './agentClient/mcp.js'
// ── arg parse ──────────────────────────────────────────────────────────────────────────────────
// `hn` is the terminal client's short name (like tmux, fzf): the same CLI, entered at `tui`. A call
@@ -2483,6 +2485,11 @@ switch (cmd) {
case 'ps':
psCommand(rest).then(code => { process.exitCode = code }).catch(onError)
break
+ case 'mcp': {
+ const pane = process.env.TMUX_PANE
+ mcpCommand({ run: harnessRunner(SCRIPT_PATH), inPane: !!pane && !!paneOwner(pane) }).then(code => { process.exitCode = code }).catch(onError)
+ break
+ }
case 'show':
showCommand(rest).then(code => { process.exitCode = code }).catch(onError)
break
diff --git a/cli/src/lib/agentSessionEnv.ts b/cli/src/lib/agentSessionEnv.ts
index 19658f10b..ec17a51b4 100644
--- a/cli/src/lib/agentSessionEnv.ts
+++ b/cli/src/lib/agentSessionEnv.ts
@@ -12,7 +12,7 @@
* A setting the person chose (CLAUDE_CODE_USE_BEDROCK, CODEX_HOME, …) is not a session's, and stays.
*/
const AGENT_SESSION_VARIABLES: ReadonlySet<string> = new Set([
- 'AI_AGENT',
+ 'AI_AGENT', 'HARNESS_AGENT_SESSION',
'CLAUDECODE', 'CLAUDE_PID', 'CLAUDE_CODE_ENTRYPOINT', 'CLAUDE_CODE_SESSION_ID', 'CLAUDE_CODE_CHILD_SESSION',
'CLAUDE_CODE_SESSION_ATTENDED', 'CLAUDE_CODE_EXECPATH', 'CLAUDE_CODE_MESSAGING_SOCKET', 'CLAUDE_CODE_MESSAGING_TOKEN',
'CODEX_THREAD_ID', 'CODEX_CI', 'CODEX_SANDBOX', 'CODEX_SANDBOX_NETWORK_DISABLED', 'CODEX_ESCALATE_SOCKET',
diff --git a/docs/design/2026-10-11-agent-client.md b/docs/design/2026-10-11-agent-client.md
index 17fbe732e..f202228a0 100644
--- a/docs/design/2026-10-11-agent-client.md
+++ b/docs/design/2026-10-11-agent-client.md
@@ -123,6 +123,25 @@ environment to every pane: every harness would have been that agent's session, w
master and the core drop those variables before they start anything, and the core removes them from a tmux
server's environment as it removes harnessd's own (`lib/agentSessionEnv.ts`).
+### MCP
+
+`harness mcp` serves the verbs as MCP tools on stdin and stdout, for agents that reach tools through MCP rather
+than a shell (Claude Desktop, Cursor, Windsurf; Claude Code and Codex with the Harness plugin): `harness_list`,
+`harness_start`, `harness_wait`, `harness_read`, `harness_close`, and `harness_send` only in a harness's own pane,
+since nothing can message an agent outside one. Each call runs the verb as `harness` in a process of its own, so
+the rules above decide what it may do, and the tool's answer is the text the verb prints. `initialize` carries the
+when-to-use rules as the server's instructions.
+
+The server is one agent's session. An MCP server's environment need not name the session (Codex's does not), so the
+server says it: `AI_AGENT` from the client's name in `initialize` (`codex-mcp-client` is Codex, `cursor-vscode`
+Cursor, `claude-ai` Claude Desktop) and `HARNESS_AGENT_SESSION` from its parent, the agent that started it. A
+`harness_wait` waits two minutes unless told (ten at most), within what clients allow a call, and says to call it
+again; ending on the person, a stop or the clock is an answer, not an error.
+
+Checked with real clients on October 11: Claude Code (`claude -p --mcp-config`) and Codex (`codex exec -c
+mcp_servers.harness…`) each listed the harnesses through it and were told "You are Claude Code, outside Harness." and
+"You are Codex, outside Harness."
+
Signed out, all of this works: the daemon runs as this computer, and `harness new` now asks for that identity as
`harness start` does (#1183). It used to read the sign-in file alone and refuse.