playwright-mcp-server-hellork 0.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- build/lib/build/lib/build/lib/playwright_mcp/__init__.py +26 -0
- build/lib/build/lib/build/lib/playwright_mcp/__main__.py +10 -0
- build/lib/build/lib/build/lib/playwright_mcp/browser.py +124 -0
- build/lib/build/lib/build/lib/playwright_mcp/cli.py +128 -0
- build/lib/build/lib/build/lib/playwright_mcp/config.py +26 -0
- build/lib/build/lib/build/lib/playwright_mcp/executor.py +167 -0
- build/lib/build/lib/build/lib/playwright_mcp/handlers.py +100 -0
- build/lib/build/lib/build/lib/playwright_mcp/server.py +77 -0
- build/lib/build/lib/build/lib/playwright_mcp/tools.py +187 -0
- build/lib/build/lib/playwright_mcp/__init__.py +26 -0
- build/lib/build/lib/playwright_mcp/__main__.py +10 -0
- build/lib/build/lib/playwright_mcp/browser.py +124 -0
- build/lib/build/lib/playwright_mcp/cli.py +128 -0
- build/lib/build/lib/playwright_mcp/config.py +26 -0
- build/lib/build/lib/playwright_mcp/executor.py +167 -0
- build/lib/build/lib/playwright_mcp/handlers.py +100 -0
- build/lib/build/lib/playwright_mcp/server.py +77 -0
- build/lib/build/lib/playwright_mcp/tools.py +187 -0
- build/lib/playwright_mcp/__init__.py +26 -0
- build/lib/playwright_mcp/__main__.py +10 -0
- build/lib/playwright_mcp/browser.py +124 -0
- build/lib/playwright_mcp/cli.py +128 -0
- build/lib/playwright_mcp/config.py +26 -0
- build/lib/playwright_mcp/executor.py +167 -0
- build/lib/playwright_mcp/handlers.py +100 -0
- build/lib/playwright_mcp/server.py +77 -0
- build/lib/playwright_mcp/tools.py +187 -0
- playwright_mcp/__init__.py +26 -0
- playwright_mcp/__main__.py +10 -0
- playwright_mcp/browser.py +124 -0
- playwright_mcp/cli.py +128 -0
- playwright_mcp/config.py +26 -0
- playwright_mcp/executor.py +167 -0
- playwright_mcp/handlers.py +100 -0
- playwright_mcp/server.py +77 -0
- playwright_mcp/tools.py +187 -0
- playwright_mcp_server_hellork-0.2.1.dist-info/METADATA +189 -0
- playwright_mcp_server_hellork-0.2.1.dist-info/RECORD +43 -0
- playwright_mcp_server_hellork-0.2.1.dist-info/WHEEL +5 -0
- playwright_mcp_server_hellork-0.2.1.dist-info/entry_points.txt +2 -0
- playwright_mcp_server_hellork-0.2.1.dist-info/licenses/LICENSE +201 -0
- playwright_mcp_server_hellork-0.2.1.dist-info/licenses/NOTICE +37 -0
- playwright_mcp_server_hellork-0.2.1.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Copyright (c) 2024 Playwright MCP Server Contributors
|
|
2
|
+
# Licensed under the MIT License - see LICENSE file for details
|
|
3
|
+
"""Playwright MCP Server - Browser automation via Model Context Protocol."""
|
|
4
|
+
|
|
5
|
+
from .browser import BrowserManager, create_browser_manager
|
|
6
|
+
from .config import DEFAULT_CONFIG, BrowserConfig, ServerConfig
|
|
7
|
+
from .executor import ToolExecutor
|
|
8
|
+
from .handlers import RequestHandlers
|
|
9
|
+
from .server import PlaywrightMCPServer, create_server, main
|
|
10
|
+
from .tools import TOOLS, get_tools
|
|
11
|
+
|
|
12
|
+
__version__ = "0.2.1"
|
|
13
|
+
__all__ = [
|
|
14
|
+
"DEFAULT_CONFIG",
|
|
15
|
+
"TOOLS",
|
|
16
|
+
"BrowserConfig",
|
|
17
|
+
"BrowserManager",
|
|
18
|
+
"PlaywrightMCPServer",
|
|
19
|
+
"RequestHandlers",
|
|
20
|
+
"ServerConfig",
|
|
21
|
+
"ToolExecutor",
|
|
22
|
+
"create_browser_manager",
|
|
23
|
+
"create_server",
|
|
24
|
+
"get_tools",
|
|
25
|
+
"main",
|
|
26
|
+
]
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Copyright (c) 2024 Playwright MCP Server Contributors
|
|
2
|
+
# Licensed under the MIT License - see LICENSE file for details
|
|
3
|
+
"""Entry point for running the Playwright MCP server."""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
|
|
7
|
+
from .server import main
|
|
8
|
+
|
|
9
|
+
if __name__ == "__main__":
|
|
10
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
# Copyright (c) 2024 Playwright MCP Server Contributors
|
|
2
|
+
# Licensed under the MIT License - see LICENSE file for details
|
|
3
|
+
"""Browser lifecycle management."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
from collections.abc import AsyncIterator
|
|
9
|
+
from contextlib import asynccontextmanager
|
|
10
|
+
|
|
11
|
+
from playwright.async_api import Browser, BrowserContext, Page, Playwright, async_playwright
|
|
12
|
+
|
|
13
|
+
from .config import BrowserConfig, ServerConfig
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class BrowserManager:
|
|
17
|
+
"""Manages Playwright browser lifecycle and page pool."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, config: BrowserConfig) -> None:
|
|
20
|
+
self._config = config
|
|
21
|
+
self._playwright: Playwright | None = None
|
|
22
|
+
self._browser: Browser | None = None
|
|
23
|
+
self._context: BrowserContext | None = None
|
|
24
|
+
self._pages: dict[str, Page] = {}
|
|
25
|
+
self._current_page_id: str | None = None
|
|
26
|
+
self._lock = asyncio.Lock()
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def is_initialized(self) -> bool:
|
|
30
|
+
return self._browser is not None and self._browser.is_connected()
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def pages(self) -> dict[str, Page]:
|
|
34
|
+
return self._pages
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def current_page_id(self) -> str | None:
|
|
38
|
+
return self._current_page_id
|
|
39
|
+
|
|
40
|
+
@current_page_id.setter
|
|
41
|
+
def current_page_id(self, value: str | None) -> None:
|
|
42
|
+
self._current_page_id = value
|
|
43
|
+
|
|
44
|
+
async def initialize(self) -> None:
|
|
45
|
+
"""Initialize browser, context, and default page."""
|
|
46
|
+
async with self._lock:
|
|
47
|
+
if self.is_initialized:
|
|
48
|
+
return
|
|
49
|
+
|
|
50
|
+
self._playwright = await async_playwright().start()
|
|
51
|
+
browser_type = getattr(self._playwright, self._config.browser_type)
|
|
52
|
+
self._browser = await browser_type.launch(
|
|
53
|
+
headless=self._config.headless,
|
|
54
|
+
args=list(self._config.args),
|
|
55
|
+
slow_mo=self._config.slow_mo,
|
|
56
|
+
)
|
|
57
|
+
self._context = await self._browser.new_context()
|
|
58
|
+
default_page = await self._context.new_page()
|
|
59
|
+
self._pages["default"] = default_page
|
|
60
|
+
self._current_page_id = "default"
|
|
61
|
+
|
|
62
|
+
async def close(self) -> None:
|
|
63
|
+
"""Clean up browser resources."""
|
|
64
|
+
async with self._lock:
|
|
65
|
+
if self._context:
|
|
66
|
+
await self._context.close()
|
|
67
|
+
self._context = None
|
|
68
|
+
if self._browser:
|
|
69
|
+
await self._browser.close()
|
|
70
|
+
self._browser = None
|
|
71
|
+
if self._playwright:
|
|
72
|
+
await self._playwright.stop()
|
|
73
|
+
self._playwright = None
|
|
74
|
+
self._pages.clear()
|
|
75
|
+
self._current_page_id = None
|
|
76
|
+
|
|
77
|
+
def get_page(self, page_id: str | None = None) -> Page:
|
|
78
|
+
"""Get a page by ID, defaulting to current page."""
|
|
79
|
+
if page_id is None:
|
|
80
|
+
page_id = self._current_page_id
|
|
81
|
+
if page_id is None:
|
|
82
|
+
if self._pages:
|
|
83
|
+
page_id = next(iter(self._pages))
|
|
84
|
+
else:
|
|
85
|
+
raise ValueError("No pages available. Call initialize() first.")
|
|
86
|
+
if page_id not in self._pages:
|
|
87
|
+
raise ValueError(f"Page not found: {page_id}")
|
|
88
|
+
return self._pages[page_id]
|
|
89
|
+
|
|
90
|
+
async def create_page(self, page_id: str) -> Page:
|
|
91
|
+
"""Create a new page with the given ID."""
|
|
92
|
+
if not self._context:
|
|
93
|
+
raise RuntimeError("Browser not initialized")
|
|
94
|
+
page = await self._context.new_page()
|
|
95
|
+
self._pages[page_id] = page
|
|
96
|
+
self._current_page_id = page_id
|
|
97
|
+
return page
|
|
98
|
+
|
|
99
|
+
def remove_page(self, page_id: str) -> bool:
|
|
100
|
+
"""Remove a page from the pool."""
|
|
101
|
+
if page_id in self._pages:
|
|
102
|
+
# Don't actually close the page, just remove from pool
|
|
103
|
+
# The context will clean up on close()
|
|
104
|
+
del self._pages[page_id]
|
|
105
|
+
if self._current_page_id == page_id:
|
|
106
|
+
self._current_page_id = next(iter(self._pages)) if self._pages else None
|
|
107
|
+
return True
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
@asynccontextmanager
|
|
111
|
+
async def lifespan(self) -> AsyncIterator[BrowserManager]:
|
|
112
|
+
"""Context manager for browser lifecycle."""
|
|
113
|
+
await self.initialize()
|
|
114
|
+
try:
|
|
115
|
+
yield self
|
|
116
|
+
finally:
|
|
117
|
+
await self.close()
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def create_browser_manager(config: ServerConfig | None = None) -> BrowserManager:
|
|
121
|
+
"""Factory function to create a browser manager."""
|
|
122
|
+
if config is None:
|
|
123
|
+
config = ServerConfig()
|
|
124
|
+
return BrowserManager(config.browser)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
# Copyright (c) 2024 Playwright MCP Server Contributors
|
|
2
|
+
# Licensed under the MIT License - see LICENSE file for details
|
|
3
|
+
"""Command-line interface for the Playwright MCP server."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import argparse
|
|
8
|
+
import asyncio
|
|
9
|
+
import logging
|
|
10
|
+
import sys
|
|
11
|
+
|
|
12
|
+
from .config import DEFAULT_CONFIG, BrowserConfig, ServerConfig
|
|
13
|
+
from .server import create_server
|
|
14
|
+
|
|
15
|
+
logger = logging.getLogger(__name__)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def parse_args(args: list[str] | None = None) -> argparse.Namespace:
|
|
19
|
+
"""Parse command-line arguments."""
|
|
20
|
+
parser = argparse.ArgumentParser(
|
|
21
|
+
description="Playwright MCP Server - Browser automation via Model Context Protocol",
|
|
22
|
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
parser.add_argument(
|
|
26
|
+
"--headless",
|
|
27
|
+
action="store_true",
|
|
28
|
+
default=None,
|
|
29
|
+
help="Run browser in headless mode (default: True)",
|
|
30
|
+
)
|
|
31
|
+
parser.add_argument(
|
|
32
|
+
"--headed",
|
|
33
|
+
action="store_false",
|
|
34
|
+
dest="headless",
|
|
35
|
+
help="Run browser in headed mode",
|
|
36
|
+
)
|
|
37
|
+
parser.add_argument(
|
|
38
|
+
"--browser",
|
|
39
|
+
choices=["chromium", "firefox", "webkit"],
|
|
40
|
+
default=None,
|
|
41
|
+
help="Browser type to use",
|
|
42
|
+
)
|
|
43
|
+
parser.add_argument(
|
|
44
|
+
"--timeout",
|
|
45
|
+
type=float,
|
|
46
|
+
default=None,
|
|
47
|
+
help="Default timeout in milliseconds",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
parser.add_argument(
|
|
51
|
+
"--slow-mo",
|
|
52
|
+
type=float,
|
|
53
|
+
default=None,
|
|
54
|
+
help="Slow down operations by specified milliseconds",
|
|
55
|
+
)
|
|
56
|
+
parser.add_argument(
|
|
57
|
+
"--browser-arg",
|
|
58
|
+
action="append",
|
|
59
|
+
default=None,
|
|
60
|
+
help="Additional browser launch arguments (can be repeated)",
|
|
61
|
+
)
|
|
62
|
+
parser.add_argument(
|
|
63
|
+
"--log-level",
|
|
64
|
+
choices=["DEBUG", "INFO", "WARNING", "ERROR"],
|
|
65
|
+
default="INFO",
|
|
66
|
+
help="Logging level",
|
|
67
|
+
)
|
|
68
|
+
parser.add_argument(
|
|
69
|
+
"--version",
|
|
70
|
+
action="version",
|
|
71
|
+
version="%(prog)s 0.2.0",
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
return parser.parse_args(args)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def build_config(args: argparse.Namespace) -> ServerConfig:
|
|
78
|
+
"""Build server config from parsed arguments."""
|
|
79
|
+
browser_config = BrowserConfig()
|
|
80
|
+
|
|
81
|
+
if args.headless is not None:
|
|
82
|
+
browser_config = BrowserConfig(
|
|
83
|
+
headless=args.headless,
|
|
84
|
+
browser_type=args.browser or DEFAULT_CONFIG.browser.browser_type,
|
|
85
|
+
args=tuple(args.browser_arg) if args.browser_arg else DEFAULT_CONFIG.browser.args,
|
|
86
|
+
slow_mo=args.slow_mo if args.slow_mo is not None else DEFAULT_CONFIG.browser.slow_mo,
|
|
87
|
+
)
|
|
88
|
+
elif args.browser is not None or args.browser_arg is not None or args.slow_mo is not None:
|
|
89
|
+
browser_config = BrowserConfig(
|
|
90
|
+
headless=DEFAULT_CONFIG.browser.headless,
|
|
91
|
+
browser_type=args.browser or DEFAULT_CONFIG.browser.browser_type,
|
|
92
|
+
args=tuple(args.browser_arg) if args.browser_arg else DEFAULT_CONFIG.browser.args,
|
|
93
|
+
slow_mo=args.slow_mo if args.slow_mo is not None else DEFAULT_CONFIG.browser.slow_mo,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
return ServerConfig(
|
|
97
|
+
name=DEFAULT_CONFIG.name,
|
|
98
|
+
version=DEFAULT_CONFIG.version,
|
|
99
|
+
browser=browser_config,
|
|
100
|
+
default_timeout=args.timeout if args.timeout is not None else DEFAULT_CONFIG.default_timeout,
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def main(args: list[str] | None = None) -> int:
|
|
105
|
+
"""Main CLI entry point."""
|
|
106
|
+
parsed = parse_args(args)
|
|
107
|
+
|
|
108
|
+
logging.basicConfig(
|
|
109
|
+
level=parsed.log_level,
|
|
110
|
+
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
config = build_config(parsed)
|
|
114
|
+
server = create_server(config)
|
|
115
|
+
|
|
116
|
+
try:
|
|
117
|
+
asyncio.run(server.run_stdio())
|
|
118
|
+
return 0
|
|
119
|
+
except KeyboardInterrupt:
|
|
120
|
+
logger.info("Server stopped by user")
|
|
121
|
+
return 130
|
|
122
|
+
except Exception:
|
|
123
|
+
logger.exception("Server error")
|
|
124
|
+
return 1
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
if __name__ == "__main__":
|
|
128
|
+
sys.exit(main())
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Copyright (c) 2024 Playwright MCP Server Contributors
|
|
2
|
+
# Licensed under the MIT License - see LICENSE file for details
|
|
3
|
+
"""Configuration for the Playwright MCP server."""
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class BrowserConfig:
|
|
10
|
+
"""Browser launch configuration."""
|
|
11
|
+
headless: bool = True
|
|
12
|
+
browser_type: str = "chromium" # chromium, firefox, webkit
|
|
13
|
+
args: tuple[str, ...] = field(default_factory=tuple)
|
|
14
|
+
slow_mo: float = 0.0
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class ServerConfig:
|
|
19
|
+
"""Server configuration."""
|
|
20
|
+
name: str = "playwright-mcp"
|
|
21
|
+
version: str = "0.2.0"
|
|
22
|
+
browser: BrowserConfig = field(default_factory=BrowserConfig)
|
|
23
|
+
default_timeout: float = 30000.0 # ms
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
DEFAULT_CONFIG = ServerConfig()
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
# Copyright (c) 2024 Playwright MCP Server Contributors
|
|
2
|
+
# Licensed under the MIT License - see LICENSE file for details
|
|
3
|
+
"""Tool execution logic for Playwright MCP server."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import base64
|
|
8
|
+
import json
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
from mcp import types
|
|
12
|
+
from playwright.async_api import Page
|
|
13
|
+
|
|
14
|
+
from .browser import BrowserManager
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class ToolExecutor:
|
|
18
|
+
"""Executes Playwright tools against a browser manager."""
|
|
19
|
+
|
|
20
|
+
def __init__(self, browser_manager: BrowserManager, default_timeout: float = 30000.0) -> None:
|
|
21
|
+
self._browser = browser_manager
|
|
22
|
+
self._default_timeout = default_timeout
|
|
23
|
+
|
|
24
|
+
async def execute(self, name: str, arguments: dict[str, Any]) -> types.CallToolResult:
|
|
25
|
+
"""Execute a tool by name with arguments."""
|
|
26
|
+
try:
|
|
27
|
+
handler = getattr(self, f"_handle_{name}", None)
|
|
28
|
+
if handler is None:
|
|
29
|
+
raise ValueError(f"Unknown tool: {name}")
|
|
30
|
+
result: types.CallToolResult = await handler(arguments)
|
|
31
|
+
return result
|
|
32
|
+
except Exception as e: # noqa: BLE001
|
|
33
|
+
return types.CallToolResult(
|
|
34
|
+
content=[types.TextContent(type="text", text=f"Error: {e!s}")],
|
|
35
|
+
is_error=True,
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
def _get_page(self, page_id: str | None = None) -> Page:
|
|
39
|
+
return self._browser.get_page(page_id)
|
|
40
|
+
|
|
41
|
+
async def _handle_navigate(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
42
|
+
page = self._get_page(args.get("page_id"))
|
|
43
|
+
await page.goto(args["url"], timeout=self._default_timeout)
|
|
44
|
+
return types.CallToolResult(
|
|
45
|
+
content=[types.TextContent(type="text", text=f"Navigated to {args['url']}")]
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
async def _handle_click(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
49
|
+
page = self._get_page(args.get("page_id"))
|
|
50
|
+
await page.click(args["selector"], timeout=args.get("timeout", self._default_timeout))
|
|
51
|
+
return types.CallToolResult(
|
|
52
|
+
content=[types.TextContent(type="text", text=f"Clicked {args['selector']}")]
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
async def _handle_type(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
56
|
+
page = self._get_page(args.get("page_id"))
|
|
57
|
+
await page.fill(args["selector"], args["text"], timeout=self._default_timeout)
|
|
58
|
+
return types.CallToolResult(
|
|
59
|
+
content=[types.TextContent(type="text", text=f"Typed into {args['selector']}")]
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
async def _handle_get_text(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
63
|
+
page = self._get_page(args.get("page_id"))
|
|
64
|
+
text = await page.locator(args["selector"]).text_content(timeout=self._default_timeout)
|
|
65
|
+
return types.CallToolResult(
|
|
66
|
+
content=[types.TextContent(type="text", text=text or "")]
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
async def _handle_get_page_content(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
70
|
+
page = self._get_page(args.get("page_id"))
|
|
71
|
+
content = await page.content()
|
|
72
|
+
return types.CallToolResult(
|
|
73
|
+
content=[types.TextContent(type="text", text=content)]
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
async def _handle_take_screenshot(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
77
|
+
page = self._get_page(args.get("page_id"))
|
|
78
|
+
selector = args.get("selector")
|
|
79
|
+
full_page = args.get("full_page", False)
|
|
80
|
+
|
|
81
|
+
if selector:
|
|
82
|
+
screenshot = await page.locator(selector).screenshot()
|
|
83
|
+
elif full_page:
|
|
84
|
+
screenshot = await page.screenshot(full_page=True)
|
|
85
|
+
else:
|
|
86
|
+
screenshot = await page.screenshot()
|
|
87
|
+
|
|
88
|
+
b64 = base64.b64encode(screenshot).decode()
|
|
89
|
+
return types.CallToolResult(
|
|
90
|
+
content=[types.ImageContent(type="image", data=b64, mime_type="image/png")]
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
async def _handle_new_page(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
94
|
+
page_id = args["page_id"]
|
|
95
|
+
await self._browser.create_page(page_id)
|
|
96
|
+
return types.CallToolResult(
|
|
97
|
+
content=[types.TextContent(type="text", text=f"Created new page: {page_id}")]
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
async def _handle_switch_page(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
101
|
+
page_id = args["page_id"]
|
|
102
|
+
if page_id not in self._browser.pages:
|
|
103
|
+
raise ValueError(f"Page not found: {page_id}")
|
|
104
|
+
self._browser.current_page_id = page_id
|
|
105
|
+
return types.CallToolResult(
|
|
106
|
+
content=[types.TextContent(type="text", text=f"Switched to page: {page_id}")]
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
async def _handle_get_pages(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
110
|
+
page_list = [
|
|
111
|
+
{"id": pid, "url": p.url, "title": await p.title()}
|
|
112
|
+
for pid, p in self._browser.pages.items()
|
|
113
|
+
]
|
|
114
|
+
return types.CallToolResult(
|
|
115
|
+
content=[types.TextContent(type="text", text=json.dumps(page_list, indent=2))]
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
async def _handle_wait_for_selector(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
119
|
+
page = self._get_page(args.get("page_id"))
|
|
120
|
+
selector = args["selector"]
|
|
121
|
+
timeout = args.get("timeout", self._default_timeout)
|
|
122
|
+
state = args.get("state", "visible")
|
|
123
|
+
await page.wait_for_selector(selector, state=state, timeout=timeout)
|
|
124
|
+
return types.CallToolResult(
|
|
125
|
+
content=[types.TextContent(type="text", text=f"Element {selector} is {state}")]
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
async def _handle_evaluate(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
129
|
+
page = self._get_page(args.get("page_id"))
|
|
130
|
+
result = await page.evaluate(args["script"])
|
|
131
|
+
return types.CallToolResult(
|
|
132
|
+
content=[types.TextContent(type="text", text=json.dumps(result, default=str))]
|
|
133
|
+
)
|
|
134
|
+
|
|
135
|
+
async def _handle_get_title(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
136
|
+
page = self._get_page(args.get("page_id"))
|
|
137
|
+
title = await page.title()
|
|
138
|
+
return types.CallToolResult(
|
|
139
|
+
content=[types.TextContent(type="text", text=title)]
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
async def _handle_get_url(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
143
|
+
page = self._get_page(args.get("page_id"))
|
|
144
|
+
return types.CallToolResult(
|
|
145
|
+
content=[types.TextContent(type="text", text=page.url)]
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
async def _handle_go_back(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
149
|
+
page = self._get_page(args.get("page_id"))
|
|
150
|
+
await page.go_back(timeout=self._default_timeout)
|
|
151
|
+
return types.CallToolResult(
|
|
152
|
+
content=[types.TextContent(type="text", text="Navigated back")]
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
async def _handle_go_forward(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
156
|
+
page = self._get_page(args.get("page_id"))
|
|
157
|
+
await page.go_forward(timeout=self._default_timeout)
|
|
158
|
+
return types.CallToolResult(
|
|
159
|
+
content=[types.TextContent(type="text", text="Navigated forward")]
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
async def _handle_reload(self, args: dict[str, Any]) -> types.CallToolResult:
|
|
163
|
+
page = self._get_page(args.get("page_id"))
|
|
164
|
+
await page.reload(timeout=self._default_timeout)
|
|
165
|
+
return types.CallToolResult(
|
|
166
|
+
content=[types.TextContent(type="text", text="Page reloaded")]
|
|
167
|
+
)
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# Copyright (c) 2024 Playwright MCP Server Contributors
|
|
2
|
+
# Licensed under the MIT License - see LICENSE file for details
|
|
3
|
+
"""MCP request handlers for the Playwright server."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import base64
|
|
8
|
+
|
|
9
|
+
from mcp import types
|
|
10
|
+
from mcp.server import Server
|
|
11
|
+
from mcp.server.context import ServerRequestContext
|
|
12
|
+
|
|
13
|
+
from .browser import BrowserManager
|
|
14
|
+
from .executor import ToolExecutor
|
|
15
|
+
from .tools import get_tools
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class RequestHandlers:
|
|
19
|
+
"""Handles MCP requests by delegating to browser manager and tool executor."""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
browser_manager: BrowserManager,
|
|
24
|
+
default_timeout: float = 30000.0,
|
|
25
|
+
) -> None:
|
|
26
|
+
self._browser = browser_manager
|
|
27
|
+
self._executor = ToolExecutor(browser_manager, default_timeout)
|
|
28
|
+
|
|
29
|
+
async def _ensure_initialized(self) -> None:
|
|
30
|
+
"""Lazily initialize the browser on first tool call."""
|
|
31
|
+
if not self._browser.is_initialized:
|
|
32
|
+
await self._browser.initialize()
|
|
33
|
+
|
|
34
|
+
async def handle_list_tools(
|
|
35
|
+
self, ctx: ServerRequestContext, params: types.PaginatedRequestParams
|
|
36
|
+
) -> types.ListToolsResult:
|
|
37
|
+
"""List available tools."""
|
|
38
|
+
return types.ListToolsResult(tools=get_tools())
|
|
39
|
+
|
|
40
|
+
async def handle_call_tool(
|
|
41
|
+
self, ctx: ServerRequestContext, params: types.CallToolRequestParams
|
|
42
|
+
) -> types.CallToolResult:
|
|
43
|
+
"""Execute a tool."""
|
|
44
|
+
await self._ensure_initialized()
|
|
45
|
+
return await self._executor.execute(params.name, params.arguments or {})
|
|
46
|
+
|
|
47
|
+
async def handle_list_resources(
|
|
48
|
+
self, ctx: ServerRequestContext, params: types.PaginatedRequestParams
|
|
49
|
+
) -> types.ListResourcesResult:
|
|
50
|
+
"""List available resources (screenshots)."""
|
|
51
|
+
await self._ensure_initialized()
|
|
52
|
+
resources = []
|
|
53
|
+
for page_id, page in self._browser.pages.items():
|
|
54
|
+
resources.append(
|
|
55
|
+
types.Resource(
|
|
56
|
+
uri=f"screenshot://{page_id}",
|
|
57
|
+
name=f"Screenshot: {page.url}",
|
|
58
|
+
description=f"Current screenshot of page at {page.url}",
|
|
59
|
+
mime_type="image/png",
|
|
60
|
+
)
|
|
61
|
+
)
|
|
62
|
+
return types.ListResourcesResult(resources=resources)
|
|
63
|
+
|
|
64
|
+
async def handle_read_resource(
|
|
65
|
+
self, ctx: ServerRequestContext, params: types.ReadResourceRequestParams
|
|
66
|
+
) -> types.ReadResourceResult:
|
|
67
|
+
"""Read a screenshot resource."""
|
|
68
|
+
await self._ensure_initialized()
|
|
69
|
+
uri = params.uri
|
|
70
|
+
if not uri.startswith("screenshot://"):
|
|
71
|
+
raise ValueError(f"Unsupported URI scheme: {uri}")
|
|
72
|
+
|
|
73
|
+
page_id = uri.replace("screenshot://", "")
|
|
74
|
+
if page_id not in self._browser.pages:
|
|
75
|
+
raise ValueError(f"Page not found: {page_id}")
|
|
76
|
+
|
|
77
|
+
screenshot = await self._browser.pages[page_id].screenshot()
|
|
78
|
+
return types.ReadResourceResult(
|
|
79
|
+
contents=[
|
|
80
|
+
types.BlobResourceContents(
|
|
81
|
+
uri=uri,
|
|
82
|
+
mime_type="image/png",
|
|
83
|
+
blob=base64.b64encode(screenshot).decode(),
|
|
84
|
+
)
|
|
85
|
+
]
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
async def handle_list_resource_templates(
|
|
89
|
+
self, ctx: ServerRequestContext, params: types.PaginatedRequestParams
|
|
90
|
+
) -> types.ListResourceTemplatesResult:
|
|
91
|
+
"""List resource templates."""
|
|
92
|
+
return types.ListResourceTemplatesResult(resource_templates=[])
|
|
93
|
+
|
|
94
|
+
def register(self, server: Server) -> None:
|
|
95
|
+
"""Register all handlers with the MCP server."""
|
|
96
|
+
server.add_request_handler("tools/list", types.PaginatedRequestParams, self.handle_list_tools)
|
|
97
|
+
server.add_request_handler("tools/call", types.CallToolRequestParams, self.handle_call_tool)
|
|
98
|
+
server.add_request_handler("resources/list", types.PaginatedRequestParams, self.handle_list_resources)
|
|
99
|
+
server.add_request_handler("resources/read", types.ReadResourceRequestParams, self.handle_read_resource)
|
|
100
|
+
server.add_request_handler("resources/templates/list", types.PaginatedRequestParams, self.handle_list_resource_templates)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# Copyright (c) 2024 Playwright MCP Server Contributors
|
|
2
|
+
# Licensed under the MIT License - see LICENSE file for details
|
|
3
|
+
"""Main MCP server for Playwright browser automation."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import asyncio
|
|
8
|
+
import logging
|
|
9
|
+
from collections.abc import AsyncIterator
|
|
10
|
+
from contextlib import asynccontextmanager
|
|
11
|
+
|
|
12
|
+
import mcp.server.stdio
|
|
13
|
+
from mcp.server import Server
|
|
14
|
+
|
|
15
|
+
from .browser import BrowserManager, create_browser_manager
|
|
16
|
+
from .config import DEFAULT_CONFIG, ServerConfig
|
|
17
|
+
from .handlers import RequestHandlers
|
|
18
|
+
|
|
19
|
+
logger = logging.getLogger(__name__)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class PlaywrightMCPServer:
|
|
23
|
+
"""Playwright MCP Server with proper lifecycle management."""
|
|
24
|
+
|
|
25
|
+
def __init__(self, config: ServerConfig = DEFAULT_CONFIG) -> None:
|
|
26
|
+
self._config = config
|
|
27
|
+
self._browser = create_browser_manager(config)
|
|
28
|
+
self._handlers = RequestHandlers(self._browser, config.default_timeout)
|
|
29
|
+
self._server = Server(config.name)
|
|
30
|
+
self._handlers.register(self._server)
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def server(self) -> Server:
|
|
34
|
+
return self._server
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def browser(self) -> BrowserManager:
|
|
38
|
+
return self._browser
|
|
39
|
+
|
|
40
|
+
@asynccontextmanager
|
|
41
|
+
async def lifespan(self) -> AsyncIterator[None]:
|
|
42
|
+
"""Manage server lifecycle."""
|
|
43
|
+
logger.info("Starting Playwright MCP server...")
|
|
44
|
+
try:
|
|
45
|
+
yield
|
|
46
|
+
finally:
|
|
47
|
+
logger.info("Shutting down Playwright MCP server...")
|
|
48
|
+
await self._browser.close()
|
|
49
|
+
|
|
50
|
+
async def run_stdio(self) -> None:
|
|
51
|
+
"""Run the server over stdio transport."""
|
|
52
|
+
async with (
|
|
53
|
+
mcp.server.stdio.stdio_server() as (read_stream, write_stream),
|
|
54
|
+
self.lifespan(),
|
|
55
|
+
):
|
|
56
|
+
await self._server.run(
|
|
57
|
+
read_stream,
|
|
58
|
+
write_stream,
|
|
59
|
+
self._server.create_initialization_options(),
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def create_server(config: ServerConfig | None = None) -> PlaywrightMCPServer:
|
|
64
|
+
"""Factory function to create a configured server."""
|
|
65
|
+
if config is None:
|
|
66
|
+
config = DEFAULT_CONFIG
|
|
67
|
+
return PlaywrightMCPServer(config)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
async def main() -> None:
|
|
71
|
+
"""Main entry point for the server."""
|
|
72
|
+
server = create_server()
|
|
73
|
+
await server.run_stdio()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
if __name__ == "__main__":
|
|
77
|
+
asyncio.run(main())
|