{
  "canonical_name": "executeautomation/mcp-playwright",
  "compilation_id": "pack_75749727706349079215d2da36ee9bf3",
  "created_at": "2026-05-15T13:34:54.503740+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=mcp_config, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=mcp_config, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `npm install -g @executeautomation/playwright-mcp-server` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "npm install -g @executeautomation/playwright-mcp-server",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_9a9097066dab40c087774c0278318a55"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_912bd7b56991af6d0d3cfe53eff810c2",
    "canonical_name": "executeautomation/mcp-playwright",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/executeautomation/mcp-playwright",
    "slug": "mcp-playwright",
    "source_packet_id": "phit_fdf3dd806aa24898a57c59fec49fc279",
    "source_validation_id": "dval_f8a266e7fd954a8a844a96cb7b062319"
  },
  "merchandising": {
    "best_for": "需要工具连接与集成能力，并使用 mcp_host的用户",
    "github_forks": 510,
    "github_stars": 5509,
    "one_liner_en": "Playwright Model Context Protocol Server - Tool to automate Browsers and APIs in Claude Desktop, Cline, Cursor IDE and More 🔌",
    "one_liner_zh": "Playwright Model Context Protocol Server - Tool to automate Browsers and APIs in Claude Desktop, Cline, Cursor IDE and More 🔌",
    "primary_category": {
      "category_id": "tool-integrations",
      "confidence": "high",
      "name_en": "Tool Integrations",
      "name_zh": "工具连接与集成",
      "reason": "matched_keywords:mcp, api, server"
    },
    "target_user": "使用 mcp_host, claude, cursor 等宿主 AI 的用户",
    "title_en": "mcp-playwright",
    "title_zh": "mcp-playwright 能力包",
    "visible_tags": [
      {
        "label_en": "Security & Permissions",
        "label_zh": "安全审查与权限治理",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-security-permissions",
        "type": "product_domain"
      },
      {
        "label_en": "Web Task Automation",
        "label_zh": "网页任务自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-web-task-automation",
        "type": "user_job"
      },
      {
        "label_en": "Natural-language Web Actions",
        "label_zh": "自然语言网页操作",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-natural-language-web-actions",
        "type": "core_capability"
      },
      {
        "label_en": "Node-based Workflow",
        "label_zh": "节点式流程编排",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-node-based-workflow",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_fdf3dd806aa24898a57c59fec49fc279",
  "page_model": {
    "artifacts": {
      "artifact_slug": "mcp-playwright",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "npm install -g @executeautomation/playwright-mcp-server",
          "label": "Node.js / npm · 官方安装入口",
          "source": "https://github.com/executeautomation/mcp-playwright#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "安全审查与权限治理",
        "网页任务自动化",
        "自然语言网页操作",
        "节点式流程编排",
        "评测体系"
      ],
      "eyebrow": "工具连接与集成",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要工具连接与集成能力，并使用 mcp_host的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "Playwright Model Context Protocol Server - Tool to automate Browsers and APIs in Claude Desktop, Cline, Cursor IDE and More 🔌"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "mcp_host, claude, cursor",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Playwright is asking for an specific browser version.",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_38465ac94a9d4fb0bd352ba5209096ac | https://github.com/executeautomation/mcp-playwright/issues/117 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Playwright is asking for an specific browser version.",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：How to configure proxy and storageState when launching browser in Playwright MCP?",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_a2f7e4a410994d4195a9af9f139e0caa | https://github.com/executeautomation/mcp-playwright/issues/203 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：How to configure proxy and storageState when launching browser in Playwright MCP?",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。",
            "category": "配置坑",
            "evidence": [
              "capability.host_targets | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | host_targets=mcp_host, claude, cursor"
            ],
            "severity": "medium",
            "suggested_check": "列出会写入的配置文件、目录和卸载/回滚步骤。",
            "title": "可能修改宿主 AI 配置",
            "user_impact": "安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Add Clarvia AEO score badge to README (AEO 32/100)",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_74959d07d5f74165bcd9cae829d384ce | https://github.com/executeautomation/mcp-playwright/issues/212 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Add Clarvia AEO score badge to README (AEO 32/100)",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Add policy enforcement for browser automation and HTTP request tools",
            "category": "配置坑",
            "evidence": [
              "community_evidence:github | cevd_23a30d245f794b8db40c1d031b8be565 | https://github.com/executeautomation/mcp-playwright/issues/216 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Add policy enforcement for browser automation and HTTP request tools",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：How to pass in the `--ignore-https-errors` parameter?",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_47d5e333819d49b4b8ce2abb9484b23d | https://github.com/executeautomation/mcp-playwright/issues/202 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：How to pass in the `--ignore-https-errors` parameter?",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | last_activity_observed missing"
            ],
            "severity": "medium",
            "suggested_check": "补 GitHub 最近 commit、release、issue/PR 响应信号。",
            "title": "维护活跃度未知",
            "user_impact": "新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "downstream_validation.risk_items | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "No sandbox install has been executed yet; downstream must verify before user use.",
            "category": "安全/权限坑",
            "evidence": [
              "risks.safety_notes | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | No sandbox install has been executed yet; downstream must verify before user use."
            ],
            "severity": "medium",
            "suggested_check": "转成明确权限清单和安全审查提示。",
            "title": "存在安全注意事项",
            "user_impact": "用户安装前需要知道权限边界和敏感操作。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Request: Add browser context persistence for login state (userDataDir/storageState)",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_3632e6a11e044dda870b3267ccfa3040 | https://github.com/executeautomation/mcp-playwright/issues/201 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：Feature Request: Add browser context persistence for login state (userDataDir/storageState)",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Free MCP security scan report for @executeautomation/playwright-mcp-server",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_9720dc9967444ed08710cdb0660a212a | https://github.com/executeautomation/mcp-playwright/issues/211 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Free MCP security scan report for @executeautomation/playwright-mcp-server",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Security Advisory: SSRF, Prompt Injection, and Arbitrary JavaScript Execution via Browser Automation Tools",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_ced642164084421f84bbb63681653057 | https://github.com/executeautomation/mcp-playwright/issues/209 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Security Advisory: SSRF, Prompt Injection, and Arbitrary JavaScript Execution via Browser Automation Tools",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | issue_or_pr_quality=unknown"
            ],
            "severity": "low",
            "suggested_check": "抽样最近 issue/PR，判断是否长期无人处理。",
            "title": "issue/PR 响应质量未知",
            "user_impact": "用户无法判断遇到问题后是否有人维护。"
          },
          {
            "body": "release_recency=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | release_recency=unknown"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 16 个潜在踩坑项，其中 2 个为 high/blocking；最高优先级：安装坑 - 来源证据：Playwright is asking for an specific browser version.。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 34,
        "forks": 510,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 5509
      },
      "source_url": "https://github.com/executeautomation/mcp-playwright",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "Playwright Model Context Protocol Server - Tool to automate Browsers and APIs in Claude Desktop, Cline, Cursor IDE and More 🔌",
      "title": "mcp-playwright 能力包",
      "trial_prompt": "# mcp-playwright - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for executeautomation/mcp-playwright.\n\nProject:\n- Name: mcp-playwright\n- Repository: https://github.com/executeautomation/mcp-playwright\n- Summary: Playwright Model Context Protocol Server - Tool to automate Browsers and APIs in Claude Desktop, Cline, Cursor IDE and More 🔌\n- Host target: mcp_host, claude, cursor\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Playwright Model Context Protocol Server - Tool to automate Browsers and APIs in Claude Desktop, Cline, Cursor IDE and More 🔌\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Playwright Model Context Protocol Server - Tool to automate Browsers and APIs in Claude Desktop, Cline, Cursor IDE and More 🔌\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. project-introduction: Project Introduction. Produce one small intermediate artifact and wait for confirmation.\n2. getting-started: Getting Started. Produce one small intermediate artifact and wait for confirmation.\n3. architecture-overview: Architecture Overview. Produce one small intermediate artifact and wait for confirmation.\n4. transport-modes: Transport Modes. Produce one small intermediate artifact and wait for confirmation.\n5. browser-automation: Browser Automation Tools. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/executeautomation/mcp-playwright\n- https://github.com/executeautomation/mcp-playwright#readme\n- README.md\n- package.json\n- CHANGELOG.md\n- mcp-config.json\n- DOCKER.md\n- Dockerfile\n- src/index.ts\n- src/toolHandler.ts\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github。github/github_issue: Add policy enforcement for browser automation and HTTP request tools（https://github.com/executeautomation/mcp-playwright/issues/216）；github/github_issue: Add Clarvia AEO score badge to README (AEO 32/100)（https://github.com/executeautomation/mcp-playwright/issues/212）；github/github_issue: Free MCP security scan report for @executeautomation/playwright-mcp-serv（https://github.com/executeautomation/mcp-playwright/issues/211）；github/github_issue: How to configure proxy and storageState when launching browser in Playwr（https://github.com/executeautomation/mcp-playwright/issues/203）；github/github_issue: Security Advisory: SSRF, Prompt Injection, and Arbitrary JavaScript Exec（https://github.com/executeautomation/mcp-playwright/issues/209）；github/github_issue: Playwright is asking for an specific browser version.（https://github.com/executeautomation/mcp-playwright/issues/117）；github/github_issue: How to pass in the `--ignore-https-errors` parameter?（https://github.com/executeautomation/mcp-playwright/issues/202）；github/github_issue: Feature Request: Add browser context persistence for login state (userDa（https://github.com/executeautomation/mcp-playwright/issues/201）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Add policy enforcement for browser automation and HTTP request tools",
              "url": "https://github.com/executeautomation/mcp-playwright/issues/216"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Add Clarvia AEO score badge to README (AEO 32/100)",
              "url": "https://github.com/executeautomation/mcp-playwright/issues/212"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Free MCP security scan report for @executeautomation/playwright-mcp-serv",
              "url": "https://github.com/executeautomation/mcp-playwright/issues/211"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "How to configure proxy and storageState when launching browser in Playwr",
              "url": "https://github.com/executeautomation/mcp-playwright/issues/203"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Security Advisory: SSRF, Prompt Injection, and Arbitrary JavaScript Exec",
              "url": "https://github.com/executeautomation/mcp-playwright/issues/209"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Playwright is asking for an specific browser version.",
              "url": "https://github.com/executeautomation/mcp-playwright/issues/117"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "How to pass in the `--ignore-https-errors` parameter?",
              "url": "https://github.com/executeautomation/mcp-playwright/issues/202"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Feature Request: Add browser context persistence for login state (userDa",
              "url": "https://github.com/executeautomation/mcp-playwright/issues/201"
            }
          ],
          "status": "已收录 8 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "工具连接与集成",
      "desc": "Playwright Model Context Protocol Server - Tool to automate Browsers and APIs in Claude Desktop, Cline, Cursor IDE and More 🔌",
      "effort": "安装已验证",
      "forks": 510,
      "icon": "link",
      "name": "mcp-playwright 能力包",
      "risk": "可发布",
      "slug": "mcp-playwright",
      "stars": 5509,
      "tags": [
        "安全审查与权限治理",
        "网页任务自动化",
        "自然语言网页操作",
        "节点式流程编排",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/executeautomation/mcp-playwright 项目说明书\n\n生成时间：2026-05-15 13:16:39 UTC\n\n## 目录\n\n- [Project Introduction](#project-introduction)\n- [Getting Started](#getting-started)\n- [Architecture Overview](#architecture-overview)\n- [Transport Modes](#transport-modes)\n- [Browser Automation Tools](#browser-automation)\n- [Device Emulation](#device-emulation)\n- [API Testing Tools](#api-testing)\n- [Code Generation and Recording](#code-generation)\n- [Docker Deployment](#docker-deployment)\n- [Configuration Guide](#configuration)\n\n<a id='project-introduction'></a>\n\n## Project Introduction\n\n### 相关页面\n\n相关主题：[Getting Started](#getting-started), [Architecture Overview](#architecture-overview)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)\n- [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)\n</details>\n\n# Project Introduction\n\nThe **Playwright MCP Server** (`mcp-playwright`) is a Model Context Protocol (MCP) server implementation that provides browser automation capabilities through Playwright. It enables AI assistants like Claude, Cursor, and other MCP-compatible clients to interact with web pages through a standardized tool interface.\n\n## Overview\n\nThe project serves as a bridge between AI assistants and browser automation, exposing Playwright's browser control capabilities as MCP tools. This allows AI agents to perform web navigation, content extraction, form interactions, and other browser-related tasks using natural language commands.\n\n**Key Characteristics:**\n\n| Attribute | Value |\n|-----------|-------|\n| Project Name | mcp-playwright |\n| Package Name | @executeautomation/playwright-mcp-server |\n| License | MIT |\n| Node.js Version | 20+ |\n| Protocol | Model Context Protocol (MCP) |\n\n资料来源：[package.json:1-20]()\n\n## Architecture\n\nThe server follows a client-server architecture where AI assistants act as MCP clients communicating with the Playwright MCP server.\n\n```mermaid\ngraph TD\n    A[\"AI Assistant<br/>(Claude, Cursor, etc.)\"] -->|MCP Protocol| B[\"Playwright MCP Server\"]\n    B -->|stdin/stdout| A\n    B -->|HTTP/SSE| B\n    C[\"Browser Instances<br/>(Chromium, Firefox, WebKit)\"] -->|Playwright API| B\n    \n    B -->|Browser Automation| C\n    C -->|Page Content| B\n    B -->|Tool Results| A\n```\n\n### Core Components\n\n| Component | Purpose |\n|-----------|---------|\n| MCP SDK | Handles MCP protocol communication |\n| Tool Handlers | Processes tool calls and executes Playwright operations |\n| Browser Manager | Manages browser lifecycle and instances |\n| Logging System | Captures request/response data and error tracking |\n\n资料来源：[src/logging/middleware.ts:1-20]()\n\n## Installation Methods\n\nThe project supports multiple installation approaches to accommodate different deployment scenarios.\n\n### Package Managers\n\n```bash\n# npm\nnpm install -g @executeautomation/playwright-mcp-server\n\n# mcp-get\nnpx @michaellatman/mcp-get@latest install @executeautomation/playwright-mcp-server\n\n# Smithery (automated)\nnpx @smithery/cli install @executeautomation/playwright-mcp-server --client claude\n```\n\n### Claude Code\n\n```bash\nclaude mcp add --transport stdio playwright npx @executeautomation/playwright-mcp-server\n```\n\n资料来源：[README.md:40-65]()\n\n## Operation Modes\n\nThe server supports two primary operation modes based on the transport mechanism.\n\n### STDIO Mode (Default)\n\nSTDIO mode is the recommended configuration for Claude Desktop and other clients that communicate via standard input/output streams.\n\n```mermaid\ngraph LR\n    A[\"MCP Client\"] -->|\"stdio\"| B[\"Playwright MCP Server\"]\n    B -->|\"stdio\"| A\n    C[\"Playwright<br/>Browser\"] -->|Control| B\n```\n\n**Configuration Example:**\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n    }\n  }\n}\n```\n\n> **Note:** In stdio mode, logging is automatically directed to files only to maintain clean JSON-RPC communication. Logs are written to `~/playwright-mcp-server.log`.\n\n资料来源：[README.md:20-30]()\n\n### HTTP Mode (Standalone Server)\n\nHTTP mode enables the server to run as a standalone HTTP server, suitable for VS Code, custom clients, and remote deployments.\n\n```bash\nnpx @executeautomation/playwright-mcp-server --port 8931\n```\n\n**Available Endpoints:**\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/sse` | GET | SSE Stream for server-sent events |\n| `/messages?sessionId=<id>` | POST | Send messages to a session |\n| `/mcp` | GET/POST | Unified MCP protocol endpoint |\n| `/health` | GET | Health check endpoint |\n\n**Client Configuration:**\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"url\": \"http://localhost:8931/mcp\"\n    }\n  }\n}\n```\n\n资料来源：[README.md:35-55]()\n资料来源：[examples/http-mode-example.md:1-30]()\n\n## Docker Deployment\n\nThe project provides official Docker images for containerized deployments.\n\n### Basic Usage\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n### Docker Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright-docker\": {\n      \"command\": \"docker\",\n      \"args\": [\"run\", \"-i\", \"--rm\", \"mcp-playwright:latest\"]\n    }\n  }\n}\n```\n\n### Environment Variables\n\n| Variable | Purpose | Default |\n|----------|---------|---------|\n| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser installation | 1 |\n| `NODE_ENV` | Node environment | production |\n\n### Volume Mounts\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  -v $(screenshots):/app/screenshots \\\n  mcp-playwright:latest\n```\n\n> **Note:** The Docker image skips browser downloads by default to reduce size (~200MB). Browsers are downloaded on first use.\n\n资料来源：[DOCKER.md:1-80]()\n\n## Supported Tools\n\nThe server exposes a comprehensive set of Playwright operations as MCP tools.\n\n### Browser Control Tools\n\n| Tool Category | Tools | Description |\n|---------------|-------|-------------|\n| Navigation | `playwright_navigate` | Navigate to URLs with multi-browser support |\n| Interaction | `playwright_click`, `playwright_drag`, `playwright_press_key` | Element interactions |\n| Content | `playwright_get_visible_text`, `playwright_get_visible_html` | Content extraction |\n| Output | `playwright_save_as_pdf` | Page to PDF conversion |\n\n### Browser Support\n\n| Browser | Support |\n|---------|---------|\n| Chromium | ✅ Default |\n| Firefox | ✅ Since v1.0.2 |\n| WebKit | ✅ Since v1.0.2 |\n\n资料来源：[CHANGELOG.md:1-30]()\n\n## Dependencies\n\n### Production Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | 1.24.3 | MCP protocol implementation |\n| `playwright` | 1.57.0 | Browser automation framework |\n| `@playwright/browser-chromium` | 1.57.0 | Chromium browser |\n| `@playwright/browser-firefox` | 1.57.0 | Firefox browser |\n| `@playwright/browser-webkit` | 1.57.0 | WebKit browser |\n| `express` | ^4.21.1 | HTTP server for HTTP mode |\n| `cors` | ^2.8.5 | Cross-origin resource sharing |\n| `uuid` | 11.1.0 | Session ID generation |\n| `mcp-evals` | ^2.0.1 | Evaluation utilities |\n\n### Development Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `typescript` | ^5.8.3 | TypeScript compilation |\n| `jest` | ^29.7.0 | Testing framework |\n| `jest-playwright-preset` | 4.0.0 | Playwright test integration |\n| `ts-jest` | ^29.2.6 | TypeScript Jest transformer |\n\n资料来源：[package.json:20-50]()\n\n## Logging System\n\nThe server includes a comprehensive logging system for debugging and monitoring.\n\n### Log Location\n\n- **STDIO Mode:** `~/playwright-mcp-server.log` (file only)\n- **HTTP Mode:** Configurable via server settings\n\n### Log Features\n\n| Feature | Description |\n|---------|-------------|\n| Request Logging | Captures tool execution with sanitized arguments |\n| Error Context | Includes stack traces and browser state |\n| Log Rotation | Automatic rotation with configurable max files |\n| Sensitive Data Redaction | Passwords, tokens, and secrets automatically masked |\n\n资料来源：[src/logging/logger.ts:1-50]()\n资料来源：[src/logging/middleware.ts:1-30]()\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue | Solution |\n|-------|----------|\n| Container exits immediately | Ensure `-i` flag is used for Docker |\n| Browser not found | Use custom Dockerfile with `npx playwright install` |\n| Permission issues | Use `--user $(id -u):$(id -g)` flag |\n| Tool name too long | Keep names under 60 characters (server + tool name) |\n\n> **Important:** When adding new tools, ensure tool names are short enough to not exceed the 60-character limit for combined server and tool name (`server_name:tool_name`). The server name is `playwright-mcp`.\n\n资料来源：[README.md:15-18]()\n\n## Version History\n\n| Version | Date | Key Changes |\n|---------|------|-------------|\n| 1.0.8 | Current | Latest stable release |\n| 1.0.7 | 2024-12 | Advanced screenshot and content tools |\n| 1.0.2 | 2024-11-10 | Multi-browser support (Firefox, WebKit) |\n| 1.0.0 | 2024-11-01 | First major release with Bearer Auth support |\n\n资料来源：[CHANGELOG.md:1-50]()\n\n## Next Steps\n\nFor more detailed information, refer to:\n\n- [Installation Guide](https://executeautomation.github.io/mcp-playwright/) - Detailed setup instructions\n- [API Reference](https://executeautomation.github.io/mcp-playwright/docs/playwright-web/Supported-Tools) - Complete tool documentation\n- [Device Quick Reference](https://executeautomation.github.io/mcp-playwright/docs/playwright-web/Device-Quick-Reference) - Mobile device emulation\n- [Prompt Guide](https://executeautomation.github.io/mcp-playwright/docs/playwright-web/Resize-Prompts-Guide) - Resize prompt strategies\n\n---\n\n<a id='getting-started'></a>\n\n## Getting Started\n\n### 相关页面\n\n相关主题：[Project Introduction](#project-introduction), [Docker Deployment](#docker-deployment), [Configuration Guide](#configuration)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)\n- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)\n- [src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)\n- [src/logging/logger.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/logger.ts)\n</details>\n\n# Getting Started\n\nThis guide provides everything you need to install, configure, and run the Playwright MCP Server. The server enables AI assistants like Claude to interact with web browsers through a comprehensive set of automation tools.\n\n## Overview\n\nThe Playwright MCP Server is a Model Context Protocol (MCP) server that provides programmatic control over Playwright browsers. It allows AI assistants to perform web automation tasks including navigation, interaction, content extraction, and screenshot capture.\n\n**Key Features:**\n- Multi-browser support (Chromium, Firefox, WebKit)\n- 143 device presets for mobile emulation\n- Screenshot and PDF generation\n- Web scraping and content extraction\n- Keyboard and mouse automation\n- HTTP and stdio communication modes\n\n资料来源：[README.md:1-45]()\n\n## Prerequisites\n\nBefore installing the Playwright MCP Server, ensure your system meets these requirements:\n\n| Requirement | Minimum Version | Notes |\n|-------------|-----------------|-------|\n| Node.js | 20.x or higher | LTS recommended |\n| npm | 9.x or higher | Comes with Node.js |\n| Docker (optional) | 20.x or higher | For containerized deployment |\n| Playwright browsers | Latest | Auto-installed on first use |\n\n**System Dependencies for Playwright:**\n- Linux: `npx playwright install-deps`\n- macOS: Xcode Command Line Tools\n- Windows: Visual Studio Build Tools\n\n资料来源：[package.json:23-36]()\n\n## Installation Methods\n\n### Method 1: npm Package (Recommended)\n\nInstall the package globally for CLI access:\n\n```bash\nnpm install -g @executeautomation/playwright-mcp-server\n```\n\nOr use it directly with npx (no installation required):\n\n```bash\nnpx -y @executeautomation/playwright-mcp-server\n```\n\n资料来源：[README.md:56-65]()\n\n### Method 2: Docker Container\n\nPull the pre-built image from Docker Hub:\n\n```bash\ndocker pull mcp-playwright:latest\n```\n\nOr build from source:\n\n```bash\ngit clone https://github.com/executeautomation/mcp-playwright.git\ncd mcp-playwright\ndocker build -t mcp-playwright:latest .\n```\n\nThe Docker image is approximately 200MB (without browsers) and uses a Debian-based slim Node.js image.\n\n资料来源：[DOCKER.md:80-100]()\n\n## Configuration\n\n### Claude Desktop\n\nEdit your Claude Desktop configuration file:\n\n**File Locations:**\n| OS | Path |\n|----|------|\n| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |\n| Windows | `%APPDATA%\\Claude\\claude_desktop_config.json` |\n| Linux | `~/.config/Claude/claude_desktop_config.json` |\n\n**stdio Mode (Default):**\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n    }\n  }\n}\n```\n\n资料来源：[README.md:56-65]()\n\n### VS Code MCP Extension\n\nFor VS Code with the MCP extension, add this to your MCP settings:\n\n```json\n{\n  \"name\": \"playwright\",\n  \"command\": \"npx\",\n  \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n}\n```\n\n资料来源：[DOCKER.md:12-20]()\n\n### Docker Configuration\n\n**Basic Configuration:**\n```json\n{\n  \"mcpServers\": {\n    \"playwright-docker\": {\n      \"command\": \"docker\",\n      \"args\": [\"run\", \"-i\", \"--rm\", \"mcp-playwright:latest\"]\n    }\n  }\n}\n```\n\n**With Environment Variables:**\n```bash\ndocker run -i --rm \\\n  -e PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \\\n  -e NODE_ENV=production \\\n  mcp-playwright:latest\n```\n\n**With Volume Mounts:**\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  -v $(pwd)/screenshots:/app/screenshots \\\n  mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:1-50]()\n\n## Running Modes\n\n### stdio Mode (Interactive)\n\nThe default mode for Claude Desktop where the server communicates via stdin/stdout:\n\n```bash\n# Using npx\nnpx -y @executeautomation/playwright-mcp-server\n\n# Using global installation\nplaywright-mcp-server\n```\n\nIn stdio mode, logs are automatically directed to files only (`~/playwright-mcp-server.log`) to maintain clean JSON-RPC communication.\n\n资料来源：[README.md:56-65]()\n\n### HTTP Mode (Standalone Server)\n\nFor VS Code, custom clients, or remote deployments where you need a headed browser:\n\n```bash\n# Using npx\nnpx @executeautomation/playwright-mcp-server --port 8931\n\n# Using global installation\nplaywright-mcp-server --port 8931\n```\n\n**HTTP Mode Endpoints:**\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/sse` | GET | SSE stream for server-sent events |\n| `/messages` | POST | Send messages (requires `sessionId` query param) |\n| `/mcp` | GET/POST | Unified MCP endpoint |\n| `/health` | GET | Health check |\n\n**Security Note:** The HTTP server binds to `localhost` only (127.0.0.1) to prevent external access. For remote access, use SSH tunneling.\n\n资料来源：[README.md:67-90]()\n资料来源：[src/http-server.ts:1-50]()\n\n**Claude Desktop HTTP Configuration:**\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"url\": \"http://localhost:8931/mcp\"\n    }\n  }\n}\n```\n\n资料来源：[examples/http-mode-example.md:1-30]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    subgraph \"AI Assistant\"\n        A[Claude / Cursor / VS Code]\n    end\n    \n    subgraph \"MCP Client\"\n        B[MCP SDK Client]\n    end\n    \n    subgraph \"Playwright MCP Server\"\n        C[Transport Layer]\n        D[Tool Handlers]\n        E[Browser Manager]\n    end\n    \n    subgraph \"Playwright\"\n        F[Chromium]\n        G[Firefox]\n        H[WebKit]\n    end\n    \n    A --> B\n    B --> C\n    C --> D\n    D --> E\n    E --> F\n    E --> G\n    E --> H\n```\n\n## Available Tools\n\nThe server exposes the following tool categories:\n\n### Navigation Tools\n| Tool | Description |\n|------|-------------|\n| `playwright_navigate` | Navigate to a URL with optional browser type |\n| `playwright_go_back` | Navigate backward in history |\n| `playwright_go_forward` | Navigate forward in history |\n\n### Interaction Tools\n| Tool | Description |\n|------|-------------|\n| `playwright_click` | Click on an element |\n| `playwright_fill` | Fill input fields |\n| `playwright_press_key` | Press keyboard keys |\n| `playwright_drag` | Drag elements |\n\n### Content Tools\n| Tool | Description |\n|------|-------------|\n| `playwright_get_visible_text` | Extract visible text |\n| `playwright_get_visible_html` | Get HTML content with filtering options |\n| `playwright_evaluate` | Execute JavaScript in browser context |\n\n### Output Tools\n| Tool | Description |\n|------|-------------|\n| `playwright_screenshot` | Capture page screenshots |\n| `playwright_save_as_pdf` | Save page as PDF |\n\n### Device Emulation\n```javascript\n// Test on iPhone 13\nawait playwright_resize({ device: \"iPhone 13\" });\n\n// Test on iPad with landscape\nawait playwright_resize({ device: \"iPad Pro 11\", orientation: \"landscape\" });\n\n// Test desktop\nawait playwright_resize({ device: \"Desktop Chrome\" });\n```\n\n资料来源：[README.md:25-50]()\n资料来源：[CHANGELOG.md:1-30]()\n\n## First Steps\n\n### 1. Verify Installation\n\nAfter configuration, restart your AI client and verify the server is connected:\n\n```\nHealth check endpoint (HTTP mode):\ncurl http://localhost:8931/health\n```\n\nExpected response:\n```json\n{\n  \"status\": \"ok\",\n  \"version\": \"1.0.10\",\n  \"activeSessions\": 0\n}\n```\n\n资料来源：[src/http-server.ts:40-48]()\n\n### 2. Basic Browser Operations\n\nOnce connected, you can use natural language to control the browser:\n\n```\n\"Navigate to https://example.com\"\n\"Take a screenshot\"\n\"Click on the login button\"\n\"Fill in the search box with 'test'\"\n\"Get the page title\"\n```\n\n### 3. Device Emulation\n\nTest responsive designs:\n\n```\n\"Test on iPhone 13\"\n\"Switch to iPad Pro view\"\n\"Rotate to landscape\"\n```\n\n资料来源：[README.md:30-45]()\n\n## Troubleshooting\n\n### Container Exits Immediately\n\nMCP servers wait for input on stdin. Ensure you're running with the `-i` flag:\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:55-60]()\n\n### Browser Not Found\n\nThe Docker image skips browser downloads by default. Create a custom Dockerfile:\n\n```dockerfile\nFROM mcp-playwright:latest\nRUN npx playwright install chromium --with-deps\n```\n\n资料来源：[DOCKER.md:65-72]()\n\n### Permission Issues with Volumes\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  --user $(id -u):$(id -g) \\\n  mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:75-82]()\n\n### Connection Issues (HTTP Mode)\n\n| Problem | Solution |\n|---------|----------|\n| Server not starting | Check if port 8931 is available |\n| External access blocked | By design - server binds to localhost only |\n| Remote access needed | Use SSH tunneling: `ssh -L 8931:localhost:8931 user@remote` |\n\n资料来源：[README.md:103-110]()\n\n## Logging\n\nThe server includes comprehensive logging for debugging:\n\n**Log File Location (stdio mode):**\n```\n~/playwright-mcp-server.log\n```\n\n**Logged Information:**\n- Tool execution requests and responses\n- Error categorization (validation, system, resource)\n- Request duration metrics\n- Memory and uptime statistics\n\nThe logger captures:\n- Request IDs for traceability\n- Sanitized request bodies (sensitive fields redacted)\n- Stack traces for errors\n- Platform and environment information\n\n资料来源：[src/logging/logger.ts:1-50]()\n资料来源：[src/logging/middleware.ts:1-80]()\n\n## Testing\n\nRun the test suite to verify your installation:\n\n```bash\n# Run tests\nnpm test\n\n# Run tests with coverage\nnpm run test:coverage\n\n# Run custom tests\nnpm run test:custom\n```\n\nTests are located in `src/__tests__` and use Jest with Playwright preset.\n\n资料来源：[README.md:113-125]()\n\n## Resource Limits (Docker)\n\nLimit CPU and memory usage:\n\n```bash\ndocker run -i --rm \\\n  --cpus=\"2.0\" \\\n  --memory=\"2g\" \\\n  mcp-playwright:latest\n```\n\nOr in docker-compose.yml:\n\n```yaml\nservices:\n  playwright-mcp:\n    deploy:\n      resources:\n        limits:\n          cpus: '2.0'\n          memory: 2G\n```\n\n资料来源：[DOCKER.md:115-130]()\n\n## Next Steps\n\n| Topic | Description |\n|-------|-------------|\n| [Device Emulation](docs/playwright-web/Device-Quick-Reference) | Full list of 143 device presets |\n| [Docker Deployment](DOCKER.md) | Advanced Docker configuration |\n| [HTTP Mode](examples/http-mode-example.md) | Standalone server setup |\n| [API Reference](https://executeautomation.github.io/mcp-playwright/) | Complete tool documentation |\n\n---\n\n<a id='architecture-overview'></a>\n\n## Architecture Overview\n\n### 相关页面\n\n相关主题：[Project Introduction](#project-introduction), [Transport Modes](#transport-modes), [Browser Automation Tools](#browser-automation)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/index.ts)\n- [src/toolHandler.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/toolHandler.ts)\n- [src/tools.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools.ts)\n- [src/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/types.ts)\n- [src/requestHandler.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/requestHandler.ts)\n</details>\n\n# Architecture Overview\n\n## Introduction\n\nThe mcp-playwright project is a Model Context Protocol (MCP) server that exposes Playwright browser automation capabilities to AI assistants such as Claude. The architecture follows a modular, tool-based design pattern where each browser automation operation is exposed as a discrete tool that MCP clients can invoke through JSON-RPC calls.\n\nThe server is designed to operate in two distinct transport modes: **stdio mode** for direct integration with MCP clients like Claude Desktop, and **HTTP mode** for remote deployments, VS Code integration, or headless browser scenarios. This dual-mode architecture provides flexibility while maintaining a consistent internal structure for tool registration, execution, and logging.\n\n资料来源：[README.md:1-20](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n## High-Level Architecture\n\nThe architecture consists of four primary layers that work together to process tool requests and execute browser automation tasks.\n\n```mermaid\ngraph TD\n    A[MCP Client<br/>Claude Desktop / VS Code] --> B[Transport Layer<br/>stdio or HTTP]\n    B --> C[Request Handler<br/>requestHandler.ts]\n    C --> D[Tool Handler<br/>toolHandler.ts]\n    D --> E[Tool Registry<br/>tools.ts]\n    E --> F[Browser Tools<br/>playwright API]\n    F --> G[Chromium / Firefox / WebKit]\n```\n\nThe **Transport Layer** handles the communication protocol, converting between the client's transport mechanism and the internal request format. The **Request Handler** validates and routes incoming requests to the appropriate tool. The **Tool Handler** manages tool execution, error handling, and response formatting. Finally, the **Browser Tools** layer wraps the Playwright API to provide browser automation capabilities.\n\n资料来源：[src/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/index.ts)\n\n## Core Data Structures\n\nThe type system defines the fundamental interfaces used throughout the codebase. These types establish the contract between components and ensure type safety across the architecture.\n\n资料来源：[src/types.ts:1-17](https://github.com/executeautomation/mcp-playwright/blob/main/src/types.ts)\n\n### Tool Interface\n\n```typescript\nexport interface Tool {\n  name: string;\n  description: string;\n  parameters: {\n    type: string;\n    properties: Record<string, unknown>;\n    required?: string[];\n  };\n  handler: (args: any) => Promise<any>;\n}\n```\n\nThe `Tool` interface represents a single automation capability exposed to MCP clients. Each tool contains a unique `name` identifier, a human-readable `description`, a JSON Schema-compatible `parameters` definition, and an asynchronous `handler` function that executes the actual automation logic.\n\n### ToolCall Interface\n\n```typescript\nexport interface ToolCall {\n  name: string;\n  parameters: Record<string, unknown>;\n  result?: CallToolResult;\n}\n```\n\nThe `ToolCall` interface tracks the lifecycle of a tool invocation, capturing the tool name, input parameters, and the computed result.\n\n## Request Processing Pipeline\n\nThe request processing pipeline transforms incoming MCP requests into executed browser automation operations.\n\n```mermaid\ngraph LR\n    A[Incoming Request] --> B[Parse & Validate]\n    B --> C[Route to Tool Handler]\n    C --> D[Execute Tool Handler]\n    D --> E{Check Result}\n    E -->|Success| F[Return CallToolResult]\n    E -->|Error| G[Log Error Context]\n    G --> H[Return Error Response]\n```\n\n### Request Handler Component\n\nThe request handler acts as the entry point for all incoming requests. It is responsible for parsing the incoming JSON-RPC messages, validating the request structure, and delegating to the appropriate tool handler.\n\n资料来源：[src/requestHandler.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/requestHandler.ts)\n\n## Tool Registration and Management\n\nThe tool registry maintains a collection of all available automation tools. New tools are registered through the `BROWSER_TOOLS` array, which contains all browser-related automation operations.\n\n```mermaid\ngraph TD\n    A[Tool Definition<br/>src/tools/browser/*.ts] --> B[BROWSER_TOOLS Array]\n    B --> C[Tool Handler Registration]\n    C --> D[MCP Server<br/>Tool List]\n```\n\n### Tool Handler\n\nThe tool handler manages the execution context for all tools. It provides the following capabilities:\n\n| Capability | Description |\n|------------|-------------|\n| Tool Registration | Registers tools with the MCP SDK |\n| Execution Context | Provides shared state between tool invocations |\n| Error Handling | Catches and formats errors from tool execution |\n| Logging Integration | Integrates with the logging middleware for observability |\n\n资料来源：[src/toolHandler.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/toolHandler.ts)\n\n### Available Tool Categories\n\nThe tools are organized into logical categories based on their function:\n\n| Category | Tools | Purpose |\n|----------|-------|---------|\n| Navigation | `playwright_navigate`, `playwright_go_back`, `playwright_reload` | Page navigation and history |\n| Interaction | `playwright_click`, `playwright_fill`, `playwright_hover`, `playwright_drag` | User interaction simulation |\n| Content Extraction | `playwright_get_visible_text`, `playwright_get_visible_html` | Content retrieval |\n| Output | `playwright_screenshot`, `playwright_save_as_pdf` | Visual output generation |\n| Emulation | `playwright_resize` | Device emulation with 143 presets |\n\n资料来源：[CHANGELOG.md:1-30](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n\n## Logging and Observability\n\nThe logging middleware provides comprehensive observability into tool execution. It captures request context, execution duration, error details, and system metrics.\n\n```mermaid\ngraph TD\n    A[Tool Execution Start] --> B[Generate Request ID]\n    B --> C[Log Request Start]\n    C --> D[Execute Handler]\n    D --> E{Result Type}\n    E -->|Success| F[Log Success<br/>Duration: Xms]\n    E -->|Error| G[Capture Error Context]\n    G --> H[Categorize Error]\n    H --> I[Log Error<br/>with Stack Trace]\n```\n\n### Error Categorization\n\nThe middleware categorizes errors into distinct types for better debugging and monitoring:\n\n| Category | Triggers | Example Messages |\n|----------|----------|-------------------|\n| `validation` | Invalid parameters | \"invalid\", \"required\", \"missing parameter\" |\n| `resource` | Browser/page issues | \"closed\", \"disconnected\", \"protocol error\" |\n| `authentication` | Auth failures | \"unauthorized\", \"forbidden\", \"access denied\" |\n| `rate_limit` | Rate limiting | \"rate limit\", \"too many requests\" |\n| `system` | Timeout/element errors | \"timeout\", \"element not found\", \"navigation\" |\n\n资料来源：[src/logging/middleware.ts:80-120](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n### Request Sanitization\n\nThe logging middleware automatically sanitizes sensitive data from tool arguments before logging:\n\n| Field Pattern | Sanitization |\n|---------------|--------------|\n| `password`, `token`, `secret`, `key`, `auth` | Replaced with `[REDACTED]` |\n| Request bodies > 1000 characters | Truncated with character count |\n\n资料来源：[src/logging/middleware.ts:150-170](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n## Transport Modes\n\n### stdio Mode\n\nIn stdio mode, the server communicates over standard input and output streams. This mode is designed for direct integration with MCP clients like Claude Desktop.\n\n| Aspect | Configuration |\n|--------|---------------|\n| Launch Command | `npx -y @executeautomation/playwright-mcp-server` |\n| Log Output | File only (`~/playwright-mcp-server.log`) |\n| JSON-RPC | stdin/stdout streaming |\n\n资料来源：[README.md:30-45](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n### HTTP Mode\n\nHTTP mode exposes the server as a standalone HTTP server with multiple endpoints:\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/sse` | GET | Server-Sent Events stream |\n| `/messages` | POST | Send messages with session ID |\n| `/mcp` | GET/POST | Unified MCP protocol endpoint |\n| `/health` | GET | Health check |\n\nThe default port is `8931`, configurable via the `--port` flag.\n\n资料来源：[README.md:55-70](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n```mermaid\ngraph LR\n    A[MCP Client] -->|HTTP POST /mcp| B[HTTP Server]\n    B --> C[Request Handler]\n    C --> D[Tool Handler]\n    D --> E[Browser Automation]\n    E --> F[Response]\n    F --> B\n    B --> A\n```\n\n## Browser Context Management\n\nThe architecture supports multiple browser engines:\n\n| Browser | Package | Default |\n|---------|---------|---------|\n| Chromium | `@playwright/browser-chromium` | Yes |\n| Firefox | `@playwright/browser-firefox` | No |\n| WebKit | `@playwright/browser-webkit` | No |\n\nThe `browserType` parameter in `playwright_navigate` allows selection of the browser engine:\n\n```javascript\nawait playwright_navigate({ \n  url: \"https://example.com\",\n  browserType: \"firefox\"  // chromium, firefox, or webkit\n});\n```\n\n资料来源：[CHANGELOG.md:15-20](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n\n## Deployment Architecture\n\n### Docker Deployment\n\nThe Docker deployment provides a containerized environment for the MCP server:\n\n```mermaid\ngraph TD\n    A[Docker Host] --> B[mcp-playwright:latest]\n    B --> C[Node.js Runtime]\n    C --> D[MCP Server]\n    D --> E[Playwright Browsers]\n    E --> F[Chromium<br/>Firefox<br/>WebKit]\n```\n\nThe Docker image is optimized for size (~200MB without browsers) and supports environment variable configuration:\n\n| Variable | Purpose | Default |\n|----------|---------|---------|\n| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser installation | 1 |\n| `NODE_ENV` | Node environment | production |\n\n资料来源：[DOCKER.md:40-60](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Claude Desktop Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n    }\n  }\n}\n```\n\nFor HTTP mode with remote deployments:\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"url\": \"http://localhost:8931/mcp\"\n    }\n  }\n}\n```\n\n资料来源：[README.md:35-40](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n---\n\n<a id='transport-modes'></a>\n\n## Transport Modes\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Configuration Guide](#configuration)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/index.ts)\n- [src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)\n- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)\n- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n- [src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)\n</details>\n\n# Transport Modes\n\nThe mcp-playwright server supports two distinct transport modes for communicating with MCP clients: **STDIO Transport** and **HTTP/SSE Transport**. Each mode serves different deployment scenarios and client requirements.\n\n## Overview\n\nThe transport mode determines how the MCP protocol messages are exchanged between the Playwright MCP server and connected clients. The server automatically detects the appropriate mode based on command-line arguments or environment configuration.\n\n| Transport Mode | Use Case | Default Port | Security |\n|----------------|----------|--------------|----------|\n| STDIO | Local MCP clients (Claude Desktop, Cursor) | N/A | Process-bound |\n| HTTP/SSE | Remote clients, headed browsers, IDE integrations | 8931 | Localhost only |\n\n## STDIO Transport Mode\n\n### Purpose and Architecture\n\nSTDIO (Standard Input/Output) is the default transport mode for MCP servers. It provides process-based communication where messages are exchanged through the parent process's standard input and output streams.\n\n```mermaid\ngraph LR\n    A[MCP Client<br/>Claude Desktop] <-->|stdin/stdout pipes| B[playwright-mcp-server<br/>STDIO Mode]\n    B <-->|Playwright API| C[Browser Instance]\n```\n\n### How STDIO Mode Works\n\n1. The MCP client spawns the server as a child process\n2. JSON-RPC messages are sent via process stdin\n3. Responses are received via process stdout\n4. The server runs in headless mode by default\n5. Logging is automatically redirected to `~/playwright-mcp-server.log`\n\n资料来源：[README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n### Configuration for Claude Desktop\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n    }\n  }\n}\n```\n\n资料来源：[README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n### Docker Considerations\n\nWhen running in Docker containers, STDIO mode requires the `-i` flag to keep STDIN open for interactive communication:\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n| Docker Flag | Purpose |\n|-------------|---------|\n| `-i` | Keep STDIN open for interactive communication |\n| `--rm` | Automatically remove container when it exits |\n\n资料来源：[DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## HTTP/SSE Transport Mode\n\n### Purpose and Architecture\n\nHTTP/SSE transport runs the MCP server as a standalone HTTP server. This mode is designed for scenarios where STDIO communication is impractical, such as:\n\n- Running headed browsers on headless systems\n- Integration with IDE worker processes\n- Remote client access via HTTP\n- Multi-client concurrent connections\n\n```mermaid\ngraph TD\n    A[MCP Client<br/>VS Code / Custom] -->|HTTP/REST| B[HTTP Server<br/>127.0.0.1:8931]\n    B --> C[SSE Transport<br/>Server-Sent Events]\n    B --> D[Message Handler<br/>POST /messages]\n    C --> E[Session Manager]\n    D --> E\n    E --> F[Playwright MCP<br/>Tool Handler]\n    F --> G[Browser Instance]\n```\n\n### Available Endpoints\n\nThe HTTP server exposes the following endpoints:\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/sse` | GET | Server-Sent Events stream for push notifications |\n| `/messages?sessionId=<id>` | POST | Send JSON-RPC messages for a specific session |\n| `/mcp` | GET | MCP unified endpoint (GET) |\n| `/mcp?sessionId=<id>` | POST | MCP unified endpoint (POST) |\n| `/health` | GET | Health check endpoint |\n\n资料来源：[src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)\n\n### Starting the HTTP Server\n\n```bash\n# Using npx\nnpx @executeautomation/playwright-mcp-server --port 8931\n\n# Or after global installation\nnpm install -g @executeautomation/playwright-mcp-server\nplaywright-mcp-server --port 8931\n```\n\n资料来源：[examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)\n\n### HTTP Server Output\n\nWhen started successfully, the server displays:\n\n```\n==============================================\nPlaywright MCP Server (HTTP Mode)\n==============================================\nListening: 127.0.0.1:8931 (localhost only)\nVersion: <version>\n\nSECURITY: Server is bound to localhost only.\n          Not accessible from external networks.\n\nENDPOINTS:\n- SSE Stream:     GET  http://localhost:8931/sse\n- Messages:       POST http://localhost:8931/messages?sessionId=<id>\n- MCP (unified):  GET  http://localhost:8931/mcp\n- MCP (unified):  POST http://localhost:8931/mcp?sessionId=<id>\n- Health Check:   GET  http://localhost:8931/health\n```\n\n资料来源：[src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)\n\n### Client Configuration\n\n#### Claude Desktop (HTTP)\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"url\": \"http://localhost:8931/mcp\"\n    }\n  }\n}\n```\n\n#### VS Code MCP Extension\n\n```json\n{\n  \"name\": \"playwright\",\n  \"url\": \"http://localhost:8931/mcp\"\n}\n```\n\n#### Health Check\n\n```bash\ncurl http://localhost:8931/health\n```\n\n资料来源：[examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)\n\n### Security Model\n\nThe HTTP server binds exclusively to `127.0.0.1` (localhost) for security reasons:\n\n> **SECURITY**: Server binds to localhost only. Not accessible from external networks.\n\nFor remote access, SSH tunneling is recommended:\n\n```bash\nssh -L 8931:localhost:8931 user@remote-server\n```\n\n资料来源：[src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)\n\n## Mode Selection\n\n### Automatic Selection\n\nThe server automatically selects the transport mode based on:\n\n1. **Presence of `--port` argument** → HTTP/SSE mode\n2. **Absence of `--port` argument** → STDIO mode\n\n### Health Check Response\n\n| Field | Description |\n|-------|-------------|\n| `status` | Health status (`ok` when healthy) |\n| `version` | Server version |\n| `activeSessions` | Number of active MCP sessions |\n\nExample response:\n```json\n{\n  \"status\": \"ok\",\n  \"version\": \"1.0.10\",\n  \"activeSessions\": 2\n}\n```\n\n## Transport Comparison\n\n| Aspect | STDIO | HTTP/SSE |\n|--------|-------|----------|\n| Communication | stdin/stdout pipes | HTTP/REST |\n| Multi-client | No | Yes |\n| Session support | No | Yes (via sessionId) |\n| Browser mode | Headless | Headless or Headed |\n| Claude Desktop | ✅ Supported | ❌ Not supported |\n| VS Code | ✅ Supported | ✅ Supported |\n| Health endpoint | No | Yes |\n| Process lifecycle | Tied to client | Independent |\n\n资料来源：[README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n## Logging Behavior\n\n### STDIO Mode\n\n- Logging automatically directed to files only\n- Console output kept clean for JSON-RPC communication\n- Logs written to `~/playwright-mcp-server.log`\n\n### HTTP Mode\n\n- Standard logging to console and file\n- Request/response logging via middleware\n- Error context capture including:\n  - Stack traces\n  - Memory usage\n  - Platform information\n  - Request duration\n\n资料来源：[src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n## Environment Variables\n\n| Variable | Purpose | Applicable Modes |\n|----------|---------|------------------|\n| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser binary download | Both |\n| `NODE_ENV` | Set runtime environment | Both |\n| `PORT` | HTTP server port (alternative to CLI) | HTTP |\n\n资料来源：[DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n---\n\n<a id='browser-automation'></a>\n\n## Browser Automation Tools\n\n### 相关页面\n\n相关主题：[Device Emulation](#device-emulation), [API Testing Tools](#api-testing), [Code Generation and Recording](#code-generation)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/tools/browser/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/index.ts)\n- [src/tools/browser/navigation.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/navigation.ts)\n- [src/tools/browser/interaction.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/interaction.ts)\n- [src/tools/browser/screenshot.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/screenshot.ts)\n- [src/tools/browser/console.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/console.ts)\n- [src/tools/browser/output.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/output.ts)\n- [src/tools/browser/resize.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n- [src/tools/browser/useragent.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/useragent.ts)\n- [src/tools/browser/response.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/response.ts)\n- [src/tools/browser/visiblePage.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/visiblePage.ts)\n- [src/tools/browser/base.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/base.ts)\n</details>\n\n# Browser Automation Tools\n\n## Overview\n\nThe Browser Automation Tools constitute the core module of the mcp-playwright project, providing a comprehensive set of MCP (Model Context Protocol) tools for browser-based web automation and testing. These tools enable AI assistants and automated systems to interact with web pages programmatically, performing actions such as navigation, element interaction, content extraction, and response monitoring.\n\nThe module supports multiple browser engines (Chromium, Firefox, WebKit) and provides both headless and headed execution modes, making it suitable for a wide range of automation scenarios from simple web scraping to complex end-to-end testing.\n\n**Architecture Overview:**\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|JSON-RPC| B[Tool Handler]\n    B --> C[Browser Tool Executor]\n    C --> D[Browser Engine]\n    D --> E[Chromium<br/>Firefox<br/>WebKit]\n    \n    F[Base Class] -->|Inheritance| C\n    F --> G[Error Handling]\n    F --> H[Page Validation]\n    F --> I[Safe Execution]\n```\n\n## Core Components\n\n### Tool Architecture\n\nThe browser automation tools follow an object-oriented architecture with a base class pattern. All browser tools inherit from `BrowserToolBase`, which provides common functionality including error handling, page validation, and safe execution wrappers.\n\n**Class Hierarchy:**\n\n```mermaid\ngraph TD\n    A[BrowserToolBase] --> B[navigation.ts<br/>NavigateTool]\n    A --> C[interaction.ts<br/>ClickTool, FillTool, etc.]\n    A --> D[screenshot.ts<br/>ScreenshotTool]\n    A --> E[console.ts<br/>ConsoleLogsTool]\n    A --> F[output.ts<br/>PdfTool]\n    A --> G[resize.ts<br/>ResizeTool]\n    A --> H[useragent.ts<br/>CustomUserAgentTool]\n    A --> I[response.ts<br/>ExpectResponseTool, AssertResponseTool]\n    A --> J[visiblePage.ts<br/>VisibleTextTool, VisibleHtmlTool]\n    \n    K[ToolContext] --> A\n    L[Browser, Page] --> A\n```\n\n### Base Class (BrowserToolBase)\n\nThe `BrowserToolBase` class provides the foundation for all browser tools:\n\n| Method | Purpose |\n|--------|---------|\n| `ensurePage(context)` | Returns the current page or null if unavailable |\n| `validatePageAvailable(context)` | Returns error response if page not initialized |\n| `safeExecute(context, operation)` | Wraps browser operations with error handling |\n\n**File Reference:** `src/tools/browser/base.ts`\n\n## Browser Tools Registry\n\nAll browser-requiring tools are registered in the `BROWSER_TOOLS` array and exposed through the MCP tool interface:\n\n**File Reference:** `src/tools/browser/index.ts`, `src/tools.ts`\n\n```typescript\nexport const BROWSER_TOOLS = [\n  \"playwright_navigate\",\n  \"playwright_screenshot\",\n  \"playwright_click\",\n  \"playwright_iframe_click\",\n  \"playwright_iframe_fill\",\n  \"playwright_fill\",\n  \"playwright_select\",\n  \"playwright_hover\",\n  \"playwright_evaluate\",\n  \"playwright_console_logs\",\n  \"playwright_close\",\n  \"playwright_get_visible_text\",\n  \"playwright_get_visible_html\",\n  \"playwright_click_and_switch_tab\",\n  \"playwright_drag\",\n  \"playwright_press_key\",\n  \"playwright_save_as_pdf\"\n];\n```\n\n## Navigation Tools\n\n### Navigate Tool (`playwright_navigate`)\n\nThe primary navigation tool for loading web pages in the browser.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | string | Yes | Target URL to navigate to |\n| `browserType` | string | No | Browser engine: \"chromium\", \"firefox\", \"webkit\" (default: \"chromium\") |\n| `width` | number | No | Viewport width in pixels (default: 1280) |\n| `height` | number | No | Viewport height in pixels (default: 720) |\n| `timeout` | number | No | Navigation timeout in milliseconds |\n| `waitUntil` | string | No | Navigation wait condition |\n| `headless` | boolean | No | Run browser in headless mode (default: false) |\n\n**Multi-Browser Support:**\n\nStarting from version 1.0.2, the navigate tool supports specifying the browser type:\n\n> Multi-Browser Support: Firefox and WebKit in addition to Chromium\n> New `browserType` parameter for `playwright_navigate` tool\n> Supported browser types: \"chromium\" (default), \"firefox\", \"webkit\"\n> 资料来源：[CHANGELOG.md]()\n\n**File Reference:** `src/tools/browser/navigation.ts`\n\n## Interaction Tools\n\nInteraction tools enable programmatic control over browser elements, including clicking, filling forms, hovering, and keyboard input.\n\n### Click Tool (`playwright_click`)\n\nClicks an element identified by a CSS selector.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | Yes | CSS selector for the element to click |\n| `button` | string | No | Mouse button: \"left\", \"right\", \"middle\" (default: \"left\") |\n| `clickCount` | number | No | Number of clicks (default: 1) |\n| `delay` | number | No | Delay in milliseconds between key down and up |\n| `force` | boolean | No | Force click even if element obscured |\n| `timeout` | number | No | Timeout in milliseconds |\n| `noWaitAfter` | boolean | No | Don't wait for navigation after click |\n\n### Fill Tool (`playwright_fill`)\n\nFills input fields with text content.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | Yes | CSS selector for the input element |\n| `value` | string | Yes | Text value to fill |\n| `delay` | number | No | Delay between keystrokes in milliseconds |\n| `noWaitAfter` | boolean | No | Don't wait for navigation after fill |\n\n### Select Tool (`playwright_select`)\n\nSelects options in dropdown menus (select elements).\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | Yes | CSS selector for the select element |\n| `value` | string/array | Yes | Option value(s) to select |\n| `index` | array | No | Option index(es) to select |\n| `label` | string/array | No | Option label(s) to select |\n| `timeout` | number | No | Timeout in milliseconds |\n\n### Hover Tool (`playwright_hover`)\n\nHovers over an element.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | Yes | CSS selector for the element to hover |\n| `timeout` | number | No | Timeout in milliseconds |\n\n### Keyboard Interaction\n\n**Drag Tool (`playwright_drag`):**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `sourceSelector` | string | Yes | CSS selector for source element |\n| `targetSelector` | string | Yes | CSS selector for target element |\n\n**Press Key Tool (`playwright_press_key`):**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | No | CSS selector for element to focus |\n| `key` | string | Yes | Key to press (e.g., \"Enter\", \"Tab\", \"Escape\") |\n\n### iFrame Interaction\n\nThe project supports interaction with elements inside iframes through dedicated tools:\n\n| Tool | Description |\n|------|-------------|\n| `playwright_iframe_click` | Click element within an iframe |\n| `playwright_iframe_fill` | Fill input within an iframe |\n\n**File Reference:** `src/tools/browser/interaction.ts`\n\n## Screenshot Tools\n\n### Screenshot Tool (`playwright_screenshot`)\n\nCaptures screenshots of the current page or specific elements.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `name` | string | No | Name for the screenshot |\n| `selector` | string | No | CSS selector for element to screenshot |\n| `width` | number | No | Width in pixels (default: 800) |\n| `height` | number | No | Height in pixels (default: 600) |\n| `storeBase64` | boolean | No | Store in base64 format (default: true) |\n| `fullPage` | boolean | No | Screenshot entire page (default: false) |\n| `savePng` | boolean | No | Save as PNG file (default: false) |\n| `downloadsDir` | string | No | Custom downloads directory path |\n\n**File Reference:** `src/tools/browser/screenshot.ts`\n\n## Content Extraction Tools\n\n### Visible Text Tool (`playwright_get_visible_text`)\n\nExtracts visible text content from the page or specific elements.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | No | CSS selector to extract text from specific element |\n| `includeHidden` | boolean | No | Include hidden elements (default: false) |\n| `removeLineBreaks` | boolean | No | Remove line breaks (default: false) |\n| `trimText` | boolean | No | Trim whitespace (default: true) |\n\n### Visible HTML Tool (`playwright_get_visible_html`)\n\nRetrieves HTML content from the page or elements.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | No | CSS selector for specific element |\n| `removeScripts` | boolean | No | Remove script tags |\n| `removeComments` | boolean | No | Remove HTML comments |\n| `removeStyles` | boolean | No | Remove style tags |\n| `removeMeta` | boolean | No | Remove meta tags |\n| `cleanHtml` | boolean | No | Apply all cleanup filters |\n| `minify` | boolean | No | Minify the HTML output |\n\n**Content Filtering Pipeline:**\n\n```mermaid\ngraph LR\n    A[Raw HTML] --> B{removeScripts?}\n    B -->|Yes| C[Remove script tags]\n    B -->|No| D[Continue]\n    C --> E{removeStyles?}\n    E -->|Yes| F[Remove style tags]\n    E -->|No| G[Continue]\n    F --> H{removeMeta?}\n    H -->|Yes| I[Remove meta tags]\n    H -->|No| J[Continue]\n    I --> K{removeComments?}\n    K -->|Yes| L[Remove comments]\n    K -->|No| M[Continue]\n    L --> N{minify?}\n    M --> N\n    N -->|Yes| O[Minify HTML]\n    N -->|No| P[Return Clean HTML]\n```\n\n**File Reference:** `src/tools/browser/visiblePage.ts`\n\n## Output Tools\n\n### PDF Generation Tool (`playwright_save_as_pdf`)\n\nSaves the current page as a PDF document.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `outputPath` | string | Yes | Path where PDF will be saved |\n| `name` | string | No | PDF filename (default: \"page.pdf\") |\n| `format` | string | No | Page format: \"A4\", \"Letter\", etc. |\n| `printBackground` | boolean | No | Include background graphics |\n| `margin` | object | No | Page margins (top, right, bottom, left) |\n\n**File Reference:** `src/tools/browser/output.ts`\n\n## Console Tools\n\n### Console Logs Tool (`playwright_console_logs`)\n\nRetrieves console messages from the browser page.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `type` | string | No | Filter by message type: \"log\", \"info\", \"warn\", \"error\" |\n| `text` | string | No | Filter by text content (partial match) |\n| `regex` | string | No | Filter by regex pattern |\n\n**Console Message Types:**\n\n| Type | Description |\n|------|-------------|\n| `log` | General console logs |\n| `info` | Informational messages |\n| `warn` | Warning messages |\n| `error` | Error messages |\n\n**File Reference:** `src/tools/browser/console.ts`\n\n## Response Monitoring Tools\n\n### Expect Response Tool (`playwright_expect_response`)\n\nSets up expectations for network responses.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | string | No | URL pattern to match (regex or string) |\n| `statusCode` | number | No | Expected HTTP status code |\n| `timeout` | number | No | Timeout in milliseconds |\n| `method` | string | No | HTTP method filter |\n\n### Assert Response Tool (`playwright_assert_response`)\n\nAsserts that a network response meets specified criteria.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | string | No | URL pattern to match |\n| `statusCode` | number | No | Expected HTTP status code |\n| `method` | string | No | HTTP method filter |\n\n**File Reference:** `src/tools/browser/response.ts`\n\n## Viewport and Device Emulation\n\n### Resize Tool (`playwright_resize`)\n\nConfigures viewport dimensions and enables device emulation.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `device` | string | No | Device name for emulation (e.g., \"iPhone 13\", \"iPad Pro 11\") |\n| `width` | number | No | Viewport width in pixels |\n| `height` | number | No | Viewport height in pixels |\n| `orientation` | string | No | Device orientation: \"portrait\", \"landscape\" |\n| `scale` | number | No | Device scale factor |\n| `mobile` | boolean | No | Enable mobile emulation |\n\n**Device Emulation Features:**\n\n- 143 real device presets including iPhone, iPad, Pixel, Galaxy, and Desktop browsers\n- Automatic user-agent string configuration\n- Touch event support emulation\n- Device pixel ratio configuration\n\n**Natural Language Support:**\n\nAI assistants can use natural language prompts such as:\n- \"Test on iPhone 13\"\n- \"Switch to iPad view\"\n- \"Rotate to landscape\"\n\n**File Reference:** `src/tools/browser/resize.ts`\n\n## User Agent Tools\n\n### Custom User Agent Tool (`playwright_custom_user_agent`)\n\nSets a custom user agent string for the browser context.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `userAgent` | string | Yes | Custom user agent string |\n\n**File Reference:** `src/tools/browser/useragent.ts`\n\n## Browser Lifecycle Management\n\n### Close Tool (`playwright_close`)\n\nCloses the current browser context and page.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `closeBrowser` | boolean | No | Close the entire browser (default: false) |\n\n## Error Handling\n\nThe browser tools implement comprehensive error handling through the middleware system:\n\n**Error Categories:**\n\n| Category | Indicators |\n|----------|------------|\n| `validation` | Invalid parameters, missing required fields |\n| `resource` | Browser closed, page disconnected, protocol errors |\n| `authentication` | Unauthorized, forbidden, access denied |\n| `rate_limit` | Too many requests, throttling |\n| `system` | Timeout, element not found, navigation failures |\n\n**Enhanced Error Context:**\n\nThe logging middleware captures detailed error context including:\n- Error name and message\n- Stack trace\n- Timestamp\n- Node.js version and platform\n- Memory usage statistics\n- Browser state information\n\n**File Reference:** `src/logging/middleware.ts`\n\n## Tool Execution Flow\n\n**Complete Tool Execution Pipeline:**\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCP_Server\n    participant Middleware\n    participant Tool\n    participant Browser\n    \n    Client->>MCP_Server: Tool Request\n    MCP_Server->>Middleware: Intercept Request\n    Middleware->>Middleware: Log Start\n    Middleware->>Tool: Execute Tool\n    Tool->>Browser: Browser Operation\n    Browser-->>Tool: Operation Result\n    Tool-->>Middleware: Tool Response\n    Middleware->>Middleware: Log Completion\n    Middleware-->>Client: Response\n```\n\n## Summary\n\nThe Browser Automation Tools module provides a comprehensive, MCP-compatible interface for browser automation tasks. Key features include:\n\n| Feature Category | Capabilities |\n|------------------|--------------|\n| **Navigation** | Multi-browser support (Chromium, Firefox, WebKit), configurable viewport |\n| **Interaction** | Click, fill, select, hover, drag, keyboard input, iframe support |\n| **Content Extraction** | Visible text, HTML with filtering/minification |\n| **Output** | Screenshots, PDF generation |\n| **Monitoring** | Console logs, network response expectations |\n| **Emulation** | 143 device presets, custom user agents |\n\nAll tools follow a consistent pattern with base class inheritance, comprehensive error handling, and structured logging for debugging and monitoring purposes.\n\n---\n\n<a id='device-emulation'></a>\n\n## Device Emulation\n\n### 相关页面\n\n相关主题：[Browser Automation Tools](#browser-automation)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/tools/browser/resize.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n- [src/tools.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools.ts)\n- [src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n- [src/tools/browser/visiblePage.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/visiblePage.ts)\n- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)\n</details>\n\n# Device Emulation\n\nDevice Emulation is a core feature of the Playwright MCP Server that enables AI assistants and automated testing tools to simulate real-world mobile and desktop devices directly within the browser automation framework. By leveraging Playwright's built-in device descriptor library, the server provides **143 real device presets** with accurate viewport dimensions, user-agent strings, touch capabilities, and device pixel ratios.\n\n## Overview\n\nThe Device Emulation system integrates with the `playwright_resize` tool to provide a seamless interface for switching between device profiles. When a device preset is selected, the system automatically configures multiple browser properties simultaneously:\n\n- **Viewport dimensions** for accurate screen rendering\n- **User-Agent strings** for proper server-side device detection\n- **Touch capabilities** for mobile device simulation\n- **Device pixel ratio** for high-DPI display accuracy\n\n资料来源：[README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[AI Assistant / MCP Client] --> B[playwright_resize Tool]\n    B --> C{Device Preset?}\n    C -->|Yes| D[Lookup in Playwright devices]\n    C -->|No| E[Direct Dimensions]\n    D --> F[Extract Device Properties]\n    F --> G[page.setViewportSize]\n    F --> H[page.setExtraHTTPHeaders]\n    G --> I[Browser Context Updated]\n    H --> I\n    E --> G\n```\n\n### Component Flow\n\n1. **Client Request**: The AI assistant or MCP client sends a `playwright_resize` call with a `device` parameter\n2. **Device Lookup**: The system searches Playwright's device descriptor library using the provided name\n3. **Property Extraction**: Device properties including viewport, user-agent, mobile flag, touch support, and scale factor are extracted\n4. **Browser Configuration**: Playwright APIs apply the settings to the active page context\n\n资料来源：[src/tools/browser/resize.ts:17-48](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n\n## API Reference\n\n### Tool: `playwright_resize`\n\nThe primary tool for device emulation and viewport control.\n\n#### Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `device` | `string` | No | Device preset name (e.g., \"iPhone 13\", \"iPad Pro 11\") |\n| `width` | `number` | Conditional | Viewport width in pixels (default: 1280) |\n| `height` | `number` | Conditional | Viewport height in pixels (default: 720) |\n| `orientation` | `string` | No | \"portrait\" or \"landscape\" (only valid with device preset) |\n| `maxLength` | `number` | No | Maximum response length for HTML content (default: 20000) |\n\n#### Device Preset Detection\n\nThe system validates device names against Playwright's device library and returns helpful suggestions if the device is not found:\n\n```typescript\nif (!device) {\n  return createErrorResponse(\n    `Device \"${args.device}\" not found. Popular devices: ${popularDevices.join(', ')}. ` +\n    `Use playwright.devices to see all ${Object.keys(devices).length} available devices.`\n  );\n}\n```\n\n资料来源：[src/tools/browser/resize.ts:36-43](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n\n## Supported Devices\n\nThe Playwright MCP Server includes support for **143 device presets** covering major device categories:\n\n### Popular Devices\n\n| Category | Devices |\n|----------|---------|\n| **iPhone** | iPhone 13, iPhone 13 Pro, iPhone 14, iPhone 15, iPhone 15 Pro Max |\n| **iPad** | iPad Pro 11, iPad Pro 12.9, iPad Air, iPad Mini |\n| **Pixel** | Pixel 5, Pixel 7, Pixel 8, Pixel 8 Pro |\n| **Galaxy** | Galaxy S9+, Galaxy S10+, Galaxy S24, Galaxy S24 Ultra |\n| **Desktop** | Desktop Chrome, Desktop Firefox, Desktop Safari |\n\n### Device Properties Extracted\n\nWhen using a device preset, the following properties are automatically configured:\n\n```typescript\n// Extract device properties from Playwright's device library\nwidth = device.defaultBrowserViewport.width;\nheight = device.defaultBrowserViewport.height;\nuserAgent = device.defaultUserAgent;\nisMobile = device.defaultBrowserType === 'mobile';\nhasTouch = device.hasTouch;\ndeviceScaleFactor = device.deviceScaleFactor || 1;\n```\n\n资料来源：[src/tools/browser/resize.ts:48-54](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n\n## Orientation Support\n\nDevice emulation supports both portrait and landscape orientations. When an orientation is specified with a device preset, the width and height values are swapped:\n\n```javascript\n// Portrait orientation (default)\nawait playwright_resize({ device: \"iPhone 13\", orientation: \"portrait\" });\n\n// Landscape orientation\nawait playwright_resize({ device: \"iPad Pro 11\", orientation: \"landscape\" });\n```\n\n### Orientation Logic\n\n```mermaid\ngraph LR\n    A[Device Preset] --> B{orientation === \"landscape\"}\n    B -->|Yes| C[Swap width ↔ height]\n    B -->|No| D[Keep original dimensions]\n    C --> E[Apply to Viewport]\n    D --> E\n```\n\nThe orientation parameter is validated to ensure it is only used with device presets:\n\n```typescript\nif (args.orientation && !args.device) {\n  throw new Error(\"Orientation can only be set when using a device preset\");\n}\n```\n\n资料来源：[src/tools/browser/resize.ts:71-74](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n\n## Validation Rules\n\nThe device emulation system enforces several validation constraints:\n\n### Dimension Constraints\n\n| Rule | Value | Error Message |\n|------|-------|---------------|\n| Minimum dimension | > 0 | \"Width and height must be positive integers\" |\n| Maximum dimension | ≤ 7680 × 4320 | \"Width and height must not exceed 7680x4320 (8K resolution)\" |\n\n### Parameter Constraints\n\n| Constraint | Condition |\n|------------|------------|\n| Orientation requires device | `orientation` parameter cannot be used standalone |\n| Device validation | Name must exist in Playwright's device library |\n\n资料来源：[src/tools/browser/resize.ts:81-91](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n\n## Natural Language Support\n\nThe device emulation system is designed to work seamlessly with AI assistants that use natural language commands. Common prompt patterns include:\n\n- \"Test on iPhone 13\"\n- \"Switch to iPad view\"\n- \"Rotate to landscape\"\n- \"Test desktop view\"\n\nThese natural language commands are interpreted by the AI assistant and translated into `playwright_resize` tool calls with the appropriate device and orientation parameters.\n\n资料来源：[README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n## Implementation Details\n\n### Base Class Integration\n\nThe `ResizeTool` extends `BrowserToolBase`, which provides the foundation for browser interaction:\n\n```typescript\nexport class ResizeTool extends BrowserToolBase {\n  async execute(args: any, context: ToolContext): Promise<ToolResponse> {\n    return this.safeExecute(context, async (page) => {\n      // Device emulation logic\n    });\n  }\n}\n```\n\n### Error Handling\n\nThe implementation uses a safe execution pattern with comprehensive error handling:\n\n```typescript\nprivate categorizeError(error: Error): 'validation' | 'system' | 'unknown' {\n  const message = error.message.toLowerCase();\n  \n  if (message.includes('invalid') || message.includes('validation') || message.includes('required')) {\n    return 'validation';\n  }\n  \n  if (message.includes('browser') || message.includes('page') || message.includes('connection')) {\n    return 'system';\n  }\n  \n  return 'unknown';\n}\n```\n\n资料来源：[src/tools/browser/resize.ts:7-11](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n资料来源：[src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n## Response Format\n\n### Success Response\n\nWhen device emulation is successfully applied, the response includes:\n\n```\nBrowser viewport resized to iPhone 13 (390x844) [mobile, touch, 3x scale]\n```\n\nThe response includes:\n- Device name and dimensions\n- Orientation (if specified)\n- Applied features: mobile, touch, device scale factor\n\n### Error Response\n\nIf device emulation fails, an error response is returned with:\n- Specific error message explaining the failure\n- Suggestions for popular devices when device name is not found\n- Reference to available device count\n\n资料来源：[src/tools/browser/resize.ts:95-120](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n\n## Tool Registration\n\nThe `playwright_resize` tool is registered in the central tools registry:\n\n```typescript\n{\n  name: \"playwright_resize\",\n  description: \"Resize browser viewport with optional device emulation\",\n  inputSchema: {\n    type: \"object\",\n    properties: {\n      device: { type: \"string\", description: \"Device preset name\" },\n      width: { type: \"number\", description: \"Viewport width in pixels\" },\n      height: { type: \"number\", description: \"Viewport height in pixels\" },\n      orientation: { type: \"string\", description: \"Device orientation\" }\n    }\n  }\n}\n```\n\n资料来源：[src/tools.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools.ts)\n\n## Dependencies\n\nThe device emulation feature relies on the following package dependencies:\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `playwright` | 1.57.0 | Core browser automation with device descriptors |\n| `@playwright/browser-chromium` | 1.57.0 | Chromium browser support |\n| `@playwright/browser-firefox` | 1.57.0 | Firefox browser support |\n| `@playwright/browser-webkit` | 1.57.0 | WebKit browser support |\n\n资料来源：[package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)\n\n## Usage Examples\n\n### Basic Device Emulation\n\n```javascript\n// Test on iPhone 13\nawait playwright_resize({ device: \"iPhone 13\" });\n\n// Result: Browser viewport resized to iPhone 13 (390x844) [mobile, touch, 2x scale]\n```\n\n### Landscape Orientation\n\n```javascript\n// iPad in landscape mode\nawait playwright_resize({ device: \"iPad Pro 11\", orientation: \"landscape\" });\n\n// Result: Browser viewport resized to iPad Pro 11 (1194x834) in landscape orientation [mobile, touch, 2x scale]\n```\n\n### Desktop Browser\n\n```javascript\n// Switch to desktop Chrome view\nawait playwright_resize({ device: \"Desktop Chrome\" });\n\n// Result: Browser viewport resized to Desktop Chrome (1280x720)\n```\n\n### Custom Dimensions\n\n```javascript\n// Direct viewport control without device preset\nawait playwright_resize({ width: 1920, height: 1080 });\n\n// Result: Browser viewport resized to 1920x1080\n```\n\n## Integration with Other Tools\n\nDevice emulation settings persist across multiple tool calls within a session. Other tools that may interact with device emulation include:\n\n| Tool | Interaction |\n|------|-------------|\n| `playwright_screenshot` | Captures screenshots at device resolution |\n| `playwright_get_visible_html` | Extracts HTML content rendered at device viewport |\n| `playwright_navigate` | Can be combined with device presets for full mobile testing |\n\nThe viewport and user-agent settings remain active until explicitly changed by another `playwright_resize` call.\n\n资料来源：[src/tools/browser/visiblePage.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/visiblePage.ts)\n资料来源：[src/tools/browser/screenshot.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/screenshot.ts)\n\n---\n\n<a id='api-testing'></a>\n\n## API Testing Tools\n\n### 相关页面\n\n相关主题：[Browser Automation Tools](#browser-automation), [Code Generation and Recording](#code-generation)\n\n<details>\n<summary>Relevant Source Files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/tools/api/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/index.ts)\n- [src/tools/api/base.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/base.ts)\n- [src/tools/api/requests.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/requests.ts)\n- [src/tools/common/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/common/types.ts)\n- [src/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/types.ts)\n- [src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n</details>\n\n# API Testing Tools\n\n## Overview\n\nThe API Testing Tools module in MCP Playwright provides a comprehensive framework for executing and validating HTTP API requests directly within the Model Context Protocol server environment. This module enables AI assistants and automated testing systems to perform REST API testing operations with full request/response tracking, assertion capabilities, and detailed logging support.\n\nThe API Testing Tools extend the MCP Playwright server's functionality beyond browser automation to include robust HTTP client capabilities. This allows for seamless integration of API testing workflows alongside browser-based UI testing, enabling end-to-end testing scenarios that span both frontend and backend interactions.\n\n## Architecture\n\n### High-Level Architecture\n\n```mermaid\ngraph TD\n    A[MCP Client Request] --> B[Tool Router]\n    B --> C[API Testing Module]\n    C --> D[Request Executor]\n    D --> E[HTTP Client]\n    E --> F[External API]\n    F --> G[Response Handler]\n    G --> H[Assertion Engine]\n    H --> I[Tool Response]\n    D --> J[Logging Middleware]\n    J --> K[Request Logs]\n    \n    L[Request Builder] --> D\n    M[Auth Handler] --> L\n    N[Header Manager] --> L\n```\n\n### Module Structure\n\nThe API Testing Tools are organized into three primary components following the project's modular architecture pattern:\n\n| Component | File | Responsibility |\n|-----------|------|-----------------|\n| API Index | `src/tools/api/index.ts` | Tool registration and routing |\n| API Base | `src/tools/api/base.ts` | Base class with common functionality |\n| Request Handler | `src/tools/api/requests.ts` | HTTP request execution and response handling |\n\n## Core Components\n\n### API Tool Base Class\n\nThe base class for all API tools provides common functionality that mirrors the browser tool architecture while adapting for HTTP operations. This design ensures consistency with the broader MCP Playwright tool framework.\n\n```typescript\n// Pattern inherited from browser base architecture\nexport abstract class ApiToolBase implements ToolHandler {\n  protected server: any;\n  \n  constructor(server: any) {\n    this.server = server;\n  }\n  \n  abstract execute(args: any, context: ToolContext): Promise<ToolResponse>;\n  \n  protected ensureContext(context: ToolContext): ApiContext | null;\n  protected validateRequest(args: any): ToolResponse | null;\n  protected safeExecute(context: ToolContext, operation: ...): Promise<ToolResponse>;\n}\n```\n\n**资料来源：** [src/tools/api/base.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/base.ts)\n\n### Tool Registry and Handler\n\nThe API module registers its tools with the MCP server through the standard tool handler interface defined in the types system:\n\n```typescript\nexport interface Tool {\n  name: string;\n  description: string;\n  parameters: {\n    type: string;\n    properties: Record<string, unknown>;\n    required?: string[];\n  };\n  handler: (args: any) => Promise<any>;\n}\n```\n\n**资料来源：** [src/types.ts:1-15](https://github.com/executeautomation/mcp-playwright/blob/main/src/types.ts)\n\n### Request Builder and Executor\n\nThe request handler component manages the construction and execution of HTTP requests, supporting various HTTP methods and authentication mechanisms.\n\n**资料来源：** [src/tools/api/requests.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/requests.ts)\n\n## Available API Testing Tools\n\n### Response Expectation Tool\n\nThe `playwright_expect_response` tool allows tests to verify expected HTTP response characteristics before proceeding with further assertions. This tool enables proactive validation of API responses.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | string | Yes | Target API endpoint URL |\n| `method` | string | No | HTTP method (GET, POST, PUT, DELETE, etc.) |\n| `expectedStatus` | number | No | Expected HTTP status code |\n| `expectedBody` | object | No | Expected response body content |\n| `timeout` | number | No | Request timeout in milliseconds |\n\n**资料来源：** [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n\n### Response Assertion Tool\n\nThe `playwright_assert_response` tool provides comprehensive response validation capabilities, comparing actual API responses against expected values with detailed error reporting.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | string | Yes | Target API endpoint URL |\n| `expectedHeaders` | object | No | Expected response headers |\n| `expectedBody` | object | No | Expected response body pattern |\n| `schema` | object | No | JSON Schema for response validation |\n| `exactMatch` | boolean | No | Whether to require exact body matching |\n\n**资料来源：** [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n\n### Custom User Agent Tool\n\nThe `playwright_custom_user_agent` tool enables modification of the User-Agent header for API requests, supporting scenarios requiring specific client identification or browser emulation.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `userAgent` | string | Yes | Custom User-Agent string |\n| `persist` | boolean | No | Whether to persist for subsequent requests |\n\n**资料来源：** [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n\n### Optional Bearer Authorization\n\nAPI testing tools support optional Bearer token authentication for secured endpoints. This is configured at the request level and follows RFC 6750 specifications.\n\n**Configuration:**\n\n```json\n{\n  \"url\": \"https://api.example.com/protected\",\n  \"method\": \"GET\",\n  \"authorization\": {\n    \"type\": \"bearer\",\n    \"token\": \"${API_TOKEN}\"\n  }\n}\n```\n\n**资料来源：** [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n\n## Request Lifecycle\n\n```mermaid\nsequenceDiagram\n    participant MCP as MCP Client\n    participant API as API Tool Module\n    participant LOG as Logging Middleware\n    participant HTTP as HTTP Client\n    participant EXT as External API\n    \n    MCP->>API: Tool Call Request\n    API->>LOG: Log Tool Start\n    LOG->>LOG: Capture Request Context\n    API->>API: Validate Parameters\n    API->>HTTP: Execute Request\n    HTTP->>EXT: HTTP Request\n    EXT-->>HTTP: HTTP Response\n    HTTP-->>API: Raw Response\n    API->>API: Process Response\n    API->>API: Run Assertions\n    API->>LOG: Log Tool Completion\n    LOG-->>API: Log Entry Created\n    API-->>MCP: Tool Response\n```\n\n## Logging and Monitoring\n\n### Request Logging\n\nThe logging middleware captures detailed information about API tool executions, following the same pattern used for browser tools. Each API request generates a structured log entry with timing information and sanitized parameter data.\n\n**Logging Context Structure:**\n\n```typescript\ninterface RequestLogContext {\n  method: 'TOOL_CALL';\n  url: string;\n  body?: any;\n  statusCode?: number;\n  duration?: number;\n}\n```\n\n**资料来源：** [src/logging/middleware.ts:10-16](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n### Error Handling and Categorization\n\nThe logging middleware provides comprehensive error categorization for API-related errors:\n\n| Error Category | Detection Patterns | Description |\n|----------------|-------------------|-------------|\n| `validation` | invalid, validation, required, missing parameter | Request validation failures |\n| `resource` | browser, page, connection, closed, disconnected | Resource availability issues |\n| `authentication` | unauthorized, forbidden, access denied | Auth-related failures |\n| `rate_limit` | rate limit, too many requests, throttle | Rate limiting responses |\n\n**资料来源：** [src/logging/middleware.ts:85-120](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n### Sanitization\n\nSensitive data within API requests is automatically sanitized in logs:\n\n```typescript\nconst sensitiveFields = ['password', 'token', 'secret', 'key', 'auth'];\n// These fields are replaced with '[REDACTED]' in logs\n```\n\n**资料来源：** [src/logging/middleware.ts:180-190](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n## Integration with Browser Tools\n\nThe API Testing Tools are designed to work alongside browser automation tools, enabling comprehensive end-to-end testing scenarios:\n\n```mermaid\ngraph LR\n    A[playwright_navigate] --> B[Browser Actions]\n    B --> C[Extract Data]\n    C --> D[API Validation]\n    D --> E[playwright_expect_response]\n    E --> F[API Assertions]\n    F --> G[playwright_assert_response]\n    G --> H[Test Results]\n```\n\nThis integration allows for scenarios such as:\n\n1. **Data-Driven Testing**: Extract test data from the UI using browser tools, then validate against API responses\n2. **State Verification**: Use API tools to verify backend state after browser interactions\n3. **Hybrid Workflows**: Combine UI automation with API validation for complete coverage\n\n## Configuration\n\n### Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser downloads (for API-only usage) | `0` |\n| `NODE_ENV` | Node environment setting | `production` |\n| `OPENAI_API_KEY` | API key for evaluation framework | - |\n\n**资料来源：** [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Timeout Configuration\n\nAPI tool timeouts are configurable at the tool call level and can be set per-request:\n\n```typescript\n{\n  \"timeout\": 30000,  // 30 seconds\n  \"retries\": 0       // No automatic retries by default\n}\n```\n\n## Error Handling Patterns\n\n### Tool Response Structure\n\nAll API tools return responses following the standard `ToolResponse` format:\n\n```typescript\ninterface ToolResponse {\n  content: Array<{\n    type: 'text';\n    text: string;\n  }>;\n  isError?: boolean;\n}\n```\n\n**资料来源：** [src/tools/common/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/common/types.ts)\n\n### Common Error Scenarios\n\n| Scenario | Error Type | Handling |\n|----------|------------|----------|\n| Invalid URL | `validation` | Return error response with message |\n| Connection timeout | `resource` | Log with timeout details |\n| Invalid JSON response | `validation` | Include parse error in response |\n| Server error (5xx) | `system` | Log with response details |\n\n## Best Practices\n\n1. **Use Assertions Early**: Use `playwright_expect_response` for early failure detection in test suites\n2. **Sanitize Sensitive Data**: Ensure credentials are not logged by using environment variables\n3. **Set Appropriate Timeouts**: Configure timeouts based on expected API response times\n4. **Combine with Browser Tools**: Leverage both API and browser tools for comprehensive testing\n5. **Monitor Logs**: Review logging output for performance analysis and debugging\n\n## Related Documentation\n\n- [HTTP Mode Example](examples/http-mode-example.md) - Running the server in HTTP mode for API testing\n- [Docker Integration](DOCKER.md) - Containerized deployment for API testing workflows\n- [Main README](README.md) - General MCP Playwright server documentation\n\n---\n\n<a id='code-generation'></a>\n\n## Code Generation and Recording\n\n### 相关页面\n\n相关主题：[Browser Automation Tools](#browser-automation), [API Testing Tools](#api-testing)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/tools/codegen/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/codegen/index.ts)\n- [src/tools/codegen/recorder.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/codegen/recorder.ts)\n- [src/tools/codegen/generator.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/codegen/generator.ts)\n- [src/tools/codegen/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/codegen/types.ts)\n</details>\n\n# Code Generation and Recording\n\nThe Code Generation and Recording system is a module within the MCP Playwright server that enables automatic conversion of MCP tool interactions into executable Playwright test code. This feature captures user actions performed through MCP tools during browser automation sessions and transforms them into structured test cases that can be replayed using Playwright's native test runner.\n\n## Overview\n\nThe codegen module serves as a bridge between exploratory testing and automated test creation. When developers or AI assistants interact with web applications using MCP Playwright tools (such as `playwright_click`, `playwright_navigate`, `playwright_fill`, etc.), the codegen system records these actions with their parameters and results. Upon session completion, this recorded data can be converted into self-contained Playwright test files.\n\n资料来源：[src/tools/codegen/index.ts:1-30]()\n\n## Architecture\n\nThe codegen system follows a two-phase architecture: **Recording** and **Generation**.\n\n```mermaid\ngraph TD\n    A[MCP Tool Execution] --> B[ActionRecorder]\n    B --> C[CodegenSession Store]\n    C --> D[Session Actions]\n    D --> E[PlaywrightGenerator]\n    E --> F[Generated Test Code]\n    G[CodegenOptions] --> E\n    \n    style A fill:#e1f5fe\n    style F fill:#c8e6c9\n    style B fill:#fff3e0\n    style E fill:#fff3e0\n```\n\n### Core Components\n\n| Component | File | Responsibility |\n|-----------|------|-----------------|\n| ActionRecorder | recorder.ts | Captures and stores tool execution data |\n| PlaywrightGenerator | generator.ts | Transforms recorded sessions into test code |\n| CodegenSession | types.ts | Data model for tracking a recording session |\n| CodegenOptions | types.ts | Configuration for code generation behavior |\n\n资料来源：[src/tools/codegen/types.ts:1-35]()\n\n## Data Models\n\nThe codegen module defines several TypeScript interfaces that structure the recording and generation process.\n\n### CodegenAction\n\nRepresents a single recorded action during a codegen session.\n\n```typescript\nexport interface CodegenAction {\n  toolName: string;\n  parameters: Record<string, unknown>;\n  timestamp: number;\n  result?: unknown;\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| toolName | string | The name of the MCP tool that was executed |\n| parameters | Record<string, unknown> | Arguments passed to the tool |\n| timestamp | number | Unix timestamp when the action occurred |\n| result | unknown | Optional result returned by the tool execution |\n\n资料来源：[src/tools/codegen/types.ts:1-10]()\n\n### CodegenSession\n\nRepresents an entire recording session containing multiple actions.\n\n```typescript\nexport interface CodegenSession {\n  id: string;\n  actions: CodegenAction[];\n  startTime: number;\n  endTime?: number;\n  options?: CodegenOptions;\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| id | string | Unique identifier for the session |\n| actions | CodegenAction[] | Ordered list of recorded actions |\n| startTime | number | Session start timestamp |\n| endTime | number | Optional session end timestamp |\n| options | CodegenOptions | Optional generation configuration |\n\n资料来源：[src/tools/codegen/types.ts:12-20]()\n\n### CodegenOptions\n\nConfiguration options that control code generation behavior.\n\n```typescript\nexport interface CodegenOptions {\n  outputPath?: string;\n  testNamePrefix?: string;\n  includeComments?: boolean;\n}\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| outputPath | string | 'e2e' | Directory path where generated test files are written |\n| testNamePrefix | string | 'Test' | Prefix added to generated test names |\n| includeComments | boolean | true | Whether to include explanatory comments in generated code |\n\n资料来源：[src/tools/codegen/types.ts:26-32]()\n\n### CodegenResult\n\nOutput returned after generating test code from a session.\n\n```typescript\nexport interface CodegenResult {\n  testCode: string;\n  filePath: string;\n  sessionId: string;\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| testCode | string | The generated Playwright test code |\n| filePath | string | Path where the test file was or will be written |\n| sessionId | string | Reference to the originating session |\n\n资料来源：[src/tools/codegen/types.ts:34-40]()\n\n## Available Tools\n\nThe codegen module exposes the following MCP tools for managing sessions.\n\n### start_codegen_session\n\nInitiates a new recording session for capturing MCP tool actions.\n\n```typescript\nexport const startCodegenSession: Tool = {\n  name: 'start_codegen_session',\n  description: 'Start a new code generation session to record MCP tool actions',\n  parameters: {\n    type: 'object',\n    properties: {\n      options: {\n        type: 'object',\n        description: 'Code generation options',\n        properties: {\n          outputPath: { type: 'string' },\n          testNamePrefix: { type: 'string' },\n          includeComments: { type: 'boolean' }\n        }\n      }\n    }\n  },\n  // ...\n};\n```\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| options | object | No | Configuration for the codegen session |\n| options.outputPath | string | No | Custom output directory for generated tests |\n| options.testNamePrefix | string | No | Prefix for generated test names |\n| options.includeComments | boolean | No | Enable/disable code comments |\n\n资料来源：[src/tools/codegen/index.ts:37-58]()\n\n## PlaywrightGenerator Class\n\nThe `PlaywrightGenerator` class handles the transformation of recorded sessions into executable Playwright test code.\n\n### Constructor and Configuration\n\n```typescript\nexport class PlaywrightGenerator {\n  private static readonly DEFAULT_OPTIONS: Required<CodegenOptions> = {\n    outputPath: 'tests',\n    testNamePrefix: 'MCP',\n    includeComments: true,\n  };\n\n  private options: Required<CodegenOptions>;\n\n  constructor(options: CodegenOptions = {}) {\n    this.validateOptions(options);\n    this.options = { ...PlaywrightGenerator.DEFAULT_OPTIONS, ...options };\n  }\n}\n```\n\n| Default Option | Value | Description |\n|----------------|-------|-------------|\n| outputPath | 'tests' | Default directory for generated test files |\n| testNamePrefix | 'MCP' | Default prefix for test names |\n| includeComments | true | Comments included by default |\n\n资料来源：[src/tools/codegen/generator.ts:1-20]()\n\n### Options Validation\n\nThe generator performs strict validation on provided options before initializing.\n\n```typescript\nprivate validateOptions(options: CodegenOptions): void {\n  if (options.outputPath && typeof options.outputPath !== 'string') {\n    throw new Error('outputPath must be a string');\n  }\n  if (options.testNamePrefix && typeof options.testNamePrefix !== 'string') {\n    throw new Error('testNamePrefix must be a string');\n  }\n  if (options.includeComments !== undefined && typeof options.includeComments !== 'boolean') {\n    throw new Error('includeComments must be a boolean');\n  }\n}\n```\n\nAll options are validated for correct types before being applied, ensuring runtime errors are prevented during test generation.\n\n资料来源：[src/tools/codegen/generator.ts:22-33]()\n\n### Test Generation Process\n\n```typescript\nasync generateTest(session: CodegenSession): Promise<CodegenResult> {\n  if (!session || !Array.isArray(session.actions)) {\n    throw new Error('Invalid session data');\n  }\n\n  const testCase = this.createTestCase(session);\n  const testCode = this.generateTestCode(testCase);\n  const filePath = this.getOutputFilePath(session);\n\n  return {\n    testCode,\n    filePath,\n    sessionId: session.id,\n  };\n}\n```\n\nThe generation process consists of three steps:\n\n1. **Create Test Case** - Transforms session actions into a structured `PlaywrightTestCase`\n2. **Generate Test Code** - Converts the test case into Playwright test syntax\n3. **Determine Output Path** - Resolves the file path based on session ID and configuration\n\n资料来源：[src/tools/codegen/generator.ts:35-50]()\n\n## Recording Workflow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant MCP as MCP Server\n    participant Recorder as ActionRecorder\n    participant Store as CodegenSession Store\n    \n    User->>MCP: start_codegen_session(options)\n    MCP->>Recorder: createSession(options)\n    Recorder->>Store: initialize session\n    Note over Store: Session ID generated\n    \n    User->>MCP: playwright_click(selector)\n    MCP->>Recorder: record(toolName, args, result)\n    Recorder->>Store: append action\n    \n    User->>MCP: playwright_navigate(url)\n    MCP->>Recorder: record(toolName, args, result)\n    Recorder->>Store: append action\n    \n    User->>MCP: stop_codegen_session()\n    MCP->>Recorder: finalize session\n    Recorder->>Store: set endTime\n```\n\n## PlaywrightTestCase Structure\n\nThe intermediate representation used during code generation:\n\n```typescript\nexport interface PlaywrightTestCase {\n  name: string;\n  steps: string[];\n  imports: Set<string>;\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| name | string | Test case name derived from prefix and session info |\n| steps | string[] | Lines of Playwright test code |\n| imports | Set<string> | Required import statements for the test |\n\n资料来源：[src/tools/codegen/types.ts:22-26]()\n\n## Output Path Resolution\n\nThe system uses the workspace root as the base directory for generated tests:\n\n```typescript\nconst getWorkspaceRoot = () => {\n  return process.cwd();\n};\n\nconst DEFAULT_OPTIONS: Required<CodegenOptions> = {\n  outputPath: path.join(getWorkspaceRoot(), 'e2e'),\n  testNamePrefix: 'Test',\n  includeComments: true\n};\n```\n\nOutput paths are handled as follows:\n- Absolute paths are used as-is\n- Relative paths are resolved from the current working directory\n\n资料来源：[src/tools/codegen/index.ts:20-30]()\n\n## Integration with MCP Tool Execution\n\nThe recording system intercepts MCP tool calls to capture execution data. Each recorded action preserves:\n\n- The exact tool name (e.g., `playwright_click`, `playwright_fill`)\n- All parameters passed to the tool\n- The timestamp of execution\n- Optional result data from the tool\n\nThis captured data enables precise reproduction of user interactions when the generated test is executed.\n\n## Error Handling\n\nThe generator validates input at initialization and during generation:\n\n| Validation | Condition | Error |\n|------------|-----------|-------|\n| Session validity | Must exist with actions array | 'Invalid session data' |\n| Output path type | Must be string if provided | 'outputPath must be a string' |\n| Test name type | Must be string if provided | 'testNamePrefix must be a string' |\n| Comments type | Must be boolean if provided | 'includeComments must be a boolean' |\n\n资料来源：[src/tools/codegen/generator.ts:22-33]()\n\n## Usage Example\n\n```bash\n# Start a recording session with custom options\nnpx @executeautomation/playwright-mcp-server\n\n# Within your MCP client, call:\n# start_codegen_session with options { outputPath: \"./tests\", testNamePrefix: \"E2E\" }\n\n# Perform actions using playwright_* tools\n# playwright_navigate, playwright_click, etc. are recorded\n\n# Generate test code from the session\n```\n\nThe generated test code can then be executed with:\n\n```bash\nnpx playwright test ./tests/generated-test.spec.ts\n```\n\n## Related Documentation\n\n- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md) - Main project documentation\n- [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md) - Version history for codegen features\n- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md) - HTTP mode integration\n\n---\n\n<a id='docker-deployment'></a>\n\n## Docker Deployment\n\n### 相关页面\n\n相关主题：[Getting Started](#getting-started), [Configuration Guide](#configuration)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [Dockerfile](https://github.com/executeautomation/mcp-playwright/blob/main/Dockerfile)\n- [docker-compose.yml](https://github.com/executeautomation/mcp-playwright/blob/main/docker-compose.yml)\n- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n- [docker-build.sh](https://github.com/executeautomation/mcp-playwright/blob/main/docker-build.sh)\n</details>\n\n# Docker Deployment\n\n## Overview\n\nThe Playwright MCP Server provides Docker containerization support, enabling isolated execution environments for browser automation tasks. Docker deployment offers consistent runtime across different systems, simplified dependency management, and easy distribution of the MCP server.\n\nThe containerized solution is designed to work with pre-built artifacts from a local build, ensuring minimal image size while maintaining full functionality for browser automation through the MCP protocol.\n\n资料来源：[DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Host System\"\n        A[Local Build Directory] -->|npm install --omit=dev| B[node_modules]\n        A -->|npm run build| C[dist/]\n    end\n    \n    subgraph \"Docker Container\"\n        D[Dockerfile] -->|COPY| E[mcp-playwright:latest]\n        B -->|Production deps| E\n        C -->|Built artifacts| E\n    end\n    \n    subgraph \"Runtime Components\"\n        E -->|stdin/stdout| F[MCP Client]\n        E -->|Browser Automation| G[Playwright Browsers]\n    end\n    \n    F -->|JSON-RPC| H[Claude Desktop / VS Code / Custom Client]\n```\n\n## Prerequisites\n\n| Component | Requirement | Purpose |\n|-----------|-------------|---------|\n| Docker | Installed on host system | Container runtime |\n| Docker Compose | Optional (included with Docker Desktop) | Multi-container orchestration |\n| Node.js | For building locally | Pre-build step |\n| Local Build | `npm install --omit=dev && npm run build` | Generate artifacts for Docker COPY |\n\n资料来源：[DOCKER.md:prerequisites-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Building the Docker Image\n\n### Standard Build Process\n\nThe Dockerfile copies `node_modules` and `dist` from the local build directory directly into the image. This approach requires building artifacts locally before containerization.\n\n```bash\n# 1. Install production dependencies only\nnpm install --omit=dev\n\n# 2. Build the project\nnpm run build\n\n# 3. Build the Docker image\ndocker build -t mcp-playwright:latest .\n```\n\n### Automated Build Script\n\nA convenience script is provided for the build process:\n\n```bash\nchmod +x docker-build.sh\n./docker-build.sh\n```\n\n资料来源：[DOCKER.md:building-docker-image-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Build with Custom Tag\n\n```bash\ndocker build -t mcp-playwright:1.0.6 .\n```\n\n### Building from Source Inside Docker\n\nFor environments where you prefer building inside the container:\n\n```dockerfile\nFROM node:20-alpine AS builder\n\nWORKDIR /app\nCOPY package*.json ./\nENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\nRUN npm ci\n\nCOPY src ./src\nCOPY tsconfig.json ./\nRUN npm run build\n\nFROM node:20-alpine\nWORKDIR /app\nCOPY --from=builder /app/dist ./dist\nCOPY --from=builder /app/package*.json ./\nRUN npm ci --only=production\nCMD [\"node\", \"dist/index.js\"]\n```\n\n资料来源：[DOCKER.md:building-from-source-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Running the Server\n\n### Interactive Mode (Recommended for MCP)\n\nMCP servers communicate via stdin/stdout, requiring interactive mode for proper operation:\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n| Flag | Purpose |\n|------|---------|\n| `-i` | Keep STDIN open for interactive communication |\n| `--rm` | Automatically remove container when it exits |\n| `mcp-playwright:latest` | Image name and tag |\n\n资料来源：[DOCKER.md:running-the-server-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Using Docker Compose\n\n```bash\n# Start the server\ndocker compose run --rm playwright-mcp\n\n# Or build and run\ndocker compose build\ndocker compose run --rm playwright-mcp\n```\n\nThe provided `docker-compose.yml`:\n\n```yaml\nservices:\n  playwright-mcp:\n    build:\n      context: .\n      dockerfile: Dockerfile\n    image: mcp-playwright:latest\n    container_name: playwright-mcp-server\n    stdin_open: true\n    tty: true\n    environment:\n      - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\n```\n\n资料来源：[docker-compose.yml](https://github.com/executeautomation/mcp-playwright/blob/main/docker-compose.yml)\n\n## MCP Client Integration\n\n### Claude Desktop Configuration\n\nUpdate the Claude Desktop configuration file:\n\n| OS | Configuration Location |\n|----|----------------------|\n| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |\n| Windows | `%APPDATA%\\Claude\\claude_desktop_config.json` |\n| Linux | `~/.config/Claude/claude_desktop_config.json` |\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright-docker\": {\n      \"command\": \"docker\",\n      \"args\": [\"run\", \"-i\", \"--rm\", \"mcp-playwright:latest\"]\n    }\n  }\n}\n```\n\n资料来源：[DOCKER.md:claude-desktop-configuration-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### VS Code MCP Extension\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright-docker\": {\n      \"command\": \"docker\",\n      \"args\": [\"run\", \"-i\", \"--rm\", \"mcp-playwright:latest\"]\n    }\n  }\n}\n```\n\n资料来源：[DOCKER.md:vs-code-mcp-extension-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Configuration Options\n\n### Environment Variables\n\n| Variable | Default | Purpose |\n|----------|---------|---------|\n| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | `1` | Skip browser downloads to reduce image size |\n| `NODE_ENV` | `production` | Runtime environment |\n\n#### Using Environment Variables in Docker\n\n```bash\ndocker run -i --rm \\\n  -e PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \\\n  mcp-playwright:latest\n```\n\n#### Using Environment Variables in Docker Compose\n\n```yaml\nservices:\n  playwright-mcp:\n    environment:\n      - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\n      - NODE_ENV=production\n```\n\n资料来源：[DOCKER.md:environment-variables-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Volume Mounts\n\nFor persistent data or file sharing with the container:\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  mcp-playwright:latest\n```\n\n```yaml\nservices:\n  playwright-mcp:\n    volumes:\n      - ./data:/app/data\n      - ./screenshots:/app/screenshots\n```\n\n资料来源：[DOCKER.md:volume-mounts-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Resource Limits\n\n```bash\ndocker run -i --rm \\\n  --cpus=\"2.0\" \\\n  --memory=\"2g\" \\\n  mcp-playwright:latest\n```\n\n```yaml\nservices:\n  playwright-mcp:\n    deploy:\n      resources:\n        limits:\n          cpus: '2.0'\n          memory: 2G\n```\n\n资料来源：[DOCKER.md:resource-limits-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Custom Network Configuration\n\n```bash\n# Create custom network\ndocker network create mcp-network\n\n# Run container on custom network\ndocker run -i --rm --network mcp-network mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:advanced-usage-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Troubleshooting\n\n### Container Exits Immediately\n\nMCP servers wait for input on stdin. Ensure the `-i` flag is used:\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:troubleshooting-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Browser Not Found\n\nThe Docker image skips browser downloads by default to reduce size. Playwright downloads browsers on first use. To pre-install browsers:\n\n```dockerfile\nFROM mcp-playwright:latest\n\n# Install Playwright browsers\nRUN npx playwright install chromium --with-deps\n```\n\n资料来源：[DOCKER.md:browser-not-found-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Permission Issues\n\nIf encountering permission issues with mounted volumes:\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  --user $(id -u):$(id -g) \\\n  mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:permission-issues-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Health Checks\n\nAdd a health check to your docker-compose.yml:\n\n```yaml\nservices:\n  playwright-mcp:\n    healthcheck:\n      test: [\"CMD\", \"node\", \"-e\", \"process.exit(0)\"]\n      interval: 30s\n      timeout: 10s\n      retries: 3\n```\n\n资料来源：[DOCKER.md:health-checks-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Security Considerations\n\n| Practice | Implementation |\n|----------|----------------|\n| Non-root user | Add `USER node` to custom Dockerfile |\n| Read-only root filesystem | Run with `--read-only` flag |\n| Vulnerability scanning | `docker scan mcp-playwright:latest` |\n\n### Run as Non-root User (Recommended)\n\n```dockerfile\nFROM mcp-playwright:latest\nUSER node\n```\n\n### Read-only Root Filesystem\n\n```bash\ndocker run -i --rm --read-only mcp-playwright:latest\n```\n\n### Vulnerability Scanning\n\n```bash\ndocker scan mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:security-considerations-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Image Optimization\n\n| Optimization | Description |\n|--------------|-------------|\n| Base image | Debian-based slim Node.js (~200MB) |\n| Artifact strategy | Copies pre-built dist from host |\n| Dependencies | Production-only via `--omit=dev` |\n| Browser downloads | Skipped by default |\n\n**Current image size**: ~200MB (without browsers)\n\n资料来源：[DOCKER.md:image-size-optimization-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Workflow Summary\n\n```mermaid\ngraph LR\n    A[Local Build] -->|npm install --omit=dev| B[Dependencies]\n    A -->|npm run build| C[dist/]\n    B -->|COPY| D[Docker Build]\n    C -->|COPY| D\n    D -->|docker build| E[Image Created]\n    E -->|Interactive Mode| F[MCP Server Running]\n    F -->|JSON-RPC| G[MCP Client Connected]\n```\n\n## Quick Reference\n\n| Command | Description |\n|---------|-------------|\n| `docker build -t mcp-playwright:latest .` | Build image |\n| `docker run -i --rm mcp-playwright:latest` | Run in interactive mode |\n| `docker compose up` | Run via compose |\n| `docker scan mcp-playwright:latest` | Security scan |\n\n---\n\n<a id='configuration'></a>\n\n## Configuration Guide\n\n### 相关页面\n\n相关主题：[Getting Started](#getting-started), [Transport Modes](#transport-modes), [Docker Deployment](#docker-deployment)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)\n- [src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)\n- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)\n- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n</details>\n\n# Configuration Guide\n\nThis guide covers all configuration options for the mcp-playwright MCP server, including stdio mode, HTTP server mode, Docker deployment, and integration with AI assistants like Claude Desktop.\n\n## Overview\n\nThe mcp-playwright server provides browser automation capabilities through the Model Context Protocol (MCP). It supports multiple transport modes and can be configured to work with different MCP clients. 资料来源：[package.json:1-50]()\n\n```mermaid\ngraph TD\n    A[MCP Client] --> B{Mode Selection}\n    B --> C[Stdio Mode]\n    B --> D[HTTP Mode]\n    B --> E[Docker Mode]\n    C --> F[stdin/stdout]\n    D --> G[localhost:8931]\n    E --> H[Docker Container]\n    F --> I[Playwright Browser]\n    G --> I\n    H --> I\n```\n\n## Stdio Mode Configuration\n\nStdio mode is the primary transport mechanism for MCP communication, using standard input/output streams. This mode is automatically selected when running via `npx` or direct node execution. 资料来源：[README.md:1-30]()\n\n### Claude Desktop Configuration\n\nFor Claude Desktop integration, add the server configuration to your Claude Desktop config file:\n\n| Platform | Config Location |\n|----------|-----------------|\n| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |\n| Windows | `%APPDATA%\\Claude\\claude_desktop_config.json` |\n| Linux | `~/.config/Claude/claude_desktop_config.json` |\n\n**Configuration schema:**\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n    }\n  }\n}\n```\n\n### VS Code MCP Extension\n\nFor VS Code with MCP extension:\n\n```json\n{\n  \"name\": \"playwright\",\n  \"command\": \"npx\",\n  \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n}\n```\n\n> **Note:** In stdio mode, logging is automatically directed to files only (not console) to maintain clean JSON-RPC communication. Logs are written to `~/playwright-mcp-server.log`. 资料来源：[README.md:25-27]()\n\n## HTTP Mode Configuration\n\nHTTP mode enables the MCP server to run as a standalone HTTP server, useful for remote deployments or IDE integrations that support HTTP transport. 资料来源：[src/http-server.ts:1-50]()\n\n### Starting the HTTP Server\n\n```bash\n# Using npx\nnpx @executeautomation/playwright-mcp-server --port 8931\n\n# Or after global installation\nnpm install -g @executeautomation/playwright-mcp-server\nplaywright-mcp-server --port 8931\n```\n\n### HTTP Server Endpoints\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/sse` | GET | SSE Stream for Server-Sent Events |\n| `/messages` | POST | Send messages with session ID |\n| `/mcp` | GET/POST | Unified MCP endpoint |\n| `/health` | GET | Health check endpoint |\n\n### Security Configuration\n\nThe HTTP server binds to `127.0.0.1` (localhost only) by default to prevent external network access. 资料来源：[src/http-server.ts:35-36]()\n\n```typescript\nconst host = '127.0.0.1';\nconst httpServer = app.listen(port, host, () => {\n  logger.info(`Playwright MCP HTTP server listening on ${host}:${port}`);\n});\n```\n\n### Claude Desktop HTTP Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"url\": \"http://localhost:8931/mcp\"\n    }\n  }\n}\n```\n\n### Health Check\n\n```bash\ncurl http://localhost:8931/health\n```\n\nResponse format:\n\n```json\n{\n  \"status\": \"ok\",\n  \"version\": \"1.0.10\",\n  \"activeSessions\": 0\n}\n```\n\n## Docker Configuration\n\nThe Docker image provides a containerized deployment option for the mcp-playwright server. 资料来源：[DOCKER.md:1-50]()\n\n### Basic Docker Run\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n| Flag | Purpose |\n|------|---------|\n| `-i` | Keep STDIN open for interactive communication |\n| `--rm` | Automatically remove container on exit |\n\n### Docker Compose Configuration\n\n```yaml\nservices:\n  playwright-mcp:\n    image: mcp-playwright:latest\n```\n\n### Claude Desktop Docker Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright-docker\": {\n      \"command\": \"docker\",\n      \"args\": [\"run\", \"-i\", \"--rm\", \"mcp-playwright:latest\"]\n    }\n  }\n}\n```\n\n### VS Code Docker Configuration\n\n```json\n{\n  \"name\": \"playwright-docker\",\n  \"command\": \"docker\",\n  \"args\": [\"run\", \"-i\", \"--rm\", \"mcp-playwright:latest\"]\n}\n```\n\n## Environment Variables\n\nConfigure server behavior using environment variables. 资料来源：[DOCKER.md:20-35]()\n\n### Available Environment Variables\n\n| Variable | Purpose | Default |\n|----------|---------|---------|\n| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser downloads during image build | `1` (enabled) |\n| `NODE_ENV` | Node environment setting | `production` |\n\n### Docker Environment Variable Examples\n\n**Via docker run:**\n\n```bash\ndocker run -i --rm \\\n  -e PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \\\n  -e NODE_ENV=production \\\n  mcp-playwright:latest\n```\n\n**Via docker-compose.yml:**\n\n```yaml\nservices:\n  playwright-mcp:\n    environment:\n      - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\n      - NODE_ENV=production\n```\n\n## Volume Mounts\n\nShare files and persist data between the host and container. 资料来源：[DOCKER.md:36-50]()\n\n### Docker Volume Examples\n\n**Via docker run:**\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  -v $(pwd)/screenshots:/app/screenshots \\\n  mcp-playwright:latest\n```\n\n**Via docker-compose.yml:**\n\n```yaml\nservices:\n  playwright-mcp:\n    volumes:\n      - ./data:/app/data\n      - ./screenshots:/app/screenshots\n```\n\n### User and Permissions\n\nHandle permission issues with mounted volumes by specifying user:\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  --user $(id -u):$(id -g) \\\n  mcp-playwright:latest\n```\n\n## Resource Limits\n\nConfigure CPU and memory constraints for containerized deployments. 资料来源：[DOCKER.md:85-100]()\n\n### Docker Resource Limits\n\n```yaml\nservices:\n  playwright-mcp:\n    deploy:\n      resources:\n        limits:\n          cpus: '2.0'\n          memory: 2G\n```\n\n**Via docker run:**\n\n```bash\ndocker run -i --rm \\\n  --cpus=\"2.0\" \\\n  --memory=\"2g\" \\\n  mcp-playwright:latest\n```\n\n## Network Configuration\n\n### Custom Network\n\n```bash\ndocker network create mcp-network\ndocker run -i --rm --network mcp-network mcp-playwright:latest\n```\n\n### Security Considerations\n\n| Configuration | Recommendation |\n|---------------|-----------------|\n| Run as non-root user | Optional but recommended |\n| Read-only root filesystem | For containers not needing write access |\n| Vulnerability scanning | Use `docker scan mcp-playwright:latest` |\n\n## Health Checks\n\nAdd health check configuration to docker-compose.yml:\n\n```yaml\nservices:\n  playwright-mcp:\n    healthcheck:\n      test: [\"CMD\", \"node\", \"-e\", \"process.exit(0)\"]\n      interval: 30s\n      timeout: 10s\n      retries: 3\n```\n\n## Troubleshooting Configuration Issues\n\n### Container Exits Immediately\n\nMCP servers wait for input on stdin. Ensure the `-i` flag is used:\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n### Browser Not Found\n\nThe Docker image skips browser downloads by default. To pre-install browsers, create a custom Dockerfile:\n\n```dockerfile\nFROM mcp-playwright:latest\nRUN npx playwright install chromium --with-deps\n```\n\n## Tool Name Length Constraints\n\nWhen adding new tools, consider the combined server and tool name length. Some clients like Cursor have a 60-character limit for `server_name:tool_name`. 资料来源：[README.md:10-15]()\n\nCurrent server name: `playwright-mcp`\n\nEnsure tool names are short enough to not exceed this limit when combined.\n\n## Image Specifications\n\n| Aspect | Value |\n|--------|-------|\n| Base image | Debian-based slim Node.js (~200MB) |\n| Default size | ~200MB (without browsers) |\n| Dependencies | Production only (no dev dependencies) |\n\n## Building Custom Docker Images\n\n### Optimized Build (Recommended)\n\nUses pre-built artifacts from local development:\n\n```dockerfile\nFROM node:20-slim\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci --omit=dev\nCOPY node_modules ./node_modules\nCOPY dist ./dist\nCMD [\"node\", \"dist/index.js\"]\n```\n\n### Full Build from Source\n\n```dockerfile\nFROM node:20-alpine AS builder\nWORKDIR /app\nCOPY package*.json ./\nENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\nRUN npm ci\n\nCOPY src ./src\nCOPY tsconfig.json ./\nRUN npm run build\n\nFROM node:20-alpine\nWORKDIR /app\nCOPY --from=builder /app/dist ./dist\nCOPY --from=builder /app/package*.json ./\nRUN npm ci --only=production\nCMD [\"node\", \"dist/index.js\"]\n```\n\n## Dependencies Configuration\n\nThe package.json defines core dependencies for the MCP server. 资料来源：[package.json:10-35]()\n\n### Runtime Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | 1.24.3 | MCP protocol implementation |\n| `@playwright/browser-chromium` | 1.57.0 | Chromium browser |\n| `@playwright/browser-firefox` | 1.57.0 | Firefox browser |\n| `@playwright/browser-webkit` | 1.57.0 | WebKit browser |\n| `express` | ^4.21.1 | HTTP server framework |\n| `cors` | ^2.8.5 | Cross-origin resource sharing |\n| `uuid` | 11.1.0 | UUID generation |\n\n### Development Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `typescript` | ^5.8.3 | TypeScript compiler |\n| `jest` | ^29.7.0 | Testing framework |\n| `@types/node` | ^20.10.5 | Node.js type definitions |\n| `@types/express` | ^4.17.21 | Express type definitions |\n| `jest-playwright-preset` | 4.0.0 | Playwright Jest integration |\n\n## Logging Configuration\n\nIn stdio mode, logs are automatically directed to files to maintain clean JSON-RPC communication. 资料来源：[README.md:27]()\n\nLog file location: `~/playwright-mcp-server.log`\n\nThe logging middleware captures:\n- Request IDs for traceability\n- Tool execution timing and results\n- Error categorization (validation, system, resource, authentication, rate_limit)\n- Sanitized request bodies (sensitive fields redacted)\n\n## Summary\n\n| Transport Mode | Use Case | Config Key |\n|---------------|----------|------------|\n| Stdio | Claude Desktop, local MCP clients | `command: \"npx\"` |\n| HTTP | Remote deployments, VS Code | `url: \"http://localhost:8931/mcp\"` |\n| Docker | Containerized environments | `command: \"docker\"` |\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：executeautomation/mcp-playwright\n\n摘要：发现 16 个潜在踩坑项，其中 2 个为 high/blocking；最高优先级：安装坑 - 来源证据：Playwright is asking for an specific browser version.。\n\n## 1. 安装坑 · 来源证据：Playwright is asking for an specific browser version.\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Playwright is asking for an specific browser version.\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_38465ac94a9d4fb0bd352ba5209096ac | https://github.com/executeautomation/mcp-playwright/issues/117 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 2. 安全/权限坑 · 来源证据：How to configure proxy and storageState when launching browser in Playwright MCP?\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：How to configure proxy and storageState when launching browser in Playwright MCP?\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a2f7e4a410994d4195a9af9f139e0caa | https://github.com/executeautomation/mcp-playwright/issues/203 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 3. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | host_targets=mcp_host, claude, cursor\n\n## 4. 配置坑 · 来源证据：Add Clarvia AEO score badge to README (AEO 32/100)\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Add Clarvia AEO score badge to README (AEO 32/100)\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_74959d07d5f74165bcd9cae829d384ce | https://github.com/executeautomation/mcp-playwright/issues/212 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 5. 配置坑 · 来源证据：Add policy enforcement for browser automation and HTTP request tools\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Add policy enforcement for browser automation and HTTP request tools\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_23a30d245f794b8db40c1d031b8be565 | https://github.com/executeautomation/mcp-playwright/issues/216 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 6. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | README/documentation is current enough for a first validation pass.\n\n## 7. 运行坑 · 来源证据：How to pass in the `--ignore-https-errors` parameter?\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：How to pass in the `--ignore-https-errors` parameter?\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_47d5e333819d49b4b8ce2abb9484b23d | https://github.com/executeautomation/mcp-playwright/issues/202 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 8. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | last_activity_observed missing\n\n## 9. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | no_demo; severity=medium\n\n## 10. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 11. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | no_demo; severity=medium\n\n## 12. 安全/权限坑 · 来源证据：Feature Request: Add browser context persistence for login state (userDataDir/storageState)\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Request: Add browser context persistence for login state (userDataDir/storageState)\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_3632e6a11e044dda870b3267ccfa3040 | https://github.com/executeautomation/mcp-playwright/issues/201 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 13. 安全/权限坑 · 来源证据：Free MCP security scan report for @executeautomation/playwright-mcp-server\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Free MCP security scan report for @executeautomation/playwright-mcp-server\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9720dc9967444ed08710cdb0660a212a | https://github.com/executeautomation/mcp-playwright/issues/211 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 14. 安全/权限坑 · 来源证据：Security Advisory: SSRF, Prompt Injection, and Arbitrary JavaScript Execution via Browser Automation Tools\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Security Advisory: SSRF, Prompt Injection, and Arbitrary JavaScript Execution via Browser Automation Tools\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ced642164084421f84bbb63681653057 | https://github.com/executeautomation/mcp-playwright/issues/209 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 15. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | issue_or_pr_quality=unknown\n\n## 16. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | release_recency=unknown\n\n<!-- canonical_name: executeautomation/mcp-playwright; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "mcp-playwright",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:898077246",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/executeautomation/mcp-playwright"
        },
        {
          "evidence_id": "art_904b3d0637f0432db08e131df9c7b98d",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/executeautomation/mcp-playwright#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "mcp-playwright 说明书",
      "toc": [
        "https://github.com/executeautomation/mcp-playwright 项目说明书",
        "目录",
        "Project Introduction",
        "Overview",
        "Architecture",
        "Installation Methods",
        "npm",
        "mcp-get",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "2349c2891e7c499c8c07b7d78c7f3fb4c797a1da",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "Dockerfile",
      "package.json",
      "README.md",
      "docker-compose.yml",
      "docs/package-lock.json",
      "docs/package.json",
      "docs/tsconfig.json",
      "docs/sidebars.ts",
      "docs/docusaurus.config.ts",
      "docs/docs/intro.mdx",
      "docs/docs/release.mdx",
      "docs/src/pages/markdown-page.md",
      "docs/docs/ai-courses/MachineLearning.mdx",
      "docs/docs/ai-courses/_category_.json",
      "docs/docs/ai-courses/GenAICourse.mdx",
      "docs/docs/ai-courses/AIAgents.mdx",
      "docs/docs/testing-videos/_category_.json",
      "docs/docs/testing-videos/Bdd.mdx",
      "docs/docs/testing-videos/AIAgents.mdx",
      "docs/docs/local-setup/_category_.json",
      "docs/docs/local-setup/Installation.mdx",
      "docs/docs/local-setup/Debugging.mdx",
      "docs/docs/playwright-web/Supported-Tools.mdx",
      "docs/docs/playwright-web/_category_.json",
      "docs/docs/playwright-web/Device-Quick-Reference.md",
      "docs/docs/playwright-web/Examples.md",
      "docs/docs/playwright-web/Recording-Actions.mdx",
      "docs/docs/playwright-web/Support-of-Cline-Cursor.mdx",
      "docs/docs/playwright-web/Resize-Prompts-Guide.md",
      "docs/docs/playwright-web/Console-Logging.mdx",
      "docs/docs/playwright-web/HTTP-SSE-Transport.mdx",
      "docs/docs/playwright-api/Supported-Tools.mdx",
      "docs/docs/playwright-api/_category_.json",
      "docs/docs/playwright-api/Examples.md",
      "examples/http-mode-example.md",
      "src/requestHandler.ts",
      "src/tools.ts",
      "src/toolHandler.ts",
      "src/index.ts",
      "src/types.ts"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# @executeautomation/playwright-mcp-server - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 @executeautomation/playwright-mcp-server 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0002` supported 0.86\n\n## 它能做什么\n\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n## 怎么开始\n\n- `npm install -g @executeautomation/playwright-mcp-server` 证据：`README.md` Claim：`clm_0003` supported 0.86\n- `npx @michaellatman/mcp-get@latest install @executeautomation/playwright-mcp-server` 证据：`README.md` Claim：`clm_0004` supported 0.86\n- `npx @smithery/cli install @executeautomation/playwright-mcp-server --client claude` 证据：`README.md` Claim：`clm_0005` supported 0.86\n- `claude mcp add --transport stdio playwright npx @executeautomation/playwright-mcp-server` 证据：`README.md` Claim：`clm_0006` supported 0.86\n- `npx playwright install` 证据：`README.md` Claim：`clm_0007` supported 0.86, `clm_0008` supported 0.86, `clm_0009` supported 0.86, `clm_0010` supported 0.86\n- `npx playwright install chromium` 证据：`README.md` Claim：`clm_0008` supported 0.86\n- `npx playwright install firefox` 证据：`README.md` Claim：`clm_0009` supported 0.86\n- `npx playwright install webkit` 证据：`README.md` Claim：`clm_0010` supported 0.86\n- `npx @executeautomation/playwright-mcp-server --port 8931` 证据：`README.md` Claim：`clm_0011` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：需要管理员/安全审批\n- **为什么**：继续前可能涉及密钥、账号、外部服务或敏感上下文，建议先经过管理员或安全审批。\n\n### 30 秒判断\n\n- **现在怎么做**：需要管理员/安全审批\n- **最小安全下一步**：先跑 Prompt Preview；若涉及凭证或企业环境，先审批再试装\n- **先别相信**：工具权限边界不能在安装前相信。\n- **继续会触碰**：命令执行、本地环境或项目文件、环境变量 / API Key\n\n### 现在可以相信\n\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0002` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n### 现在还不能相信\n\n- **工具权限边界不能在安装前相信。**（unverified）：MCP/tool 类项目通常会触碰文件、网络、浏览器或外部 API，必须真实检查权限和日志。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **环境变量 / API Key**：项目入口文档明确出现 API key、token、secret 或账号凭证配置。 原因：如果真实安装需要凭证，应先使用测试凭证并经过权限/合规判断。 证据：`README.md`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **不要使用真实生产凭证**：环境变量/API key 一旦进入宿主或工具链，可能产生账号和合规风险。（适用：出现 API、TOKEN、KEY、SECRET 等环境线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **准备撤销测试 API key 或 token**：测试凭证泄露或误用时，可以快速止损。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0012` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0013` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md` Claim：`clm_0001` supported 0.86\n\n### 上下文规模\n\n- 文件总数：122\n- 重要文件覆盖：40/122\n- 证据索引条目：40\n- 角色 / Skill 条目：9\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 @executeautomation/playwright-mcp-server 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 @executeautomation/playwright-mcp-server 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 @executeautomation/playwright-mcp-server 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 9 个角色 / Skill / 项目文档条目。\n\n- **Playwright MCP Server 🎭**（project_doc）：! Trust Score https://archestra.ai/mcp-catalog/api/badge/quality/executeautomation/mcp-playwright https://archestra.ai/mcp-catalog/executeautomation mcp-playwright ! smithery badge https://smithery.ai/badge/@executeautomation/playwright-mcp-server https://smithery.ai/server/@executeautomation/playwright-mcp-server 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **⚙️Examples of API automation**（project_doc）：Lets see how we can use the power of Playwright MCP Server to automate API of our application 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/playwright-api/Examples.md`\n- **Device Testing Quick Reference**（project_doc）：What You Want Natural Language Prompt --------------- ------------------------ 📱 iPhone \"Test on iPhone 13\" 📱 iPhone Landscape \"Switch to iPhone 13 landscape\" 📱 Android \"Test on Pixel 7\" 📱 Samsung \"Switch to Galaxy S24\" 📱 Tablet \"Test on iPad Pro 11\" 💻 Desktop \"Show desktop view\" or \"Desktop Chrome\" 🔄 Rotate \"Rotate to landscape\" 📏 Custom \"Resize to 1024x768\" 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/playwright-web/Device-Quick-Reference.md`\n- **🌐 Examples of browser automation**（project_doc）：🌐 Examples of browser automation Lets see how we can use the power of Playwright MCP Server to automate our browser and do webscrapping 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/playwright-web/Examples.md`\n- **Prompt Guide: Using playwright resize**（project_doc）：Prompt Guide: Using playwright resize 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/docs/playwright-web/Resize-Prompts-Guide.md`\n- **Markdown page example**（project_doc）：You don't need React to write simple standalone pages. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/src/pages/markdown-page.md`\n- **Changelog**（project_doc）：All notable changes to the Playwright MCP Server will be documented in this file. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`CHANGELOG.md`\n- **Docker Support for Playwright MCP Server**（project_doc）：Docker Support for Playwright MCP Server 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`DOCKER.md`\n- **HTTP Mode Example**（project_doc）：This example demonstrates how to use the Playwright MCP Server in HTTP mode. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`examples/http-mode-example.md`\n\n## 证据索引\n\n- 共索引 40 条证据。\n\n- **Playwright MCP Server 🎭**（documentation）：! Trust Score https://archestra.ai/mcp-catalog/api/badge/quality/executeautomation/mcp-playwright https://archestra.ai/mcp-catalog/executeautomation mcp-playwright ! smithery badge https://smithery.ai/badge/@executeautomation/playwright-mcp-server https://smithery.ai/server/@executeautomation/playwright-mcp-server 证据：`README.md`\n- **Package**（package_manifest）：{ \"name\": \"playwright-mcp-server\", \"version\": \"0.0.0\", \"private\": true, \"scripts\": { \"docusaurus\": \"docusaurus\", \"start\": \"docusaurus start\", \"build\": \"docusaurus build\", \"swizzle\": \"docusaurus swizzle\", \"deploy\": \"docusaurus deploy\", \"clear\": \"docusaurus clear\", \"serve\": \"docusaurus serve\", \"write-translations\": \"docusaurus write-translations\", \"write-heading-ids\": \"docusaurus write-heading-ids\", \"typecheck\": \"tsc\" }, \"dependencies\": { \"@docusaurus/core\": \"3.6.3\", \"@docusaurus/preset-classic\": \"3.6.3\", \"@mdx-js/react\": \"^3.0.0\", \"clsx\": \"^2.0.0\", \"gh-pages\": \"^6.2.0\", \"prism-react-renderer\": \"^2.3.0\", \"react\": \"^18.0.0\", \"react-dom\": \"^18.0.0\" }, \"devDependencies\": { \"@docusaurus/module-ty… 证据：`docs/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@executeautomation/playwright-mcp-server\", \"version\": \"1.0.12\", \"description\": \"Model Context Protocol servers for Playwright\", \"license\": \"MIT\", \"author\": \"ExecuteAutomation, Ltd https://executeautomation.com \", \"homepage\": \"https://executeautomation.github.io/mcp-playwright/\", \"bugs\": \"https://github.com/executeautomation/mcp-playwright/issues\", \"types\": \"dist/index.d.ts\", \"type\": \"module\", \"bin\": { \"playwright-mcp-server\": \"dist/index.js\" }, \"files\": \"dist\" , \"scripts\": { \"build\": \"tsc && shx chmod +x dist/ .js\", \"prepare\": \"npm run build\", \"watch\": \"tsc --watch\", \"test\": \"jest --testMatch=\\\" /src/ tests / / .test.ts\\\"\", \"test:coverage\": \"jest --coverage --testMatch=\\\" /src/ t… 证据：`package.json`\n- **License**（source_file）：Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files the \"Software\" , to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 证据：`LICENSE`\n- **⚙️Examples of API automation**（documentation）：Lets see how we can use the power of Playwright MCP Server to automate API of our application 证据：`docs/docs/playwright-api/Examples.md`\n- **Device Testing Quick Reference**（documentation）：What You Want Natural Language Prompt --------------- ------------------------ 📱 iPhone \"Test on iPhone 13\" 📱 iPhone Landscape \"Switch to iPhone 13 landscape\" 📱 Android \"Test on Pixel 7\" 📱 Samsung \"Switch to Galaxy S24\" 📱 Tablet \"Test on iPad Pro 11\" 💻 Desktop \"Show desktop view\" or \"Desktop Chrome\" 🔄 Rotate \"Rotate to landscape\" 📏 Custom \"Resize to 1024x768\" 证据：`docs/docs/playwright-web/Device-Quick-Reference.md`\n- **🌐 Examples of browser automation**（documentation）：🌐 Examples of browser automation Lets see how we can use the power of Playwright MCP Server to automate our browser and do webscrapping 证据：`docs/docs/playwright-web/Examples.md`\n- **Prompt Guide: Using playwright resize**（documentation）：Prompt Guide: Using playwright resize 证据：`docs/docs/playwright-web/Resize-Prompts-Guide.md`\n- **Markdown page example**（documentation）：You don't need React to write simple standalone pages. 证据：`docs/src/pages/markdown-page.md`\n- **Changelog**（documentation）：All notable changes to the Playwright MCP Server will be documented in this file. 证据：`CHANGELOG.md`\n- **Docker Support for Playwright MCP Server**（documentation）：Docker Support for Playwright MCP Server 证据：`DOCKER.md`\n- **HTTP Mode Example**（documentation）：This example demonstrates how to use the Playwright MCP Server in HTTP mode. 证据：`examples/http-mode-example.md`\n- **Tsconfig**（structured_config）：{ // This file is not used in compilation. It is here just for a nice editor experience. \"extends\": \"@docusaurus/tsconfig\", \"compilerOptions\": { \"baseUrl\": \".\" }, \"exclude\": \".docusaurus\", \"build\" } 证据：`docs/tsconfig.json`\n- **Mcp Config**（structured_config）：{ \"mcpServers\": { \"playwright\": { \"command\": \"npx\", \"args\": \"-y\", \"@executeautomation/playwright-mcp-server\" } } } 证据：`mcp-config.json`\n- **Tsconfig**（structured_config）：{ \"compilerOptions\": { \"target\": \"ES2020\", \"module\": \"ES2022\", \"moduleResolution\": \"bundler\", \"outDir\": \"./dist\", \"strict\": true, \"esModuleInterop\": true, \"skipLibCheck\": true, \"declaration\": true, \"noImplicitAny\": false, \"strictNullChecks\": false, \"allowJs\": true, \"resolveJsonModule\": true }, \"include\": \"src/ / \" , \"exclude\": \"node modules\", \"dist\", \"src/ tests \" } 证据：`tsconfig.json`\n- **Tsconfig.Test**（structured_config）：{ \"extends\": \"./tsconfig.json\", \"compilerOptions\": { \"noImplicitAny\": false, \"strictNullChecks\": false, \"types\": \"jest\", \"node\" }, \"include\": \"src/ / \", \"test/ / \", \"src/ tests / / \" } 证据：`tsconfig.test.json`\n- **Category**（structured_config）：{ \"label\": \"AI Courses to Learn\", \"position\": 6, \"collapsed\": false, \"link\": { \"type\": \"generated-index\", \"description\": \"AI Courses which helps you learn more on Using it for Testing and Development\" } } 证据：`docs/docs/ai-courses/_category_.json`\n- **Category**（structured_config）：{ \"label\": \"Local Development\", \"position\": 3, \"collapsed\": false, \"link\": { \"type\": \"generated-index\", \"description\": \"Understand how to setup Playwright MCP Server to run in your local machine.\" } } 证据：`docs/docs/local-setup/_category_.json`\n- **Category**（structured_config）：{ \"label\": \"Playwright API Features\", \"position\": 5, \"collapsed\": false, \"link\": { \"type\": \"generated-index\", \"description\": \"Supported features in Playwright API Testing.\" } } 证据：`docs/docs/playwright-api/_category_.json`\n- **Category**（structured_config）：{ \"label\": \"Playwright Web Features\", \"position\": 4, \"collapsed\": false, \"link\": { \"type\": \"generated-index\", \"description\": \"Supported features in Playwright Web browser automation.\" } } 证据：`docs/docs/playwright-web/_category_.json`\n- **Node modules - commented out to allow copying from host**（source_file）：Node modules - commented out to allow copying from host node modules npm-debug.log 证据：`.dockerignore`\n- **.gitattributes**（source_file）：package-lock.json linguist-generated=true 证据：`.gitattributes`\n- **Logs**（source_file）：Logs logs .log npm-debug.log yarn-debug.log yarn-error.log lerna-debug.log .pnpm-debug.log 证据：`.gitignore`\n- **Multi-stage Dockerfile for MCP Playwright Server**（source_file）：Multi-stage Dockerfile for MCP Playwright Server This Dockerfile expects the project to be built before running docker build Run npm install --omit=dev && npm run build before building the image 证据：`Dockerfile`\n- **!/bin/bash**（source_file）：!/bin/bash Build script for Docker image This ensures the project and dependencies are properly prepared 证据：`docker-build.sh`\n- **MCP servers communicate via stdio**（source_file）：services: playwright-mcp: build: context: . dockerfile: Dockerfile image: mcp-playwright:latest container name: playwright-mcp-server stdin open: true tty: true MCP servers communicate via stdio You can interact with this container using: docker compose run --rm playwright-mcp environment: Skip browser download in container - PLAYWRIGHT SKIP BROWSER DOWNLOAD=1 Optionally mount a volume for persistent data volumes: - ./data:/app/data 证据：`docker-compose.yml`\n- **Docusaurus.Config**（source_file）：import {themes as prismThemes} from 'prism-react-renderer'; import type {Config} from '@docusaurus/types'; import type as Preset from '@docusaurus/preset-classic'; 证据：`docs/docusaurus.config.ts`\n- **Sidebars**（source_file）：import type {SidebarsConfig} from '@docusaurus/plugin-content-docs'; 证据：`docs/sidebars.ts`\n- **Jest.Config**（source_file）：module.exports = { preset: 'ts-jest', testEnvironment: 'node', collectCoverage: true, coverageDirectory: 'coverage', coverageReporters: 'text', 'lcov' , collectCoverageFrom: 'src/ / .ts', '!src/index.ts', // exclude index.ts , testMatch: ' /src/ tests / / .test.ts' , modulePathIgnorePatterns: \" /docs/\", \" /dist/\" , moduleNameMapper: { \"^ . \\\\.js$\": \"$1\" }, transform: { '^.+\\\\.tsx?$': 'ts-jest', { useESM: true, tsconfig: 'tsconfig.test.json' } , }, extensionsToTreatAsEsm: '.ts' , moduleFileExtensions: 'ts', 'tsx', 'js', 'jsx', 'json', 'node' , }; 证据：`jest.config.cjs`\n- **Run Tests**（source_file）：const { execSync } = require 'child process' ; 证据：`run-tests.cjs`\n- **Run Tests**（source_file）：const { execSync } = require 'child process' ; 证据：`run-tests.js`\n- **!/usr/bin/env node**（source_file）：/ Script to list all available Playwright device descriptors Usage: node scripts/list-devices.js filter / 证据：`scripts/list-devices.cjs`\n- **Smithery configuration file: https://smithery.ai/docs/config smitheryyaml**（source_file）：Smithery configuration file: https://smithery.ai/docs/config smitheryyaml 证据：`smithery.yaml`\n- **!/usr/bin/env node**（source_file）：import express from 'express'; import { randomUUID } from 'node:crypto'; import { Server } from \"@modelcontextprotocol/sdk/server/index.js\"; import { SSEServerTransport } from \"@modelcontextprotocol/sdk/server/sse.js\"; import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js'; import { createToolDefinitions } from \"./tools.js\"; import { setupRequestHandlers } from \"./requestHandler.js\"; import { Logger, RequestLoggingMiddleware } from \"./logging/index.js\"; import { MonitoringSystem } from \"./monitoring/index.js\"; 证据：`src/http-server.ts`\n- **!/usr/bin/env node**（source_file）：import { Server } from \"@modelcontextprotocol/sdk/server/index.js\"; import { StdioServerTransport } from \"@modelcontextprotocol/sdk/server/stdio.js\"; import { createToolDefinitions } from \"./tools.js\"; import { setupRequestHandlers } from \"./requestHandler.js\"; import { Logger, RequestLoggingMiddleware } from \"./logging/index.js\"; import { MonitoringSystem } from \"./monitoring/index.js\"; import { startHttpServer } from \"./http-server.js\"; 证据：`src/index.ts`\n- **Requesthandler**（source_file）：import { Server } from \"@modelcontextprotocol/sdk/server/index.js\"; import { ListResourcesRequestSchema, ReadResourceRequestSchema, ListToolsRequestSchema, CallToolRequestSchema, Tool, McpError } from \"@modelcontextprotocol/sdk/types.js\"; import { handleToolCall, getConsoleLogs, getScreenshots } from \"./toolHandler.js\"; import { Logger, RequestLoggingMiddleware } from \"./logging/index.js\"; import { MonitoringSystem } from \"./monitoring/index.js\"; 证据：`src/requestHandler.ts`\n- **Toolhandler**（source_file）：import type { Browser, Page } from 'playwright'; import { chromium, firefox, webkit, request } from 'playwright'; import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; import { BROWSER TOOLS, API TOOLS } from './tools.js'; import type { ToolContext } from './tools/common/types.js'; import { ActionRecorder } from './tools/codegen/recorder.js'; import { spawn } from 'child process'; import { startCodegenSession, endCodegenSession, getCodegenSession, clearCodegenSession } from './tools/codegen/index.js'; import { ScreenshotTool, NavigationTool, CloseBrowserTool, ConsoleLogsTool, ExpectResponseTool, AssertResponseTool, CustomUserAgentTool, ResizeTool } from './tools/browser/… 证据：`src/toolHandler.ts`\n- **Tools**（source_file）：import type { Tool } from \"@modelcontextprotocol/sdk/types.js\"; import { codegenTools } from './tools/codegen'; 证据：`src/tools.ts`\n- **Types**（source_file）：import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'; 证据：`src/types.ts`\n- **Test Import**（source_file）：// test-import.js import { setupRequestHandlers } from './dist/requestHandler.js'; import { handleToolCall } from './dist/toolHandler.js'; 证据：`test-import.js`\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`README.md`, `docs/package.json`, `package.json`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`README.md`, `docs/package.json`, `package.json`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **Project Introduction**：importance `high`\n  - source_paths: README.md, package.json, CHANGELOG.md\n- **Getting Started**：importance `high`\n  - source_paths: README.md, mcp-config.json, DOCKER.md, Dockerfile\n- **Architecture Overview**：importance `high`\n  - source_paths: src/index.ts, src/toolHandler.ts, src/tools.ts, src/types.ts, src/requestHandler.ts\n- **Transport Modes**：importance `high`\n  - source_paths: src/index.ts, src/http-server.ts, src/sse/server.ts, src/sse/types.ts\n- **Browser Automation Tools**：importance `high`\n  - source_paths: src/tools/browser/index.ts, src/tools/browser/navigation.ts, src/tools/browser/interaction.ts, src/tools/browser/screenshot.ts, src/tools/browser/console.ts\n- **Device Emulation**：importance `medium`\n  - source_paths: src/tools/browser/resize.ts, scripts/list-devices.cjs\n- **API Testing Tools**：importance `medium`\n  - source_paths: src/tools/api/index.ts, src/tools/api/base.ts, src/tools/api/requests.ts\n- **Code Generation and Recording**：importance `medium`\n  - source_paths: src/tools/codegen/index.ts, src/tools/codegen/recorder.ts, src/tools/codegen/generator.ts, src/tools/codegen/types.ts\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `2349c2891e7c499c8c07b7d78c7f3fb4c797a1da`\n- inspected_files: `Dockerfile`, `package.json`, `README.md`, `docker-compose.yml`, `docs/package-lock.json`, `docs/package.json`, `docs/tsconfig.json`, `docs/sidebars.ts`, `docs/docusaurus.config.ts`, `docs/docs/intro.mdx`, `docs/docs/release.mdx`, `docs/src/pages/markdown-page.md`, `docs/docs/ai-courses/MachineLearning.mdx`, `docs/docs/ai-courses/_category_.json`, `docs/docs/ai-courses/GenAICourse.mdx`, `docs/docs/ai-courses/AIAgents.mdx`, `docs/docs/testing-videos/_category_.json`, `docs/docs/testing-videos/Bdd.mdx`, `docs/docs/testing-videos/AIAgents.mdx`, `docs/docs/local-setup/_category_.json`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 来源证据：Playwright is asking for an specific browser version.\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Playwright is asking for an specific browser version.\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_38465ac94a9d4fb0bd352ba5209096ac | https://github.com/executeautomation/mcp-playwright/issues/117 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 来源证据：How to configure proxy and storageState when launching browser in Playwright MCP?\n\n- Trigger: GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：How to configure proxy and storageState when launching browser in Playwright MCP?\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响授权、密钥配置或安全边界。\n- Evidence: community_evidence:github | cevd_a2f7e4a410994d4195a9af9f139e0caa | https://github.com/executeautomation/mcp-playwright/issues/203 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 可能修改宿主 AI 配置\n\n- Trigger: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- Host AI rule: 列出会写入的配置文件、目录和卸载/回滚步骤。\n- Why it matters: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- Evidence: capability.host_targets | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | host_targets=mcp_host, claude, cursor\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 来源证据：Add Clarvia AEO score badge to README (AEO 32/100)\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Add Clarvia AEO score badge to README (AEO 32/100)\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_74959d07d5f74165bcd9cae829d384ce | https://github.com/executeautomation/mcp-playwright/issues/212 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 来源证据：Add policy enforcement for browser automation and HTTP request tools\n\n- Trigger: GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Add policy enforcement for browser automation and HTTP request tools\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_23a30d245f794b8db40c1d031b8be565 | https://github.com/executeautomation/mcp-playwright/issues/216 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | README/documentation is current enough for a first validation pass.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 来源证据：How to pass in the `--ignore-https-errors` parameter?\n\n- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：How to pass in the `--ignore-https-errors` parameter?\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_47d5e333819d49b4b8ce2abb9484b23d | https://github.com/executeautomation/mcp-playwright/issues/202 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 维护活跃度未知\n\n- Trigger: 未记录 last_activity_observed。\n- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Evidence: evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | last_activity_observed missing\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 9: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 10: 存在安全注意事项\n\n- Trigger: No sandbox install has been executed yet; downstream must verify before user use.\n- Host AI rule: 转成明确权限清单和安全审查提示。\n- Why it matters: 用户安装前需要知道权限边界和敏感操作。\n- Evidence: risks.safety_notes | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | No sandbox install has been executed yet; downstream must verify before user use.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：executeautomation/mcp-playwright\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：mcp_host, claude, cursor\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 来源证据：Playwright is asking for an specific browser version.（high）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：How to configure proxy and storageState when launching browser in Playwright MCP?（high）：可能影响授权、密钥配置或安全边界。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 可能修改宿主 AI 配置（medium）：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 来源证据：Add Clarvia AEO score badge to README (AEO 32/100)（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Add policy enforcement for browser automation and HTTP request tools（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/executeautomation/mcp-playwright 项目说明书\n\n生成时间：2026-05-15 13:16:39 UTC\n\n## 目录\n\n- [Project Introduction](#project-introduction)\n- [Getting Started](#getting-started)\n- [Architecture Overview](#architecture-overview)\n- [Transport Modes](#transport-modes)\n- [Browser Automation Tools](#browser-automation)\n- [Device Emulation](#device-emulation)\n- [API Testing Tools](#api-testing)\n- [Code Generation and Recording](#code-generation)\n- [Docker Deployment](#docker-deployment)\n- [Configuration Guide](#configuration)\n\n<a id='project-introduction'></a>\n\n## Project Introduction\n\n### 相关页面\n\n相关主题：[Getting Started](#getting-started), [Architecture Overview](#architecture-overview)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)\n- [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)\n</details>\n\n# Project Introduction\n\nThe **Playwright MCP Server** (`mcp-playwright`) is a Model Context Protocol (MCP) server implementation that provides browser automation capabilities through Playwright. It enables AI assistants like Claude, Cursor, and other MCP-compatible clients to interact with web pages through a standardized tool interface.\n\n## Overview\n\nThe project serves as a bridge between AI assistants and browser automation, exposing Playwright's browser control capabilities as MCP tools. This allows AI agents to perform web navigation, content extraction, form interactions, and other browser-related tasks using natural language commands.\n\n**Key Characteristics:**\n\n| Attribute | Value |\n|-----------|-------|\n| Project Name | mcp-playwright |\n| Package Name | @executeautomation/playwright-mcp-server |\n| License | MIT |\n| Node.js Version | 20+ |\n| Protocol | Model Context Protocol (MCP) |\n\n资料来源：[package.json:1-20]()\n\n## Architecture\n\nThe server follows a client-server architecture where AI assistants act as MCP clients communicating with the Playwright MCP server.\n\n```mermaid\ngraph TD\n    A[\"AI Assistant<br/>(Claude, Cursor, etc.)\"] -->|MCP Protocol| B[\"Playwright MCP Server\"]\n    B -->|stdin/stdout| A\n    B -->|HTTP/SSE| B\n    C[\"Browser Instances<br/>(Chromium, Firefox, WebKit)\"] -->|Playwright API| B\n    \n    B -->|Browser Automation| C\n    C -->|Page Content| B\n    B -->|Tool Results| A\n```\n\n### Core Components\n\n| Component | Purpose |\n|-----------|---------|\n| MCP SDK | Handles MCP protocol communication |\n| Tool Handlers | Processes tool calls and executes Playwright operations |\n| Browser Manager | Manages browser lifecycle and instances |\n| Logging System | Captures request/response data and error tracking |\n\n资料来源：[src/logging/middleware.ts:1-20]()\n\n## Installation Methods\n\nThe project supports multiple installation approaches to accommodate different deployment scenarios.\n\n### Package Managers\n\n```bash\n# npm\nnpm install -g @executeautomation/playwright-mcp-server\n\n# mcp-get\nnpx @michaellatman/mcp-get@latest install @executeautomation/playwright-mcp-server\n\n# Smithery (automated)\nnpx @smithery/cli install @executeautomation/playwright-mcp-server --client claude\n```\n\n### Claude Code\n\n```bash\nclaude mcp add --transport stdio playwright npx @executeautomation/playwright-mcp-server\n```\n\n资料来源：[README.md:40-65]()\n\n## Operation Modes\n\nThe server supports two primary operation modes based on the transport mechanism.\n\n### STDIO Mode (Default)\n\nSTDIO mode is the recommended configuration for Claude Desktop and other clients that communicate via standard input/output streams.\n\n```mermaid\ngraph LR\n    A[\"MCP Client\"] -->|\"stdio\"| B[\"Playwright MCP Server\"]\n    B -->|\"stdio\"| A\n    C[\"Playwright<br/>Browser\"] -->|Control| B\n```\n\n**Configuration Example:**\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n    }\n  }\n}\n```\n\n> **Note:** In stdio mode, logging is automatically directed to files only to maintain clean JSON-RPC communication. Logs are written to `~/playwright-mcp-server.log`.\n\n资料来源：[README.md:20-30]()\n\n### HTTP Mode (Standalone Server)\n\nHTTP mode enables the server to run as a standalone HTTP server, suitable for VS Code, custom clients, and remote deployments.\n\n```bash\nnpx @executeautomation/playwright-mcp-server --port 8931\n```\n\n**Available Endpoints:**\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/sse` | GET | SSE Stream for server-sent events |\n| `/messages?sessionId=<id>` | POST | Send messages to a session |\n| `/mcp` | GET/POST | Unified MCP protocol endpoint |\n| `/health` | GET | Health check endpoint |\n\n**Client Configuration:**\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"url\": \"http://localhost:8931/mcp\"\n    }\n  }\n}\n```\n\n资料来源：[README.md:35-55]()\n资料来源：[examples/http-mode-example.md:1-30]()\n\n## Docker Deployment\n\nThe project provides official Docker images for containerized deployments.\n\n### Basic Usage\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n### Docker Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright-docker\": {\n      \"command\": \"docker\",\n      \"args\": [\"run\", \"-i\", \"--rm\", \"mcp-playwright:latest\"]\n    }\n  }\n}\n```\n\n### Environment Variables\n\n| Variable | Purpose | Default |\n|----------|---------|---------|\n| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser installation | 1 |\n| `NODE_ENV` | Node environment | production |\n\n### Volume Mounts\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  -v $(screenshots):/app/screenshots \\\n  mcp-playwright:latest\n```\n\n> **Note:** The Docker image skips browser downloads by default to reduce size (~200MB). Browsers are downloaded on first use.\n\n资料来源：[DOCKER.md:1-80]()\n\n## Supported Tools\n\nThe server exposes a comprehensive set of Playwright operations as MCP tools.\n\n### Browser Control Tools\n\n| Tool Category | Tools | Description |\n|---------------|-------|-------------|\n| Navigation | `playwright_navigate` | Navigate to URLs with multi-browser support |\n| Interaction | `playwright_click`, `playwright_drag`, `playwright_press_key` | Element interactions |\n| Content | `playwright_get_visible_text`, `playwright_get_visible_html` | Content extraction |\n| Output | `playwright_save_as_pdf` | Page to PDF conversion |\n\n### Browser Support\n\n| Browser | Support |\n|---------|---------|\n| Chromium | ✅ Default |\n| Firefox | ✅ Since v1.0.2 |\n| WebKit | ✅ Since v1.0.2 |\n\n资料来源：[CHANGELOG.md:1-30]()\n\n## Dependencies\n\n### Production Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | 1.24.3 | MCP protocol implementation |\n| `playwright` | 1.57.0 | Browser automation framework |\n| `@playwright/browser-chromium` | 1.57.0 | Chromium browser |\n| `@playwright/browser-firefox` | 1.57.0 | Firefox browser |\n| `@playwright/browser-webkit` | 1.57.0 | WebKit browser |\n| `express` | ^4.21.1 | HTTP server for HTTP mode |\n| `cors` | ^2.8.5 | Cross-origin resource sharing |\n| `uuid` | 11.1.0 | Session ID generation |\n| `mcp-evals` | ^2.0.1 | Evaluation utilities |\n\n### Development Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `typescript` | ^5.8.3 | TypeScript compilation |\n| `jest` | ^29.7.0 | Testing framework |\n| `jest-playwright-preset` | 4.0.0 | Playwright test integration |\n| `ts-jest` | ^29.2.6 | TypeScript Jest transformer |\n\n资料来源：[package.json:20-50]()\n\n## Logging System\n\nThe server includes a comprehensive logging system for debugging and monitoring.\n\n### Log Location\n\n- **STDIO Mode:** `~/playwright-mcp-server.log` (file only)\n- **HTTP Mode:** Configurable via server settings\n\n### Log Features\n\n| Feature | Description |\n|---------|-------------|\n| Request Logging | Captures tool execution with sanitized arguments |\n| Error Context | Includes stack traces and browser state |\n| Log Rotation | Automatic rotation with configurable max files |\n| Sensitive Data Redaction | Passwords, tokens, and secrets automatically masked |\n\n资料来源：[src/logging/logger.ts:1-50]()\n资料来源：[src/logging/middleware.ts:1-30]()\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue | Solution |\n|-------|----------|\n| Container exits immediately | Ensure `-i` flag is used for Docker |\n| Browser not found | Use custom Dockerfile with `npx playwright install` |\n| Permission issues | Use `--user $(id -u):$(id -g)` flag |\n| Tool name too long | Keep names under 60 characters (server + tool name) |\n\n> **Important:** When adding new tools, ensure tool names are short enough to not exceed the 60-character limit for combined server and tool name (`server_name:tool_name`). The server name is `playwright-mcp`.\n\n资料来源：[README.md:15-18]()\n\n## Version History\n\n| Version | Date | Key Changes |\n|---------|------|-------------|\n| 1.0.8 | Current | Latest stable release |\n| 1.0.7 | 2024-12 | Advanced screenshot and content tools |\n| 1.0.2 | 2024-11-10 | Multi-browser support (Firefox, WebKit) |\n| 1.0.0 | 2024-11-01 | First major release with Bearer Auth support |\n\n资料来源：[CHANGELOG.md:1-50]()\n\n## Next Steps\n\nFor more detailed information, refer to:\n\n- [Installation Guide](https://executeautomation.github.io/mcp-playwright/) - Detailed setup instructions\n- [API Reference](https://executeautomation.github.io/mcp-playwright/docs/playwright-web/Supported-Tools) - Complete tool documentation\n- [Device Quick Reference](https://executeautomation.github.io/mcp-playwright/docs/playwright-web/Device-Quick-Reference) - Mobile device emulation\n- [Prompt Guide](https://executeautomation.github.io/mcp-playwright/docs/playwright-web/Resize-Prompts-Guide) - Resize prompt strategies\n\n---\n\n<a id='getting-started'></a>\n\n## Getting Started\n\n### 相关页面\n\n相关主题：[Project Introduction](#project-introduction), [Docker Deployment](#docker-deployment), [Configuration Guide](#configuration)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)\n- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)\n- [src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)\n- [src/logging/logger.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/logger.ts)\n</details>\n\n# Getting Started\n\nThis guide provides everything you need to install, configure, and run the Playwright MCP Server. The server enables AI assistants like Claude to interact with web browsers through a comprehensive set of automation tools.\n\n## Overview\n\nThe Playwright MCP Server is a Model Context Protocol (MCP) server that provides programmatic control over Playwright browsers. It allows AI assistants to perform web automation tasks including navigation, interaction, content extraction, and screenshot capture.\n\n**Key Features:**\n- Multi-browser support (Chromium, Firefox, WebKit)\n- 143 device presets for mobile emulation\n- Screenshot and PDF generation\n- Web scraping and content extraction\n- Keyboard and mouse automation\n- HTTP and stdio communication modes\n\n资料来源：[README.md:1-45]()\n\n## Prerequisites\n\nBefore installing the Playwright MCP Server, ensure your system meets these requirements:\n\n| Requirement | Minimum Version | Notes |\n|-------------|-----------------|-------|\n| Node.js | 20.x or higher | LTS recommended |\n| npm | 9.x or higher | Comes with Node.js |\n| Docker (optional) | 20.x or higher | For containerized deployment |\n| Playwright browsers | Latest | Auto-installed on first use |\n\n**System Dependencies for Playwright:**\n- Linux: `npx playwright install-deps`\n- macOS: Xcode Command Line Tools\n- Windows: Visual Studio Build Tools\n\n资料来源：[package.json:23-36]()\n\n## Installation Methods\n\n### Method 1: npm Package (Recommended)\n\nInstall the package globally for CLI access:\n\n```bash\nnpm install -g @executeautomation/playwright-mcp-server\n```\n\nOr use it directly with npx (no installation required):\n\n```bash\nnpx -y @executeautomation/playwright-mcp-server\n```\n\n资料来源：[README.md:56-65]()\n\n### Method 2: Docker Container\n\nPull the pre-built image from Docker Hub:\n\n```bash\ndocker pull mcp-playwright:latest\n```\n\nOr build from source:\n\n```bash\ngit clone https://github.com/executeautomation/mcp-playwright.git\ncd mcp-playwright\ndocker build -t mcp-playwright:latest .\n```\n\nThe Docker image is approximately 200MB (without browsers) and uses a Debian-based slim Node.js image.\n\n资料来源：[DOCKER.md:80-100]()\n\n## Configuration\n\n### Claude Desktop\n\nEdit your Claude Desktop configuration file:\n\n**File Locations:**\n| OS | Path |\n|----|------|\n| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |\n| Windows | `%APPDATA%\\Claude\\claude_desktop_config.json` |\n| Linux | `~/.config/Claude/claude_desktop_config.json` |\n\n**stdio Mode (Default):**\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n    }\n  }\n}\n```\n\n资料来源：[README.md:56-65]()\n\n### VS Code MCP Extension\n\nFor VS Code with the MCP extension, add this to your MCP settings:\n\n```json\n{\n  \"name\": \"playwright\",\n  \"command\": \"npx\",\n  \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n}\n```\n\n资料来源：[DOCKER.md:12-20]()\n\n### Docker Configuration\n\n**Basic Configuration:**\n```json\n{\n  \"mcpServers\": {\n    \"playwright-docker\": {\n      \"command\": \"docker\",\n      \"args\": [\"run\", \"-i\", \"--rm\", \"mcp-playwright:latest\"]\n    }\n  }\n}\n```\n\n**With Environment Variables:**\n```bash\ndocker run -i --rm \\\n  -e PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \\\n  -e NODE_ENV=production \\\n  mcp-playwright:latest\n```\n\n**With Volume Mounts:**\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  -v $(pwd)/screenshots:/app/screenshots \\\n  mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:1-50]()\n\n## Running Modes\n\n### stdio Mode (Interactive)\n\nThe default mode for Claude Desktop where the server communicates via stdin/stdout:\n\n```bash\n# Using npx\nnpx -y @executeautomation/playwright-mcp-server\n\n# Using global installation\nplaywright-mcp-server\n```\n\nIn stdio mode, logs are automatically directed to files only (`~/playwright-mcp-server.log`) to maintain clean JSON-RPC communication.\n\n资料来源：[README.md:56-65]()\n\n### HTTP Mode (Standalone Server)\n\nFor VS Code, custom clients, or remote deployments where you need a headed browser:\n\n```bash\n# Using npx\nnpx @executeautomation/playwright-mcp-server --port 8931\n\n# Using global installation\nplaywright-mcp-server --port 8931\n```\n\n**HTTP Mode Endpoints:**\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/sse` | GET | SSE stream for server-sent events |\n| `/messages` | POST | Send messages (requires `sessionId` query param) |\n| `/mcp` | GET/POST | Unified MCP endpoint |\n| `/health` | GET | Health check |\n\n**Security Note:** The HTTP server binds to `localhost` only (127.0.0.1) to prevent external access. For remote access, use SSH tunneling.\n\n资料来源：[README.md:67-90]()\n资料来源：[src/http-server.ts:1-50]()\n\n**Claude Desktop HTTP Configuration:**\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"url\": \"http://localhost:8931/mcp\"\n    }\n  }\n}\n```\n\n资料来源：[examples/http-mode-example.md:1-30]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    subgraph \"AI Assistant\"\n        A[Claude / Cursor / VS Code]\n    end\n    \n    subgraph \"MCP Client\"\n        B[MCP SDK Client]\n    end\n    \n    subgraph \"Playwright MCP Server\"\n        C[Transport Layer]\n        D[Tool Handlers]\n        E[Browser Manager]\n    end\n    \n    subgraph \"Playwright\"\n        F[Chromium]\n        G[Firefox]\n        H[WebKit]\n    end\n    \n    A --> B\n    B --> C\n    C --> D\n    D --> E\n    E --> F\n    E --> G\n    E --> H\n```\n\n## Available Tools\n\nThe server exposes the following tool categories:\n\n### Navigation Tools\n| Tool | Description |\n|------|-------------|\n| `playwright_navigate` | Navigate to a URL with optional browser type |\n| `playwright_go_back` | Navigate backward in history |\n| `playwright_go_forward` | Navigate forward in history |\n\n### Interaction Tools\n| Tool | Description |\n|------|-------------|\n| `playwright_click` | Click on an element |\n| `playwright_fill` | Fill input fields |\n| `playwright_press_key` | Press keyboard keys |\n| `playwright_drag` | Drag elements |\n\n### Content Tools\n| Tool | Description |\n|------|-------------|\n| `playwright_get_visible_text` | Extract visible text |\n| `playwright_get_visible_html` | Get HTML content with filtering options |\n| `playwright_evaluate` | Execute JavaScript in browser context |\n\n### Output Tools\n| Tool | Description |\n|------|-------------|\n| `playwright_screenshot` | Capture page screenshots |\n| `playwright_save_as_pdf` | Save page as PDF |\n\n### Device Emulation\n```javascript\n// Test on iPhone 13\nawait playwright_resize({ device: \"iPhone 13\" });\n\n// Test on iPad with landscape\nawait playwright_resize({ device: \"iPad Pro 11\", orientation: \"landscape\" });\n\n// Test desktop\nawait playwright_resize({ device: \"Desktop Chrome\" });\n```\n\n资料来源：[README.md:25-50]()\n资料来源：[CHANGELOG.md:1-30]()\n\n## First Steps\n\n### 1. Verify Installation\n\nAfter configuration, restart your AI client and verify the server is connected:\n\n```\nHealth check endpoint (HTTP mode):\ncurl http://localhost:8931/health\n```\n\nExpected response:\n```json\n{\n  \"status\": \"ok\",\n  \"version\": \"1.0.10\",\n  \"activeSessions\": 0\n}\n```\n\n资料来源：[src/http-server.ts:40-48]()\n\n### 2. Basic Browser Operations\n\nOnce connected, you can use natural language to control the browser:\n\n```\n\"Navigate to https://example.com\"\n\"Take a screenshot\"\n\"Click on the login button\"\n\"Fill in the search box with 'test'\"\n\"Get the page title\"\n```\n\n### 3. Device Emulation\n\nTest responsive designs:\n\n```\n\"Test on iPhone 13\"\n\"Switch to iPad Pro view\"\n\"Rotate to landscape\"\n```\n\n资料来源：[README.md:30-45]()\n\n## Troubleshooting\n\n### Container Exits Immediately\n\nMCP servers wait for input on stdin. Ensure you're running with the `-i` flag:\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:55-60]()\n\n### Browser Not Found\n\nThe Docker image skips browser downloads by default. Create a custom Dockerfile:\n\n```dockerfile\nFROM mcp-playwright:latest\nRUN npx playwright install chromium --with-deps\n```\n\n资料来源：[DOCKER.md:65-72]()\n\n### Permission Issues with Volumes\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  --user $(id -u):$(id -g) \\\n  mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:75-82]()\n\n### Connection Issues (HTTP Mode)\n\n| Problem | Solution |\n|---------|----------|\n| Server not starting | Check if port 8931 is available |\n| External access blocked | By design - server binds to localhost only |\n| Remote access needed | Use SSH tunneling: `ssh -L 8931:localhost:8931 user@remote` |\n\n资料来源：[README.md:103-110]()\n\n## Logging\n\nThe server includes comprehensive logging for debugging:\n\n**Log File Location (stdio mode):**\n```\n~/playwright-mcp-server.log\n```\n\n**Logged Information:**\n- Tool execution requests and responses\n- Error categorization (validation, system, resource)\n- Request duration metrics\n- Memory and uptime statistics\n\nThe logger captures:\n- Request IDs for traceability\n- Sanitized request bodies (sensitive fields redacted)\n- Stack traces for errors\n- Platform and environment information\n\n资料来源：[src/logging/logger.ts:1-50]()\n资料来源：[src/logging/middleware.ts:1-80]()\n\n## Testing\n\nRun the test suite to verify your installation:\n\n```bash\n# Run tests\nnpm test\n\n# Run tests with coverage\nnpm run test:coverage\n\n# Run custom tests\nnpm run test:custom\n```\n\nTests are located in `src/__tests__` and use Jest with Playwright preset.\n\n资料来源：[README.md:113-125]()\n\n## Resource Limits (Docker)\n\nLimit CPU and memory usage:\n\n```bash\ndocker run -i --rm \\\n  --cpus=\"2.0\" \\\n  --memory=\"2g\" \\\n  mcp-playwright:latest\n```\n\nOr in docker-compose.yml:\n\n```yaml\nservices:\n  playwright-mcp:\n    deploy:\n      resources:\n        limits:\n          cpus: '2.0'\n          memory: 2G\n```\n\n资料来源：[DOCKER.md:115-130]()\n\n## Next Steps\n\n| Topic | Description |\n|-------|-------------|\n| [Device Emulation](docs/playwright-web/Device-Quick-Reference) | Full list of 143 device presets |\n| [Docker Deployment](DOCKER.md) | Advanced Docker configuration |\n| [HTTP Mode](examples/http-mode-example.md) | Standalone server setup |\n| [API Reference](https://executeautomation.github.io/mcp-playwright/) | Complete tool documentation |\n\n---\n\n<a id='architecture-overview'></a>\n\n## Architecture Overview\n\n### 相关页面\n\n相关主题：[Project Introduction](#project-introduction), [Transport Modes](#transport-modes), [Browser Automation Tools](#browser-automation)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/index.ts)\n- [src/toolHandler.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/toolHandler.ts)\n- [src/tools.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools.ts)\n- [src/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/types.ts)\n- [src/requestHandler.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/requestHandler.ts)\n</details>\n\n# Architecture Overview\n\n## Introduction\n\nThe mcp-playwright project is a Model Context Protocol (MCP) server that exposes Playwright browser automation capabilities to AI assistants such as Claude. The architecture follows a modular, tool-based design pattern where each browser automation operation is exposed as a discrete tool that MCP clients can invoke through JSON-RPC calls.\n\nThe server is designed to operate in two distinct transport modes: **stdio mode** for direct integration with MCP clients like Claude Desktop, and **HTTP mode** for remote deployments, VS Code integration, or headless browser scenarios. This dual-mode architecture provides flexibility while maintaining a consistent internal structure for tool registration, execution, and logging.\n\n资料来源：[README.md:1-20](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n## High-Level Architecture\n\nThe architecture consists of four primary layers that work together to process tool requests and execute browser automation tasks.\n\n```mermaid\ngraph TD\n    A[MCP Client<br/>Claude Desktop / VS Code] --> B[Transport Layer<br/>stdio or HTTP]\n    B --> C[Request Handler<br/>requestHandler.ts]\n    C --> D[Tool Handler<br/>toolHandler.ts]\n    D --> E[Tool Registry<br/>tools.ts]\n    E --> F[Browser Tools<br/>playwright API]\n    F --> G[Chromium / Firefox / WebKit]\n```\n\nThe **Transport Layer** handles the communication protocol, converting between the client's transport mechanism and the internal request format. The **Request Handler** validates and routes incoming requests to the appropriate tool. The **Tool Handler** manages tool execution, error handling, and response formatting. Finally, the **Browser Tools** layer wraps the Playwright API to provide browser automation capabilities.\n\n资料来源：[src/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/index.ts)\n\n## Core Data Structures\n\nThe type system defines the fundamental interfaces used throughout the codebase. These types establish the contract between components and ensure type safety across the architecture.\n\n资料来源：[src/types.ts:1-17](https://github.com/executeautomation/mcp-playwright/blob/main/src/types.ts)\n\n### Tool Interface\n\n```typescript\nexport interface Tool {\n  name: string;\n  description: string;\n  parameters: {\n    type: string;\n    properties: Record<string, unknown>;\n    required?: string[];\n  };\n  handler: (args: any) => Promise<any>;\n}\n```\n\nThe `Tool` interface represents a single automation capability exposed to MCP clients. Each tool contains a unique `name` identifier, a human-readable `description`, a JSON Schema-compatible `parameters` definition, and an asynchronous `handler` function that executes the actual automation logic.\n\n### ToolCall Interface\n\n```typescript\nexport interface ToolCall {\n  name: string;\n  parameters: Record<string, unknown>;\n  result?: CallToolResult;\n}\n```\n\nThe `ToolCall` interface tracks the lifecycle of a tool invocation, capturing the tool name, input parameters, and the computed result.\n\n## Request Processing Pipeline\n\nThe request processing pipeline transforms incoming MCP requests into executed browser automation operations.\n\n```mermaid\ngraph LR\n    A[Incoming Request] --> B[Parse & Validate]\n    B --> C[Route to Tool Handler]\n    C --> D[Execute Tool Handler]\n    D --> E{Check Result}\n    E -->|Success| F[Return CallToolResult]\n    E -->|Error| G[Log Error Context]\n    G --> H[Return Error Response]\n```\n\n### Request Handler Component\n\nThe request handler acts as the entry point for all incoming requests. It is responsible for parsing the incoming JSON-RPC messages, validating the request structure, and delegating to the appropriate tool handler.\n\n资料来源：[src/requestHandler.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/requestHandler.ts)\n\n## Tool Registration and Management\n\nThe tool registry maintains a collection of all available automation tools. New tools are registered through the `BROWSER_TOOLS` array, which contains all browser-related automation operations.\n\n```mermaid\ngraph TD\n    A[Tool Definition<br/>src/tools/browser/*.ts] --> B[BROWSER_TOOLS Array]\n    B --> C[Tool Handler Registration]\n    C --> D[MCP Server<br/>Tool List]\n```\n\n### Tool Handler\n\nThe tool handler manages the execution context for all tools. It provides the following capabilities:\n\n| Capability | Description |\n|------------|-------------|\n| Tool Registration | Registers tools with the MCP SDK |\n| Execution Context | Provides shared state between tool invocations |\n| Error Handling | Catches and formats errors from tool execution |\n| Logging Integration | Integrates with the logging middleware for observability |\n\n资料来源：[src/toolHandler.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/toolHandler.ts)\n\n### Available Tool Categories\n\nThe tools are organized into logical categories based on their function:\n\n| Category | Tools | Purpose |\n|----------|-------|---------|\n| Navigation | `playwright_navigate`, `playwright_go_back`, `playwright_reload` | Page navigation and history |\n| Interaction | `playwright_click`, `playwright_fill`, `playwright_hover`, `playwright_drag` | User interaction simulation |\n| Content Extraction | `playwright_get_visible_text`, `playwright_get_visible_html` | Content retrieval |\n| Output | `playwright_screenshot`, `playwright_save_as_pdf` | Visual output generation |\n| Emulation | `playwright_resize` | Device emulation with 143 presets |\n\n资料来源：[CHANGELOG.md:1-30](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n\n## Logging and Observability\n\nThe logging middleware provides comprehensive observability into tool execution. It captures request context, execution duration, error details, and system metrics.\n\n```mermaid\ngraph TD\n    A[Tool Execution Start] --> B[Generate Request ID]\n    B --> C[Log Request Start]\n    C --> D[Execute Handler]\n    D --> E{Result Type}\n    E -->|Success| F[Log Success<br/>Duration: Xms]\n    E -->|Error| G[Capture Error Context]\n    G --> H[Categorize Error]\n    H --> I[Log Error<br/>with Stack Trace]\n```\n\n### Error Categorization\n\nThe middleware categorizes errors into distinct types for better debugging and monitoring:\n\n| Category | Triggers | Example Messages |\n|----------|----------|-------------------|\n| `validation` | Invalid parameters | \"invalid\", \"required\", \"missing parameter\" |\n| `resource` | Browser/page issues | \"closed\", \"disconnected\", \"protocol error\" |\n| `authentication` | Auth failures | \"unauthorized\", \"forbidden\", \"access denied\" |\n| `rate_limit` | Rate limiting | \"rate limit\", \"too many requests\" |\n| `system` | Timeout/element errors | \"timeout\", \"element not found\", \"navigation\" |\n\n资料来源：[src/logging/middleware.ts:80-120](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n### Request Sanitization\n\nThe logging middleware automatically sanitizes sensitive data from tool arguments before logging:\n\n| Field Pattern | Sanitization |\n|---------------|--------------|\n| `password`, `token`, `secret`, `key`, `auth` | Replaced with `[REDACTED]` |\n| Request bodies > 1000 characters | Truncated with character count |\n\n资料来源：[src/logging/middleware.ts:150-170](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n## Transport Modes\n\n### stdio Mode\n\nIn stdio mode, the server communicates over standard input and output streams. This mode is designed for direct integration with MCP clients like Claude Desktop.\n\n| Aspect | Configuration |\n|--------|---------------|\n| Launch Command | `npx -y @executeautomation/playwright-mcp-server` |\n| Log Output | File only (`~/playwright-mcp-server.log`) |\n| JSON-RPC | stdin/stdout streaming |\n\n资料来源：[README.md:30-45](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n### HTTP Mode\n\nHTTP mode exposes the server as a standalone HTTP server with multiple endpoints:\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/sse` | GET | Server-Sent Events stream |\n| `/messages` | POST | Send messages with session ID |\n| `/mcp` | GET/POST | Unified MCP protocol endpoint |\n| `/health` | GET | Health check |\n\nThe default port is `8931`, configurable via the `--port` flag.\n\n资料来源：[README.md:55-70](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n```mermaid\ngraph LR\n    A[MCP Client] -->|HTTP POST /mcp| B[HTTP Server]\n    B --> C[Request Handler]\n    C --> D[Tool Handler]\n    D --> E[Browser Automation]\n    E --> F[Response]\n    F --> B\n    B --> A\n```\n\n## Browser Context Management\n\nThe architecture supports multiple browser engines:\n\n| Browser | Package | Default |\n|---------|---------|---------|\n| Chromium | `@playwright/browser-chromium` | Yes |\n| Firefox | `@playwright/browser-firefox` | No |\n| WebKit | `@playwright/browser-webkit` | No |\n\nThe `browserType` parameter in `playwright_navigate` allows selection of the browser engine:\n\n```javascript\nawait playwright_navigate({ \n  url: \"https://example.com\",\n  browserType: \"firefox\"  // chromium, firefox, or webkit\n});\n```\n\n资料来源：[CHANGELOG.md:15-20](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n\n## Deployment Architecture\n\n### Docker Deployment\n\nThe Docker deployment provides a containerized environment for the MCP server:\n\n```mermaid\ngraph TD\n    A[Docker Host] --> B[mcp-playwright:latest]\n    B --> C[Node.js Runtime]\n    C --> D[MCP Server]\n    D --> E[Playwright Browsers]\n    E --> F[Chromium<br/>Firefox<br/>WebKit]\n```\n\nThe Docker image is optimized for size (~200MB without browsers) and supports environment variable configuration:\n\n| Variable | Purpose | Default |\n|----------|---------|---------|\n| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser installation | 1 |\n| `NODE_ENV` | Node environment | production |\n\n资料来源：[DOCKER.md:40-60](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Claude Desktop Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n    }\n  }\n}\n```\n\nFor HTTP mode with remote deployments:\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"url\": \"http://localhost:8931/mcp\"\n    }\n  }\n}\n```\n\n资料来源：[README.md:35-40](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n---\n\n<a id='transport-modes'></a>\n\n## Transport Modes\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Configuration Guide](#configuration)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/index.ts)\n- [src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)\n- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)\n- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n- [src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)\n</details>\n\n# Transport Modes\n\nThe mcp-playwright server supports two distinct transport modes for communicating with MCP clients: **STDIO Transport** and **HTTP/SSE Transport**. Each mode serves different deployment scenarios and client requirements.\n\n## Overview\n\nThe transport mode determines how the MCP protocol messages are exchanged between the Playwright MCP server and connected clients. The server automatically detects the appropriate mode based on command-line arguments or environment configuration.\n\n| Transport Mode | Use Case | Default Port | Security |\n|----------------|----------|--------------|----------|\n| STDIO | Local MCP clients (Claude Desktop, Cursor) | N/A | Process-bound |\n| HTTP/SSE | Remote clients, headed browsers, IDE integrations | 8931 | Localhost only |\n\n## STDIO Transport Mode\n\n### Purpose and Architecture\n\nSTDIO (Standard Input/Output) is the default transport mode for MCP servers. It provides process-based communication where messages are exchanged through the parent process's standard input and output streams.\n\n```mermaid\ngraph LR\n    A[MCP Client<br/>Claude Desktop] <-->|stdin/stdout pipes| B[playwright-mcp-server<br/>STDIO Mode]\n    B <-->|Playwright API| C[Browser Instance]\n```\n\n### How STDIO Mode Works\n\n1. The MCP client spawns the server as a child process\n2. JSON-RPC messages are sent via process stdin\n3. Responses are received via process stdout\n4. The server runs in headless mode by default\n5. Logging is automatically redirected to `~/playwright-mcp-server.log`\n\n资料来源：[README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n### Configuration for Claude Desktop\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n    }\n  }\n}\n```\n\n资料来源：[README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n### Docker Considerations\n\nWhen running in Docker containers, STDIO mode requires the `-i` flag to keep STDIN open for interactive communication:\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n| Docker Flag | Purpose |\n|-------------|---------|\n| `-i` | Keep STDIN open for interactive communication |\n| `--rm` | Automatically remove container when it exits |\n\n资料来源：[DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## HTTP/SSE Transport Mode\n\n### Purpose and Architecture\n\nHTTP/SSE transport runs the MCP server as a standalone HTTP server. This mode is designed for scenarios where STDIO communication is impractical, such as:\n\n- Running headed browsers on headless systems\n- Integration with IDE worker processes\n- Remote client access via HTTP\n- Multi-client concurrent connections\n\n```mermaid\ngraph TD\n    A[MCP Client<br/>VS Code / Custom] -->|HTTP/REST| B[HTTP Server<br/>127.0.0.1:8931]\n    B --> C[SSE Transport<br/>Server-Sent Events]\n    B --> D[Message Handler<br/>POST /messages]\n    C --> E[Session Manager]\n    D --> E\n    E --> F[Playwright MCP<br/>Tool Handler]\n    F --> G[Browser Instance]\n```\n\n### Available Endpoints\n\nThe HTTP server exposes the following endpoints:\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/sse` | GET | Server-Sent Events stream for push notifications |\n| `/messages?sessionId=<id>` | POST | Send JSON-RPC messages for a specific session |\n| `/mcp` | GET | MCP unified endpoint (GET) |\n| `/mcp?sessionId=<id>` | POST | MCP unified endpoint (POST) |\n| `/health` | GET | Health check endpoint |\n\n资料来源：[src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)\n\n### Starting the HTTP Server\n\n```bash\n# Using npx\nnpx @executeautomation/playwright-mcp-server --port 8931\n\n# Or after global installation\nnpm install -g @executeautomation/playwright-mcp-server\nplaywright-mcp-server --port 8931\n```\n\n资料来源：[examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)\n\n### HTTP Server Output\n\nWhen started successfully, the server displays:\n\n```\n==============================================\nPlaywright MCP Server (HTTP Mode)\n==============================================\nListening: 127.0.0.1:8931 (localhost only)\nVersion: <version>\n\nSECURITY: Server is bound to localhost only.\n          Not accessible from external networks.\n\nENDPOINTS:\n- SSE Stream:     GET  http://localhost:8931/sse\n- Messages:       POST http://localhost:8931/messages?sessionId=<id>\n- MCP (unified):  GET  http://localhost:8931/mcp\n- MCP (unified):  POST http://localhost:8931/mcp?sessionId=<id>\n- Health Check:   GET  http://localhost:8931/health\n```\n\n资料来源：[src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)\n\n### Client Configuration\n\n#### Claude Desktop (HTTP)\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"url\": \"http://localhost:8931/mcp\"\n    }\n  }\n}\n```\n\n#### VS Code MCP Extension\n\n```json\n{\n  \"name\": \"playwright\",\n  \"url\": \"http://localhost:8931/mcp\"\n}\n```\n\n#### Health Check\n\n```bash\ncurl http://localhost:8931/health\n```\n\n资料来源：[examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)\n\n### Security Model\n\nThe HTTP server binds exclusively to `127.0.0.1` (localhost) for security reasons:\n\n> **SECURITY**: Server binds to localhost only. Not accessible from external networks.\n\nFor remote access, SSH tunneling is recommended:\n\n```bash\nssh -L 8931:localhost:8931 user@remote-server\n```\n\n资料来源：[src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)\n\n## Mode Selection\n\n### Automatic Selection\n\nThe server automatically selects the transport mode based on:\n\n1. **Presence of `--port` argument** → HTTP/SSE mode\n2. **Absence of `--port` argument** → STDIO mode\n\n### Health Check Response\n\n| Field | Description |\n|-------|-------------|\n| `status` | Health status (`ok` when healthy) |\n| `version` | Server version |\n| `activeSessions` | Number of active MCP sessions |\n\nExample response:\n```json\n{\n  \"status\": \"ok\",\n  \"version\": \"1.0.10\",\n  \"activeSessions\": 2\n}\n```\n\n## Transport Comparison\n\n| Aspect | STDIO | HTTP/SSE |\n|--------|-------|----------|\n| Communication | stdin/stdout pipes | HTTP/REST |\n| Multi-client | No | Yes |\n| Session support | No | Yes (via sessionId) |\n| Browser mode | Headless | Headless or Headed |\n| Claude Desktop | ✅ Supported | ❌ Not supported |\n| VS Code | ✅ Supported | ✅ Supported |\n| Health endpoint | No | Yes |\n| Process lifecycle | Tied to client | Independent |\n\n资料来源：[README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n## Logging Behavior\n\n### STDIO Mode\n\n- Logging automatically directed to files only\n- Console output kept clean for JSON-RPC communication\n- Logs written to `~/playwright-mcp-server.log`\n\n### HTTP Mode\n\n- Standard logging to console and file\n- Request/response logging via middleware\n- Error context capture including:\n  - Stack traces\n  - Memory usage\n  - Platform information\n  - Request duration\n\n资料来源：[src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n## Environment Variables\n\n| Variable | Purpose | Applicable Modes |\n|----------|---------|------------------|\n| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser binary download | Both |\n| `NODE_ENV` | Set runtime environment | Both |\n| `PORT` | HTTP server port (alternative to CLI) | HTTP |\n\n资料来源：[DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n---\n\n<a id='browser-automation'></a>\n\n## Browser Automation Tools\n\n### 相关页面\n\n相关主题：[Device Emulation](#device-emulation), [API Testing Tools](#api-testing), [Code Generation and Recording](#code-generation)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/tools/browser/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/index.ts)\n- [src/tools/browser/navigation.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/navigation.ts)\n- [src/tools/browser/interaction.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/interaction.ts)\n- [src/tools/browser/screenshot.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/screenshot.ts)\n- [src/tools/browser/console.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/console.ts)\n- [src/tools/browser/output.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/output.ts)\n- [src/tools/browser/resize.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n- [src/tools/browser/useragent.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/useragent.ts)\n- [src/tools/browser/response.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/response.ts)\n- [src/tools/browser/visiblePage.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/visiblePage.ts)\n- [src/tools/browser/base.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/base.ts)\n</details>\n\n# Browser Automation Tools\n\n## Overview\n\nThe Browser Automation Tools constitute the core module of the mcp-playwright project, providing a comprehensive set of MCP (Model Context Protocol) tools for browser-based web automation and testing. These tools enable AI assistants and automated systems to interact with web pages programmatically, performing actions such as navigation, element interaction, content extraction, and response monitoring.\n\nThe module supports multiple browser engines (Chromium, Firefox, WebKit) and provides both headless and headed execution modes, making it suitable for a wide range of automation scenarios from simple web scraping to complex end-to-end testing.\n\n**Architecture Overview:**\n\n```mermaid\ngraph TD\n    A[MCP Client] -->|JSON-RPC| B[Tool Handler]\n    B --> C[Browser Tool Executor]\n    C --> D[Browser Engine]\n    D --> E[Chromium<br/>Firefox<br/>WebKit]\n    \n    F[Base Class] -->|Inheritance| C\n    F --> G[Error Handling]\n    F --> H[Page Validation]\n    F --> I[Safe Execution]\n```\n\n## Core Components\n\n### Tool Architecture\n\nThe browser automation tools follow an object-oriented architecture with a base class pattern. All browser tools inherit from `BrowserToolBase`, which provides common functionality including error handling, page validation, and safe execution wrappers.\n\n**Class Hierarchy:**\n\n```mermaid\ngraph TD\n    A[BrowserToolBase] --> B[navigation.ts<br/>NavigateTool]\n    A --> C[interaction.ts<br/>ClickTool, FillTool, etc.]\n    A --> D[screenshot.ts<br/>ScreenshotTool]\n    A --> E[console.ts<br/>ConsoleLogsTool]\n    A --> F[output.ts<br/>PdfTool]\n    A --> G[resize.ts<br/>ResizeTool]\n    A --> H[useragent.ts<br/>CustomUserAgentTool]\n    A --> I[response.ts<br/>ExpectResponseTool, AssertResponseTool]\n    A --> J[visiblePage.ts<br/>VisibleTextTool, VisibleHtmlTool]\n    \n    K[ToolContext] --> A\n    L[Browser, Page] --> A\n```\n\n### Base Class (BrowserToolBase)\n\nThe `BrowserToolBase` class provides the foundation for all browser tools:\n\n| Method | Purpose |\n|--------|---------|\n| `ensurePage(context)` | Returns the current page or null if unavailable |\n| `validatePageAvailable(context)` | Returns error response if page not initialized |\n| `safeExecute(context, operation)` | Wraps browser operations with error handling |\n\n**File Reference:** `src/tools/browser/base.ts`\n\n## Browser Tools Registry\n\nAll browser-requiring tools are registered in the `BROWSER_TOOLS` array and exposed through the MCP tool interface:\n\n**File Reference:** `src/tools/browser/index.ts`, `src/tools.ts`\n\n```typescript\nexport const BROWSER_TOOLS = [\n  \"playwright_navigate\",\n  \"playwright_screenshot\",\n  \"playwright_click\",\n  \"playwright_iframe_click\",\n  \"playwright_iframe_fill\",\n  \"playwright_fill\",\n  \"playwright_select\",\n  \"playwright_hover\",\n  \"playwright_evaluate\",\n  \"playwright_console_logs\",\n  \"playwright_close\",\n  \"playwright_get_visible_text\",\n  \"playwright_get_visible_html\",\n  \"playwright_click_and_switch_tab\",\n  \"playwright_drag\",\n  \"playwright_press_key\",\n  \"playwright_save_as_pdf\"\n];\n```\n\n## Navigation Tools\n\n### Navigate Tool (`playwright_navigate`)\n\nThe primary navigation tool for loading web pages in the browser.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | string | Yes | Target URL to navigate to |\n| `browserType` | string | No | Browser engine: \"chromium\", \"firefox\", \"webkit\" (default: \"chromium\") |\n| `width` | number | No | Viewport width in pixels (default: 1280) |\n| `height` | number | No | Viewport height in pixels (default: 720) |\n| `timeout` | number | No | Navigation timeout in milliseconds |\n| `waitUntil` | string | No | Navigation wait condition |\n| `headless` | boolean | No | Run browser in headless mode (default: false) |\n\n**Multi-Browser Support:**\n\nStarting from version 1.0.2, the navigate tool supports specifying the browser type:\n\n> Multi-Browser Support: Firefox and WebKit in addition to Chromium\n> New `browserType` parameter for `playwright_navigate` tool\n> Supported browser types: \"chromium\" (default), \"firefox\", \"webkit\"\n> 资料来源：[CHANGELOG.md]()\n\n**File Reference:** `src/tools/browser/navigation.ts`\n\n## Interaction Tools\n\nInteraction tools enable programmatic control over browser elements, including clicking, filling forms, hovering, and keyboard input.\n\n### Click Tool (`playwright_click`)\n\nClicks an element identified by a CSS selector.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | Yes | CSS selector for the element to click |\n| `button` | string | No | Mouse button: \"left\", \"right\", \"middle\" (default: \"left\") |\n| `clickCount` | number | No | Number of clicks (default: 1) |\n| `delay` | number | No | Delay in milliseconds between key down and up |\n| `force` | boolean | No | Force click even if element obscured |\n| `timeout` | number | No | Timeout in milliseconds |\n| `noWaitAfter` | boolean | No | Don't wait for navigation after click |\n\n### Fill Tool (`playwright_fill`)\n\nFills input fields with text content.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | Yes | CSS selector for the input element |\n| `value` | string | Yes | Text value to fill |\n| `delay` | number | No | Delay between keystrokes in milliseconds |\n| `noWaitAfter` | boolean | No | Don't wait for navigation after fill |\n\n### Select Tool (`playwright_select`)\n\nSelects options in dropdown menus (select elements).\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | Yes | CSS selector for the select element |\n| `value` | string/array | Yes | Option value(s) to select |\n| `index` | array | No | Option index(es) to select |\n| `label` | string/array | No | Option label(s) to select |\n| `timeout` | number | No | Timeout in milliseconds |\n\n### Hover Tool (`playwright_hover`)\n\nHovers over an element.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | Yes | CSS selector for the element to hover |\n| `timeout` | number | No | Timeout in milliseconds |\n\n### Keyboard Interaction\n\n**Drag Tool (`playwright_drag`):**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `sourceSelector` | string | Yes | CSS selector for source element |\n| `targetSelector` | string | Yes | CSS selector for target element |\n\n**Press Key Tool (`playwright_press_key`):**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | No | CSS selector for element to focus |\n| `key` | string | Yes | Key to press (e.g., \"Enter\", \"Tab\", \"Escape\") |\n\n### iFrame Interaction\n\nThe project supports interaction with elements inside iframes through dedicated tools:\n\n| Tool | Description |\n|------|-------------|\n| `playwright_iframe_click` | Click element within an iframe |\n| `playwright_iframe_fill` | Fill input within an iframe |\n\n**File Reference:** `src/tools/browser/interaction.ts`\n\n## Screenshot Tools\n\n### Screenshot Tool (`playwright_screenshot`)\n\nCaptures screenshots of the current page or specific elements.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `name` | string | No | Name for the screenshot |\n| `selector` | string | No | CSS selector for element to screenshot |\n| `width` | number | No | Width in pixels (default: 800) |\n| `height` | number | No | Height in pixels (default: 600) |\n| `storeBase64` | boolean | No | Store in base64 format (default: true) |\n| `fullPage` | boolean | No | Screenshot entire page (default: false) |\n| `savePng` | boolean | No | Save as PNG file (default: false) |\n| `downloadsDir` | string | No | Custom downloads directory path |\n\n**File Reference:** `src/tools/browser/screenshot.ts`\n\n## Content Extraction Tools\n\n### Visible Text Tool (`playwright_get_visible_text`)\n\nExtracts visible text content from the page or specific elements.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | No | CSS selector to extract text from specific element |\n| `includeHidden` | boolean | No | Include hidden elements (default: false) |\n| `removeLineBreaks` | boolean | No | Remove line breaks (default: false) |\n| `trimText` | boolean | No | Trim whitespace (default: true) |\n\n### Visible HTML Tool (`playwright_get_visible_html`)\n\nRetrieves HTML content from the page or elements.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | string | No | CSS selector for specific element |\n| `removeScripts` | boolean | No | Remove script tags |\n| `removeComments` | boolean | No | Remove HTML comments |\n| `removeStyles` | boolean | No | Remove style tags |\n| `removeMeta` | boolean | No | Remove meta tags |\n| `cleanHtml` | boolean | No | Apply all cleanup filters |\n| `minify` | boolean | No | Minify the HTML output |\n\n**Content Filtering Pipeline:**\n\n```mermaid\ngraph LR\n    A[Raw HTML] --> B{removeScripts?}\n    B -->|Yes| C[Remove script tags]\n    B -->|No| D[Continue]\n    C --> E{removeStyles?}\n    E -->|Yes| F[Remove style tags]\n    E -->|No| G[Continue]\n    F --> H{removeMeta?}\n    H -->|Yes| I[Remove meta tags]\n    H -->|No| J[Continue]\n    I --> K{removeComments?}\n    K -->|Yes| L[Remove comments]\n    K -->|No| M[Continue]\n    L --> N{minify?}\n    M --> N\n    N -->|Yes| O[Minify HTML]\n    N -->|No| P[Return Clean HTML]\n```\n\n**File Reference:** `src/tools/browser/visiblePage.ts`\n\n## Output Tools\n\n### PDF Generation Tool (`playwright_save_as_pdf`)\n\nSaves the current page as a PDF document.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `outputPath` | string | Yes | Path where PDF will be saved |\n| `name` | string | No | PDF filename (default: \"page.pdf\") |\n| `format` | string | No | Page format: \"A4\", \"Letter\", etc. |\n| `printBackground` | boolean | No | Include background graphics |\n| `margin` | object | No | Page margins (top, right, bottom, left) |\n\n**File Reference:** `src/tools/browser/output.ts`\n\n## Console Tools\n\n### Console Logs Tool (`playwright_console_logs`)\n\nRetrieves console messages from the browser page.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `type` | string | No | Filter by message type: \"log\", \"info\", \"warn\", \"error\" |\n| `text` | string | No | Filter by text content (partial match) |\n| `regex` | string | No | Filter by regex pattern |\n\n**Console Message Types:**\n\n| Type | Description |\n|------|-------------|\n| `log` | General console logs |\n| `info` | Informational messages |\n| `warn` | Warning messages |\n| `error` | Error messages |\n\n**File Reference:** `src/tools/browser/console.ts`\n\n## Response Monitoring Tools\n\n### Expect Response Tool (`playwright_expect_response`)\n\nSets up expectations for network responses.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | string | No | URL pattern to match (regex or string) |\n| `statusCode` | number | No | Expected HTTP status code |\n| `timeout` | number | No | Timeout in milliseconds |\n| `method` | string | No | HTTP method filter |\n\n### Assert Response Tool (`playwright_assert_response`)\n\nAsserts that a network response meets specified criteria.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | string | No | URL pattern to match |\n| `statusCode` | number | No | Expected HTTP status code |\n| `method` | string | No | HTTP method filter |\n\n**File Reference:** `src/tools/browser/response.ts`\n\n## Viewport and Device Emulation\n\n### Resize Tool (`playwright_resize`)\n\nConfigures viewport dimensions and enables device emulation.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `device` | string | No | Device name for emulation (e.g., \"iPhone 13\", \"iPad Pro 11\") |\n| `width` | number | No | Viewport width in pixels |\n| `height` | number | No | Viewport height in pixels |\n| `orientation` | string | No | Device orientation: \"portrait\", \"landscape\" |\n| `scale` | number | No | Device scale factor |\n| `mobile` | boolean | No | Enable mobile emulation |\n\n**Device Emulation Features:**\n\n- 143 real device presets including iPhone, iPad, Pixel, Galaxy, and Desktop browsers\n- Automatic user-agent string configuration\n- Touch event support emulation\n- Device pixel ratio configuration\n\n**Natural Language Support:**\n\nAI assistants can use natural language prompts such as:\n- \"Test on iPhone 13\"\n- \"Switch to iPad view\"\n- \"Rotate to landscape\"\n\n**File Reference:** `src/tools/browser/resize.ts`\n\n## User Agent Tools\n\n### Custom User Agent Tool (`playwright_custom_user_agent`)\n\nSets a custom user agent string for the browser context.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `userAgent` | string | Yes | Custom user agent string |\n\n**File Reference:** `src/tools/browser/useragent.ts`\n\n## Browser Lifecycle Management\n\n### Close Tool (`playwright_close`)\n\nCloses the current browser context and page.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `closeBrowser` | boolean | No | Close the entire browser (default: false) |\n\n## Error Handling\n\nThe browser tools implement comprehensive error handling through the middleware system:\n\n**Error Categories:**\n\n| Category | Indicators |\n|----------|------------|\n| `validation` | Invalid parameters, missing required fields |\n| `resource` | Browser closed, page disconnected, protocol errors |\n| `authentication` | Unauthorized, forbidden, access denied |\n| `rate_limit` | Too many requests, throttling |\n| `system` | Timeout, element not found, navigation failures |\n\n**Enhanced Error Context:**\n\nThe logging middleware captures detailed error context including:\n- Error name and message\n- Stack trace\n- Timestamp\n- Node.js version and platform\n- Memory usage statistics\n- Browser state information\n\n**File Reference:** `src/logging/middleware.ts`\n\n## Tool Execution Flow\n\n**Complete Tool Execution Pipeline:**\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant MCP_Server\n    participant Middleware\n    participant Tool\n    participant Browser\n    \n    Client->>MCP_Server: Tool Request\n    MCP_Server->>Middleware: Intercept Request\n    Middleware->>Middleware: Log Start\n    Middleware->>Tool: Execute Tool\n    Tool->>Browser: Browser Operation\n    Browser-->>Tool: Operation Result\n    Tool-->>Middleware: Tool Response\n    Middleware->>Middleware: Log Completion\n    Middleware-->>Client: Response\n```\n\n## Summary\n\nThe Browser Automation Tools module provides a comprehensive, MCP-compatible interface for browser automation tasks. Key features include:\n\n| Feature Category | Capabilities |\n|------------------|--------------|\n| **Navigation** | Multi-browser support (Chromium, Firefox, WebKit), configurable viewport |\n| **Interaction** | Click, fill, select, hover, drag, keyboard input, iframe support |\n| **Content Extraction** | Visible text, HTML with filtering/minification |\n| **Output** | Screenshots, PDF generation |\n| **Monitoring** | Console logs, network response expectations |\n| **Emulation** | 143 device presets, custom user agents |\n\nAll tools follow a consistent pattern with base class inheritance, comprehensive error handling, and structured logging for debugging and monitoring purposes.\n\n---\n\n<a id='device-emulation'></a>\n\n## Device Emulation\n\n### 相关页面\n\n相关主题：[Browser Automation Tools](#browser-automation)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/tools/browser/resize.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n- [src/tools.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools.ts)\n- [src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n- [src/tools/browser/visiblePage.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/visiblePage.ts)\n- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)\n</details>\n\n# Device Emulation\n\nDevice Emulation is a core feature of the Playwright MCP Server that enables AI assistants and automated testing tools to simulate real-world mobile and desktop devices directly within the browser automation framework. By leveraging Playwright's built-in device descriptor library, the server provides **143 real device presets** with accurate viewport dimensions, user-agent strings, touch capabilities, and device pixel ratios.\n\n## Overview\n\nThe Device Emulation system integrates with the `playwright_resize` tool to provide a seamless interface for switching between device profiles. When a device preset is selected, the system automatically configures multiple browser properties simultaneously:\n\n- **Viewport dimensions** for accurate screen rendering\n- **User-Agent strings** for proper server-side device detection\n- **Touch capabilities** for mobile device simulation\n- **Device pixel ratio** for high-DPI display accuracy\n\n资料来源：[README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[AI Assistant / MCP Client] --> B[playwright_resize Tool]\n    B --> C{Device Preset?}\n    C -->|Yes| D[Lookup in Playwright devices]\n    C -->|No| E[Direct Dimensions]\n    D --> F[Extract Device Properties]\n    F --> G[page.setViewportSize]\n    F --> H[page.setExtraHTTPHeaders]\n    G --> I[Browser Context Updated]\n    H --> I\n    E --> G\n```\n\n### Component Flow\n\n1. **Client Request**: The AI assistant or MCP client sends a `playwright_resize` call with a `device` parameter\n2. **Device Lookup**: The system searches Playwright's device descriptor library using the provided name\n3. **Property Extraction**: Device properties including viewport, user-agent, mobile flag, touch support, and scale factor are extracted\n4. **Browser Configuration**: Playwright APIs apply the settings to the active page context\n\n资料来源：[src/tools/browser/resize.ts:17-48](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n\n## API Reference\n\n### Tool: `playwright_resize`\n\nThe primary tool for device emulation and viewport control.\n\n#### Parameters\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `device` | `string` | No | Device preset name (e.g., \"iPhone 13\", \"iPad Pro 11\") |\n| `width` | `number` | Conditional | Viewport width in pixels (default: 1280) |\n| `height` | `number` | Conditional | Viewport height in pixels (default: 720) |\n| `orientation` | `string` | No | \"portrait\" or \"landscape\" (only valid with device preset) |\n| `maxLength` | `number` | No | Maximum response length for HTML content (default: 20000) |\n\n#### Device Preset Detection\n\nThe system validates device names against Playwright's device library and returns helpful suggestions if the device is not found:\n\n```typescript\nif (!device) {\n  return createErrorResponse(\n    `Device \"${args.device}\" not found. Popular devices: ${popularDevices.join(', ')}. ` +\n    `Use playwright.devices to see all ${Object.keys(devices).length} available devices.`\n  );\n}\n```\n\n资料来源：[src/tools/browser/resize.ts:36-43](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n\n## Supported Devices\n\nThe Playwright MCP Server includes support for **143 device presets** covering major device categories:\n\n### Popular Devices\n\n| Category | Devices |\n|----------|---------|\n| **iPhone** | iPhone 13, iPhone 13 Pro, iPhone 14, iPhone 15, iPhone 15 Pro Max |\n| **iPad** | iPad Pro 11, iPad Pro 12.9, iPad Air, iPad Mini |\n| **Pixel** | Pixel 5, Pixel 7, Pixel 8, Pixel 8 Pro |\n| **Galaxy** | Galaxy S9+, Galaxy S10+, Galaxy S24, Galaxy S24 Ultra |\n| **Desktop** | Desktop Chrome, Desktop Firefox, Desktop Safari |\n\n### Device Properties Extracted\n\nWhen using a device preset, the following properties are automatically configured:\n\n```typescript\n// Extract device properties from Playwright's device library\nwidth = device.defaultBrowserViewport.width;\nheight = device.defaultBrowserViewport.height;\nuserAgent = device.defaultUserAgent;\nisMobile = device.defaultBrowserType === 'mobile';\nhasTouch = device.hasTouch;\ndeviceScaleFactor = device.deviceScaleFactor || 1;\n```\n\n资料来源：[src/tools/browser/resize.ts:48-54](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n\n## Orientation Support\n\nDevice emulation supports both portrait and landscape orientations. When an orientation is specified with a device preset, the width and height values are swapped:\n\n```javascript\n// Portrait orientation (default)\nawait playwright_resize({ device: \"iPhone 13\", orientation: \"portrait\" });\n\n// Landscape orientation\nawait playwright_resize({ device: \"iPad Pro 11\", orientation: \"landscape\" });\n```\n\n### Orientation Logic\n\n```mermaid\ngraph LR\n    A[Device Preset] --> B{orientation === \"landscape\"}\n    B -->|Yes| C[Swap width ↔ height]\n    B -->|No| D[Keep original dimensions]\n    C --> E[Apply to Viewport]\n    D --> E\n```\n\nThe orientation parameter is validated to ensure it is only used with device presets:\n\n```typescript\nif (args.orientation && !args.device) {\n  throw new Error(\"Orientation can only be set when using a device preset\");\n}\n```\n\n资料来源：[src/tools/browser/resize.ts:71-74](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n\n## Validation Rules\n\nThe device emulation system enforces several validation constraints:\n\n### Dimension Constraints\n\n| Rule | Value | Error Message |\n|------|-------|---------------|\n| Minimum dimension | > 0 | \"Width and height must be positive integers\" |\n| Maximum dimension | ≤ 7680 × 4320 | \"Width and height must not exceed 7680x4320 (8K resolution)\" |\n\n### Parameter Constraints\n\n| Constraint | Condition |\n|------------|------------|\n| Orientation requires device | `orientation` parameter cannot be used standalone |\n| Device validation | Name must exist in Playwright's device library |\n\n资料来源：[src/tools/browser/resize.ts:81-91](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n\n## Natural Language Support\n\nThe device emulation system is designed to work seamlessly with AI assistants that use natural language commands. Common prompt patterns include:\n\n- \"Test on iPhone 13\"\n- \"Switch to iPad view\"\n- \"Rotate to landscape\"\n- \"Test desktop view\"\n\nThese natural language commands are interpreted by the AI assistant and translated into `playwright_resize` tool calls with the appropriate device and orientation parameters.\n\n资料来源：[README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n\n## Implementation Details\n\n### Base Class Integration\n\nThe `ResizeTool` extends `BrowserToolBase`, which provides the foundation for browser interaction:\n\n```typescript\nexport class ResizeTool extends BrowserToolBase {\n  async execute(args: any, context: ToolContext): Promise<ToolResponse> {\n    return this.safeExecute(context, async (page) => {\n      // Device emulation logic\n    });\n  }\n}\n```\n\n### Error Handling\n\nThe implementation uses a safe execution pattern with comprehensive error handling:\n\n```typescript\nprivate categorizeError(error: Error): 'validation' | 'system' | 'unknown' {\n  const message = error.message.toLowerCase();\n  \n  if (message.includes('invalid') || message.includes('validation') || message.includes('required')) {\n    return 'validation';\n  }\n  \n  if (message.includes('browser') || message.includes('page') || message.includes('connection')) {\n    return 'system';\n  }\n  \n  return 'unknown';\n}\n```\n\n资料来源：[src/tools/browser/resize.ts:7-11](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n资料来源：[src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n## Response Format\n\n### Success Response\n\nWhen device emulation is successfully applied, the response includes:\n\n```\nBrowser viewport resized to iPhone 13 (390x844) [mobile, touch, 3x scale]\n```\n\nThe response includes:\n- Device name and dimensions\n- Orientation (if specified)\n- Applied features: mobile, touch, device scale factor\n\n### Error Response\n\nIf device emulation fails, an error response is returned with:\n- Specific error message explaining the failure\n- Suggestions for popular devices when device name is not found\n- Reference to available device count\n\n资料来源：[src/tools/browser/resize.ts:95-120](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)\n\n## Tool Registration\n\nThe `playwright_resize` tool is registered in the central tools registry:\n\n```typescript\n{\n  name: \"playwright_resize\",\n  description: \"Resize browser viewport with optional device emulation\",\n  inputSchema: {\n    type: \"object\",\n    properties: {\n      device: { type: \"string\", description: \"Device preset name\" },\n      width: { type: \"number\", description: \"Viewport width in pixels\" },\n      height: { type: \"number\", description: \"Viewport height in pixels\" },\n      orientation: { type: \"string\", description: \"Device orientation\" }\n    }\n  }\n}\n```\n\n资料来源：[src/tools.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools.ts)\n\n## Dependencies\n\nThe device emulation feature relies on the following package dependencies:\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `playwright` | 1.57.0 | Core browser automation with device descriptors |\n| `@playwright/browser-chromium` | 1.57.0 | Chromium browser support |\n| `@playwright/browser-firefox` | 1.57.0 | Firefox browser support |\n| `@playwright/browser-webkit` | 1.57.0 | WebKit browser support |\n\n资料来源：[package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)\n\n## Usage Examples\n\n### Basic Device Emulation\n\n```javascript\n// Test on iPhone 13\nawait playwright_resize({ device: \"iPhone 13\" });\n\n// Result: Browser viewport resized to iPhone 13 (390x844) [mobile, touch, 2x scale]\n```\n\n### Landscape Orientation\n\n```javascript\n// iPad in landscape mode\nawait playwright_resize({ device: \"iPad Pro 11\", orientation: \"landscape\" });\n\n// Result: Browser viewport resized to iPad Pro 11 (1194x834) in landscape orientation [mobile, touch, 2x scale]\n```\n\n### Desktop Browser\n\n```javascript\n// Switch to desktop Chrome view\nawait playwright_resize({ device: \"Desktop Chrome\" });\n\n// Result: Browser viewport resized to Desktop Chrome (1280x720)\n```\n\n### Custom Dimensions\n\n```javascript\n// Direct viewport control without device preset\nawait playwright_resize({ width: 1920, height: 1080 });\n\n// Result: Browser viewport resized to 1920x1080\n```\n\n## Integration with Other Tools\n\nDevice emulation settings persist across multiple tool calls within a session. Other tools that may interact with device emulation include:\n\n| Tool | Interaction |\n|------|-------------|\n| `playwright_screenshot` | Captures screenshots at device resolution |\n| `playwright_get_visible_html` | Extracts HTML content rendered at device viewport |\n| `playwright_navigate` | Can be combined with device presets for full mobile testing |\n\nThe viewport and user-agent settings remain active until explicitly changed by another `playwright_resize` call.\n\n资料来源：[src/tools/browser/visiblePage.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/visiblePage.ts)\n资料来源：[src/tools/browser/screenshot.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/screenshot.ts)\n\n---\n\n<a id='api-testing'></a>\n\n## API Testing Tools\n\n### 相关页面\n\n相关主题：[Browser Automation Tools](#browser-automation), [Code Generation and Recording](#code-generation)\n\n<details>\n<summary>Relevant Source Files</summary>\n\nThe following source files were used to generate this page:\n\n- [src/tools/api/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/index.ts)\n- [src/tools/api/base.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/base.ts)\n- [src/tools/api/requests.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/requests.ts)\n- [src/tools/common/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/common/types.ts)\n- [src/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/types.ts)\n- [src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n</details>\n\n# API Testing Tools\n\n## Overview\n\nThe API Testing Tools module in MCP Playwright provides a comprehensive framework for executing and validating HTTP API requests directly within the Model Context Protocol server environment. This module enables AI assistants and automated testing systems to perform REST API testing operations with full request/response tracking, assertion capabilities, and detailed logging support.\n\nThe API Testing Tools extend the MCP Playwright server's functionality beyond browser automation to include robust HTTP client capabilities. This allows for seamless integration of API testing workflows alongside browser-based UI testing, enabling end-to-end testing scenarios that span both frontend and backend interactions.\n\n## Architecture\n\n### High-Level Architecture\n\n```mermaid\ngraph TD\n    A[MCP Client Request] --> B[Tool Router]\n    B --> C[API Testing Module]\n    C --> D[Request Executor]\n    D --> E[HTTP Client]\n    E --> F[External API]\n    F --> G[Response Handler]\n    G --> H[Assertion Engine]\n    H --> I[Tool Response]\n    D --> J[Logging Middleware]\n    J --> K[Request Logs]\n    \n    L[Request Builder] --> D\n    M[Auth Handler] --> L\n    N[Header Manager] --> L\n```\n\n### Module Structure\n\nThe API Testing Tools are organized into three primary components following the project's modular architecture pattern:\n\n| Component | File | Responsibility |\n|-----------|------|-----------------|\n| API Index | `src/tools/api/index.ts` | Tool registration and routing |\n| API Base | `src/tools/api/base.ts` | Base class with common functionality |\n| Request Handler | `src/tools/api/requests.ts` | HTTP request execution and response handling |\n\n## Core Components\n\n### API Tool Base Class\n\nThe base class for all API tools provides common functionality that mirrors the browser tool architecture while adapting for HTTP operations. This design ensures consistency with the broader MCP Playwright tool framework.\n\n```typescript\n// Pattern inherited from browser base architecture\nexport abstract class ApiToolBase implements ToolHandler {\n  protected server: any;\n  \n  constructor(server: any) {\n    this.server = server;\n  }\n  \n  abstract execute(args: any, context: ToolContext): Promise<ToolResponse>;\n  \n  protected ensureContext(context: ToolContext): ApiContext | null;\n  protected validateRequest(args: any): ToolResponse | null;\n  protected safeExecute(context: ToolContext, operation: ...): Promise<ToolResponse>;\n}\n```\n\n**资料来源：** [src/tools/api/base.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/base.ts)\n\n### Tool Registry and Handler\n\nThe API module registers its tools with the MCP server through the standard tool handler interface defined in the types system:\n\n```typescript\nexport interface Tool {\n  name: string;\n  description: string;\n  parameters: {\n    type: string;\n    properties: Record<string, unknown>;\n    required?: string[];\n  };\n  handler: (args: any) => Promise<any>;\n}\n```\n\n**资料来源：** [src/types.ts:1-15](https://github.com/executeautomation/mcp-playwright/blob/main/src/types.ts)\n\n### Request Builder and Executor\n\nThe request handler component manages the construction and execution of HTTP requests, supporting various HTTP methods and authentication mechanisms.\n\n**资料来源：** [src/tools/api/requests.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/requests.ts)\n\n## Available API Testing Tools\n\n### Response Expectation Tool\n\nThe `playwright_expect_response` tool allows tests to verify expected HTTP response characteristics before proceeding with further assertions. This tool enables proactive validation of API responses.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | string | Yes | Target API endpoint URL |\n| `method` | string | No | HTTP method (GET, POST, PUT, DELETE, etc.) |\n| `expectedStatus` | number | No | Expected HTTP status code |\n| `expectedBody` | object | No | Expected response body content |\n| `timeout` | number | No | Request timeout in milliseconds |\n\n**资料来源：** [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n\n### Response Assertion Tool\n\nThe `playwright_assert_response` tool provides comprehensive response validation capabilities, comparing actual API responses against expected values with detailed error reporting.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | string | Yes | Target API endpoint URL |\n| `expectedHeaders` | object | No | Expected response headers |\n| `expectedBody` | object | No | Expected response body pattern |\n| `schema` | object | No | JSON Schema for response validation |\n| `exactMatch` | boolean | No | Whether to require exact body matching |\n\n**资料来源：** [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n\n### Custom User Agent Tool\n\nThe `playwright_custom_user_agent` tool enables modification of the User-Agent header for API requests, supporting scenarios requiring specific client identification or browser emulation.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `userAgent` | string | Yes | Custom User-Agent string |\n| `persist` | boolean | No | Whether to persist for subsequent requests |\n\n**资料来源：** [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n\n### Optional Bearer Authorization\n\nAPI testing tools support optional Bearer token authentication for secured endpoints. This is configured at the request level and follows RFC 6750 specifications.\n\n**Configuration:**\n\n```json\n{\n  \"url\": \"https://api.example.com/protected\",\n  \"method\": \"GET\",\n  \"authorization\": {\n    \"type\": \"bearer\",\n    \"token\": \"${API_TOKEN}\"\n  }\n}\n```\n\n**资料来源：** [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)\n\n## Request Lifecycle\n\n```mermaid\nsequenceDiagram\n    participant MCP as MCP Client\n    participant API as API Tool Module\n    participant LOG as Logging Middleware\n    participant HTTP as HTTP Client\n    participant EXT as External API\n    \n    MCP->>API: Tool Call Request\n    API->>LOG: Log Tool Start\n    LOG->>LOG: Capture Request Context\n    API->>API: Validate Parameters\n    API->>HTTP: Execute Request\n    HTTP->>EXT: HTTP Request\n    EXT-->>HTTP: HTTP Response\n    HTTP-->>API: Raw Response\n    API->>API: Process Response\n    API->>API: Run Assertions\n    API->>LOG: Log Tool Completion\n    LOG-->>API: Log Entry Created\n    API-->>MCP: Tool Response\n```\n\n## Logging and Monitoring\n\n### Request Logging\n\nThe logging middleware captures detailed information about API tool executions, following the same pattern used for browser tools. Each API request generates a structured log entry with timing information and sanitized parameter data.\n\n**Logging Context Structure:**\n\n```typescript\ninterface RequestLogContext {\n  method: 'TOOL_CALL';\n  url: string;\n  body?: any;\n  statusCode?: number;\n  duration?: number;\n}\n```\n\n**资料来源：** [src/logging/middleware.ts:10-16](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n### Error Handling and Categorization\n\nThe logging middleware provides comprehensive error categorization for API-related errors:\n\n| Error Category | Detection Patterns | Description |\n|----------------|-------------------|-------------|\n| `validation` | invalid, validation, required, missing parameter | Request validation failures |\n| `resource` | browser, page, connection, closed, disconnected | Resource availability issues |\n| `authentication` | unauthorized, forbidden, access denied | Auth-related failures |\n| `rate_limit` | rate limit, too many requests, throttle | Rate limiting responses |\n\n**资料来源：** [src/logging/middleware.ts:85-120](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n### Sanitization\n\nSensitive data within API requests is automatically sanitized in logs:\n\n```typescript\nconst sensitiveFields = ['password', 'token', 'secret', 'key', 'auth'];\n// These fields are replaced with '[REDACTED]' in logs\n```\n\n**资料来源：** [src/logging/middleware.ts:180-190](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)\n\n## Integration with Browser Tools\n\nThe API Testing Tools are designed to work alongside browser automation tools, enabling comprehensive end-to-end testing scenarios:\n\n```mermaid\ngraph LR\n    A[playwright_navigate] --> B[Browser Actions]\n    B --> C[Extract Data]\n    C --> D[API Validation]\n    D --> E[playwright_expect_response]\n    E --> F[API Assertions]\n    F --> G[playwright_assert_response]\n    G --> H[Test Results]\n```\n\nThis integration allows for scenarios such as:\n\n1. **Data-Driven Testing**: Extract test data from the UI using browser tools, then validate against API responses\n2. **State Verification**: Use API tools to verify backend state after browser interactions\n3. **Hybrid Workflows**: Combine UI automation with API validation for complete coverage\n\n## Configuration\n\n### Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser downloads (for API-only usage) | `0` |\n| `NODE_ENV` | Node environment setting | `production` |\n| `OPENAI_API_KEY` | API key for evaluation framework | - |\n\n**资料来源：** [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Timeout Configuration\n\nAPI tool timeouts are configurable at the tool call level and can be set per-request:\n\n```typescript\n{\n  \"timeout\": 30000,  // 30 seconds\n  \"retries\": 0       // No automatic retries by default\n}\n```\n\n## Error Handling Patterns\n\n### Tool Response Structure\n\nAll API tools return responses following the standard `ToolResponse` format:\n\n```typescript\ninterface ToolResponse {\n  content: Array<{\n    type: 'text';\n    text: string;\n  }>;\n  isError?: boolean;\n}\n```\n\n**资料来源：** [src/tools/common/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/common/types.ts)\n\n### Common Error Scenarios\n\n| Scenario | Error Type | Handling |\n|----------|------------|----------|\n| Invalid URL | `validation` | Return error response with message |\n| Connection timeout | `resource` | Log with timeout details |\n| Invalid JSON response | `validation` | Include parse error in response |\n| Server error (5xx) | `system` | Log with response details |\n\n## Best Practices\n\n1. **Use Assertions Early**: Use `playwright_expect_response` for early failure detection in test suites\n2. **Sanitize Sensitive Data**: Ensure credentials are not logged by using environment variables\n3. **Set Appropriate Timeouts**: Configure timeouts based on expected API response times\n4. **Combine with Browser Tools**: Leverage both API and browser tools for comprehensive testing\n5. **Monitor Logs**: Review logging output for performance analysis and debugging\n\n## Related Documentation\n\n- [HTTP Mode Example](examples/http-mode-example.md) - Running the server in HTTP mode for API testing\n- [Docker Integration](DOCKER.md) - Containerized deployment for API testing workflows\n- [Main README](README.md) - General MCP Playwright server documentation\n\n---\n\n<a id='code-generation'></a>\n\n## Code Generation and Recording\n\n### 相关页面\n\n相关主题：[Browser Automation Tools](#browser-automation), [API Testing Tools](#api-testing)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [src/tools/codegen/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/codegen/index.ts)\n- [src/tools/codegen/recorder.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/codegen/recorder.ts)\n- [src/tools/codegen/generator.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/codegen/generator.ts)\n- [src/tools/codegen/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/codegen/types.ts)\n</details>\n\n# Code Generation and Recording\n\nThe Code Generation and Recording system is a module within the MCP Playwright server that enables automatic conversion of MCP tool interactions into executable Playwright test code. This feature captures user actions performed through MCP tools during browser automation sessions and transforms them into structured test cases that can be replayed using Playwright's native test runner.\n\n## Overview\n\nThe codegen module serves as a bridge between exploratory testing and automated test creation. When developers or AI assistants interact with web applications using MCP Playwright tools (such as `playwright_click`, `playwright_navigate`, `playwright_fill`, etc.), the codegen system records these actions with their parameters and results. Upon session completion, this recorded data can be converted into self-contained Playwright test files.\n\n资料来源：[src/tools/codegen/index.ts:1-30]()\n\n## Architecture\n\nThe codegen system follows a two-phase architecture: **Recording** and **Generation**.\n\n```mermaid\ngraph TD\n    A[MCP Tool Execution] --> B[ActionRecorder]\n    B --> C[CodegenSession Store]\n    C --> D[Session Actions]\n    D --> E[PlaywrightGenerator]\n    E --> F[Generated Test Code]\n    G[CodegenOptions] --> E\n    \n    style A fill:#e1f5fe\n    style F fill:#c8e6c9\n    style B fill:#fff3e0\n    style E fill:#fff3e0\n```\n\n### Core Components\n\n| Component | File | Responsibility |\n|-----------|------|-----------------|\n| ActionRecorder | recorder.ts | Captures and stores tool execution data |\n| PlaywrightGenerator | generator.ts | Transforms recorded sessions into test code |\n| CodegenSession | types.ts | Data model for tracking a recording session |\n| CodegenOptions | types.ts | Configuration for code generation behavior |\n\n资料来源：[src/tools/codegen/types.ts:1-35]()\n\n## Data Models\n\nThe codegen module defines several TypeScript interfaces that structure the recording and generation process.\n\n### CodegenAction\n\nRepresents a single recorded action during a codegen session.\n\n```typescript\nexport interface CodegenAction {\n  toolName: string;\n  parameters: Record<string, unknown>;\n  timestamp: number;\n  result?: unknown;\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| toolName | string | The name of the MCP tool that was executed |\n| parameters | Record<string, unknown> | Arguments passed to the tool |\n| timestamp | number | Unix timestamp when the action occurred |\n| result | unknown | Optional result returned by the tool execution |\n\n资料来源：[src/tools/codegen/types.ts:1-10]()\n\n### CodegenSession\n\nRepresents an entire recording session containing multiple actions.\n\n```typescript\nexport interface CodegenSession {\n  id: string;\n  actions: CodegenAction[];\n  startTime: number;\n  endTime?: number;\n  options?: CodegenOptions;\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| id | string | Unique identifier for the session |\n| actions | CodegenAction[] | Ordered list of recorded actions |\n| startTime | number | Session start timestamp |\n| endTime | number | Optional session end timestamp |\n| options | CodegenOptions | Optional generation configuration |\n\n资料来源：[src/tools/codegen/types.ts:12-20]()\n\n### CodegenOptions\n\nConfiguration options that control code generation behavior.\n\n```typescript\nexport interface CodegenOptions {\n  outputPath?: string;\n  testNamePrefix?: string;\n  includeComments?: boolean;\n}\n```\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| outputPath | string | 'e2e' | Directory path where generated test files are written |\n| testNamePrefix | string | 'Test' | Prefix added to generated test names |\n| includeComments | boolean | true | Whether to include explanatory comments in generated code |\n\n资料来源：[src/tools/codegen/types.ts:26-32]()\n\n### CodegenResult\n\nOutput returned after generating test code from a session.\n\n```typescript\nexport interface CodegenResult {\n  testCode: string;\n  filePath: string;\n  sessionId: string;\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| testCode | string | The generated Playwright test code |\n| filePath | string | Path where the test file was or will be written |\n| sessionId | string | Reference to the originating session |\n\n资料来源：[src/tools/codegen/types.ts:34-40]()\n\n## Available Tools\n\nThe codegen module exposes the following MCP tools for managing sessions.\n\n### start_codegen_session\n\nInitiates a new recording session for capturing MCP tool actions.\n\n```typescript\nexport const startCodegenSession: Tool = {\n  name: 'start_codegen_session',\n  description: 'Start a new code generation session to record MCP tool actions',\n  parameters: {\n    type: 'object',\n    properties: {\n      options: {\n        type: 'object',\n        description: 'Code generation options',\n        properties: {\n          outputPath: { type: 'string' },\n          testNamePrefix: { type: 'string' },\n          includeComments: { type: 'boolean' }\n        }\n      }\n    }\n  },\n  // ...\n};\n```\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| options | object | No | Configuration for the codegen session |\n| options.outputPath | string | No | Custom output directory for generated tests |\n| options.testNamePrefix | string | No | Prefix for generated test names |\n| options.includeComments | boolean | No | Enable/disable code comments |\n\n资料来源：[src/tools/codegen/index.ts:37-58]()\n\n## PlaywrightGenerator Class\n\nThe `PlaywrightGenerator` class handles the transformation of recorded sessions into executable Playwright test code.\n\n### Constructor and Configuration\n\n```typescript\nexport class PlaywrightGenerator {\n  private static readonly DEFAULT_OPTIONS: Required<CodegenOptions> = {\n    outputPath: 'tests',\n    testNamePrefix: 'MCP',\n    includeComments: true,\n  };\n\n  private options: Required<CodegenOptions>;\n\n  constructor(options: CodegenOptions = {}) {\n    this.validateOptions(options);\n    this.options = { ...PlaywrightGenerator.DEFAULT_OPTIONS, ...options };\n  }\n}\n```\n\n| Default Option | Value | Description |\n|----------------|-------|-------------|\n| outputPath | 'tests' | Default directory for generated test files |\n| testNamePrefix | 'MCP' | Default prefix for test names |\n| includeComments | true | Comments included by default |\n\n资料来源：[src/tools/codegen/generator.ts:1-20]()\n\n### Options Validation\n\nThe generator performs strict validation on provided options before initializing.\n\n```typescript\nprivate validateOptions(options: CodegenOptions): void {\n  if (options.outputPath && typeof options.outputPath !== 'string') {\n    throw new Error('outputPath must be a string');\n  }\n  if (options.testNamePrefix && typeof options.testNamePrefix !== 'string') {\n    throw new Error('testNamePrefix must be a string');\n  }\n  if (options.includeComments !== undefined && typeof options.includeComments !== 'boolean') {\n    throw new Error('includeComments must be a boolean');\n  }\n}\n```\n\nAll options are validated for correct types before being applied, ensuring runtime errors are prevented during test generation.\n\n资料来源：[src/tools/codegen/generator.ts:22-33]()\n\n### Test Generation Process\n\n```typescript\nasync generateTest(session: CodegenSession): Promise<CodegenResult> {\n  if (!session || !Array.isArray(session.actions)) {\n    throw new Error('Invalid session data');\n  }\n\n  const testCase = this.createTestCase(session);\n  const testCode = this.generateTestCode(testCase);\n  const filePath = this.getOutputFilePath(session);\n\n  return {\n    testCode,\n    filePath,\n    sessionId: session.id,\n  };\n}\n```\n\nThe generation process consists of three steps:\n\n1. **Create Test Case** - Transforms session actions into a structured `PlaywrightTestCase`\n2. **Generate Test Code** - Converts the test case into Playwright test syntax\n3. **Determine Output Path** - Resolves the file path based on session ID and configuration\n\n资料来源：[src/tools/codegen/generator.ts:35-50]()\n\n## Recording Workflow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant MCP as MCP Server\n    participant Recorder as ActionRecorder\n    participant Store as CodegenSession Store\n    \n    User->>MCP: start_codegen_session(options)\n    MCP->>Recorder: createSession(options)\n    Recorder->>Store: initialize session\n    Note over Store: Session ID generated\n    \n    User->>MCP: playwright_click(selector)\n    MCP->>Recorder: record(toolName, args, result)\n    Recorder->>Store: append action\n    \n    User->>MCP: playwright_navigate(url)\n    MCP->>Recorder: record(toolName, args, result)\n    Recorder->>Store: append action\n    \n    User->>MCP: stop_codegen_session()\n    MCP->>Recorder: finalize session\n    Recorder->>Store: set endTime\n```\n\n## PlaywrightTestCase Structure\n\nThe intermediate representation used during code generation:\n\n```typescript\nexport interface PlaywrightTestCase {\n  name: string;\n  steps: string[];\n  imports: Set<string>;\n}\n```\n\n| Field | Type | Description |\n|-------|------|-------------|\n| name | string | Test case name derived from prefix and session info |\n| steps | string[] | Lines of Playwright test code |\n| imports | Set<string> | Required import statements for the test |\n\n资料来源：[src/tools/codegen/types.ts:22-26]()\n\n## Output Path Resolution\n\nThe system uses the workspace root as the base directory for generated tests:\n\n```typescript\nconst getWorkspaceRoot = () => {\n  return process.cwd();\n};\n\nconst DEFAULT_OPTIONS: Required<CodegenOptions> = {\n  outputPath: path.join(getWorkspaceRoot(), 'e2e'),\n  testNamePrefix: 'Test',\n  includeComments: true\n};\n```\n\nOutput paths are handled as follows:\n- Absolute paths are used as-is\n- Relative paths are resolved from the current working directory\n\n资料来源：[src/tools/codegen/index.ts:20-30]()\n\n## Integration with MCP Tool Execution\n\nThe recording system intercepts MCP tool calls to capture execution data. Each recorded action preserves:\n\n- The exact tool name (e.g., `playwright_click`, `playwright_fill`)\n- All parameters passed to the tool\n- The timestamp of execution\n- Optional result data from the tool\n\nThis captured data enables precise reproduction of user interactions when the generated test is executed.\n\n## Error Handling\n\nThe generator validates input at initialization and during generation:\n\n| Validation | Condition | Error |\n|------------|-----------|-------|\n| Session validity | Must exist with actions array | 'Invalid session data' |\n| Output path type | Must be string if provided | 'outputPath must be a string' |\n| Test name type | Must be string if provided | 'testNamePrefix must be a string' |\n| Comments type | Must be boolean if provided | 'includeComments must be a boolean' |\n\n资料来源：[src/tools/codegen/generator.ts:22-33]()\n\n## Usage Example\n\n```bash\n# Start a recording session with custom options\nnpx @executeautomation/playwright-mcp-server\n\n# Within your MCP client, call:\n# start_codegen_session with options { outputPath: \"./tests\", testNamePrefix: \"E2E\" }\n\n# Perform actions using playwright_* tools\n# playwright_navigate, playwright_click, etc. are recorded\n\n# Generate test code from the session\n```\n\nThe generated test code can then be executed with:\n\n```bash\nnpx playwright test ./tests/generated-test.spec.ts\n```\n\n## Related Documentation\n\n- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md) - Main project documentation\n- [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md) - Version history for codegen features\n- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md) - HTTP mode integration\n\n---\n\n<a id='docker-deployment'></a>\n\n## Docker Deployment\n\n### 相关页面\n\n相关主题：[Getting Started](#getting-started), [Configuration Guide](#configuration)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [Dockerfile](https://github.com/executeautomation/mcp-playwright/blob/main/Dockerfile)\n- [docker-compose.yml](https://github.com/executeautomation/mcp-playwright/blob/main/docker-compose.yml)\n- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n- [docker-build.sh](https://github.com/executeautomation/mcp-playwright/blob/main/docker-build.sh)\n</details>\n\n# Docker Deployment\n\n## Overview\n\nThe Playwright MCP Server provides Docker containerization support, enabling isolated execution environments for browser automation tasks. Docker deployment offers consistent runtime across different systems, simplified dependency management, and easy distribution of the MCP server.\n\nThe containerized solution is designed to work with pre-built artifacts from a local build, ensuring minimal image size while maintaining full functionality for browser automation through the MCP protocol.\n\n资料来源：[DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph \"Host System\"\n        A[Local Build Directory] -->|npm install --omit=dev| B[node_modules]\n        A -->|npm run build| C[dist/]\n    end\n    \n    subgraph \"Docker Container\"\n        D[Dockerfile] -->|COPY| E[mcp-playwright:latest]\n        B -->|Production deps| E\n        C -->|Built artifacts| E\n    end\n    \n    subgraph \"Runtime Components\"\n        E -->|stdin/stdout| F[MCP Client]\n        E -->|Browser Automation| G[Playwright Browsers]\n    end\n    \n    F -->|JSON-RPC| H[Claude Desktop / VS Code / Custom Client]\n```\n\n## Prerequisites\n\n| Component | Requirement | Purpose |\n|-----------|-------------|---------|\n| Docker | Installed on host system | Container runtime |\n| Docker Compose | Optional (included with Docker Desktop) | Multi-container orchestration |\n| Node.js | For building locally | Pre-build step |\n| Local Build | `npm install --omit=dev && npm run build` | Generate artifacts for Docker COPY |\n\n资料来源：[DOCKER.md:prerequisites-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Building the Docker Image\n\n### Standard Build Process\n\nThe Dockerfile copies `node_modules` and `dist` from the local build directory directly into the image. This approach requires building artifacts locally before containerization.\n\n```bash\n# 1. Install production dependencies only\nnpm install --omit=dev\n\n# 2. Build the project\nnpm run build\n\n# 3. Build the Docker image\ndocker build -t mcp-playwright:latest .\n```\n\n### Automated Build Script\n\nA convenience script is provided for the build process:\n\n```bash\nchmod +x docker-build.sh\n./docker-build.sh\n```\n\n资料来源：[DOCKER.md:building-docker-image-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Build with Custom Tag\n\n```bash\ndocker build -t mcp-playwright:1.0.6 .\n```\n\n### Building from Source Inside Docker\n\nFor environments where you prefer building inside the container:\n\n```dockerfile\nFROM node:20-alpine AS builder\n\nWORKDIR /app\nCOPY package*.json ./\nENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\nRUN npm ci\n\nCOPY src ./src\nCOPY tsconfig.json ./\nRUN npm run build\n\nFROM node:20-alpine\nWORKDIR /app\nCOPY --from=builder /app/dist ./dist\nCOPY --from=builder /app/package*.json ./\nRUN npm ci --only=production\nCMD [\"node\", \"dist/index.js\"]\n```\n\n资料来源：[DOCKER.md:building-from-source-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Running the Server\n\n### Interactive Mode (Recommended for MCP)\n\nMCP servers communicate via stdin/stdout, requiring interactive mode for proper operation:\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n| Flag | Purpose |\n|------|---------|\n| `-i` | Keep STDIN open for interactive communication |\n| `--rm` | Automatically remove container when it exits |\n| `mcp-playwright:latest` | Image name and tag |\n\n资料来源：[DOCKER.md:running-the-server-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Using Docker Compose\n\n```bash\n# Start the server\ndocker compose run --rm playwright-mcp\n\n# Or build and run\ndocker compose build\ndocker compose run --rm playwright-mcp\n```\n\nThe provided `docker-compose.yml`:\n\n```yaml\nservices:\n  playwright-mcp:\n    build:\n      context: .\n      dockerfile: Dockerfile\n    image: mcp-playwright:latest\n    container_name: playwright-mcp-server\n    stdin_open: true\n    tty: true\n    environment:\n      - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\n```\n\n资料来源：[docker-compose.yml](https://github.com/executeautomation/mcp-playwright/blob/main/docker-compose.yml)\n\n## MCP Client Integration\n\n### Claude Desktop Configuration\n\nUpdate the Claude Desktop configuration file:\n\n| OS | Configuration Location |\n|----|----------------------|\n| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |\n| Windows | `%APPDATA%\\Claude\\claude_desktop_config.json` |\n| Linux | `~/.config/Claude/claude_desktop_config.json` |\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright-docker\": {\n      \"command\": \"docker\",\n      \"args\": [\"run\", \"-i\", \"--rm\", \"mcp-playwright:latest\"]\n    }\n  }\n}\n```\n\n资料来源：[DOCKER.md:claude-desktop-configuration-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### VS Code MCP Extension\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright-docker\": {\n      \"command\": \"docker\",\n      \"args\": [\"run\", \"-i\", \"--rm\", \"mcp-playwright:latest\"]\n    }\n  }\n}\n```\n\n资料来源：[DOCKER.md:vs-code-mcp-extension-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Configuration Options\n\n### Environment Variables\n\n| Variable | Default | Purpose |\n|----------|---------|---------|\n| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | `1` | Skip browser downloads to reduce image size |\n| `NODE_ENV` | `production` | Runtime environment |\n\n#### Using Environment Variables in Docker\n\n```bash\ndocker run -i --rm \\\n  -e PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \\\n  mcp-playwright:latest\n```\n\n#### Using Environment Variables in Docker Compose\n\n```yaml\nservices:\n  playwright-mcp:\n    environment:\n      - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\n      - NODE_ENV=production\n```\n\n资料来源：[DOCKER.md:environment-variables-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Volume Mounts\n\nFor persistent data or file sharing with the container:\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  mcp-playwright:latest\n```\n\n```yaml\nservices:\n  playwright-mcp:\n    volumes:\n      - ./data:/app/data\n      - ./screenshots:/app/screenshots\n```\n\n资料来源：[DOCKER.md:volume-mounts-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Resource Limits\n\n```bash\ndocker run -i --rm \\\n  --cpus=\"2.0\" \\\n  --memory=\"2g\" \\\n  mcp-playwright:latest\n```\n\n```yaml\nservices:\n  playwright-mcp:\n    deploy:\n      resources:\n        limits:\n          cpus: '2.0'\n          memory: 2G\n```\n\n资料来源：[DOCKER.md:resource-limits-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Custom Network Configuration\n\n```bash\n# Create custom network\ndocker network create mcp-network\n\n# Run container on custom network\ndocker run -i --rm --network mcp-network mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:advanced-usage-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Troubleshooting\n\n### Container Exits Immediately\n\nMCP servers wait for input on stdin. Ensure the `-i` flag is used:\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:troubleshooting-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Browser Not Found\n\nThe Docker image skips browser downloads by default to reduce size. Playwright downloads browsers on first use. To pre-install browsers:\n\n```dockerfile\nFROM mcp-playwright:latest\n\n# Install Playwright browsers\nRUN npx playwright install chromium --with-deps\n```\n\n资料来源：[DOCKER.md:browser-not-found-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n### Permission Issues\n\nIf encountering permission issues with mounted volumes:\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  --user $(id -u):$(id -g) \\\n  mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:permission-issues-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Health Checks\n\nAdd a health check to your docker-compose.yml:\n\n```yaml\nservices:\n  playwright-mcp:\n    healthcheck:\n      test: [\"CMD\", \"node\", \"-e\", \"process.exit(0)\"]\n      interval: 30s\n      timeout: 10s\n      retries: 3\n```\n\n资料来源：[DOCKER.md:health-checks-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Security Considerations\n\n| Practice | Implementation |\n|----------|----------------|\n| Non-root user | Add `USER node` to custom Dockerfile |\n| Read-only root filesystem | Run with `--read-only` flag |\n| Vulnerability scanning | `docker scan mcp-playwright:latest` |\n\n### Run as Non-root User (Recommended)\n\n```dockerfile\nFROM mcp-playwright:latest\nUSER node\n```\n\n### Read-only Root Filesystem\n\n```bash\ndocker run -i --rm --read-only mcp-playwright:latest\n```\n\n### Vulnerability Scanning\n\n```bash\ndocker scan mcp-playwright:latest\n```\n\n资料来源：[DOCKER.md:security-considerations-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Image Optimization\n\n| Optimization | Description |\n|--------------|-------------|\n| Base image | Debian-based slim Node.js (~200MB) |\n| Artifact strategy | Copies pre-built dist from host |\n| Dependencies | Production-only via `--omit=dev` |\n| Browser downloads | Skipped by default |\n\n**Current image size**: ~200MB (without browsers)\n\n资料来源：[DOCKER.md:image-size-optimization-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n\n## Workflow Summary\n\n```mermaid\ngraph LR\n    A[Local Build] -->|npm install --omit=dev| B[Dependencies]\n    A -->|npm run build| C[dist/]\n    B -->|COPY| D[Docker Build]\n    C -->|COPY| D\n    D -->|docker build| E[Image Created]\n    E -->|Interactive Mode| F[MCP Server Running]\n    F -->|JSON-RPC| G[MCP Client Connected]\n```\n\n## Quick Reference\n\n| Command | Description |\n|---------|-------------|\n| `docker build -t mcp-playwright:latest .` | Build image |\n| `docker run -i --rm mcp-playwright:latest` | Run in interactive mode |\n| `docker compose up` | Run via compose |\n| `docker scan mcp-playwright:latest` | Security scan |\n\n---\n\n<a id='configuration'></a>\n\n## Configuration Guide\n\n### 相关页面\n\n相关主题：[Getting Started](#getting-started), [Transport Modes](#transport-modes), [Docker Deployment](#docker-deployment)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)\n- [src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)\n- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)\n- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)\n- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)\n</details>\n\n# Configuration Guide\n\nThis guide covers all configuration options for the mcp-playwright MCP server, including stdio mode, HTTP server mode, Docker deployment, and integration with AI assistants like Claude Desktop.\n\n## Overview\n\nThe mcp-playwright server provides browser automation capabilities through the Model Context Protocol (MCP). It supports multiple transport modes and can be configured to work with different MCP clients. 资料来源：[package.json:1-50]()\n\n```mermaid\ngraph TD\n    A[MCP Client] --> B{Mode Selection}\n    B --> C[Stdio Mode]\n    B --> D[HTTP Mode]\n    B --> E[Docker Mode]\n    C --> F[stdin/stdout]\n    D --> G[localhost:8931]\n    E --> H[Docker Container]\n    F --> I[Playwright Browser]\n    G --> I\n    H --> I\n```\n\n## Stdio Mode Configuration\n\nStdio mode is the primary transport mechanism for MCP communication, using standard input/output streams. This mode is automatically selected when running via `npx` or direct node execution. 资料来源：[README.md:1-30]()\n\n### Claude Desktop Configuration\n\nFor Claude Desktop integration, add the server configuration to your Claude Desktop config file:\n\n| Platform | Config Location |\n|----------|-----------------|\n| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |\n| Windows | `%APPDATA%\\Claude\\claude_desktop_config.json` |\n| Linux | `~/.config/Claude/claude_desktop_config.json` |\n\n**Configuration schema:**\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n    }\n  }\n}\n```\n\n### VS Code MCP Extension\n\nFor VS Code with MCP extension:\n\n```json\n{\n  \"name\": \"playwright\",\n  \"command\": \"npx\",\n  \"args\": [\"-y\", \"@executeautomation/playwright-mcp-server\"]\n}\n```\n\n> **Note:** In stdio mode, logging is automatically directed to files only (not console) to maintain clean JSON-RPC communication. Logs are written to `~/playwright-mcp-server.log`. 资料来源：[README.md:25-27]()\n\n## HTTP Mode Configuration\n\nHTTP mode enables the MCP server to run as a standalone HTTP server, useful for remote deployments or IDE integrations that support HTTP transport. 资料来源：[src/http-server.ts:1-50]()\n\n### Starting the HTTP Server\n\n```bash\n# Using npx\nnpx @executeautomation/playwright-mcp-server --port 8931\n\n# Or after global installation\nnpm install -g @executeautomation/playwright-mcp-server\nplaywright-mcp-server --port 8931\n```\n\n### HTTP Server Endpoints\n\n| Endpoint | Method | Purpose |\n|----------|--------|---------|\n| `/sse` | GET | SSE Stream for Server-Sent Events |\n| `/messages` | POST | Send messages with session ID |\n| `/mcp` | GET/POST | Unified MCP endpoint |\n| `/health` | GET | Health check endpoint |\n\n### Security Configuration\n\nThe HTTP server binds to `127.0.0.1` (localhost only) by default to prevent external network access. 资料来源：[src/http-server.ts:35-36]()\n\n```typescript\nconst host = '127.0.0.1';\nconst httpServer = app.listen(port, host, () => {\n  logger.info(`Playwright MCP HTTP server listening on ${host}:${port}`);\n});\n```\n\n### Claude Desktop HTTP Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright\": {\n      \"url\": \"http://localhost:8931/mcp\"\n    }\n  }\n}\n```\n\n### Health Check\n\n```bash\ncurl http://localhost:8931/health\n```\n\nResponse format:\n\n```json\n{\n  \"status\": \"ok\",\n  \"version\": \"1.0.10\",\n  \"activeSessions\": 0\n}\n```\n\n## Docker Configuration\n\nThe Docker image provides a containerized deployment option for the mcp-playwright server. 资料来源：[DOCKER.md:1-50]()\n\n### Basic Docker Run\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n| Flag | Purpose |\n|------|---------|\n| `-i` | Keep STDIN open for interactive communication |\n| `--rm` | Automatically remove container on exit |\n\n### Docker Compose Configuration\n\n```yaml\nservices:\n  playwright-mcp:\n    image: mcp-playwright:latest\n```\n\n### Claude Desktop Docker Configuration\n\n```json\n{\n  \"mcpServers\": {\n    \"playwright-docker\": {\n      \"command\": \"docker\",\n      \"args\": [\"run\", \"-i\", \"--rm\", \"mcp-playwright:latest\"]\n    }\n  }\n}\n```\n\n### VS Code Docker Configuration\n\n```json\n{\n  \"name\": \"playwright-docker\",\n  \"command\": \"docker\",\n  \"args\": [\"run\", \"-i\", \"--rm\", \"mcp-playwright:latest\"]\n}\n```\n\n## Environment Variables\n\nConfigure server behavior using environment variables. 资料来源：[DOCKER.md:20-35]()\n\n### Available Environment Variables\n\n| Variable | Purpose | Default |\n|----------|---------|---------|\n| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser downloads during image build | `1` (enabled) |\n| `NODE_ENV` | Node environment setting | `production` |\n\n### Docker Environment Variable Examples\n\n**Via docker run:**\n\n```bash\ndocker run -i --rm \\\n  -e PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \\\n  -e NODE_ENV=production \\\n  mcp-playwright:latest\n```\n\n**Via docker-compose.yml:**\n\n```yaml\nservices:\n  playwright-mcp:\n    environment:\n      - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\n      - NODE_ENV=production\n```\n\n## Volume Mounts\n\nShare files and persist data between the host and container. 资料来源：[DOCKER.md:36-50]()\n\n### Docker Volume Examples\n\n**Via docker run:**\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  -v $(pwd)/screenshots:/app/screenshots \\\n  mcp-playwright:latest\n```\n\n**Via docker-compose.yml:**\n\n```yaml\nservices:\n  playwright-mcp:\n    volumes:\n      - ./data:/app/data\n      - ./screenshots:/app/screenshots\n```\n\n### User and Permissions\n\nHandle permission issues with mounted volumes by specifying user:\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd)/data:/app/data \\\n  --user $(id -u):$(id -g) \\\n  mcp-playwright:latest\n```\n\n## Resource Limits\n\nConfigure CPU and memory constraints for containerized deployments. 资料来源：[DOCKER.md:85-100]()\n\n### Docker Resource Limits\n\n```yaml\nservices:\n  playwright-mcp:\n    deploy:\n      resources:\n        limits:\n          cpus: '2.0'\n          memory: 2G\n```\n\n**Via docker run:**\n\n```bash\ndocker run -i --rm \\\n  --cpus=\"2.0\" \\\n  --memory=\"2g\" \\\n  mcp-playwright:latest\n```\n\n## Network Configuration\n\n### Custom Network\n\n```bash\ndocker network create mcp-network\ndocker run -i --rm --network mcp-network mcp-playwright:latest\n```\n\n### Security Considerations\n\n| Configuration | Recommendation |\n|---------------|-----------------|\n| Run as non-root user | Optional but recommended |\n| Read-only root filesystem | For containers not needing write access |\n| Vulnerability scanning | Use `docker scan mcp-playwright:latest` |\n\n## Health Checks\n\nAdd health check configuration to docker-compose.yml:\n\n```yaml\nservices:\n  playwright-mcp:\n    healthcheck:\n      test: [\"CMD\", \"node\", \"-e\", \"process.exit(0)\"]\n      interval: 30s\n      timeout: 10s\n      retries: 3\n```\n\n## Troubleshooting Configuration Issues\n\n### Container Exits Immediately\n\nMCP servers wait for input on stdin. Ensure the `-i` flag is used:\n\n```bash\ndocker run -i --rm mcp-playwright:latest\n```\n\n### Browser Not Found\n\nThe Docker image skips browser downloads by default. To pre-install browsers, create a custom Dockerfile:\n\n```dockerfile\nFROM mcp-playwright:latest\nRUN npx playwright install chromium --with-deps\n```\n\n## Tool Name Length Constraints\n\nWhen adding new tools, consider the combined server and tool name length. Some clients like Cursor have a 60-character limit for `server_name:tool_name`. 资料来源：[README.md:10-15]()\n\nCurrent server name: `playwright-mcp`\n\nEnsure tool names are short enough to not exceed this limit when combined.\n\n## Image Specifications\n\n| Aspect | Value |\n|--------|-------|\n| Base image | Debian-based slim Node.js (~200MB) |\n| Default size | ~200MB (without browsers) |\n| Dependencies | Production only (no dev dependencies) |\n\n## Building Custom Docker Images\n\n### Optimized Build (Recommended)\n\nUses pre-built artifacts from local development:\n\n```dockerfile\nFROM node:20-slim\nWORKDIR /app\nCOPY package*.json ./\nRUN npm ci --omit=dev\nCOPY node_modules ./node_modules\nCOPY dist ./dist\nCMD [\"node\", \"dist/index.js\"]\n```\n\n### Full Build from Source\n\n```dockerfile\nFROM node:20-alpine AS builder\nWORKDIR /app\nCOPY package*.json ./\nENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1\nRUN npm ci\n\nCOPY src ./src\nCOPY tsconfig.json ./\nRUN npm run build\n\nFROM node:20-alpine\nWORKDIR /app\nCOPY --from=builder /app/dist ./dist\nCOPY --from=builder /app/package*.json ./\nRUN npm ci --only=production\nCMD [\"node\", \"dist/index.js\"]\n```\n\n## Dependencies Configuration\n\nThe package.json defines core dependencies for the MCP server. 资料来源：[package.json:10-35]()\n\n### Runtime Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `@modelcontextprotocol/sdk` | 1.24.3 | MCP protocol implementation |\n| `@playwright/browser-chromium` | 1.57.0 | Chromium browser |\n| `@playwright/browser-firefox` | 1.57.0 | Firefox browser |\n| `@playwright/browser-webkit` | 1.57.0 | WebKit browser |\n| `express` | ^4.21.1 | HTTP server framework |\n| `cors` | ^2.8.5 | Cross-origin resource sharing |\n| `uuid` | 11.1.0 | UUID generation |\n\n### Development Dependencies\n\n| Package | Version | Purpose |\n|---------|---------|---------|\n| `typescript` | ^5.8.3 | TypeScript compiler |\n| `jest` | ^29.7.0 | Testing framework |\n| `@types/node` | ^20.10.5 | Node.js type definitions |\n| `@types/express` | ^4.17.21 | Express type definitions |\n| `jest-playwright-preset` | 4.0.0 | Playwright Jest integration |\n\n## Logging Configuration\n\nIn stdio mode, logs are automatically directed to files to maintain clean JSON-RPC communication. 资料来源：[README.md:27]()\n\nLog file location: `~/playwright-mcp-server.log`\n\nThe logging middleware captures:\n- Request IDs for traceability\n- Tool execution timing and results\n- Error categorization (validation, system, resource, authentication, rate_limit)\n- Sanitized request bodies (sensitive fields redacted)\n\n## Summary\n\n| Transport Mode | Use Case | Config Key |\n|---------------|----------|------------|\n| Stdio | Claude Desktop, local MCP clients | `command: \"npx\"` |\n| HTTP | Remote deployments, VS Code | `url: \"http://localhost:8931/mcp\"` |\n| Docker | Containerized environments | `command: \"docker\"` |\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：executeautomation/mcp-playwright\n\n摘要：发现 16 个潜在踩坑项，其中 2 个为 high/blocking；最高优先级：安装坑 - 来源证据：Playwright is asking for an specific browser version.。\n\n## 1. 安装坑 · 来源证据：Playwright is asking for an specific browser version.\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Playwright is asking for an specific browser version.\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_38465ac94a9d4fb0bd352ba5209096ac | https://github.com/executeautomation/mcp-playwright/issues/117 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 2. 安全/权限坑 · 来源证据：How to configure proxy and storageState when launching browser in Playwright MCP?\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：How to configure proxy and storageState when launching browser in Playwright MCP?\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a2f7e4a410994d4195a9af9f139e0caa | https://github.com/executeautomation/mcp-playwright/issues/203 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 3. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | host_targets=mcp_host, claude, cursor\n\n## 4. 配置坑 · 来源证据：Add Clarvia AEO score badge to README (AEO 32/100)\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Add Clarvia AEO score badge to README (AEO 32/100)\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_74959d07d5f74165bcd9cae829d384ce | https://github.com/executeautomation/mcp-playwright/issues/212 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 5. 配置坑 · 来源证据：Add policy enforcement for browser automation and HTTP request tools\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Add policy enforcement for browser automation and HTTP request tools\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_23a30d245f794b8db40c1d031b8be565 | https://github.com/executeautomation/mcp-playwright/issues/216 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 6. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | README/documentation is current enough for a first validation pass.\n\n## 7. 运行坑 · 来源证据：How to pass in the `--ignore-https-errors` parameter?\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：How to pass in the `--ignore-https-errors` parameter?\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_47d5e333819d49b4b8ce2abb9484b23d | https://github.com/executeautomation/mcp-playwright/issues/202 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 8. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | last_activity_observed missing\n\n## 9. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | no_demo; severity=medium\n\n## 10. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 11. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | no_demo; severity=medium\n\n## 12. 安全/权限坑 · 来源证据：Feature Request: Add browser context persistence for login state (userDataDir/storageState)\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Request: Add browser context persistence for login state (userDataDir/storageState)\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_3632e6a11e044dda870b3267ccfa3040 | https://github.com/executeautomation/mcp-playwright/issues/201 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 13. 安全/权限坑 · 来源证据：Free MCP security scan report for @executeautomation/playwright-mcp-server\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Free MCP security scan report for @executeautomation/playwright-mcp-server\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9720dc9967444ed08710cdb0660a212a | https://github.com/executeautomation/mcp-playwright/issues/211 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 14. 安全/权限坑 · 来源证据：Security Advisory: SSRF, Prompt Injection, and Arbitrary JavaScript Execution via Browser Automation Tools\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Security Advisory: SSRF, Prompt Injection, and Arbitrary JavaScript Execution via Browser Automation Tools\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ced642164084421f84bbb63681653057 | https://github.com/executeautomation/mcp-playwright/issues/209 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 15. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | issue_or_pr_quality=unknown\n\n## 16. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | release_recency=unknown\n\n<!-- canonical_name: executeautomation/mcp-playwright; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Human Manual / 人类版说明书"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log / 踩坑日志\n\n项目：executeautomation/mcp-playwright\n\n摘要：发现 16 个潜在踩坑项，其中 2 个为 high/blocking；最高优先级：安装坑 - 来源证据：Playwright is asking for an specific browser version.。\n\n## 1. 安装坑 · 来源证据：Playwright is asking for an specific browser version.\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Playwright is asking for an specific browser version.\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_38465ac94a9d4fb0bd352ba5209096ac | https://github.com/executeautomation/mcp-playwright/issues/117 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 2. 安全/权限坑 · 来源证据：How to configure proxy and storageState when launching browser in Playwright MCP?\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：How to configure proxy and storageState when launching browser in Playwright MCP?\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a2f7e4a410994d4195a9af9f139e0caa | https://github.com/executeautomation/mcp-playwright/issues/203 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 3. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | host_targets=mcp_host, claude, cursor\n\n## 4. 配置坑 · 来源证据：Add Clarvia AEO score badge to README (AEO 32/100)\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Add Clarvia AEO score badge to README (AEO 32/100)\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_74959d07d5f74165bcd9cae829d384ce | https://github.com/executeautomation/mcp-playwright/issues/212 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 5. 配置坑 · 来源证据：Add policy enforcement for browser automation and HTTP request tools\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Add policy enforcement for browser automation and HTTP request tools\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_23a30d245f794b8db40c1d031b8be565 | https://github.com/executeautomation/mcp-playwright/issues/216 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 6. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | README/documentation is current enough for a first validation pass.\n\n## 7. 运行坑 · 来源证据：How to pass in the `--ignore-https-errors` parameter?\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：How to pass in the `--ignore-https-errors` parameter?\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_47d5e333819d49b4b8ce2abb9484b23d | https://github.com/executeautomation/mcp-playwright/issues/202 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 8. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | last_activity_observed missing\n\n## 9. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | no_demo; severity=medium\n\n## 10. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 11. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | no_demo; severity=medium\n\n## 12. 安全/权限坑 · 来源证据：Feature Request: Add browser context persistence for login state (userDataDir/storageState)\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Feature Request: Add browser context persistence for login state (userDataDir/storageState)\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_3632e6a11e044dda870b3267ccfa3040 | https://github.com/executeautomation/mcp-playwright/issues/201 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 13. 安全/权限坑 · 来源证据：Free MCP security scan report for @executeautomation/playwright-mcp-server\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Free MCP security scan report for @executeautomation/playwright-mcp-server\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9720dc9967444ed08710cdb0660a212a | https://github.com/executeautomation/mcp-playwright/issues/211 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 14. 安全/权限坑 · 来源证据：Security Advisory: SSRF, Prompt Injection, and Arbitrary JavaScript Execution via Browser Automation Tools\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Security Advisory: SSRF, Prompt Injection, and Arbitrary JavaScript Execution via Browser Automation Tools\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ced642164084421f84bbb63681653057 | https://github.com/executeautomation/mcp-playwright/issues/209 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 15. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | issue_or_pr_quality=unknown\n\n## 16. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# mcp-playwright - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for executeautomation/mcp-playwright.\n\nProject:\n- Name: mcp-playwright\n- Repository: https://github.com/executeautomation/mcp-playwright\n- Summary: Playwright Model Context Protocol Server - Tool to automate Browsers and APIs in Claude Desktop, Cline, Cursor IDE and More 🔌\n- Host target: mcp_host, claude, cursor\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Playwright Model Context Protocol Server - Tool to automate Browsers and APIs in Claude Desktop, Cline, Cursor IDE and More 🔌\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Playwright Model Context Protocol Server - Tool to automate Browsers and APIs in Claude Desktop, Cline, Cursor IDE and More 🔌\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. project-introduction: Project Introduction. Produce one small intermediate artifact and wait for confirmation.\n2. getting-started: Getting Started. Produce one small intermediate artifact and wait for confirmation.\n3. architecture-overview: Architecture Overview. Produce one small intermediate artifact and wait for confirmation.\n4. transport-modes: Transport Modes. Produce one small intermediate artifact and wait for confirmation.\n5. browser-automation: Browser Automation Tools. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/executeautomation/mcp-playwright\n- https://github.com/executeautomation/mcp-playwright#readme\n- README.md\n- package.json\n- CHANGELOG.md\n- mcp-config.json\n- DOCKER.md\n- Dockerfile\n- src/index.ts\n- src/toolHandler.ts\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：executeautomation/mcp-playwright\n\n## 官方安装入口\n\n### Node.js / npm · 官方安装入口\n\n```bash\nnpm install -g @executeautomation/playwright-mcp-server\n```\n\n来源：https://github.com/executeautomation/mcp-playwright#readme\n\n## 来源\n\n- repo: https://github.com/executeautomation/mcp-playwright\n- docs: https://github.com/executeautomation/mcp-playwright#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_f8a266e7fd954a8a844a96cb7b062319"
}
