# Playwright MCP Server (`upadhyay.labs/playwright-mcp-server`) Actor

Hosted Playwright MCP server: give Claude, Cursor, n8n or any AI agent a remote cloud browser to navigate, click, type, fill forms, take screenshots and scrape web data. Isolated sessions, pay per event.

- **URL**: https://apify.com/upadhyay.labs/playwright-mcp-server.md
- **Developed by:** [Upadhyay Labs](https://apify.com/upadhyay.labs) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: 5.00 out of 5 stars

## Pricing

from $2.00 / 1,000 page snapshots

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

### What does Playwright MCP Server do?

**Playwright MCP Server** is an [Apify Actor](https://apify.com/actors) that gives AI agents a **real, remote Chromium browser** through the **Model Context Protocol (MCP)**. Your agent can navigate web pages, read them as a compact accessibility snapshot, click, type, fill multi-step forms, wait for elements, switch tabs and take screenshots — all running on the Apify cloud platform instead of on your machine.

https://youtu.be/ENX2V5SOPks

It is a hosted, production-ready **Playwright MCP server** for browser automation and web scraping: the tool set agents already know from `@playwright/mcp`, available at a URL, so it works from places where `npx` can't run — cloud servers, CI pipelines, n8n workflows and serverless agent backends.

### Why use Playwright MCP Server?

- 🌐 **Runs anywhere your agent runs.** Cloud agents, n8n workflows, OpenAI Agents SDK, Anthropic Claude agent backends, CI jobs. Nothing to install, no local browser needed.
- 🔒 **Private by design.** Every Apify user gets an isolated browser session (cookies, storage, tabs never shared). Private networks and cloud metadata addresses are blocked.
- ⚡ **Fast.** One warm Chromium serves many sessions, so a new session opens in tens of milliseconds and actions return as soon as the page reacts. Fast-fail errors tell the agent exactly what to do next instead of waiting on timeouts.
- 🧠 **Built for how AI agents work.** Snapshots with short element refs (`e12`) keep token use low. `browser_fill_form` fills a whole form in one call. Errors are clean MCP tool errors the agent can recover from.
- 🛡️ **Prompt-injection aware.** Page content is always labelled untrusted, and typed text (passwords included) is never echoed back or logged.
- 🧰 **Apify platform included.** API access, run logs and monitoring, Apify Proxy support, spending limits, and screenshots stored with shareable URLs.
- 💳 **Pay per call.** You pay only for the browser actions your agent actually performs. See the Pricing tab for the current event prices.

#### When to use something else

Use this Actor when your agent has to **interact** with a page: log in, click through, fill forms, paginate, handle JavaScript-heavy sites. If all you need is "give me the text of this URL" or a web search, a plain fetch or search tool is cheaper and simpler.

### How to connect (integrations)

The MCP endpoint is:

```
https://<your-apify-username>--playwright-mcp-actor.apify.actor/mcp
```

Authenticate with an [Apify API token](https://console.apify.com/settings/integrations) as `Authorization: Bearer <token>`. Streamable HTTP transport.

#### Cursor, Windsurf and other MCP clients

```json
{
  "mcpServers": {
    "agent-browser": {
      "url": "https://<your-apify-username>--playwright-mcp-actor.apify.actor/mcp",
      "headers": { "Authorization": "Bearer <YOUR_APIFY_TOKEN>" }
    }
  }
}
```

#### Claude Code (CLI)

```bash
claude mcp add --transport http agent-browser \
  https://<your-apify-username>--playwright-mcp-actor.apify.actor/mcp \
  --header "Authorization: Bearer $APIFY_TOKEN"
```

#### Claude Desktop

Claude Desktop launches local servers, so bridge to the remote URL with `mcp-remote`:

```json
{
  "mcpServers": {
    "agent-browser": {
      "command": "npx",
      "args": ["-y", "mcp-remote",
        "https://<your-apify-username>--playwright-mcp-actor.apify.actor/mcp",
        "--header", "Authorization: Bearer <YOUR_APIFY_TOKEN>"]
    }
  }
}
```

> The claude.ai web "custom connector" flow signs in with OAuth and cannot send a bearer-token header, so it is not supported.

#### Python (FastMCP client)

```python
import asyncio, os
from fastmcp import Client
from fastmcp.client.transports import StreamableHttpTransport

transport = StreamableHttpTransport(
    "https://<your-apify-username>--playwright-mcp-actor.apify.actor/mcp",
    headers={"Authorization": f"Bearer {os.environ['APIFY_TOKEN']}"},
)

async def main():
    async with Client(transport) as client:
        await client.call_tool("browser_navigate", {"url": "https://example.com"})
        snapshot = await client.call_tool("browser_snapshot", {})
        print(snapshot.content[0].text)

asyncio.run(main())
```

#### OpenAI Agents SDK, n8n and other platforms

Any MCP client with Streamable HTTP support works: point it at the URL above and add the `Authorization` header. In n8n use the *MCP Client Tool* node with HTTP Streamable transport and header authentication.

### Available tools

| Tool | What it does |
|---|---|
| `browser_navigate` | Open a URL in the current tab |
| `browser_snapshot` | Accessibility snapshot with element refs like `[ref=e12]`. This is how the agent "sees" the page. |
| `browser_click` | Click (or double-click) an element by ref |
| `browser_type` | Type into an input; optionally press Enter. The text is never echoed or logged. |
| `browser_select` | Choose dropdown option(s) |
| `browser_press` | Press a key: `Enter`, `Tab`, `Escape`, `ArrowDown`, `Control+A`, … |
| `browser_fill_form` | Fill several fields (text, dropdown, checkbox, radio) in one call |
| `browser_wait_for` | Wait for text to appear or disappear, or for a short time |
| `browser_get_markdown` | The page's main content as clean Markdown, with scripts and chrome removed |
| `browser_screenshot` | JPEG of the viewport, full page or one element, also stored with a URL |
| `browser_tabs` | List, open, switch to or close tabs (popups open as new tabs automatically) |
| `browser_back` | Go back in the current tab |
| `browser_close` | End your session and free its resources |

#### A typical agent workflow

1. `browser_navigate` to the target page.
2. `browser_snapshot` to read the page structure and get element refs.
3. Act with `browser_click`, `browser_type`, `browser_select` or `browser_fill_form` using those refs.
4. `browser_snapshot` again. Refs are only valid until the page changes; a stale ref returns an error telling the agent to re-snapshot.
5. `browser_close` when done.

#### Example snapshot output

```yaml
- heading "Example Domain" [level=1] [ref=e2]
- paragraph [ref=e3]: This domain is for use in documentation examples…
- link "Learn more" [ref=e4] [cursor=pointer]:
  - /url: https://iana.org/domains/example
```

### Sessions, limits and safety

- **One browser per Apify user.** Your browser (tabs, cookies, logins) persists across tool calls and across reconnects while it is active, and is closed after a few idle minutes or on `browser_close`.
- **Built-in limits keep it reliable:** limited concurrent sessions per instance, up to 5 tabs per session, bounded snapshot and Markdown size, a time ceiling on every call, and automatic recovery if the browser crashes. When the server is busy the agent gets a clear "retry shortly" error.
- **Blocked targets:** `localhost`, private network ranges, cloud metadata endpoints and non-web schemes such as `file:` and `javascript:` can't be opened, including via redirects.
- **Chromium only, no file downloads.** Pass-through of your Apify Proxy settings is supported via the `proxy` input.
- **No CAPTCHA solving and no fingerprint spoofing.** This is an ordinary browser. If a site blocks it, use a proxy that suits your use case or choose a different tool.

#### Prompt injection warning

Web pages can contain text written to hijack AI agents. Snapshots and Markdown are clearly marked as untrusted data, but your agent must treat page content as **data, never as instructions**. Don't give a browsing agent access to secrets or destructive tools it doesn't need, and keep a human in the loop for sensitive actions.

### Pricing and cost control

Playwright MCP Server uses **pay-per-event pricing**: you are charged for the browser actions your agent performs, and the current price of each event is on the **Pricing** tab. Opening a tab, switching tabs and closing your session are free, and calls that are rejected before reaching the browser (bad ref, blocked URL, server busy) aren't charged.

To control spend, set a **maximum cost per run** when you start it (in Console or via the API). When the limit is reached, tools return an error instead of running. Platform compute time is billed to your Apify account as usual.

### Batch mode: automated browser actions

Start the Actor normally (not through the MCP server URL) to run a fixed list of browser actions, then collect the results from the dataset and key-value store. Ideal for scheduled checks, automated screenshots, and scripted web scraping.

#### Input example

```json
{
  "actions": [
    { "type": "navigate", "value": "https://example.com" },
    { "type": "get_title" },
    { "type": "extract_text", "selector": "body" },
    { "type": "screenshot" }
  ],
  "continue_on_error": true
}
```

Supported action types: `navigate`, `click`, `type`, `fill`, `select`, `check`, `uncheck`, `screenshot`, `extract_text`, `extract_attributes`, `wait`, `scroll`, `hover`, `focus`, `press_key`, `get_html`, `evaluate`, `wait_for_element`, `get_title`, `get_url`, `go_back`, `go_forward`, `reload`. Selectors can be CSS, XPath, text or role; the default `auto` tries them together. You can also use a ready-made `template` (Google search, Amazon search, LinkedIn profile, X/Twitter, Google Maps business). See the **Input** tab for every option, including retries, delays, viewport, proxy and export format.

#### Output example

One dataset item per run; screenshots go to the key-value store. You can download the dataset as JSON, HTML, CSV or Excel.

```json
{
  "success": true,
  "stats": { "total_actions": 4, "successful_actions": 4, "failed_actions": 0, "average_action_time_ms": 241.7 },
  "aborted": false,
  "actions": [
    { "type": "navigate", "success": true, "output": "https://example.com/", "execution_time_ms": 570 },
    { "type": "get_title", "success": true, "output": "Example Domain", "execution_time_ms": 6 },
    { "type": "screenshot", "success": true, "output": "Screenshot captured (78288 bytes)", "execution_time_ms": 68 }
  ]
}
```

Failed clicks and waits don't hang: element lookup waits once, up to the action timeout. Actions that could repeat a side effect (typing, key presses, scrolling, custom JavaScript, back/forward) are never retried automatically.

### Server settings

| Input | Default | Meaning |
|---|---|---|
| `mcp_max_sessions` | 8 | Concurrent isolated browser sessions per instance |
| `mcp_idle_timeout_secs` | 300 | Close a session after this much inactivity |
| `proxy` | none | Apify Proxy or custom proxies, applied to every session |

### FAQ

#### What is an MCP server?

The Model Context Protocol (MCP) is an open standard that lets AI applications call external tools. This Apify Actor is an MCP server whose tools control a remote cloud browser.

#### How is this different from running Playwright MCP locally?

It exposes the same kind of browser tools, but hosted on Apify. Your agent doesn't need Node.js, a browser or a desktop, so it works from cloud agents, workflows and servers.

#### Does my browser session survive between calls?

Yes. While you keep calling it, the same browser (tabs, cookies, logged-in state) is reused, even across new connections. It closes after a short idle period.

#### Can it log in to websites?

Yes, by filling the login form like a user. Only do this for accounts you are entitled to use, and remember that passwords you type pass through the agent that sent them.

#### Why do I get "Ref not found"?

Refs belong to one snapshot and change when the page changes. Call `browser_snapshot` again and use the new refs.

#### Why can't I open `localhost` or an internal address?

Those targets are blocked on purpose so an agent or a malicious page can't reach the server's own network.

#### Can I use the first call right after a long idle period?

The server starts on demand (Apify Standby mode), so the first request after idle can take longer while it spins up. Later calls are fast.

### Legal and support

This Actor drives an ordinary browser. You are responsible for what your agent does: respect each website's terms of service and robots rules, and don't collect personal data without a legitimate reason. Personal data is protected by the GDPR in the European Union and by other regulations around the world.

Found a bug or need a feature? Open an issue on the **Issues** tab.

Browser engine: [Playwright](https://playwright.dev) (Apache-2.0). MCP server framework: [FastMCP](https://gofastmcp.com).

# Actor input Schema

## `browser_type` (type: `string`):

Browser to use for automation (chromium, firefox, or webkit)

## `headless` (type: `boolean`):

Run browser in headless mode (without UI). Faster and uses less resources.

## `stealth_mode` (type: `boolean`):

Enable advanced anti-detection features to avoid bot detection. Recommended for social media and e-commerce sites.

## `proxy` (type: `object`):

Optional. Apify Proxy or custom proxies. Used by batch runs and by every MCP browser session.

## `template` (type: `string`):

Use a pre-built automation template. Templates provide optimized workflows for common use cases.

## `template_params` (type: `object`):

Parameters for the selected template. Each template has its own required parameters.

## `actions` (type: `array`):

Array of browser automation actions to execute sequentially. Required if not using a template.

## `export_format` (type: `string`):

Format to export extracted data. JSON is best for integrations, CSV/Excel for spreadsheets.

## `delay_between_actions` (type: `integer`):

Milliseconds to wait between each action. Helps avoid rate limits and detection. 0 = no delay.

## `max_retries` (type: `integer`):

Number of times to retry a failed action before giving up. Uses exponential backoff.

## `continue_on_error` (type: `boolean`):

If enabled, continues executing remaining actions even if one fails. Failed actions are logged.

## `max_actions_per_run` (type: `integer`):

Maximum number of actions to execute. Prevents runaway automation. 0 = unlimited.

## `page_load_timeout` (type: `integer`):

Maximum time to wait for pages to load. Increase for slow sites.

## `viewport_width` (type: `integer`):

Browser viewport width in pixels

## `viewport_height` (type: `integer`):

Browser viewport height in pixels

## `user_agent` (type: `string`):

Custom User-Agent string. Leave empty for auto-rotation in stealth mode.

## `mcp_max_sessions` (type: `integer`):

Standby (MCP server) only. Each session is an isolated browser context (~150-300 MB). Size memory accordingly.

## `mcp_idle_timeout_secs` (type: `integer`):

Standby (MCP server) only. A session with no tool calls for this long is closed to free memory.

## Actor input object example

```json
{
  "browser_type": "chromium",
  "headless": true,
  "stealth_mode": false,
  "template_params": {
    "search_query": "your search term",
    "max_results": 10
  },
  "actions": [
    {
      "type": "navigate",
      "value": "https://example.com"
    },
    {
      "type": "screenshot"
    }
  ],
  "export_format": "json",
  "delay_between_actions": 0,
  "max_retries": 2,
  "continue_on_error": false,
  "max_actions_per_run": 100,
  "page_load_timeout": 30000,
  "viewport_width": 1920,
  "viewport_height": 1080,
  "mcp_max_sessions": 8,
  "mcp_idle_timeout_secs": 300
}
```

# Actor output Schema

## `overview` (type: `string`):

Summary statistics of the automation run

## `allActions` (type: `string`):

Complete list of all executed actions with details

## `successful` (type: `string`):

Only successfully executed actions

## `failed` (type: `string`):

Failed actions with error details

## `screenshots` (type: `string`):

Captured screenshots from browser automation

## `exports` (type: `string`):

CSV and Excel exports of extracted data

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "template_params": {
        "search_query": "your search term",
        "max_results": 10
    },
    "actions": [
        {
            "type": "navigate",
            "value": "https://example.com"
        },
        {
            "type": "screenshot"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("upadhyay.labs/playwright-mcp-server").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "template_params": {
        "search_query": "your search term",
        "max_results": 10,
    },
    "actions": [
        {
            "type": "navigate",
            "value": "https://example.com",
        },
        { "type": "screenshot" },
    ],
}

# Run the Actor and wait for it to finish
run = client.actor("upadhyay.labs/playwright-mcp-server").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "template_params": {
    "search_query": "your search term",
    "max_results": 10
  },
  "actions": [
    {
      "type": "navigate",
      "value": "https://example.com"
    },
    {
      "type": "screenshot"
    }
  ]
}' |
apify call upadhyay.labs/playwright-mcp-server --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,upadhyay.labs/playwright-mcp-server"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/ncmgulAkbupkRGv3U/builds/jWbzrIcupoaN08oMX/openapi.json
