🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

ai-browser

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ai-browser

AI-friendly browser with semantic output

latest
npmnpm
Version
0.3.1
Version published
Maintainers
1
Created
Source

AI Browser

An AI-friendly browser automation service. It extracts structured semantic information from web pages and exposes browser tools via the MCP (Model Context Protocol), enabling LLM agents to browse and interact with the web efficiently.

中文文档

Install

npm install -g ai-browser

This provides two commands:

CommandDescription
ai-browserStart the HTTP server (Web UI + REST API + SSE MCP endpoint)
ai-browser-mcpStart a stdio MCP server for Claude Desktop / Cursor

Quick Start

1. Start the server

ai-browser
# or specify a port
ai-browser --port 8080

Open http://localhost:3000 — the homepage provides a semantic analysis demo and a link to the built-in test Agent.

2. Configure the test Agent

Click Settings in the Agent page to set your LLM API key, base URL, and model. The Agent supports any OpenAI-compatible API.

Task-oriented pages:

  • http://localhost:3000/tasks.html — submit TaskAgent tasks
  • http://localhost:3000/task-result.html?taskId=... — inspect task status/result/event stream

3. Use with Claude Desktop (stdio MCP)

Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "ai-browser": {
      "command": "ai-browser-mcp"
    }
  }
}

4. Use with remote MCP clients (SSE)

Start the HTTP server:

ai-browser --port 3000

SSE endpoint:

  • http://127.0.0.1:3000/mcp/sse

For custom clients, use MCP SDK SSEClientTransport (it handles the message endpoint internally):

import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js';

const client = new Client({ name: 'my-client', version: '0.1.0' });
const transport = new SSEClientTransport(new URL('http://127.0.0.1:3000/mcp/sse'));

await client.connect(transport);

const { tools } = await client.listTools();
console.log('tool count:', tools.length);

const created = await client.callTool({ name: 'create_session', arguments: {} });
console.log(created);

Notes:

  • This server currently exposes legacy HTTP+SSE MCP transport (/mcp/sse + /mcp/message).
  • The message endpoint is POST /mcp/message?sessionId=... and is primarily for transport internals.

4.1 MCP AI Consumer Guide

For AI-oriented consumption rules (nextActions, hasMore/nextCursor, topIssues, detail levels), see:

  • docs/18-mcp-ai-consumer-guide.md
  • docs/19-mcp-ai-readability-roadmap.md (P0-P2 roadmap and execution checklist)
  • benchmark command: npm run baseline:v1 (includes aiFieldCoverageRate / invalidToolCallRate)

5. Use as a library

import {
  createBrowserMcpServer,
  BrowserManager,
  SessionManager,
  BrowsingAgent,
} from 'ai-browser';

Features

  • Semantic Web Analysis — Extracts interactive elements (buttons, links, inputs) from pages using the Chrome Accessibility Tree, assigning each a unique semantic ID
  • MCP Protocol — Browser tools exposed via MCP with both stdio and SSE transports
  • LLM-Powered Agent — Built-in autonomous browsing agent driven by LLM tool calls
  • Headless / Headful Switching — Start in headful mode for manual login, then switch to headless for automation while preserving cookies
  • Real-time Monitoring — Web UI with SSE-based live streaming of agent actions and results
  • Multi-Session & Multi-Tab — Concurrent browser sessions with up to 20 tabs each, automatic cleanup on expiration

Architecture

┌──────────────────────────────────────────────────────────┐
│                       AI Browser                          │
├──────────────────────────────────────────────────────────┤
│                                                          │
│  CLI Layer (src/cli/)                                    │
│    ai-browser ──→ Fastify HTTP + SSE MCP                 │
│    ai-browser-mcp ──→ stdio MCP                          │
│                                                          │
│  API Layer (src/api/)                                    │
│    REST API (/v1/sessions, /v1/agent, ...)               │
│    SSE MCP  (/mcp/sse, /mcp/message)                     │
│                                                          │
│  MCP Layer (src/mcp/)                                    │
│    Browser tools: navigate, click, type, scroll, ...     │
│                                                          │
│  Agent Layer (src/agent/)                                │
│    LLM-driven agent loop with tool calling               │
│                                                          │
│  Semantic Layer (src/semantic/)                           │
│    Accessibility tree analysis, content extraction        │
│    Element matching, page classification                 │
│                                                          │
│  Browser Layer (src/browser/)                            │
│    Puppeteer (headless + headful dual instances)          │
│    Session & tab management, cookie store                │
│                                                          │
└──────────────────────────────────────────────────────────┘

