### Install and Build Project Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/README.md Standard npm commands to install dependencies, compile TypeScript, start the server, and test with the CLI. ```bash npm install # Install dependencies npm run build # Compile TypeScript npm start # Start server npm run fetch # Test with CLI ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/configuration.md Clone the project repository and install all necessary npm packages. This step also downloads the Puppeteer browser. ```bash git clone https://github.com/christophe77/puppeteer-mcp cd puppeteer-mcp npm install ``` -------------------------------- ### Start Direct Server and Send JSON-RPC Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/README.md Start the MCP server using npm and then send JSON-RPC requests to its standard input for programmatic interaction. ```bash npm start # Send JSON-RPC requests via stdin ``` -------------------------------- ### Start Server with Stdio Transport Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/mcp-server.md A common pattern to start the MCP server by creating a StdioServerTransport and connecting the server to it. Includes basic error handling. ```typescript async function startServer() { const transport = new StdioServerTransport(); await server.connect(transport); } startServer().catch(console.error); ``` -------------------------------- ### Fetch Website Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/cli-wrapper.md Demonstrates how to fetch the content of a website using the fetch-web.js CLI script. ```bash node fetch-web.js https://example.com ``` ```bash node fetch-web.js http://localhost:3000 ``` ```bash npm run fetch https://example.com ``` -------------------------------- ### Start Puppeteer MCP Server Source: https://github.com/christophe77/puppeteer-mcp/blob/main/README.md Start the MCP server in the foreground. ```bash npm start ``` -------------------------------- ### CLI Usage Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/cli-wrapper.md Demonstrates the correct command-line usage for the fetch-web.js script. Ensure a URL is provided as an argument. ```bash $ node fetch-web.js Example: node fetch-web.js https://example.com ``` -------------------------------- ### Clone and Install Puppeteer MCP Source: https://github.com/christophe77/puppeteer-mcp/blob/main/README.md Clone the repository and install project dependencies using npm. ```bash git clone https://github.com/christophe77/puppeteer-mcp cd puppeteer-mcp npm install ``` -------------------------------- ### Fetch Page Source Tool Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/mcp-server.md An example of registering the 'fetchPageSource' tool. It uses Puppeteer to open a URL, capture the rendered page source, and return it in the MCP content format. ```typescript server.registerTool("fetchPageSource", { title: "Fetch Page Source", description: "Opens a URL with Puppeteer and returns the rendered page source", inputSchema: { url: z.string() } }, async ({ url }) => { const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPage(); await page.goto(url, { waitUntil: "domcontentloaded" }); const content = await page.content(); await browser.close(); return { content: [{ type: "text", text: content }] }; }); ``` -------------------------------- ### Example ToolResponse Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/types.md An example of a ToolResponse object, specifically for the fetchPageSource tool, containing HTML content. ```typescript { content: [{ type: "text", text: "\n\nPage\nContent\n" }] } ``` -------------------------------- ### Registering a New Tool Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/ARCHITECTURE.md Example of how to register a new tool with the MCP server. This involves providing a name, definition (including schema), and an asynchronous handler function. ```typescript server.registerTool("newTool", { title: "New Tool Title", description: "What it does", inputSchema: { param: z.string() } }, async ({ param }) => { // Implementation return { content: [{ type: "text", text: "result" }] }; }); ``` -------------------------------- ### Start MCP Server Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/errors.md Run the MCP server directly to view errors and logs printed to stderr. ```bash npm start ``` -------------------------------- ### JSON-RPC Response Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md This is an example of a server sending a JSON-RPC response back to the client after processing a request. ```json { "jsonrpc": "2.0", "id": 1, "result": { "content": [ { "type": "text", "text": "\n..." } ] } } ``` -------------------------------- ### Successful HTML Fetch Response Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md An example of a successful response specifically for fetching page source, demonstrating the HTML content within the result. ```APIDOC ## FetchPageSource Response Example ### Successful HTML Fetch ```json { "jsonrpc": "2.0", "id": 1, "result": { "content": [ { "type": "text", "text": "\n\n\nExample Domain\n\n\n

