Skip to main content
Glama
README.md
# VPS Browser MCP

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-blue.svg)]()
[![Chrome Extension](https://img.shields.io/badge/Chrome-Extension-green.svg)](https://chrome.google.com/webstore/)

> Control your local Chrome browser from a remote VPS. Cross-platform Chrome extension with WebSocket bridge for secure remote browser automation. MCP (Model Context Protocol) compatible.

## 🎯 What is this?

VPS Browser MCP is a system that allows you to **remotely control and inspect a Chrome browser** running on your personal laptop from a Virtual Private Server (VPS). It's perfect for:

- **Remote debugging** web applications
- **Automated testing** from different network locations
- **Secure browser automation** without exposing your browser publicly
- **Web scraping** with full browser capabilities
- **Remote technical support** and troubleshooting
- **AI/LLM integration** via MCP (Model Context Protocol)

## πŸ—οΈ Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   VPS Agent     │◄──►│  Local Bridge   │◄──►│ Chrome Extensionβ”‚
β”‚   (Node.js)     β”‚    β”‚  (Node.js)      β”‚    β”‚  (Manifest V3)  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚                      β”‚                      β”‚
         β”‚                      β”‚                      β”‚
         β–Ό                      β–Ό                      β–Ό
   WebSocket              WebSocket              Chrome APIs
   (Tailscale/SSH)        (localhost)            (tabs, scripting)
```

### Components

1. **Chrome Extension (Manifest V3)**
   - Runs in your local Chrome browser
   - Executes browser actions via Chrome APIs
   - Maintains WebSocket connection to local bridge
   - Handles tab management, DOM inspection, script execution

2. **Local Bridge (Node.js)**
   - Lightweight service running on your laptop
   - Bridges WebSocket connections between VPS and Chrome extension
   - Routes commands and responses
   - Keeps connections alive with ping/pong

3. **VPS Agent (Node.js)**
   - Module running on your remote server
   - Sends structured JSON commands
   - Receives execution results and logs
   - Simple API for browser automation

## πŸš€ Quick Start

### Prerequisites

- **Node.js** (v16 or higher) - [Download](https://nodejs.org/)
- **Chrome browser** - [Download](https://www.google.com/chrome/)
- **Remote access** (optional): SSH or Tailscale

### Installation

```bash
# Clone the repository
git clone https://github.com/Parithosh-Varma/VPS-browser-MCP.git
cd VPS-browser-MCP

# Run setup (installs dependencies)
npm run setup

# Install Chrome extension
npm run install-extension

# Start the bridge
npm start
```

### 3-Step Usage

1. **Setup**: `npm run setup` (one-time installation)
2. **Install Extension**: `npm run install-extension` (opens Chrome extensions page)
3. **Start**: `npm start` (launches WebSocket bridge)

## πŸ“– Usage Examples

### Basic Commands

```javascript
const BrowserController = require('./vps_agent/vps_client_example');

// Create controller instance
const browser = new BrowserController();
await browser.connect();

// Get current page URL and title
const pageInfo = await browser.getUrl();
console.log(pageInfo);
// { url: 'https://example.com', title: 'Example Domain' }

// Click an element
await browser.click('#submit-button');

// Type in a search box
await browser.type('#search-input', 'hello world');

// Execute custom JavaScript
const result = await browser.executeJs('document.title.length');
console.log(result); // 13

// Take a screenshot
const screenshot = await browser.screenshot();
// Returns base64 encoded PNG image

// Get DOM content
const dom = await browser.getDom();
console.log(dom.html); // Full page HTML
console.log(dom.elements); // Array of elements
```

### Advanced Usage

```javascript
// Execute complex JavaScript
const complexResult = await browser.executeJs(`
  // Get all links on the page
  const links = Array.from(document.querySelectorAll('a'));
  links.map(link => ({
    text: link.textContent,
    href: link.href
  }));
`);

// Get specific element's DOM
const elementDom = await browser.getDom('#main-content');

// Type with validation
await browser.type('input[name="email"]', 'user@example.com');

// Click and wait for navigation
await browser.click('a[href="/dashboard"]');
```

## πŸ› οΈ Available Commands

| Command | Description | Returns |
|---------|-------------|---------|
| `getUrl()` | Get active tab URL and title | `{ url, title }` |
| `getDom(selector?)` | Get DOM HTML or specific element | `{ html, elements }` |
| `click(selector)` | Click an element by CSS selector | `{ success }` |
| `type(selector, text)` | Type text into input field | `{ success, inputValue }` |
| `executeJs(code)` | Execute JavaScript in page context | `{ result, type }` |
| `screenshot()` | Capture tab screenshot | `{ base64 }` |

## πŸ”’ Security Features

- **No public exposure**: Extension only connects to localhost
- **Encrypted tunneling**: Use SSH or Tailscale for remote access
- **Local execution**: Scripts run in your browser's security context
- **Permission-based**: Extension only accesses what you allow
- **No data storage**: Everything runs in memory, no logs saved

## 🌐 Remote Access Options

### Option 1: SSH Tunnel (Recommended)

**On your VPS:**
```bash
# Create SSH tunnel to forward port 9877
ssh -R 9877:127.0.0.1:9877 user@your-laptop-ip -N

# Keep tunnel running in background
ssh -R 9877:127.0.0.1:9877 user@your-laptop-ip -N -f
```

**On your VPS (in another terminal):**
```bash
# Connect to the bridge
node vps_agent/vps_client_example.js
```

### Option 2: Tailscale (Zero-Config)

1. Install Tailscale on both machines:
   ```bash
   # macOS/Linux
   curl -fsSL https://tailscale.com/install.sh | sh
   
   # Windows: Download from https://tailscale.com/download/
   ```

2. Login on both machines:
   ```bash
   tailscale up
   ```

3. Use the Tailnet IP in your connection:
   ```javascript
   const browser = new BrowserController('ws://100.x.x.x:9877');
   ```

## πŸ“ Project Structure

```
VPS-browser-MCP/
β”œβ”€β”€ extension/                    # Chrome Extension
β”‚   β”œβ”€β”€ manifest.json            # Extension configuration
β”‚   β”œβ”€β”€ background.js            # Service worker (WebSocket handler)
β”‚   β”œβ”€β”€ content.js               # Content script (page injection)
β”‚   └── inject.js                # Injected script (DOM access)
β”‚
β”œβ”€β”€ local_bridge/                 # Bridge Server
β”‚   β”œβ”€β”€ local_bridge.js          # WebSocket bridge server
β”‚   └── package.json             # Dependencies
β”‚
β”œβ”€β”€ vps_agent/                    # VPS Client
β”‚   β”œβ”€β”€ vps_client_example.js    # Example client with BrowserController class
β”‚   └── package.json             # Dependencies
β”‚
β”œβ”€β”€ setup.js                     # Cross-platform setup script
β”œβ”€β”€ start.js                     # Cross-platform service starter
β”œβ”€β”€ install-extension.js         # Chrome extension installer
β”œβ”€β”€ package.json                 # Root package configuration
β”œβ”€β”€ README.md                    # This file
└── LICENSE                      # MIT License
```

## 🎨 Features

### Chrome Extension Capabilities

- **Tab Management**: Query, create, update, and remove tabs
- **DOM Inspection**: Query elements, get HTML, inspect attributes
- **Script Execution**: Run arbitrary JavaScript in page context
- **Event Handling**: Click elements, type text, trigger events
- **Screenshot Capture**: Take PNG screenshots of visible tabs
- **Console Access**: Capture console logs and errors

### Bridge Features

- **Bidirectional Communication**: Commands flow VPS β†’ Extension, results flow back
- **Connection Management**: Automatic reconnection and keep-alive
- **Multiple Clients**: Support for multiple VPS agents simultaneously
- **Message Routing**: Proper command/response correlation with UUIDs
- **Error Handling**: Graceful error recovery and reporting

### VPS Agent Features

- **Simple API**: Easy-to-use methods for common operations
- **Async/Await**: Modern JavaScript async patterns
- **Type Safety**: Clear result types and error handling
- **Extensible**: Easy to add custom commands
- **Logging**: Built-in logging for debugging

## πŸ”§ Configuration

### Environment Variables

Create a `.env` file (created automatically by setup):

```bash
# Extension WebSocket port (Chrome connects here)
EXTENSION_WS_PORT=9876

# VPS Agent WebSocket port (Remote agent connects here)
VPS_WS_PORT=9877

# VPS Agent connection URL
VPS_WS_URL=ws://127.0.0.1:9877
```

### Chrome Extension Permissions

The extension requires these permissions:

- `tabs`: Access tab information
- `activeTab`: Access current active tab
- `scripting`: Execute scripts in tabs
- `webNavigation`: Monitor page navigation

## πŸ› Troubleshooting

### Extension not connecting?

1. Ensure the bridge is running: `npm start`
2. Check Chrome console for errors: Right-click extension β†’ Inspect
3. Verify WebSocket port is available: `netstat -an | grep 9876`

### VPS can't connect?

1. Verify SSH tunnel is active: `ssh -R 9877:127.0.0.1:9877 user@laptop-ip -N`
2. Check firewall allows port 9877
3. Test connection: `telnet localhost 9877`

### Commands not working?

1. Ensure extension has required permissions (check chrome://extensions/)
2. Check Chrome DevTools console for errors
3. Verify the page you're trying to control is fully loaded

### Bridge crashes?

1. Check Node.js version: `node --version` (need v16+)
2. Reinstall dependencies: `npm run setup`
3. Check for port conflicts: `lsof -i :9876` or `netstat -an | grep 9876`

## πŸ“Š JSON Command Schema

### Request Format

```json
{
  "id": "uuid-v4-string",
  "action": "get_url | get_dom | click | type | execute_js | screenshot",
  "target": "current_tab | tab_id | {selector: string}",
  "payload": {
    "text": "string",
    "js": "string",
    "selector": "css-selector",
    "wait": 0
  },
  "timestamp": "ISO-8601-UTC-string"
}
```

### Response Format

```json
{
  "id": "matching-request-id",
  "status": "ok | error",
  "result": {},
  "error": {
    "code": "ERR_TIMEOUT | ERR_NOT_FOUND | ERR_PERMISSION",
    "message": "human-readable error"
  },
  "timestamp": "ISO-8601-UTC-string"
}
```

## 🀝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

## πŸ“„ License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## πŸ™ Acknowledgments

- [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) - Browser API for real-time communication
- [Chrome Extensions](https://developer.chrome.com/docs/extensions/) - Chrome extension documentation
- [Node.js](https://nodejs.org/) - JavaScript runtime for bridge and VPS agent
- [ws](https://github.com/websockets/ws) - WebSocket library for Node.js

## πŸ“ž Support

If you have any questions or issues, please:

1. Check the [Troubleshooting](#-troubleshooting) section
2. Open an issue on [GitHub Issues](https://github.com/Parithosh-Varma/VPS-browser-MCP/issues)
3. Contact: [Your Email or Discord]

---

**Made with ❀️ for the developer community**