This document describes the architecture of Harbor, a single browser extension.
Harbor brings AI and MCP (Model Context Protocol) capabilities to web applications:
- Infrastructure — LLM connections, MCP server hosting, and the native bridge
- Page API (
extension/src/page-api/) — Implements the Web Agent API specification, exposingwindow.agent,document.modelContext, and the Prompt API'sLanguageModel(https://webmachinelearning.github.io/prompt-api/) to web pages
Related Documentation:
- Web Agent API Spec — The API specification Harbor's page API implements
- User Guide — Installation and usage
- Developer Guide — Building apps with the Web Agent API
- Contributing — Development setup
- MCP Host — Execution environment details
Harbor provides:
| Capability | Provided By | Description |
|---|---|---|
| Web Agent API | Page API | LanguageModel (the Prompt API), window.agent and document.modelContext for web pages |
| Permission System | Harbor | Per-origin capability grants with user consent; Harbor's page API checks them before every page call |
| MCP Server Management | Harbor | Install, run, and connect to MCP servers |
| In-Browser MCP Execution | Harbor | Run MCP servers as WASM or JavaScript directly in the browser |
| LLM Integration | Harbor | Local model support (Ollama, llamafile) + cloud providers |
| Chat Sidebar | Harbor | Built-in chat UI with tool calling |
| Bring Your Own Chatbot | Harbor | Websites can integrate with the user's AI via agent.mcp.* and agent.chat.* |
The system exposes AI capabilities to web pages through a layered architecture involving four key components:
- Page API (
extension/src/page-api/) — Injects the JavaScript APIs into web pages and routes their calls to the rest of Harbor - Harbor Extension — Manages LLM provider selection, MCP servers, and provides the chat sidebar
- Native Bridge (Rust) — Handles LLM inference and native MCP server communication
- WASM and JavaScript Runtimes — Run MCP servers compiled to WebAssembly, or written in JavaScript, directly in the browser
When a web page loads, Harbor's content script injects a script that exposes two global JavaScript objects:
// LanguageModel — Text generation (the Prompt API: https://webmachinelearning.github.io/prompt-api/).
// create() asks the person for the model:prompt grant itself if the site doesn't have it.
const session = await LanguageModel.create({
initialPrompts: [{ role: 'system', content: 'You are helpful.' }]
});
const response = await session.prompt('Hello!');
// window.agent — Tools, browser access, autonomous agents
await window.agent.requestPermissions({
scopes: ['model:prompt', 'mcp:tools.list', 'mcp:tools.call'],
reason: 'Enable AI features'
});
for await (const event of window.agent.run({ task: 'Search for news' })) {
console.log(event);
}These APIs are permission-gated — web pages must request explicit user consent before accessing AI capabilities.
Web Page Harbor Extension Bridge
│ │ │
│ session.prompt() │ │
├──────────────────────────────────────►│ │
│ postMessage to page-api/ │ │
│ content-script.ts, which forwards │ Native Messaging │
│ over a port to background.ts ├───────────────────────►│
│ │ │ LLM call
│ │◄───────────────────────┤
│◄──────────────────────────────────────┤ │
│ "Hello! How can.." │ │
The system supports two execution paths for different capabilities:
MCP servers can run entirely in the browser using:
- WASM Runtime — Servers compiled to WebAssembly (e.g.,
mcp-time.wasm) - JavaScript Runtime — Built-in JavaScript servers running in Web Workers (other JavaScript servers run in the bridge's QuickJS runtime)
This path is ideal for:
- Privacy-sensitive operations (data never leaves the browser)
- Offline functionality
- Simple tools that don't need external resources
For LLM inference and native MCP servers, Harbor uses a Rust native messaging bridge:
- LLM Communication — Connects to Ollama, OpenAI, Anthropic, and other providers
- Native MCP Servers — Runs stdio-based MCP servers as child processes
- OAuth Flows — Handles authentication with external services
┌─────────────────────────────────────────────────────────────────────────────┐
│ WEB PAGE │
│ │
│ LanguageModel window.agent │
│ ├── availability() ├── requestPermissions() │
│ └── create() ├── capabilities() │
│ ├── browser.activeTab.* │
│ ├── run({ task }) │
│ ├── sessions.create() │
│ ├── mcp.discover/register() [BYOC] │
│ └── chat.open/close() [BYOC] │
└───────────────────────────────────────┬─────────────────────────────────────┘
│ postMessage (harbor_page_api channel)
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ BROWSER EXTENSION (Chrome/Firefox) │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────────┐ ┌───────────────────┐ ┌───────────────────────┐ │
│ │ Content Script │ │ Background │ │ Sidebar │ │
│ │ (injected.ts) │ │ (background.ts) │ │ (sidebar.ts) │ │
│ │ │ │ │ │ │ │
│ │ • Inject APIs │ │ • Message router │ │ • Server management │ │
│ │ • Route messages │ │ • Permissions │ │ • LLM configuration │ │
│ │ • Feature flags │ │ • Orchestration │ │ • Feature flags │ │
│ └─────────┬─────────┘ └─────────┬─────────┘ └───────────┬───────────┘ │
│ │ │ │ │
│ └──────────────────────┼────────────────────────┘ │
│ │ │
│ ┌────────────────────────────────┴──────────────────────────────────────┐ │
│ │ IN-BROWSER MCP EXECUTION │ │
│ │ │ │
│ │ ┌──────────────────┐ ┌──────────────────┐ │ │
│ │ │ WASM Runtime │ │ JS Runtime │ │ │
│ │ │ (runtime.ts) │ │ (session.ts) │ │ │
│ │ │ │ │ │ │ │
│ │ │ • WASI support │ │ • QuickJS/bridge│ │ │
│ │ │ • Isolated mem │ │ • Web Workers │ │ │
│ │ │ • MCP protocol │ │ • MCP protocol │ │ │
│ │ └──────────────────┘ └──────────────────┘ │ │
│ └───────────────────────────────────────────────────────────────────────┘ │
│ │ │
└───────────────────────────────────┼──────────────────────────────────────────┘
│ Native Messaging (stdin/stdout JSON)
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ RUST BRIDGE (bridge-rs) │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌──────────────────────────────────────────────────────────────────────┐ │
│ │ NATIVE MESSAGING │ │
│ │ (native_messaging.rs) │ │
│ │ Length-prefixed JSON frames over stdin/stdout │ │
│ └──────────────────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────────────┐ │
│ │ RPC Handler │ │ LLM Manager │ │ QuickJS Runtime │ │
│ │ (rpc/) │ │ (llm/) │ │ (js/) │ │
│ │ │ │ │ │ │ │
│ │ • Method │ │ • any-llm lib │ │ • JS MCP servers │ │
│ │ dispatch │ │ • Ollama │ │ • Sandboxed execution │ │
│ │ • Request/ │ │ • OpenAI │ │ • Capability-based │ │
│ │ response │ │ • Anthropic │ │ permissions │ │
│ └─────────────────┘ └─────────────────┘ └─────────────────────────┘ │
│ │
│ ┌─────────────────┐ ┌─────────────────────────────────────────────────┐ │
│ │ OAuth Manager │ │ File System Access (fs/) │ │
│ │ (oauth/) │ │ │ │
│ │ │ │ • Configuration storage (~/.harbor/) │ │
│ │ • OAuth flows │ │ • Credential management │ │
│ │ • Token cache │ │ • Session persistence │ │
│ │ • Providers │ │ │ │
│ └─────────────────┘ └─────────────────────────────────────────────────┘ │
│ │
└──────────────────────────────────────────────────────────────────────────────┘
│
│ HTTP (OpenAI-compatible API)
▼
┌─────────────────────────┐
│ LLM Providers │
│ Ollama, OpenAI, │
│ Anthropic, llamafile │
└─────────────────────────┘
The page API (extension/src/page-api/) is the part of Harbor that talks to web pages. It has its own content script and background wiring, but runs in Harbor's own background process — there is no separate extension and no cross-extension messaging:
┌─────────────────────────────────────────────────────────────────────────────┐
│ WEB PAGE │
│ LanguageModel / window.agent │
└───────────────────────────────────────┬─────────────────────────────────────┘
│ postMessage
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ HARBOR EXTENSION — PAGE API │
│ │
│ ┌───────────────────┐ ┌───────────────────┐ ┌───────────────────────┐ │
│ │ Content Script │ │ Background │ │ harbor-core.ts │ │
│ │ (injected.ts) │ │ (background.ts) │ │ │ │
│ │ │ │ │ │ │ │
│ │ • Inject APIs │ │ • Feature flags │ │ • In-process call │ │
│ │ • Route messages │ │ (the real gate)│ │ into Harbor's │ │
│ │ │ │ • Origin from │ │ extension-api and │ │
│ │ │ │ port.sender │ │ agent router │ │
│ └───────────────────┘ └─────────┬─────────┘ └───────────┬───────────┘ │
│ │ │ │
│ └────────────────────────┘ │
└───────────────────────────────────┬─────────────────────────────────────────┘
│ in-process function call
▼
┌─────────────────────────────────────────────────────────────────────────────┐
│ HARBOR EXTENSION — THE REST OF HARBOR │
│ (extension-api.ts, agents/background-router.ts, and below) │
└─────────────────────────────────────────────────────────────────────────────┘
harbor-core.ts is the seam: it's the only file under page-api/ allowed to import from outside page-api/, so the rest of the page API stays swappable if the agent side changes shape later. The page's origin always comes from the connecting port's sender (its URL in Firefox, its origin in Chrome) — never from the message itself, which a page or a compromised content script could otherwise forge.
Every page-facing member exists and calls through regardless of these flags; a turned-off one makes the background refuse the call (ERR_FEATURE_DISABLED), not disappear from the page. They're managed from the sidebar's "Browser Agent Capabilities" panel:
| Flag | Description | Default |
|---|---|---|
textGeneration |
Gates LanguageModel, Summarizer, Writer, Rewriter, Proofreader, Translator and LanguageDetector (prompts/runs and their streaming forms; availability() reports "unavailable" instead of refusing) |
true |
toolCalling |
Gates agent.run() for autonomous tasks |
true |
toolAccess |
Gates agent.mcp.register(), a site registering its own MCP server (discover() and unregister() aren't gated) |
true |
browserInteraction |
Gates click/fill/scroll on pages | false |
browserControl |
Gates navigation and tab management | false |
The native bridge (bridge-rs/) is a Rust binary that communicates with the browser extension via native messaging — a protocol where the browser spawns the binary and communicates over stdin/stdout with length-prefixed JSON frames.
Key responsibilities:
-
LLM Provider Abstraction — Unified interface to multiple LLM backends:
- Ollama — Local models via HTTP API
- OpenAI — GPT models via OpenAI API
- Anthropic — Claude models via Anthropic API
- llamafile — Single-file local models
-
Configuration Management — Stores settings in
~/.harbor/:~/.harbor/ ├── harbor.db # SQLite database for server configs ├── catalog.db # Cached MCP server catalog ├── installed_servers.json ├── secrets/ │ └── credentials.json # API keys (mode 600) └── sessions/ # Chat session history -
OAuth Handling — Browser-based OAuth flows for services requiring authentication
-
RPC Dispatch — Routes incoming requests to appropriate handlers:
// Example RPC message { "type": "rpc", "id": "abc123", "method": "llm.chat", "params": { "messages": [...] } }
The WASM runtime (extension/src/wasm/) executes MCP servers compiled to WebAssembly directly in the browser using WASI (WebAssembly System Interface).
How it works:
┌─────────────────────────────────────────────────────────────────┐
│ WASM MCP Server │
│ │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────────┐ │
│ │ .wasm file │───►│ WASI Runtime │───►│ MCP Protocol │ │
│ │ (compiled) │ │ (jco/wasmer) │ │ (JSON-RPC) │ │
│ └──────────────┘ └──────────────┘ └──────────────────┘ │
│ │
│ Features: │
│ • Isolated memory (no access to host memory) │
│ • Sandboxed execution (limited syscalls) │
│ • Controlled I/O through WASI interface │
│ • MCP stdio transport emulation │
└─────────────────────────────────────────────────────────────────┘
Example WASM server lifecycle:
// 1. Register the server
const handle = registerMcpServer({
id: 'time-wasm',
wasmUrl: 'mcp-time.wasm',
tools: [{ name: 'time.now', description: 'Get current time' }]
});
// 2. Start the server (loads WASM, creates session)
await startMcpServer('time-wasm');
// 3. Call tools via MCP protocol
const result = await callMcpTool('time-wasm', 'time.now', {});
// { ok: true, result: { iso: "2026-01-27T10:30:00Z" } }The JS runtime (extension/src/js-runtime/session.ts) runs JavaScript MCP servers in one of two places:
- The bridge's QuickJS runtime. This is the normal path, and the only one for servers that aren't built in. The extension sends the server's code to the bridge and speaks MCP to it over the bridge connection.
- A Web Worker, for built-in servers only. When the bridge isn't connected, a built-in server (today,
echo-js) runs from a pre-bundled worker file such asjs-runtime/builtin-echo-worker.js. That file carries its own preamble: it deletesfetch,XMLHttpRequest,WebSocketandimportScripts, and providesMCP.readLine()/MCP.writeLine()for stdio.
Third-party JavaScript never runs in an extension Web Worker.
Web Page Extension Bridge LLM
│ │ │ │
│ session.prompt("Hi") │ │ │
├──────────────────────────►│ │ │
│ │ llm.chat │ │
│ ├──────────────────────────►│ │
│ │ │ POST /v1/chat/... │
│ │ ├───────────────────────►│
│ │ │◄───────────────────────┤
│ │◄──────────────────────────┤ │
│◄──────────────────────────┤ │ │
│ "Hello! How can I help?" │ │ │
Web Page Extension Bridge MCP Server
│ │ │ │
│ agent.run({ task }) │ │ │
├──────────────────────────►│ │ │
│ │ ① Check permission │ │
│ │ ② host_call_tool │ │
│ ├──────────────────────────►│ │
│ │ │ ③ Check rate limit │
│ │ │ ④ Resolve tool │
│ │ │ ⑤ MCP call │
│ │ ├───────────────────────►│
│ │ │◄───────────────────────┤
│ │◄──────────────────────────┤ │
│◄──────────────────────────┤ │ │
│ { result: ... } │ │ │
User: "Find my recent GitHub PRs and summarize them"
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ Harbor's built-in agent loop │
│ │
│ 1. Collect every tool the site may use │
│ 2. Offer them all; nothing picks tools per task │
│ 3. Send to LLM with tool definitions │
│ 4. LLM returns: call github/list_prs │
│ 5. Execute tool → get results │
│ 6. Send results back to LLM │
│ 7. LLM returns: call github/get_pr_details │
│ 8. Execute tool → get results │
│ 9. Send results back to LLM │
│ 10. LLM generates final summary │
└─────────────────────────────────────────────────────────────────┘
│
▼
"You have 3 open PRs: #123 fixes auth bug, #124 adds dark mode..."
Web Page Extension WASM/JS Runtime
│ │ │
│ agent.run({ task: 'What time is it?' }) │
├──────────────────────────►│ │
│ │ ① Check permission │
│ │ ② Route to runtime │
│ ├─────────────────────────────►│
│ │ │ ③ Execute tool
│ │ │ (no network)
│ │◄─────────────────────────────┤
│◄──────────────────────────┤ │
│ { iso: "2026-01-27T..." } │ │
Note: In-browser tools execute entirely within the extension — no native bridge communication is required, making them faster and available offline.
The injected.ts script (extension/src/page-api/injected.ts) is the heart of the Web Agent API. It's injected into every web page and creates the LanguageModel class and the window.agent object.
injected.js is declared as its own content script, in the page's main
world ("world": "MAIN" in the Firefox manifest; registered at runtime
with scripting.registerContentScripts on Chrome and Safari), at
document_start — the same point the isolated-world content script
(content-script.ts) runs at. Running in the main world, not injected via
a <script> element the isolated-world script creates, is what makes
LanguageModel/window.agent/document.modelContext visible to a page's
own parse-time scripts: a dynamically inserted <script> only runs once
the page's own parser has already finished.
Chrome registers it at runtime so the background can decide, per page
load, whether Harbor's LanguageModel replaces Chrome's native one: only
when the person chose a backend other than Chrome's model
(page-api/chrome-injection.ts, llm/sites-backend.ts). Then a tiny
marker script runs first in the same registration, and injected.ts
reads and deletes the marker before any page script runs.
┌─────────────────────────────────────────────────────────────────┐
│ ISOLATED-WORLD CONTENT SCRIPT │
│ │
│ 1. Runs at document_start, same as the main-world script below │
│ (their relative order across worlds isn't guaranteed) │
│ 2. Fetches feature flags from the background (chrome.storage) │
│ 3. Posts them to the page as a message, once known and again │
│ on change — the one thing injected.ts can't read itself │
│ 4. Relays postMessage traffic to/from the background │
└───────────────────────────────────────────────────────────────────┘
│ ▲
│ postMessage (flags, responses) │ postMessage (requests)
▼ │
┌─────────────────────────────────────────────────────────────────┐
│ WEB PAGE CONTEXT │
│ │
│ class LanguageModel extends EventTarget { │
│ static availability(options), │
│ static create(options), // asks for model:prompt itself │
│ prompt(), promptStreaming(), append(), measureContextUsage(), │
│ clone(), destroy() │
│ } │
│ │
│ window.agent = { │
│ capabilities(), │
│ requestPermissions(options), │
│ permissions: { list() }, │
│ tools: { list(), call() }, │
│ browser: { activeTab: { readability(), click(), ... } }, │
│ run(options), // Returns AsyncIterable<RunEvent> │
│ sessions: { create(), list(), terminate() }, │
│ mcp: { discover(), register() }, // BYOC │
│ chat: { canOpen(), open(), close() } // BYOC │
│ } │
└─────────────────────────────────────────────────────────────────┘
Communication between the injected script and content script uses postMessage with a dedicated channel:
// Injected script → Content script (request)
window.postMessage({
channel: 'harbor_page_api',
request: {
id: 'uuid-here',
type: 'languageModel.create',
payload: { initialPrompts: [{ role: 'system', content: 'Be helpful' }] }
}
}, '*');
// Content script → Injected script (response)
window.postMessage({
channel: 'harbor_page_api',
response: {
id: 'uuid-here',
ok: true,
result: { sessionId: 'session-id-here', samplingMode: 'balanced' }
}
}, '*');
// Streaming events (for promptStreaming, agent.run)
window.postMessage({
channel: 'harbor_page_api',
streamEvent: {
id: 'uuid-here',
event: { type: 'token', token: 'Hello' },
done: false
}
}, '*');The agent.run() and session.promptStreaming() methods return AsyncIterable objects that yield events as they arrive:
// Implementation pattern
function createStreamIterable(type, payload) {
const id = crypto.randomUUID();
return {
[Symbol.asyncIterator]() {
const queue = [];
let resolveNext = null;
let done = false;
// Register listener BEFORE sending request
streamListeners.set(id, (event, isDone) => {
if (isDone) done = true;
if (resolveNext) {
resolveNext({ done: false, value: event });
resolveNext = null;
} else {
queue.push(event);
}
});
// Send the request
window.postMessage({ channel, request: { id, type, payload } }, '*');
return {
async next() {
if (queue.length > 0) return { done: false, value: queue.shift() };
if (done) return { done: true, value: undefined };
return new Promise(resolve => { resolveNext = resolve; });
},
async return() {
window.postMessage({ channel, abort: { id } }, '*');
return { done: true, value: undefined };
}
};
}
};
}| Directory/File | Purpose |
|---|---|
page-api/ |
The Web Agent API: injects and serves LanguageModel, window.agent and document.modelContext |
page-api/injected.ts |
LanguageModel / window.agent / document.modelContext creation, in the page |
page-api/content-script.ts |
Content script bridge between the injected script and background.ts |
page-api/background.ts |
Port listener; derives the page's origin from port.sender, wires streaming (session.promptStreaming, agent.run) |
page-api/harbor-core.ts |
The seam: in-process call into extension-api.ts and agents/background-router.ts — the only file under page-api/ allowed to import from outside it |
page-api/handlers/ |
Map-based handler registry (index.ts's routeMessage()) for languageModel.*, agent.*, session.* and tab/browser handlers |
page-api/policy/feature-flags.ts |
The feature flags shown in the sidebar's "Browser Agent Capabilities" panel |
handlers/ |
Modular message handler architecture for Harbor's own background |
handlers/index.ts |
Handler registry initialization |
handlers/types.ts |
Shared handler types and utilities |
handlers/server-handlers.ts |
MCP server management handlers |
handlers/bridge-handlers.ts |
Native bridge status handlers |
handlers/llm-handlers.ts |
LLM configuration handlers |
handlers/oauth-handlers.ts |
OAuth flow handlers |
handlers/permission-handlers.ts |
Permission management handlers |
handlers/session-handlers.ts |
Session management handlers |
handlers/remote-server-handlers.ts |
Remote MCP server handlers |
handlers/page-chat-handlers.ts |
Page chat feature handlers |
agents/background-router.ts |
Routes agent.chat.* and agent.mcp.* calls to their handlers |
agents/handlers/ |
Chat and MCP-website handler implementations |
agents/types.ts |
TypeScript type definitions |
js-runtime/ |
JavaScript MCP server sandbox |
js-runtime/worker-loader.ts |
Generic Web Worker loader for JS server code |
js-runtime/session.ts |
JS server session management |
wasm/ |
WebAssembly MCP server runtime |
wasm/runtime.ts |
WASI-compatible WASM execution |
wasm/session.ts |
WASM server session management |
llm/ |
LLM communication |
llm/native-bridge.ts |
Native messaging to Rust bridge |
llm/bridge-client.ts |
RPC client for bridge |
mcp/ |
MCP protocol implementation |
mcp/host.ts |
In-browser MCP host |
policy/ |
Permission system |
policy/permissions.ts |
Permission checking and prompts |
storage/ |
Extension storage utilities |
background.ts |
Service worker entry point (initializes handlers and the page API) |
extension-api.ts |
Harbor's typed internal API for LLM, MCP, session, permissions and system operations; called in-process by page-api/harbor-core.ts |
sidebar.ts |
Sidebar UI for server management and feature flags |
directory.ts |
MCP server directory/catalog UI |
| Directory/File | Purpose |
|---|---|
main.rs |
Entry point, native messaging loop |
native_messaging.rs |
Length-prefixed JSON protocol |
rpc/mod.rs |
Handler registry pattern with domain registration |
llm/ |
LLM provider management |
llm/config.rs |
LLM configuration and model aliases |
js/ |
QuickJS JavaScript runtime |
js/runtime.rs |
JS execution environment |
js/sandbox.rs |
Capability-based sandboxing |
oauth/ |
OAuth flow management |
mcp/ |
MCP tool registry (Safari compatibility) |
fs/ |
Filesystem utilities |
http_server.rs |
HTTP server mode (Safari) |
any-llm-rust/ |
Multi-provider LLM library (submodule) |
Harbor's extension and the Rust bridge use a handler registry pattern for message routing. This provides:
- Modularity — Each domain (LLM, MCP, permissions, etc.) has its own handler module
- Testability — Handlers can be unit tested in isolation
- Extensibility — New message types can be added without modifying core routing logic
- Type Safety — Shared types ensure consistent request/response formats
// handlers/types.ts - Shared handler infrastructure
export interface RequestContext {
id: string;
type: string;
payload: unknown;
sender: chrome.runtime.MessageSender;
origin: string;
tabId?: number;
}
export type HandlerResponse = Promise<TransportResponse | null>;
export type MessageHandler = (ctx: RequestContext) => HandlerResponse;
// handlers/index.ts - Central registry
const handlers = new Map<string, MessageHandler>();
export function routeMessage(ctx: RequestContext): HandlerResponse {
const handler = handlers.get(ctx.type);
if (handler) return handler(ctx);
return Promise.resolve(errorResponse(ctx.id, 'ERR_INTERNAL', `Unknown: ${ctx.type}`));
}
// handlers/ai-handlers.ts - Domain-specific handlers
handlers.set('create_session', handleCreateSession);
handlers.set('session_prompt', handleSessionPrompt);
handlers.set('get_capabilities', handleGetCapabilities);// rpc/mod.rs - Handler registry with lazy initialization
pub type RpcHandler = fn(serde_json::Value)
-> Pin<Box<dyn Future<Output = Result<serde_json::Value, RpcError>> + Send>>;
static HANDLERS: OnceLock<HashMap<&'static str, RpcHandler>> = OnceLock::new();
fn get_handlers() -> &'static HashMap<&'static str, RpcHandler> {
HANDLERS.get_or_init(|| {
let mut handlers = HashMap::new();
register_llm_handlers(&mut handlers);
register_fs_handlers(&mut handlers);
register_oauth_handlers(&mut handlers);
// ...
handlers
})
}
pub async fn handle(request: RpcRequest) -> RpcResponse {
match get_handlers().get(request.method.as_str()) {
Some(handler) => {
match handler(request.params).await {
Ok(value) => RpcResponse::success(request.id, value),
Err(error) => RpcResponse::error(request.id, error),
}
}
None => RpcResponse::error(request.id, RpcError::method_not_found(&request.method)),
}
}| Layer | Pattern | Registration |
|---|---|---|
Page API (page-api/handlers/) |
Map-based registry | handlers.set(type, fn) |
Harbor Extension (handlers/) |
registerHandler() utility |
registerAsyncHandler(type, fn) |
| Rust Bridge | HashMap with lazy init | handlers.insert(method, fn) |
A handlers/ message is for Harbor's own extension pages (the sidebar, the directory, the permission prompt). registerHandler() answers any other sender, including Harbor's content script in a site's tab, with "Not available to this sender". The page chat's handlers are the exception: they're registered with registerContentScriptHandler() and check the sending tab and origin themselves.
Harbor uses a multi-process architecture for crash isolation and security when running third-party MCP servers.
MCP servers are third-party code downloaded from npm, PyPI, or GitHub. Without isolation:
- A buggy server could crash the entire bridge
- Memory leaks in one server affect all servers
- A malicious server could potentially access data from other servers
┌──────────────────────────────────────────────────────────────────┐
│ MAIN BRIDGE PROCESS │
│ - Native messaging (Firefox communication) │
│ - Permission enforcement │
│ - Rate limiting │
│ - Tool registry │
│ - LLM communication │
└──────────────────┬────────────────────────────────┬──────────────┘
│ IPC (fork) │ IPC (fork)
▼ ▼
┌──────────────────────────────┐ ┌──────────────────────────────┐
│ MCP RUNNER PROCESS │ │ MCP RUNNER PROCESS │
│ (one per server) │ │ (one per server) │
│ │ │ │
│ - Manages single server │ │ - Manages single server │
│ - Crash isolated │ │ - Crash isolated │
│ - Communicates via IPC │ │ - Communicates via IPC │
│ │ │ │
│ ┌────────────────────────┐ │ │ ┌────────────────────────┐ │
│ │ stdio subprocess │ │ │ │ stdio subprocess │ │
│ │ (npx, uvx, binary) │ │ │ │ (npx, uvx, binary) │ │
│ └────────────────────────┘ │ │ └────────────────────────┘ │
└──────────────────────────────┘ └──────────────────────────────┘
Process isolation is opt-in. Enable it via environment variable:
export HARBOR_MCP_ISOLATION=1- Process Spawning: When connecting to a server, the Rust bridge spawns the MCP server as a child process
- Stdio Communication: The bridge communicates with servers via stdin/stdout using JSON-RPC
- Crash Recovery: If a server crashes, only that server is affected; the bridge survives and can restart it
The bridge manages servers via stdio JSON-RPC:
| Command | Description |
|---|---|
connect |
Spawn the MCP server and establish connection |
disconnect |
Stop the server process |
list_tools |
Get tools from the server |
call_tool |
Execute a tool |
list_resources |
Get resources from the server |
read_resource |
Read a resource |
get_prompt |
Get a prompt |
shutdown |
Terminate the runner |
A similar isolation pattern is used for the catalog system:
- Main bridge: Only reads from the catalog database
- Catalog worker: Separate process that handles network fetches and database writes
- Enabled via:
HARBOR_CATALOG_WORKER=1
# Enable catalog worker isolation
export HARBOR_CATALOG_WORKER=1Permissions are scoped per-origin with capability-based grants. Harbor holds the only grant store and the only consent prompt; Harbor's page API checks it (permissions.check, permissions.request) before every page call. A site with no tool allowlist may call no tools.
| Scope | Description | Grants Access To |
|---|---|---|
model:prompt |
Basic text generation | LanguageModel.create() (asked for by create() itself if missing) |
model:tools |
AI with tool calling | agent.run() |
mcp:tools.list |
Let your agent see your installed tools | agent.run() |
mcp:tools.call |
Let your agent use your installed tools | agent.run() |
mcp:servers.register |
Register website MCP servers | agent.mcp.register() |
browser:activeTab.read |
Read active tab | agent.browser.activeTab.readability() |
chat:open |
Open browser chat UI | agent.chat.open() |
| Type | Behavior | Storage |
|---|---|---|
ALLOW_ONCE |
Expires after 10 min or tab close | Memory |
ALLOW_ALWAYS |
Persists across sessions | browser.storage.local |
DENY |
Explicitly denied (no re-prompt) | browser.storage.local |
Request arrives with origin "https://example.com"
│
▼
┌───────────────────────────┐
│ Check DENY grants │─────► Denied? Return ERR_PERMISSION_DENIED
└───────────────────────────┘
│
▼
┌───────────────────────────┐
│ Check ALLOW_ALWAYS grants │─────► Found? Proceed
└───────────────────────────┘
│
▼
┌───────────────────────────┐
│ Check ALLOW_ONCE grants │─────► Found & not expired? Proceed
│ (check expiry & tab) │─────► Expired? Remove & continue
└───────────────────────────┘
│
▼
Return ERR_PERMISSION_DENIED
Tools from MCP servers are namespaced to prevent collisions.
Format: {serverId}/{toolName}
Examples:
filesystem/read_filegithub/search_issuesmemory-server/save_memory
MCP Server connects
│
▼
┌───────────────────────────┐
│ Call tools/list │
└───────────────────────────┘
│
▼
┌───────────────────────────┐
│ Register tools with │
│ namespace prefix │
│ │
│ read_file → filesystem/ │
│ read_file │
└───────────────────────────┘
│
▼
Tools available for invocation
┌──────────────────┐
│ INSTALLING │ Package download/build
└────────┬─────────┘
│
▼
┌──────────────────┐
│ STOPPED │ Installed but not running
└────────┬─────────┘
│ start
▼
┌──────────────────┐
│ STARTING │ Process spawning
└────────┬─────────┘
│
▼
┌──────────────────┐
┌───►│ RUNNING │ Connected and operational
│ └────────┬─────────┘
│ │ crash
│ ▼
│ ┌──────────────────┐
│ │ CRASHED │ Unexpected exit
│ └────────┬─────────┘
│ │ auto-restart (up to 3 times)
└─────────────┘
All persistent data is stored in ~/.harbor/:
| File | Format | Contents |
|---|---|---|
harbor.db |
SQLite | Server configurations |
catalog.db |
SQLite | Cached server catalog |
installed_servers.json |
JSON | Installed server metadata |
secrets/credentials.json |
JSON | API keys (file permissions: 600) |
sessions/*.json |
JSON | Chat session history |
A sample of the codes these layers return:
| Code | Description |
|---|---|
ERR_HARBOR_NOT_FOUND |
Harbor extension not found or not connected |
ERR_TIMEOUT |
Request timed out |
ERR_INVALID_REQUEST |
Invalid request format |
ERR_PERMISSION_DENIED |
Permission denied by user or policy |
ERR_SESSION_NOT_FOUND |
Session not found |
ERR_TOOL_FAILED |
Tool execution failed |
ERR_MODEL_FAILED |
Model/LLM execution failed |
ERR_INTERNAL |
Internal error |
See docs/WEB_AGENTS_API.md#error-handling for the full list.
| Layer | Protection |
|---|---|
| Origin Isolation | Permissions scoped to origin |
| User Consent | Explicit grants required |
| No Payload Logging | Tool args/results not logged |
| Rate Limiting | Prevents abuse |
| Tool Allowlisting | Origins can be restricted to specific tools |
| Tab-Scoped Grants | ALLOW_ONCE can be tied to a tab |
| Secret Storage | Credentials stored with restricted file permissions |
The bridge uses native messaging with length-prefixed JSON frames.
┌─────────────────┬────────────────────────────────────────┐
│ Length (4 bytes)│ JSON Payload (UTF-8) │
│ Little-endian │ { "type": "...", "request_id": "..." } │
└─────────────────┴────────────────────────────────────────┘
Server Management: add_server, remove_server, list_servers, connect_server, disconnect_server
MCP Operations: mcp_connect, mcp_list_tools, mcp_call_tool, mcp_read_resource
BYOC: connect_remote_mcp, disconnect_remote_mcp, page_chat_message
LLM: llm_detect, llm_set_active
Chat: chat_create_session, chat_send_message, chat_list_sessions
Host: host_list_tools, host_call_tool, host_grant_permission
See Developer Guide for complete message reference.