Example Domain

\n\n" } ] } } ``` ``` -------------------------------- ### JSON-RPC Batch Response Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md This is an example of a server response to a batch of JSON-RPC requests. Each request in the batch receives a corresponding response. ```json [ { "jsonrpc": "2.0", "id": 1, "result": { "content": [{ "type": "text", "text": "..." }] } }, { "jsonrpc": "2.0", "id": 2, "result": { "content": [{ "type": "text", "text": "..." }] } } ] ``` -------------------------------- ### JSON-RPC Batch Request Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md This example demonstrates how to send multiple JSON-RPC requests in a single batch. Note that puppeteer-mcp processes these sequentially. ```json [ { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "fetchPageSource", "arguments": { "url": "https://example.com" } } }, { "jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": { "name": "fetchPageSource", "arguments": { "url": "https://github.com" } } } ] ``` -------------------------------- ### Successful HTML Fetch Response Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md This example shows a successful response specifically for a fetchPageSource request, returning the HTML content of a web page. ```json { "jsonrpc": "2.0", "id": 1, "result": { "content": [ { "type": "text", "text": "\n\n\nExample Domain\n\n\n

Example Domain

\n\n" } ] } } ``` -------------------------------- ### Fetch Page Source for Debugging Source: https://github.com/christophe77/puppeteer-mcp/blob/main/README.md Example of fetching the page source for a local development server to debug frontend components. ```text @mcp puppeteer-mcp.fetchPageSource {"url": "http://localhost:3000"} ``` -------------------------------- ### Example Tool Handler Function Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/types.md An example implementation of a ToolHandler for fetching page source using Puppeteer. It launches a browser, navigates to a URL, captures content, and returns it in a ToolResponse. ```typescript async ({ url }: { url: string }): Promise => { const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPage(); await page.goto(url, { waitUntil: "domcontentloaded" }); const content = await page.content(); await browser.close(); return { content: [{ type: "text", text: content }] }; } ``` -------------------------------- ### Successful Response JSON-RPC Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/ARCHITECTURE.md Shows the expected JSON-RPC response from the server upon successful tool execution, containing the result. ```json { "jsonrpc": "2.0", "id": 1, "result": { "content": [ { "type": "text", "text": "[HTML content]" } ] } } ``` -------------------------------- ### Example of Invalid Parameters for tools/call Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md This example shows invalid arguments for the 'fetchPageSource' method, specifically a missing 'url' or incorrect type. Correct this to avoid 'Invalid params' (-32602) errors. ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "fetchPageSource", "arguments": { "url": "https://example.com" // Must be string } } } ``` -------------------------------- ### Project Documentation Structure Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/INDEX.md This snippet illustrates the hierarchical organization of the project's documentation files, guiding users to specific information about the API, architecture, configuration, and more. ```markdown /output/ ├── README.md # Start here ├── INDEX.md # This file ├── EXPORTS.md # API surface ├── ARCHITECTURE.md # System design ├── JSON-RPC-PROTOCOL.md # Protocol reference ├── types.md # Type definitions ├── configuration.md # Setup & config ├── errors.md # Error reference └── api-reference/ ├── mcp-server.md # Server API ├── fetch-page-source.md # Tool API └── cli-wrapper.md # CLI API ``` -------------------------------- ### Run Puppeteer MCP in Development Mode Source: https://github.com/christophe77/puppeteer-mcp/blob/main/README.md Start the MCP server in development mode, which includes building, watching for changes, and running the server. ```bash npm run dev ``` -------------------------------- ### Transmit FetchPageSource Request (Bash) Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md Example of how to transmit a JSON-RPC request to the puppeteer-mcp server using bash and node. ```bash echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"fetchPageSource","arguments":{"url":"https://example.com"}}}' | node dist/puppeteer-mcp.js ``` -------------------------------- ### fetchPageSource Tool Signature and Usage Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/fetch-page-source.md This snippet details the tool's signature, parameters, return type, and provides examples of how to use it via different methods. ```APIDOC ## fetchPageSource Tool ### Description Opens a URL with Puppeteer and returns the rendered page source. ### Tool Signature ```typescript registerTool( "fetchPageSource", { title: "Fetch Page Source", description: "Opens a URL with Puppeteer and returns the rendered page source", inputSchema: { url: z.string() } }, async ({ url }: { url: string }): Promise<{ content: Array<{ type: "text", text: string }> }> ) ``` ### Parameters #### Path Parameters - **url** (string) - Required - The full URL to fetch. Must be a valid HTTP or HTTPS URL (e.g., `https://example.com`) ### Return Type - **content** (Array) - Array of content blocks. For fetchPageSource, always contains a single text element. - **content[].type** (string) - Always `"text"` for fetchPageSource - **content[].text** (string) - The complete rendered HTML source of the page. Includes all DOM elements after JavaScript execution. ### Usage Examples #### Basic URL Fetch (MCP Client) ```typescript // Via MCP client (e.g., Cursor AI) @mcp puppeteer-mcp.fetchPageSource {"url": "https://example.com"} ``` #### Using NPM Script ```bash npm run fetch https://example.com ``` #### Using Node CLI ```bash node dist/puppeteer-mcp.js # Then send JSON-RPC request via stdin ``` ### Example Response ```json { "content": [ { "type": "text", "text": "\n\n\nExample Page\n\n\n

