## File: README.md

# Page Agent


  
  


[](https://github.com/alibaba/page-agent/actions/workflows/main-ci.yml)
[](https://www.npmjs.com/package/page-agent)
[](https://www.npmjs.com/package/page-agent)
[](https://bundlephobia.com/package/page-agent)
[](https://opensource.org/licenses/MIT)
[](http://www.typescriptlang.org/)
[](https://chromewebstore.google.com/detail/page-agent-ext/akldabonmimlicnjlflnapfeklbfemhj)
[](https://github.com/alibaba/page-agent)

The GUI Agent Living in Your Webpage. One script gives any web page its own AI agent.

[](https://trendshift.io/repositories/22551?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-22551)

🌐 **English** | [中文](./docs/README-zh.md)

[**🚀 Demo**](https://alibaba.github.io/page-agent/) | [**📖 Docs**](https://alibaba.github.io/page-agent/docs/introduction/overview) | [**📢 HN Discussion**](https://news.ycombinator.com/item?id=47264138) | [**𝕏 Follow on X**](https://x.com/simonluvramen)



[](https://github.com/user-attachments/assets/a1f2eae2-13fb-4aae-98cf-a3fc1620a6c2)

---

## ✨ Features

- **🎯 Easy integration**
    - No need for `browser extension` / `python` / `headless browser`.
    - Just in-page javascript. Everything happens in your web page.
- **📖 Text-based DOM manipulation**
    - No screenshots. No multi-modal LLMs or special permissions needed.
- **🧠 Bring your own LLMs**
    - Works with most mainstream models, including locally deployed ones. See [supported models](https://alibaba.github.io/page-agent/docs/features/models).
- **🐙 Optional [chrome extension](https://alibaba.github.io/page-agent/docs/features/chrome-extension) for multi-page tasks.**
    - And an [MCP Server (Beta)](https://alibaba.github.io/page-agent/docs/features/mcp-server) to control it from outside

## 💡 Use Cases

- **SaaS AI Copilot** — Ship an AI copilot in your product in lines of code. No backend rewrite.
- **Smart Form Filling** — Turn 20-click workflows into one sentence. Perfect for ERP, CRM, and admin systems.
- **Accessibility** — Make any web app accessible through natural language. Voice commands, screen readers, zero barrier.
- **Multi-page Agent** — Extend your own web agent's reach across browser tabs via the [Chrome extension](https://alibaba.github.io/page-agent/docs/features/chrome-extension).
- **MCP** - Allow your agent clients to control your browser.

## 🚀 Quick Start

### One-line integration

Fastest way to try PageAgent with our free Demo LLM:

```html
<script
    src="https://cdn.jsdelivr.net/npm/page-agent@1.12.2/dist/iife/page-agent.demo.js"
    crossorigin="anonymous"
></script>



```

> **⚠️ For technical evaluation only.** This demo CDN uses our free [testing LLM API](https://alibaba.github.io/page-agent/docs/features/models#free-testing-api). By using it, you agree to its [terms](https://github.com/alibaba/page-agent/blob/main/docs/terms-and-privacy.md).
>
> Add `?autoInit=false` to load the script without creating the demo agent automatically. You can then instantiate it with `new window.PageAgent(...)` and your own LLMs.

### NPM Installation

```bash
npm install page-agent
```

```javascript
import { PageAgent } from 'page-agent'

const agent = new PageAgent({
    model: 'qwen3.5-plus',
    baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
    apiKey: 'YOUR_API_KEY',
    language: 'en-US',
})

await agent.execute('Click the login button')
```

For more programmatic usage, see [📖 Documentations](https://alibaba.github.io/page-agent/docs/introduction/overview).

## 🤝 Contributing

We welcome contributions from the community! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines and [docs/developer-guide.md](docs/developer-guide.md) for local development workflows.

Built something cool with PageAgent? Share it in [Show and Tell](https://github.com/alibaba/page-agent/discussions/categories/show-and-tell). 🙌

Please read the [maintainer's note](https://github.com/alibaba/page-agent/issues/349) on principles and current state.

Contributions generated entirely by **bots or AI** without substantial human involvement will **not be accepted**.

## ⚖️ License

[MIT License](LICENSE)

## 👏 Acknowledgments

This project builds upon the excellent work of **[`browser-use`](https://github.com/browser-use/browser-use)**.

`PageAgent` is designed for **client-side web enhancement**, not server-side automation.

```
DOM processing components and prompt are derived from browser-use:

Browser Use <https://github.com/browser-use/browser-use>
Copyright (c) 2024 Gregor Zunic
Licensed under the MIT License

We gratefully acknowledge the browser-use project and its contributors for their
excellent work on web automation and DOM interaction patterns that helped make
this project possible.
```

**⭐ Star this repo if you find PageAgent helpful!**

---

## File: docs/CODE_OF_CONDUCT.md

# Alibaba Open Source Code of Conduct

[¶中文版](#我们的保证)

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

- Using welcoming and inclusive language
- Being respectful of differing viewpoints and experiences
- Gracefully accepting constructive criticism
- Focusing on what is best for the community
- Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

- The use of sexualized language or imagery and unwelcome sexual attention or
  advances
- Trolling, insulting/derogatory comments, and personal or political attacks
- Public or private harassment
- Publishing others' private information, such as a physical or electronic
  address, without explicit permission
- Other conduct which could reasonably be considered inappropriate in a
  professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at opensource@alibaba-inc.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html

---

> Chinese Version
> 《阿里巴巴开源行为准则》

## 我们的保证

为了促进一个开放透明且友好的环境，我们作为贡献者和维护者保证：无论年龄、种族、民族、性别认同和表达（方式）、体型、身体健全与否、经验水平、国籍、个人表现、宗教或性别取向，参与者在我们项目和社区中都免于骚扰。

## 我们的标准

有助于创造正面环境的行为包括但不限于：

- 使用友好和包容性语言
- 尊重不同的观点和经历
- 耐心地接受建设性批评
- 关注对社区最有利的事情
- 友善对待其他社区成员

身为参与者不能接受的行为包括但不限于：

- 使用与性有关的言语或是图像，以及不受欢迎的性骚扰
- 捣乱/煽动/造谣的行为或进行侮辱/贬损的评论，人身攻击及政治攻击
- 公开或私下的骚扰
- 未经许可地发布他人的个人资料，例如住址或是电子地址
- 其他可以被合理地认定为不恰当或者违反职业操守的行为

## 我们的责任

项目维护者有责任为「可接受的行为」标准做出诠释，以及对已发生的不被接受的行为采取恰当且公平的纠正措施。

项目维护者有权利及责任去删除、编辑、拒绝与本行为标准有所违背的评论 (comments)、提交 (commits)、代码、wiki 编辑、问题 (issues) 和其他贡献，以及项目维护者可暂时或永久性的禁止任何他们认为有不适当、威胁、冒犯、有害行为的贡献者。

## 使用范围

当一个人代表该项目或是其社区时，本行为标准适用于其项目平台和公共平台。

代表项目或是社区的情况，举例来说包括使用官方项目的电子邮件地址、通过官方的社区媒体账号发布或线上或线下事件中担任指定代表。

该项目的呈现方式可由其项目维护者进行进一步的定义及解释。

## 强制执行

可以通过 opensource@alibaba-inc.com 来联系项目团队来举报滥用、骚扰或其他不被接受的行为。

任何维护团队认为有必要且适合的所有投诉都将进行审查及调查，并做出相对应的回应。项目小组有对事件回报者有保密的义务。具体执行的方针近一步细节可能会单独公布。

没有切实地遵守或是执行本行为标准的项目维护人员，可能会因项目领导人或是其他成员的决定，暂时或是永久地取消其参与资格。

## 来源

本行为标准改编自[贡献者公约](https://www.contributor-covenant.org)，版本 1.4
可在此查看[https://www.contributor-covenant.org/zh-cn/version/1/4/code-of-conduct.html](https://www.contributor-covenant.org/zh-cn/version/1/4/code-of-conduct.html)

---

## File: docs/developer-guide.md

# Developer Guide

This file is for local development workflows.

For contribution rules and expectations, see [../CONTRIBUTING.md](../CONTRIBUTING.md).

## 🚀 Quick Start

### Development Setup

1. **Prerequisites**
    - `macOS` / `Linux` / `WSL`
    - `node.js ^22.13 || >=24` with `npm >= 11`
    - An editor that supports `ts/eslint/prettier`
    - Make sure `eslint`, `prettier` and `commitlint` work well. Un-linted code won't pass the CI.

2. **Setup**

    ```bash
    npm i            # Or `npm ci` if you don't want to change the lockfile
    npm start        # Start website dev server
    npm run build    # Build everything
    ```

## 📦 Project Structure

This is a **monorepo** with npm workspaces.

Published packages:

- **Page Agent** (`packages/page-agent/`) - Main entry with built-in UI Panel (npm: `page-agent`)
- **MCP** (`packages/mcp/`) - MCP server for browser control via Page Agent extension (npm: `@page-agent/mcp`)
- **Core** (`packages/core/`) - Core agent logic without UI (npm: `@page-agent/core`)
- **LLMs** (`packages/llms/`) - LLM client with reflection-before-action mental model
- **Page Controller** (`packages/page-controller/`) - DOM operations and visual feedback, independent of LLM
- **UI** (`packages/ui/`) - Panel and i18n, decoupled from PageAgent

Applications:

- **Extension** (`packages/extension/`) - Browser extension (WXT + React)
- **Website** (`packages/website/`) - React docs, landing page, and dev playground (private)

> Source-first monorepo with `npm workspaces + ts references + vite alias`. Library `package.json` exports point to `src/*.ts` during development, and point to `dist/*.js` when published. `workspaces` in root `package.json` must be in topological order.

## 🤖 AGENTS.md Alias

If your AI assistant does not support [AGENTS.md](https://agents.md/). Add an alias for it.

## 🔧 Development Workflows

### Test With Your Own LLM API

- Create a `.env` file in the repo root with your LLM API config

    ```env
    LLM_MODEL_NAME=gpt-5.2
    LLM_API_KEY=your-api-key
    LLM_BASE_URL=https://api.your-llm-provider.com/v1
    ```

- **Ollama example** (tested on 0.15 + qwen3:14b, RTX3090 24GB):

    ```env
    LLM_BASE_URL="http://localhost:11434/v1"
    LLM_API_KEY="NA"
    LLM_MODEL_NAME="qwen3:14b"
    ```

    > @see https://alibaba.github.io/page-agent/docs/features/models#ollama for configuration

- **Restart the dev server** to load new env vars
- If not provided, the demo will use the free testing proxy by default. By using it, you agree to its [terms](./terms-and-privacy.md).

### Extension Development

```bash
npm run dev:ext
npm run build:ext
```

- Update `packages/extension/docs/extension_api.md` for API integration details

### Testing on Other Websites

- Start and serve a local `iife` script

    ```bash
    npm run dev:demo # Serving IIFE with auto rebuild at http://localhost:5174/page-agent.demo.js
    ```

- Add a new bookmark

    ```javascript
    javascript:(function(){var s=document.createElement('script');s.src=`http://localhost:5174/page-agent.demo.js?lang=en-US&t=${Math.random()}`;s.onload=()=>console.log(%27PageAgent ready!%27);document.head.appendChild(s);})();
    ```

- Click the bookmark on any page to load Page-Agent

> Warning: AK in your local `.env` will be inlined in the iife script. Be very careful when you distribute the script.

### Adding Documentation

Ask an AI to help you add documentation to the `website/` package. Follow the existing style.

> Our AGENTS.md file and guardrails are designed for this purpose. But please be careful and review anything AI generated.

---

## File: docs/README-zh.md

# Page Agent


  
  


[](https://github.com/alibaba/page-agent/actions/workflows/main-ci.yml)
[](https://www.npmjs.com/package/page-agent)
[](https://www.npmjs.com/package/page-agent)
[](https://bundlephobia.com/package/page-agent)
[](https://opensource.org/licenses/MIT)
[](http://www.typescriptlang.org/)
[](https://chromewebstore.google.com/detail/page-agent-ext/akldabonmimlicnjlflnapfeklbfemhj)
[](https://github.com/alibaba/page-agent)

纯 JS 实现的 GUI agent。使用自然语言操作你的 Web 应用。无须后端、客户端、浏览器插件。

[](https://trendshift.io/repositories/22551?utm_source=repository-badge&amp;utm_medium=badge&amp;utm_campaign=badge-repository-22551)

🌐 [English](../README.md) | **中文**

[**🚀 Demo**](https://alibaba.github.io/page-agent/) | [**📖 Docs**](https://alibaba.github.io/page-agent/docs/introduction/overview) | [**📢 HN Discussion**](https://news.ycombinator.com/item?id=47264138) | [**𝕏 Follow on X**](https://x.com/simonluvramen)



[](https://github.com/user-attachments/assets/a1f2eae2-13fb-4aae-98cf-a3fc1620a6c2)

---

## ✨ Features

- **🎯 轻松集成**
    - 无需 `浏览器插件` / `Python` / `无头浏览器`，纯页面内 JavaScript
- **📖 基于文本的 DOM 操作**
    - 无需截图，无需多模态模型或特殊权限
- **🧠 自备 LLM**
    - 支持多数主流模型，包括本地部署模型。参见[支持的模型](https://alibaba.github.io/page-agent/docs/features/models)。
- 🐙 可选的 [Chrome 扩展](https://alibaba.github.io/page-agent/docs/features/chrome-extension)，支持跨页面任务
    - [MCP Server (Beta)](https://alibaba.github.io/page-agent/docs/features/mcp-server)

## 💡 应用场景

- **SaaS AI Copilot** — 几行代码为你的产品加上 AI 副驾驶，无需重写后端。
- **智能表单填写** — 把 20 次点击变成一句话。ERP、CRM、管理后台的最佳拍档。
- **无障碍增强** — 用自然语言让任何网页无障碍。语音指令、屏幕阅读器，零门槛。
- **跨页面 Agent** — 通过可选的 [Chrome 扩展](https://alibaba.github.io/page-agent/docs/features/chrome-extension)，让你自己的 Web Agent 跨标签页工作。
- 通过 MCP 为现有 Agent 加入浏览器控制能力。

## 🚀 快速开始

### 一行代码集成

通过我们免费的 Demo LLM 快速体验 PageAgent：

```html
<script
    src="https://registry.npmmirror.com/page-agent/1.12.2/files/dist/iife/page-agent.demo.js"
    crossorigin="anonymous"
></script>
```

> **⚠️ 仅用于技术评估。** 该 Demo CDN 使用了免费的[测试 LLM API](https://alibaba.github.io/page-agent/docs/features/models#free-testing-api)，使用即表示您同意其[条款](https://github.com/alibaba/page-agent/blob/main/docs/terms-and-privacy.md)。
>
> 在 URL 后添加 `?autoInit=false` 可只加载脚本，不自动创建 Demo Agent，之后可通过 `new window.PageAgent(...)` 手动初始化，并使用自定义 LLM。

### NPM 安装

```bash
npm install page-agent
```

```javascript
import { PageAgent } from 'page-agent'

const agent = new PageAgent({
    model: 'qwen3.5-plus',
    baseURL: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
    apiKey: 'YOUR_API_KEY',
    language: 'zh-CN',
})

await agent.execute('点击登录按钮')
```

更多编程用法，请参阅 [📖 文档](https://alibaba.github.io/page-agent/docs/introduction/overview)。

## 🤝 贡献

欢迎社区贡献！请参阅 [CONTRIBUTING.md](../CONTRIBUTING.md) 了解安装与贡献指南。

提交 issue 或 PR 之前，请先阅读[作者声明](https://github.com/alibaba/page-agent/issues/349)和[行为准则](CODE_OF_CONDUCT.md)。

我们不接受未经实质性人类参与、完全由 Bot 或 Agent 自动生成的代码。

用 PageAgent 做了有趣的东西？欢迎到 [Show and Tell](https://github.com/alibaba/page-agent/discussions/categories/show-and-tell) 分享。🙌

## 👏 声明与致谢

本项目基于 **[`browser-use`](https://github.com/browser-use/browser-use)** 的优秀工作构建。

`PageAgent` 专为**客户端网页增强**设计，不是服务端自动化工具。

```
DOM processing components and prompt are derived from browser-use:

Browser Use <https://github.com/browser-use/browser-use>
Copyright (c) 2024 Gregor Zunic
Licensed under the MIT License

We gratefully acknowledge the browser-use project and its contributors for their
excellent work on web automation and DOM interaction patterns that helped make
this project possible.
```

## ⚖️ 许可证

[MIT License](../LICENSE)

**⭐ 如果觉得 PageAgent 有用或有趣，请给项目点个星！**

---

## File: docs/SECURITY.md

# Security Policy

## Supported Versions

We provide security fixes on a best-effort basis for:

| Version                                                   | Supported |
| --------------------------------------------------------- | --------- |
| `main`                                                    | Yes       |
| Latest npm release of `page-agent` and workspace packages | Yes       |
| Older releases                                            | No        |

Please upgrade to the latest release before reporting an issue against an older build.

## Reporting a Vulnerability

Please do not report security vulnerabilities through public GitHub issues, discussions, or pull requests.

Use GitHub's private vulnerability reporting flow:

- Open https://github.com/alibaba/page-agent/security/policy
- Click `Report a vulnerability`

If private reporting is unavailable, open a minimal public issue only to request a private contact channel. Do not include exploit details.

## What to Include

- Affected package or feature
- Exact version, commit, or build
- Browser, OS, and runtime environment
- Reproduction steps or a proof of concept
- Expected impact

## Scope

We prioritize reports that show a real security boundary failure, such as:

- Unauthorized access to data, tokens, or extension capabilities
- Bypassing explicit safety constraints
- Sensitive data exposure caused by default behavior

The following usually do not qualify by themselves:

- Unsafe custom integrations that ignore documented safeguards
- Intentionally embedding secrets into client-side builds
- Reports against unsupported older versions

## Disclosure

Please avoid public disclosure until maintainers have had a reasonable chance to investigate and ship a fix.

---

## File: docs/terms-and-privacy.md

# Terms of Use & Privacy

**Last updated:** March 2026

"We" in this document refers to the maintainers of the open-source Page Agent project (https://github.com/alibaba/page-agent). "The software" refers to Page Agent (the JavaScript library) and Page Agent Ext (the browser extension). This document covers the software itself and the testing API we provide — **not** any third-party product or service built with it.

---

## 1. Open Source Software Privacy

The software is a **client-side only** tool with a "Bring Your Own Key" (BYOK) architecture. The software itself does **not** include any backend service. The software does **not** collect or transmit any user data on its own, and we do **not** have access to your browsing activity, page content, or task instructions through the software.

All data transmission occurs **only** between your browser and the LLM provider you configure. You are in full control of which provider receives your data.

The project is open source under the [MIT License](https://github.com/alibaba/page-agent/blob/main/LICENSE) and can be audited at: https://github.com/alibaba/page-agent

---

## 2. Testing API and Demo Disclaimer & Terms of Use

To facilitate easy testing and technical evaluation, we provide a free testing LLM API. This API is used in the project homepage's live demo, the pre-built demo CDN bundles, and the browser extension's default configuration. Users may also use it independently for their own technical evaluation of the software.

This free testing API is provided **strictly for technical evaluation and R&D purposes only**. It must not be used in any production environment. By using this API, you agree to the following terms:

- **Permitted Use Only**: This API must be used solely for technical evaluation of the software. Any other use — including integration into other products or services, unlawful activities, violation of the underlying LLM provider's usage policies, or automated scraping at scale — is strictly prohibited.

- **No Sensitive Data**: You are strictly prohibited from inputting any Personal Identifiable Information (PII), confidential business data, financial/medical records, or using this agent on web pages containing such sensitive information.

- **Data Processing**: We do not store or log your prompts, webpage data (HTML), or any submitted content, nor do we use such data for model training. All data is processed in-transit and immediately discarded. We perform in-memory request validation to prevent abuse of the testing API, and temporarily process IP addresses for rate-limiting purposes. No data from these processes is retained. Data is processed through Alibaba Cloud infrastructure, which is subject to its own privacy policy.

- **Independent Infrastructure**: The software is completely frontend-based with a "Bring Your Own Key" (BYOK) architecture and **no built-in backend**. To facilitate easy testing, the maintainers have purchased public cloud services from Alibaba Cloud China ([aliyun.com](https://www.aliyun.com) Function Compute and BaiLian Qwen models). This project is not a product of, nor endorsed by, Alibaba Cloud.

- **No Guaranteed Availability**: This testing API may be rate-limited, degraded, or discontinued at any time without prior notice.

- **"AS IS" & Limitation of Liability**: This service is provided strictly on an "AS IS" and "AS AVAILABLE" basis, without any warranties. The maintainers bear no liability for any data loss, service interruption, or legal consequences arising from your use of this service.

- **Recommendation for Real Usage**: For secure and continuous usage, we strongly advise using the BYOK mode with your own legally compliant commercial LLM API keys, or connecting to local, offline models (e.g., Ollama).

**Note**: This free testing LLM API processes data via servers located in Mainland China. If you are located in a region with strict data localization laws (such as the EU/EEA), please do not use this API.

**Age Requirement**: The software and testing API are not intended for use by individuals under the age of 13 (or the minimum age of digital consent in your jurisdiction).

---

## 3. Browser Extension (Page Agent Ext)

### Data Processing

The extension performs DOM analysis and automation actions **locally in your browser**. Your browsing history, passwords, and form data are not accessed or collected by the extension developer.

Data is transmitted to external servers **only when you initiate an automation task**. When this occurs:

- Your task instructions (natural language commands)
- Simplified page structure (cleaned HTML) of all pages under the extension's control

are sent to the LLM API endpoint configured in **your settings**.

> **Note:** The HTML cleaning process simplifies page structure for AI readability but **does not guarantee removal of sensitive information** (e.g., visible text, form values, or personal data on the page). Please be mindful of the page content when initiating tasks.

**If you configure a third-party LLM provider** (e.g., OpenAI, Anthropic, or others), data is sent directly to that provider. Their privacy policies apply.

**If you use the testing API**, the terms in [Section 2](#2-testing-api-and-demo-disclaimer--terms-of-use) apply. By using the extension with the default testing API, you agree to those terms.

### Data Storage

- **Local storage only**: Your configuration (API endpoint, API key, model selection) is stored in your browser via `chrome.storage.local` (or equivalent browser storage APIs)
- **No cloud sync**: Configuration is not synced to any external server
- **No analytics**: The extension does not include any analytics or tracking code

### Your Control

- The extension is open source and can be audited by anyone
- You choose which LLM provider to use
- You may configure your own API endpoint at any time
- You can clear all stored data by removing the extension

---

## Changes

We may update these terms at our discretion.

## Contact

https://github.com/alibaba/page-agent/issues

---

## File: packages/mcp/README.md

# @page-agent/mcp

MCP server that lets AI agent clients (Claude Desktop, Copilot, etc.) control your browser through the [Page Agent](https://github.com/alibaba/page-agent) extension.

## Prerequisites

- Node.js >= 20
- [Page Agent Extension](https://chromewebstore.google.com/detail/page-agent-ext/akldabonmimlicnjlflnapfeklbfemhj) installed in Chrome
- An LLM API key (OpenAI-compatible)

## Installation

### Claude Desktop

Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:

```json
{
    "mcpServers": {
        "page-agent": {
            "command": "npx",
            "args": ["-y", "@page-agent/mcp"],
            "env": {
                "LLM_BASE_URL": "https://dashscope.aliyuncs.com/compatible-mode/v1",
                "LLM_API_KEY": "sk-xxx",
                "LLM_MODEL_NAME": "qwen3.5-plus"
            }
        }
    }
}
```

### Cursor / Copilot

Same format — add the config to the MCP settings of your client.

## MCP Tools

| Tool           | Input              | Description                                           |
| -------------- | ------------------ | ----------------------------------------------------- |
| `execute_task` | `{ task: string }` | Execute a browser task in natural language. Blocking. |
| `get_status`   | —                  | Returns `{ connected, busy }`                         |
| `stop_task`    | —                  | Stop the currently running task.                      |

## Environment Variables

| Variable         | Default | Description           |
| ---------------- | ------- | --------------------- |
| `LLM_BASE_URL`   | —       | LLM API base URL      |
| `LLM_API_KEY`    | —       | LLM API key           |
| `LLM_MODEL_NAME` | —       | Model name            |
| `PORT`           | `38401` | HTTP + WebSocket port |

## How It Works

```
┌──────────────┐  stdio   ┌──────────────────┐  WebSocket   ┌──────────────┐
│ Claude /     │◄────────►│ @page-agent/mcp  │◄────────────►│ Hub tab      │
│ Copilot      │  (MCP)   │ (Node.js)        │  (localhost) │ (extension)  │
└──────────────┘          └──────────────────┘              └──────┬───────┘
                                   │                               │
                                   │ HTTP                          │ useAgent
                                   ▼                               ▼
                          ┌──────────────────┐              ┌──────────────┐
                          │ Launcher page    │              │ MultiPage    │
                          │ (localhost:PORT) │              │ Agent        │
                          └──────────────────┘              └──────────────┘
```

1. Agent client starts the MCP server via stdio (`npx @page-agent/mcp`).
2. Server starts HTTP + WS on `localhost:PORT`, opens the launcher page in browser.
3. Launcher page triggers the extension to open a **hub tab** (`hub.html?ws=PORT`).
4. Hub connects to the WS server. MCP tools now proxy tasks to the hub.

The hub tab speaks a generic WebSocket protocol (defined in `hub-ws.ts` in the extension package) and has no knowledge of MCP. See the hub's protocol docs for message format details.

## Architecture

Pure JS ESM, no build step. Source files are the published artifacts.

```
src/
├── index.js        # CLI entry: MCP server (stdio) + opens launcher
├── hub-bridge.js   # HTTP server + WebSocket bridge to hub tab
└── launcher.html   # Bootstrap page: detects extension, triggers hub open
```

## Dev

```bash
npm run dev:ext
npx @modelcontextprotocol/inspector node packages/mcp/src/index.js
```

---

## File: packages/extension/docs/extension_api.md

# Page Agent Extension API

Integrate the Page Agent extension into your web app and trigger multi-page browser tasks from page JavaScript.

## Installation

### 1. Install the browser extension

Primary channel:

- Chrome Web Store: https://chromewebstore.google.com/detail/page-agent-ext/akldabonmimlicnjlflnapfeklbfemhj

Latest updates are often published earlier on:

- GitHub Releases: https://github.com/alibaba/page-agent/releases

### 2. Install type definitions (recommended)

```bash
npm install @page-agent/core --save-dev
```

### 3. Authorization (Token)

The token allows your page JS to call the extension API (`window.PAGE_AGENT_EXT`) and execute multi-page tasks.

Why token-based access is required:

- The extension has broad browser permissions (page access, navigation, multi-tab control).
- If abused, it can harm user privacy and security.
- Users must explicitly provide the token only to applications they trust.

Setup:

1. Open the extension side panel and copy your auth token.
2. Set the token in your page:

```typescript
localStorage.setItem('PageAgentExtUserAuthToken', 'your-token')
```

## Quick Start

```typescript
import type { AgentActivity, AgentStatus, ExecutionResult, HistoricalEvent } from '@page-agent/core'

// Wait for extension injection (up to 1 second)
async function waitForExtension(timeout = 1000): Promise {
    const start = Date.now()
    while (Date.now() - start < timeout) {
        if (window.PAGE_AGENT_EXT) return true
        await new Promise((r) => setTimeout(r, 100))
    }
    return false
}

// Usage
if (await waitForExtension()) {
    const result = await window.PAGE_AGENT_EXT!.execute('Click the login button', {
        baseURL: 'https://api.openai.com/v1',
        apiKey: 'your-api-key',
        model: 'gpt-5.2',
        onStatusChange: (status) => console.log('Status:', status),
        onActivity: (activity) => console.log('Activity:', activity),
    })
    console.log('Result:', result)
}
```

## Global API

After token match, the extension injects APIs into `window`.

### `window.PAGE_AGENT_EXT_VERSION`

Extension version string (for capability checks before using the main API).

### `window.PAGE_AGENT_EXT`

Main namespace object.

#### `PAGE_AGENT_EXT.execute(task, config)`

Execute one agent task.

Parameters:

| Name     | Type            | Required | Description                          |
| -------- | --------------- | -------- | ------------------------------------ |
| `task`   | `string`        | Yes      | Task description                     |
| `config` | `ExecuteConfig` | Yes      | LLM settings, options, and callbacks |

Returns: `Promise<ExecutionResult>`

#### `PAGE_AGENT_EXT.stop()`

Stop the current task.

## Limitations

- **Normal browser windows only.** This extension relies on tab group API which does not work for pop-up window or PWA App window.

## Types

Install `@page-agent/core` for complete types:

```typescript
import type { AgentActivity, AgentStatus, ExecutionResult, HistoricalEvent } from '@page-agent/core'

export interface ExecuteConfig {
    baseURL: string
    model: string
    apiKey?: string

    // Global system-level instructions for the agent.
    // Equivalent to AgentConfig.instructions.system.
    systemInstruction?: string

    // Include the initial tab where page JS starts. Default: true.
    includeInitialTab?: boolean

    // Control all unpinned tabs in the window instead of only the tab group.
    // When enabled, agent sees and can switch to every non-pinned tab.
    // Default: false. Experimental.
    experimentalIncludeAllTabs?: boolean

    onStatusChange?: (status: AgentStatus) => void
    onActivity?: (activity: AgentActivity) => void
    onHistoryUpdate?: (history: HistoricalEvent[]) => void
}

export type Execute = (task: string, config: ExecuteConfig) => Promise<ExecutionResult>
```

`AgentStatus`

```typescript
type AgentStatus = 'idle' | 'running' | 'completed' | 'error' | 'stopped'
```

`AgentActivity`

```typescript
type AgentActivity =
    | { type: 'thinking' }
    | { type: 'executing'; tool: string; input: unknown }
    | { type: 'executed'; tool: string; input: unknown; output: string; duration: number }
    | { type: 'retrying'; attempt: number; maxAttempts: number }
    | { type: 'error'; message: string }
```

`HistoricalEvent`

```typescript
type HistoricalEvent =
    | { type: 'step'; stepIndex: number; reflection: AgentReflection; action: Action }
    | { type: 'observation'; content: string }
    | { type: 'user_takeover' }
    | { type: 'retry'; message: string; attempt: number; maxAttempts: number }
    | { type: 'error'; message: string; rawResponse?: unknown }
```

`ExecutionResult`

```typescript
interface ExecutionResult {
    success: boolean
    data: string
    history: HistoricalEvent[]
}
```

## Usage Examples

### Basic Execution

```typescript
const result = await window.PAGE_AGENT_EXT!.execute(
    'Fill in the email field with test@example.com and click Submit',
    {
        baseURL: 'https://api.openai.com/v1',
        apiKey: process.env.OPENAI_API_KEY!,
        model: 'gpt-5.2',
        includeInitialTab: false, // Optional: exclude current tab
        onStatusChange: (status) => console.log(status),
        onActivity: (activity) => console.log(activity),
    }
)
```

### Stop the Current Task

```typescript
window.PAGE_AGENT_EXT!.stop()
```

## Window Type Declaration

If you are not importing `@page-agent/core`, add:

```typescript
import type { AgentActivity, AgentStatus, ExecutionResult, HistoricalEvent } from '@page-agent/core'

interface ExecuteConfig {
    baseURL: string
    model: string
    apiKey?: string

    systemInstruction?: string

    includeInitialTab?: boolean
    experimentalIncludeAllTabs?: boolean
    onStatusChange?: (status: AgentStatus) => void
    onActivity?: (activity: AgentActivity) => void
    onHistoryUpdate?: (history: HistoricalEvent[]) => void
}

declare global {
    interface Window {
        PAGE_AGENT_EXT_VERSION?: string
        PAGE_AGENT_EXT?: {
            version: string
            execute: Execute
            stop: () => void
        }
    }
}
```