An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.
TypeScript agentic-browseragentic-browsingagy-cliaiai-agentai-browser-extensionai-toolsbrave-extensionbrowser-agentbrowser-automationbrowser-extensionbrowser-usebrowserskillchrome-extensionclaude-codecodexfirefox-addonmcp-servernanobrowserweb-automation
feat(agent): drive uploads and site mapping from the agent session
Shahriard3e9b5bf91f3
diff --git a/mcp/src/agent/runner.ts b/mcp/src/agent/runner.tsindex 3f9c8d4..19ffe9f 100644--- a/mcp/src/agent/runner.ts+++ b/mcp/src/agent/runner.ts@@ -6,14 +6,22 @@ import type { RunEvent } from '@/lib/actions/protocol';import { stateDir } from '../lockfile';import { log } from '../log';import type { AgentConfig } from './config';-import { buildSystemPrompt } from './prompt';-import type { Skill } from './skills';export interface RunRequest {runId: string;instruction: string;- skill: Skill;+ /** Already composed by the caller, which needs `dropped` and must not build it twice. */+ systemPrompt: string;config: AgentConfig;+ /**+ * Enable Claude Code's own `WebSearch`/`WebFetch` for this run. Only a mapping run sets it,+ * and only to satisfy "public info about this domain".+ *+ * Worth being plain about what this costs: these are not MCP tools, so they do not pass+ * through the daemon, the approval gate, or `invokeForRun`. Nothing can gate them; the+ * `tool_use` rows below exist so they are at least *visible* on the timeline.+ */+ research?: boolean;/** The Claude Code session this browser's conversation lives in. */sessionId: string;/** False on the first instruction, true once the session exists to be resumed. */@@ -87,11 +95,18 @@ export function runInstruction(request: RunRequest): Promise<RunOutcome> {JSON.stringify({ mcpServers: { voicelink: { command: process.execPath, args: [cliPath] } } }),'--strict-mcp-config',// Print mode auto-denies tools that would prompt; the server-level grant lets every- // voicelink tool run. The daemon applies its own approval gate on top.+ // voicelink tool run. The daemon applies its own approval gate on top. One flag, not two:+ // the option is variadic, so a second `--allowedTools` would replace this list rather than+ // extend it.'--allowedTools','mcp__voicelink',- // The job is in the browser. Filesystem, shell, web and subagent tools stay off, so a- // hostile page cannot talk the agent into reaching outside it.+ // The web tools are the one exception to the deny list below, and only for a mapping run,+ // which is asked to report what public sources say about a domain. That run therefore both+ // reads hostile page text and can make outbound requests — the exfiltration shape the deny+ // list otherwise prevents. A deliberate trade, switchable off with `siteMap.research: false`.+ ...(request.research ? ['WebSearch', 'WebFetch'] : []),+ // The job is in the browser. Filesystem, shell and subagent tools stay off, so a hostile+ // page cannot talk the agent into reaching outside it.'--disallowedTools','Bash','Edit',@@ -100,11 +115,10 @@ export function runInstruction(request: RunRequest): Promise<RunOutcome> {'Read','Glob','Grep',- 'WebFetch',- 'WebSearch',+ ...(request.research ? [] : ['WebFetch', 'WebSearch']),'Task','--append-system-prompt',- buildSystemPrompt(request.skill),+ request.systemPrompt,...(request.resume ? ['--resume', request.sessionId] : ['--session-id', request.sessionId]),...(config.model ? ['--model', config.model] : []),...(config.effort ? ['--effort', config.effort] : []),@@ -146,6 +160,15 @@ export function runInstruction(request: RunRequest): Promise<RunOutcome> {const event = message.event;if (event?.type === 'content_block_delta' && event.delta?.type === 'text_delta' && event.delta.text) {emit({ kind: 'text', delta: event.delta.text });+ return;+ }+ // Claude Code's own tools never reach the daemon — they are not MCP calls — so this+ // is the only place a web search can be reported at all. Not a gate; a record.+ if (event?.type === 'content_block_start' && event.content_block?.type === 'tool_use') {+ const name = event.content_block.name ?? 'tool';+ if (name === 'WebSearch' || name === 'WebFetch') {+ emit({ kind: 'tool', toolId: event.content_block.id ?? `web-${Date.now()}`, action: name, input: {} });+ }}return;}@@ -197,7 +220,11 @@ type StreamLine =| {type: 'stream_event';parent_tool_use_id?: string | null;- event?: { type?: string; delta?: { type?: string; text?: string } };+ event?: {+ type?: string;+ delta?: { type?: string; text?: string };+ content_block?: { type?: string; id?: string; name?: string };+ };}| { type: 'result'; is_error?: boolean; subtype?: string; stop_reason?: string | null; result?: string };diff --git a/mcp/src/agent/service.ts b/mcp/src/agent/service.tsindex 2deae1f..bf828a2 100644--- a/mcp/src/agent/service.ts+++ b/mcp/src/agent/service.ts@@ -1,14 +1,44 @@import { randomUUID } from 'node:crypto';-import { failure, type ActionResult, type ExtensionRequest, type RunEvent } from '@/lib/actions/protocol';+import {+ failure,+ success,+ type ActionResult,+ type ExtensionRequest,+ type RunContext,+ type RunEvent,+} from '@/lib/actions/protocol';+import { SAVE_SITE_MAP_ACTION, SITE_MAPPER_SKILL, validateSiteMapReport } from '@/lib/skills/site-map';import { log } from '../log';-import { readAgentConfig, type AgentConfig } from './config';+import { readAgentConfig, siteMapSettings, type AgentConfig } from './config';+import { gateMappingInvoke, noteMappingResult, type MapRun } from './mapping';+import { buildSystemPrompt } from './prompt';import { RunError, runInstruction } from './runner';-import { loadSkills, routeSkill, skillDirs } from './skills';+import {+ discardStaging,+ mapTargetFor,+ prepareStaging,+ stageSiteMap,+ stagedScreenshots,+ sweepStaging,+ writeEvidence,+} from './site-map-store';+import { fetchSiteIndex, type SiteIndex } from './sitemap';+import { loadSkills, routeSkill, skillDirNames, type Skill } from './skills';export interface AgentSessionDeps {- /** The daemon's own invoke path, so the agent reaches the browser exactly as MCP clients do. */- invoke: (action: string, input?: unknown) => Promise<ActionResult>;+ /**+ * The daemon's own invoke path, so the agent reaches the browser exactly as MCP clients do.+ * `opts.saveTo` is how a mapping run's screenshots are placed by the daemon rather than named+ * by the model; `opts.tabId` pins a long autonomous run to the tab it started in.+ */+ invoke: (+ action: string,+ input?: unknown,+ opts?: { saveTo?: { dir: string; filename: string }; tabId?: number },+ ) => Promise<ActionResult>;emit: (runId: string, event: RunEvent) => void;+ /** A staged site map awaiting review. Separate from run events: it outlives the run. */+ draft: (runId: string, draft: import('@/lib/skills/site-map').SiteMapDraft) => void;}interface ActiveRun {@@ -17,6 +47,8 @@ interface ActiveRun {abort: AbortController;/** Approvals the run is blocked on, keyed by tool-use id. */pending: Map<string, (allow: boolean) => void>;+ /** Present only while this run is mapping a site. */+ map?: MapRun;}/**@@ -35,7 +67,7 @@ export class AgentSession {handle(request: ExtensionRequest): void {switch (request.t) {case 'instruct':- void this.start(request.id, request.text);+ void this.start(request.id, request.text, request.context);return;case 'cancel':this.cancel(request.id);@@ -65,6 +97,32 @@ export class AgentSession {const toolId = randomUUID();emit({ kind: 'tool', toolId, action, input });+ // The reserved write action exists only for a mapping run. An ordinary run reaching it means+ // something is wrong with the tool list, not that it should be honoured.+ if (action === SAVE_SITE_MAP_ACTION) {+ if (!run.map) {+ emit({ kind: 'toolResult', toolId, ok: false, summary: 'not a mapping run' });+ return failure('UNKNOWN_ACTION', `Unknown action "${action}".`);+ }+ const result = this.submitSiteMap(run, input);+ emit({ kind: 'toolResult', toolId, ok: result.ok, summary: summarize(input, result) });+ return result;+ }++ if (run.map) {+ const gate = gateMappingInvoke(run.map, action, input);+ if (!gate.allow) {+ log(`mapping run ${runId} refused ${action}: ${gate.result.ok ? '' : gate.result.error.code}`);+ emit({ kind: 'toolResult', toolId, ok: false, summary: summarize(input, gate.result) });+ return gate.result;+ }+ const result = await this.deps.invoke(action, input, { saveTo: gate.saveTo, tabId: run.map.tabId });+ noteMappingResult(run.map, action, result);+ log(`agent → ${action} ${result.ok ? 'ok' : result.error.code}`);+ emit({ kind: 'toolResult', toolId, ok: result.ok, summary: summarize(input, result) });+ return result;+ }+if (run.config.requireApproval.includes(action)) {emit({ kind: 'approval', toolId, action, input });if (!(await this.awaitDecision(run, toolId))) {@@ -88,7 +146,7 @@ export class AgentSession {this.claudeSession = null;}- private async start(runId: string, instruction: string): Promise<void> {+ private async start(runId: string, instruction: string, context?: RunContext): Promise<void> {const emit = (event: RunEvent) => this.deps.emit(runId, event);const text = instruction.trim();@@ -101,28 +159,69 @@ export class AgentSession {});}- const routed = routeSkill(loadSkills(), text);+ const routed = routeSkill(loadSkills(), text, context);if (!routed) {return emit({kind: 'error',code: 'NO_SKILL',- message: `No skills found. Looked in ${skillDirs.join(' and ')} — reinstall the package, or add a skill of your own.`,+ message: `No skills found. Looked in ${skillDirNames().join(' and ')} — reinstall the package, or add a skill of your own.`,+ });+ }++ const config = readAgentConfig();+ // Mapping mode turns on the run's *identity*, never on front matter: `~/.voicelink/skills`+ // is parsed with no key allowlist, so a skill that could name its own privileges would be+ // granting them to itself. A hand-authored shadow of this name is `source: 'user'` and gets+ // an ordinary, fully locked-down run.+ const mapping = routed.base.name === SITE_MAPPER_SKILL && routed.base.source === 'bundled';+ if (mapping && !explicitlyAsked(text)) {+ return emit({+ kind: 'error',+ code: 'MAPPING_NOT_REQUESTED',+ message:+ 'Mapping a site takes several minutes and drives this tab. Ask for it explicitly with the Map this site button, or by starting your message with @site-mapper.',});}- const run: ActiveRun = { id: runId, config: readAgentConfig(), abort: new AbortController(), pending: new Map() };+ const overlayNames = routed.overlays.map((overlay) => overlay.name);+ const run: ActiveRun = { id: runId, config, abort: new AbortController(), pending: new Map() };this.active = run;- log(`agent run ${runId} started with skill "${routed.skill.name}"`);- emit({ kind: 'started', skill: routed.skill.name });- const resume = this.claudeSession !== null;- const sessionId = this.claudeSession ?? randomUUID();+ let built: { prompt: string; dropped: string[] };+ let instructionText = routed.text;+ try {+ if (mapping) {+ const prepared = await this.prepareMapping(run, routed.base, context, emit);+ if (!prepared) return;+ built = prepared.built;+ instructionText = prepared.instruction;+ } else {+ built = buildSystemPrompt(routed.base, routed.overlays);+ }+ } catch (error) {+ this.active = null;+ return emit({ kind: 'error', code: 'AGENT_FAILED', message: String(error) });+ }++ log(+ `agent run ${runId} started with skill "${routed.base.name}"` ++ (overlayNames.length ? ` + site notes [${overlayNames.join(', ')}]` : '') ++ (run.map ? ` mapping ${run.map.target.host}` : ''),+ );+ emit({ kind: 'started', skill: routed.base.name, overlays: [...overlayNames, ...built.dropped.map((n) => `${n} (too large — not applied)`)] });++ // A mapping run is a side quest, not part of the conversation: resuming it later would put+ // the whole crawl transcript behind the user's next message.+ const resume = !mapping && this.claudeSession !== null;+ const sessionId = mapping ? randomUUID() : (this.claudeSession ?? randomUUID());+ const budget = run.map ? setTimeout(() => run.abort.abort(), run.map.settings.timeoutMs) : undefined;try {const outcome = await runInstruction({runId,- instruction: routed.text,- skill: routed.skill,+ instruction: instructionText,+ systemPrompt: built.prompt,+ research: run.map ? run.map.settings.research : false,config: run.config,sessionId,resume,@@ -138,11 +237,117 @@ export class AgentSession {log(`agent run ${runId} failed: ${code}: ${message}`);emit({ kind: 'error', code, message });} finally {+ clearTimeout(budget);+ // A mapping run that never submitted leaves nothing behind: an empty quarantine directory+ // would otherwise sit there until the next sweep looking like a map that failed to appear.+ if (run.map && !run.map.submitted) discardStaging(run.map.staging.id);// Only clear if this run is still the current one; a cancel may already have moved on.if (this.active === run) this.active = null;}}+ /**+ * Everything a mapping run needs before Claude Code starts: a target it is allowed to map, a+ * quarantine directory to write into, and the two phases that do not need a browser.+ *+ * Phase A (the sitemap) is plain Node, and Phase B (public background) is the run's own web+ * tools. Both feed the prompt as *fetched data* rather than as the user speaking — see+ * `buildSystemPrompt`'s third argument.+ */+ private async prepareMapping(+ run: ActiveRun,+ skill: Skill,+ context: RunContext | undefined,+ emit: (event: RunEvent) => void,+ ): Promise<{ built: { prompt: string; dropped: string[] }; instruction: string } | null> {+ if (!context?.url) {+ this.active = null;+ emit({ kind: 'error', code: 'INVALID_INPUT', message: 'Open the site you want mapped in this tab first.' });+ return null;+ }+ const target = mapTargetFor(context.url);+ if (!target.ok) {+ this.active = null;+ emit({ kind: 'error', code: 'MAPPING_REFUSED', message: target.message });+ return null;+ }++ sweepStaging();+ const settings = siteMapSettings(run.config);+ const staging = prepareStaging();++ const toolId = randomUUID();+ emit({ kind: 'tool', toolId, action: 'voicelink.readSitemap', input: { origin: target.target.origin } });+ let index: SiteIndex;+ try {+ index = await fetchSiteIndex(target.target.origin, run.abort.signal);+ } catch (error) {+ // A sitemap is a nice-to-have; a site without one still gets mapped by walking it.+ log('sitemap phase failed', error);+ index = { source: 'none', documents: 0, urlCount: 0, truncated: false, paths: [], patterns: [], raw: '' };+ }+ emit({+ kind: 'toolResult',+ toolId,+ ok: true,+ summary: index.urlCount ? `${index.urlCount} URLs from ${index.source}` : 'no sitemap published',+ });+ writeEvidence(staging, 'sitemap.txt', index.raw);++ run.map = {+ target: target.target,+ staging,+ index,+ settings,+ tabId: context.tabId,+ shots: 0,+ pagesVisited: new Set(),+ offSite: null,+ submitted: false,+ };++ const built = buildSystemPrompt(skill, [], fetchedBlock(target.target.origin, index));+ return { built, instruction: mappingBrief(target.target.host, settings) };+ }++ /**+ * The agent's one persistence channel. The report is typed, every leaf is scrubbed and capped,+ * and the daemon renders the document itself — the model fills slots, it never writes a file.+ */+ private submitSiteMap(run: ActiveRun, input: unknown): ActionResult {+ const map = run.map!;+ if (map.submitted) return failure('ALREADY_SUBMITTED', 'This run has already written its map.');++ const raw = (input as { report?: unknown } | undefined)?.report;+ if (JSON.stringify(raw ?? null).length > 256 * 1024) {+ return failure('MAPPING_REPORT_TOO_LARGE', 'That report is far too large. Summarize each page in a sentence.');+ }+ const checked = validateSiteMapReport(raw, {+ origin: map.target.origin,+ screenshots: stagedScreenshots(map.staging),+ });+ if (!checked.ok) return failure('INVALID_INPUT', checked.message);++ const draft = stageSiteMap({+ staging: map.staging,+ target: map.target,+ report: checked.report,+ index: map.index,+ background: null,+ warnings: checked.warnings,+ runId: run.id,+ });+ map.submitted = true;+ this.deps.draft(run.id, draft);+ log(`mapping run ${run.id} staged ${draft.name} (${draft.pages} pages, ${draft.screenshots} shots)`);+ return success({+ staged: true,+ name: draft.name,+ pages: draft.pages,+ message: 'The map is written and waiting for the user to review it. Tell them what you found, briefly.',+ });+ }+private cancel(runId: string): void {if (!this.active || this.active.id !== runId) return;// Release anything blocked on approval first — an aborted run would otherwise leave a@@ -166,6 +371,42 @@ export class AgentSession {}}+/**+ * Mapping must be asked for, never inferred. Trigger scoring is `haystack.includes(...)`, and the+ * side panel listens continuously and auto-sends after a pause — so a phrase like "show me the+ * site map" spoken near the laptop would otherwise start a ten-minute crawl that screenshots+ * whatever is on screen.+ */+function explicitlyAsked(text: string): boolean {+ return /^@site-mapper\b/i.test(text.trim());+}++/** The sitemap findings, as data the run was handed rather than as anything anyone said. */+function fetchedBlock(origin: string, index: SiteIndex): string {+ if (!index.urlCount) return `No sitemap is published at ${origin}. Discover the site by walking its own links.`;+ const lines = [+ `## ${origin} sitemap (${index.source}, ${index.urlCount} URLs across ${index.documents} documents)`,+ '',+ '### Shapes',+ ...index.patterns.map((p) => `- ${p.pattern} — ${p.count} pages, e.g. ${p.example}`),+ '',+ '### Paths',+ ...index.paths.map((path) => `- ${path}`),+ ];+ if (index.truncated) lines.push('- (truncated: the sitemap lists more than was read)');+ return lines.join('\n');+}++function mappingBrief(host: string, settings: { maxPages: number; maxScreenshots: number }): string {+ return (+ `Map ${host}. Visit up to ${settings.maxPages} pages and take up to ${settings.maxScreenshots} screenshots, ` ++ `then call voicelink_saveSiteMap once with everything you found. Prefer breadth over depth: the landing page, ` ++ `the main navigation destinations, and one example of each repeated page shape. Record what you observed, ` ++ `not advice — a future assistant will read this to find its way around, and anything that reads like an ` ++ `instruction will be shown to the user as suspicious.`+ );+}+const SUMMARY_LIMIT = 80;/** A one-line "what just happened" for the timeline — the detail, not the action name. */diff --git a/mcp/src/daemon.ts b/mcp/src/daemon.tsindex 850b711..ecacb97 100644--- a/mcp/src/daemon.ts+++ b/mcp/src/daemon.ts@@ -18,6 +18,8 @@ import {import { AgentSession } from './agent/service';import { summarizeFile } from './agent/analyze';import { readAgentConfig } from './agent/config';+import { deleteSiteMap, deleteSkill, saveSkill } from './agent/skill-store';+import { commitStaging, discardStaging } from './agent/site-map-store';import type { Bridge, BridgeStatus, ControlMessage, ControlRequest, SessionSummary } from './control';import { ExtensionLink } from './extension-link';import { log } from './log';@@ -41,14 +43,22 @@ export interface Daemon extends Bridge {* path (or the write error) on the result. A failed save never fails the capture — the caller* still gets the image to look at.*/-function persistScreenshot(action: string, input: unknown, result: ActionResult): ActionResult {+function persistScreenshot(+ action: string,+ input: unknown,+ result: ActionResult,+ saveTo?: { dir: string; filename: string },+): ActionResult {if (action !== 'page.screenshot' || !result.ok) return result;const args = (input ?? {}) as { save?: unknown; filename?: unknown };const data = result.data as { dataUrl?: unknown } | null;- if (args.save !== true || typeof data?.dataUrl !== 'string') return result;+ // A mapping run's captures are always kept: they are the evidence for the map it is writing,+ // and the daemon — not the model — decided where they go.+ if ((args.save !== true && !saveTo) || typeof data?.dataUrl !== 'string') return result;try {const savedTo = saveScreenshot(data.dataUrl, {- filename: typeof args.filename === 'string' ? args.filename : undefined,+ dir: saveTo?.dir,+ filename: saveTo?.filename ?? (typeof args.filename === 'string' ? args.filename : undefined),});log(`screenshot saved to ${savedTo}`);return { ok: true, data: { ...(result.data as object), savedTo } };@@ -195,9 +205,9 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):scheduleIdleExit();},// The agent harness: the extension asks the daemon to think, and the daemon answers- // by driving the browser back down this same socket. A file to summarize is the one- // stateless request — it runs outside the conversation and replies with `fileSummary`,- // so it is handled here rather than in the run-gated AgentSession.+ // by driving the browser back down this same socket. Summarizing a file and saving a+ // skill are the stateless requests — they run outside the conversation and reply on+ // their own frames, so they are handled here rather than in the run-gated AgentSession.(request, source) => {if (request.t === 'analyzeFile') {void summarizeFile(request, readAgentConfig())@@ -207,6 +217,28 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):);return;}+ if (request.t === 'saveSkill') {+ return source.send({ t: 'skillResult', id: request.id, result: saveSkill(request.skill) });+ }+ if (request.t === 'deleteSkill') {+ return source.send({ t: 'skillResult', id: request.id, result: deleteSkill(request.name) });+ }+ if (request.t === 'deleteSiteMap') {+ return source.send({ t: 'skillResult', id: request.id, result: deleteSiteMap(request.name) });+ }+ // Reviewing a staged map outlives the run that produced it — the panel may be reopened+ // long after — so it is handled here rather than against the active AgentSession.+ if (request.t === 'activateSiteMap') {+ const result = commitStaging(request.stagingId, request.exactHost === true);+ return source.send({+ t: 'skillResult',+ id: request.id,+ result: result.ok ? { ok: true, data: { name: result.data.name, path: result.data.path } } : result,+ });+ }+ if (request.t === 'discardSiteMap') {+ return source.send({ t: 'skillResult', id: request.id, result: discardStaging(request.stagingId) });+ }session(source).handle(request);},);@@ -232,6 +264,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):return (agent ??= new AgentSession({invoke,emit: (id, event) => source.send({ t: 'run', id, event }),+ draft: (id, draft) => source.send({ t: 'siteMapDraft', id, draft }),}));}@@ -325,7 +358,17 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):};}- async function invoke(action: string, input?: unknown) {+ async function invoke(+ action: string,+ input?: unknown,+ opts?: { saveTo?: { dir: string; filename: string }; tabId?: number },+ ) {+ // The `voicelink.` namespace is not browser capability — it is the mapping run's write+ // channel, intercepted in AgentSession before it ever gets here. Anything reaching this+ // point with that prefix came from an untagged caller, i.e. some other MCP client.+ if (action.startsWith('voicelink.')) {+ return failure('UNKNOWN_ACTION', `Unknown action "${action}".`);+ }if (!link?.isOpen) {return failure('EXTENSION_OFFLINE',@@ -334,7 +377,7 @@ export async function startDaemon({ version, idleExit = true }: DaemonOptions):}// Every caller — direct MCP clients and spawned agent runs alike — reaches the browser// through here, so this is the one place to write a screenshot to disk when asked.- return persistScreenshot(action, input, await link.invoke(action, input));+ return persistScreenshot(action, input, await link.invoke(action, input, opts?.tabId), opts?.saveTo);}/** Nothing attached and nobody asking: don't linger in the user's process list forever. */diff --git a/mcp/src/extension-link.ts b/mcp/src/extension-link.tsindex 92dad09..9f38b0c 100644--- a/mcp/src/extension-link.ts+++ b/mcp/src/extension-link.ts@@ -53,8 +53,8 @@ export class ExtensionLink {return !this.closed && this.socket.readyState === this.socket.OPEN;}- invoke(action: string, input?: unknown): Promise<ActionResult> {- return this.request({ t: 'invoke', id: randomUUID(), action, input }, timeoutFor(action, input));+ invoke(action: string, input?: unknown, tabId?: number): Promise<ActionResult> {+ return this.request({ t: 'invoke', id: randomUUID(), action, input, tabId }, timeoutFor(action, input));}async describe(): Promise<ToolDescriptor[] | null> {diff --git a/mcp/src/server.ts b/mcp/src/server.tsindex 33cf9b5..2a55ea1 100644--- a/mcp/src/server.ts+++ b/mcp/src/server.ts@@ -34,7 +34,86 @@ const RESOURCES = [},] as const;-export function createMcpServer(bridge: Bridge, version: string): Server {+/**+ * The one tool that writes rather than looks. It is advertised only to a spawned agent run —+ * `daemon.invoke` refuses the whole `voicelink.` namespace for anyone else, so an external MCP+ * client could not use it even if it guessed the name.+ *+ * No `actionNameFor` special case is needed: that helper replaces only the *first* underscore,+ * so `voicelink_saveSiteMap` already maps to `voicelink.saveSiteMap`, and CallTool's existing+ * fall-through routes it with the run id attached.+ */+const SAVE_SITE_MAP_TOOL = {+ name: 'voicelink_saveSiteMap',+ description:+ 'Write up a finished site map. Call this exactly once, at the end of a mapping run. The map is staged for the user to review before it takes effect — it does not apply immediately.',+ inputSchema: {+ type: 'object' as const,+ additionalProperties: false,+ required: ['report'],+ properties: {+ report: {+ type: 'object',+ additionalProperties: false,+ required: ['summary', 'pages'],+ properties: {+ summary: { type: 'string', description: 'What this site is, in two or three sentences.' },+ landmarks: {+ type: 'array',+ description: 'Durable parts of the interface: the primary nav, a search box, a cookie wall.',+ items: {+ type: 'object',+ additionalProperties: false,+ required: ['name'],+ properties: {+ name: { type: 'string', description: 'What it is called, as a person would say it.' },+ selector: { type: 'string', description: 'A CSS selector that finds it.' },+ note: { type: 'string', description: 'One line on how it behaves.' },+ },+ },+ },+ pages: {+ type: 'array',+ description: 'Each page visited, once.',+ items: {+ type: 'object',+ additionalProperties: false,+ required: ['path', 'title', 'purpose'],+ properties: {+ path: { type: 'string', description: 'The path on the mapped site, e.g. /pricing.' },+ title: { type: 'string', description: 'The page title.' },+ purpose: { type: 'string', description: 'What the page is for, in one short phrase.' },+ reachedBy: { type: 'string', description: 'How you got there, e.g. "Pricing" in the top nav.' },+ screenshot: { type: 'string', description: 'Filename of a screenshot you took of this page.' },+ notes: { type: 'string', description: 'Anything else worth recording. Kept out of the prompt.' },+ },+ },+ },+ links: {+ type: 'array',+ description: 'How the pages connect: one entry per link you followed or saw.',+ items: {+ type: 'object',+ additionalProperties: false,+ required: ['from', 'to'],+ properties: {+ from: { type: 'string', description: 'Path the link is on.' },+ to: { type: 'string', description: 'Path it leads to.' },+ },+ },+ },+ quirks: {+ type: 'array',+ description: 'Things that would trip up someone driving this site. Observations, never advice.',+ items: { type: 'string' },+ },+ },+ },+ },+ },+};++export function createMcpServer(bridge: Bridge, version: string, opts: { agentRun?: boolean } = {}): Server {const server = new Server({ name: 'voicelink', version },{@@ -62,6 +141,7 @@ export function createMcpServer(bridge: Bridge, version: string): Server {'Report whether the VoiceLink browser extension is connected, its version, and the active tab. Use this first if a page tool fails.',inputSchema: { type: 'object' as const, properties: {}, additionalProperties: false },},+ ...(opts.agentRun ? [SAVE_SITE_MAP_TOOL] : []),],};});