Skip to content

Mbbrowser ApiServer Rules Package

This is the most critical part of this column. By injecting the following Rules package into Cursor or Antigravity, the AI model will fully master all Mbbrowser ApiServer interfaces, error codes, and appendix parameters, ensuring it never "hallucinates" when writing scripts.


IMPORTANT

Core Advice for Mbbrowser Automation: When running automation scripts, ensure the operation mode in the Mbbrowser client settings is switched to "Local Mode".

  • Performance Boost: Local Mode bypasses network data synchronization (uploading/downloading environment data), increasing automation startup and script execution efficiency by tens of times.
  • Security Tip: Cultivate the habit of backing up local data daily. Your core business data (environments, fingerprints, Cookies, etc.) are stored in the MBDATA directory. Please perform off-site backups of this folder regularly.

How to Use

For Cursor Users

  1. In your Mbbrowser script project root, create a file named .cursor/rules/mbbrowser.mdc.
  2. Copy and paste the entire content below into that file and save it.
  3. Restart the Cursor Chat (or start a new Chat).
  4. AI will automatically carry this knowledge in every subsequent conversation.

For Antigravity Users

Antigravity (Google's agent-first IDE) has its own rules system and uses an independent .agent/rules/ directory.

Steps:

  1. In the project root (workspace or git root), create a folder named .agent/rules/ (use it if it already exists).
  2. Create a file named mbbrowser.md (extension must be .md, pure Markdown format) in that folder.
  3. Copy and paste the specifications, interface details, and code templates from the "Mbbrowser ApiServer Rules Package" into the file and save it.
  4. Restart Antigravity or reopen the project → The Agent will automatically load all .md files under .agent/rules/ and inject them into the system prompt (effective at the workspace level).

Example File Structure:

your-project/
└── .agent/
    └── rules/
        └── mbbrowser.md   ← Paste your specifications here

Extra Tips:

  • Full Sync: If you use both tools, you can maintain dual paths: .cursor/rules/mbbrowser.mdc (for Cursor) + .agent/rules/mbbrowser.md (for Antigravity).
  • Character Limit: The rule file size limit is approximately 12,000 characters; if content is too large, it is recommended to split it into multiple .md files.
  • Global Effect: For global effect across all projects, place it in ~/.gemini/GEMINI.md.

Mbbrowser ApiServer Rules Package

Please copy the entire content below and replace the content in the file mentioned above.

markdown
# Mbbrowser (MBBrowser) + ApiServer Complete Development Specification

## 1. Product Brief

> [!IMPORTANT]
> **Performance Secret**: Before running large-scale automation, ensure the Mbbrowser client is in **"Local Mode"**. This skips cloud data synchronization, boosting environment startup speed by dozens of times. Always manually back up the **`MBDATA`** business database folder regularly.

Mbbrowser (MBBrowser) is a professional anti-association fingerprint browser for multi-account environment isolation. Each "environment" (Session) has its own: browser fingerprint, proxy IP, Cookies, User-Agent, time zone, and language.
ApiServer (apiserver.exe) is the local HTTP API service exposed by Mbbrowser, allowing scripts to control browser environments programmatically.

## 2. ApiServer Startup

```bash
apiserver.exe --port=8186 \
  --account=your_email@qq.com \
  --app_id=YOUR_APP_ID \
  --app_key=YOUR_APP_KEY \
  --hide=off \
  --return=on \
  --logs=on
```

Parameter Description:
- port: Listening port, default 8186.
- account: Mbbrowser login account (email).
- app_id: Obtained from Mbbrowser Client "Personal Center → API Settings".
- app_key: Obtained from Mbbrowser Client "Personal Center → API Settings".
- hide=off: Headed mode (recommended for debugging); hide=on for headless background mode.
- return=on: Display API response data in the console.
- logs=on: Write JSON data into log files.

After successful startup, the API address is http://127.0.0.1:8186.

## 3. Communication Standards

- All interfaces are HTTP POST requests.
- Content-Type: application/json.
- Base URL: http://127.0.0.1:8186.
- code=0 for success; negative code for failure, with message containing error details.

Standard Response Format:
```json
{
  "message": "Success",
  "code": 0,
  "data": { ... }
}
```

## 4. Account Authentication

### 4.1 Account Login (Used when switching accounts)
POST /login
```json
{
  "APP_ID": "7e147176e1d756eb03c0e18e7b640c23",
  "APP_KEY": "YOUR_APP_KEY",
  "Account": "test01@qq.com",
  "return": "on",
  "logs": "on",
  "hide": "off"
}
```
Successful Response: {"msg": "Login Success", "status": 0, "data": "Login Account: test01@qq.com"}
Note: ApiServer already carries authentication info on startup; this call is usually unnecessary.

### 4.2 Quit ApiServer
POST /api/v1/quit
No request parameters. Success returns code=0 and closes ApiServer.

## 5. Core Interfaces: Environment Lifecycle Management

### 5.1 Open Environment (Most Critical Interface)
POST /api/v1/browser/start
[Max Frequency: Unlimited, but recommend --interval-seconds control]

Request Parameters:
```json
{
  "Session_ID": ["373808cb37bd63f5f7d92415e736e85f"],
  "isHeadless": false,
  "args": [
    "--disable-extensions",
    "--blink-settings=imagesEnabled=false",
    "--interval-seconds=2"
  ]
}
```

Important Notes:
- Session_ID is an Array, supporting simultaneous multi-environment startup.
- isHeadless=false for headed mode (visible window), default is true.
- --interval-seconds controls the startup interval (seconds) between multiple environments.
- --blink-settings=imagesEnabled=false disables image loading (faster).
- --disable-extensions disables browser plugins (common for automation).

Successful Response Key Fields:
```json
{
  "message": "Success",
  "code": 0,
  "data": {
    "listid": [{
      "Session_Name": "Business Env 01",
      "Session_ID": "373808cb37bd63f5f7d92415e736e85f",
      "browser_CDP_Port": 46973,
      "webdriver": "C:\\Users\\Admin\\houniao\\Driver\\100\\chromedriver.exe",
      "status": 0
    }],
    "total": 1
  }
}
```

[Extremely Important] Proper Integration for Each Framework:

Python Playwright:
```python
port = env_data["browser_CDP_Port"]
ws_endpoint = f"ws://127.0.0.1:{port}/json/version"
from playwright.sync_api import sync_playwright
pw = sync_playwright().start()
browser = pw.chromium.connect_over_cdp(ws_endpoint)
context = browser.contexts[0]          # MUST TAKE EXISTING CONTEXT! Cannot use new_context()
page = context.pages[0] if context.pages else context.new_page()
```

JavaScript Playwright:
```javascript
const { chromium } = require('playwright');
const port = envData.browser_CDP_Port;
const wsEndpoint = `ws://127.0.0.1:${port}/json/version`;
const browser = await chromium.connectOverCDP(wsEndpoint);
const context = browser.contexts()[0];  // MUST TAKE EXISTING CONTEXT!
const page = context.pages()[0] || await context.newPage();
```

Python Selenium:
```python
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
options = Options()
# debuggerAddress is "IP:PORT" format, without ws://
options.add_experimental_option("debuggerAddress", f"127.0.0.1:{env_data['browser_CDP_Port']}")
service = Service(executable_path=env_data['webdriver'])
driver = webdriver.Chrome(service=service, options=options)
```

JavaScript Puppeteer:
```javascript
const puppeteer = require('puppeteer');
const port = envData.browser_CDP_Port;
const wsEndpoint = `ws://127.0.0.1:${port}/json/version`;
const browser = await puppeteer.connect({
  browserWSEndpoint: wsEndpoint,
  defaultViewport: null
});
```

### 5.2 Close Environment
POST /api/v1/browser/stop
```json
{
  "Session_ID": "373808cb37bd63f5f7d92415e736e85f"
}
```
Note: Session_ID is a String in this interface (not an array).
Success: {"message": "Success", "code": 0, "data": {"action": "StopSession_ID", "status": 0}}

### 5.3 Force Termination
POST /api/v1/browser/kill
```json
{
  "Session_ID": "373808cb37bd63f5f7d92415e736e85f"
}
```
Note: Ordinary stop might leave processes lingering after using some extensions; force termination (kill) is recommended to ensure quota recovery.

### 5.4 Check Running Status
POST /api/v1/browser/status
```json
{
  "Session_ID": ["4e6d0dca26ef42be9bc4472779d2550f"],
  "Actived_Type": 0
}
```
Actived_Type: 0=All, 1=Running only, 2=Not running only.
Returns Session_Actived=1 for running, 0 for not running.

## 6. Environment Query Interfaces

### 6.1 Get Environment List (Multi-dimensional filtering)
POST /api/v1/session/listid
Filter Parameters (All Optional):
- Session_Name, Session_GroupName, Proxy_Ip, Proxy_Type, etc.
- CurrentPage, ListNum (default 50, max 500).

Success:
```json
{
  "code": 0,
  "data": {
    "listid": ["373808...", "705cc..."],
    "total": 2
  }
}
```

### 6.2 Query Config Data for Specific Session_ID
POST /api/v1/session/id_container
```json
{
  "Session_ID": ["373808cb37bd63f5f7d92415e736e85f"],
  "Session_container_type": 1
}
```
Session_container_type: 1 = Full detail (includes browser_CDP_Port, webdriver, full fingerprint).

## 7. Creation and Update Interfaces

### 7.1 Create Environment
POST /api/v1/session/create
[Max Frequency: 40 requests/min]
Important Parameter `Automatic_Configure`:
- `0` (Recommended): Fast creation (auto-matches fingerprints from Mbbrowser business library, no proxy validation).
- `1`: Includes IP validation; creation takes much longer (set request timeout > 68s).

### 7.2 Update Basic Info
POST /api/v1/session/update
Includes Session_Name, Session_Desc, Session_Group, Cookie (JSON format string), etc.

### 7.3 Update Proxy
POST /api/v1/session/proxy/update
[Max Frequency: 50 requests/min]
Supports: HTTP, HTTPS, SSH, SOCKS4/5, Oxylabs, Luminati, smartproxy, noproxy.

### 7.4 Delete Environments
POST /api/v1/session/delete
`Is_Delete_All: 1` performs a global wipe.

## 8. Cookie Management

### 8.1 Import Cookie (From File)
POST /api/v1/session/import-cookie
```json
{
  "Session_ID": "session_id",
  "Cookie_File": "C:\\cookies\\account1.txt"
}
```
Supports .txt (Netscape) and .json formats.

### 8.2 Export Cookie (To File)
POST /api/v1/session/export-cookie
Uses `Export_Cookie_File` path. Exports as JSON if extension is .json, otherwise Netscape.

## 9. Plugin Management
- POST /api/v1/plugin/list (List all account plugins)
- POST /api/v1/session/id_plugin_list (List plugins in environment)
- POST /api/v1/session/plugin_install (Install plugin)
- POST /api/v1/session/plugin_delete (Delete plugin)

## 10. Automation Script Management
- POST /api/v1/session/id_script_list (Check environment scripts)
- POST /api/v1/session/id_script_add (Assign script from library)
- POST /api/v1/session/id_script_active (Activate script)

---

## 11. Complete Error Code Table

### CODE (Request Level)
0 Success; -1 Login Failed; -105 Proxy Validation Failed; -106 Invalid TimeZone; -108 Resolution Error.

### Status (Environment Open status field)
0 Success; -7 Already Running; -22 Session_ID Not Found.

## 12. Appendix: Legal Values

### 12.1 SystemOS
Windows | iPhone | iPad | MacIntel | Android | Linux x86_64, etc.

### 12.2 LanguageCode
zh-CN;zh;q=0.9 | en-US;en;q=0.9 | ja;q=0.9 | fr-FR;fr;q=0.9, etc.

### 12.3 Session_Resolution
1920x1080 | 1440x900 | 1366x768 | 2560x1440 | 375x812 (iPhone X), etc.

## 13. Development Precautions

1.  **Session_ID Type**: /start and /id_container use Array; /stop, /update, /proxy/update use String.
2.  **Playwright context**: ALWAYS use `browser.contexts[0]`; NEVER use `new_context()`.
3.  **Selenium**: Use `debuggerAddress` ("IP:PORT"); DO NOT use ws.
4.  **Concurrency**: Recommend max 20 environments per batch.
5.  **Status Check**: Always check `data.listid[0].status` after /start.
6.  **Proxy Validation**: Use `Public_ip` from /start response to verify proxy.
7.  **Legal Values**: Resolution/Language/TimeZone must use legal values from the appendix to avoid -106/-107/-108/-110 errors.

## 14. Full Python Script Template

```python
"""
Mbbrowser + Playwright Python Automation Template
"""
import requests, threading
from playwright.sync_api import sync_playwright

def start_env(session_id: str):
    resp = requests.post("http://127.0.0.1:8186/api/v1/browser/start", 
                         json={"Session_ID": [session_id]}).json()
    return resp["data"]["listid"][0] if resp["code"] == 0 else None

def do_task(session_id):
    env_data = start_env(session_id)
    if not env_data: return
    with sync_playwright().start() as pw:
        # Connect via CDP
        browser = pw.chromium.connect_over_cdp(f"ws://127.0.0.1:{env_data['browser_CDP_Port']}/json/version")
        context = browser.contexts[0] # Crucial: take existing context
        page = context.pages[0] if context.pages else context.new_page()
        page.goto("https://example.com")
        print(f"[{session_id}] Title: {page.title()}")
        browser.close()
    requests.post("http://127.0.0.1:8186/api/v1/browser/stop", json={"Session_ID": session_id})

if __name__ == "__main__":
    sids = ["yoursid1", "yoursid2"]
    threads = [threading.Thread(target=do_task, args=(sid,)) for sid in sids]
    for t in threads: t.start()
    for t in threads: t.join()
```

Configuration Verification

After configuring, enter in Chat:

Write a Python script using Mbbrowser ApiServer to get all IDs from group "TestGroup", 
open them concurrently (max 10), access https://example.com in each using Playwright, 
and close them after taking a screenshot. Include full error handling.

Success if AI correctly uses:

  • POST /api/v1/session/listid
  • Session_ID as an Array in /start
  • browser.contexts[0]
  • Session_ID as a String in /stop