MCP Tools

The server currently exposes 38 MCP tools:

  • 28 browser primitive tools (navigation, interaction, tabs, logs, uploads, etc.)
  • 3 composite tools (multi-step operations in one call)
  • 7 task-runtime tools (template execution, run tracking, artifacts)

Most browser tools accept an optional sessionId — omitting it auto-creates/reuses a default session.

AI-oriented tool responses now include additive helper fields on key tools:

  • aiSchemaVersion: schema version for AI helper payload
  • aiDetailLevel: applied detail level (brief / normal / full)
  • aiSummary: short status sentence for fast decision-making
  • aiMarkdown: compact, sectioned markdown with high-signal details
  • aiHints: suggested next actions (text)
  • nextActions: structured next-step suggestions (tool, args, reason)
  • deltaSummary: polling-oriented change summary (key, changes)
  • schemaRepairGuidance: repair-oriented hints for schema verification failures

List-like responses are also normalized with:

  • hasMore + nextCursor for continuation semantics
  • topIssues on log-oriented tools (network/console) for quick fault triage

These fields are additive and backward-compatible; existing JSON fields are unchanged.

You can control verbosity via environment variable AI_MARKDOWN_DETAIL_LEVEL=brief|normal|full (default: normal).

Optional adaptive policy (prototype): AI_MARKDOWN_ADAPTIVE_POLICY=1

  • For polling-heavy tools, detail can auto-shift to brief
  • On terminal failure states, detail can auto-escalate to full

Session Management

ToolDescription
create_sessionCreate a new browser session
close_sessionClose a browser session (force=true closes headful sessions)

Navigation & Page Info

ToolDescription
navigateOpen a URL, returns statusCode, with timeout degradation for slow pages, detects pending dialogs
get_page_infoGet interactive elements with semantic IDs (supports maxElements, visibleOnly; masks sensitive field values; includes stability and dialog info)
get_page_contentExtract page text with attention scores (supports maxLength truncation)
find_elementFuzzy search for elements by name or type
screenshotTake a page screenshot (supports fullPage, element_id, format, quality)
execute_javascriptExecute JavaScript on the page (local mode only; 5s timeout, 4000-char result truncation)

Element Interaction

ToolDescription
clickClick an element by semantic ID (captures popup windows as new tabs)
type_textType text into an input, optionally press Enter
hoverHover over an element to trigger tooltips/dropdowns
select_optionSelect a dropdown option by value
set_valueSet element value directly (for rich text editors, contenteditable)
press_keyPress keyboard keys (Enter, Escape, Tab, etc.), supports modifier combos (modifiers: ['Control'])
scrollScroll the page up or down
go_backNavigate back
waitWait by condition: time, selector, networkidle, or element_hidden

Tab Management

ToolDescription
create_tabCreate a new tab (auto-switches to it, optional URL)
list_tabsList all tabs in the session
switch_tabSwitch to a specific tab
close_tabClose a specific tab

Dialog Handling

ToolDescription
handle_dialogHandle page dialogs — accept or dismiss alert, confirm, prompt
get_dialog_infoGet pending dialog info and dialog history

Page Monitoring

ToolDescription
wait_for_stableWait for DOM stability (no mutations + no pending network requests)
get_network_logsGet network request logs (filter by xhr, failed, slow, urlPattern)
get_console_logsGet console logs (filter by level, default: error + warn)

File Handling

ToolDescription
upload_fileUpload a file to a file input element (local mode only)
get_downloadsGet downloaded files list

Composite Tools (Multi-Step Operations)

ToolDescription
fill_formFill multiple form fields and optionally submit in one call (fields: [{ element_id, value }], optional submit)
click_and_waitClick an element then wait for stable/navigation/selector (element_id + waitFor: 'stable'|'navigation'|'selector')
navigate_and_extractNavigate to URL and extract content in one call (url + extract: 'content'|'elements'|'both')

Task Runtime (Non-LLM Templates)

ToolDescription
list_task_templatesList available deterministic task templates
run_task_templateRun a template in sync / async / auto mode
get_task_runQuery run status, progress, result, and artifact refs
list_task_runsList runs with pagination and filters (status, templateId)
cancel_task_runCancel an active run
get_artifactRead run artifacts by chunks (offset, limit)
get_runtime_profileGet runtime limits and profile info

Structured Error Codes

Error responses include an errorCode field for programmatic handling:

