# Organized Browser MCP Server

**A properly organized MCP server that NEVER auto-launches browsers and only connects to your existing browser when actually needed.**

## 🛡️ Safety-First Design

This MCP server is designed with strict safety policies to ensure it:

- ✅ **NEVER auto-launches browsers** - Zero risk of unwanted browser instances
- ✅ **Only connects to existing browsers** - Respects your current browser setup
- ✅ **Lazy initialization** - No connections until you actually use MCP tools
- ✅ **VS Code startup friendly** - Won't slow down or interfere with VS Code startup
- ✅ **User-controlled** - You decide when and how to use browser automation

## 🏗️ Architecture Overview

### Core Components

1. **ConfigManager** (`src/core/ConfigManager.ts`)
   - Enforces safety policies at configuration level
   - Prevents any auto-launch configurations
   - Provides consistent settings across the application

2. **LazyBrowserManager** (`src/core/LazyBrowserManager.ts`)
   - Manages lazy initialization of browser connections
   - Only connects when MCP tools are actually called
   - Handles connection state and retry logic

3. **BrowserConnection** (`src/utils/BrowserConnection.ts`)
   - Low-level browser connection utility
   - Strict "existing browser only" policy
   - Chrome DevTools Protocol (CDP) based communication

4. **MCP Server** (`src/server.ts`)
   - Main MCP server implementation
   - Exposes browser automation tools
   - Integrates with lazy browser manager

## 🔧 Setup Instructions

### 1. Install Dependencies

```bash
cd organized_browser_mcp
npm install
```

### 2. Build the Project

```bash
npm run build
```

### 3. Start Your Browser with Debugging

**Before using the MCP server**, start your browser with debugging enabled:

**Chrome:**
```bash
# Close Chrome completely first, then:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222
```

**Edge:**
```bash
msedge --remote-debugging-port=9222
```

**Linux Chrome:**
```bash
google-chrome --remote-debugging-port=9222
```

### 4. Configure VS Code

Add to your VS Code `settings.json`:

```json
{
  "mcp.servers": [
    {
      "name": "organized-browser",
      "command": "node",
      "args": ["/path/to/organized_browser_mcp/bin/server.js"],
      "env": {}
    }
  ]
}
```

### 5. Test the Setup

1. **Start VS Code** - No browser should launch automatically ✅
2. **Check MCP status** - Server should be ready but not connected ✅  
3. **Use a browser tool** - Now it connects to your existing browser ✅
4. **Verify** - Should use your existing browser with all your data ✅

## 🛠️ Available Tools

Once you use a browser tool (and lazy initialization connects), you have access to:

- `browser_navigate` - Navigate to URLs
- `browser_screenshot` - Take screenshots
- `browser_click` - Click elements  
- `browser_type` - Type text
- `browser_get_content` - Extract page content
- `browser_list_pages` - List all open tabs
- `browser_status` - Get connection status

## 🔍 Debugging & Troubleshooting

### Check Browser Availability

```bash
# Test if your browser debugging is working:
curl http://localhost:9222/json/version
```

Should return browser information if properly configured.

### Enable Verbose Logging

```bash
node bin/server.js --verbose
```

### Common Issues

**"Browser not available"**
- Ensure browser is running with `--remote-debugging-port=9222`
- Check that port 9222 is not blocked by firewall
- Verify no other tools are using the debugging port

**"Connection timeout"**
- Browser might not have debugging enabled
- Try restarting browser with debugging flag
- Check browser process is actually running

## 🛡️ Safety Features

### Configuration-Level Safety

```typescript
// These settings are ENFORCED regardless of config file:
autoLaunch: false,           // Never auto-launch
allowLaunch: false,          // Never allow launching  
useExistingOnly: true,       // Only existing browsers
initializeOnStartup: false,  // Don't connect on startup
lazyInitialization: true,    // Connect only when needed
neverLaunchBrowser: true,    // Safety flag
requireExistingBrowser: true // Must have existing browser
```

### Code-Level Safety

- **LaunchBrowser() method throws error** - Prevents accidental launches
- **Connection checks before operations** - Validates browser availability
- **Graceful failure** - Clear error messages when browser not available
- **No automatic retries** - Won't keep trying to launch browsers

### Runtime Safety

- **Lazy initialization** - No connections until tool use
- **Connection validation** - Checks browser availability before connecting
- **Clear error messages** - Guides user to start browser manually
- **Graceful degradation** - Fails safely when browser not available

## 📁 Project Structure

```
organized_browser_mcp/
├── package.json              # Dependencies and scripts
├── tsconfig.json            # TypeScript configuration  
├── config.json              # Runtime configuration
├── bin/
│   └── server.js           # CLI entry point
├── src/
│   ├── server.ts           # Main MCP server
│   ├── core/
│   │   ├── ConfigManager.ts       # Configuration management
│   │   └── LazyBrowserManager.ts  # Lazy initialization logic
│   ├── utils/
│   │   └── BrowserConnection.ts   # Browser connection utility
│   └── types/
│       └── index.ts        # TypeScript type definitions
└── dist/                   # Compiled JavaScript (after build)
```

## 🔄 How Lazy Initialization Works

### Before (❌ Bad Behavior)
```
VS Code starts → MCP server starts → Immediately connects to browser
```

### After (✅ Good Behavior)  
```
VS Code starts → MCP server starts → Waits quietly
User calls browser tool → Lazy manager connects → Tool executes
```

### Implementation Details

1. **Server Startup**: Only creates MCP server, no browser connections
2. **Tool Registration**: Tools are available but no browser access yet
3. **First Tool Call**: Triggers lazy initialization
4. **Browser Connection**: Connects to existing browser
5. **Tool Execution**: Performs the actual browser action
6. **Subsequent Tools**: Use existing connection

## 🎯 Benefits

- ✅ **Zero VS Code startup impact** - No browser operations during startup
- ✅ **Respects user workflow** - Uses your actual browser with all data
- ✅ **Safe by design** - Cannot accidentally launch browsers
- ✅ **Clear error handling** - Helpful messages when browser not ready
- ✅ **Predictable behavior** - Consistent "existing browser only" policy
- ✅ **Professional MCP behavior** - Works like a proper service

## 🔧 Development

### Build
```bash
npm run build
```

### Development Mode  
```bash
npm run dev
```

### Test Connection
```bash
node bin/server.js --verbose
```

## 📜 License

MIT License - See LICENSE file for details.

---

**This MCP server prioritizes safety and user control over convenience. It will never surprise you by launching browsers automatically!** 🛡️
