Skip to content

Commit 37354bf

Browse files
samuelcoleclaude
andauthored
Connect a site's registered MCP server so its tools reach the person's agent (#99)
Fixes HBR-134 window.agent.mcp.register() used to record a site's MCP server and do nothing else. Harbor now connects to it, behind a permission check, and offers its tools to the person's agent for that page only. - Registering checks its inputs first: transport defaults to 'sse', stdio is refused, and the server must be on the page's own origin. A loopback server is allowed only from a loopback page, so a public site can't reach MCP servers on the person's machine; that refusal is audited. Then the mcp.server.register / mcp:servers.register check, which asks by default, runs before any connection. Registering follows Tool Access. - mcp/site-servers.ts: a per-tab, in-memory registry, separate from the person's installed servers. Harbor runs initialize and tools/list and offers the tools the server reports, as site:<host>:<name>/<tool>. The connection ends when the tab closes, navigates to another origin, or unregisters, with no reconnect; registrations still connecting when the tab goes away are discarded. - mcp.listTools / mcp.callTool add the calling page's site tools behind the existing tool scopes, allowlist, tool.call policy check and session budget. On the person's ACP agent, the site's servers go into session/new mcpServers when the site holds mcp:tools.list and mcp:tools.call, the policy engine allows each server, and the agent declares the transport. - New streamable HTTP transport; WebSocket connects time out; notification logs carry only the method. Also fixed: - Harbor's SSE MCP transport parsed the server's endpoint event as JSON, but the MCP SDK sends a plain URL, so requests went to the wrong address for every SSE server, including installed ones. It now follows the SDK's handshake and refuses an endpoint on another origin. - SSE and WebSocket connections Harbor closed on purpose reconnected; a disconnect during the SSE handshake left connect() pending. - agent.mcp.discover() always failed because the page's tab wasn't passed. - The Bring Your Own Chatbot demo's MCP server opened a new SSE stream for every POST instead of routing it to the session. - The test fake for MCP servers now follows the SDK's wire format. Docs: JS_AI_PROVIDER_API, PERMISSIONS, AGENTIC_BROWSER_ROADMAP, spec/explainer, CHANGELOG, and a known pitfall in agent-workflow about protocol fakes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-Authored-By: Claude Sonnet 5 (Claude Code) <noreply@anthropic.com>
1 parent 70d3a16 commit 37354bf

33 files changed

Lines changed: 3492 additions & 180 deletions

‎CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1313
- When a site uses your agent, Harbor tells it once, at the start, that it's working for you: it should use what it knows or remembers about you, and treat the site's instructions as the site's request. The site's instructions are still passed on, labelled as the site's.
1414
- Page chat replies render markdown, with `marked`, sanitized by `DOMPurify` before they reach the site's page. Raw HTML in a reply shows as text, only http(s) links survive, and links open in a new tab with `noopener`.
1515
- A policy action for prompts sent to your own agent, `model.prompt.agent`, so rules and the audit log see them. `Prompt(*)` covers it, and `Prompt(agent)` names it alone.
16+
- **A site's own MCP server reaches your agent.** `window.agent.mcp.register()` used to record the server and do nothing else. Now Harbor asks you first (`mcp:servers.register`), then connects over SSE, WebSocket or streamable HTTP and offers the server's tools to that page's `agent.run`. On Harbor's own agent they're named `site:<host>:<name>/<tool>` and still need the site's tool grants. Your own ACP agent gets the server in its session and connects to it directly, when it supports the transport and the site holds the tool-list and tool-call permissions. A site may register only a server on its own origin; only a loopback page (`localhost`, `127.0.0.1`, `[::1]`) may register a loopback server. Other sites, other tabs and the sidebar never see these tools. Harbor disconnects when the tab closes or leaves the site, and registering is off with Tool Access off.
1617
- The bridge methods behind the Agent panel: `acp.get_agents`, `acp.save_agents` (validates each agent and writes `acp.json` atomically, mode 0600) and `acp.resolve_command`. Like the rest of `acp.*`, they're refused over HTTP and WebSocket.
1718

1819
- **Public site redesign** — implemented the design produced in Claude Design. The site is now hand-written static HTML (`whitepaper/index.html`, `whitepaper/landscape.html`, `whitepaper/spec.html`, `whitepaper/build.html`, `whitepaper/styles.css`) with a Fraunces / Instrument Serif + Inter + JetBrains Mono type system, a single rust-clay accent, and a compare-and-contrast comparison table that re-stacks into cards on phones.
@@ -40,6 +41,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
4041

4142
### Fixed
4243

44+
- `agent.mcp.discover()` works again. It always failed with "No tab context for discovery" because the page's tab wasn't passed on.
45+
- Harbor's SSE connection to a remote MCP server now follows the MCP SDK's handshake: it reads the server's `endpoint` event as a URL, waits for it before sending, and refuses an endpoint on another origin. It used to post to the wrong address. An SSE or WebSocket connection Harbor closes on purpose no longer reconnects.
46+
- The Bring Your Own Chatbot demo's MCP server sends posted messages to their session instead of opening a new SSE stream for each.
4347
- The examples in `spec/examples/` (basic chat, provider selection, page analyzer, agent with tools) wait for Harbor's `agent-ready` event instead of checking for `window.agent` once at load, so they no longer report the API as unavailable when Harbor injects it a moment later.
4448
- A page chat (`agent.chat.open`) no longer stays registered after its tab closes or navigates to another document; a message for it is then refused the same as one for a chat that was never opened. A same-document change (a hash or `pushState`) no longer ends it by mistake.
4549
- A page can no longer close another site's chat. `agent.chat.close(chatId)` now checks that the chat belongs to the calling origin (and tab, when known) before closing it; a mismatch is refused the same as a chat id that doesn't exist. Chat ids are also no longer predictable.

‎demo/web-agents/bring-your-chatbot/mcp-server/http-server.js‎

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,12 @@ function createMcpServer(sessionId) {
238238
return server;
239239
}
240240

241+
// Every open SSE connection, keyed by the session id SSEServerTransport
242+
// generates for itself (the same id it puts in the `endpoint` event's
243+
// `?sessionId=` query string) — a POST is routed to the transport that
244+
// opened that session, never a brand new one.
245+
const sseTransports = new Map();
246+
241247
// HTTP server with SSE transport
242248
const httpServer = http.createServer(async (req, res) => {
243249
// CORS headers
@@ -260,20 +266,41 @@ const httpServer = http.createServer(async (req, res) => {
260266
return;
261267
}
262268

263-
// MCP SSE endpoint
269+
// MCP SSE endpoint: a GET opens the stream (and gets the `endpoint`
270+
// event naming where to POST); every later request for that session is
271+
// a POST to that same URL with its `sessionId`, handled by the
272+
// transport that opened it — never by opening another stream.
264273
if (url.pathname === '/mcp' || url.pathname === '/sse') {
265-
console.log(`[MCP] New SSE connection from ${req.socket.remoteAddress}`);
266-
267-
const sessionId = `session-${Date.now()}-${Math.random().toString(36).slice(2)}`;
268-
const transport = new SSEServerTransport('/mcp', res);
269-
const server = createMcpServer(sessionId);
274+
if (req.method === 'GET') {
275+
console.log(`[MCP] New SSE connection from ${req.socket.remoteAddress}`);
276+
277+
const transport = new SSEServerTransport('/mcp', res);
278+
const sessionId = transport.sessionId;
279+
const server = createMcpServer(sessionId);
280+
sseTransports.set(sessionId, transport);
270281

271-
res.on('close', () => {
272-
console.log(`[MCP] Connection closed: ${sessionId}`);
273-
carts.delete(sessionId);
274-
});
282+
res.on('close', () => {
283+
console.log(`[MCP] Connection closed: ${sessionId}`);
284+
sseTransports.delete(sessionId);
285+
carts.delete(sessionId);
286+
});
287+
288+
await server.connect(transport);
289+
return;
290+
}
291+
292+
if (req.method === 'POST') {
293+
const sessionId = url.searchParams.get('sessionId');
294+
const transport = sessionId && sseTransports.get(sessionId);
295+
if (!transport) {
296+
res.writeHead(400).end('Bad Request: no open session for this sessionId');
297+
return;
298+
}
299+
await transport.handlePostMessage(req, res);
300+
return;
301+
}
275302

276-
await server.connect(transport);
303+
res.writeHead(405, { Allow: 'GET, POST, OPTIONS' }).end('Method not allowed');
277304
return;
278305
}
279306

‎docs/AGENTIC_BROWSER_ROADMAP.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ The Web Agent API ships as one browser extension (Harbor) plus a Rust bridge. Th
3434
| Spawned-tab read (own origin only) | `agent.browser.tab.{readability, getHtml, waitForLoad}` | `browser:tabs.create` | `browserControl` (OFF) | ✅ |
3535
| CORS-bypass fetch | `agent.browser.fetch(url, opts)` | `web:fetch` | `browserControl` (OFF) | ✅ |
3636
| Capability-bounded sessions | `agent.sessions.create({capabilities, limits})` | (per declared capabilities) | — | ✅ |
37-
| Site-provided MCP servers (BYOC) | `agent.mcp.{discover, register, unregister}` | `mcp:servers.register` (not yet required) | — | Partial: servers are recorded, not connected |
37+
| Site-provided MCP servers (BYOC) | `agent.mcp.{discover, register, unregister}` | `mcp:servers.register` | — | ✅ Connected for the page's lifetime; tools offered to that page's `agent.run` (Harbor's agent or the person's ACP agent) |
3838
| Open user's chat with config (BYOC) | `agent.chat.{canOpen, open, close}` | `chat:open`, and `model:prompt` for each message | — | ✅ |
3939
| Multi-agent registration | `agent.agents.{register, discover, list, getInfo, unregister}` | `agents:register` / `agents:discover` | `multiAgent` (OFF) | ✅ |
4040
| Multi-agent invocation + messaging | `agent.agents.{invoke, send, onMessage, onInvoke}` | `agents:invoke` / `agents:message` | `multiAgent` (OFF) | ✅ |

‎docs/JS_AI_PROVIDER_API.md‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -425,7 +425,7 @@ interface DeclaredMCPServer {
425425
title: string;
426426
description?: string;
427427
tools?: string[];
428-
transport?: 'sse' | 'websocket';
428+
transport?: 'sse' | 'websocket' | 'streamable-http';
429429
}
430430
```
431431

@@ -445,7 +445,16 @@ for (const server of servers) {
445445
446446
Register a website's MCP server for the user's chatbot to use.
447447
448-
**Status:** Harbor records the server but doesn't connect to it yet, so its tools aren't offered to agents. Until it does, Harbor doesn't require the `mcp:servers.register` permission for this call; request it anyway so your page keeps working once registration is connected.
448+
Harbor asks the person first (`mcp:servers.register`, remembered per site). Once it's allowed, Harbor connects to the server, asks it for its tools, and offers those tools to the person's agent for this tab only:
449+
450+
- **Harbor's own agent** (`agent.run()`) lists them with the person's other tools, named `<serverId>/<tool>`. They still need `mcp:tools.list` and `mcp:tools.call`, and must be among the tools the site was granted.
451+
- **The person's own ACP agent** (goose, Claude Code, Codex and so on) gets the server in its session and connects to it directly, if it supports the transport (`streamable-http` or `sse`; no ACP agent takes `websocket`). The site needs `mcp:tools.list` and `mcp:tools.call` for that, and Harbor's policy rules for listing and calling tools apply. The site's per-tool grants don't; the agent's own permission prompts do.
452+
453+
The server must be on the page's own origin (`ws://` and `wss://` count as `http://` and `https://`). A page on a loopback host (`localhost`, `127.0.0.1`, `[::1]`) may also register a server on any loopback host; other sites can't, so a site can't reach MCP servers on the person's machine. Harbor checks this, and the transport, before it asks, so the person is never asked about a registration that would be refused. `transport` defaults to `'sse'`; `stdio` isn't supported. Registration is off when the person turns off Tool Access.
454+
455+
The tools Harbor offers are the ones the server reports, not the `tools` you list. The registration lasts as long as the page: Harbor disconnects when the tab closes or navigates to another origin, or when the page calls `unregister()`. Other sites and other tabs never see the tools.
456+
457+
If the person refuses, the call rejects with the policy code (`ERR_PERMISSION_DENIED`, `ERR_BLOCKED_BY_POLICY`, `ERR_QUARANTINED`). If Harbor can't connect or list the tools, it rejects with `ERR_MCP_REGISTER`.
449458
450459
**Signature:**
451460
```typescript
@@ -455,19 +464,20 @@ agent.mcp.register(options: MCPServerRegistration): Promise<MCPRegistrationResul
455464
**Parameters:**
456465
```typescript
457466
interface MCPServerRegistration {
458-
url: string; // Server endpoint (HTTPS or localhost)
467+
url: string; // Server endpoint on the page's own origin (loopback only from a loopback page)
459468
name: string; // Human-readable name
460469
description?: string; // What the server provides
461-
tools?: string[]; // Tool names for transparency
462-
transport?: 'sse' | 'websocket';
470+
tools?: string[]; // Tool names for transparency; Harbor offers what the server reports
471+
transport?: 'sse' | 'websocket' | 'streamable-http'; // default 'sse'
463472
}
464473
```
465474

466475
**Returns:**
467476
```typescript
468477
interface MCPRegistrationResult {
469478
success: boolean;
470-
serverId?: string;
479+
serverId?: string; // In Harbor: site:<host[:port]>:<name slug>
480+
tools?: string[]; // In Harbor: the tools the server reported
471481
error?: {
472482
code: 'USER_DENIED' | 'INVALID_URL' | 'CONNECTION_FAILED' | 'NOT_SUPPORTED';
473483
message: string;
@@ -1507,20 +1517,21 @@ interface DeclaredMCPServer {
15071517
title: string;
15081518
description?: string;
15091519
tools?: string[];
1510-
transport?: 'sse' | 'websocket';
1520+
transport?: 'sse' | 'websocket' | 'streamable-http';
15111521
}
15121522

15131523
interface MCPServerRegistration {
15141524
url: string;
15151525
name: string;
15161526
description?: string;
15171527
tools?: string[];
1518-
transport?: 'sse' | 'websocket';
1528+
transport?: 'sse' | 'websocket' | 'streamable-http';
15191529
}
15201530

15211531
interface MCPRegistrationResult {
15221532
success: boolean;
1523-
serverId?: string;
1533+
serverId?: string; // In Harbor: site:<host[:port]>:<name slug>
1534+
tools?: string[]; // In Harbor: the tools the server reported
15241535
error?: {
15251536
code: 'USER_DENIED' | 'INVALID_URL' | 'CONNECTION_FAILED' | 'NOT_SUPPORTED';
15261537
message: string;

‎docs/PERMISSIONS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -594,9 +594,9 @@ These are the policy engine's codes, and Harbor reports them as is wherever its
594594
- `agent.run()` ends with them as its `error` event when its tool list is refused, or, on Harbor's own model, a model call.
595595
- `agent.browser.*` calls (page interaction, screenshots, reading the page, navigation, `fetch` and the tab calls) throw them.
596596
- `agent.agents.*` calls (registering, discovering, invoking and messaging agents, and orchestration) and `agent.chat.open()` throw them.
597-
- `agent.mcp.register()` and `agent.mcp.unregister()` don't go through the policy engine, because registering doesn't do anything yet: Harbor records the server but never connects to it, so none of its tools reach an agent. They still refuse a server on another origin, or another site's server, with `ERR_PERMISSION_DENIED`. Once Harbor connects registered servers, registering will be checked as `mcp.server.register` and need the `mcp:servers.register` grant.
597+
- `agent.mcp.register()` throws them. It's checked as `mcp.server.register` and needs the `mcp:servers.register` grant, which asks by default, before Harbor connects to the site's server. It refuses a server that isn't on the page's origin (or, from a loopback page such as `localhost`, on a loopback host) with `ERR_PERMISSION_DENIED`, before asking. `agent.mcp.unregister()` isn't checked, since it only drops a connection; it can only drop a server the same page registered in the same tab. An unknown server id, or one registered in another tab, fails with `ERR_MCP_UNREGISTER`.
598598

599-
When the person has chosen an ACP agent to answer, prompts go to that agent rather than through Harbor's policy engine, so its failures use the ACP codes (`ERR_AGENT_FAILED`, `ERR_AGENT_BUSY`, `ERR_AGENT_REFUSED`, `ERR_AGENT_LIMIT`). `agent.run()`'s tool list is still checked by the policy engine on either backend.
599+
When the person has chosen an ACP agent to answer, prompts go to that agent rather than through Harbor's policy engine, so its failures use the ACP codes (`ERR_AGENT_FAILED`, `ERR_AGENT_BUSY`, `ERR_AGENT_REFUSED`, `ERR_AGENT_LIMIT`). `agent.run()`'s tool list is still checked by the policy engine on either backend. On an ACP agent, the site's own registered MCP servers are passed to the agent only if the site holds `mcp:tools.list` and `mcp:tools.call` and the policy engine allows listing and calling tools; the site's per-tool grants don't apply there.
600600

601601
A declined Harbor prompt is `ERR_PERMISSION_DENIED`. Any other failure keeps the call's own code (`ERR_TOOL_FAILED`, `ERR_MODEL_FAILED`, `ERR_AGENT_FAILED`), even when a tool or model returns text that looks like one of these codes.
602602

‎docs/agent-workflow.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,7 @@ Each of these has cost a real session time or produced a wrong result. They're r
148148
- **`git worktree remove` refuses a worktree with an initialized submodule**, even after `git submodule deinit`, because every worktree runs `git submodule update --init` for `bridge-rs/any-llm-rust`. Check that `git -C <worktree> status --porcelain` is empty and that its commits are merged or pushed, then use `git worktree remove --force <worktree>`. Never force-remove a worktree with uncommitted or unpushed work.
149149
- **Never use `git stash` to compare against the base or to capture red evidence.** The stash stack is shared by every worktree, so `stash pop` in one worktree can pop another checkout's stash and leave a conflict. Check the base out into a separate detached worktree (`git worktree add --detach <dir> <base>`), or read single files with `git show <base>:<path>`. To show a test failing against pre-fix code, copy the old file over with `git show <rev>:<path> > <path>`, run the test, then restore your version from a copy you made first. Builders reached for `stash` for this repeatedly. Read-only roles must not run `stash`, `reset`, `checkout` or anything else that changes git state.
150150
- **Check that a demo port is free on both IPv4 and IPv6 before using it.** Another session's server can be listening on `*:8001` over IPv6 while yours binds `127.0.0.1:8001`. `localhost` may then reach the other server, so the page you test isn't yours. Run `lsof -nP -iTCP:<port> -sTCP:LISTEN` first, bind `127.0.0.1`, and point Firefox at `http://127.0.0.1:<port>`, not `localhost`.
151+
- **A protocol fake written from the client's side passes the client's bugs.** Harbor's SSE MCP transport parsed the server's `endpoint` event as JSON, and the test fake sent JSON, so the tests passed while every real MCP SDK server failed. When you fake a protocol peer (MCP, ACP), build its wire format from the real SDK's source, and check at least once against a real server in Firefox. The MCP SDK ships with `demo/web-agents/bring-your-chatbot/mcp-server/`.
151152
- **Firefox may try to update itself when an agent launches it.** macOS then reports that the terminal app (for example "Rex Server") tried to modify an application, and blocks it. Leave the block in place; the test browser still runs.
152153

153154
## Leave it better than you found it

0 commit comments

Comments
 (0)