CodeMeaning
ELEMENT_NOT_FOUNDElement does not exist, includes hint to refresh page info
NAVIGATION_TIMEOUTPage load timed out, may retry
SESSION_NOT_FOUNDSession does not exist
PAGE_CRASHEDPage crashed or was closed
INVALID_PARAMETERInvalid parameter value
EXECUTION_ERRORJavaScript execution error
TEMPLATE_NOT_FOUNDTask template does not exist
TRUST_LEVEL_NOT_ALLOWEDTemplate not allowed in current trust level
RUN_NOT_FOUNDRun ID does not exist
RUN_TIMEOUTRun exceeded timeout
RUN_CANCELEDRun canceled by client
ARTIFACT_NOT_FOUNDArtifact does not exist or expired

REST API

MethodPathDescription
GET/healthHealth check
POST/v1/sessionsCreate a browser session
GET/v1/sessions/:idGet session details
DELETE/v1/sessions/:idClose a session
POST/v1/sessions/:id/navigateNavigate to a URL
GET/v1/sessions/:id/semanticGet semantic elements
POST/v1/sessions/:id/actionExecute browser action
GET/v1/sessions/:id/screenshotTake a screenshot
GET/v1/sessions/:id/contentExtract page content
POST/v1/sessions/:id/tabsCreate a new tab
GET/v1/sessions/:id/tabsList all tabs
POST/v1/agent/runStart an agent task
GET/v1/agent/:id/eventsSSE stream of agent events
POST/v1/tasksSubmit a TaskAgent task
GET/v1/tasks/:taskIdQuery task status and result
GET/v1/tasks/:taskId/eventsSSE stream of task events
GET/mcp/sseSSE MCP connection
POST/mcp/messageSSE MCP message endpoint

Task API Quick Start

Submit a task:

curl -sX POST http://127.0.0.1:3000/v1/tasks \
  -H 'content-type: application/json' \
  -d '{
    "goal": "Batch extract page summaries",
    "inputs": { "urls": ["https://example.com"] },
    "constraints": { "maxDurationMs": 30000, "maxSteps": 20 },
    "budget": { "maxRetries": 1, "maxToolCalls": 120 }
  }'

Then poll status by taskId (GET /v1/tasks/:taskId) or subscribe to events (GET /v1/tasks/:taskId/events).

Headless / Headful Mode

By default the browser runs in headless mode. To use headful mode (e.g. for manual login):

  • CLI: HEADLESS=false ai-browser
  • Agent UI: Uncheck "Headless Mode" in Settings
  • API: POST /v1/sessions with { "options": { "headless": false } }

Cookies are shared across sessions via the built-in cookie store, so you can log in with a headful session and then create a headless session that reuses the login state.

Security

AI Browser uses a trust level system to control security policies across different entry points.

Trust Levels

LevelEntry PointDescription
localstdio MCP (ai-browser-mcp), Agent API, Task API (/v1/tasks)Full access — allows file: URLs, no private IP blocking
remoteSSE MCP (/mcp/sse)Restricted — blocks private/loopback IPs, DNS rebinding protection, disables upload_file and execute_javascript

SSE Endpoint Restrictions (remote mode)

  • Private IP blocking: Navigation to localhost, 127.0.0.1, 10.x.x.x, 192.168.x.x, and other RFC 1918 addresses is denied
  • DNS rebinding protection: Hostnames that resolve to private IPs are blocked via async DNS lookup
  • Tool gating: upload_file and execute_javascript are disabled to prevent local file access and arbitrary code execution
  • Session cleanup: When an SSE connection disconnects, headless browser sessions created by that connection are automatically closed (headful sessions are preserved)

AI Browser is designed as a single-user local tool. All sessions share a single cookie store. For multi-user deployments, run separate instances per user.

Environment Variables

VariableDescriptionDefault
PORTHTTP server port3000
HOSTHTTP server host127.0.0.1
HEADLESSSet to false for headful modetrue
CHROME_PATHCustom Chrome/Chromium pathauto-detect
PROXY_SERVERHTTP proxy for the browser
LLM_API_KEYLLM API key (for built-in agent)
LLM_BASE_URLLLM API base URL
LLM_MODELLLM model name

Development

git clone https://github.com/chenpu17/ai-browser.git
cd ai-browser
npm install
npm run dev         # Dev server with hot reload
npm run build       # Build TypeScript
npm test            # Run tests
npm run test:run    # Run tests once
npm run baseline:v1 # Collect v1 baseline report
npm run benchmark:v1:expanded # Run expanded readability scenarios (P2 prototype)
npm run stress:v1   # Run 100-task stress report

License

MIT

FAQs

Package last updated on 13 Feb 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts