Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

feat(mcp): add MCP server with 21 tools, docs, and tests

Yash Jadhav9aa0ec837d74
diff --git a/cmd/pinchtab/cmd_cli.go b/cmd/pinchtab/cmd_cli.go
index 81263296..df4f7d40 100644
--- a/cmd/pinchtab/cmd_cli.go
+++ b/cmd/pinchtab/cmd_cli.go
@@ -23,6 +23,7 @@ MODES:
pinchtab Start full server (default)
pinchtab server Start full server explicitly
pinchtab bridge Start single-instance bridge-only server
+ pinchtab mcp Start MCP (Model Context Protocol) server on stdio
pinchtab connect <name> Get URL for a running profile
pinchtab security Review runtime security posture
diff --git a/cmd/pinchtab/cmd_mcp.go b/cmd/pinchtab/cmd_mcp.go
new file mode 100644
index 00000000..62c045d8
--- /dev/null
+++ b/cmd/pinchtab/cmd_mcp.go
@@ -0,0 +1,32 @@
+package main
+
+import (
+ "fmt"
+ "os"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/mcp"
+)
+
+func runMCP(cfg *config.RuntimeConfig) {
+ baseURL := os.Getenv("PINCHTAB_URL")
+ if baseURL == "" {
+ port := cfg.Port
+ if port == "" {
+ port = "9867"
+ }
+ baseURL = "http://127.0.0.1:" + port
+ }
+
+ token := os.Getenv("PINCHTAB_TOKEN")
+ if token == "" {
+ token = cfg.Token
+ }
+
+ mcp.Version = version
+
+ if err := mcp.Serve(baseURL, token); err != nil {
+ fmt.Fprintf(os.Stderr, "mcp server error: %v\n", err)
+ os.Exit(1)
+ }
+}
diff --git a/cmd/pinchtab/main.go b/cmd/pinchtab/main.go
index 1c9ec45c..f2b06d6b 100644
--- a/cmd/pinchtab/main.go
+++ b/cmd/pinchtab/main.go
@@ -54,6 +54,11 @@ func main() {
os.Exit(0)
}
+ if len(os.Args) > 1 && os.Args[1] == "mcp" {
+ runMCP(cfg)
+ return
+ }
+
// CLI commands
if len(os.Args) > 1 && isCLICommand(os.Args[1]) {
runCLI(cfg)
diff --git a/docs/architecture/mcp.md b/docs/architecture/mcp.md
new file mode 100644
index 00000000..7d5d2d74
--- /dev/null
+++ b/docs/architecture/mcp.md
@@ -0,0 +1,114 @@
+# MCP Server Architecture
+
+This page describes how the PinchTab MCP server is structured internally and how it integrates with the rest of the stack.
+
+## Overview
+
+The MCP server is a thin stdio-based JSON-RPC 2.0 layer. It runs as a separate process (`pinchtab mcp`) and delegates every browser action to an already-running PinchTab instance via its REST API.
+
+```mermaid
+flowchart LR
+ A["AI Agent\n(Claude, Copilot, Cursor…)"] -- "stdio / JSON-RPC 2.0" --> M["pinchtab mcp"]
+ M -- "HTTP / REST" --> P["PinchTab Server\nor Bridge"]
+ P -- "Chrome DevTools Protocol" --> C["Chrome"]
+```
+
+Key design decisions:
+
+- **No direct Chrome dependency** — the MCP process has no CDP connection. All browser work is delegated to the PinchTab instance.
+- **Any deployment works** — point `PINCHTAB_URL` at a local server, a Docker container, or a remote host.
+- **Stateless protocol layer** — the MCP server holds no browser state itself; it is purely a translation adapter.
+
+## Transport
+
+The MCP server uses the **stdio transport** defined in the [MCP specification 2025-11-25](https://spec.modelcontextprotocol.io/). The AI client writes JSON-RPC requests to stdin and reads responses from stdout. Logs and diagnostics go to stderr.
+
+This transport is universally supported by MCP clients (Claude Desktop, VS Code, Cursor, and any SDK-based client).
+
+## Process Model
+
+```
+pinchtab mcp
+ │
+ ├── reads PINCHTAB_URL (env or config, default http://127.0.0.1:9867)
+ ├── reads PINCHTAB_TOKEN (env or config)
+ │
+ ├── creates internal/mcp.Client (HTTP client with 120 s timeout)
+ ├── registers 21 MCP tools via mcp-go SDK
+ └── calls server.ServeStdio() (blocking read loop)
+```
+
+The process exits when stdin is closed by the client.
+
+## Code Layout
+
+```
+internal/mcp/
+├── server.go # NewServer() wires tools → handlers; Serve() starts stdio
+├── tools.go # allTools() — JSON-schema tool definitions for all 21 tools
+├── handlers.go # handlerMap() — one handler closure per tool
+└── client.go # Client — thin HTTP wrapper for PinchTab REST API
+
+cmd/pinchtab/
+└── cmd_mcp.go # runMCP() — reads config, calls mcp.Serve()
+```
+
+### server.go
+
+`NewServer` creates an `MCPServer` via the `mcp-go` SDK, iterates `allTools()`, looks up the matching handler in `handlerMap`, and calls `s.AddTool`. A panic fires at startup if a tool has no handler, preventing silent gaps.
+
+`Serve` wraps `server.ServeStdio` for the normal execution path.
+
+### tools.go
+
+`allTools` returns a `[]mcp.Tool` slice. Each tool is declared with:
+
+- a name (`pinchtab_*`)
+- a human-readable description used by the LLM to select the right tool
+- typed parameter schemas with `Required()` / `Description()` annotations
+
+The declarations are grouped by category: Navigation, Interaction, Content, Tab Management, Utility.
+
+### handlers.go
+
+Each handler is a factory function returning a `func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error)` closure. Handlers:
+
+1. Extract and validate arguments from `r.GetArguments()`
+2. Build the corresponding PinchTab REST payload
+3. Call `c.Get` or `c.Post` with the request context
+4. Return `mcp.NewToolResultText` on success or `mcp.NewToolResultError` on HTTP 4xx/5xx
+
+The context passed from the MCP SDK carries the client's deadline, so long-running navigations will be cancelled if the client disconnects.
+
+### client.go
+
+`Client` wraps `net/http` with:
+
+- a 120-second timeout (covers page loads and PDF exports)
+- optional `Authorization: Bearer <token>` header injection
+- a 10 MB response body limit
+- URL validation in `handleNavigate` (must start with `http://` or `https://`)
+
+## Tool Categories
+
+| Category | Count | REST Endpoints Used |
+|----------|-------|---------------------|
+| Navigation | 4 | `/navigate`, `/snapshot`, `/screenshot`, `/text` |
+| Interaction | 8 | `/action` (with `action` field) |
+| Content | 3 | `/evaluate`, `/pdf`, `/find` |
+| Tab Management | 4 | `/tabs`, `/health`, `/cookies` |
+| Utility | 2 | `/evaluate` (wait-for-selector), local sleep |
+
+## Security Considerations
+
+- **`pinchtab_eval`** calls `/evaluate`, which requires `security.allowEvaluate: true` in the PinchTab config. It returns HTTP 403 by default. This is intentional — arbitrary JS execution is a separate opt-in from browser control.
+- **URL validation** — `pinchtab_navigate` rejects non-HTTP/HTTPS URLs to prevent SSRF via `file://`, `javascript:`, or custom schemes.
+- **Token forwarding** — the MCP client forwards the configured bearer token to PinchTab, so access control at the PinchTab layer applies to all tool calls.
+- **Wait caps** — `pinchtab_wait` and `pinchtab_wait_for_selector` enforce a 30-second maximum to prevent agent runaway.
+
+## Related Pages
+
+- [MCP User Guide](../mcp.md)
+- [Architecture Overview](./index.md)
+- [MCP Tool Reference](../reference/mcp-tools.md)
+- [Security Guide](../guides/security.md)
diff --git a/docs/guides/mcp-agents.md b/docs/guides/mcp-agents.md
new file mode 100644
index 00000000..b2da4de6
--- /dev/null
+++ b/docs/guides/mcp-agents.md
@@ -0,0 +1,215 @@
+# Using PinchTab with AI Agents (MCP)
+
+This guide walks through setting up PinchTab as an MCP tool server for AI coding assistants and agent frameworks.
+
+## What is MCP?
+
+The [Model Context Protocol](https://modelcontextprotocol.io/) is an open standard for connecting AI models to external tools. PinchTab implements an MCP server that exposes 21 browser-control tools — navigation, interaction, screenshot, PDF export, and more — over a simple stdio interface that every major AI client supports.
+
+## Prerequisites
+
+- PinchTab installed (`pinchtab --version`)
+- Chrome installed and on PATH (or pointed to via config)
+- An MCP-compatible client: Claude Desktop, VS Code with GitHub Copilot, or Cursor
+
+## Step 1: Start PinchTab
+
+The MCP server is a thin adapter — it needs a running PinchTab instance to delegate to.
+
+**Headless mode (recommended for agents):**
+
+```bash
+pinchtab bridge --headless
+```
+
+**Normal server mode (if you want the dashboard too):**
+
+```bash
+pinchtab
+```
+
+PinchTab listens on `http://127.0.0.1:9867` by default.
+
+## Step 2: Configure Your MCP Client
+
+### Claude Desktop
+
+Edit `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):
+
+```json
+{
+ "mcpServers": {
+ "pinchtab": {
+ "command": "pinchtab",
+ "args": ["mcp"],
+ "env": {
+ "PINCHTAB_URL": "http://127.0.0.1:9867",
+ "PINCHTAB_TOKEN": "your-token-here"
+ }
+ }
+ }
+}
+```
+
+Restart Claude Desktop. You should see PinchTab in the tool list.
+
+### VS Code / GitHub Copilot
+
+Create `.vscode/mcp.json` in your workspace root:
+
+```json
+{
+ "servers": {
+ "pinchtab": {
+ "type": "stdio",
+ "command": "pinchtab",
+ "args": ["mcp"],
+ "env": {
+ "PINCHTAB_URL": "http://127.0.0.1:9867"
+ }
+ }
+ }
+}
+```
+
+### Cursor
+
+Add to your Cursor MCP settings (`~/.cursor/mcp.json`):
+
+```json
+{
+ "mcpServers": {
+ "pinchtab": {
+ "command": "pinchtab",
+ "args": ["mcp"]
+ }
+ }
+}
+```
+
+### Any SDK-based Agent
+
+```python
+# Python example using the mcp SDK
+import subprocess, mcp
+
+proc = subprocess.Popen(
+ ["pinchtab", "mcp"],
+ stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE,
+ env={"PINCHTAB_URL": "http://127.0.0.1:9867"},
+)
+# pass proc.stdin / proc.stdout to your MCP client transport
+```
+
+## Environment Variables
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `PINCHTAB_URL` | `http://127.0.0.1:9867` | PinchTab server URL |
+| `PINCHTAB_TOKEN` | *(from config)* | Bearer token for auth-protected servers |
+
+`PINCHTAB_TOKEN` can be found in `~/.config/pinchtab/config.yaml` under `server.token`, or by running `pinchtab config show`.
+
+## Typical Agent Workflow
+
+A well-written agent prompt would use tools in this order:
+
+```
+1. pinchtab_navigate → go to the target URL
+2. pinchtab_snapshot → understand the page structure (find refs)
+3. pinchtab_click / type → interact with elements by ref
+4. pinchtab_snapshot → confirm state after interaction
+5. pinchtab_get_text / pdf → extract or export results
+```
+
+### Example: Fill a Search Form
+
+```
+Agent: Search for "climate change" on Wikipedia
+
+Tools called:
+ pinchtab_navigate url="https://www.wikipedia.org"
+ pinchtab_snapshot interactive=true
+ → ...input[ref=e3] placeholder="Search Wikipedia"...
+ pinchtab_click ref="e3"
+ pinchtab_type ref="e3" text="climate change"
+ pinchtab_press key="Enter"
+ pinchtab_snapshot compact=true
+ pinchtab_get_text
+```
+
+## Enabling JavaScript Evaluation
+
+`pinchtab_eval` is disabled by default as a security measure. To enable it:
+
+```bash
+pinchtab config set security.allowEvaluate true
+```
+
+Or in `~/.config/pinchtab/config.yaml`:
+
+```yaml
+security:
+ allowEvaluate: true
+```
+
+Restart PinchTab after changing this setting.
+
+> **Warning:** Enabling evaluate allows the agent (and any page it visits) to run arbitrary JavaScript in the browser. Only enable this on trusted networks with a token set.
+
+## Connecting to a Remote PinchTab
+
+If PinchTab is running on another machine (e.g. a Docker container):
+
+```json
+{
+ "mcpServers": {
+ "pinchtab": {
+ "command": "pinchtab",
+ "args": ["mcp"],
+ "env": {
+ "PINCHTAB_URL": "http://192.168.1.50:9867",
+ "PINCHTAB_TOKEN": "your-secure-token"
+ }
+ }
+ }
+}
+```
+
+The `pinchtab mcp` process runs locally (on the agent machine) and makes HTTP calls to the remote PinchTab instance. Chrome is on the remote machine — only the stdio MCP transport is local.
+
+## Troubleshooting
+
+**"Connection refused" from all tools**
+
+PinchTab is not running, or is on a different port. Check:
+
+```bash
+curl http://127.0.0.1:9867/health
+```
+
+**"HTTP 401" from tools**
+
+Token mismatch. Set `PINCHTAB_TOKEN` to match `server.token` in your PinchTab config.
+
+**"HTTP 403" from `pinchtab_eval`**
+
+JavaScript evaluation is disabled. See [Enabling JavaScript Evaluation](#enabling-javascript-evaluation) above.
+
+**"ref not found" errors**
+
+Element refs change after every navigation or significant DOM update. Always call `pinchtab_snapshot` again after a page change before using refs from a previous snapshot.
+
+**MCP server not appearing in client**
+
+- Check the `command` value — `pinchtab` must be on PATH, or use an absolute path.
+- Run `pinchtab mcp` manually in a terminal to check for startup errors.
+- Check stderr output from the MCP process (client-specific, often in a log file).
+
+## Related Pages
+
+- [MCP Overview](../mcp.md)
+- [MCP Tool Reference](../reference/mcp-tools.md)
+- [MCP Architecture](../architecture/mcp.md)
+- [Security Guide](./security.md)
diff --git a/docs/index.json b/docs/index.json
index 4d4371dd..eb00ace5 100644
--- a/docs/index.json
+++ b/docs/index.json
@@ -5,11 +5,13 @@
"get-started.md",
"core-concepts.md",
"headless-vs-headed.md",
- "dashboard.md"
+ "dashboard.md",
+ "mcp.md"
],
"guides": [
"guides/contributing.md",
"guides/security.md",
+ "guides/mcp-agents.md",
"guides/attach-chrome.md",
"guides/multi-instance.md",
"guides/identifying-instances.md",
diff --git a/docs/mcp.md b/docs/mcp.md
new file mode 100644
index 00000000..d2d4ef26
--- /dev/null
+++ b/docs/mcp.md
@@ -0,0 +1,348 @@
+# MCP Server
+
+PinchTab includes a native [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server that lets AI agents control the browser directly through the standardized MCP interface.
+
+## Quick Start
+
+1. **Start PinchTab** in any mode (server or bridge):
+ ```bash
+ pinchtab
+ ```
+
+2. **Start the MCP server** (in a separate terminal or from your MCP client config):
+ ```bash
+ pinchtab mcp
+ ```
+
+The MCP server communicates over **stdio** (stdin/stdout with JSON-RPC 2.0), which is the standard transport for MCP tools.
+
+## Client Configuration
+
+### Claude Desktop
+
+Add to your `claude_desktop_config.json`:
+
+```json
+{
+ "mcpServers": {
+ "pinchtab": {
+ "command": "pinchtab",
+ "args": ["mcp"],
+ "env": {
+ "PINCHTAB_URL": "http://127.0.0.1:9867"
+ }
+ }
+ }
+}
+```
+
+### VS Code / GitHub Copilot
+
+Create `.vscode/mcp.json` in your workspace:
+
+```json
+{
+ "servers": {
+ "pinchtab": {
+ "type": "stdio",
+ "command": "pinchtab",
+ "args": ["mcp"]
+ }
+ }
+}
+```
+
+### Cursor
+
+Add to your Cursor MCP settings:
+
+```json
+{
+ "mcpServers": {
+ "pinchtab": {
+ "command": "pinchtab",
+ "args": ["mcp"]
+ }
+ }
+}
+```
+
+## Environment Variables
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `PINCHTAB_URL` | `http://127.0.0.1:9867` | PinchTab server URL |
+| `PINCHTAB_TOKEN` | *(from config)* | Auth token for secured servers |
+
+## Available Tools
+
+### Navigation (4 tools)
+
+| Tool | Description |
+|------|-------------|
+| `pinchtab_navigate` | Navigate to a URL |
+| `pinchtab_snapshot` | Get accessibility tree snapshot |
+| `pinchtab_screenshot` | Take a screenshot (base64 PNG) |
+| `pinchtab_get_text` | Extract readable text content |
+
+### Interaction (8 tools)
+
+| Tool | Description |
+|------|-------------|
+| `pinchtab_click` | Click an element by ref |
+| `pinchtab_type` | Type text into an input |
+| `pinchtab_press` | Press a keyboard key |
+| `pinchtab_hover` | Hover over an element |
+| `pinchtab_focus` | Focus an element |
+| `pinchtab_select` | Select a dropdown option |
+| `pinchtab_scroll` | Scroll page or element |
+| `pinchtab_fill` | Fill input via JS dispatch |
+
+### Content (3 tools)
+
+| Tool | Description |
+|------|-------------|
+| `pinchtab_eval` | Execute JavaScript |
+| `pinchtab_pdf` | Export page as PDF |
+| `pinchtab_find` | Find elements by text or CSS |
+
+### Tab Management (4 tools)
+
+| Tool | Description |
+|------|-------------|
+| `pinchtab_list_tabs` | List open browser tabs |
+| `pinchtab_close_tab` | Close a tab |
+| `pinchtab_health` | Check server health |
+| `pinchtab_cookies` | Get page cookies |
+
+### Utility (2 tools)
+
+| Tool | Description |
+|------|-------------|
+| `pinchtab_wait` | Wait for N milliseconds |
+| `pinchtab_wait_for_selector` | Wait for a CSS selector to appear |
+
+## Tool Reference
+
+### pinchtab_navigate
+
+Navigate the browser to a URL.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `url` | string | Yes | URL to navigate to |
+| `tabId` | string | No | Target tab (uses current if empty) |
+
+### pinchtab_snapshot
+
+Get an accessibility tree snapshot of the page. This is the primary way agents understand page structure.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `tabId` | string | No | Target tab |
+| `interactive` | boolean | No | Only interactive elements |
+| `compact` | boolean | No | Compact format (fewer tokens) |
+| `diff` | boolean | No | Only changes since last snapshot |
+| `selector` | string | No | CSS selector to scope |
+
+### pinchtab_screenshot
+
+Capture a screenshot of the page.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `tabId` | string | No | Target tab |
+| `quality` | number | No | JPEG quality 0-100 |
+
+### pinchtab_get_text
+
+Extract readable text from the page.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `tabId` | string | No | Target tab |
+| `raw` | boolean | No | Raw text without formatting |
+
+### pinchtab_click
+
+Click an element identified by its ref from a snapshot.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `ref` | string | Yes | Element ref (e.g., `e5`) |
+| `tabId` | string | No | Target tab |
+
+### pinchtab_type
+
+Type text into an input element.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `ref` | string | Yes | Element ref |
+| `text` | string | Yes | Text to type |
+| `tabId` | string | No | Target tab |
+
+### pinchtab_press
+
+Press a keyboard key.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `key` | string | Yes | Key name (Enter, Tab, Escape, etc.) |
+| `tabId` | string | No | Target tab |
+
+### pinchtab_hover
+
+Hover over an element.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `ref` | string | Yes | Element ref |
+| `tabId` | string | No | Target tab |
+
+### pinchtab_focus
+
+Focus an element.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `ref` | string | Yes | Element ref |
+| `tabId` | string | No | Target tab |
+
+### pinchtab_select
+
+Select a dropdown option.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `ref` | string | Yes | Select element ref |
+| `value` | string | Yes | Option value |
+| `tabId` | string | No | Target tab |
+
+### pinchtab_scroll
+
+Scroll the page or a specific element.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `ref` | string | No | Element ref (omit for page scroll) |
+| `pixels` | number | No | Pixels to scroll (positive=down) |
+| `tabId` | string | No | Target tab |
+
+### pinchtab_fill
+
+Fill an input using JavaScript dispatch (works with React/Vue/Angular).
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `ref` | string | Yes | Element ref or CSS selector |
+| `value` | string | Yes | Value to fill |
+| `tabId` | string | No | Target tab |
+
+### pinchtab_eval
+
+Execute JavaScript in the browser. Requires `security.allowEvaluate: true` in config.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `expression` | string | Yes | JavaScript expression |
+| `tabId` | string | No | Target tab |
+
+### pinchtab_pdf
+
+Export the page as a PDF document.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `tabId` | string | No | Target tab |
+| `landscape` | boolean | No | Landscape orientation |
+| `scale` | number | No | Print scale 0.1-2.0 |
+| `pageRanges` | string | No | Pages (e.g., "1-3,5") |
+
+### pinchtab_find
+
+Find elements by text content or CSS selector using semantic matching.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `query` | string | Yes | Text or CSS selector |
+| `tabId` | string | No | Target tab |
+
+### pinchtab_list_tabs
+
+List all open browser tabs. No parameters.
+
+### pinchtab_close_tab
+
+Close a browser tab.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `tabId` | string | No | Tab to close (current if empty) |
+
+### pinchtab_health
+
+Check server health. No parameters.
+
+### pinchtab_cookies
+
+Get cookies for the current page.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `tabId` | string | No | Target tab |
+
+### pinchtab_wait
+
+Wait for a specified duration.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `ms` | number | Yes | Milliseconds (max 30000) |
+
+### pinchtab_wait_for_selector
+
+Wait for a CSS selector to appear on the page. Polls every 250ms.
+
+| Parameter | Type | Required | Description |
+|-----------|------|----------|-------------|
+| `selector` | string | Yes | CSS selector |
+| `timeout` | number | No | Timeout ms (default 10000, max 30000) |
+| `tabId` | string | No | Target tab |
+
+## Typical Agent Workflow
+
+```
+1. pinchtab_navigate → go to URL
+2. pinchtab_snapshot → understand page structure
+3. pinchtab_click → interact with elements
+4. pinchtab_type → fill in forms
+5. pinchtab_snapshot → verify changes
+6. pinchtab_get_text → extract results
+```
+
+## Architecture
+
+The MCP server is a thin stdio-based JSON-RPC layer that translates MCP tool calls into HTTP requests to a running PinchTab instance:
+
+```
+LLM Client ──stdio──▶ pinchtab mcp ──HTTP──▶ PinchTab Server
+```
+
+This architecture means:
+- The MCP server works with any PinchTab deployment (local, remote, Docker)
+- No direct Chrome dependency — the server delegates to PinchTab
+- Built with [mcp-go](https://github.com/mark3labs/mcp-go) SDK (MCP spec 2025-11-25)
+
+## Code Layout
+
+```
+internal/mcp/
+├── server.go # MCP server setup and stdio transport
+├── tools.go # Tool definitions with JSON schemas
+├── handlers.go # Tool handler implementations
+└── client.go # HTTP client for PinchTab API
+
+cmd/pinchtab/
+└── cmd_mcp.go # `pinchtab mcp` subcommand
+```
diff --git a/docs/reference/index.md b/docs/reference/index.md
index 9df70c32..31f81d7d 100644
--- a/docs/reference/index.md
+++ b/docs/reference/index.md
@@ -26,3 +26,7 @@ Note: this index is generated and should be checked against the code when comman
- [Tabs](./tabs.md)
- [Text](./text.md)
- [Type](./type.md)
+
+## MCP Tools
+
+- [MCP Tool Reference](./mcp-tools.md)
diff --git a/docs/reference/mcp-tools.md b/docs/reference/mcp-tools.md
new file mode 100644
index 00000000..47323133
--- /dev/null
+++ b/docs/reference/mcp-tools.md
@@ -0,0 +1,308 @@
+# MCP Tool Reference
+
+Complete parameter reference for all 21 tools exposed by the PinchTab MCP server.
+
+All tool names are prefixed with `pinchtab_`. The server communicates over **stdio JSON-RPC 2.0** (MCP spec 2025-11-25).
+
+---
+
+## Navigation
+
+### pinchtab_navigate
+
+Navigate the browser to a URL.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `url` | string | **Yes** | Full URL including scheme (`http://` or `https://`) |
+| `tabId` | string | No | Target tab. Uses current tab if omitted. |
+
+**Returns:** JSON object with `tabId`, `url`, and `title`.
+
+```json
+{ "tabId": "abc123", "url": "https://example.com", "title": "Example Domain" }
+```
+
+---
+
+### pinchtab_snapshot
+
+Get an accessibility tree snapshot of the current page. This is the primary way agents understand page structure and discover interactive element refs.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `tabId` | string | No | Target tab |
+| `interactive` | boolean | No | Only return interactive elements (buttons, links, inputs) |
+| `compact` | boolean | No | Compact format — uses fewer tokens |
+| `diff` | boolean | No | Only changes since the last snapshot |
+| `selector` | string | No | CSS selector to scope the snapshot to a subtree |
+
+**Returns:** Accessibility tree as text. Element refs (e.g. `e5`, `e12`) are used in interaction tool calls.
+
+---
+
+### pinchtab_screenshot
+
+Capture a screenshot of the current page.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `tabId` | string | No | Target tab |
+| `quality` | number | No | JPEG quality 0–100 (default PNG) |
+
+**Returns:** Base64-encoded image string.
+
+---
+
+### pinchtab_get_text
+
+Extract readable text content from the page, suitable for summarisation and Q&A.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `tabId` | string | No | Target tab |
+| `raw` | boolean | No | Return raw text without formatting |
+
+**Returns:** Plain text string.
+
+---
+
+## Interaction
+
+All interaction tools that target page elements require a `ref` — the element identifier from a `pinchtab_snapshot` response (e.g. `e5`).
+
+### pinchtab_click
+
+Click an element by its accessibility ref.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `ref` | string | **Yes** | Element ref from snapshot (e.g. `e5`) |
+| `tabId` | string | No | Target tab |
+
+---
+
+### pinchtab_type
+
+Type text into an input element, simulating keystrokes.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `ref` | string | **Yes** | Element ref |
+| `text` | string | **Yes** | Text to type |
+| `tabId` | string | No | Target tab |
+
+---
+
+### pinchtab_press
+
+Press a named keyboard key.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `key` | string | **Yes** | Key name: `Enter`, `Tab`, `Escape`, `ArrowDown`, `Backspace`, etc. |
+| `tabId` | string | No | Target tab |
+
+---
+
+### pinchtab_hover
+
+Hover the mouse over an element (triggers `:hover` styles and tooltips).
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `ref` | string | **Yes** | Element ref |
+| `tabId` | string | No | Target tab |
+
+---
+
+### pinchtab_focus
+
+Give keyboard focus to an element.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `ref` | string | **Yes** | Element ref |
+| `tabId` | string | No | Target tab |
+
+---
+
+### pinchtab_select
+
+Select an option from a `<select>` dropdown.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `ref` | string | **Yes** | `<select>` element ref |
+| `value` | string | **Yes** | Option value to select |
+| `tabId` | string | No | Target tab |
+
+---
+
+### pinchtab_scroll
+
+Scroll the page or a specific element.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `ref` | string | No | Element ref. Omit to scroll the whole page. |
+| `pixels` | number | No | Pixels to scroll. Positive = down/right, negative = up/left. Default 300. |
+| `tabId` | string | No | Target tab |
+
+---
+
+### pinchtab_fill
+
+Fill an input field using JavaScript event dispatch. Works with React, Vue, Angular, and other frameworks that intercept native input events.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `ref` | string | **Yes** | Element ref or CSS selector |
+| `value` | string | **Yes** | Value to set |
+| `tabId` | string | No | Target tab |
+
+> **Tip:** Use `pinchtab_fill` instead of `pinchtab_type` when the page uses a frontend framework that does not react to raw keystroke simulation.
+
+---
+
+## Content
+
+### pinchtab_eval
+
+Execute a JavaScript expression in the browser context and return the result.
+
+> **Security note:** Requires `security.allowEvaluate: true` in the PinchTab config. Returns HTTP 403 by default.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `expression` | string | **Yes** | JavaScript expression to evaluate |
+| `tabId` | string | No | Target tab |
+
+**Returns:** JSON-serialised result of the expression.
+
+```javascript
+// Example expressions
+"document.title"
+"document.querySelectorAll('a').length"
+"window.location.href"
+```
+
+---
+
+### pinchtab_pdf
+
+Export the current page as a PDF document.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `tabId` | string | No | Target tab |
+| `landscape` | boolean | No | Landscape orientation (default portrait) |
+| `scale` | number | No | Print scale 0.1–2.0 (default 1.0) |
+| `pageRanges` | string | No | Pages to include, e.g. `"1-3,5"` |
+
+**Returns:** Base64-encoded PDF bytes.
+
+---
+
+### pinchtab_find
+
+Find elements by text content or CSS selector using semantic matching.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `query` | string | **Yes** | Text content or CSS selector |
+| `tabId` | string | No | Target tab |
+
+**Returns:** List of matching elements with their refs, text, and positions.
+
+---
+
+## Tab Management
+
+### pinchtab_list_tabs
+
+List all open browser tabs.
+
+No parameters.
+
+**Returns:** Array of tab objects with `tabId`, `url`, and `title`.
+
+---
+
+### pinchtab_close_tab
+
+Close a browser tab.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `tabId` | string | No | Tab to close. Closes the current tab if omitted. |
+
+---
+
+### pinchtab_health
+
+Check whether the PinchTab server is reachable and healthy.
+
+No parameters.
+
+**Returns:** `{"status":"ok"}` on success.
+
+---
+
+### pinchtab_cookies
+
+Get cookies for the current page.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `tabId` | string | No | Target tab |
+
+**Returns:** Array of cookie objects (name, value, domain, path, etc.).
+
+---
+
+## Utility
+
+### pinchtab_wait
+
+Wait for a fixed duration. Use sparingly — prefer `pinchtab_wait_for_selector` when possible.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `ms` | number | **Yes** | Milliseconds to wait. Maximum 30000. |
+
+---
+
+### pinchtab_wait_for_selector
+
+Wait for a CSS selector to appear on the page. Polls every 250 ms.
+
+| Parameter | Type | Required | Description |
+|-----------|------|:--------:|-------------|
+| `selector` | string | **Yes** | CSS selector to wait for |
+| `timeout` | number | No | Timeout in milliseconds. Default 10000, maximum 30000. |
+| `tabId` | string | No | Target tab |
+
+**Returns:** `{"present": true}` when the selector is found, `{"present": false}` on timeout.
+
+---
+
+## Error Responses
+
+All tools return errors as MCP tool errors (not Go-level errors). Common error patterns:
+
+| Situation | Response |
+|-----------|----------|
+| PinchTab not running | Connection refused error |
+| Element ref not found | `HTTP 500: ref not found` |
+| `pinchtab_eval` without security flag | `HTTP 403: evaluate not allowed` |
+| Invalid URL in navigate | `invalid URL: must start with http:// or https://` |
+| Required parameter missing | Parameter validation error from MCP SDK |
+
+---
+
+## Related Pages
+
+- [MCP User Guide](../mcp.md)
+- [MCP Architecture](../architecture/mcp.md)
+- [Security Guide](../guides/security.md)
diff --git a/go.mod b/go.mod
index 717a119a..8072c13d 100644
--- a/go.mod
+++ b/go.mod
@@ -6,27 +6,33 @@ require (
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d
github.com/chromedp/chromedp v0.14.2
github.com/gobwas/ws v1.4.0
+ github.com/gost-dom/browser v0.11.0
+ github.com/mark3labs/mcp-go v0.45.0
github.com/shirou/gopsutil/v4 v4.26.2
+ golang.org/x/net v0.47.0
gopkg.in/yaml.v3 v3.0.1
)
require (
+ github.com/bahlo/generic-list-go v0.2.0 // indirect
+ github.com/buger/jsonparser v1.1.1 // indirect
github.com/chromedp/sysutil v1.1.0 // indirect
github.com/ebitengine/purego v0.10.0 // indirect
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 // indirect
github.com/go-ole/go-ole v1.2.6 // indirect
github.com/gobwas/httphead v0.1.0 // indirect
github.com/gobwas/pool v0.2.1 // indirect
- github.com/gost-dom/browser v0.11.0 // indirect
+ github.com/google/uuid v1.6.0 // indirect
github.com/gost-dom/css v0.1.0 // indirect
- github.com/kr/pretty v0.3.0 // indirect
+ github.com/invopop/jsonschema v0.13.0 // indirect
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect
+ github.com/mailru/easyjson v0.7.7 // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
- github.com/rogpeppe/go-internal v1.14.1 // indirect
+ github.com/spf13/cast v1.7.1 // indirect
github.com/tklauser/go-sysconf v0.3.16 // indirect
github.com/tklauser/numcpus v0.11.0 // indirect
+ github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect
+ github.com/yosida95/uritemplate/v3 v3.0.2 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
- golang.org/x/net v0.47.0 // indirect
golang.org/x/sys v0.41.0 // indirect
- gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
)
diff --git a/go.sum b/go.sum
index b99f9dcb..635e4934 100644
--- a/go.sum
+++ b/go.sum
@@ -1,14 +1,19 @@
+github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
+github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
+github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
+github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d h1:ZtA1sedVbEW7EW80Iz2GR3Ye6PwbJAJXjv7D74xG6HU=
github.com/chromedp/cdproto v0.0.0-20250803210736-d308e07a266d/go.mod h1:NItd7aLkcfOA/dcMXvl8p1u+lQqioRMq/SqDp71Pb/k=
github.com/chromedp/chromedp v0.14.2 h1:r3b/WtwM50RsBZHMUm9fsNhhzRStTHrKdr2zmwbZSzM=
github.com/chromedp/chromedp v0.14.2/go.mod h1:rHzAv60xDE7VNy/MYtTUrYreSc0ujt2O1/C3bzctYBo=
github.com/chromedp/sysutil v1.1.0 h1:PUFNv5EcprjqXZD9nJb9b/c9ibAbxiYo4exNWZyipwM=
github.com/chromedp/sysutil v1.1.0/go.mod h1:WiThHUdltqCNKGc4gaU50XgYjwjYIhKWoHGPTUfWTJ8=
-github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=
github.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
+github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
+github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 h1:iizUGZ9pEquQS5jTGkh4AqeeHCMbfbjeb0zMt0aEFzs=
github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M=
github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=
@@ -22,40 +27,57 @@ github.com/gobwas/ws v1.4.0/go.mod h1:G3gNqMNtPppf5XUz7O4shetPpcZ1VJ7zt18dlUeakr
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gost-dom/browser v0.11.0 h1:eBz3bzY6BrfIR7bA6LOJl3aIHW/+0a9GfKjMWcPbe6g=
github.com/gost-dom/browser v0.11.0/go.mod h1:P3WlayFDicfvxIg90iZIqLqYuR84FJ4jYf8Qf3bKevw=
github.com/gost-dom/css v0.1.0 h1:O4aXjnYonQH1EDwKysXCQOgGVLwCWd/+HJeGO15sDIE=
github.com/gost-dom/css v0.1.0/go.mod h1:BYfl+dr6Dzl6RoKn4op6TynJ7GmFqP0kFCM44NEVgNs=
-github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
-github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
-github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
-github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
-github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
+github.com/gost-dom/fixture v0.1.0 h1:7PnEpkuww1QBOh4gyoR8updPfyosHJfxmFRY+2t05+w=
+github.com/gost-dom/fixture v0.1.0/go.mod h1:7mSGaBhOfi/NO+YiD426CQ1DTkko62vYxoSVRmveqqY=
+github.com/invopop/jsonschema v0.13.0 h1:KvpoAJWEjR3uD9Kbm2HWJmqsEaHt8lBUpd0qHcIi21E=
+github.com/invopop/jsonschema v0.13.0/go.mod h1:ffZ5Km5SWWRAIN6wbDXItl95euhFz2uON45H2qjYt+0=
+github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80 h1:6Yzfa6GP0rIo/kULo2bwGEkFvCePZ3qHDDTC3/J9Swo=
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4=
github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I=
+github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
+github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
+github.com/mark3labs/mcp-go v0.45.0 h1:s0S8qR/9fWaQ3pHxz7pm1uQ0DrswoSnRIxKIjbiQtkc=
+github.com/mark3labs/mcp-go v0.45.0/go.mod h1:YnJfOL382MIWDx1kMY+2zsRHU/q78dBg9aFb8W6Thdw=
+github.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A=
+github.com/onsi/gomega v1.38.2/go.mod h1:W2MJcYxRGV63b418Ai34Ud0hEdTVXq9NW9+Sx6uXf3k=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde h1:x0TT0RDC7UhAVbbWWBzr41ElhJx5tXPWkIHA2HWPRuw=
github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzbfBr3hhjoZnS66nKrHmduYNpc34ny7RK4z5/HM0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
-github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=
github.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=
+github.com/spf13/cast v1.7.1 h1:cuNEagBQEHWN1FnbGEjCXL2szYEXqfJPbP2HNUaca9Y=
+github.com/spf13/cast v1.7.1/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=
github.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=
github.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=
github.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=
+github.com/wk8/go-ordered-map/v2 v2.1.8 h1:5h/BUHu93oj4gIdvHHHGsScSTMijfx5PeYkE/fJgbpc=
+github.com/wk8/go-ordered-map/v2 v2.1.8/go.mod h1:5nJHM5DyteebpVlHnWMV0rPz6Zp7+xBAnxjb1X5vnTw=
+github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
+github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
+go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
+go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
@@ -68,11 +90,12 @@ golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
+golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
-gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/internal/mcp/client.go b/internal/mcp/client.go
new file mode 100644
index 00000000..2b0c54fd
--- /dev/null
+++ b/internal/mcp/client.go
@@ -0,0 +1,85 @@
+// Package mcp provides a native MCP (Model Context Protocol) server for PinchTab.
+package mcp
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "time"
+)
+
+// Client is an HTTP client for PinchTab's REST API.
+type Client struct {
+ BaseURL string
+ Token string
+ HTTPClient *http.Client
+}
+
+// NewClient creates a Client for the given PinchTab base URL.
+func NewClient(baseURL, token string) *Client {
+ return &Client{
+ BaseURL: baseURL,
+ Token: token,
+ HTTPClient: &http.Client{
+ Timeout: 120 * time.Second,
+ },
+ }
+}
+
+func (c *Client) url(path string) string {
+ return c.BaseURL + path
+}
+
+func (c *Client) do(req *http.Request) ([]byte, int, error) {
+ if c.Token != "" {
+ req.Header.Set("Authorization", "Bearer "+c.Token)
+ }
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return nil, 0, fmt.Errorf("request %s %s: %w", req.Method, req.URL.Path, err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ body, err := io.ReadAll(io.LimitReader(resp.Body, 10<<20)) // 10 MB limit
+ if err != nil {
+ return nil, resp.StatusCode, fmt.Errorf("read response: %w", err)
+ }
+ return body, resp.StatusCode, nil
+}
+
+// Get performs a GET request and returns the response body.
+func (c *Client) Get(ctx context.Context, path string, query url.Values) ([]byte, int, error) {
+ u := c.url(path)
+ if len(query) > 0 {
+ u += "?" + query.Encode()
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
+ if err != nil {
+ return nil, 0, err
+ }
+ return c.do(req)
+}
+
+// Post performs a POST request with a JSON body.
+func (c *Client) Post(ctx context.Context, path string, payload any) ([]byte, int, error) {
+ var body io.Reader
+ if payload != nil {
+ b, err := json.Marshal(payload)
+ if err != nil {
+ return nil, 0, fmt.Errorf("marshal payload: %w", err)
+ }
+ body = bytes.NewReader(b)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url(path), body)
+ if err != nil {
+ return nil, 0, err
+ }
+ if payload != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ return c.do(req)
+}
diff --git a/internal/mcp/client_test.go b/internal/mcp/client_test.go
new file mode 100644
index 00000000..46213a59
--- /dev/null
+++ b/internal/mcp/client_test.go
@@ -0,0 +1,141 @@
+package mcp
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+func TestNewClient(t *testing.T) {
+ c := NewClient("http://localhost:9867", "tok123")
+ if c.BaseURL != "http://localhost:9867" {
+ t.Fatalf("BaseURL = %q, want %q", c.BaseURL, "http://localhost:9867")
+ }
+ if c.Token != "tok123" {
+ t.Fatalf("Token = %q, want %q", c.Token, "tok123")
+ }
+ if c.HTTPClient == nil {
+ t.Fatal("HTTPClient is nil")
+ }
+}
+
+func TestClientGet(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ t.Errorf("method = %s, want GET", r.Method)
+ }
+ if r.Header.Get("Authorization") != "Bearer testtoken" {
+ t.Errorf("no auth header")
+ }
+ if r.URL.Query().Get("tabId") != "t1" {
+ t.Errorf("tabId = %q, want t1", r.URL.Query().Get("tabId"))
+ }
+ w.WriteHeader(200)
+ _, _ = io.WriteString(w, `{"ok":true}`)
+ }))
+ defer srv.Close()
+
+ c := NewClient(srv.URL, "testtoken")
+ body, code, err := c.Get(context.Background(), "/health", url.Values{"tabId": {"t1"}})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code != 200 {
+ t.Fatalf("code = %d, want 200", code)
+ }
+ if !strings.Contains(string(body), `"ok":true`) {
+ t.Fatalf("body = %q", body)
+ }
+}
+
+func TestClientGetNoQuery(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.RawQuery != "" {
+ t.Errorf("unexpected query: %s", r.URL.RawQuery)
+ }
+ w.WriteHeader(200)
+ _, _ = io.WriteString(w, `{}`)
+ }))
+ defer srv.Close()
+
+ c := NewClient(srv.URL, "")
+ _, code, err := c.Get(context.Background(), "/health", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code != 200 {
+ t.Fatalf("code = %d", code)
+ }
+}
+
+func TestClientPost(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ t.Errorf("method = %s, want POST", r.Method)
+ }
+ if ct := r.Header.Get("Content-Type"); ct != "application/json" {
+ t.Errorf("content-type = %q", ct)
+ }
+ body, _ := io.ReadAll(r.Body)
+ if !strings.Contains(string(body), `"url"`) {
+ t.Errorf("body missing url field: %s", body)
+ }
+ w.WriteHeader(200)
+ _, _ = io.WriteString(w, `{"navigated":true}`)
+ }))
+ defer srv.Close()
+
+ c := NewClient(srv.URL, "")
+ body, code, err := c.Post(context.Background(), "/navigate", map[string]any{"url": "https://example.com"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code != 200 {
+ t.Fatalf("code = %d", code)
+ }
+ if !strings.Contains(string(body), "navigated") {
+ t.Fatalf("body = %q", body)
+ }
+}
+
+func TestClientPostNilPayload(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ if len(body) != 0 {
+ t.Errorf("expected empty body, got %s", body)
+ }
+ w.WriteHeader(200)
+ _, _ = io.WriteString(w, `{}`)
+ }))
+ defer srv.Close()
+
+ c := NewClient(srv.URL, "")
+ _, code, err := c.Post(context.Background(), "/shutdown", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if code != 200 {
+ t.Fatalf("code = %d", code)
+ }
+}
+
+func TestClientAuthHeaderAbsentWhenNoToken(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if h := r.Header.Get("Authorization"); h != "" {
+ t.Errorf("unexpected Authorization header: %s", h)
+ }
+ w.WriteHeader(200)
+ _, _ = io.WriteString(w, `{}`)
+ }))
+ defer srv.Close()
+
+ c := NewClient(srv.URL, "")
+ _, _, err := c.Get(context.Background(), "/health", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/internal/mcp/handlers.go b/internal/mcp/handlers.go
new file mode 100644
index 00000000..3da5d906
--- /dev/null
+++ b/internal/mcp/handlers.go
@@ -0,0 +1,429 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/url"
+ "strings"
+ "time"
+
+ "github.com/mark3labs/mcp-go/mcp"
+)
+
+// maxWaitMS caps wait/timeout durations for safety.
+const maxWaitMS = 30_000
+
+// handlerMap returns a name→handler map for all PinchTab MCP tools.
+func handlerMap(c *Client) map[string]func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return map[string]func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error){
+ // Navigation
+ "pinchtab_navigate": handleNavigate(c),
+ "pinchtab_snapshot": handleSnapshot(c),
+ "pinchtab_screenshot": handleScreenshot(c),
+ "pinchtab_get_text": handleGetText(c),
+
+ // Interaction
+ "pinchtab_click": handleAction(c, "click"),
+ "pinchtab_type": handleAction(c, "type"),
+ "pinchtab_press": handleAction(c, "press"),
+ "pinchtab_hover": handleAction(c, "hover"),
+ "pinchtab_focus": handleAction(c, "focus"),
+ "pinchtab_select": handleAction(c, "select"),
+ "pinchtab_scroll": handleAction(c, "scroll"),
+ "pinchtab_fill": handleAction(c, "fill"),
+
+ // Content
+ "pinchtab_eval": handleEval(c),
+ "pinchtab_pdf": handlePDF(c),
+ "pinchtab_find": handleFind(c),
+
+ // Tab management
+ "pinchtab_list_tabs": handleListTabs(c),
+ "pinchtab_close_tab": handleCloseTab(c),
+ "pinchtab_health": handleHealth(c),
+ "pinchtab_cookies": handleCookies(c),
+
+ // Utility
+ "pinchtab_wait": handleWait(),
+ "pinchtab_wait_for_selector": handleWaitForSelector(c),
+ }
+}
+
+// ── helpers ────────────────────────────────────────────────────────────
+
+func optString(r mcp.CallToolRequest, key string) string {
+ v, _ := r.GetArguments()[key].(string)
+ return v
+}
+
+func optFloat(r mcp.CallToolRequest, key string) (float64, bool) {
+ v, ok := r.GetArguments()[key].(float64)
+ return v, ok
+}
+
+func optBool(r mcp.CallToolRequest, key string) (bool, bool) {
+ v, ok := r.GetArguments()[key].(bool)
+ return v, ok
+}
+
+func resultFromBytes(body []byte, code int) (*mcp.CallToolResult, error) {
+ if code >= 400 {
+ return mcp.NewToolResultError(fmt.Sprintf("HTTP %d: %s", code, string(body))), nil
+ }
+ return mcp.NewToolResultText(string(body)), nil
+}
+
+// ── Navigation handlers ────────────────────────────────────────────────
+
+func handleNavigate(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ u, err := r.RequireString("url")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ parsed, err := url.Parse(u)
+ if err != nil || !strings.HasPrefix(parsed.Scheme, "http") {
+ return mcp.NewToolResultError("invalid URL: must start with http:// or https://"), nil
+ }
+ payload := map[string]any{"url": u}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ payload["tabId"] = tabID
+ }
+ body, code, err := c.Post(ctx, "/navigate", payload)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+func handleSnapshot(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ q := url.Values{}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ q.Set("tabId", tabID)
+ }
+ if v, ok := optBool(r, "interactive"); ok && v {
+ q.Set("interactive", "true")
+ }
+ if v, ok := optBool(r, "compact"); ok && v {
+ q.Set("compact", "true")
+ }
+ if v, ok := optBool(r, "diff"); ok && v {
+ q.Set("diff", "true")
+ }
+ if sel := optString(r, "selector"); sel != "" {
+ q.Set("selector", sel)
+ }
+ body, code, err := c.Get(ctx, "/snapshot", q)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+func handleScreenshot(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ q := url.Values{}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ q.Set("tabId", tabID)
+ }
+ if quality, ok := optFloat(r, "quality"); ok {
+ q.Set("quality", fmt.Sprintf("%d", int(quality)))
+ }
+ body, code, err := c.Get(ctx, "/screenshot", q)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+func handleGetText(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ q := url.Values{}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ q.Set("tabId", tabID)
+ }
+ if v, ok := optBool(r, "raw"); ok && v {
+ q.Set("mode", "raw")
+ }
+ body, code, err := c.Get(ctx, "/text", q)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+// ── Interaction handlers ───────────────────────────────────────────────
+
+func handleAction(c *Client, kind string) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ payload := map[string]any{"kind": kind}
+
+ if tabID := optString(r, "tabId"); tabID != "" {
+ payload["tabId"] = tabID
+ }
+
+ switch kind {
+ case "click", "hover", "focus":
+ ref, err := r.RequireString("ref")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ payload["ref"] = ref
+
+ case "type":
+ ref, err := r.RequireString("ref")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ text, err := r.RequireString("text")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ payload["ref"] = ref
+ payload["text"] = text
+
+ case "press":
+ key, err := r.RequireString("key")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ payload["key"] = key
+
+ case "select":
+ ref, err := r.RequireString("ref")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ value, err := r.RequireString("value")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ payload["ref"] = ref
+ payload["value"] = value
+
+ case "scroll":
+ if ref := optString(r, "ref"); ref != "" {
+ payload["ref"] = ref
+ }
+ if px, ok := optFloat(r, "pixels"); ok {
+ payload["scrollY"] = int(px)
+ }
+
+ case "fill":
+ ref, err := r.RequireString("ref")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ value, err := r.RequireString("value")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ payload["ref"] = ref
+ payload["value"] = value
+ }
+
+ body, code, err := c.Post(ctx, "/action", payload)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+// ── Content handlers ───────────────────────────────────────────────────
+
+func handleEval(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ expr, err := r.RequireString("expression")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ payload := map[string]any{"expression": expr}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ payload["tabId"] = tabID
+ }
+ body, code, err := c.Post(ctx, "/evaluate", payload)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+func handlePDF(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ q := url.Values{}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ q.Set("tabId", tabID)
+ }
+ if v, ok := optBool(r, "landscape"); ok && v {
+ q.Set("landscape", "true")
+ }
+ if scale, ok := optFloat(r, "scale"); ok {
+ q.Set("scale", fmt.Sprintf("%.2f", scale))
+ }
+ if pr := optString(r, "pageRanges"); pr != "" {
+ q.Set("pageRanges", pr)
+ }
+ body, code, err := c.Get(ctx, "/pdf", q)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+func handleFind(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ query, err := r.RequireString("query")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ payload := map[string]any{"query": query}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ payload["tabId"] = tabID
+ }
+ body, code, err := c.Post(ctx, "/find", payload)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+// ── Tab management handlers ────────────────────────────────────────────
+
+func handleListTabs(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ body, code, err := c.Get(ctx, "/tabs", nil)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+func handleCloseTab(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ payload := map[string]any{"action": "close"}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ payload["tabId"] = tabID
+ }
+ body, code, err := c.Post(ctx, "/tab", payload)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+func handleHealth(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ body, code, err := c.Get(ctx, "/health", nil)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+func handleCookies(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ q := url.Values{}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ q.Set("tabId", tabID)
+ }
+ body, code, err := c.Get(ctx, "/cookies", q)
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ return resultFromBytes(body, code)
+ }
+}
+
+// ── Utility handlers ───────────────────────────────────────────────────
+
+func handleWait() func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ ms, err := r.RequireFloat("ms")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ if ms < 0 {
+ ms = 0
+ }
+ if ms > maxWaitMS {
+ ms = maxWaitMS
+ }
+ select {
+ case <-time.After(time.Duration(ms) * time.Millisecond):
+ return mcp.NewToolResultText(fmt.Sprintf(`{"waited_ms":%d}`, int(ms))), nil
+ case <-ctx.Done():
+ return mcp.NewToolResultError("wait cancelled"), nil
+ }
+ }
+}
+
+func handleWaitForSelector(c *Client) func(context.Context, mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ return func(ctx context.Context, r mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ selector, err := r.RequireString("selector")
+ if err != nil {
+ return mcp.NewToolResultError(err.Error()), nil
+ }
+ timeoutMS := 10000.0
+ if t, ok := optFloat(r, "timeout"); ok {
+ timeoutMS = t
+ }
+ if timeoutMS > maxWaitMS {
+ timeoutMS = maxWaitMS
+ }
+ if timeoutMS < 100 {
+ timeoutMS = 100
+ }
+
+ // JavaScript that checks for the selector
+ js := fmt.Sprintf(`document.querySelector(%s) !== null`, jsonString(selector))
+
+ payload := map[string]any{"expression": js}
+ if tabID := optString(r, "tabId"); tabID != "" {
+ payload["tabId"] = tabID
+ }
+
+ deadline := time.Now().Add(time.Duration(timeoutMS) * time.Millisecond)
+ interval := 250 * time.Millisecond
+
+ for {
+ body, code, err := c.Post(ctx, "/evaluate", payload)
+ if err == nil && code < 400 {
+ var resp struct {
+ Result any `json:"result"`
+ }
+ if json.Unmarshal(body, &resp) == nil && resp.Result == true {
+ return mcp.NewToolResultText(fmt.Sprintf(`{"found":true,"selector":%s}`, jsonString(selector))), nil
+ }
+ }
+
+ if time.Now().After(deadline) {
+ return mcp.NewToolResultError(fmt.Sprintf("timeout: selector %q not found within %dms", selector, int(timeoutMS))), nil
+ }
+
+ select {
+ case <-time.After(interval):
+ case <-ctx.Done():
+ return mcp.NewToolResultError("wait_for_selector cancelled"), nil
+ }
+ }
+ }
+}
+
+// jsonString returns a JSON-encoded string (with quotes).
+func jsonString(s string) string {
+ b, _ := json.Marshal(s)
+ return string(b)
+}
diff --git a/internal/mcp/handlers_test.go b/internal/mcp/handlers_test.go
new file mode 100644
index 00000000..a4eaba4f
--- /dev/null
+++ b/internal/mcp/handlers_test.go
@@ -0,0 +1,528 @@
+package mcp
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/mark3labs/mcp-go/mcp"
+)
+
+// mockPinchTab returns an httptest.Server that echoes back request details.
+func mockPinchTab() *httptest.Server {
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ resp := map[string]any{
+ "path": r.URL.Path,
+ "method": r.Method,
+ }
+
+ // Echo query params
+ if r.URL.RawQuery != "" {
+ resp["query"] = r.URL.Query()
+ }
+
+ // Echo JSON body
+ if r.Method == http.MethodPost {
+ body, _ := io.ReadAll(r.Body)
+ if len(body) > 0 {
+ var parsed map[string]any
+ if json.Unmarshal(body, &parsed) == nil {
+ resp["body"] = parsed
+ }
+ }
+ }
+
+ // Special: /evaluate for wait_for_selector returns true
+ if r.URL.Path == "/evaluate" {
+ resp["result"] = true
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(200)
+ _ = json.NewEncoder(w).Encode(resp)
+ }))
+}
+
+func callTool(t *testing.T, name string, args map[string]any, srv *httptest.Server) *mcp.CallToolResult {
+ t.Helper()
+ c := NewClient(srv.URL, "")
+ handlers := handlerMap(c)
+ h, ok := handlers[name]
+ if !ok {
+ t.Fatalf("no handler for %q", name)
+ }
+ req := mcp.CallToolRequest{}
+ req.Params.Name = name
+ req.Params.Arguments = args
+ result, err := h(context.Background(), req)
+ if err != nil {
+ t.Fatalf("handler error: %v", err)
+ }
+ return result
+}
+
+func resultText(t *testing.T, r *mcp.CallToolResult) string {
+ t.Helper()
+ if len(r.Content) == 0 {
+ t.Fatal("no content in result")
+ }
+ tc, ok := r.Content[0].(mcp.TextContent)
+ if !ok {
+ t.Fatalf("content[0] is %T, not TextContent", r.Content[0])
+ }
+ return tc.Text
+}
+
+func TestHandleNavigate(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_navigate", map[string]any{
+ "url": "https://example.com",
+ "tabId": "t1",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "/navigate") {
+ t.Errorf("expected /navigate in response, got %s", text)
+ }
+ if !strings.Contains(text, "https://example.com") {
+ t.Errorf("expected URL in response, got %s", text)
+ }
+}
+
+func TestHandleNavigateMissingURL(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_navigate", map[string]any{}, srv)
+ if !r.IsError {
+ t.Error("expected error for missing URL")
+ }
+}
+
+func TestHandleNavigateInvalidURL(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_navigate", map[string]any{"url": "not-a-url"}, srv)
+ if !r.IsError {
+ t.Error("expected error for invalid URL scheme")
+ }
+ text := resultText(t, r)
+ if !strings.Contains(text, "invalid URL") {
+ t.Errorf("expected 'invalid URL' in error, got %s", text)
+ }
+}
+
+func TestHandleNavigateFTPScheme(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_navigate", map[string]any{"url": "ftp://files.example.com/readme"}, srv)
+ if !r.IsError {
+ t.Error("expected error for ftp:// URL")
+ }
+}
+
+func TestHandleSnapshot(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_snapshot", map[string]any{
+ "interactive": true,
+ "compact": true,
+ "selector": "#main",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "/snapshot") {
+ t.Errorf("expected /snapshot path, got %s", text)
+ }
+}
+
+func TestHandleScreenshot(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_screenshot", map[string]any{
+ "quality": float64(90),
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "/screenshot") {
+ t.Errorf("expected /screenshot, got %s", text)
+ }
+}
+
+func TestHandleGetText(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_get_text", map[string]any{
+ "raw": true,
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "/text") {
+ t.Errorf("expected /text, got %s", text)
+ }
+}
+
+func TestHandleClick(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_click", map[string]any{
+ "ref": "e5",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "click") {
+ t.Errorf("expected click in response, got %s", text)
+ }
+}
+
+func TestHandleClickMissingRef(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_click", map[string]any{}, srv)
+ if !r.IsError {
+ t.Error("expected error for missing ref")
+ }
+}
+
+func TestHandleType(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_type", map[string]any{
+ "ref": "e12",
+ "text": "hello world",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "type") {
+ t.Errorf("expected type in response, got %s", text)
+ }
+ if !strings.Contains(text, "hello world") {
+ t.Errorf("expected text in response, got %s", text)
+ }
+}
+
+func TestHandlePress(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_press", map[string]any{
+ "key": "Enter",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "Enter") {
+ t.Errorf("expected Enter in response, got %s", text)
+ }
+}
+
+func TestHandleSelect(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_select", map[string]any{
+ "ref": "e3",
+ "value": "option2",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "select") {
+ t.Errorf("expected select, got %s", text)
+ }
+}
+
+func TestHandleScroll(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_scroll", map[string]any{
+ "pixels": float64(500),
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "scroll") {
+ t.Errorf("expected scroll, got %s", text)
+ }
+}
+
+func TestHandleFill(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_fill", map[string]any{
+ "ref": "e7",
+ "value": "[email protected]",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "fill") {
+ t.Errorf("expected fill, got %s", text)
+ }
+}
+
+func TestHandleEval(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_eval", map[string]any{
+ "expression": "document.title",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "/evaluate") {
+ t.Errorf("expected /evaluate, got %s", text)
+ }
+}
+
+func TestHandleEvalMissingExpression(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_eval", map[string]any{}, srv)
+ if !r.IsError {
+ t.Error("expected error for missing expression")
+ }
+}
+
+func TestHandlePDF(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_pdf", map[string]any{
+ "landscape": true,
+ "scale": float64(0.8),
+ "pageRanges": "1-3",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "/pdf") {
+ t.Errorf("expected /pdf, got %s", text)
+ }
+}
+
+func TestHandleFind(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_find", map[string]any{
+ "query": "login button",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "/find") {
+ t.Errorf("expected /find, got %s", text)
+ }
+}
+
+func TestHandleListTabs(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_list_tabs", map[string]any{}, srv)
+ text := resultText(t, r)
+ if !strings.Contains(text, "/tabs") {
+ t.Errorf("expected /tabs, got %s", text)
+ }
+}
+
+func TestHandleCloseTab(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_close_tab", map[string]any{
+ "tabId": "t2",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "close") {
+ t.Errorf("expected close, got %s", text)
+ }
+}
+
+func TestHandleHealth(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_health", map[string]any{}, srv)
+ text := resultText(t, r)
+ if !strings.Contains(text, "/health") {
+ t.Errorf("expected /health, got %s", text)
+ }
+}
+
+func TestHandleCookies(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_cookies", map[string]any{
+ "tabId": "t1",
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "/cookies") {
+ t.Errorf("expected /cookies, got %s", text)
+ }
+}
+
+func TestHandleWait(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_wait", map[string]any{
+ "ms": float64(50),
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "waited_ms") {
+ t.Errorf("expected waited_ms, got %s", text)
+ }
+}
+
+func TestHandleWaitClampsMax(t *testing.T) {
+ // Verify that the wait handler clamps values > maxWaitMS.
+ // We don't actually wait — just check the handler's clamping logic
+ // by inspecting the response. Use a small value that still triggers clamping.
+ ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
+ defer cancel()
+
+ c := NewClient("http://localhost:1", "")
+ handlers := handlerMap(c)
+ h := handlers["pinchtab_wait"]
+ req := mcp.CallToolRequest{}
+ req.Params.Name = "pinchtab_wait"
+ req.Params.Arguments = map[string]any{"ms": float64(999999)}
+ r, err := h(ctx, req)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ // Context will cancel before 30s expires, so we expect cancellation.
+ text := resultText(t, r)
+ if !strings.Contains(text, "cancelled") && !strings.Contains(text, "30000") {
+ t.Errorf("expected 'cancelled' or '30000', got %s", text)
+ }
+}
+
+func TestHandleWaitForSelector(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_wait_for_selector", map[string]any{
+ "selector": ".loaded",
+ "timeout": float64(5000),
+ }, srv)
+
+ text := resultText(t, r)
+ if !strings.Contains(text, "found") {
+ t.Errorf("expected found, got %s", text)
+ }
+}
+
+func TestHandleWaitForSelectorMissing(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_wait_for_selector", map[string]any{}, srv)
+ if !r.IsError {
+ t.Error("expected error for missing selector")
+ }
+}
+
+func TestHandleHTTPError(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(500)
+ _, _ = io.WriteString(w, `{"error":"internal"}`)
+ }))
+ defer srv.Close()
+
+ c := NewClient(srv.URL, "")
+ handlers := handlerMap(c)
+ h := handlers["pinchtab_health"]
+ req := mcp.CallToolRequest{}
+ req.Params.Name = "pinchtab_health"
+ req.Params.Arguments = map[string]any{}
+ r, err := h(context.Background(), req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !r.IsError {
+ t.Error("expected error result for HTTP 500")
+ }
+}
+
+func TestHandleHover(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_hover", map[string]any{"ref": "e3"}, srv)
+ text := resultText(t, r)
+ if !strings.Contains(text, "hover") {
+ t.Errorf("expected hover, got %s", text)
+ }
+}
+
+func TestHandleFocus(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_focus", map[string]any{"ref": "e1"}, srv)
+ text := resultText(t, r)
+ if !strings.Contains(text, "focus") {
+ t.Errorf("expected focus, got %s", text)
+ }
+}
+
+func TestHandleContextCancellation(t *testing.T) {
+ // Slow server that blocks until context is cancelled
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ <-r.Context().Done()
+ }))
+ defer srv.Close()
+
+ c := NewClient(srv.URL, "")
+ handlers := handlerMap(c)
+ h := handlers["pinchtab_health"]
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel() // cancel immediately
+
+ req := mcp.CallToolRequest{}
+ req.Params.Name = "pinchtab_health"
+ req.Params.Arguments = map[string]any{}
+
+ r, err := h(ctx, req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !r.IsError {
+ t.Error("expected error result when context is cancelled")
+ }
+}
+
+func TestHandleWaitNegativeMs(t *testing.T) {
+ srv := mockPinchTab()
+ defer srv.Close()
+
+ r := callTool(t, "pinchtab_wait", map[string]any{"ms": float64(-100)}, srv)
+ text := resultText(t, r)
+ if !strings.Contains(text, "waited_ms") {
+ t.Errorf("expected waited_ms, got %s", text)
+ }
+ if !strings.Contains(text, "0") {
+ t.Errorf("expected 0ms for negative input, got %s", text)
+ }
+}
diff --git a/internal/mcp/server.go b/internal/mcp/server.go
new file mode 100644
index 00000000..d986620c
--- /dev/null
+++ b/internal/mcp/server.go
@@ -0,0 +1,41 @@
+package mcp
+
+import (
+ "fmt"
+
+ "github.com/mark3labs/mcp-go/server"
+)
+
+// Version is the MCP server version, set at build time.
+var Version = "dev"
+
+// NewServer creates a fully configured MCP server with all PinchTab tools registered.
+func NewServer(baseURL, token string) *server.MCPServer {
+ c := NewClient(baseURL, token)
+
+ s := server.NewMCPServer(
+ "PinchTab",
+ Version,
+ server.WithToolCapabilities(false),
+ server.WithRecovery(),
+ )
+
+ tools := allTools()
+ handlers := handlerMap(c)
+
+ for _, tool := range tools {
+ h, ok := handlers[tool.Name]
+ if !ok {
+ panic(fmt.Sprintf("mcp: no handler for tool %q", tool.Name))
+ }
+ s.AddTool(tool, h)
+ }
+
+ return s
+}
+
+// Serve starts the MCP server on stdio.
+func Serve(baseURL, token string) error {
+ s := NewServer(baseURL, token)
+ return server.ServeStdio(s)
+}
diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.go
new file mode 100644
index 00000000..51d23ef6
--- /dev/null
+++ b/internal/mcp/server_test.go
@@ -0,0 +1,51 @@
+package mcp
+
+import (
+ "testing"
+)
+
+func TestNewServer(t *testing.T) {
+ s := NewServer("http://localhost:9867", "tok")
+ if s == nil {
+ t.Fatal("NewServer returned nil")
+ }
+}
+
+func TestNewServerRegistersAllTools(t *testing.T) {
+ _ = NewServer("http://localhost:9867", "")
+ tools := allTools()
+
+ // The server should have registered all tools.
+ // We verify by checking that NewServer doesn't panic — the panic
+ // in NewServer fires if any tool lacks a handler.
+ if len(tools) != 21 {
+ t.Errorf("expected 21 tools, got %d", len(tools))
+ }
+}
+
+func TestAllToolsHaveUniqueNames(t *testing.T) {
+ tools := allTools()
+ seen := make(map[string]bool, len(tools))
+ for _, tool := range tools {
+ if seen[tool.Name] {
+ t.Errorf("duplicate tool name: %s", tool.Name)
+ }
+ seen[tool.Name] = true
+ }
+}
+
+func TestAllToolsHaveHandlers(t *testing.T) {
+ tools := allTools()
+ handlers := handlerMap(NewClient("http://localhost:9867", ""))
+ for _, tool := range tools {
+ if _, ok := handlers[tool.Name]; !ok {
+ t.Errorf("tool %q has no handler", tool.Name)
+ }
+ }
+}
+
+func TestVersionDefault(t *testing.T) {
+ if Version != "dev" {
+ t.Errorf("default Version = %q, want 'dev'", Version)
+ }
+}
diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go
new file mode 100644
index 00000000..1e892d6d
--- /dev/null
+++ b/internal/mcp/tools.go
@@ -0,0 +1,126 @@
+package mcp
+
+import "github.com/mark3labs/mcp-go/mcp"
+
+// allTools returns every MCP tool exposed by the PinchTab MCP server.
+func allTools() []mcp.Tool {
+ return []mcp.Tool{
+ // ── Navigation ──────────────────────────────────────────────
+ mcp.NewTool("pinchtab_navigate",
+ mcp.WithDescription("Navigate to a URL in the browser"),
+ mcp.WithString("url", mcp.Required(), mcp.Description("The URL to navigate to")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID (optional, uses current tab if empty)")),
+ ),
+ mcp.NewTool("pinchtab_snapshot",
+ mcp.WithDescription("Get an accessibility tree snapshot of the current page"),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ mcp.WithBoolean("interactive", mcp.Description("Only interactive elements (buttons, links, inputs)")),
+ mcp.WithBoolean("compact", mcp.Description("Compact format (most token-efficient)")),
+ mcp.WithBoolean("diff", mcp.Description("Only changes since last snapshot")),
+ mcp.WithString("selector", mcp.Description("CSS selector to scope the snapshot")),
+ ),
+ mcp.NewTool("pinchtab_screenshot",
+ mcp.WithDescription("Take a screenshot of the current page (returns base64 PNG)"),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ mcp.WithNumber("quality", mcp.Description("JPEG quality 0-100 (only for JPEG format)")),
+ ),
+ mcp.NewTool("pinchtab_get_text",
+ mcp.WithDescription("Extract readable text content from the current page"),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ mcp.WithBoolean("raw", mcp.Description("Return raw text without formatting")),
+ ),
+
+ // ── Interaction ─────────────────────────────────────────────
+ mcp.NewTool("pinchtab_click",
+ mcp.WithDescription("Click an element by its accessibility ref"),
+ mcp.WithString("ref", mcp.Required(), mcp.Description("Element ref from snapshot (e.g., 'e5')")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_type",
+ mcp.WithDescription("Type text into an input element"),
+ mcp.WithString("ref", mcp.Required(), mcp.Description("Element ref from snapshot")),
+ mcp.WithString("text", mcp.Required(), mcp.Description("Text to type")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_press",
+ mcp.WithDescription("Press a keyboard key (Enter, Tab, Escape, etc.)"),
+ mcp.WithString("key", mcp.Required(), mcp.Description("Key to press (e.g., 'Enter', 'Tab', 'Escape')")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_hover",
+ mcp.WithDescription("Hover over an element"),
+ mcp.WithString("ref", mcp.Required(), mcp.Description("Element ref from snapshot")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_focus",
+ mcp.WithDescription("Focus an element"),
+ mcp.WithString("ref", mcp.Required(), mcp.Description("Element ref from snapshot")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_select",
+ mcp.WithDescription("Select a dropdown option by value"),
+ mcp.WithString("ref", mcp.Required(), mcp.Description("Element ref for the select element")),
+ mcp.WithString("value", mcp.Required(), mcp.Description("Option value to select")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_scroll",
+ mcp.WithDescription("Scroll the page or an element"),
+ mcp.WithString("ref", mcp.Description("Element ref to scroll (omit for page scroll)")),
+ mcp.WithNumber("pixels", mcp.Description("Number of pixels to scroll (positive=down, negative=up)")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_fill",
+ mcp.WithDescription("Fill an input field directly via JavaScript dispatch"),
+ mcp.WithString("ref", mcp.Required(), mcp.Description("Element ref or CSS selector")),
+ mcp.WithString("value", mcp.Required(), mcp.Description("Value to fill")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+
+ // ── Content ─────────────────────────────────────────────────
+ mcp.NewTool("pinchtab_eval",
+ mcp.WithDescription("Execute JavaScript in the browser and return the result"),
+ mcp.WithString("expression", mcp.Required(), mcp.Description("JavaScript expression to evaluate")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ mcp.NewTool("pinchtab_pdf",
+ mcp.WithDescription("Export the current page as a PDF (returns base64-encoded PDF)"),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ mcp.WithBoolean("landscape", mcp.Description("Landscape orientation")),
+ mcp.WithNumber("scale", mcp.Description("Print scale 0.1-2.0 (default: 1.0)")),
+ mcp.WithString("pageRanges", mcp.Description("Pages to export (e.g., '1-3,5')")),
+ ),
+ mcp.NewTool("pinchtab_find",
+ mcp.WithDescription("Find elements by text content or CSS selector"),
+ mcp.WithString("query", mcp.Required(), mcp.Description("Text or CSS selector to search for")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+
+ // ── Tab Management ──────────────────────────────────────────
+ mcp.NewTool("pinchtab_list_tabs",
+ mcp.WithDescription("List all open browser tabs"),
+ ),
+ mcp.NewTool("pinchtab_close_tab",
+ mcp.WithDescription("Close a browser tab"),
+ mcp.WithString("tabId", mcp.Description("ID of the tab to close")),
+ ),
+ mcp.NewTool("pinchtab_health",
+ mcp.WithDescription("Check PinchTab server health status"),
+ ),
+ mcp.NewTool("pinchtab_cookies",
+ mcp.WithDescription("Get cookies for the current page"),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+
+ // ── Utility ─────────────────────────────────────────────────
+ mcp.NewTool("pinchtab_wait",
+ mcp.WithDescription("Wait for a specified number of milliseconds"),
+ mcp.WithNumber("ms", mcp.Required(), mcp.Description("Milliseconds to wait (max 30000)")),
+ ),
+ mcp.NewTool("pinchtab_wait_for_selector",
+ mcp.WithDescription("Wait for an element matching a CSS selector to appear on the page"),
+ mcp.WithString("selector", mcp.Required(), mcp.Description("CSS selector to wait for")),
+ mcp.WithNumber("timeout", mcp.Description("Timeout in milliseconds (default: 10000, max: 30000)")),
+ mcp.WithString("tabId", mcp.Description("Target tab ID")),
+ ),
+ }
+}