Initial commit
This commit is contained in:
commit
52ddc6ba9a
27 files changed
+2166
No files matched your search
+176
@@ -0,0 +1,176 @@
|
|||||||
|
# Created by https://www.toptal.com/developers/gitignore/api/python
|
||||||
|
# Edit at https://www.toptal.com/developers/gitignore?templates=python
|
||||||
|
|
||||||
|
### Python ###
|
||||||
|
# Byte-compiled / optimized / DLL files
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
|
||||||
|
# C extensions
|
||||||
|
*.so
|
||||||
|
|
||||||
|
# Distribution / packaging
|
||||||
|
.Python
|
||||||
|
build/
|
||||||
|
develop-eggs/
|
||||||
|
dist/
|
||||||
|
downloads/
|
||||||
|
eggs/
|
||||||
|
.eggs/
|
||||||
|
lib/
|
||||||
|
lib64/
|
||||||
|
parts/
|
||||||
|
sdist/
|
||||||
|
var/
|
||||||
|
wheels/
|
||||||
|
share/python-wheels/
|
||||||
|
*.egg-info/
|
||||||
|
.installed.cfg
|
||||||
|
*.egg
|
||||||
|
MANIFEST
|
||||||
|
|
||||||
|
# PyInstaller
|
||||||
|
# Usually these files are written by a python script from a template
|
||||||
|
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||||
|
*.manifest
|
||||||
|
*.spec
|
||||||
|
|
||||||
|
# Installer logs
|
||||||
|
pip-log.txt
|
||||||
|
pip-delete-this-directory.txt
|
||||||
|
|
||||||
|
# Unit test / coverage reports
|
||||||
|
htmlcov/
|
||||||
|
.tox/
|
||||||
|
.nox/
|
||||||
|
.coverage
|
||||||
|
.coverage.*
|
||||||
|
.cache
|
||||||
|
nosetests.xml
|
||||||
|
coverage.xml
|
||||||
|
*.cover
|
||||||
|
*.py,cover
|
||||||
|
.hypothesis/
|
||||||
|
.pytest_cache/
|
||||||
|
cover/
|
||||||
|
|
||||||
|
# Translations
|
||||||
|
*.mo
|
||||||
|
*.pot
|
||||||
|
|
||||||
|
# Django stuff:
|
||||||
|
*.log
|
||||||
|
local_settings.py
|
||||||
|
db.sqlite3
|
||||||
|
db.sqlite3-journal
|
||||||
|
|
||||||
|
# Flask stuff:
|
||||||
|
instance/
|
||||||
|
.webassets-cache
|
||||||
|
|
||||||
|
# Scrapy stuff:
|
||||||
|
.scrapy
|
||||||
|
|
||||||
|
# Sphinx documentation
|
||||||
|
docs/_build/
|
||||||
|
|
||||||
|
# PyBuilder
|
||||||
|
.pybuilder/
|
||||||
|
target/
|
||||||
|
|
||||||
|
# Jupyter Notebook
|
||||||
|
.ipynb_checkpoints
|
||||||
|
|
||||||
|
# IPython
|
||||||
|
profile_default/
|
||||||
|
ipython_config.py
|
||||||
|
|
||||||
|
# pyenv
|
||||||
|
# For a library or package, you might want to ignore these files since the code is
|
||||||
|
# intended to run in multiple environments; otherwise, check them in:
|
||||||
|
# .python-version
|
||||||
|
|
||||||
|
# pipenv
|
||||||
|
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||||
|
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||||
|
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||||
|
# install all needed dependencies.
|
||||||
|
#Pipfile.lock
|
||||||
|
|
||||||
|
# poetry
|
||||||
|
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||||
|
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||||
|
# commonly ignored for libraries.
|
||||||
|
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||||
|
#poetry.lock
|
||||||
|
|
||||||
|
# pdm
|
||||||
|
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||||
|
#pdm.lock
|
||||||
|
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||||
|
# in version control.
|
||||||
|
# https://pdm.fming.dev/#use-with-ide
|
||||||
|
.pdm.toml
|
||||||
|
|
||||||
|
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||||
|
__pypackages__/
|
||||||
|
|
||||||
|
# Celery stuff
|
||||||
|
celerybeat-schedule
|
||||||
|
celerybeat.pid
|
||||||
|
|
||||||
|
# SageMath parsed files
|
||||||
|
*.sage.py
|
||||||
|
|
||||||
|
# Environments
|
||||||
|
.env
|
||||||
|
.venv
|
||||||
|
env/
|
||||||
|
venv/
|
||||||
|
ENV/
|
||||||
|
env.bak/
|
||||||
|
venv.bak/
|
||||||
|
|
||||||
|
# Spyder project settings
|
||||||
|
.spyderproject
|
||||||
|
.spyproject
|
||||||
|
|
||||||
|
# Rope project settings
|
||||||
|
.ropeproject
|
||||||
|
|
||||||
|
# mkdocs documentation
|
||||||
|
/site
|
||||||
|
|
||||||
|
# mypy
|
||||||
|
.mypy_cache/
|
||||||
|
.dmypy.json
|
||||||
|
dmypy.json
|
||||||
|
|
||||||
|
# Pyre type checker
|
||||||
|
.pyre/
|
||||||
|
|
||||||
|
# pytype static type analyzer
|
||||||
|
.pytype/
|
||||||
|
|
||||||
|
# Cython debug symbols
|
||||||
|
cython_debug/
|
||||||
|
|
||||||
|
# PyCharm
|
||||||
|
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||||
|
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||||
|
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||||
|
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||||
|
#.idea/
|
||||||
|
|
||||||
|
### Python Patch ###
|
||||||
|
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
|
||||||
|
poetry.toml
|
||||||
|
|
||||||
|
# ruff
|
||||||
|
.ruff_cache/
|
||||||
|
|
||||||
|
# LSP config files
|
||||||
|
pyrightconfig.json
|
||||||
|
|
||||||
|
# End of https://www.toptal.com/developers/gitignore/api/python
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
# Firefox MCP Bridge
|
||||||
|
|
||||||
|
An MCP (Model Context Protocol) server that lets an LLM control a local Firefox instance through a browser extension. Uses a **Bridge Architecture** — no remote debugging, no automation flags — all interactions go through a Firefox extension's content scripts to mimic human behavior.
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
LLM (MCP Client)
|
||||||
|
│ SSE + HTTP POST (port 8008)
|
||||||
|
▼
|
||||||
|
Python Bridge (FastAPI/Starlette)
|
||||||
|
│ WebSocket (ws://127.0.0.1:8008/ws)
|
||||||
|
▼
|
||||||
|
Firefox Extension (Background Script)
|
||||||
|
│ browser.tabs.sendMessage
|
||||||
|
▼
|
||||||
|
Content Script (DOM interaction in web pages)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Directory Layout
|
||||||
|
|
||||||
|
```
|
||||||
|
mcp-firefox-extension/
|
||||||
|
├── bridge/ # Python MCP server
|
||||||
|
│ ├── main.py # Starlette app (SSE + WebSocket)
|
||||||
|
│ ├── mcp_logic.py # MCP protocol + extension correlation
|
||||||
|
│ ├── config.py # Configuration (port 8008, etc.)
|
||||||
|
│ ├── requirements.txt # Python deps
|
||||||
|
│ └── tools/ # MCP tool handlers
|
||||||
|
│ ├── __init__.py # Tool registry
|
||||||
|
│ ├── utils.py # Shared helpers
|
||||||
|
│ ├── page_summary.py
|
||||||
|
│ ├── element_details.py
|
||||||
|
│ ├── click_element.py
|
||||||
|
│ ├── type_text.py
|
||||||
|
│ ├── press_key.py
|
||||||
|
│ ├── scroll_page.py
|
||||||
|
│ ├── execute_script.py
|
||||||
|
│ ├── take_screenshot.py
|
||||||
|
│ ├── read_page_text.py
|
||||||
|
│ ├── list_tabs.py
|
||||||
|
│ ├── switch_tab.py
|
||||||
|
│ ├── navigate_to.py
|
||||||
|
│ ├── open_new_tab.py
|
||||||
|
│ ├── get_current_url.py
|
||||||
|
│ └── get_page_cookies.py
|
||||||
|
├── extension/ # Firefox WebExtension
|
||||||
|
│ ├── manifest.json
|
||||||
|
│ ├── background.js # WebSocket client + browser.* APIs
|
||||||
|
│ └── content.js # DOM scanning + interaction
|
||||||
|
└── README.md
|
||||||
|
```
|
||||||
|
|
||||||
|
## Setup
|
||||||
|
|
||||||
|
### 1. Create a Python virtual environment
|
||||||
|
|
||||||
|
Since your Python is system-managed, create a venv:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /home/matt/code/mcp-firefox-extension
|
||||||
|
python3 -m venv bridge/venv
|
||||||
|
source bridge/venv/bin/activate
|
||||||
|
pip install -r bridge/requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Start the Bridge server
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd /home/matt/code/mcp-firefox-extension/bridge
|
||||||
|
source venv/bin/activate # if not already activated
|
||||||
|
python main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
The server will listen on `http://127.0.0.1:8008` and expose:
|
||||||
|
- `GET /sse` — MCP SSE endpoint
|
||||||
|
- `POST /messages` — MCP message endpoint
|
||||||
|
- `WS /ws` — WebSocket for the Firefox extension
|
||||||
|
|
||||||
|
### 3. Load the Firefox Extension
|
||||||
|
|
||||||
|
1. Open Firefox and go to `about:debugging`
|
||||||
|
2. Click **"This Firefox"** in the left sidebar
|
||||||
|
3. Click **"Load Temporary Add-on..."**
|
||||||
|
4. Select the `extension/manifest.json` file from this project
|
||||||
|
5. The extension will attempt to connect to `ws://127.0.0.1:8008/ws` automatically
|
||||||
|
|
||||||
|
You should see "Firefox extension connected via WebSocket" in the bridge server logs.
|
||||||
|
|
||||||
|
> **Note:** Temporary add-ons are cleared when Firefox restarts. You'll need to reload the add-on via `about:debugging` after each browser restart.
|
||||||
|
|
||||||
|
### 4. Connect your LLM client
|
||||||
|
|
||||||
|
Point your MCP client at the SSE endpoint:
|
||||||
|
- SSE URL: `http://127.0.0.1:8008/sse`
|
||||||
|
- Message URL: `http://127.0.0.1:8008/messages?session_id=<session-id>`
|
||||||
|
|
||||||
|
The session ID is provided in the first SSE event (`event: endpoint`).
|
||||||
|
|
||||||
|
## Available MCP Tools
|
||||||
|
|
||||||
|
| Tool | Description |
|
||||||
|
|------|-------------|
|
||||||
|
| `get_page_summary` | Scans the page and indexes interactive elements (buttons, links, inputs, etc.) with `data-mcp-id` attributes |
|
||||||
|
| `get_element_details(id)` | Returns detailed attributes, HTML, bounding box, and computed style for an element |
|
||||||
|
| `click_element(id)` | Clicks the element with the given mcp-id |
|
||||||
|
| `type_text(id, text)` | Focuses an element and types text into it |
|
||||||
|
| `press_key(key)` | Simulates a keyboard key press (Enter, Escape, Tab, etc.) |
|
||||||
|
| `scroll_page(direction, amount)` | Scrolls up/down/left/right by pixels or percentage |
|
||||||
|
| `execute_script(js_code)` | Executes arbitrary JavaScript in the page (God Mode) |
|
||||||
|
| `take_screenshot()` | Captures a PNG screenshot of the viewport |
|
||||||
|
| `read_page_text()` | Returns reader-mode text content of the page |
|
||||||
|
| `list_tabs()` | Lists all open Firefox tabs |
|
||||||
|
| `switch_tab(tab_id)` | Switches to a specific tab by ID |
|
||||||
|
| `navigate_to(url)` | Navigates the active tab to a URL |
|
||||||
|
| `open_new_tab(url)` | Opens a new tab |
|
||||||
|
| `get_current_url()` | Returns the current active tab's URL |
|
||||||
|
| `get_page_cookies()` | Returns cookies for the current domain |
|
||||||
|
|
||||||
|
## How Element Indexing Works
|
||||||
|
|
||||||
|
When `get_page_summary` is called, the content script:
|
||||||
|
1. Queries all interactive elements (`button`, `a`, `input`, `select`, `textarea`, elements with `role` attributes, `onclick` handlers, or `contenteditable`)
|
||||||
|
2. Assigns each a unique `data-mcp-id` attribute (e.g., `data-mcp-id="1"`)
|
||||||
|
3. Returns a list with id, role, visible text, tag name, and other attributes
|
||||||
|
|
||||||
|
All subsequent interaction tools reference elements by this `mcp-id`, so you never need fragile CSS selectors.
|
||||||
|
|
||||||
|
## Stealth
|
||||||
|
|
||||||
|
- No `remote-debugging-port` is used
|
||||||
|
- No `automation` flags are set
|
||||||
|
- All DOM interactions are triggered by the extension's content scripts, which run in the same context as normal page scripts
|
||||||
|
- The extension appears as a normal Firefox add-on
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
| Issue | Solution |
|
||||||
|
|-------|----------|
|
||||||
|
| "Firefox extension is not connected" | Make sure the bridge is running (`python main.py`) and the extension is loaded via `about:debugging`. Check the bridge logs for WebSocket connection messages. |
|
||||||
|
| "Content script not available in this tab" | Refresh the page or navigate to a different URL. Content scripts are injected on page load. |
|
||||||
|
| Extension won't load | Make sure you're using Firefox (not Chrome). Manifest V2 is used for better Firefox compatibility. |
|
||||||
|
| `port 8008 already in use` | Change `config.PORT` in `bridge/config.py` to another free port. |
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT — "vibe-coded" prototype, use at your own risk.
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
# Created by https://www.toptal.com/developers/gitignore/api/python
|
||||||
|
# Edit at https://www.toptal.com/developers/gitignore?templates=python
|
||||||
|
|
||||||
|
### Python ###
|
||||||
|
# Byte-compiled / optimized / DLL files
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
|
||||||
|
# C extensions
|
||||||
|
*.so
|
||||||
|
|
||||||
|
# Distribution / packaging
|
||||||
|
.Python
|
||||||
|
build/
|
||||||
|
develop-eggs/
|
||||||
|
dist/
|
||||||
|
downloads/
|
||||||
|
eggs/
|
||||||
|
.eggs/
|
||||||
|
lib/
|
||||||
|
lib64/
|
||||||
|
parts/
|
||||||
|
sdist/
|
||||||
|
var/
|
||||||
|
wheels/
|
||||||
|
share/python-wheels/
|
||||||
|
*.egg-info/
|
||||||
|
.installed.cfg
|
||||||
|
*.egg
|
||||||
|
MANIFEST
|
||||||
|
|
||||||
|
# PyInstaller
|
||||||
|
# Usually these files are written by a python script from a template
|
||||||
|
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||||
|
*.manifest
|
||||||
|
*.spec
|
||||||
|
|
||||||
|
# Installer logs
|
||||||
|
pip-log.txt
|
||||||
|
pip-delete-this-directory.txt
|
||||||
|
|
||||||
|
# Unit test / coverage reports
|
||||||
|
htmlcov/
|
||||||
|
.tox/
|
||||||
|
.nox/
|
||||||
|
.coverage
|
||||||
|
.coverage.*
|
||||||
|
.cache
|
||||||
|
nosetests.xml
|
||||||
|
coverage.xml
|
||||||
|
*.cover
|
||||||
|
*.py,cover
|
||||||
|
.hypothesis/
|
||||||
|
.pytest_cache/
|
||||||
|
cover/
|
||||||
|
|
||||||
|
# Translations
|
||||||
|
*.mo
|
||||||
|
*.pot
|
||||||
|
|
||||||
|
# Django stuff:
|
||||||
|
*.log
|
||||||
|
local_settings.py
|
||||||
|
db.sqlite3
|
||||||
|
db.sqlite3-journal
|
||||||
|
|
||||||
|
# Flask stuff:
|
||||||
|
instance/
|
||||||
|
.webassets-cache
|
||||||
|
|
||||||
|
# Scrapy stuff:
|
||||||
|
.scrapy
|
||||||
|
|
||||||
|
# Sphinx documentation
|
||||||
|
docs/_build/
|
||||||
|
|
||||||
|
# PyBuilder
|
||||||
|
.pybuilder/
|
||||||
|
target/
|
||||||
|
|
||||||
|
# Jupyter Notebook
|
||||||
|
.ipynb_checkpoints
|
||||||
|
|
||||||
|
# IPython
|
||||||
|
profile_default/
|
||||||
|
ipython_config.py
|
||||||
|
|
||||||
|
# pyenv
|
||||||
|
# For a library or package, you might want to ignore these files since the code is
|
||||||
|
# intended to run in multiple environments; otherwise, check them in:
|
||||||
|
# .python-version
|
||||||
|
|
||||||
|
# pipenv
|
||||||
|
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||||
|
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||||
|
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||||
|
# install all needed dependencies.
|
||||||
|
#Pipfile.lock
|
||||||
|
|
||||||
|
# poetry
|
||||||
|
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||||
|
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||||
|
# commonly ignored for libraries.
|
||||||
|
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||||
|
#poetry.lock
|
||||||
|
|
||||||
|
# pdm
|
||||||
|
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||||
|
#pdm.lock
|
||||||
|
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||||
|
# in version control.
|
||||||
|
# https://pdm.fming.dev/#use-with-ide
|
||||||
|
.pdm.toml
|
||||||
|
|
||||||
|
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||||
|
__pypackages__/
|
||||||
|
|
||||||
|
# Celery stuff
|
||||||
|
celerybeat-schedule
|
||||||
|
celerybeat.pid
|
||||||
|
|
||||||
|
# SageMath parsed files
|
||||||
|
*.sage.py
|
||||||
|
|
||||||
|
# Environments
|
||||||
|
.env
|
||||||
|
.venv
|
||||||
|
env/
|
||||||
|
venv/
|
||||||
|
ENV/
|
||||||
|
env.bak/
|
||||||
|
venv.bak/
|
||||||
|
|
||||||
|
# Spyder project settings
|
||||||
|
.spyderproject
|
||||||
|
.spyproject
|
||||||
|
|
||||||
|
# Rope project settings
|
||||||
|
.ropeproject
|
||||||
|
|
||||||
|
# mkdocs documentation
|
||||||
|
/site
|
||||||
|
|
||||||
|
# mypy
|
||||||
|
.mypy_cache/
|
||||||
|
.dmypy.json
|
||||||
|
dmypy.json
|
||||||
|
|
||||||
|
# Pyre type checker
|
||||||
|
.pyre/
|
||||||
|
|
||||||
|
# pytype static type analyzer
|
||||||
|
.pytype/
|
||||||
|
|
||||||
|
# Cython debug symbols
|
||||||
|
cython_debug/
|
||||||
|
|
||||||
|
# PyCharm
|
||||||
|
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||||
|
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||||
|
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||||
|
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||||
|
#.idea/
|
||||||
|
|
||||||
|
### Python Patch ###
|
||||||
|
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
|
||||||
|
poetry.toml
|
||||||
|
|
||||||
|
# ruff
|
||||||
|
.ruff_cache/
|
||||||
|
|
||||||
|
# LSP config files
|
||||||
|
pyrightconfig.json
|
||||||
|
|
||||||
|
# End of https://www.toptal.com/developers/gitignore/api/python
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
from contextvars import ContextVar
|
||||||
|
|
||||||
|
# --- Project Root ---
|
||||||
|
ROOT_DIR = Path(__file__).parent.resolve()
|
||||||
|
|
||||||
|
# --- Server & Logs ---
|
||||||
|
HOST = "127.0.0.1"
|
||||||
|
PORT = 8008
|
||||||
|
request_host = ContextVar("request_host", default=f"{HOST}:{PORT}")
|
||||||
|
LOG_LEVEL = "INFO"
|
||||||
|
LOG_FILE = str(ROOT_DIR / "debug.log")
|
||||||
|
|
||||||
|
# --- WebSocket (Extension) ---
|
||||||
|
WS_PATH = "/ws"
|
||||||
|
WS_TIMEOUT = 30 # seconds to wait for extension response
|
||||||
|
|
||||||
|
# --- Extension ---
|
||||||
|
EXTENSION_DIR = ROOT_DIR.parent / "extension"
|
||||||
+179
@@ -0,0 +1,179 @@
|
|||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
import signal
|
||||||
|
import sys
|
||||||
|
import json
|
||||||
|
|
||||||
|
import uvicorn
|
||||||
|
from starlette.applications import Starlette
|
||||||
|
from starlette.routing import Route, WebSocketRoute
|
||||||
|
from starlette.responses import Response, StreamingResponse
|
||||||
|
from starlette.middleware.cors import CORSMiddleware
|
||||||
|
from starlette.websockets import WebSocket, WebSocketDisconnect
|
||||||
|
|
||||||
|
from mcp_logic import MCPBridge
|
||||||
|
from tools import TOOL_REGISTRY
|
||||||
|
import config
|
||||||
|
|
||||||
|
|
||||||
|
# --- Configuration & Logging ---
|
||||||
|
logging.basicConfig(
|
||||||
|
level=getattr(logging, config.LOG_LEVEL),
|
||||||
|
filename=config.LOG_FILE,
|
||||||
|
filemode="a",
|
||||||
|
format="%(asctime)s - %(levelname)s - %(message)s",
|
||||||
|
)
|
||||||
|
logger = logging.getLogger("FirefoxMCP")
|
||||||
|
|
||||||
|
bridge = MCPBridge()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# SSE Transport (for MCP clients / LLMs)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
async def sse_endpoint(request):
|
||||||
|
"""SSE endpoint: MCP clients connect here to receive responses."""
|
||||||
|
sid = bridge.create_session()
|
||||||
|
logger.debug(f"SSE session started: {sid}")
|
||||||
|
|
||||||
|
async def event_generator():
|
||||||
|
try:
|
||||||
|
# Tell the client where to POST messages
|
||||||
|
yield f"event: endpoint\ndata: /messages?session_id={sid}\n\n"
|
||||||
|
queue = bridge.sessions[sid]
|
||||||
|
while bridge.running:
|
||||||
|
try:
|
||||||
|
msg = await asyncio.wait_for(queue.get(), timeout=0.5)
|
||||||
|
yield f"event: message\ndata: {msg}\n\n"
|
||||||
|
queue.task_done()
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
continue
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
logger.debug(f"SSE session cancelled: {sid}")
|
||||||
|
finally:
|
||||||
|
bridge.sessions.pop(sid, None)
|
||||||
|
logger.debug(f"SSE session closed: {sid}")
|
||||||
|
|
||||||
|
return StreamingResponse(event_generator(), media_type="text/event-stream")
|
||||||
|
|
||||||
|
|
||||||
|
async def messages_endpoint(request):
|
||||||
|
"""HTTP POST endpoint: MCP clients send tool calls here."""
|
||||||
|
sid = request.query_params.get("session_id")
|
||||||
|
if not sid or sid not in bridge.sessions:
|
||||||
|
return Response("Session not found", status_code=404)
|
||||||
|
|
||||||
|
# Capture host header for any URL generation
|
||||||
|
host_header = request.headers.get("host", f"{config.HOST}:{config.PORT}")
|
||||||
|
config.request_host.set(host_header)
|
||||||
|
|
||||||
|
try:
|
||||||
|
body = await request.json()
|
||||||
|
except Exception as e:
|
||||||
|
return Response(f"Invalid JSON: {e}", status_code=400)
|
||||||
|
|
||||||
|
method = body.get("method")
|
||||||
|
params = body.get("params", {})
|
||||||
|
req_id = body.get("id")
|
||||||
|
|
||||||
|
logger.debug(f"MCP Request: {method} (ID: {req_id})")
|
||||||
|
|
||||||
|
result = await bridge.handle_request(method, params, req_id, TOOL_REGISTRY)
|
||||||
|
|
||||||
|
if isinstance(result, Response):
|
||||||
|
return result
|
||||||
|
|
||||||
|
# Send the result back via SSE
|
||||||
|
await bridge.send_to_session(
|
||||||
|
sid,
|
||||||
|
{"jsonrpc": "2.0", "id": req_id, "result": result},
|
||||||
|
)
|
||||||
|
return Response(status_code=202)
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# WebSocket Transport (for the Firefox Extension)
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
async def extension_websocket(websocket: WebSocket):
|
||||||
|
"""WebSocket endpoint: the Firefox extension connects here."""
|
||||||
|
await websocket.accept()
|
||||||
|
bridge.set_extension_websocket(websocket)
|
||||||
|
logger.info("Firefox extension connected via WebSocket")
|
||||||
|
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
data = await websocket.receive_text()
|
||||||
|
try:
|
||||||
|
msg = json.loads(data)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
logger.error(f"Invalid JSON from extension: {data}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
msg_type = msg.get("type")
|
||||||
|
request_id = msg.get("request_id")
|
||||||
|
|
||||||
|
if msg_type == "response":
|
||||||
|
result = msg.get("result")
|
||||||
|
error = msg.get("error")
|
||||||
|
bridge.handle_extension_response(request_id, result=result, error=error)
|
||||||
|
logger.debug(f"Extension response for {request_id}: {'error' if error else 'ok'}")
|
||||||
|
elif msg_type == "register":
|
||||||
|
logger.debug(f"Extension registered: {msg}")
|
||||||
|
else:
|
||||||
|
logger.warning(f"Unknown message type from extension: {msg_type}")
|
||||||
|
|
||||||
|
except WebSocketDisconnect:
|
||||||
|
logger.info("Firefox extension disconnected")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"WebSocket error: {e}")
|
||||||
|
finally:
|
||||||
|
bridge.remove_extension_websocket()
|
||||||
|
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Starlette App
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
app = Starlette(
|
||||||
|
routes=[
|
||||||
|
Route("/sse", endpoint=sse_endpoint),
|
||||||
|
Route("/messages", endpoint=messages_endpoint, methods=["POST"]),
|
||||||
|
WebSocketRoute(config.WS_PATH, endpoint=extension_websocket),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Entry point
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
if __name__ == "__main__":
|
||||||
|
uvicorn_config = uvicorn.Config(
|
||||||
|
app=app,
|
||||||
|
host=config.HOST,
|
||||||
|
port=config.PORT,
|
||||||
|
log_level="info",
|
||||||
|
timeout_graceful_shutdown=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
server = uvicorn.Server(uvicorn_config)
|
||||||
|
|
||||||
|
def signal_handler(sig, frame):
|
||||||
|
logger.info("Shutdown signal received")
|
||||||
|
bridge.running = False
|
||||||
|
server.should_exit = True
|
||||||
|
|
||||||
|
signal.signal(signal.SIGINT, signal_handler)
|
||||||
|
signal.signal(signal.SIGTERM, signal_handler)
|
||||||
|
|
||||||
|
try:
|
||||||
|
asyncio.run(server.serve())
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
pass
|
||||||
|
finally:
|
||||||
|
logger.info("Server process exiting.")
|
||||||
|
sys.exit(0)
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
import asyncio
|
||||||
|
import uuid
|
||||||
|
import json
|
||||||
|
from typing import Any, Dict, Union, List, Optional
|
||||||
|
from starlette.responses import Response
|
||||||
|
from starlette.websockets import WebSocket
|
||||||
|
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
|
||||||
|
class MCPBridge:
|
||||||
|
"""
|
||||||
|
The Bridge between MCP clients (LLMs) and the Firefox Extension.
|
||||||
|
|
||||||
|
Manages:
|
||||||
|
- SSE sessions for MCP clients
|
||||||
|
- WebSocket connection from the Firefox extension
|
||||||
|
- Correlation of MCP tool calls with extension responses
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
# SSE sessions: session_id -> asyncio.Queue
|
||||||
|
self.sessions: Dict[str, asyncio.Queue] = {}
|
||||||
|
self.running = True
|
||||||
|
|
||||||
|
# WebSocket connection from the Firefox extension
|
||||||
|
self.extension_ws: Optional[WebSocket] = None
|
||||||
|
|
||||||
|
# Pending requests: request_id -> asyncio.Future
|
||||||
|
self.pending_requests: Dict[str, asyncio.Future] = {}
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# SSE session management
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def create_session(self) -> str:
|
||||||
|
sid = str(uuid.uuid4())
|
||||||
|
self.sessions[sid] = asyncio.Queue()
|
||||||
|
return sid
|
||||||
|
|
||||||
|
async def send_to_session(self, sid: str, message: Dict[str, Any]):
|
||||||
|
if sid in self.sessions:
|
||||||
|
await self.sessions[sid].put(json.dumps(message))
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Extension WebSocket management
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def set_extension_websocket(self, ws: WebSocket):
|
||||||
|
self.extension_ws = ws
|
||||||
|
|
||||||
|
def remove_extension_websocket(self):
|
||||||
|
self.extension_ws = None
|
||||||
|
# Cancel all pending requests since the extension is gone
|
||||||
|
for fut in self.pending_requests.values():
|
||||||
|
if not fut.done():
|
||||||
|
fut.set_exception(Exception("Firefox extension disconnected"))
|
||||||
|
self.pending_requests.clear()
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Send a request to the extension and wait for its response
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
async def send_to_extension(
|
||||||
|
self,
|
||||||
|
request_id: str,
|
||||||
|
action: str,
|
||||||
|
params: Dict[str, Any],
|
||||||
|
timeout: float = 30.0,
|
||||||
|
) -> Any:
|
||||||
|
if not self.extension_ws:
|
||||||
|
raise ToolError(
|
||||||
|
"Firefox extension is not connected. "
|
||||||
|
"Load the extension in Firefox (about:debugging) and ensure it connects to ws://127.0.0.1:8008/ws"
|
||||||
|
)
|
||||||
|
|
||||||
|
loop = asyncio.get_event_loop()
|
||||||
|
future: asyncio.Future = loop.create_future()
|
||||||
|
self.pending_requests[request_id] = future
|
||||||
|
|
||||||
|
message = json.dumps({
|
||||||
|
"type": "request",
|
||||||
|
"request_id": request_id,
|
||||||
|
"action": action,
|
||||||
|
"params": params,
|
||||||
|
})
|
||||||
|
|
||||||
|
try:
|
||||||
|
await self.extension_ws.send_text(message)
|
||||||
|
result = await asyncio.wait_for(future, timeout=timeout)
|
||||||
|
return result
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
raise ToolError(f"Extension did not respond to '{action}' within {timeout:.0f} seconds")
|
||||||
|
finally:
|
||||||
|
self.pending_requests.pop(request_id, None)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# Called by the WebSocket handler when the extension responds
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
def handle_extension_response(self, request_id: str, result: Any = None, error: Optional[str] = None):
|
||||||
|
future = self.pending_requests.get(request_id)
|
||||||
|
if future and not future.done():
|
||||||
|
if error:
|
||||||
|
future.set_exception(Exception(error))
|
||||||
|
else:
|
||||||
|
future.set_result(result)
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
# MCP protocol request handling
|
||||||
|
# ------------------------------------------------------------------
|
||||||
|
async def handle_request(
|
||||||
|
self,
|
||||||
|
method: str,
|
||||||
|
params: Dict[str, Any],
|
||||||
|
req_id: Any,
|
||||||
|
tool_registry: List[Any],
|
||||||
|
) -> Union[Dict[str, Any], Response]:
|
||||||
|
if method == "initialize":
|
||||||
|
return {
|
||||||
|
"protocolVersion": "2024-11-05",
|
||||||
|
"capabilities": {"tools": {}},
|
||||||
|
"serverInfo": {"name": "FirefoxMCP", "version": "0.1.0"},
|
||||||
|
}
|
||||||
|
|
||||||
|
if method == "tools/list":
|
||||||
|
return {"tools": [t.to_mcp_dict() for t in tool_registry]}
|
||||||
|
|
||||||
|
if method == "tools/call":
|
||||||
|
name = params.get("name")
|
||||||
|
args = params.get("arguments", {})
|
||||||
|
|
||||||
|
tool = next((t for t in tool_registry if t.name == name), None)
|
||||||
|
if not tool:
|
||||||
|
return Response(
|
||||||
|
content=json.dumps(
|
||||||
|
{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": req_id,
|
||||||
|
"error": {"code": -32601, "message": f"Tool {name} not found"},
|
||||||
|
}
|
||||||
|
),
|
||||||
|
media_type="application/json",
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Pass the bridge instance as the second argument so tools can
|
||||||
|
# send commands to the Firefox extension.
|
||||||
|
content = await tool.handler(args, self)
|
||||||
|
except ToolError as e:
|
||||||
|
content = [{"type": "text", "text": str(e)}]
|
||||||
|
except Exception as e:
|
||||||
|
content = [{"type": "text", "text": f"Unexpected internal error: {str(e)}"}]
|
||||||
|
|
||||||
|
return {"content": content}
|
||||||
|
|
||||||
|
return Response(
|
||||||
|
content=json.dumps(
|
||||||
|
{
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": req_id,
|
||||||
|
"error": {"code": -32601, "message": f"Method {method} not found"},
|
||||||
|
}
|
||||||
|
),
|
||||||
|
media_type="application/json",
|
||||||
|
)
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
uvicorn[standard]
|
||||||
|
starlette
|
||||||
|
websockets
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
from typing import Any, Callable, Dict
|
||||||
|
|
||||||
|
|
||||||
|
class Tool:
|
||||||
|
def __init__(self, name: str, description: str, schema: Dict[str, Any], handler: Callable):
|
||||||
|
self.name = name
|
||||||
|
self.description = description
|
||||||
|
self.schema = schema
|
||||||
|
self.handler = handler
|
||||||
|
|
||||||
|
def to_mcp_dict(self):
|
||||||
|
return {
|
||||||
|
"name": self.name,
|
||||||
|
"description": self.description,
|
||||||
|
"inputSchema": self.schema
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
from .page_summary import handle as get_page_summary_handler
|
||||||
|
from .element_details import handle as get_element_details_handler
|
||||||
|
from .click_element import handle as click_element_handler
|
||||||
|
from .type_text import handle as type_text_handler
|
||||||
|
from .press_key import handle as press_key_handler
|
||||||
|
from .scroll_page import handle as scroll_page_handler
|
||||||
|
from .execute_script import handle as execute_script_handler
|
||||||
|
from .take_screenshot import handle as take_screenshot_handler
|
||||||
|
from .read_page_text import handle as read_page_text_handler
|
||||||
|
from .list_tabs import handle as list_tabs_handler
|
||||||
|
from .switch_tab import handle as switch_tab_handler
|
||||||
|
from .navigate_to import handle as navigate_to_handler
|
||||||
|
from .open_new_tab import handle as open_new_tab_handler
|
||||||
|
from .get_current_url import handle as get_current_url_handler
|
||||||
|
from .get_page_cookies import handle as get_page_cookies_handler
|
||||||
|
|
||||||
|
TOOL_REGISTRY = [
|
||||||
|
Tool(
|
||||||
|
name="get_page_summary",
|
||||||
|
description="Returns a condensed 'Accessibility Tree' of the current page. Scans for interactive elements (buttons, links, inputs, etc.), assigns a temporary unique ID (data-mcp-id), and returns a simplified list with role and visible text/label.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to scan"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the tab to scan"},
|
||||||
|
},
|
||||||
|
"required": [],
|
||||||
|
},
|
||||||
|
handler=get_page_summary_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="get_element_details",
|
||||||
|
description="Returns detailed attributes, value, bounding box, computed style, and surrounding HTML context for a specific element mcp-id.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": {"type": "integer", "description": "The mcp-id of the element to inspect"},
|
||||||
|
"tab_id": {"type": "integer", "description": "The Firefox Tab ID containing the element"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the element"},
|
||||||
|
},
|
||||||
|
"required": ["id"],
|
||||||
|
},
|
||||||
|
handler=get_element_details_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="click_element",
|
||||||
|
description="Performs a click action on the element with the specified mcp-id.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": {"type": "integer", "description": "The mcp-id of the element to click"},
|
||||||
|
"tab_id": {"type": "integer", "description": "The Firefox Tab ID containing the element"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the element"},
|
||||||
|
},
|
||||||
|
"required": ["id"],
|
||||||
|
},
|
||||||
|
handler=click_element_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="type_text",
|
||||||
|
description="Focuses the element with the specified mcp-id and types the provided text into it.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"id": {"type": "integer", "description": "The mcp-id of the element to type into"},
|
||||||
|
"text": {"type": "string", "description": "The text to type"},
|
||||||
|
"tab_id": {"type": "integer", "description": "The Firefox Tab ID containing the element"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the element"},
|
||||||
|
},
|
||||||
|
"required": ["id", "text"],
|
||||||
|
},
|
||||||
|
handler=type_text_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="press_key",
|
||||||
|
description="Simulates a keyboard press on the currently focused element (e.g., 'Enter', 'Escape', 'Tab', 'ArrowDown').",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"key": {"type": "string", "description": "The key to press (e.g., 'Enter', 'Escape', 'Tab')"},
|
||||||
|
"tab_id": {"type": "integer", "description": "The Firefox Tab ID containing the element"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the element"},
|
||||||
|
},
|
||||||
|
"required": ["key"],
|
||||||
|
},
|
||||||
|
handler=press_key_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="scroll_page",
|
||||||
|
description="Scrolls the page by a specified direction and amount. Amount can be pixels or a percentage (1-100) of the viewport.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"direction": {"type": "string", "description": "Direction to scroll: 'up', 'down', 'left', 'right'", "enum": ["up", "down", "left", "right"]},
|
||||||
|
"amount": {"type": "integer", "description": "Pixels to scroll, or a percentage (1-100) of viewport size", "default": 500},
|
||||||
|
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to scroll"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID to scroll"},
|
||||||
|
},
|
||||||
|
"required": ["direction"],
|
||||||
|
},
|
||||||
|
handler=scroll_page_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="execute_script",
|
||||||
|
description="Executes arbitrary JavaScript in the context of the current page. (God Mode - use with caution).",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"js_code": {"type": "string", "description": "JavaScript code to execute"},
|
||||||
|
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to execute in"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID to execute in"},
|
||||||
|
},
|
||||||
|
"required": ["js_code"],
|
||||||
|
},
|
||||||
|
handler=execute_script_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="take_screenshot",
|
||||||
|
description="Captures a screenshot of the current viewport in a window and returns it as a data URL (PNG). Can only capture the visible tab in a window.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID to capture (uses the visible tab in that window)"},
|
||||||
|
},
|
||||||
|
"required": [],
|
||||||
|
},
|
||||||
|
handler=take_screenshot_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="read_page_text",
|
||||||
|
description="Returns a 'Reader Mode' version of the page, stripping scripts, styles, nav, headers, footers, and returning only the primary textual content.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to read"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID to read"},
|
||||||
|
},
|
||||||
|
"required": [],
|
||||||
|
},
|
||||||
|
handler=read_page_text_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="list_tabs",
|
||||||
|
description="Lists all open Firefox tabs, including their titles, URLs, internal Tab IDs, and active status.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {},
|
||||||
|
"required": [],
|
||||||
|
},
|
||||||
|
handler=list_tabs_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="switch_tab",
|
||||||
|
description="Switches focus to the specified Tab ID or Window ID.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to switch to"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID to switch to (switches to active tab in that window)"},
|
||||||
|
},
|
||||||
|
"required": [],
|
||||||
|
},
|
||||||
|
handler=switch_tab_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="navigate_to",
|
||||||
|
description="Navigates the specified tab to the specified URL.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"url": {"type": "string", "description": "The URL to navigate to"},
|
||||||
|
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to navigate"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the tab to navigate"},
|
||||||
|
},
|
||||||
|
"required": ["url"],
|
||||||
|
},
|
||||||
|
handler=navigate_to_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="open_new_tab",
|
||||||
|
description="Opens a new tab with the specified URL.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"url": {"type": "string", "description": "The URL to open in the new tab"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID to open the new tab in"},
|
||||||
|
},
|
||||||
|
"required": ["url"],
|
||||||
|
},
|
||||||
|
handler=open_new_tab_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="get_current_url",
|
||||||
|
description="Returns the current URL of the specified tab or the active tab.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to get the URL from"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the tab to get the URL from"},
|
||||||
|
},
|
||||||
|
"required": [],
|
||||||
|
},
|
||||||
|
handler=get_current_url_handler
|
||||||
|
),
|
||||||
|
Tool(
|
||||||
|
name="get_page_cookies",
|
||||||
|
description="Retrieves cookies for the specified tab or current domain.",
|
||||||
|
schema={
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to get cookies from"},
|
||||||
|
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the tab to get cookies from"},
|
||||||
|
},
|
||||||
|
"required": [],
|
||||||
|
},
|
||||||
|
handler=get_page_cookies_handler
|
||||||
|
),
|
||||||
|
]
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Clicks the element with the specified mcp-id.
|
||||||
|
"""
|
||||||
|
eid = args.get("id")
|
||||||
|
if eid is None:
|
||||||
|
raise ToolError("Missing required argument: 'id'")
|
||||||
|
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {"id": int(eid)}
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
if args.get("tab_id") is not None:
|
||||||
|
params["tab_id"] = int(args["tab_id"])
|
||||||
|
|
||||||
|
await bridge.send_to_extension(request_id, "click_element", params)
|
||||||
|
|
||||||
|
return [{"type": "text", "text": f"Clicked element with mcp-id={eid}."}]
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Returns detailed attributes and HTML for a specific element mcp-id.
|
||||||
|
"""
|
||||||
|
eid = args.get("id")
|
||||||
|
if eid is None:
|
||||||
|
raise ToolError("Missing required argument: 'id'")
|
||||||
|
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {"id": int(eid)}
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
if args.get("tab_id") is not None:
|
||||||
|
params["tab_id"] = int(args["tab_id"])
|
||||||
|
|
||||||
|
result = await bridge.send_to_extension(request_id, "get_element_details", params)
|
||||||
|
|
||||||
|
if not result:
|
||||||
|
raise ToolError(f"Element with mcp-id {eid} not found or has no details")
|
||||||
|
|
||||||
|
lines = [f"# Element Details (mcp-id={eid})\n"]
|
||||||
|
|
||||||
|
for key, value in result.items():
|
||||||
|
if key == "html":
|
||||||
|
lines.append(f"## HTML\n```html\n{value}\n```")
|
||||||
|
elif key == "bounding_box":
|
||||||
|
lines.append(f"## Bounding Box\n- x: {value.get('x', 'N/A')}\n- y: {value.get('y', 'N/A')}\n- width: {value.get('width', 'N/A')}\n- height: {value.get('height', 'N/A')}")
|
||||||
|
elif key == "attributes" and isinstance(value, dict):
|
||||||
|
lines.append("## Attributes")
|
||||||
|
for k, v in value.items():
|
||||||
|
lines.append(f"- {k}: {v}")
|
||||||
|
else:
|
||||||
|
lines.append(f"- **{key}**: {value}")
|
||||||
|
|
||||||
|
return [{"type": "text", "text": "\n".join(lines)}]
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Executes arbitrary JavaScript in the current page.
|
||||||
|
"""
|
||||||
|
js_code = args.get("js_code")
|
||||||
|
if not js_code:
|
||||||
|
raise ToolError("Missing required argument: 'js_code'")
|
||||||
|
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {"js_code": str(js_code)}
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
if args.get("tab_id") is not None:
|
||||||
|
params["tab_id"] = int(args["tab_id"])
|
||||||
|
|
||||||
|
result = await bridge.send_to_extension(request_id, "execute_script", params)
|
||||||
|
|
||||||
|
output = result.get("result", "") if isinstance(result, dict) else str(result)
|
||||||
|
|
||||||
|
return [{"type": "text", "text": f"Script result:\n{output}"}]
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Returns the current URL of the specified tab or the active tab.
|
||||||
|
"""
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {}
|
||||||
|
if args.get("tab_id") is not None:
|
||||||
|
params["tab_id"] = int(args["tab_id"])
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
|
||||||
|
result = await bridge.send_to_extension(request_id, "get_current_url", params)
|
||||||
|
|
||||||
|
url = result.get("url", "unknown") if isinstance(result, dict) else str(result)
|
||||||
|
|
||||||
|
return [{"type": "text", "text": f"Current URL: {url}"}]
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Retrieves cookies for the specified tab or current domain.
|
||||||
|
"""
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {}
|
||||||
|
if args.get("tab_id") is not None:
|
||||||
|
params["tab_id"] = int(args["tab_id"])
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
|
||||||
|
result = await bridge.send_to_extension(request_id, "get_page_cookies", params)
|
||||||
|
|
||||||
|
cookies = result if isinstance(result, list) else []
|
||||||
|
|
||||||
|
lines = ["# Page Cookies\n"]
|
||||||
|
if not cookies:
|
||||||
|
lines.append("No cookies found for this domain.")
|
||||||
|
else:
|
||||||
|
for c in cookies:
|
||||||
|
name = c.get("name", "")
|
||||||
|
value = c.get("value", "")
|
||||||
|
domain = c.get("domain", "")
|
||||||
|
path = c.get("path", "")
|
||||||
|
secure = "Secure" if c.get("secure") else ""
|
||||||
|
http_only = "HttpOnly" if c.get("httpOnly") else ""
|
||||||
|
session = "Session" if c.get("session") else ""
|
||||||
|
flags = " | ".join([f for f in [secure, http_only, session] if f])
|
||||||
|
lines.append(f"- **{name}**: {value} (domain={domain}, path={path}) {flags}")
|
||||||
|
|
||||||
|
return [{"type": "text", "text": "\n".join(lines)}]
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Lists all open Firefox tabs.
|
||||||
|
"""
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
result = await bridge.send_to_extension(request_id, "list_tabs", {})
|
||||||
|
|
||||||
|
tabs = result if isinstance(result, list) else []
|
||||||
|
|
||||||
|
lines = ["# Open Tabs\n"]
|
||||||
|
if not tabs:
|
||||||
|
lines.append("No tabs found.")
|
||||||
|
else:
|
||||||
|
for tab in tabs:
|
||||||
|
tid = tab.get("id", "?")
|
||||||
|
title = tab.get("title", "(no title)")
|
||||||
|
url = tab.get("url", "")
|
||||||
|
active = " (ACTIVE)" if tab.get("active") else ""
|
||||||
|
wid = tab.get("windowId", "?")
|
||||||
|
lines.append(f"- **Tab {tid}** (window {wid}): {title}{active}")
|
||||||
|
lines.append(f" URL: {url}")
|
||||||
|
|
||||||
|
return [{"type": "text", "text": "\n".join(lines)}]
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Navigates the specified tab to the specified URL.
|
||||||
|
"""
|
||||||
|
url = args.get("url")
|
||||||
|
if not url:
|
||||||
|
raise ToolError("Missing required argument: 'url'")
|
||||||
|
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {"url": str(url)}
|
||||||
|
if args.get("tab_id") is not None:
|
||||||
|
params["tab_id"] = int(args["tab_id"])
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
|
||||||
|
await bridge.send_to_extension(request_id, "navigate_to", params)
|
||||||
|
|
||||||
|
return [{"type": "text", "text": f"Navigated to {url}."}]
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Opens a new tab with the specified URL.
|
||||||
|
"""
|
||||||
|
url = args.get("url")
|
||||||
|
if not url:
|
||||||
|
raise ToolError("Missing required argument: 'url'")
|
||||||
|
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {"url": str(url)}
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
|
||||||
|
await bridge.send_to_extension(request_id, "open_new_tab", params)
|
||||||
|
|
||||||
|
return [{"type": "text", "text": f"Opened new tab with {url}."}]
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Scans the specified tab for interactive elements, assigns mcp-ids,
|
||||||
|
and returns a simplified list.
|
||||||
|
"""
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {}
|
||||||
|
if args.get("tab_id") is not None:
|
||||||
|
params["tab_id"] = int(args["tab_id"])
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
result = await bridge.send_to_extension(request_id, "get_page_summary", params)
|
||||||
|
|
||||||
|
elements = result if isinstance(result, list) else []
|
||||||
|
|
||||||
|
lines = ["# Page Summary - Interactive Elements\n"]
|
||||||
|
lines.append("The following interactive elements have been indexed on the current page.")
|
||||||
|
lines.append("Use the `id` (mcp-id) with `click_element`, `type_text`, or `get_element_details`.\n")
|
||||||
|
|
||||||
|
if not elements:
|
||||||
|
lines.append("No interactive elements found on this page.")
|
||||||
|
else:
|
||||||
|
for el in elements:
|
||||||
|
eid = el.get("id", "?")
|
||||||
|
role = el.get("role", "unknown")
|
||||||
|
text = el.get("text", "") or el.get("label", "")
|
||||||
|
tag = el.get("tag", "")
|
||||||
|
href = el.get("href", "")
|
||||||
|
line = f"- **id={eid}** [{role}]"
|
||||||
|
if text:
|
||||||
|
line += f" - \"{text[:100]}\""
|
||||||
|
if tag:
|
||||||
|
line += f" (<{tag}>"
|
||||||
|
if href:
|
||||||
|
line += f" href={href}"
|
||||||
|
line += ")"
|
||||||
|
lines.append(line)
|
||||||
|
|
||||||
|
lines.append("\nTotal elements indexed: " + str(len(elements)))
|
||||||
|
|
||||||
|
return [{"type": "text", "text": "\n".join(lines)}]
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Simulates a keyboard press.
|
||||||
|
"""
|
||||||
|
key = args.get("key")
|
||||||
|
if not key:
|
||||||
|
raise ToolError("Missing required argument: 'key'")
|
||||||
|
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {"key": str(key)}
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
if args.get("tab_id") is not None:
|
||||||
|
params["tab_id"] = int(args["tab_id"])
|
||||||
|
|
||||||
|
await bridge.send_to_extension(request_id, "press_key", params)
|
||||||
|
|
||||||
|
return [{"type": "text", "text": f"Pressed key '{key}'."}]
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Returns a reader-mode version of the page text.
|
||||||
|
"""
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {}
|
||||||
|
if args.get("tab_id") is not None:
|
||||||
|
params["tab_id"] = int(args["tab_id"])
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
|
||||||
|
result = await bridge.send_to_extension(request_id, "read_page_text", params)
|
||||||
|
|
||||||
|
text = result if isinstance(result, str) else str(result)
|
||||||
|
|
||||||
|
if not text or text.strip() == "":
|
||||||
|
return [{"type": "text", "text": "No readable text found on this page."}]
|
||||||
|
|
||||||
|
return [{"type": "text", "text": f"# Page Text (Reader Mode)\n\n{text}"}]
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Scrolls the page by direction and amount.
|
||||||
|
"""
|
||||||
|
direction = args.get("direction")
|
||||||
|
amount = args.get("amount", 500)
|
||||||
|
|
||||||
|
if not direction:
|
||||||
|
raise ToolError("Missing required argument: 'direction'")
|
||||||
|
if direction not in ("up", "down", "left", "right"):
|
||||||
|
raise ToolError(f"Invalid direction '{direction}'. Must be: up, down, left, right")
|
||||||
|
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {"direction": direction, "amount": int(amount)}
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
if args.get("tab_id") is not None:
|
||||||
|
params["tab_id"] = int(args["tab_id"])
|
||||||
|
|
||||||
|
await bridge.send_to_extension(request_id, "scroll_page", params)
|
||||||
|
|
||||||
|
return [{"type": "text", "text": f"Scrolled {direction} by {amount}."}]
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Switches focus to the specified Tab ID. Gets the tab by its internal ID
|
||||||
|
(works across all windows), focuses that tab's window, and highlights it.
|
||||||
|
"""
|
||||||
|
tab_id = args.get("tab_id")
|
||||||
|
if tab_id is None:
|
||||||
|
raise ToolError("Missing required argument: 'tab_id'")
|
||||||
|
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
result = await bridge.send_to_extension(request_id, "switch_tab", {"tab_id": int(tab_id)})
|
||||||
|
|
||||||
|
if result and result.get("url"):
|
||||||
|
return [{"type": "text", "text": f"Switched to tab {tab_id} ({result['url']})."}]
|
||||||
|
|
||||||
|
return [{"type": "text", "text": f"Switched to tab {tab_id}."}]
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Captures a screenshot of the current viewport.
|
||||||
|
Window ID is optional - captures the visible tab in that window.
|
||||||
|
"""
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {}
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
|
||||||
|
result = await bridge.send_to_extension(request_id, "take_screenshot", params)
|
||||||
|
|
||||||
|
screenshot_url = None
|
||||||
|
if isinstance(result, dict):
|
||||||
|
screenshot_url = result.get("screenshot")
|
||||||
|
|
||||||
|
if screenshot_url and screenshot_url.startswith("data:image/png;base64,"):
|
||||||
|
b64_data = screenshot_url.split(",", 1)[1]
|
||||||
|
return [
|
||||||
|
{"type": "text", "text": "Screenshot captured successfully."},
|
||||||
|
{"type": "image", "data": b64_data, "mimeType": "image/png"}
|
||||||
|
]
|
||||||
|
|
||||||
|
return [{"type": "text", "text": "Failed to capture screenshot."}]
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import asyncio
|
||||||
|
from typing import Any, Dict
|
||||||
|
from tools.utils import ToolError
|
||||||
|
|
||||||
|
async def handle(args: Dict[str, Any], bridge: Any) -> list:
|
||||||
|
"""
|
||||||
|
Types text into the element with the specified mcp-id.
|
||||||
|
"""
|
||||||
|
eid = args.get("id")
|
||||||
|
text = args.get("text")
|
||||||
|
|
||||||
|
if eid is None:
|
||||||
|
raise ToolError("Missing required argument: 'id'")
|
||||||
|
if text is None:
|
||||||
|
raise ToolError("Missing required argument: 'text'")
|
||||||
|
|
||||||
|
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
|
||||||
|
params: Dict[str, Any] = {"id": int(eid), "text": str(text)}
|
||||||
|
if args.get("window_id") is not None:
|
||||||
|
params["window_id"] = int(args["window_id"])
|
||||||
|
if args.get("tab_id") is not None:
|
||||||
|
params["tab_id"] = int(args["tab_id"])
|
||||||
|
|
||||||
|
await bridge.send_to_extension(request_id, "type_text", params)
|
||||||
|
|
||||||
|
return [{"type": "text", "text": f"Typed text into element mcp-id={eid}."}]
|
||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import time
|
||||||
|
import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Dict, Any, Optional
|
||||||
|
|
||||||
|
|
||||||
|
class ToolError(Exception):
|
||||||
|
"""Custom exception for tool-related errors to be caught by the MCP server."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def format_relative_time(timestamp: float) -> str:
|
||||||
|
"""Converts a timestamp to a human-readable relative format."""
|
||||||
|
now = time.time()
|
||||||
|
diff = now - timestamp
|
||||||
|
seconds = int(diff)
|
||||||
|
|
||||||
|
if seconds < 0:
|
||||||
|
return "In the future"
|
||||||
|
if seconds < 60:
|
||||||
|
return "Just now"
|
||||||
|
|
||||||
|
minutes = seconds // 60
|
||||||
|
if minutes < 60:
|
||||||
|
return f"{minutes}m ago"
|
||||||
|
|
||||||
|
hours = minutes // 60
|
||||||
|
if hours < 24:
|
||||||
|
return f"{hours}h ago"
|
||||||
|
|
||||||
|
days = hours // 24
|
||||||
|
if days == 1:
|
||||||
|
return "Yesterday"
|
||||||
|
if days < 30:
|
||||||
|
return f"{days}d ago"
|
||||||
|
|
||||||
|
months = days // 30
|
||||||
|
if months < 12:
|
||||||
|
return f"{months}mo ago"
|
||||||
|
|
||||||
|
dt = datetime.datetime.fromtimestamp(timestamp)
|
||||||
|
return dt.strftime('%Y-%m-%d')
|
||||||
@@ -0,0 +1,313 @@
|
|||||||
|
/*
|
||||||
|
* Firefox MCP Bridge - Background Script
|
||||||
|
*
|
||||||
|
* Connects to the Python bridge via WebSocket and relays commands
|
||||||
|
* between the bridge and the content scripts running in web pages.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const WS_URL = "ws://127.0.0.1:8008/ws";
|
||||||
|
let ws = null;
|
||||||
|
let reconnectTimer = null;
|
||||||
|
let heartbeatTimer = null;
|
||||||
|
const RECONNECT_DELAY = 2000;
|
||||||
|
const HEARTBEAT_INTERVAL = 30000;
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// WebSocket connection to the Python bridge
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
function connect() {
|
||||||
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ws = new WebSocket(WS_URL);
|
||||||
|
|
||||||
|
ws.onopen = () => {
|
||||||
|
console.log("[MCP Bridge] WebSocket connected to Python bridge");
|
||||||
|
if (reconnectTimer) {
|
||||||
|
clearInterval(reconnectTimer);
|
||||||
|
reconnectTimer = null;
|
||||||
|
}
|
||||||
|
startHeartbeat();
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onmessage = (event) => {
|
||||||
|
try {
|
||||||
|
const msg = JSON.parse(event.data);
|
||||||
|
if (msg.type === "request") {
|
||||||
|
handleRequest(msg);
|
||||||
|
} else if (msg.type === "pong") {
|
||||||
|
// Heartbeat response
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("[MCP Bridge] Failed to parse message from bridge:", err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onclose = () => {
|
||||||
|
console.log("[MCP Bridge] WebSocket disconnected");
|
||||||
|
ws = null;
|
||||||
|
stopHeartbeat();
|
||||||
|
scheduleReconnect();
|
||||||
|
};
|
||||||
|
|
||||||
|
ws.onerror = (err) => {
|
||||||
|
console.error("[MCP Bridge] WebSocket error:", err);
|
||||||
|
ws.close();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduleReconnect() {
|
||||||
|
if (reconnectTimer) return;
|
||||||
|
console.log("[MCP Bridge] Reconnecting in " + RECONNECT_DELAY + "ms...");
|
||||||
|
reconnectTimer = setInterval(() => {
|
||||||
|
connect();
|
||||||
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||||
|
clearInterval(reconnectTimer);
|
||||||
|
reconnectTimer = null;
|
||||||
|
}
|
||||||
|
}, RECONNECT_DELAY);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// Heartbeat
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
function startHeartbeat() {
|
||||||
|
stopHeartbeat();
|
||||||
|
heartbeatTimer = setInterval(() => {
|
||||||
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||||
|
ws.send(JSON.stringify({ type: "ping" }));
|
||||||
|
}
|
||||||
|
}, HEARTBEAT_INTERVAL);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopHeartbeat() {
|
||||||
|
if (heartbeatTimer) {
|
||||||
|
clearInterval(heartbeatTimer);
|
||||||
|
heartbeatTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// Send response back to Python bridge
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
function sendResponse(requestId, payload) {
|
||||||
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||||
|
ws.send(JSON.stringify({
|
||||||
|
type: "response",
|
||||||
|
request_id: requestId,
|
||||||
|
...payload,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// Resolve a target tab: by tab_id, or by window_id + active, or focused window
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
async function resolveTarget(tabId, windowId) {
|
||||||
|
let tab;
|
||||||
|
if (tabId) {
|
||||||
|
tab = await browser.tabs.get(tabId);
|
||||||
|
if (!tab) throw new Error(`Tab ${tabId} not found`);
|
||||||
|
} else if (windowId) {
|
||||||
|
const tabs = await browser.tabs.query({ windowId, active: true });
|
||||||
|
if (!tabs || tabs.length === 0) {
|
||||||
|
throw new Error(`No active tab in window ${windowId}`);
|
||||||
|
}
|
||||||
|
tab = tabs[0];
|
||||||
|
} else {
|
||||||
|
const tabs = await browser.tabs.query({ active: true, currentWindow: true });
|
||||||
|
if (!tabs || tabs.length === 0) {
|
||||||
|
throw new Error("No active tab found");
|
||||||
|
}
|
||||||
|
tab = tabs[0];
|
||||||
|
}
|
||||||
|
return tab;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// Execute a function in a specific tab's content script
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
async function execInTab(tabId, windowId, functionName, args) {
|
||||||
|
const tab = await resolveTarget(tabId, windowId);
|
||||||
|
try {
|
||||||
|
const response = await browser.tabs.sendMessage(tab.id, {
|
||||||
|
type: "mcp_call",
|
||||||
|
function: functionName,
|
||||||
|
args: args,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response && response.error) {
|
||||||
|
throw new Error(response.error);
|
||||||
|
}
|
||||||
|
return response && response.result;
|
||||||
|
} catch (err) {
|
||||||
|
if (err.message && err.message.includes("Could not establish connection")) {
|
||||||
|
throw new Error(
|
||||||
|
"Content script not available in this tab. Try refreshing the page."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// Route incoming requests from the Python bridge
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
async function handleRequest(msg) {
|
||||||
|
const { request_id, action, params } = msg;
|
||||||
|
try {
|
||||||
|
let result;
|
||||||
|
|
||||||
|
switch (action) {
|
||||||
|
// --- DOM / content script actions ---
|
||||||
|
case "get_page_summary":
|
||||||
|
result = await execInTab(params.tab_id, params.window_id, "getPageSummary", {});
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "get_element_details":
|
||||||
|
result = await execInTab(params.tab_id, params.window_id, "getElementDetails", { id: params.id });
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "click_element":
|
||||||
|
result = await execInTab(params.tab_id, params.window_id, "clickElement", { id: params.id });
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "type_text":
|
||||||
|
result = await execInTab(params.tab_id, params.window_id, "typeText", { id: params.id, text: params.text });
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "press_key":
|
||||||
|
result = await execInTab(params.tab_id, params.window_id, "pressKey", { key: params.key });
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "scroll_page":
|
||||||
|
result = await execInTab(params.tab_id, params.window_id, "scrollPage", {
|
||||||
|
direction: params.direction,
|
||||||
|
amount: params.amount,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "execute_script":
|
||||||
|
result = await execInTab(params.tab_id, params.window_id, "executeScript", { js_code: params.js_code });
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "read_page_text":
|
||||||
|
result = await execInTab(params.tab_id, params.window_id, "readPageText", {});
|
||||||
|
break;
|
||||||
|
|
||||||
|
// --- Background-only actions ---
|
||||||
|
case "take_screenshot":
|
||||||
|
result = await takeScreenshot(params.tab_id, params.window_id);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "get_page_cookies":
|
||||||
|
result = await getPageCookies(params.tab_id, params.window_id);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "get_current_url":
|
||||||
|
result = await getCurrentUrl(params.tab_id, params.window_id);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "list_tabs":
|
||||||
|
result = await listTabs();
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "switch_tab":
|
||||||
|
result = await switchTab(params.tab_id, params.window_id);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "navigate_to":
|
||||||
|
result = await navigateTo(params.url, params.tab_id, params.window_id);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case "open_new_tab":
|
||||||
|
result = await openNewTab(params.url, params.window_id);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown action: ${action}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
sendResponse(request_id, { success: true, result: result });
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`[MCP Bridge] Error handling ${action}:`, err);
|
||||||
|
sendResponse(request_id, { success: false, error: err.message });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// Background-only implementations
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
|
||||||
|
async function takeScreenshot(tabId, windowId) {
|
||||||
|
const tab = await resolveTarget(tabId, windowId);
|
||||||
|
const dataUrl = await browser.tabs.captureVisibleTab(tab.windowId, { format: "png" });
|
||||||
|
return { screenshot: dataUrl };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getPageCookies(tabId, windowId) {
|
||||||
|
const tab = await resolveTarget(tabId, windowId);
|
||||||
|
const url = tab.url;
|
||||||
|
console.log("[MCP Bridge] getPageCookies for URL:", url);
|
||||||
|
const cookies = await browser.cookies.getAll({ url: url });
|
||||||
|
console.log("[MCP Bridge] getPageCookies result:", cookies);
|
||||||
|
return cookies;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getCurrentUrl(tabId, windowId) {
|
||||||
|
const tab = await resolveTarget(tabId, windowId);
|
||||||
|
return { url: tab.url };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function listTabs() {
|
||||||
|
const tabs = await browser.tabs.query({});
|
||||||
|
return tabs.map((t) => ({
|
||||||
|
id: t.id,
|
||||||
|
title: t.title || "",
|
||||||
|
url: t.url || "",
|
||||||
|
active: t.active || false,
|
||||||
|
windowId: t.windowId,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function switchTab(tabId, windowId) {
|
||||||
|
let tab;
|
||||||
|
if (tabId) {
|
||||||
|
tab = await browser.tabs.get(tabId);
|
||||||
|
if (!tab) throw new Error(`Tab ${tabId} not found`);
|
||||||
|
} else if (windowId) {
|
||||||
|
const tabs = await browser.tabs.query({ windowId, active: true });
|
||||||
|
if (!tabs || tabs.length === 0) {
|
||||||
|
throw new Error(`No active tab in window ${windowId}`);
|
||||||
|
}
|
||||||
|
tab = tabs[0];
|
||||||
|
} else {
|
||||||
|
throw new Error("Either tab_id or window_id is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
await browser.windows.update(tab.windowId, { focused: true });
|
||||||
|
await browser.tabs.update(tab.id, { active: true });
|
||||||
|
const updated = await browser.tabs.get(tab.id);
|
||||||
|
return { success: true, tabId: updated.id, windowId: updated.windowId, url: updated.url };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function navigateTo(url, tabId, windowId) {
|
||||||
|
const tab = await resolveTarget(tabId, windowId);
|
||||||
|
await browser.tabs.update(tab.id, { url: url });
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openNewTab(url, windowId) {
|
||||||
|
const createProps = { url: url };
|
||||||
|
if (windowId) {
|
||||||
|
createProps.windowId = windowId;
|
||||||
|
}
|
||||||
|
await browser.tabs.create(createProps);
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// Initialize connection
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
connect();
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
/*
|
||||||
|
* Firefox MCP Bridge - Content Script
|
||||||
|
*
|
||||||
|
* Runs in the context of web pages. Provides DOM-level access
|
||||||
|
* to the background script via browser.runtime.onMessage.
|
||||||
|
*/
|
||||||
|
|
||||||
|
let mcpIdCounter = 0;
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// Element indexing helpers
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
|
||||||
|
function getNextId() {
|
||||||
|
return ++mcpIdCounter;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isInteractiveElement(el) {
|
||||||
|
const tag = el.tagName.toLowerCase();
|
||||||
|
const interactiveTags = [
|
||||||
|
"button",
|
||||||
|
"a",
|
||||||
|
"input",
|
||||||
|
"select",
|
||||||
|
"textarea",
|
||||||
|
];
|
||||||
|
if (interactiveTags.includes(tag)) return true;
|
||||||
|
|
||||||
|
const role = el.getAttribute("role");
|
||||||
|
if (role === "button" || role === "link" || role === "checkbox" || role === "radio" || role === "switch") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (el.onclick || el.getAttribute("onclick")) return true;
|
||||||
|
if (el.isContentEditable) return true;
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getBasicInfo(el) {
|
||||||
|
const tag = el.tagName.toLowerCase();
|
||||||
|
const ariaRole = el.getAttribute("role");
|
||||||
|
const role = ariaRole || tag;
|
||||||
|
|
||||||
|
let text = "";
|
||||||
|
if (tag === "input") {
|
||||||
|
text = el.value || el.getAttribute("placeholder") || el.getAttribute("type") || "";
|
||||||
|
} else if (tag === "img") {
|
||||||
|
text = el.alt || el.getAttribute("src") || "";
|
||||||
|
} else {
|
||||||
|
const tc = el.textContent || el.innerText || "";
|
||||||
|
text = tc.trim().substring(0, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
const label =
|
||||||
|
el.getAttribute("aria-label") ||
|
||||||
|
el.getAttribute("alt") ||
|
||||||
|
el.getAttribute("title") ||
|
||||||
|
"";
|
||||||
|
|
||||||
|
const href = el.href || "";
|
||||||
|
const src = el.src || "";
|
||||||
|
|
||||||
|
return {
|
||||||
|
role: role,
|
||||||
|
text: text,
|
||||||
|
label: label,
|
||||||
|
tag: tag,
|
||||||
|
type: el.type || "",
|
||||||
|
name: el.name || "",
|
||||||
|
id_attr: el.id || "",
|
||||||
|
class: el.className || "",
|
||||||
|
href: href,
|
||||||
|
src: src,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function scanPage() {
|
||||||
|
const elements = [];
|
||||||
|
const selector =
|
||||||
|
"button, a, input, select, textarea, " +
|
||||||
|
"[role='button'], [role='link'], [role='checkbox'], [role='radio'], [role='switch'], " +
|
||||||
|
"[onclick], [contenteditable='true']";
|
||||||
|
|
||||||
|
const interactive = document.querySelectorAll(selector);
|
||||||
|
|
||||||
|
interactive.forEach((el) => {
|
||||||
|
// Assign a stable mcp-id if not already present
|
||||||
|
let mcpId = el.getAttribute("data-mcp-id");
|
||||||
|
if (!mcpId) {
|
||||||
|
mcpId = getNextId().toString();
|
||||||
|
el.setAttribute("data-mcp-id", mcpId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const info = getBasicInfo(el);
|
||||||
|
info.id = parseInt(mcpId, 10);
|
||||||
|
elements.push(info);
|
||||||
|
});
|
||||||
|
|
||||||
|
return elements;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getElementByMcpId(id) {
|
||||||
|
return document.querySelector(`[data-mcp-id="${id}"]`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getElementDetails(id) {
|
||||||
|
const el = getElementByMcpId(id);
|
||||||
|
if (!el) {
|
||||||
|
throw new Error(`Element with mcp-id ${id} not found in the DOM`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rect = el.getBoundingClientRect();
|
||||||
|
const computed = window.getComputedStyle(el);
|
||||||
|
|
||||||
|
const attributes = {};
|
||||||
|
for (let i = 0; i < el.attributes.length; i++) {
|
||||||
|
const attr = el.attributes[i];
|
||||||
|
attributes[attr.name] = attr.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: parseInt(el.getAttribute("data-mcp-id"), 10),
|
||||||
|
tag: el.tagName.toLowerCase(),
|
||||||
|
text: el.textContent ? el.textContent.trim() : "",
|
||||||
|
value: el.value || "",
|
||||||
|
html: el.outerHTML.substring(0, 2000),
|
||||||
|
attributes: attributes,
|
||||||
|
bounding_box: {
|
||||||
|
x: Math.round(rect.x),
|
||||||
|
y: Math.round(rect.y),
|
||||||
|
width: Math.round(rect.width),
|
||||||
|
height: Math.round(rect.height),
|
||||||
|
},
|
||||||
|
visible: computed.visibility !== "hidden" && computed.display !== "none",
|
||||||
|
disabled: el.disabled === true,
|
||||||
|
readonly: el.readOnly === true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// Action implementations
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
|
||||||
|
function clickElement(id) {
|
||||||
|
const el = getElementByMcpId(id);
|
||||||
|
if (!el) {
|
||||||
|
throw new Error(`Element with mcp-id ${id} not found`);
|
||||||
|
}
|
||||||
|
el.click();
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
function typeText(id, text) {
|
||||||
|
const el = getElementByMcpId(id);
|
||||||
|
if (!el) {
|
||||||
|
throw new Error(`Element with mcp-id ${id} not found`);
|
||||||
|
}
|
||||||
|
el.focus();
|
||||||
|
el.value = text;
|
||||||
|
// Dispatch input and change events so frameworks (React, Vue, etc.) notice
|
||||||
|
el.dispatchEvent(new Event("input", { bubbles: true }));
|
||||||
|
el.dispatchEvent(new Event("change", { bubbles: true }));
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
function pressKey(key) {
|
||||||
|
const active = document.activeElement || document.body;
|
||||||
|
const event = new KeyboardEvent("keydown", {
|
||||||
|
key: key,
|
||||||
|
code: key,
|
||||||
|
bubbles: true,
|
||||||
|
cancelable: true,
|
||||||
|
});
|
||||||
|
active.dispatchEvent(event);
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
function scrollPage(direction, amount) {
|
||||||
|
let pixels = amount;
|
||||||
|
if (amount > 0 && amount <= 100) {
|
||||||
|
// Treat as percentage of viewport
|
||||||
|
const viewportSize =
|
||||||
|
direction === "up" || direction === "down"
|
||||||
|
? window.innerHeight
|
||||||
|
: window.innerWidth;
|
||||||
|
pixels = (amount / 100) * viewportSize;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (direction === "up") {
|
||||||
|
window.scrollBy(0, -pixels);
|
||||||
|
} else if (direction === "down") {
|
||||||
|
window.scrollBy(0, pixels);
|
||||||
|
} else if (direction === "left") {
|
||||||
|
window.scrollBy(-pixels, 0);
|
||||||
|
} else if (direction === "right") {
|
||||||
|
window.scrollBy(pixels, 0);
|
||||||
|
}
|
||||||
|
return { success: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
function executeScript(jsCode) {
|
||||||
|
try {
|
||||||
|
const result = window.eval(jsCode);
|
||||||
|
return {
|
||||||
|
result: result !== undefined ? String(result) : "",
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
throw new Error(`Script error: ${err.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function readPageText() {
|
||||||
|
// Build a "reader mode" version by cloning the document and stripping noise
|
||||||
|
const clone = document.cloneNode(true);
|
||||||
|
const removeTags = [
|
||||||
|
"script",
|
||||||
|
"style",
|
||||||
|
"nav",
|
||||||
|
"header",
|
||||||
|
"footer",
|
||||||
|
"aside",
|
||||||
|
"iframe",
|
||||||
|
"noscript",
|
||||||
|
];
|
||||||
|
removeTags.forEach((tag) => {
|
||||||
|
clone.querySelectorAll(tag).forEach((el) => el.remove());
|
||||||
|
});
|
||||||
|
|
||||||
|
let text = clone.textContent || clone.innerText || "";
|
||||||
|
// Normalize whitespace
|
||||||
|
text = text.replace(/\n\s*\n/g, "\n").replace(/\s+/g, " ").trim();
|
||||||
|
return text.substring(0, 10000); // Cap size for token budget
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
// Message listener: receives requests from the background script
|
||||||
|
// ------------------------------------------------------------------
|
||||||
|
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
|
||||||
|
if (message.type !== "mcp_call") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
(async () => {
|
||||||
|
try {
|
||||||
|
let result;
|
||||||
|
switch (message.function) {
|
||||||
|
case "getPageSummary":
|
||||||
|
result = scanPage();
|
||||||
|
break;
|
||||||
|
case "getElementDetails":
|
||||||
|
result = getElementDetails(message.args.id);
|
||||||
|
break;
|
||||||
|
case "clickElement":
|
||||||
|
result = clickElement(message.args.id);
|
||||||
|
break;
|
||||||
|
case "typeText":
|
||||||
|
result = typeText(message.args.id, message.args.text);
|
||||||
|
break;
|
||||||
|
case "pressKey":
|
||||||
|
result = pressKey(message.args.key);
|
||||||
|
break;
|
||||||
|
case "scrollPage":
|
||||||
|
result = scrollPage(message.args.direction, message.args.amount);
|
||||||
|
break;
|
||||||
|
case "executeScript":
|
||||||
|
result = executeScript(message.args.js_code);
|
||||||
|
break;
|
||||||
|
case "readPageText":
|
||||||
|
result = readPageText();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown content function: ${message.function}`);
|
||||||
|
}
|
||||||
|
sendResponse({ result: result });
|
||||||
|
} catch (err) {
|
||||||
|
sendResponse({ error: err.message });
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
return true; // Keep the message channel open for async response
|
||||||
|
});
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
"manifest_version": 2,
|
||||||
|
"name": "Firefox MCP Bridge",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"description": "Allows an LLM to control Firefox via the Model Context Protocol (MCP).",
|
||||||
|
"permissions": [
|
||||||
|
"tabs",
|
||||||
|
"activeTab",
|
||||||
|
"storage",
|
||||||
|
"cookies",
|
||||||
|
"<all_urls>"
|
||||||
|
],
|
||||||
|
"background": {
|
||||||
|
"scripts": ["background.js"],
|
||||||
|
"persistent": true
|
||||||
|
},
|
||||||
|
"content_scripts": [
|
||||||
|
{
|
||||||
|
"matches": ["<all_urls>"],
|
||||||
|
"js": ["content.js"],
|
||||||
|
"run_at": "document_end",
|
||||||
|
"all_frames": false
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"web_accessible_resources": [],
|
||||||
|
"browser_specific_settings": {
|
||||||
|
"gecko": {
|
||||||
|
"id": "mcp-firefox-bridge@local",
|
||||||
|
"strict_min_version": "109.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user