Content

\n\n" } ] } ``` ``` -------------------------------- ### JSON-RPC Browser Launch Error Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md Shows a JSON-RPC 2.0 internal error response (-32603) related to a browser launch issue, such as a target being closed. ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error", "data": { "originalError": "Error: Target closed" } } } ``` -------------------------------- ### Example of a Valid JSON-RPC Request Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md This is an example of a correctly formatted JSON-RPC request. Ensure all required fields like 'jsonrpc', 'id', and 'method' are present to avoid 'Invalid Request' (-32600) errors. ```json { "jsonrpc": "2.0", "id": , "method": "tools/call", "params": { "name": "...", "arguments": {...} } } ``` -------------------------------- ### Windows Platform-Specific Path Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/configuration.md Example of an absolute path argument for the `puppeteer-mcp` server on a Windows system. This path must point to the compiled JavaScript file. ```json "args": ["C:\\Users\\YourUser\\path\\to\\puppeteer-mcp\\dist\\puppeteer-mcp.js"] ``` -------------------------------- ### Fetch Page Source for SEO Verification Source: https://github.com/christophe77/puppeteer-mcp/blob/main/README.md Example of fetching the page source for a specific URL to verify SEO elements like meta tags and title tags. ```text @mcp puppeteer-mcp.fetchPageSource {"url": "https://myapp.com/product/123"} ``` -------------------------------- ### Register Tool with Puppeteer MCP Server Source: https://github.com/christophe77/puppeteer-mcp/blob/main/README.md Use `server.registerTool` to add new functionalities to the MCP server. This example shows how to register a 'screenshot' tool with its schema and an asynchronous handler. ```typescript server.registerTool( 'screenshot', { title: 'Take Screenshot', description: 'Capture a screenshot of a webpage', inputSchema: { url: z.string() }, }, async ({ url }) => { // Implementation here }, ); ``` -------------------------------- ### Error Response JSON-RPC Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/ARCHITECTURE.md Demonstrates the JSON-RPC error response format when a request fails due to validation errors or handler exceptions. ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error", "data": { "originalError": "..." } } } ``` -------------------------------- ### JSON-RPC Navigation Timeout Error Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md Represents a JSON-RPC 2.0 internal error (-32603) indicating a navigation timeout during a page fetch operation. ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32603, "message": "Internal error", "data": { "originalError": "TimeoutError: Timeout 30000ms exceeded" } } } ``` -------------------------------- ### macOS/Linux Platform-Specific Path Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/configuration.md Example of an absolute path argument for the `puppeteer-mcp` server on macOS or Linux systems. This path must point to the compiled JavaScript file. ```json "args": ["/home/user/path/to/puppeteer-mcp/dist/puppeteer-mcp.js"] ``` -------------------------------- ### Example Response Structure Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/fetch-page-source.md This JSON object represents a typical response from the fetchPageSource tool. It contains an array named 'content' with a single element of type 'text', holding the fetched HTML. ```json { "content": [ { "type": "text", "text": "\n\n\nExample Page\n\n\n

Content

\n\n" } ] } ``` -------------------------------- ### Fetch URL using NPM Script Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/fetch-page-source.md Shows how to execute the fetchPageSource functionality from the command line using an npm script. The URL is passed as a command-line argument. ```bash npm run fetch https://example.com ``` -------------------------------- ### Build Pipeline Overview Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/README.md Illustrates the build process from TypeScript source files to JavaScript and source maps using the TypeScript Compiler. ```text TypeScript (src/*.ts) ↓ TypeScript Compiler (tsc) ↓ JavaScript (dist/*.js) ↓ Source Maps (dist/*.js.map) ``` -------------------------------- ### Fetch Webpage using NPM Script Source: https://github.com/christophe77/puppeteer-mcp/blob/main/README.md Use the recommended npm script to fetch a webpage by providing the URL as an argument. ```bash npm run fetch https://example.com ``` -------------------------------- ### McpServer Constructor Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/mcp-server.md Initializes the main MCP server instance with a name and version. This server acts as the central hub for managing and exposing tools. ```APIDOC ## McpServer Constructor The main server instance is initialized using the `McpServer` class from the `@modelcontextprotocol/sdk/server/mcp.js` module. ```typescript const server = new McpServer({ name: "puppeteer-mcp", version: "1.0.0" }); ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | name | string | Yes | — | Server identifier, must be "puppeteer-mcp" | | version | string | Yes | — | Server version, currently "1.0.0" | ``` -------------------------------- ### Fetch URL using Node CLI Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/fetch-page-source.md Illustrates how to run the fetchPageSource tool via the Node.js command-line interface. After launching the script, JSON-RPC requests containing the URL can be sent via standard input. ```bash node dist/puppeteer-mcp.js # Then send JSON-RPC request via stdin ``` -------------------------------- ### Initialize McpServer Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/mcp-server.md Instantiate the McpServer with a name and version. The name must be 'puppeteer-mcp' and the version is '1.0.0'. ```typescript const server = new McpServer({ name: "puppeteer-mcp", version: "1.0.0" }); ``` -------------------------------- ### Standalone Execution Architecture Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/ARCHITECTURE.md Outlines the steps for executing the project standalone using npm run fetch, including spawning the Node.js process and making JSON-RPC requests. ```text npm run fetch ↓ node fetch-web.js ↓ spawn('node dist/puppeteer-mcp.js') ↓ JSON-RPC request to stdin ↓ HTML response to stdout ``` -------------------------------- ### Launching Puppeteer with Options Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/ARCHITECTURE.md Demonstrates how to launch a Puppeteer browser instance with custom configuration options. This snippet shows common options like headless mode, arguments, executable path, and timeout. ```typescript const browser = await puppeteer.launch({ headless: true, args: [...], executablePath: '...', timeout: 30000 }); ``` -------------------------------- ### Fetch Web Page CLI Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/configuration.md Executes a command-line interface script for fetching web pages. ```bash npm run fetch ``` -------------------------------- ### JSON-RPC Validation Error Example Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md Illustrates a JSON-RPC 2.0 validation error response, specifically for invalid parameters (-32602). ```json { "jsonrpc": "2.0", "id": 1, "error": { "code": -32602, "message": "Invalid params", "data": { "originalError": "Expected string, received null" } } } ``` -------------------------------- ### Module Dependency Graph for fetch-web.js Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/ARCHITECTURE.md Illustrates the dependencies for the fetch-web.js script, highlighting its reliance on Node.js built-in modules like child_process and path. ```text fetch-web.js ├─ child_process (Node.js built-in) │ └─ spawn() function └─ path (Node.js built-in) └─ path.join() function ``` -------------------------------- ### Launch Puppeteer Browser Instance Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/EXPORTS.md Imports the puppeteer library for browser automation. Use puppeteer.launch() to create a browser instance. ```typescript import puppeteer from "puppeteer"; ``` -------------------------------- ### Access Tool via MCP Protocol Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/EXPORTS.md Illustrates how to access the 'fetchPageSource' tool through the MCP protocol. This pattern is used for invoking registered tools. ```shell @mcp puppeteer-mcp.fetchPageSource {"url": "..."} ``` -------------------------------- ### Basic URL Fetch via MCP Client Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/fetch-page-source.md Demonstrates how to invoke the fetchPageSource tool using the MCP client, such as within an AI environment like Cursor. The URL to be fetched is provided as a JSON argument. ```typescript // Via MCP client (e.g., Cursor AI) @mcp puppeteer-mcp.fetchPageSource {"url": "https://example.com"} ``` -------------------------------- ### Fetch Webpage using Windows Batch File Source: https://github.com/christophe77/puppeteer-mcp/blob/main/README.md Execute a Windows batch file to fetch a webpage, passing the URL as an argument. ```cmd fetch.bat https://example.com ``` -------------------------------- ### Increase Node.js Heap Size Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/configuration.md Use this command to increase the Node.js heap size when encountering out-of-memory errors. Ensure Node.js is installed and accessible in your environment. ```bash node --max-old-space-size=4096 dist/puppeteer-mcp.js ``` -------------------------------- ### JSON-RPC Request with Missing URL Parameter Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md An example of a JSON-RPC request for 'fetchPageSource' where the 'url' parameter is missing, which would result in a -32602 Invalid params error. ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "fetchPageSource", "arguments": {} } } // Returns error: -32602 Invalid params ``` -------------------------------- ### Launch Puppeteer Browser (Headless with Args) Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/configuration.md Launches a Puppeteer browser instance with additional arguments for restricted environments like Docker. Use '--no-sandbox' and '--disable-setuid-sandbox' when necessary. ```typescript const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'], }); ``` -------------------------------- ### Verbose Output with npm Wrapper Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md Use the npm wrapper with verbose output to capture all communication to a log file. This is a simpler alternative to manual logging. ```bash npm run fetch https://example.com 2>&1 | tee /tmp/output.log ``` -------------------------------- ### Configuring Page Navigation Wait Strategy Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/ARCHITECTURE.md Shows how to set the `waitUntil` option for `page.goto()` to control when navigation is considered complete. Different strategies like 'load', 'networkidle2', or 'networkidle0' can be used. ```typescript await page.goto(url, { waitUntil: "load" // or "networkidle2", "networkidle0" }); ``` -------------------------------- ### Log Startup Errors Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/errors.md Logs startup errors to the console but does not prevent propagation or perform recovery. ```typescript startServer().catch(console.error); ``` -------------------------------- ### Tool Invocation Flow Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/INDEX.md Outlines the steps involved in invoking a tool using the MCP protocol, from client request to server response. ```text 1. Client prepares JSON-RPC request 2. Client sends to server stdin (newline-terminated) 3. Server parses and validates 4. Server executes handler 5. Server sends JSON-RPC response to stdout 6. Client parses response 7. Client extracts result from content ``` -------------------------------- ### Debug Request with CLI Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/README.md Use the `npm run fetch` command with error output redirection to a file for debugging requests. ```bash npm run fetch https://example.com 2>&1 | tee output.log ``` -------------------------------- ### Build Process for Source Maps Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/ARCHITECTURE.md Illustrates the build process where TypeScript source files are compiled into JavaScript, generating accompanying source maps for debugging. Stack traces will reference original .ts files. ```text src/puppeteer-mcp.ts ↓ tsc (compile) ↓ dist/puppeteer-mcp.js + dist/puppeteer-mcp.js.map ``` -------------------------------- ### Cursor AI Integration Architecture Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/ARCHITECTURE.md Details the communication flow for integrating with Cursor AI, showing how the MCP server process is spawned and communicates via stdio. ```text Cursor AI ↓ (stdio) ~/.cursor/mcp.json ↓ (reads config) "command": "node" "args": ["/path/to/dist/puppeteer-mcp.js"] ↓ (spawns) MCP Server Process ↓ (stdio) Response to Cursor ``` -------------------------------- ### Registering a New Tool Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md Register a new tool with the server, defining its schema and execution logic. This is used for extending the server's capabilities. ```typescript server.registerTool("newTool", { title: "New Tool", description: "Tool description", inputSchema: { param1: z.string(), param2: z.number() } }, async ({ param1, param2 }) => { return { content: [{ type: "text", text: "result" }] }; }); ``` -------------------------------- ### McpServerConfig Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/types.md Configuration object passed to the McpServer constructor. It requires a name and version. ```APIDOC ## McpServerConfig ### Description Configuration object passed to the McpServer constructor. ### Parameters #### Request Body - **name** (string) - Required - Server identifier. Must be `"puppeteer-mcp"`. - **version** (string) - Required - Server version. Currently `"1.0.0"`. ``` -------------------------------- ### MCP Service Contract - Available Tools Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/EXPORTS.md Defines the MCP protocol's available tools, including their names, descriptions, and input schemas. This JSON structure details the 'fetchPageSource' tool, which opens a URL and returns the rendered page source. ```json { "tools": [ { "name": "fetchPageSource", "description": "Opens a URL with Puppeteer and returns the rendered page source", "inputSchema": { "type": "object", "properties": { "url": { "type": "string" } }, "required": ["url"] } } ] } ``` -------------------------------- ### Capture Protocol Requests/Responses with Node.js Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md Capture all server logs to a file and send requests to the server. Ensure the server is running in the background before sending requests. Kill the server process after completion. ```bash node dist/puppeteer-mcp.js > /tmp/server.log 2>&1 & PID=$! echo '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"fetchPageSource","arguments":{"url":"https://example.com"}}}' > /tmp/request.json cat /tmp/request.json | node dist/puppeteer-mcp.js kill $PID cat /tmp/server.log ``` -------------------------------- ### Register McpServer and StdioServerTransport Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/EXPORTS.md Imports necessary classes for server initialization and communication transport from the '@modelcontextprotocol/sdk'. ```typescript import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; ``` -------------------------------- ### Build and Watch Puppeteer MCP Source: https://github.com/christophe77/puppeteer-mcp/blob/main/README.md Build the project and continuously watch for file changes, automatically rebuilding as needed. ```bash npm run build:watch ``` -------------------------------- ### Build Project with Watch Mode Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/configuration.md Compiles TypeScript to JavaScript and continuously watches for file changes, recompiling automatically. ```bash npm run build:watch ``` -------------------------------- ### Development Mode: Watch and Run Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/configuration.md Enables development mode by simultaneously compiling TypeScript files as they change and running the application. This is useful for rapid development cycles. ```bash npm run dev ``` -------------------------------- ### Project Document Relationships Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/MANIFEST.md Illustrates the hierarchical structure and relationships between different documentation files within the project. ```markdown README (entry point) ├─→ INDEX (navigation) ├─→ ARCHITECTURE (design overview) ├─→ EXPORTS (API surface) └─→ Configuration (setup) ARCHITECTURE (detailed design) ├─→ Component Details │ ├─→ MCP Server API │ ├─→ fetchPageSource Tool │ └─→ CLI Wrapper ├─→ Data Flow ├─→ Resource Management └─→ Extensibility Points Configuration (setup & options) ├─→ Server Configuration ├─→ Cursor Integration ├─→ Build Configuration ├─→ Dependencies └─→ Troubleshooting └─→ Errors (detailed) JSON-RPC Protocol (communication) ├─→ Request Format ├─→ Response Format ├─→ Error Codes └─→ Debugging Types (definitions) ├─→ Input Types (FetchPageSourceInput) ├─→ Output Types (ToolResponse) └─→ External Types (McpServer, etc.) Errors (troubleshooting) ├─→ Error Scenarios ├─→ Causes & Solutions ├─→ Recommended Patterns └─→ Debugging Techniques ``` -------------------------------- ### Define McpServerConfig Interface Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/types.md Defines the configuration object required for initializing the McpServer, including name and version. ```typescript interface McpServerConfig { name: string; version: string; } ``` -------------------------------- ### Configure Cursor MCP Server Source: https://github.com/christophe77/puppeteer-mcp/blob/main/README.md Add the Puppeteer MCP server configuration to your Cursor MCP settings file. Ensure the command path is correct for your system. ```json { "mcpServers": { "puppeteer-mcp": { "command": "node", "args": ["C:\\path\\to\\your\\puppeteer-mcp\\dist\\puppeteer-mcp.js"] } } } ``` -------------------------------- ### Resource Cleanup Pattern Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/INDEX.md Illustrates the recommended pattern for ensuring browser resources are cleaned up after operations using Puppeteer. ```text Browser launched ↓ Page operations ↓ browser.close() [should be guaranteed with try/finally] ``` -------------------------------- ### Project File Structure Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/README.md Details the directory and file layout of the Puppeteer MCP project, including source, distribution, and configuration files. ```text puppeteer-mcp/ ├── src/ │ └── puppeteer-mcp.ts # Main MCP server (43 lines) ├── dist/ # Compiled JavaScript (generated) ├── fetch-web.js # CLI wrapper (61 lines) ├── fetch.bat # Windows batch wrapper ├── package.json # Dependencies and scripts ├── tsconfig.json # TypeScript configuration ├── README.md # User-facing documentation └── package-lock.json # Dependency lock file ``` -------------------------------- ### Register Tool with McpServer Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/mcp-server.md Register a new tool with the MCP server. This involves providing a unique tool name, a definition including title, description, and input schema, and an asynchronous handler function that processes input and returns content. ```typescript server.registerTool( toolName: string, toolDefinition: { title: string, description: string, inputSchema: { [key: string]: ZodSchema } }, handler: async (params: Record) => { content: Array<{ type: string, text: string }> } ) ``` -------------------------------- ### TypeScript Compiler Options Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/configuration.md Key TypeScript compiler options for the project, including target, module system, output directory, and strict type-checking settings. Ensure `npm run build` is executed to generate the necessary files. ```json { "target": "ES2020", "module": "Node16", "moduleResolution": "node16", "lib": ["ES2020"], "outDir": "./dist", "rootDir": "./src", "strict": true, "declaration": true, "declarationMap": true, "sourceMap": true } ``` -------------------------------- ### Package.json Main Export Configuration Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/EXPORTS.md Defines the main entry point for Node.js require() and specifies the module type. This configuration indicates that the primary file for execution is 'dist/puppeteer-mcp.js' and it uses the CommonJS module system. ```json { "main": "dist/puppeteer-mcp.js", "type": "commonjs" } ``` -------------------------------- ### Module Dependency Graph for puppeteer-mcp.ts Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/ARCHITECTURE.md Visualizes the direct dependencies of the main puppeteer-mcp.ts file, including SDK components, Puppeteer, and Zod. ```text puppeteer-mcp.ts ├─ @modelcontextprotocol/sdk/server/mcp.js │ └─ (MCP protocol implementation) ├─ @modelcontextprotocol/sdk/server/stdio.js │ └─ (stdio transport) ├─ puppeteer │ ├─ Chromium browser download │ └─ Browser automation API └─ zod └─ Runtime input validation ``` -------------------------------- ### Build Puppeteer MCP Project Source: https://github.com/christophe77/puppeteer-mcp/blob/main/README.md Compile the TypeScript project into JavaScript for execution. ```bash npm run build ``` -------------------------------- ### Call fetchPageSource via Cursor AI Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/EXPORTS.md Use this command within Cursor AI to fetch the source code of a webpage. ```shell @mcp puppeteer-mcp.fetchPageSource {"url": "https://example.com"} ``` -------------------------------- ### Accessing Content from Tool Response Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/cli-wrapper.md Illustrates the expected structure for accessing the content text from a tool's response. This path is specific to the MCP tool's output format. ```javascript response.result.content[0].text ``` -------------------------------- ### Register a New Tool with MCP Server Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/README.md Use the `registerTool` method to add a new tool to the MCP server, defining its name, title, description, and input schema. ```typescript server.registerTool("toolName", { title: "Tool Title", description: "Tool description", inputSchema: { param: z.string() } }, async ({ param }) => { // Implementation return { content: [{ type: "text", text: "result" }] }; }); ``` -------------------------------- ### Invoking a Tool via JSON-RPC Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/JSON-RPC-PROTOCOL.md Call a registered tool using the JSON-RPC protocol. Specify the tool name and its arguments in the params object. ```json { "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "newTool", "arguments": { "param1": "value", "param2": 42 } } } ``` -------------------------------- ### Spawn MCP Server Process Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/cli-wrapper.md Spawns the compiled MCP server as a child process using Node.js. It configures stdio to pipe all streams for capturing. ```javascript const server = spawn('node', [path.join(__dirname, 'dist', 'puppeteer-mcp.js')], { stdio: ['pipe', 'pipe', 'pipe'] }); ``` -------------------------------- ### registerTool Method Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/mcp-server.md Registers a tool with the MCP server, making it available for invocation through the MCP protocol. This involves defining the tool's metadata, input schema, and the handler function that executes its logic. ```APIDOC ## registerTool Method Registers a callable tool that can be invoked through the MCP protocol. ```typescript server.registerTool( toolName: string, toolDefinition: { title: string, description: string, inputSchema: { [key: string]: ZodSchema } }, handler: async (params: Record) => { content: Array<{ type: string, text: string }> } ) ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | toolName | string | Yes | Identifier for the tool. Used to reference the tool in MCP calls. | | toolDefinition.title | string | Yes | Human-readable name displayed in Cursor AI and other MCP clients. | | toolDefinition.description | string | Yes | Detailed explanation of what the tool does. Used to help AI understand tool capabilities. | | toolDefinition.inputSchema | Object | Yes | Zod schema object defining the structure and types of input parameters. | | handler | async function | Yes | Async function that implements the tool logic. Receives parsed input parameters and returns MCP-formatted response. | ### Return Type The handler function must return an object with the structure: ```typescript { content: Array<{ type: "text" | "image" | "resource", text: string }> } ``` The `content` array contains the tool output in MCP-compliant format. ### Example ```typescript server.registerTool("fetchPageSource", { title: "Fetch Page Source", description: "Opens a URL with Puppeteer and returns the rendered page source", inputSchema: { url: z.string() } }, async ({ url }) => { const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPage(); await page.goto(url, { waitUntil: "domcontentloaded" }); const content = await page.content(); await browser.close(); return { content: [{ type: "text", text: content }] }; }); ``` ``` -------------------------------- ### Connect McpServer with StdioServerTransport Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/api-reference/mcp-server.md Establish communication between the McpServer and the MCP client using standard input/output streams via StdioServerTransport. ```typescript const transport = new StdioServerTransport(); await server.connect(transport); ``` -------------------------------- ### FetchPageSourceInput Source: https://github.com/christophe77/puppeteer-mcp/blob/main/_autodocs/types.md Input parameters for the `fetchPageSource` tool. It requires a URL to fetch. ```APIDOC ## FetchPageSourceInput ### Description Input parameters for the `fetchPageSource` tool. ### Parameters #### Request Body - **url** (string) - Required - The full URL to fetch. Must be a valid HTTP or HTTPS URL. Examples: `https://example.com`, `http://localhost:3000/page` ```