{
  "canonical_name": "hangwin/mcp-chrome",
  "compilation_id": "pack_4439a597b9e741afaccca508259275b2",
  "created_at": "2026-05-19T11:52:48.638648+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 mcp-chrome-bridge` 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 mcp-chrome-bridge",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_1a65d5bed20b442b96b8d64c89709e37"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_ab38dd86b62d6e551031fd52eb98cdcc",
    "canonical_name": "hangwin/mcp-chrome",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/hangwin/mcp-chrome",
    "slug": "mcp-chrome",
    "source_packet_id": "phit_97e77b470a2841a9a4e0566988aa9539",
    "source_validation_id": "dval_a6d83c5a87334dad90fad29e067b04a9"
  },
  "merchandising": {
    "best_for": "需要工具连接与集成能力，并使用 mcp_host的用户",
    "github_forks": 1044,
    "github_stars": 11608,
    "one_liner_en": "Chrome MCP Server is a Chrome extension-based Model Context Protocol (MCP) server that exposes your Chrome browser functionality to AI assistants like Claude, enabling complex browser automation, content analysis, and semantic search.",
    "one_liner_zh": "Chrome MCP Server is a Chrome extension-based Model Context Protocol (MCP) server that exposes your Chrome browser functionality to AI assistants like Claude, enabling complex browser automation, content analysis, and semantic search.",
    "primary_category": {
      "category_id": "tool-integrations",
      "confidence": "high",
      "name_en": "Tool Integrations",
      "name_zh": "工具连接与集成",
      "reason": "matched_keywords:mcp, server, github"
    },
    "target_user": "使用 mcp_host, claude 等宿主 AI 的用户",
    "title_en": "mcp-chrome",
    "title_zh": "mcp-chrome 能力包",
    "visible_tags": [
      {
        "label_en": "Browser Agents",
        "label_zh": "浏览器 Agent",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-browser-agents",
        "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": "Page Observation and Action Planning",
        "label_zh": "页面观察与动作规划",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-page-observation-and-action-planning",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Structured Data Extraction",
        "label_zh": "结构化数据提取",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-structured-data-extraction",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_97e77b470a2841a9a4e0566988aa9539",
  "page_model": {
    "artifacts": {
      "artifact_slug": "mcp-chrome",
      "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 mcp-chrome-bridge",
          "label": "Node.js / npm · 官方安装入口",
          "source": "https://github.com/hangwin/mcp-chrome#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "自然语言网页操作",
        "页面观察与动作规划",
        "结构化数据提取"
      ],
      "eyebrow": "工具连接与集成",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要工具连接与集成能力，并使用 mcp_host的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "Chrome MCP Server is a Chrome extension-based Model Context Protocol (MCP) server that exposes your Chrome browser functionality to AI assistants like Claude, enabling complex browser automation, content analysis, and semantic search."
        },
        {
          "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",
          "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 社区证据显示该项目存在一个安装相关的待验证问题：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_ba76885913a744f0832665f5c62d0f1d | https://github.com/hangwin/mcp-chrome/issues/321 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed to connect to MCP server)",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_4ac5f778b292489482bfdb7953190f96 | https://github.com/hangwin/mcp-chrome/issues/319 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "high",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed to connect to MCP server)",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Codex CLI setup guide still points to ~/.codex/config.json and a port-only flow Codex does not pick up",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_559f34b86ade48e598dac510e9341b9e | https://github.com/hangwin/mcp-chrome/issues/339 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Codex CLI setup guide still points to ~/.codex/config.json and a port-only flow Codex does not pick up",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature] Profile-aware bridge — multi-Chrome-profile support without port collision",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_93bfb3c85fbc4c0a8134e7159ddf4511 | https://github.com/hangwin/mcp-chrome/issues/347 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[Feature] Profile-aware bridge — multi-Chrome-profile support without port collision",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：mcp-chrome-bridge 无法使用",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_5f19fb6526174af2abe5c1eab67e25ff | https://github.com/hangwin/mcp-chrome/issues/333 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：mcp-chrome-bridge 无法使用",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安装相关的待验证问题：🐛 Status indicator stuck on yellow - Service shows as \"not started\" after connection",
            "category": "安装坑",
            "evidence": [
              "community_evidence:github | cevd_2b32536c95a7456788ba78e1fc705116 | https://github.com/hangwin/mcp-chrome/issues/342 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：🐛 Status indicator stuck on yellow - Service shows as \"not started\" after connection",
            "user_impact": "可能影响升级、迁移或版本选择。"
          },
          {
            "body": "项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。",
            "category": "配置坑",
            "evidence": [
              "capability.host_targets | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | host_targets=mcp_host, claude"
            ],
            "severity": "medium",
            "suggested_check": "列出会写入的配置文件、目录和卸载/回滚步骤。",
            "title": "可能修改宿主 AI 配置",
            "user_impact": "安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.0.6",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_035dffafcbe64f4ea112f20258430e71 | https://github.com/hangwin/mcp-chrome/releases/tag/v0.0.6 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.0.6",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[Feature/Bug] Multi-client MCP support — second Claude Code session kills first via shared MCP Server singleton",
            "category": "维护坑",
            "evidence": [
              "community_evidence:github | cevd_4d4eaf47bd284105af5632bbe220b628 | https://github.com/hangwin/mcp-chrome/issues/345 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：[Feature/Bug] Multi-client MCP support — second Claude Code session kills first via shared MCP Server singleton",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | 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:998796026 | https://github.com/hangwin/mcp-chrome | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：issue",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_82ad93635a5e4ff5aeb2b35e36cbd02e | https://github.com/hangwin/mcp-chrome/issues/330 | 来源讨论提到 node 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：issue",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "issue_or_pr_quality=unknown。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | 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:998796026 | https://github.com/hangwin/mcp-chrome | release_recency=unknown"
            ],
            "severity": "low",
            "suggested_check": "确认最近 release/tag 和 README 安装命令是否一致。",
            "title": "发布节奏不明确",
            "user_impact": "安装命令和文档可能落后于代码，用户踩坑概率升高。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 16 个潜在踩坑项，其中 2 个为 high/blocking；最高优先级：安装坑 - 来源证据：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": 17,
        "forks": 1044,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": 11608
      },
      "source_url": "https://github.com/hangwin/mcp-chrome",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "Chrome MCP Server is a Chrome extension-based Model Context Protocol (MCP) server that exposes your Chrome browser functionality to AI assistants like Claude, enabling complex browser automation, content analysis, and semantic search.",
      "title": "mcp-chrome 能力包",
      "trial_prompt": "# mcp-chrome - 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 hangwin/mcp-chrome.\n\nProject:\n- Name: mcp-chrome\n- Repository: https://github.com/hangwin/mcp-chrome\n- Summary: Chrome MCP Server is a Chrome extension-based Model Context Protocol (MCP) server that exposes your Chrome browser functionality to AI assistants like Claude, enabling complex browser automation, content analysis, and semantic search.\n- Host target: mcp_host, claude\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Chrome MCP Server is a Chrome extension-based Model Context Protocol (MCP) server that exposes your Chrome browser functionality to AI assistants like Claude, enabling complex browser automation, content analysis, and semantic search.\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: Chrome MCP Server is a Chrome extension-based Model Context Protocol (MCP) server that exposes your Chrome browser functionality to AI assistants like Claude, enabling complex browser automation, content analysis, and semantic search.\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. page-introduction: Introduction to Chrome MCP Server. Produce one small intermediate artifact and wait for confirmation.\n2. page-quickstart: Quick Start Guide. Produce one small intermediate artifact and wait for confirmation.\n3. page-architecture: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n4. page-communication: Communication Protocols. Produce one small intermediate artifact and wait for confirmation.\n5. page-extension-structure: Chrome Extension Structure. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/hangwin/mcp-chrome\n- https://github.com/hangwin/mcp-chrome#readme\n- README.md\n- app/chrome-extension/manifest.json\n- app/chrome-extension/README.md\n- app/native-server/README.md\n- docs/ARCHITECTURE.md\n- app/chrome-extension/common/message-types.ts\n- app/native-server/src/index.ts\n- app/chrome-extension/entrypoints/background/native-host.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: Bug: Singleton McpServer causes 'Already connected to a transport' on HT（https://github.com/hangwin/mcp-chrome/issues/321）；github/github_issue: [Feature] Profile-aware bridge — multi-Chrome-profile support without po（https://github.com/hangwin/mcp-chrome/issues/347）；github/github_issue: [Feature/Bug] Multi-client MCP support — second Claude Code session kill（https://github.com/hangwin/mcp-chrome/issues/345）；github/github_issue: 🐛 Status indicator stuck on yellow - Service shows as \"not started\" afte（https://github.com/hangwin/mcp-chrome/issues/342）；github/github_issue: Bug: Singleton McpServer causes 'Already connected to a transport' on HT（https://github.com/hangwin/mcp-chrome/issues/321）；github/github_issue: Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed t（https://github.com/hangwin/mcp-chrome/issues/319）；github/github_issue: Codex CLI setup guide still points to ~/.codex/config.json and a port-on（https://github.com/hangwin/mcp-chrome/issues/339）；github/github_issue: mcp-chrome-bridge 无法使用（https://github.com/hangwin/mcp-chrome/issues/333）；github/github_issue: issue（https://github.com/hangwin/mcp-chrome/issues/330）；github/github_release: v0.0.6（https://github.com/hangwin/mcp-chrome/releases/tag/v0.0.6）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Bug: Singleton McpServer causes 'Already connected to a transport' on HT",
              "url": "https://github.com/hangwin/mcp-chrome/issues/321"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Feature] Profile-aware bridge — multi-Chrome-profile support without po",
              "url": "https://github.com/hangwin/mcp-chrome/issues/347"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "[Feature/Bug] Multi-client MCP support — second Claude Code session kill",
              "url": "https://github.com/hangwin/mcp-chrome/issues/345"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "🐛 Status indicator stuck on yellow - Service shows as \"not started\" afte",
              "url": "https://github.com/hangwin/mcp-chrome/issues/342"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Bug: Singleton McpServer causes 'Already connected to a transport' on HT",
              "url": "https://github.com/hangwin/mcp-chrome/issues/321"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed t",
              "url": "https://github.com/hangwin/mcp-chrome/issues/319"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Codex CLI setup guide still points to ~/.codex/config.json and a port-on",
              "url": "https://github.com/hangwin/mcp-chrome/issues/339"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "mcp-chrome-bridge 无法使用",
              "url": "https://github.com/hangwin/mcp-chrome/issues/333"
            },
            {
              "kind": "github_issue",
              "source": "github",
              "title": "issue",
              "url": "https://github.com/hangwin/mcp-chrome/issues/330"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.0.6",
              "url": "https://github.com/hangwin/mcp-chrome/releases/tag/v0.0.6"
            }
          ],
          "status": "已收录 10 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "工具连接与集成",
      "desc": "Chrome MCP Server is a Chrome extension-based Model Context Protocol (MCP) server that exposes your Chrome browser functionality to AI assistants like Claude, enabling complex browser automation, content analysis, and semantic search.",
      "effort": "安装已验证",
      "forks": 1044,
      "icon": "link",
      "name": "mcp-chrome 能力包",
      "risk": "可发布",
      "slug": "mcp-chrome",
      "stars": 11608,
      "tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "自然语言网页操作",
        "页面观察与动作规划",
        "结构化数据提取"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/hangwin/mcp-chrome 项目说明书\n\n生成时间：2026-05-16 01:25:43 UTC\n\n## 目录\n\n- [Introduction to Chrome MCP Server](#page-introduction)\n- [Quick Start Guide](#page-quickstart)\n- [System Architecture](#page-architecture)\n- [Communication Protocols](#page-communication)\n- [Chrome Extension Structure](#page-extension-structure)\n- [Browser Tools and APIs](#page-browser-tools)\n- [Record and Replay Engine](#page-record-replay)\n- [MCP Server Implementation](#page-mcp-server)\n- [AI Agent Engines](#page-agent-engines)\n- [Storage and Data Management](#page-storage)\n\n<a id='page-introduction'></a>\n\n## Introduction to Chrome MCP Server\n\n### 相关页面\n\n相关主题：[System Architecture](#page-architecture)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/hangwin/mcp-chrome/blob/main/README.md)\n- [app/native-server/src/scripts/utils.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n- [app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n- [app/native-server/src/scripts/browser-config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/browser-config.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/common.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n- [app/chrome-extension/utils/content-indexer.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n- [packages/wasm-simd/package.json](https://github.com/hangwin/mcp-chrome/blob/main/packages/wasm-simd/package.json)\n</details>\n\n# Introduction to Chrome MCP Server\n\nChrome MCP Server is a Model Context Protocol (MCP) implementation that bridges AI assistants with Chrome/Chromium browsers, enabling AI-powered browser automation, content analysis, and control through a comprehensive set of tools. The project consists of two main components: a Chrome extension that runs in the browser and a native server that communicates with AI clients via the MCP protocol.\n\n## Overview and Purpose\n\nChrome MCP Server provides AI assistants with the ability to interact with web pages, manage browser tabs, capture screenshots, monitor network traffic, and perform automated actions. By exposing browser functionality as MCP tools, developers can create AI agents that can browse the web, fill forms, click elements, search history, and analyze page content.\n\n资料来源：[README.md:1-20](https://github.com/hangwin/mcp-chrome/blob/main/README.md)\n\n## System Architecture\n\nThe Chrome MCP Server architecture consists of multiple interconnected components that work together to provide browser automation capabilities.\n\n### Component Overview\n\n```mermaid\ngraph TD\n    A[\"AI Client<br/>(Claude, etc.)\"] --> B[\"MCP Chrome Bridge<br/>(mcp-chrome-bridge)\"]\n    B --> C[\"Native Server<br/>(Node.js)\"]\n    C <--> D[\"Chrome Extension<br/>(WXT-based)\"]\n    D --> E[\"Chrome Browser\"]\n    F[\"Web Content Scripts\"] --> D\n    G[\"Injected Scripts\"] --> E\n```\n\n### Native Messaging Host Configuration\n\nThe native server registers itself as a Native Messaging Host with the operating system, enabling secure communication between native applications and Chrome extensions.\n\n| Platform | User-Level Path | System-Level Path |\n|----------|-----------------|-------------------|\n| Windows | `%APPDATA%\\Google\\Chrome\\NativeMessagingHosts\\` | `%ProgramFiles%\\Google\\Chrome\\NativeMessagingHosts\\` |\n| macOS | `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/` | `/Library/Google/Chrome/NativeMessagingHosts/` |\n| Linux | `~/.config/google-chrome/NativeMessagingHosts/` | `/etc/opt/chrome/native-messaging-hosts/` |\n\n资料来源：[app/native-server/src/scripts/utils.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n\nThe `HOST_NAME` constant identifies the native messaging host configuration file, which Chrome reads to establish the connection with the native server.\n\n### Chrome Extension Structure\n\nThe Chrome extension is built using WXT, a modern build tool for Chrome extensions. The extension configuration includes security policies, content scripts, and web-accessible resources.\n\n```typescript\n// Key configuration from wxt.config.ts\nweb_accessible_resources: [\n  {\n    resources: [\n      '/models/*',      // ML models for semantic search\n      '/workers/*',     // Web Workers for background tasks\n      '/inject-scripts/*', // Scripts injected into web pages\n    ],\n    matches: ['<all_urls>'],\n  },\n]\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:1-30](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n## Tool Categories\n\nChrome MCP Server organizes its functionality into several tool categories, each targeting specific browser interaction needs.\n\n### Navigation and Tab Management\n\n| Tool | Purpose |\n|------|---------|\n| `chrome_navigate` | Navigate to URLs with viewport control |\n| `chrome_switch_tab` | Switch the current active tab |\n| `chrome_close_tabs` | Close specific tabs or windows |\n| `chrome_go_back_or_forward` | Browser navigation control |\n\nThese tools enable AI assistants to control the browser's navigation state and manage multiple tabs programmatically. The `chrome_close_tabs` function, for example, accepts URL patterns to match and close multiple tabs at once.\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/common.ts:1-80](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n\n### Content Interaction\n\n| Tool | Purpose |\n|------|---------|\n| `chrome_click_element` | Click elements using CSS selectors |\n| `chrome_fill_or_select` | Fill forms and select options |\n| `chrome_keyboard` | Simulate keyboard input and shortcuts |\n| `chrome_inject_script` | Inject content scripts into web pages |\n| `chrome_send_command_to_inject_script` | Send commands to injected content scripts |\n\nThe interaction tools support complex user interaction scenarios by translating high-level commands into browser automation actions.\n\n### Network Monitoring\n\n| Tool | Purpose |\n|------|---------|\n| `chrome_network_capture_start/stop` | Capture network requests via webRequest API |\n| `chrome_network_debugger_start/stop` | Debugger API with response bodies |\n| `chrome_network_request` | Send custom HTTP requests |\n\n资料来源：[README.md:40-55](https://github.com/hangwin/mcp-chrome/blob/main/README.md)\n\n### Content Analysis\n\n| Tool | Purpose |\n|------|---------|\n| `search_tabs_content` | AI-powered semantic search across browser tabs |\n| `chrome_get_web_content` | Extract HTML/text content from pages |\n| `chrome_get_interactive_elements` | Find clickable elements |\n| `chrome_console` | Capture and retrieve console output |\n\nThe content analysis tools leverage semantic search capabilities powered by WebAssembly-optimized math functions for cosine similarity and vector operations.\n\n资料来源：[packages/wasm-simd/package.json:1-30](https://github.com/hangwin/mcp-chrome/blob/main/packages/wasm-simd/package.json)\n\n### Screenshots\n\n| Tool | Purpose |\n|------|---------|\n| `chrome_screenshot` | Advanced screenshot capture with element targeting, full-page support, and custom dimensions |\n\n### Data Management\n\n| Tool | Purpose |\n|------|---------|\n| `chrome_history` | Search browser history with time filters |\n| `chrome_bookmark_search` | Find bookmarks by keywords |\n| `chrome_bookmark_add` | Add new bookmarks with folder support |\n| `chrome_bookmark_delete` | Delete bookmarks |\n\n## Content Indexing System\n\nThe Chrome extension includes a sophisticated content indexing system that enables semantic search across open browser tabs.\n\n```mermaid\ngraph LR\n    A[\"Tab Load Complete\"] --> B[\"ContentIndexer\"]\n    B --> C{\"URL Excluded?\"}\n    C -->|Yes| D[\"Skip\"]\n    C -->|No| E[\"Execute web-fetcher-helper.js\"]\n    E --> F[\"Extract Metadata\"]\n    F --> G[\"Index Content\"]\n    G --> H[\"Searchable Index\"]\n```\n\nThe indexer automatically processes tabs when they complete loading, extracting text content, titles, and metadata. It excludes internal Chrome URLs, extensions, and local files.\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:1-60](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n\n### URL Exclusion Patterns\n\nThe content indexer skips indexing for the following URL patterns:\n\n| Pattern | Description |\n|---------|-------------|\n| `chrome://*` | Internal Chrome pages |\n| `chrome-extension://*` | Extension pages |\n| `edge://*` | Microsoft Edge pages |\n| `about:*` | About pages |\n| `moz-extension://*` | Firefox extension pages |\n| `file://*` | Local files |\n\n## Web Fetcher Tool\n\nThe `chrome_get_web_content` tool provides flexible content extraction from web pages.\n\n```typescript\ninterface WebFetcherToolParams {\n  htmlContent?: boolean;  // Get visible HTML content\n  textContent?: boolean;  // Get visible text content\n  url?: string;           // Optional URL to fetch\n  selector?: string;      // CSS selector for specific elements\n  tabId?: number;         // Target existing tab\n  background?: boolean;   // Don't activate/focus tab\n  windowId?: number;      // Target window\n}\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/web-fetcher.ts:1-30](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/web-fetcher.ts)\n\n### Metadata Extraction\n\nThe injected web fetcher script extracts comprehensive metadata from web pages:\n\n| Field | Source Priority |\n|-------|-----------------|\n| title | JSON-LD → Open Graph → Twitter Cards |\n| byline | JSON-LD → Meta tags |\n| excerpt | JSON-LD → Open Graph → Twitter |\n| siteName | Open Graph |\n| publishedTime | JSON-LD → Article tags |\n\nAll values are automatically unescaped from HTML entities to ensure proper formatting.\n\n资料来源：[app/chrome-extension/inject-scripts/web-fetcher-helper.js:1-100](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/inject-scripts/web-fetcher-helper.js)\n\n## Record and Replay System\n\nThe extension includes a record-replay engine for automating browser interactions. The wait policies ensure that automated actions wait for appropriate page states before proceeding.\n\n```typescript\n// Wait policies monitor various browser events\nchrome.webNavigation.onCommitted  // Page navigation committed\nchrome.webNavigation.onCompleted  // Page fully loaded\nchrome.tabs.onUpdated             // Tab state changes\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts)\n\n## Security Configuration\n\nThe extension implements a multi-layered security model:\n\n| Environment | COEP | COOP | CSP |\n|-------------|------|------|-----|\n| Development | Disabled (WXT default) | Disabled (WXT default) | Relaxed for HMR |\n| Production | `require-corp` | `same-origin` | Strict |\n\nThe Content Security Policy for production enforces:\n- Scripts: `'self' 'wasm-unsafe-eval'`\n- Objects: `'self'`\n- Styles: `'self' 'unsafe-inline'`\n- Images: `'self' data: blob:`\n\n资料来源：[app/chrome-extension/wxt.config.ts:25-40](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n## Browser Configuration Support\n\nThe native server supports multiple browsers and platforms:\n\n| Browser | Windows | macOS | Linux |\n|---------|---------|-------|-------|\n| Chrome | ✅ | ✅ | ✅ |\n| Chromium | ✅ | ✅ | ✅ |\n\nThe configuration system automatically detects the platform and selects appropriate paths for native messaging host manifests.\n\n资料来源：[app/native-server/src/scripts/browser-config.ts:1-100](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/browser-config.ts)\n\n## Installation Flow\n\n```mermaid\ngraph TD\n    A[\"Install mcp-chrome-bridge\"] --> B{\"pnpm config set enable-pre-post-scripts\"}\n    B -->|pnpm| C[\"Auto-register native host\"]\n    B -->|npm| C\n    C --> D[\"Load Chrome Extension\"]\n    D --> E[\"Click Extension Icon\"]\n    E --> F[\"Connect to Bridge\"]\n    F --> G[\"Get MCP Configuration\"]\n```\n\n### Prerequisites\n\n- Node.js >= 20.0.0\n- pnpm/npm\n- Chrome/Chromium browser\n\n### Registration Methods\n\n**Automatic (pnpm):**\n```bash\npnpm config set enable-pre-post-scripts true\npnpm install -g mcp-chrome-bridge\n```\n\n**Manual:**\n```bash\nnpm install -g mcp-chrome-bridge\nmcp-chrome-bridge register\n```\n\n资料来源：[README.md:60-100](https://github.com/hangwin/mcp-chrome/blob/main/README.md)\n\n## Future Roadmap\n\nThe project has planned several enhancements:\n\n| Feature | Status |\n|---------|--------|\n| Authentication | Planned |\n| Recording and Playback | Planned |\n| Workflow Automation | Planned |\n| Firefox Extension | Planned |\n\n## Project Structure\n\n```\nmcp-chrome/\n├── app/\n│   ├── chrome-extension/     # WXT-based Chrome extension\n│   │   ├── entrypoints/      # Extension entry points (background, sidepanel, etc.)\n│   │   ├── inject-scripts/   # Scripts injected into web pages\n│   │   └── utils/            # Utility modules\n│   └── native-server/        # Node.js MCP server\n│       └── src/\n│           ├── agent/        # AI agent integration\n│           └── scripts/      # Native messaging setup\n└── packages/\n    └── wasm-simd/           # WebAssembly SIMD math functions\n```\n\nThis structure enables clear separation between the browser extension (UI and web interaction), the native server (MCP protocol and AI integration), and shared packages (common utilities and optimized algorithms).\n\n---\n\n<a id='page-quickstart'></a>\n\n## Quick Start Guide\n\n### 相关页面\n\n相关主题：[Communication Protocols](#page-communication)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/hangwin/mcp-chrome/blob/main/README.md)\n- [app/chrome-extension/README.md](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/README.md)\n- [app/native-server/README.md](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/README.md)\n- [app/native-server/install.md](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/install.md)\n- [app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n- [app/chrome-extension/entrypoints/sidepanel/composables/useAgentThreads.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/sidepanel/composables/useAgentThreads.ts)\n</details>\n\n# Quick Start Guide\n\n## Overview\n\nThe **mcp-chrome** project provides a Model Context Protocol (MCP) server that enables AI assistants to control and interact with Chrome browser instances. This integration allows AI-powered automation of web browsing tasks through a comprehensive set of tools for navigation, interaction, content extraction, and network monitoring.\n\nThe project consists of two primary components:\n\n| Component | Location | Purpose |\n|-----------|----------|---------|\n| Chrome Extension | `app/chrome-extension/` | Handles browser-level operations via Chrome Extension APIs |\n| Native Server | `app/native-server/` | Bridges MCP clients (Claude Desktop, Cursor, etc.) with the extension |\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[MCP Client<br/>Claude Desktop / Cursor] -->|MCP Protocol| B[Native Server<br/>mcp-chrome-bridge]\n    B -->|Chrome Native Messaging| C[Chrome Extension<br/>Background Script]\n    C -->|Chrome APIs| D[Browser Tabs & Content]\n    E[Content Scripts] -->|Injection| D\n    C -->|scripting.executeScript| E\n```\n\n## Prerequisites\n\nBefore starting, ensure the following requirements are met:\n\n| Requirement | Version/Details |\n|-------------|-----------------|\n| Chrome/Chromium Browser | Version 88+ |\n| Node.js | v18+ |\n| npm | v8+ |\n| MCP Client | Claude Desktop, Cursor, or compatible |\n\n## Installation Steps\n\n### 1. Chrome Extension Installation\n\nThe Chrome extension must be loaded in developer mode:\n\n1. Open Chrome and navigate to `chrome://extensions/`\n2. Enable **Developer mode** (toggle in top-right corner)\n3. Click **Load unpacked**\n4. Select the `app/chrome-extension/` directory from the repository\n\n资料来源：[app/chrome-extension/README.md]()\n\nThe extension provides the following entry points:\n\n| Entry Point | File | Purpose |\n|-------------|------|---------|\n| Side Panel | `entrypoints/sidepanel/` | Main AI chat interface |\n| Popup | `entrypoints/popup/` | Quick access toolbar popup |\n| Options | `entrypoints/options/` | Extension settings |\n| Welcome | `entrypoints/welcome/` | Onboarding page |\n| Builder | `entrypoints/builder/` | Workflow editor |\n\n### 2. Native Server Setup\n\nThe native server acts as the bridge between MCP clients and the Chrome extension.\n\n#### Installation via npm\n\n```bash\nnpm install -g @mcp-chrome/native-server\n```\n\n#### Manual Installation\n\nFor manual installation, use the registry command:\n\n```bash\n# User-level installation (default)\nmcp-chrome-bridge register\n\n# System-level installation (requires admin)\nmcp-chrome-bridge register --system\n```\n\n资料来源：[app/native-server/install.md]()\n\n### 3. Registry Configuration\n\nOn **Windows**, the native messaging host must be registered in the Windows Registry:\n\n```\nHKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\com.mcp.chrome\n```\n\nOr for system-wide installation:\n\n```\nHKLM\\Software\\Google\\Chrome\\NativeMessagingHosts\\com.mcp.chrome\n```\n\n资料来源：[app/native-server/install.md]()\n\n## MCP Client Configuration\n\n### Claude Desktop\n\nAdd the following to your Claude Desktop configuration file:\n\n| OS | Config Location |\n|----|-----------------|\n| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |\n| Windows | `%APPDATA%\\Claude\\claude_desktop_config.json` |\n\n```json\n{\n  \"mcpServers\": {\n    \"chrome\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@mcp-chrome/native-server\"]\n    }\n  }\n}\n```\n\n资料来源：[app/native-server/README.md]()\n\n## Available MCP Tools\n\n### Browser Navigation (4 tools)\n\n| Tool | Description |\n|------|-------------|\n| `chrome_navigate` | Navigate to URL or perform search |\n| `chrome_go_back_or_forward` | Browser history navigation |\n| `chrome_reload` | Reload current page |\n| `chrome_control_viewport` | Zoom and scroll control |\n\n### Tab Management (6 tools)\n\n| Tool | Description |\n|------|-------------|\n| `chrome_new_tab` | Open new tab with optional URL |\n| `chrome_switch_tab` | Switch to specific tab |\n| `chrome_close_tabs` | Close tabs by URL pattern or tab IDs |\n| `chrome_get_tabs` | List all open tabs |\n| `chrome_duplicate_tab` | Duplicate current tab |\n\n资料来源：[README.md]()\n\n### Interaction (3 tools)\n\n| Tool | Parameters | Description |\n|------|------------|-------------|\n| `chrome_click_element` | `selector` (CSS) | Click elements using CSS selectors |\n| `chrome_fill_or_select` | `selector`, `value` | Fill forms and select options |\n| `chrome_keyboard` | `text`, `shortcut` | Simulate keyboard input |\n\n### Content Analysis (4 tools)\n\n| Tool | Description |\n|------|-------------|\n| `chrome_get_web_content` | Extract HTML/text content from pages |\n| `chrome_get_interactive_elements` | Find clickable elements |\n| `chrome_console` | Capture browser console output |\n| `search_tabs_content` | AI-powered semantic search across tabs |\n\n### Screenshot & Visual (1 tool)\n\n| Tool | Features |\n|------|----------|\n| `chrome_screenshot` | Element targeting, full-page capture, custom dimensions |\n\n### Network Monitoring (4 tools)\n\n| Tool | Description |\n|------|-------------|\n| `chrome_network_capture_start/stop` | webRequest API network capture |\n| `chrome_network_debugger_start/stop` | Debugger API with response bodies |\n| `chrome_network_request` | Send custom HTTP requests |\n\n### Data Management (5 tools)\n\n| Tool | Description |\n|------|-------------|\n| `chrome_history` | Search browser history with time filters |\n| `chrome_bookmark_search` | Find bookmarks by keywords |\n| `chrome_bookmark_add` | Add bookmarks with folder support |\n| `chrome_bookmark_delete` | Delete bookmarks |\n\n资料来源：[README.md]()\n\n## Content Script Injection\n\nThe extension uses content scripts for web page interaction. Scripts are injected via the Chrome scripting API:\n\n```typescript\nawait chrome.scripting.executeScript({\n  target: { tabId },\n  files: ['inject-scripts/web-fetcher-helper.js'],\n});\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts]()\n\nWeb-accessible resources are configured in `wxt.config.ts`:\n\n| Resource Path | Purpose |\n|---------------|---------|\n| `/models/*` | Local AI models |\n| `/workers/*` | Web workers |\n| `/inject-scripts/*` | Helper scripts for content scripts |\n\n```typescript\nweb_accessible_resources: [\n  {\n    resources: [\n      '/models/*',\n      '/workers/*',\n      '/inject-scripts/*',\n    ],\n    matches: ['<all_urls>'],\n  },\n]\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts]()\n\n## Security Configuration\n\nThe extension implements Content Security Policy (CSP) for production builds:\n\n```typescript\ncontent_security_policy: {\n  extension_pages:\n    \"script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:;\",\n}\n```\n\nNote: Security policies are disabled in development mode to allow Vite dev server resource loading.\n\n资料来源：[app/chrome-extension/wxt.config.ts]()\n\n## URL Exclusion Patterns\n\nThe content indexer automatically excludes internal browser URLs:\n\n```typescript\nconst excludePatterns = [\n  /^chrome:\\/\\//,\n  /^chrome-extension:\\/\\//,\n  /^edge:\\/\\//,\n  /^about:/,\n  /^moz-extension:\\/\\//,\n  /^file:\\/\\//,\n];\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts]()\n\n## Agent Thread Visualization\n\nThe sidepanel provides visual representation of agent activities:\n\n```typescript\n// Tool kinds tracked in useAgentThreads\nconst toolKinds = ['run', 'grep', 'edit', 'read', 'search'] as const;\n```\n\nEach tool execution is categorized and displayed with:\n\n| Property | Description |\n|----------|-------------|\n| `kind` | Tool category (edit, run, grep, etc.) |\n| `title` | File name or command |\n| `details` | Output content |\n| `severity` | Error, success, or info status |\n| `phase` | Execution phase (input, output, result) |\n\n资料来源：[app/chrome-extension/entrypoints/sidepanel/composables/useAgentThreads.ts]()\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue | Solution |\n|-------|----------|\n| Extension not responding | Reload the extension at `chrome://extensions/` |\n| Native messaging fails | Verify registry entries on Windows |\n| Permission denied | Check that extension has required permissions |\n| Tab access fails | Ensure tab ID is valid and accessible |\n\n资料来源：[app/native-server/install.md]()\n\n### Verbose Logging\n\nEnable verbose logging for debugging:\n\n```bash\nmcp-chrome-bridge --verbose\n```\n\n## Quick Usage Example\n\nOnce installed, you can interact with Chrome using natural language:\n\n```\nNavigate to github.com and search for mcp-chrome repositories\n```\n\nThis triggers the following workflow:\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant MCP\n    participant NativeServer\n    participant Extension\n    participant Chrome\n    \n    User->>MCP: \"Navigate to github.com...\"\n    MCP->>NativeServer: chrome_navigate\n    NativeServer->>Extension: chrome.tabs.update()\n    Extension->>Chrome: Navigate URL\n    Chrome-->>Extension: Page loaded\n    Extension-->>NativeServer: Success response\n    NativeServer-->>MCP: Result\n    MCP-->>User: Confirmation\n```\n\n## Next Steps\n\n- Explore the [Workflow Editor](builder) for advanced automation\n- Configure AI model settings in the [Options page](options)\n- Review [Content Analysis](content-analize) capabilities\n- Set up [Bookmark Management](#bookmarks) workflows\n\n---\n\n<a id='page-architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[System Architecture](#page-architecture), [Chrome Extension Structure](#page-extension-structure), [MCP Server Implementation](#page-mcp-server)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n- [app/chrome-extension/utils/content-indexer.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/common.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n- [app/native-server/src/scripts/browser-config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/browser-config.ts)\n- [app/native-server/src/scripts/utils.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n- [app/native-server/src/agent/session-service.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/session-service.ts)\n- [app/native-server/src/agent/engines/claude.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/engines/claude.ts)\n</details>\n\n# System Architecture\n\n## Overview\n\nmcp-chrome is a Model Context Protocol (MCP) server implementation that extends AI assistant capabilities to browser automation through a Chrome extension and native messaging host architecture. The system enables AI models to interact with web pages, control browser tabs, capture network traffic, and perform semantic search across browser content.\n\n## High-Level Architecture\n\nThe architecture consists of three primary layers:\n\n| Layer | Component | Responsibility |\n|-------|-----------|----------------|\n| Chrome Extension | Background Service Worker | Hosts MCP tools, manages tab state, handles browser API calls |\n| Native Server | Node.js Application | Manages browser configuration, handles native messaging, coordinates with AI engines |\n| AI Integration | Claude Engine / Codex Engine | Executes AI logic, processes tool requests, manages sessions |\n\n资料来源：[app/chrome-extension/wxt.config.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n## Extension Entrypoint Architecture\n\nThe Chrome extension uses multiple HTML entrypoints, each serving a specific purpose:\n\n```mermaid\ngraph TD\n    A[Chrome Extension] --> B[Background Service Worker]\n    A --> C[Popup]\n    A --> D[Side Panel]\n    A --> E[Options Page]\n    A --> F[Welcome Page]\n    A --> G[Builder]\n    A --> H[Offscreen Document]\n    \n    B --> I[MCP Tools]\n    B --> J[Tab Management]\n    B --> K[Content Indexer]\n    \n    C --> L[Quick Actions]\n    D --> M[Workflow Management]\n    E --> N[Userscripts Manager]\n```\n\n### Entrypoint Components\n\n| Entrypoint | File Path | Purpose |\n|------------|-----------|---------|\n| Background | `entrypoints/background/` | Service worker hosting all MCP tools |\n| Popup | `entrypoints/popup/` | Quick access to AI chat interface |\n| Side Panel | `entrypoints/sidepanel/` | Workflow management and agent threads |\n| Builder | `entrypoints/builder/` | Visual workflow editor |\n| Options | `entrypoints/options/` | Userscripts configuration |\n| Welcome | `entrypoints/welcome/` | Onboarding page |\n| Offscreen | `entrypoints/offscreen/` | Background document for long-running tasks |\n\n资料来源：[app/chrome-extension/entrypoints/popup/index.html:1-12](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/popup/index.html), [app/chrome-extension/entrypoints/sidepanel/index.html:1-12](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/sidepanel/index.html)\n\n## Native Messaging Architecture\n\n### Cross-Platform Manifest Configuration\n\nThe native server uses platform-specific manifest paths for Chrome Native Messaging, enabling secure communication between the native application and Chrome extension:\n\n```mermaid\ngraph TD\n    A[Native Server] --> B{Platform Detection}\n    B -->|win32| C[Windows Registry + JSON]\n    B -->|darwin| D[macOS plist]\n    B -->|linux| E[Linux JSON]\n    \n    C --> F[User Manifest]\n    C --> G[System Manifest]\n    D --> H[User Manifest]\n    D --> I[System Manifest]\n    E --> J[User Manifest]\n    E --> K[System Manifest]\n```\n\n**Manifest Path Locations by Platform:**\n\n| Platform | User-Level Path | System-Level Path |\n|----------|-----------------|-------------------|\n| Windows | `%APPDATA%\\Google\\Chrome\\NativeMessagingHosts\\` | `%ProgramFiles%\\Google\\Chrome\\NativeMessagingHosts\\` |\n| macOS | `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/` | `/Library/Google/Chrome/NativeMessagingHosts/` |\n| Linux | `~/.config/google-chrome/NativeMessagingHosts/` | `/etc/opt/chrome/native-messaging-hosts/` |\n\n资料来源：[app/native-server/src/scripts/browser-config.ts:1-100](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/browser-config.ts), [app/native-server/src/scripts/utils.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n\n### Browser Support Matrix\n\nThe native server supports multiple Chromium-based browsers:\n\n| Browser | Chrome | Chromium | Edge |\n|---------|--------|----------|------|\n| Windows Registry | `HKCU\\Software\\Google\\Chrome\\` | `HKCU\\Software\\Chromium\\` | Not configured |\n| System Registry | `HKLM\\Software\\Google\\Chrome\\` | `HKLM\\Software\\Chromium\\` | Not configured |\n\n## MCP Tool Architecture\n\n### Tool Categories\n\nThe extension exposes MCP tools organized into functional categories:\n\n```mermaid\ngraph LR\n    A[MCP Tools] --> B[Viewport & Navigation]\n    A --> C[Interaction]\n    A --> D[Data Management]\n    A --> E[Screenshots & Visual]\n    A --> F[Network Monitoring]\n    A --> G[Content Analysis]\n    \n    B --> B1[chrome_set_viewport]\n    B --> B2[chrome_switch_tab]\n    B --> B3[chrome_close_tabs]\n    B --> B4[chrome_go_back_or_forward]\n    \n    C --> C1[chrome_click_element]\n    C --> C2[chrome_fill_or_select]\n    C --> C3[chrome_keyboard]\n    \n    D --> D1[chrome_history]\n    D --> D2[chrome_bookmark_*]\n    \n    E --> E1[chrome_screenshot]\n    \n    F --> F1[chrome_network_*]\n    \n    G --> G1[search_tabs_content]\n    G --> G2[chrome_get_web_content]\n```\n\n### Tab Management Tools\n\nTabs can be queried and closed using URL pattern matching:\n\n```typescript\nconst tabs = await chrome.tabs.query({ url: urlPattern });\nawait chrome.tabs.remove(tabIdsToClose);\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/common.ts:1-80](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n\n### Dialog Handling\n\nThe extension can handle JavaScript dialogs using Chrome DevTools Protocol (CDP):\n\n```typescript\nawait cdpSessionManager.sendCommand(tabId, 'Page.handleJavaScriptDialog', {\n  accept: action === 'accept',\n  promptText: action === 'accept' ? promptText : undefined,\n});\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/dialog.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/dialog.ts)\n\n## Content Indexer System\n\nThe content indexer provides semantic search across open browser tabs:\n\n### Indexing Logic\n\n| Step | Action | Trigger |\n|------|--------|---------|\n| 1 | Detect tab update | `chrome.tabs.onUpdated` with `status === 'complete'` |\n| 2 | Check semantic engine readiness | 2-second delay to allow engine initialization |\n| 3 | Extract content | Execute `web-fetcher-helper.js` injection script |\n| 4 | Index content | Store in semantic engine for `search_tabs_content` |\n\n### URL Exclusion Patterns\n\nThe indexer automatically excludes internal Chrome URLs:\n\n```typescript\nconst excludePatterns = [\n  /^chrome:\\/\\//,\n  /^chrome-extension:\\/\\//,\n  /^edge:\\/\\//,\n  /^about:/,\n  /^moz-extension:\\/\\//,\n  /^file:\\/\\//,\n];\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:1-100](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n\n## Agent Session Management\n\n### Session Service Architecture\n\nThe native server manages AI agent sessions with structured metadata:\n\n```mermaid\ngraph TD\n    A[SessionService] --> B[ManagementInfo]\n    A --> C[AgentSessionPreviewMeta]\n    A --> D[Engine Configuration]\n    \n    B --> B1[models]\n    B --> B2[commands]\n    B --> B3[mcpServers]\n    B --> B4[plugins]\n    B --> B5[skills]\n    \n    D --> D1[ClaudeEngine]\n    D --> D2[CodexEngine]\n```\n\n### Session Interface\n\n```typescript\ninterface ManagementInfo {\n  models?: Array<{ value: string; displayName: string; description: string }>;\n  commands?: Array<{ name: string; description: string; argumentHint: string }>;\n  account?: { email?: string; organization?: string; subscriptionType?: string };\n  mcpServers?: Array<{ name: string; status: string }>;\n  tools?: string[];\n  agents?: string[];\n  plugins?: Array<{ name: string; path?: string }>;\n  skills?: string[];\n  model?: string;\n  permissionMode?: string;\n  cwd?: string;\n}\n```\n\n资料来源：[app/native-server/src/agent/session-service.ts:1-60](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/session-service.ts)\n\n## Claude Engine Integration\n\n### Tool Message Processing\n\nThe Claude engine handles streaming tool execution results:\n\n```mermaid\nsequenceDiagram\n    participant AI as Claude API\n    participant Engine as ClaudeEngine\n    participant Dispatch as Tool Dispatch\n    \n    AI->>Engine: content_block_start (tool_use)\n    Engine->>Dispatch: Register pending tool\n    AI->>Engine: content_block_delta (input_json_delta)\n    Engine->>Engine: Accumulate JSON parts\n    AI->>Engine: content_block_stop\n    Engine->>Engine: Parse accumulated JSON\n    Engine->>Dispatch: Execute tool with full input\n    Dispatch->>Engine: Result content\n    Engine->>AI: tool_result\n```\n\n### Tool Result Processing\n\n```typescript\nif (contentBlock.type === 'tool_result') {\n  const metadata = this.buildToolResultMetadata(contentBlock);\n  const content = this.extractToolResultContent(contentBlock);\n  const isError = contentBlock.is_error === true;\n  \n  dispatchToolMessage(\n    isError ? `Error: ${content || 'Tool execution failed'}` : content || 'Tool completed',\n    metadata,\n    'tool_result',\n    false\n  );\n}\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:1-100](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/engines/claude.ts)\n\n## Security Architecture\n\n### Content Security Policy\n\nThe extension implements strict CSP in production:\n\n| Policy | Value | Purpose |\n|--------|-------|---------|\n| script-src | `'self' 'wasm-unsafe-eval'` | Restrict script execution |\n| object-src | `'self'` | Limit object embedding |\n| style-src | `'self' 'unsafe-inline'` | Allow Vite-compiled styles |\n| img-src | `'self' data: blob:` | Permit data URIs for thumbnails |\n\n### Cross-Origin Policies\n\n| Policy | Value | Development | Production |\n|--------|-------|-------------|------------|\n| COOP | `same-origin` | Disabled | Enabled |\n| COEP | `require-corp` | Disabled | Enabled |\n\n资料来源：[app/chrome-extension/wxt.config.ts:20-35](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n### Web Accessible Resources\n\nThe extension exposes specific directories to content scripts:\n\n| Directory | Purpose |\n|-----------|---------|\n| `/models/*` | AI model files |\n| `/workers/*` | Web Worker scripts |\n| `/inject-scripts/*` | Content script helpers |\n\n## Record-Replay System\n\nThe background service includes a record-replay engine for browser automation testing:\n\n### Wait Policy\n\nThe `waitForNetworkIdle` function monitors browser events:\n\n| Event Type | Listener | Purpose |\n|------------|----------|---------|\n| `onCommitted` | webNavigation | Detect navigation commits |\n| `onCompleted` | webNavigation | Detect page load completion |\n| `onHistoryStateUpdated` | webNavigation (optional) | Detect SPA route changes |\n| `onUpdated` | tabs | Detect tab status changes |\n\n```typescript\nconst onUpdated = (updatedId: number, change: chrome.tabs.TabChangeInfo) => {\n  if (updatedId !== tabId) return;\n  if (change.status === 'loading') mark();\n  if (typeof change.url === 'string' && (!prevUrl || change.url !== prevUrl)) mark();\n};\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts:1-60](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts)\n\n## Data Flow Diagram\n\n```mermaid\ngraph LR\n    A[User] -->|Command| B[AI Assistant]\n    B -->|MCP Request| C[Native Server]\n    C -->|Native Messaging| D[Chrome Extension]\n    D -->|Chrome APIs| E[Browser]\n    E -->|Response| D\n    D -->|Tool Result| C\n    C -->|Stream| B\n    B -->|Response| A\n```\n\n## Extension Development Configuration\n\n### Keyboard Shortcuts\n\n| Shortcut | Windows/Linux | macOS | Action |\n|----------|---------------|-------|--------|\n| Quick Panel | `Alt+Shift+U` | `Cmd+Shift+U` | Toggle AI Chat |\n\n### Vite Plugin Stack\n\n| Plugin | Purpose |\n|--------|---------|\n| TailwindCSS v4 | Styling without PostCSS |\n| `@vitejs/plugin-vue` | Vue component auto-registration |\n| WXT | Extension framework |\n\n资料来源：[app/chrome-extension/wxt.config.ts:40-50](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n---\n\n<a id='page-communication'></a>\n\n## Communication Protocols\n\n### 相关页面\n\n相关主题：[System Architecture](#page-architecture), [MCP Server Implementation](#page-mcp-server)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/chrome-extension/entrypoints/background/native-host.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/native-host.ts)\n- [app/native-server/src/scripts/utils.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n- [app/native-server/src/scripts/browser-config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/browser-config.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/common.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n- [app/native-server/README.md](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/README.md)\n</details>\n\n# Communication Protocols\n\n## Overview\n\nThe mcp-chrome project implements a sophisticated communication architecture that bridges Chrome browser extensions with a native Node.js server. This architecture relies on multiple communication protocols working in concert to enable AI-powered browser automation through the Model Context Protocol (MCP).\n\nThe system employs two primary communication mechanisms:\n\n1. **Native Messaging Protocol** - Chrome extension to native host communication using Chrome's `runtime.connectNative` API\n2. **Internal Message Routing** - Communication between background scripts and tool handlers within the extension\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[Chrome Extension UI/Popup] -->|chrome.runtime.sendMessage| B[Background Script]\n    B -->|call_tool messages| C[Tool Handlers]\n    C -->|CDP Commands| D[Chrome DevTools Protocol]\n    B -->|connectNative| E[Native Host]\n    E -->|stdio| F[Node.js MCP Server]\n    F -->|WebSocket/CDP| G[Browser Instance]\n    \n    H[Content Scripts] -->|injected scripts| G\n    \n    I[Offscreen Document] -->|file operations| E\n```\n\n## Native Messaging Protocol\n\n### Purpose and Scope\n\nThe Native Messaging Protocol enables secure communication between the Chrome extension and a standalone native application. This is essential for operations that require direct system access, such as file system operations, native module execution, and port management for the MCP server.\n\n资料来源：[app/native-server/README.md](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/README.md)\n\n### Connection Establishment\n\nThe extension initiates native connections using Chrome's `runtime.connectNative` API with a predefined application ID:\n\n```typescript\nnativePort = chrome.runtime.connectNative('com.yourcompany.fastify_native_host');\n```\n\n资料来源：[app/native-server/README.md:40](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/README.md)\n\n### Auto-Connect Behavior\n\nThe system implements intelligent auto-connect functionality that activates on browser startup and extension installation:\n\n```typescript\n// Auto-connect on Chrome browser startup\nchrome.runtime.onStartup.addListener(() => {\n  void ensureNativeConnected('onStartup').catch(() => {});\n});\n\n// Auto-connect on extension install/update\nchrome.runtime.onInstalled.addListener(() => {\n  void ensureNativeConnected('onInstalled').catch(() => {});\n});\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/native-host.ts:1-20](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/native-host.ts)\n\n### Message Types\n\n| Message Type | Direction | Purpose |\n|--------------|-----------|---------|\n| `call_tool` | Extension → Native | Request tool execution |\n| `ENSURE_NATIVE` | UI → Background | Trigger connection check |\n| `CONNECT_NATIVE` | UI → Background | User-initiated connection |\n| `forward_to_native` | Background → Native | Route messages to native host |\n| `file_operation` | Extension → Native | File preparation for uploads |\n| `started` | Native → Extension | Server startup confirmation |\n| `stopped` | Native → Extension | Server shutdown notification |\n| `error` | Native → Extension | Error reporting |\n\n### Message Format\n\nMessages follow a structured format with `type` and `payload` fields:\n\n```typescript\nchrome.runtime.sendMessage({\n  type: 'forward_to_native',\n  message: {\n    type: 'file_operation',\n    requestId: requestId,\n    payload: {\n      action: 'prepareFile',\n      fileUrl,\n      base64Data,\n      fileName,\n    },\n  },\n});\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts:58-75](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts)\n\n## Internal Message Routing\n\n### Tool Call Routing\n\nThe background script routes tool calls from various sources (UI, content scripts) to appropriate handlers:\n\n```typescript\nchrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {\n  // Allow UI to call tools directly\n  if (message && message.type === 'call_tool' && message.name) {\n    handleCallTool({ name: message.name, args: message.args })\n      .then((res) => sendResponse({ success: true, result: res }))\n      .catch((err) =>\n        sendResponse({ success: false, error: err instanceof Error ? err.message : String(err) }),\n      );\n    return true;\n  }\n  // ... additional routing logic\n});\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/native-host.ts:28-45](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/native-host.ts)\n\n### Connection Management States\n\n```mermaid\nstateDiagram-v2\n    [*] --> Disconnected\n    Disconnected --> Connecting: ensureNativeConnected()\n    Connecting --> Connected: Port established\n    Connecting --> Disconnected: Connection failed\n    Connected --> Disconnected: Port disconnect\n    Connected --> AutoConnectDisabled: User explicit disconnect\n    AutoConnectDisabled --> Connecting: CONNECT_NATIVE message\n    AutoConnectDisabled --> Connecting: ensureNativeConnected()\n```\n\n## File Operation Protocol\n\n### File Upload Flow\n\nThe file upload mechanism uses a request-response pattern with unique request IDs:\n\n```typescript\nconst requestId = `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n\nconst handleMessage = (message: any) => {\n  if (\n    message.type === 'file_operation_response' &&\n    message.responseToRequestId === requestId\n  ) {\n    clearTimeout(timeout);\n    chrome.runtime.onMessage.removeListener(handleMessage);\n    \n    if (message.payload?.success && message.payload?.filePath) {\n      resolve(message.payload.filePath);\n    } else {\n      resolve(null);\n    }\n  }\n};\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts:25-48](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts)\n\n### Timeout Handling\n\nFile operations implement a 30-second timeout to prevent hanging connections:\n\n```typescript\nconst timeout = setTimeout(() => {\n  console.error('File preparation request timed out');\n  resolve(null);\n}, 30000); // 30 second timeout\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts:14-18](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts)\n\n## Native Host Manifest Configuration\n\n### Platform-Specific Paths\n\nThe native messaging host manifest location varies by operating system:\n\n| Platform | User-Level Path |\n|----------|-----------------|\n| Windows | `%APPDATA%\\Google\\Chrome\\NativeMessagingHosts\\` |\n| macOS | `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/` |\n| Linux | `~/.config/google-chrome/NativeMessagingHosts/` |\n\n| Platform | System-Level Path |\n|----------|-------------------|\n| Windows | `%ProgramFiles%\\Google\\Chrome\\NativeMessagingHosts\\` |\n| macOS | `/Library/Google/Chrome/NativeMessagingHosts/` |\n| Linux | `/etc/opt/chrome/native-messaging-hosts/` |\n\n资料来源：[app/native-server/src/scripts/utils.ts:1-35](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n\n### Browser-Specific Configuration\n\nDifferent Chromium-based browsers have distinct manifest locations:\n\n```typescript\nswitch (browser) {\n  case BrowserType.CHROME:\n    return path.join(home, 'Library', 'Application Support', 'Google', 'Chrome', 'NativeMessagingHosts', `${HOST_NAME}.json`);\n  case BrowserType.CHROMIUM:\n    return path.join(home, 'Library', 'Application Support', 'Chromium', 'NativeMessagingHosts', `${HOST_NAME}.json`);\n}\n```\n\n资料来源：[app/native-server/src/scripts/browser-config.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/browser-config.ts)\n\n### Manifest Validation\n\nThe doctor command validates manifest files for correctness:\n\n| Validation Check | Error Message |\n|------------------|---------------|\n| File existence | Manifest not found |\n| JSON parsing | Failed to parse manifest |\n| Name field | name != HOST_NAME |\n| Type field | type != stdio |\n| Path field | path is missing |\n| Path existence | path target does not exist |\n\n资料来源：[app/native-server/src/scripts/doctor.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/doctor.ts)\n\n## Tab Operation Protocol\n\n### URL Pattern Matching\n\nThe close tabs functionality supports glob-style URL pattern matching:\n\n```typescript\nlet urlPattern = url;\nif (!urlPattern.includes('*')) {\n  try {\n    new URL(urlPattern);\n    urlPattern = urlPattern.endsWith('/') ? `${urlPattern}*` : `${urlPattern}/*`;\n  } catch {\n    urlPattern = urlPattern.endsWith('*')\n      ? urlPattern\n      : urlPattern.endsWith('/')\n        ? `${urlPattern}*`\n        : `${urlPattern}/*`;\n  }\n}\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/common.ts:1-30](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n\n### Tab Query and Response Format\n\n```typescript\nconst tabs = await chrome.tabs.query({ url: urlPattern });\nawait chrome.tabs.remove(tabIdsToClose);\n\nreturn {\n  content: [{\n    type: 'text',\n    text: JSON.stringify({\n      success: true,\n      message: `Closed ${tabIdsToClose.length} tabs with URL: ${url}`,\n      closedCount: tabIdsToClose.length,\n      closedTabIds: tabIdsToClose,\n    }),\n  }],\n  isError: false,\n};\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/common.ts:60-80](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n\n## Port Configuration Protocol\n\n### Stdio Configuration\n\nThe native server communicates over a configured port for MCP operations:\n\n```typescript\nconst url = new URL(configValue.url as string);\nconst port = Number(url.port);\nconst portOk = port === EXPECTED_PORT;\n\nchecks.push({\n  id: 'port.config',\n  title: 'Port config',\n  status: portOk ? 'ok' : 'error',\n  message: configValue.url as string,\n  details: {\n    expectedPort: EXPECTED_PORT,\n    actualPort: port,\n    fix: portOk ? undefined : [`${COMMAND_NAME} update-port ${EXPECTED_PORT}`],\n  },\n});\n```\n\n资料来源：[app/native-server/src/scripts/doctor.ts:80-100](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/doctor.ts)\n\n## Node.js Path Management\n\n### Version Consistency\n\nThe system ensures consistent Node.js versions between installation and runtime to avoid native module version mismatches:\n\n```typescript\nexport function writeNodePathFile(distDir: string, nodeExecPath = process.execPath): void {\n  try {\n    const nodePathFile = path.join(distDir, 'node_path.txt');\n    fs.mkdirSync(distDir, { recursive: true });\n    // Write Node.js executable path for runtime consistency\n  } catch (error) {\n    // Error handling\n  }\n}\n```\n\n资料来源：[app/native-server/src/scripts/utils.ts:80-100](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n\n## Security Considerations\n\n### Cross-Origin Policies\n\nProduction builds implement strict COEP and COOP headers:\n\n```typescript\ncross_origin_embedder_policy: { value: 'require-corp' as const },\ncross_origin_opener_policy: { value: 'same-origin' as const },\ncontent_security_policy: {\n  extension_pages: \"script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:;\",\n}\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:1-30](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n### Web Accessible Resources\n\nOnly specific resource paths are accessible to web pages:\n\n```typescript\nweb_accessible_resources: [\n  {\n    resources: [\n      '/models/*',\n      '/workers/*',\n      '/inject-scripts/*',\n    ],\n    matches: ['<all_urls>'],\n  },\n],\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:20-30](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n## Summary\n\nThe mcp-chrome communication architecture consists of multiple protocol layers:\n\n1. **Native Messaging Layer** - Chrome-to-native bridge using Chrome's native messaging API\n2. **Internal Message Routing** - Efficient routing of tool calls within the extension\n3. **File Operation Protocol** - Request-response pattern with timeout handling\n4. **Tab Management Protocol** - URL pattern-based tab operations\n5. **Port Configuration Protocol** - Stdio-based MCP server communication\n\nAll protocols emphasize reliability through timeout handling, error reporting, and connection state management.\n\n---\n\n<a id='page-extension-structure'></a>\n\n## Chrome Extension Structure\n\n### 相关页面\n\n相关主题：[Browser Tools and APIs](#page-browser-tools), [Storage and Data Management](#page-storage)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n- [app/chrome-extension/entrypoints/background/index.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/index.ts)\n- [app/chrome-extension/entrypoints/content.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/content.ts)\n- [app/chrome-extension/entrypoints/background/native-host.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/native-host.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/common.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n- [app/chrome-extension/entrypoints/background/record-replay/index.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/index.ts)\n- [app/chrome-extension/utils/content-indexer.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n</details>\n\n# Chrome Extension Structure\n\n## Overview\n\nThe mcp-chrome project implements a Chrome Extension that serves as a bridge between a Chrome browser instance and an AI-powered automation system. The extension enables Large Language Models (LLMs) to control browser behavior, capture web content, manage tabs, inject scripts, and automate user interactions through the Model Context Protocol (MCP).\n\nThe extension is built using **WXT**, a modern framework for Chrome extension development, which handles manifest generation, build configuration, and hot module replacement. The architecture follows a multi-process model with background service workers, content scripts, and UI entrypoints communicating through Chrome's message passing APIs and native messaging.\n\n资料来源：[app/chrome-extension/wxt.config.ts:1-100]()\n\n---\n\n## Architecture Overview\n\nThe Chrome extension consists of several interconnected layers:\n\n```mermaid\ngraph TD\n    subgraph \"UI Layer\"\n        POPUP[Popup UI]\n        SIDEPANEL[Side Panel]\n        WELCOME[Welcome Page]\n        OPTIONS[Options Page]\n    end\n    \n    subgraph \"Background Layer\"\n        BG[Background Service Worker]\n        NATIVE[Native Host Bridge]\n        RECORDREPLAY[Record/Replay Engine]\n    end\n    \n    subgraph \"Content Layer\"\n        CONTENT[Content Scripts]\n        INJECT[inject-scripts]\n    end\n    \n    subgraph \"Native Layer\"\n        NATIVE_SERVER[mcp-chrome-bridge]\n    end\n    \n    POPUP <-->|chrome.runtime| BG\n    SIDEPANEL <-->|chrome.runtime| BG\n    OPTIONS <-->|chrome.runtime| BG\n    \n    BG <-->|nativeMessaging| NATIVE\n    BG <-->|chrome.tabs.sendMessage| CONTENT\n    CONTENT <-->|window messages| INJECT\n    \n    NATIVE <-->|stdin/stdout| NATIVE_SERVER\n    \n    RECORDREPLAY <-->|chrome.scripting| CONTENT\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:20-60]()\n\n---\n\n## Entry Points\n\nThe extension defines multiple entry points through WXT's manifest configuration. Each entry point represents a distinct execution context within Chrome.\n\n### Entry Point Configuration\n\n| Entry Point | File Path | Purpose | Permissions |\n|-------------|-----------|---------|-------------|\n| `action` (Popup) | `popup.html` | Quick access UI with MCP configuration | Standard |\n| `side_panel` | `sidepanel.html` | Workflow management interface | `sidePanel` |\n| `options_ui` | `options.html` | Extension settings | Storage |\n| `welcome` | `welcome/index.html` | Onboarding page | None |\n| Background | `background/index.ts` | Service worker | All browser APIs |\n\n资料来源：[app/chrome-extension/wxt.config.ts:20-55]()\n\n### Manifest Permissions\n\nThe extension declares extensive permissions to support its automation capabilities:\n\n```typescript\npermissions: [\n  'nativeMessaging',  // Native host communication\n  'tabs',             // Tab management\n  'activeTab',        // Active tab access\n  'scripting',        // Script injection\n  'contextMenus',     // Context menu creation\n  'downloads',        // Download management\n  'webRequest',       // Network monitoring\n  'webNavigation',    // Navigation events\n  'debugger',         // Debugging capabilities\n  'history',          // Browser history\n  'bookmarks',        // Bookmark management\n  'offscreen',        // Offscreen documents\n  'storage',          // Local storage\n  'declarativeNetRequest', // Ad blocking\n  'alarms',           // Scheduled tasks\n  'sidePanel',        // Side panel access\n],\nhost_permissions: ['<all_urls>'],\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:20-40]()\n\n---\n\n## Background Service Worker\n\nThe background service worker (`entrypoints/background/index.ts`) serves as the central coordinator for all extension functionality.\n\n### Core Responsibilities\n\n```mermaid\ngraph LR\n    A[Incoming Messages] --> B[Type Router]\n    B --> C{Message Type}\n    C -->|tool_call| D[Tool Executor]\n    C -->|native| E[Native Host]\n    C -->|rr_trigger| F[Record/Replay]\n    D --> G[chrome.* APIs]\n    E --> H[Native Bridge]\n    F --> I[Content Scripts]\n```\n\n### Native Host Communication\n\nThe background script maintains a persistent connection to the native `mcp-chrome-bridge` server through Chrome's native messaging API:\n\n```typescript\n// Connection lifecycle management\nchrome.runtime.onStartup.addListener(() => {\n  void ensureNativeConnected('onStartup').catch(() => {});\n});\n\nchrome.runtime.onInstalled.addListener(() => {\n  void ensureNativeConnected('onInstalled').catch(() => {});\n});\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/native-host.ts:1-20]()\n\nThe native messaging follows a request-response pattern with auto-reconnect capabilities:\n\n| Message Type | Direction | Purpose |\n|--------------|-----------|---------|\n| `ENSURE_NATIVE` | UI → Background | Trigger connection without changing autoConnect state |\n| `CONNECT_NATIVE` | UI → Background | Explicit user-initiated connection, re-enables auto-connect |\n| `call_tool` | UI → Background | Direct tool execution via message |\n\n资料来源：[app/chrome-extension/entrypoints/background/native-host.ts:25-45]()\n\n### Tool Execution System\n\nTools are executed through the `handleCallTool` function, which routes requests to appropriate handlers:\n\n```typescript\nchrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {\n  if (message && message.type === 'call_tool' && message.name) {\n    handleCallTool({ name: message.name, args: message.args })\n      .then((res) => sendResponse({ success: true, result: res }))\n      .catch((err) => sendResponse({ success: false, error: err.message }));\n    return true;\n  }\n});\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/native-host.ts:30-38]()\n\n---\n\n## Content Scripts Architecture\n\nContent scripts (`entrypoints/content.ts`) run in the context of web pages and provide the bridge between the background service worker and page-level JavaScript.\n\n### Injection Strategy\n\nThe extension uses a multi-file injection approach:\n\n```typescript\n// Files injected into all frames\nfiles: ['inject-scripts/inject-bridge.js', 'inject-scripts/accessibility-tree-helper.js']\n```\n\n| Script | Purpose |\n|--------|---------|\n| `inject-bridge.js` | Message communication bridge |\n| `accessibility-tree-helper.js` | DOM accessibility tree generation |\n| `dom-observer.js` | DOM change monitoring for triggers |\n| `web-fetcher-helper.js` | Content extraction utilities |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/index.ts:15-25]()\n\n### Script Injection Modes\n\nContent scripts can be injected with different world contexts:\n\n| World | Isolation | Use Case |\n|-------|-----------|----------|\n| `ISOLATED` | Full isolation | Script injection via `chrome.scripting.executeScript` |\n| `MAIN` | Shared with page | User scripts requiring DOM access |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/index.ts:20-25]()\n\n---\n\n## Web-Accessible Resources\n\nThe extension exposes certain resources to web pages for content script functionality:\n\n```typescript\nweb_accessible_resources: [\n  {\n    resources: [\n      '/models/*',           // ML models for content analysis\n      '/workers/*',          // Web Workers\n      '/inject-scripts/*',   // Helper scripts\n    ],\n    matches: ['<all_urls>'],\n  },\n]\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:55-65]()\n\n---\n\n## Content Indexing System\n\nThe `ContentIndexer` class manages automatic content indexing for semantic search capabilities.\n\n### Indexing Flow\n\n```mermaid\ngraph TD\n    A[Tab Load Complete] --> B{URL Valid?}\n    B -->|No| C[Skip]\n    B -->|Yes| D{Semantic Engine Ready?}\n    D -->|No| E[Wait + Retry]\n    D -->|Yes| F[Extract Content]\n    F --> G[Update Index]\n    \n    H[Tab Closed] --> I[Remove Index]\n    J[Navigation Committed] --> K[Remove Index]\n```\n\n### URL Filtering\n\nThe indexer excludes internal Chrome pages:\n\n```typescript\nprivate shouldIndexUrl(url: string): boolean {\n  const excludePatterns = [\n    /^chrome:\\/\\//,\n    /^chrome-extension:\\/\\//,\n    /^edge:\\/\\//,\n    /^about:/,\n    /^moz-extension:\\/\\//,\n    /^file:\\/\\//,\n  ];\n  return !excludePatterns.some((pattern) => pattern.test(url));\n}\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:30-50]()\n\nAuto-indexing is triggered with a 2-second delay after page load:\n\n```typescript\nsetTimeout(() => {\n  if (!this.isSemanticEngineReady() && !this.isSemanticEngineInitializing()) {\n    console.log('ContentIndexer: Skipping auto-index - semantic engine not ready');\n    return;\n  }\n  this.indexTabContent(tabId).catch((error) => {\n    console.error('ContentIndexer: Auto-indexing failed:', error);\n  });\n}, 2000);\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:10-20]()\n\n---\n\n## Record/Replay Engine\n\nThe record/replay system enables automation workflow recording and playback.\n\n### Trigger Types\n\n| Type | Description | Configuration |\n|------|-------------|---------------|\n| `dom` | DOM element triggers | selector, appear, once, debounceMs |\n| `network` | Network request patterns | request/response matching |\n| `navigation` | Page navigation events | URL patterns |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/index.ts:5-15]()\n\n### Trigger Initialization\n\n```typescript\nconst domTriggers = triggers\n  .filter((x) => x.type === 'dom' && x.enabled !== false)\n  .map((x: any) => ({\n    id: x.id,\n    selector: x.selector,\n    appear: x.appear !== false,\n    once: x.once !== false,\n    debounceMs: x.debounceMs ?? 800,\n  }));\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/index.ts:10-20]()\n\n### Node Runtimes\n\nThe engine executes steps through node runtimes:\n\n| Node Type | File | Capabilities |\n|-----------|------|--------------|\n| `scroll` | `nodes/scroll.ts` | Page/container scrolling with offset or element targeting |\n| `tabs` | `nodes/tabs.ts` | Tab creation, switching, closing |\n| `wait` | `engine/policies/wait.ts` | Network idle and DOM state waiting |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/nodes/scroll.ts:1-20]()\n\n### Navigation State Tracking\n\n```typescript\nconst onCommitted = (d: any) => {\n  if (d.tabId === tabId && d.frameId === 0 && d.timeStamp >= startedAt) mark();\n};\nconst onHistoryStateUpdated = (d: any) => {\n  if (d.tabId === tabId && d.frameId === 0 && d.timeStamp >= startedAt) mark();\n};\nconst onUpdated = (updatedId: number, change: chrome.tabs.TabChangeInfo) => {\n  if (updatedId !== tabId) return;\n  if (change.status === 'loading') mark();\n  if (typeof change.url === 'string' && (!prevUrl || change.url !== prevUrl)) mark();\n};\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts:15-25]()\n\n---\n\n## Tool System Architecture\n\n### Browser Tool Categories\n\n| Category | Tools |\n|----------|-------|\n| Navigation | go_back_or_forward, switch_tab, close_tabs |\n| Interaction | click_element, fill_or_select, keyboard |\n| Data | history, bookmark_search, bookmark_add, bookmark_delete |\n| Screenshot | screenshot (with element targeting, full-page support) |\n| Network | network_capture_start/stop, network_debugger_start/stop, network_request |\n| Content | get_web_content, get_interactive_elements, console, search_tabs_content |\n\n资料来源：[README.md]()\n\n### Tool Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant UI\n    participant BG as Background Worker\n    participant NATIVE as Native Bridge\n    participant CHROME as Chrome APIs\n    \n    UI->>BG: call_tool { name, args }\n    BG->>BG: Route to Handler\n    alt Native Tool\n        BG->>NATIVE: nativeMessage\n        NATIVE->>CHROME: Browser API\n        CHROME-->>NATIVE: Response\n        NATIVE-->>BG: { success, result }\n    else Browser Tool\n        BG->>CHROME: chrome.* API\n        CHROME-->>BG: Result\n    end\n    BG-->>UI: { success, result }\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/common.ts:1-50]()\n\n---\n\n## Security Configuration\n\nThe extension implements security policies for production builds:\n\n```typescript\n...(IS_DEV\n  ? {}\n  : {\n      cross_origin_embedder_policy: { value: 'require-corp' as const },\n      cross_origin_opener_policy: { value: 'same-origin' as const },\n      content_security_policy: {\n        extension_pages:\n          \"script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:;\",\n      },\n    }),\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:65-80]()\n\n| Policy | Development | Production |\n|--------|-------------|------------|\n| COEP | Disabled | `require-corp` |\n| COOP | Disabled | `same-origin` |\n| CSP | WXT Default | Restricted to self + wasm |\n\n---\n\n## Keyboard Shortcuts\n\nThe extension defines keyboard commands:\n\n```typescript\ncommands: {\n  toggle_quick_panel: {\n    suggested_key: { default: 'Ctrl+Shift+Space', mac: 'Command+Shift+Space' },\n    description: 'Toggle Quick Panel AI Chat',\n  },\n}\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:45-55]()\n\n---\n\n## Side Panel Interface\n\nThe side panel (`sidepanel.html`) provides a workflow management interface with agent thread tracking:\n\n```typescript\n// Message parsing rules\nif (\n  normalize(toolName) === 'bash' ||\n  normalize(toolName).includes('shell') ||\n  typeof command === 'string'\n) {\n  return { kind: 'run', title: commandDescription || extractedCommand };\n}\n\nif (normalize(toolName) === 'grep' || normalize(toolName).includes('search')) {\n  return { kind: 'grep', title: displayPattern };\n}\n```\n\n资料来源：[app/chrome-extension/entrypoints/sidepanel/composables/useAgentThreads.ts:1-30]()\n\n---\n\n## Native Messaging Bridge\n\nThe native messaging layer communicates with `mcp-chrome-bridge` installed on the host system.\n\n### Communication Flow\n\n```mermaid\ngraph LR\n    subgraph \"Chrome Extension\"\n        BG[Background]\n        PORT[Native Port]\n    end\n    \n    subgraph \"Host System\"\n        BRIDGE[mcp-chrome-bridge]\n        NATIVE_HOST[Native Host JSON]\n    end\n    \n    BG <-->|Native Messaging| PORT\n    PORT <-->|stdin/stdout| BRIDGE\n    BRIDGE <-->|Browser APIs| CHROME[(Chrome)]\n    \n    NATIVE_HOST -.->|Manifest Path| BRIDGE\n```\n\n### Manifest Configuration\n\nNative messaging manifests are installed at platform-specific paths:\n\n| Platform | User-Level Path |\n|----------|-----------------|\n| Windows | `%APPDATA%\\Google\\Chrome\\NativeMessagingHosts\\` |\n| macOS | `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/` |\n| Linux | `~/.config/google-chrome/NativeMessagingHosts/` |\n\n| Platform | System-Level Path |\n|----------|-------------------|\n| Windows | `%ProgramFiles%\\Google\\Chrome\\NativeMessagingHosts\\` |\n| macOS | `/Library/Google/Chrome/NativeMessagingHosts/` |\n| Linux | `/etc/opt/chrome/native-messaging-hosts/` |\n\n资料来源：[app/native-server/src/scripts/browser-config.ts:1-80]()\n\n---\n\n## State Management\n\nThe extension uses Chrome's storage API for state persistence:\n\n| Key | Type | Purpose |\n|-----|------|---------|\n| `RR_TRIGGERS` | Array | Record/replay trigger configurations |\n| `USERSCRIPTS_DISABLED` | Boolean | Userscript execution toggle |\n| `autoConnectEnabled` | Boolean | Native connection auto-connect state |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/index.ts:5-10]()\n\n---\n\n## Build Configuration\n\nThe extension uses Vite with TailwindCSS v4:\n\n```typescript\nvite: (env) => ({\n  plugins: [\n    tailwindcss(),\n    Components({\n      dts: true,\n    }),\n  ],\n}),\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:80-90]()\n\n### Build Requirements\n\n| Dependency | Version | Purpose |\n|------------|---------|---------|\n| Node.js | >= 20.0.0 | Runtime |\n| pnpm/npm | Latest | Package manager |\n| WXT | Latest | Build framework |\n| TailwindCSS v4 | Latest | Styling |\n\n---\n\n## Summary\n\nThe Chrome Extension architecture of mcp-chrome follows a layered design:\n\n1. **UI Layer**: Popup, side panel, welcome page, and options provide user-facing interfaces\n2. **Background Layer**: Service worker coordinates native messaging, tool execution, and automation\n3. **Content Layer**: Injected scripts enable page-level interaction and accessibility tree generation\n4. **Native Layer**: External `mcp-chrome-bridge` process handles OS-level browser automation\n\nThe extension leverages Chrome's extensive APIs for tab management, network monitoring, script injection, and state persistence while maintaining security through manifest-defined permissions and CSP policies.\n\n---\n\n<a id='page-browser-tools'></a>\n\n## Browser Tools and APIs\n\n### 相关页面\n\n相关主题：[Chrome Extension Structure](#page-extension-structure), [Record and Replay Engine](#page-record-replay)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [docs/TOOLS.md](https://github.com/hangwin/mcp-chrome/blob/main/docs/TOOLS.md)\n- [app/chrome-extension/entrypoints/background/tools/browser/index.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/index.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/computer.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/computer.ts)\n- [app/chrome-extension/shared/tools.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/shared/tools.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/common.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n- [app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n</details>\n\n# Browser Tools and APIs\n\n## Overview\n\nThe Browser Tools and APIs module is a core component of the mcp-chrome extension that provides AI agents with programmatic control over browser functionality. This module bridges the gap between AI decision-making and browser operations, enabling automated web navigation, content extraction, tab management, and user interaction simulation.\n\nThe system operates as a collection of Chrome extension background script tools that expose browser capabilities through a structured MCP (Model Context Protocol) interface, allowing LLM-powered agents to interact with the browser as if performing actions themselves.\n\n资料来源：[docs/TOOLS.md](https://github.com/hangwin/mcp-chrome/blob/main/docs/TOOLS.md)\n\n## Architecture\n\n### High-Level Architecture\n\n```mermaid\ngraph TD\n    A[MCP Client / AI Agent] -->|MCP Protocol| B[Native Server]\n    B -->|Native Messaging| C[Chrome Extension Background]\n    C -->|Chrome APIs| D[Browser Environment]\n    \n    E[Content Scripts] -->|Injection| D\n    F[Injected Scripts] -->|Web Fetcher| D\n    \n    G[Sidepanel UI] -->|User Interaction| C\n    H[Popup UI] -->|Quick Actions| C\n```\n\n### Tool Registration Flow\n\n```mermaid\nsequenceDiagram\n    participant T as Tool Registry\n    participant B as Background Script\n    participant C as Chrome API\n    participant M as MCP Bridge\n    \n    T->>B: Register tool handlers\n    B->>C: Initialize chrome.tabs listeners\n    C->>M: Expose via native messaging\n    M->>T: Forward tool calls\n```\n\nThe extension registers tools through the shared `tools.ts` module, which defines the complete tool schema including names, descriptions, input parameters, and response formats. The background script then connects these tool definitions to actual Chrome API implementations.\n\n资料来源：[app/chrome-extension/shared/tools.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/shared/tools.ts)\n\n## Tool Categories\n\nThe browser tools are organized into the following functional categories:\n\n| Category | Tools | Purpose |\n|----------|-------|---------|\n| **Navigation** | `chrome_navigate`, `chrome_go_back_or_forward` | Page navigation and history control |\n| **Tab Management** | `chrome_switch_tab`, `chrome_close_tabs`, `chrome_close_other_tabs` | Tab lifecycle management |\n| **View Control** | `chrome_set_viewport`, `chrome_screenshot` | Visual viewport manipulation and capture |\n| **Content Extraction** | `chrome_get_web_content`, `chrome_get_interactive_elements` | Page content retrieval |\n| **User Interaction** | `chrome_click_element`, `chrome_fill_or_select`, `chrome_keyboard` | Simulated user actions |\n| **Data Management** | `chrome_bookmark_*`, `chrome_history` | Bookmark and history access |\n| **Network Monitoring** | `chrome_network_*` | HTTP traffic inspection |\n| **Script Injection** | `chrome_inject_script`, `chrome_send_command_to_inject_script` | Custom script execution |\n\n资料来源：[docs/TOOLS.md](https://github.com/hangwin/mcp-chrome/blob/main/docs/TOOLS.md)\n\n## Navigation Tools\n\n### chrome_navigate\n\nNavigates the current tab to a specified URL or performs search queries.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | `string` | Yes | Target URL or search query |\n| `options` | `object` | No | Navigation options |\n\n**Options:**\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `waitUntil` | `string` | `\"networkidle2\"` | When to consider navigation complete |\n| `timeout` | `number` | `30000` | Navigation timeout in milliseconds |\n\n**Implementation Details:**\n\nThe navigation tool first validates the URL, handling search queries by converting them to search engine URLs. It then attempts to find an existing tab matching the URL before creating a new one, promoting existing tabs to reduce clutter.\n\n```typescript\n// Simplified navigation flow\nasync function chrome_navigate(url: string, options?: NavigationOptions) {\n  const normalizedUrl = validateAndNormalizeUrl(url);\n  const existingTab = await findExistingTab(normalizedUrl);\n  \n  if (existingTab) {\n    await chrome.tabs.update(existingTab.id, { active: true });\n    return existingTab;\n  }\n  \n  return await chrome.tabs.create({ url: normalizedUrl, active: true });\n}\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/index.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/index.ts)\n\n### chrome_go_back_or_forward\n\nNavigates browser history by a specified number of steps.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `historySteps` | `number` | Yes | Number of steps (- for back, + for forward) |\n\n## Tab Management Tools\n\n### Tab Query System\n\n```mermaid\ngraph LR\n    A[URL Pattern] -->|Parse| B[Tab Filter]\n    B -->|Query| C[chrome.tabs.query]\n    C -->|Results| D[Tab IDs Array]\n    \n    E[Tab ID] -->|Direct| D\n    F[Window ID] -->|Window Filter| D\n```\n\nThe tab management system supports multiple query mechanisms:\n\n- **URL Pattern Matching**: Glob-style patterns with wildcard support\n- **Direct Tab ID**: Integer-based tab identification\n- **Window Scoping**: Restricting operations to specific windows\n\n**Pattern Matching Implementation:**\n\n```typescript\nprivate async queryTabsByUrl(urlPattern: string): Promise<number[]> {\n  // Normalize pattern with proper glob-to-regex conversion\n  const pattern = urlPattern\n    .replace(/\\./g, '\\\\.')\n    .replace(/\\*/g, '.*')\n    .replace(/\\?/g, '.');\n  \n  const tabs = await chrome.tabs.query({ url: `<all_urls>` });\n  return tabs\n    .filter(tab => tab.url?.match(new RegExp(pattern)))\n    .map(tab => tab.id)\n    .filter((id): id is number => id !== undefined);\n}\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/common.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n\n### chrome_close_tabs\n\nCloses tabs matching a URL pattern or specified tab IDs.\n\n**Response Schema:**\n\n```typescript\ninterface CloseTabsResponse {\n  success: boolean;\n  message: string;\n  closedCount: number;\n  closedTabIds: number[];\n}\n```\n\n**Example Response:**\n\n```json\n{\n  \"success\": true,\n  \"message\": \"Closed 3 tabs with URL: https://github.com/*\",\n  \"closedCount\": 3,\n  \"closedTabIds\": [123, 456, 789]\n}\n```\n\n### chrome_switch_tab\n\nActivates a specific tab by ID or switches to adjacent tabs relative to the current tab.\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `tabId` | `number` | Target tab ID |\n| `offset` | `number` | Relative offset from current tab |\n\n## View Control Tools\n\n### chrome_screenshot\n\nCaptures screenshots with multiple targeting modes.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `captureArea` | `string` | No | `\"fullpage\"`, `\"viewport\"`, or CSS selector |\n| `selector` | `string` | No | CSS selector for element targeting |\n| `options` | `object` | No | Screenshot options (quality, format) |\n\n**Capture Modes:**\n\n| Mode | Description | Use Case |\n|------|-------------|----------|\n| `viewport` | Current visible area | Quick preview |\n| `fullpage` | Entire scrollable page | Complete documentation |\n| `element` | Specific element by selector | Targeted capture |\n\n资料来源：[docs/TOOLS.md](https://github.com/hangwin/mcp-chrome/blob/main/docs/TOOLS.md)\n\n### chrome_set_viewport\n\nControls the browser viewport dimensions for responsive testing and content adaptation.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `width` | `number` | Yes | Viewport width in pixels |\n| `height` | `number` | Yes | Viewport height in pixels |\n| `deviceScaleFactor` | `number` | No | Device pixel ratio (default: 1) |\n\n## Content Extraction Tools\n\n### chrome_get_web_content\n\nExtracts structured content from web pages including text, metadata, and semantic elements.\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `extractOptions` | `object` | Configuration for content extraction |\n| `metadata` | `boolean` | Include page metadata (default: true) |\n\n**Extracted Metadata Fields:**\n\n| Field | Source | Description |\n|-------|--------|-------------|\n| `title` | `<title>`, `og:title`, JSON-LD | Page title |\n| `byline` | `author`, `article:author` | Content author |\n| `excerpt` | `description`, `og:description` | Page summary |\n| `siteName` | `og:site_name` | Website name |\n| `publishedTime` | `article:published_time` | Publication date |\n\n**Content Script Injection:**\n\n```typescript\n// Web fetcher helper extracts structured data from pages\nconst response = await chrome.scripting.executeScript({\n  target: { tabId },\n  files: ['inject-scripts/web-fetcher-helper.js'],\n});\n```\n\n资料来源：[app/chrome-extension/inject-scripts/web-fetcher-helper.js](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/inject-scripts/web-fetcher-helper.js)\n\n### chrome_get_interactive_elements\n\nRetrieves clickable and interactive elements from a page for automation targeting.\n\n**Response:**\n\n```typescript\ninterface InteractiveElementsResponse {\n  elements: Array<{\n    selector: string;      // CSS selector for the element\n    tagName: string;       // HTML tag name\n    text: string;          // Visible text content\n    attributes: Record<string, string>;\n    isClickable: boolean;\n    boundingRect: DOMRect;\n  }>;\n}\n```\n\n### search_tabs_content\n\nAI-powered semantic search across all open browser tabs.\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `query` | `string` | Semantic search query |\n| `maxResults` | `number` | Maximum results to return |\n\n## User Interaction Tools\n\n### chrome_click_element\n\nSimulates mouse clicks on elements identified by CSS selectors.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | `string` | Yes | CSS selector for target element |\n| `button` | `string` | No | Mouse button (`left`, `middle`, `right`) |\n| `clickCount` | `number` | No | Number of clicks |\n\n### chrome_fill_or_select\n\nFills form inputs and selects options.\n\n**Supported Input Types:**\n\n| Input Type | Action |\n|------------|--------|\n| `input[type=text]` | Text input |\n| `input[type=email]` | Email input |\n| `input[type=password]` | Password input |\n| `textarea` | Multi-line text |\n| `select` | Dropdown selection |\n| `input[type=checkbox]` | Toggle state |\n| `input[type=radio]` | Radio selection |\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | `string` | Yes | Target element selector |\n| `value` | `string` | Yes | Value to input or select |\n| `options` | `object` | No | Additional options |\n\n### chrome_keyboard\n\nSimulates keyboard input and shortcuts.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `text` | `string` | No | Text to type |\n| `shortcuts` | `string[]` | No | Keyboard shortcuts to execute |\n| `options` | `object` | No | Keyboard simulation options |\n\n**Supported Shortcuts:**\n\n```typescript\nconst shortcuts = [\n  'Ctrl+C',      // Copy\n  'Ctrl+V',      // Paste\n  'Ctrl+A',      // Select all\n  'Ctrl+K',      // Clear\n  'Enter',       // Submit\n  'Escape',      // Cancel/Dismiss\n  'Tab',         // Next element\n  'Shift+Tab',   // Previous element\n];\n```\n\n## Network Monitoring Tools\n\n### chrome_network_capture_start / stop\n\nControls webRequest API-based network traffic capture.\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `options` | `object` | Capture configuration |\n| `filterUrls` | `string[]` | URL patterns to monitor |\n\n**Captured Data:**\n\n| Field | Description |\n|-------|-------------|\n| `url` | Request URL |\n| `method` | HTTP method |\n| `headers` | Request/response headers |\n| `status` | HTTP status code |\n| `timing` | Request timing data |\n| `bodySize` | Response body size |\n\n### chrome_network_debugger_start / stop\n\nEnables Chrome DevTools Protocol debugger for detailed request/response inspection including response bodies.\n\n### chrome_network_request\n\nSends custom HTTP requests through the browser context, useful for bypassing CORS and maintaining session state.\n\n## Script Injection System\n\n### chrome_inject_script\n\nInjects JavaScript files into web pages for extended functionality.\n\n**Implementation:**\n\n```typescript\nawait chrome.scripting.executeScript({\n  target: { tabId },\n  files: ['inject-scripts/web-fetcher-helper.js'],\n});\n```\n\n**Web Accessible Resources Configuration:**\n\nThe extension allows injection of specific resource categories defined in `wxt.config.ts`:\n\n```typescript\nweb_accessible_resources: [\n  {\n    resources: [\n      '/models/*',           // ML models\n      '/workers/*',          // Web workers\n      '/inject-scripts/*',   // Helper scripts\n    ],\n    matches: ['<all_urls>'],\n  },\n]\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n### chrome_send_command_to_inject_script\n\nSends structured commands to injected content scripts via a messaging bridge.\n\n**Command Flow:**\n\n```mermaid\nsequenceDiagram\n    participant B as Background Script\n    participant C as Content Script\n    participant P as Web Page\n    \n    B->>C: chrome.tabs.sendMessage\n    C->>P: postMessage to page context\n    P-->>C: Response message\n    C-->>B: chrome.runtime.sendResponse\n```\n\n## Bookmark and History Tools\n\n### Bookmark Operations\n\n| Tool | Function |\n|------|----------|\n| `chrome_bookmark_search` | Search bookmarks by keywords |\n| `chrome_bookmark_add` | Create new bookmarks with folder support |\n| `chrome_bookmark_delete` | Remove bookmarks |\n\n### chrome_history\n\nSearches browser history with temporal filtering.\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `query` | `string` | Search query |\n| `maxResults` | `number` | Maximum entries |\n| `startTime` | `number` | Unix timestamp lower bound |\n| `endTime` | `number` | Unix timestamp upper bound |\n\n## Error Handling\n\nAll browser tools implement consistent error handling patterns:\n\n```typescript\ninterface ToolResponse {\n  content: Array<{\n    type: 'text';\n    text: string;  // JSON stringified response or error\n  }>;\n  isError: boolean;\n}\n```\n\n**Error Response Format:**\n\n```json\n{\n  \"success\": false,\n  \"error\": \"Error description\",\n  \"code\": \"ERROR_CODE\"\n}\n```\n\n**URL Exclusion Patterns:**\n\nInternal Chrome URLs are automatically excluded from operations:\n\n```typescript\nconst excludePatterns = [\n  /^chrome:\\/\\//,\n  /^chrome-extension:\\/\\//,\n  /^edge:\\/\\//,\n  /^about:/,\n  /^moz-extension:\\/\\//,\n  /^file:\\/\\//,\n];\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n\n## Security Considerations\n\n### Cross-Origin Policies\n\nThe extension implements COOP/COEP headers in production to enable SharedArrayBuffer and other features:\n\n```typescript\n...(IS_DEV\n  ? {}\n  : {\n      cross_origin_embedder_policy: { value: 'require-corp' as const },\n      cross_origin_opener_policy: { value: 'same-origin' as const },\n    })\n```\n\n### Content Security Policy\n\nProduction builds enforce strict CSP:\n\n```\nscript-src 'self' 'wasm-unsafe-eval'; \nobject-src 'self'; \nstyle-src 'self' 'unsafe-inline'; \nimg-src 'self' data: blob:;\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n## Usage with AI Agents\n\nThe browser tools are designed for seamless integration with AI agents:\n\n```typescript\n// Example: Agent task to research a topic\nconst task = {\n  instruction: \"Search for TypeScript best practices and summarize the top 5 tips\",\n  tools: [\n    \"chrome_navigate\",      // Go to search engine\n    \"chrome_get_web_content\", // Extract results\n    \"chrome_screenshot\",    // Document findings\n  ]\n};\n```\n\nThe tools provide structured, parseable responses that AI agents can use for decision-making and subsequent actions, enabling complex multi-step workflows in the browser environment.\n\n---\n\n<a id='page-record-replay'></a>\n\n## Record and Replay Engine\n\n### 相关页面\n\n相关主题：[Browser Tools and APIs](#page-browser-tools), [Storage and Data Management](#page-storage)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/chrome-extension/entrypoints/background/record-replay/index.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/index.ts)\n- [app/chrome-extension/entrypoints/background/record-replay/recording/browser-event-listener.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/recording/browser-event-listener.ts)\n- [app/chrome-extension/entrypoints/background/record-replay/rr-utils.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/rr-utils.ts)\n- [app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts)\n</details>\n\n# Record and Replay Engine\n\n## Overview\n\nThe Record and Replay Engine is a Chrome extension feature within mcp-chrome that enables automatic capture and reproduction of user browser interactions. It records navigation events, user actions, and DOM interactions into a structured flow, then replays these flows to automate repetitive browser tasks.\n\nThe engine operates as a background service within the Chrome extension, using Chrome's webExtension APIs to monitor and control browser behavior across tabs and windows.\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph Recording\n        BEL[Browser Event Listener] -->|captures| Session[Recording Session]\n        Session -->|stores| Flow[Flow Data]\n    end\n    \n    subgraph Replay\n        FR[Flow Runner] -->|executes| Steps[Flow Steps]\n        Steps -->|waits for| NI[Network Idle Detection]\n        Steps -->|injects| IS[Injected Scripts]\n    end\n    \n    subgraph Triggers\n        TriggerStore[Trigger Store] -->|activates| FR\n        DOMObs[DOM Observer] -->|detects| TriggerStore\n    end\n    \n    Flow -->|loads| FR\n    TriggerStore -->|manages| Flow\n```\n\n## Core Components\n\n### Session Manager\n\nThe session manager tracks the current recording state and maintains a list of active tabs under observation.\n\n**Key Responsibilities:**\n- Track recording status (`recording`, `idle`, `paused`)\n- Manage set of active tabs during recording\n- Store and retrieve flow data from Chrome storage\n\n**State Management:**\n```typescript\nsession.getStatus() !== 'recording'  // Check if recording is active\nsession.addActiveTab(tabId)           // Track tab for targeted STOP\nsession.removeActiveTab(tabId)        // Cleanup when tab closes\nsession.getFlow()                     // Retrieve current flow data\n```\n\n资料来源：[browser-event-listener.ts:25-30]()\n\n### Browser Event Listener\n\nThe event listener hooks into Chrome's navigation and tab APIs to capture user interactions during recording.\n\n**Monitored Events:**\n\n| Event Source | Event Type | Recording Behavior |\n|--------------|------------|-------------------|\n| `chrome.webNavigation.onCommitted` | Link navigation | Record if `transitionType === 'link'` |\n| `chrome.webNavigation.onCommitted` | reload/typed/generated | Always record |\n| `chrome.webNavigation.onCommitted` | auto_bookmark/keyword | Record |\n| `chrome.webNavigation.onCommitted` | form_submit | Record for search navigations |\n| `chrome.tabs.onRemoved` | Tab close | Remove from active set |\n| `chrome.tabs.onUpdated` | Status/URL change | Mark navigation event |\n\n**Transition Types Tracked:**\n```typescript\nconst shouldRecord = \n  t === 'reload' ||\n  t === 'typed' ||\n  t === 'generated' ||\n  t === 'auto_bookmark' ||\n  t === 'keyword' ||\n  t === 'form_submit';\n```\n\n资料来源：[browser-event-listener.ts:8-22]()\n\n### Flow Runner\n\nThe flow runner executes recorded flows by iterating through steps and performing the recorded actions.\n\n**Execution Pipeline:**\n1. Load flow from storage by `flowId`\n2. Resolve template variables from execution arguments\n3. Execute steps sequentially\n4. Handle variable assignment between steps\n5. Wait for network idle between navigation steps\n\n**Key Features:**\n- Template variable expansion using `\\{variable\\}` syntax\n- Variable assignment from step outputs via `assign` map\n- Network idle detection for reliable page load waits\n- Support for both DOM-based and programmatic triggers\n\n资料来源：[index.ts:1-50]()\n\n### DOM Trigger System\n\nTriggers enable automatic replay initiation based on DOM element presence or changes.\n\n**Trigger Configuration:**\n```typescript\n{\n  id: string,\n  type: 'dom',\n  enabled: boolean,\n  selector: string,       // CSS selector for target element\n  appear: boolean,        // Trigger on element appearance\n  once: boolean,          // Fire only once per session\n  debounceMs: number      // Default: 800ms\n}\n```\n\n**Trigger Lifecycle:**\n1. Store triggers in `chrome.storage.local` under `STORAGE_KEYS.RR_TRIGGERS`\n2. Inject `dom-observer.js` into target tab\n3. Send trigger configuration via message to injected script\n4. DOM observer monitors for selector matches\n5. On match, initiate flow replay\n\n资料来源：[index.ts:60-85]()\n\n### Utility Functions\n\n**applyAssign**: Maps values from a source object to a target using path notation.\n\n```typescript\napplyAssign(target, source, {\n  'variableName': 'path.to.value',\n  'nested.value': 'data[0].field'\n});\n```\n\n**expandTemplatesDeep**: Recursively expands template variables in any value type.\n\n```typescript\n// Input: \"Navigate to \\{baseUrl\\}/home\"\n// Scope: { baseUrl: 'https://example.com' }\n// Output: \"Navigate to https://example.com/home\"\n```\n\n资料来源：[rr-utils.ts:1-50]()\n\n## Recording Process\n\n### 1. Initialization\n\nWhen recording starts:\n1. Session status transitions to `recording`\n2. Active tab list is initialized\n3. Event listeners are attached to Chrome APIs\n\n### 2. Event Capture\n\n```mermaid\nsequenceDiagram\n    participant U as User\n    participant C as Chrome API\n    participant L as Event Listener\n    participant S as Session\n    \n    U->>C: Click/Type/Navigate\n    C->>L: webNavigation.onCommitted\n    L->>L: Check transition type\n    L->>S: getFlow()\n    S-->>L: Current flow object\n    L->>S: addNavigationStep(url)\n    L->>L: ensureRecorderInjected(tabId)\n    L->>L: broadcastControlToTab(START)\n    S->>S: addActiveTab(tabId)\n```\n\n### 3. Navigation Step Recording\n\nNavigation events are captured with the current tab URL:\n\n```typescript\nconst tab = await chrome.tabs.get(tabId);\nconst url = tab.url || details.url;\nif (flow && url) addNavigationStep(flow, url);\n```\n\n### 4. Script Injection\n\nAfter each navigation, the extension ensures content scripts are injected for replay preparation:\n\n```typescript\nawait ensureCoreInjected(details.tabId);\nawait ensureRecorderInjected(tabId);\nawait broadcastControlToTab(tabId, REC_CMD.START);\n```\n\n## Replay Process\n\n### 1. Flow Loading\n\nFlows are retrieved by ID and validated before execution:\n\n```typescript\nconst flow = await getFlow(t.flowId);\nif (!flow) return;\nawait runFlow(flow, { args: t.args || {}, returnLogs: false });\n```\n\n### 2. Variable Expansion\n\nTemplate variables in flow steps are resolved from the execution arguments:\n\n```typescript\nexpandTemplatesDeep(value, { ...scope, ...args });\n```\n\n### 3. Step Execution\n\nEach step in the flow is executed in topological order, with:\n- Network idle waits between navigation steps\n- DOM query waits for element visibility\n- Error handling for selector mismatches\n\n### 4. Network Idle Detection\n\nThe engine waits for network activity to settle before proceeding:\n\n```typescript\nexport async function waitForNetworkIdle(\n  tabId: number,\n  sniffMs: number = 2000\n): Promise<void>\n```\n\n**Detection Strategy:**\n- Monitor `onCommitted`, `onCompleted`, `onHistoryStateUpdated`\n- Track tab loading status via `tabs.onUpdated`\n- Set timeout for sniff period (default: 2000ms)\n\n资料来源：[wait.ts:1-50]()\n\n## Data Models\n\n### Flow Structure\n\n```typescript\ninterface Flow {\n  id: string;\n  name?: string;\n  steps: Step[];\n  variables?: Record<string, any>;\n  createdAt: number;\n}\n\ninterface Step {\n  id: string;\n  type: 'navigation' | 'interaction' | 'wait';\n  action?: string;\n  selector?: string;\n  url?: string;\n  value?: any;\n  assign?: Record<string, string>;  // Variable assignments\n}\n```\n\n### Trigger Storage\n\n```typescript\ninterface StoredTriggers {\n  triggers: Array<{\n    id: string;\n    type: 'dom' | 'network';\n    enabled: boolean;\n    selector?: string;\n    appear?: boolean;\n    once?: boolean;\n    debounceMs?: number;\n  }>;\n}\n```\n\n## Security Considerations\n\n### Content Security Policy\n\nThe extension enforces strict CSP in production:\n\n```typescript\ncontent_security_policy: {\n  extension_pages: \n    \"script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; \" +\n    \"style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:;\"\n}\n```\n\n### Script Injection Safety\n\n- Scripts are injected only into controlled pages\n- DOM observers use isolated worlds\n- Script injection is preheated only for valid flow replays\n\n## Configuration\n\n### Flow Execution Options\n\n```typescript\ninterface RunFlowOptions {\n  args?: Record<string, string>;      // Template variable values\n  returnLogs?: boolean;               // Include execution logs\n  triggerId?: string;                 // Associated trigger ID\n}\n```\n\n### Recording Commands\n\n```typescript\nenum REC_CMD {\n  START = 'start',      // Begin recording in tab\n  STOP = 'stop',        // End recording in tab\n  PAUSE = 'pause',      // Pause current recording\n  RESUME = 'resume'     // Resume paused recording\n}\n```\n\n## Extension Points\n\n### Custom Event Handlers\n\nThe engine supports extension through the shared utility layer:\n\n```typescript\nimport { TOOL_NAMES, topoOrder, mapNodeToStep } from 'chrome-mcp-shared';\n```\n\n### Policy-Based Waiting\n\nAdditional wait policies can be registered for specialized scenarios:\n\n```typescript\n// In engine/policies/wait.ts\nexport { waitForNetworkIdle };\n```\n\n## Related Components\n\n| Component | Location | Purpose |\n|-----------|----------|---------|\n| DOM Observer | `inject-scripts/dom-observer.js` | Monitors DOM for trigger elements |\n| Web Fetcher | `inject-scripts/web-fetcher-helper.js` | Extracts page content |\n| Element Marker | `inject-scripts/element-marker.js` | Visual element selection UI |\n\n## Usage Example\n\n**Recording a flow:**\n1. Open Chrome DevTools → MCP tab\n2. Click \"Start Recording\"\n3. Perform browser actions (navigate, fill forms, click)\n4. Click \"Stop Recording\"\n5. Flow is saved with captured steps\n\n**Replaying a flow:**\n1. Load saved flow by ID\n2. Optionally provide template variable values\n3. Engine executes steps with network idle waits\n4. Variables are assigned and can be used in subsequent steps\n\n## References\n\n- Chrome Extension webNavigation API: [developer.chrome.com](https://developer.chrome.com/docs/extensions/reference/api/webNavigation)\n- Chrome Extension tabs API: [developer.chrome.com](https://developer.chrome.com/docs/extensions/reference/api/tabs)\n- Chrome.scripting API: [developer.chrome.com](https://developer.chrome.com/docs/extensions/reference/api/scripting)\n\n---\n\n<a id='page-mcp-server'></a>\n\n## MCP Server Implementation\n\n### 相关页面\n\n相关主题：[Communication Protocols](#page-communication), [Browser Tools and APIs](#page-browser-tools), [AI Agent Engines](#page-agent-engines)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/native-server/src/mcp/mcp-server.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/mcp/mcp-server.ts)\n- [app/native-server/src/mcp/register-tools.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/mcp/register-tools.ts)\n- [app/native-server/src/server/index.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/server/index.ts)\n- [app/native-server/src/mcp/mcp-server-stdio.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/mcp/mcp-server-stdio.ts)\n- [app/native-server/src/agent/session-service.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/session-service.ts)\n- [app/native-server/src/agent/engines/claude.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/engines/claude.ts)\n- [app/native-server/src/scripts/doctor.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/doctor.ts)\n</details>\n\n# MCP Server Implementation\n\n## Overview\n\nThe MCP Server Implementation provides a bridge between AI coding assistants and Chrome browser automation through the Model Context Protocol (MCP). This component enables AI agents to interact with the browser by exposing a comprehensive set of tools for navigation, content extraction, interaction, and network monitoring.\n\n资料来源：[app/native-server/src/mcp/register-tools.ts]()\n\n## Architecture\n\n### System Components\n\nThe MCP Server Implementation consists of four primary components that work together to enable AI-browser interaction:\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| MCP Server Core | `mcp-server.ts` | Core protocol implementation and message handling |\n| Tool Registry | `register-tools.ts` | Tool registration and definition |\n| Stdio Transport | `mcp-server-stdio.ts` | Standard I/O communication layer |\n| Server Entry | `server/index.ts` | Server initialization and lifecycle management |\n\n资料来源：[app/native-server/src/mcp/mcp-server.ts](), [app/native-server/src/mcp/register-tools.ts]()\n\n### Communication Flow\n\n```mermaid\ngraph TD\n    A[AI Client] -->|MCP Protocol| B[Stdio Transport Layer]\n    B --> C[MCP Server Core]\n    C --> D[Tool Registry]\n    D --> E[Chrome Extension]\n    E --> F[Browser Tabs]\n    F -->|Results| E\n    E -->|Tool Results| D\n    D -->|Structured Response| C\n    C -->|JSON-RPC| B\n    B -->|stdout| A\n```\n\n## MCP Server Core\n\nThe core server implementation handles the MCP protocol lifecycle, managing tool invocations, tool results, and resource operations.\n\n资料来源：[app/native-server/src/mcp/mcp-server.ts]()\n\n### Message Handling\n\nThe server processes incoming JSON-RPC requests and dispatches them to appropriate handlers:\n\n```typescript\n// Message dispatch pattern\ndispatchToolMessage(\n  isError\n    ? `Error: ${content || 'Tool execution failed'}`\n    : content || 'Tool completed',\n  metadata,\n  'tool_result',\n  false,\n);\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:50-56]()\n\n### Tool Metadata Building\n\nTool metadata is constructed with full input details to provide context to AI clients:\n\n```typescript\nconst metadata = buildToolMetadata({\n  name: pending.toolName,\n  id: pending.toolId,\n  input,\n});\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:85-89]()\n\n## Tool Categories\n\n### Navigation Tools (7 tools)\n\n| Tool Name | Description | Key Parameters |\n|-----------|-------------|----------------|\n| `chrome_navigate` | Navigate to URLs or perform searches | `url`, `query` |\n| `chrome_go_back_or_forward` | Browser navigation control | `direction` |\n| `chrome_switch_tab` | Switch the current active tab | `tabId` |\n| `chrome_close_tabs` | Close specific tabs or windows | `tabIds`, `windowIds` |\n| `chrome_reload` | Reload current page or tabs | `tabId` |\n| `chrome_inject_script` | Inject content scripts into web pages | `script`, `tabId` |\n| `chrome_send_command_to_inject_script` | Send commands to injected scripts | `command`, `tabId` |\n\n### Interaction Tools (3 tools)\n\n| Tool Name | Description |\n|-----------|-------------|\n| `chrome_click_element` | Click elements using CSS selectors |\n| `chrome_fill_or_select` | Fill forms and select options |\n| `chrome_keyboard` | Simulate keyboard input and shortcuts |\n\n### Data Management (5 tools)\n\n| Tool Name | Description | Parameters |\n|-----------|-------------|------------|\n| `chrome_history` | Search browser history with time filters | `query`, `startTime`, `endTime` |\n| `chrome_bookmark_search` | Find bookmarks by keywords | `query` |\n| `chrome_bookmark_add` | Add new bookmarks with folder support | `url`, `title`, `folder` |\n| `chrome_bookmark_delete` | Delete bookmarks | `bookmarkId` |\n\n### Network Monitoring (4 tools)\n\n| Tool Name | Description | API Used |\n|-----------|-------------|----------|\n| `chrome_network_capture_start/stop` | webRequest API network capture | `chrome.webRequest` |\n| `chrome_network_debugger_start/stop` | Debugger API with response bodies | `chrome.debugger` |\n| `chrome_network_request` | Send custom HTTP requests | `fetch` via background |\n\n### Content Analysis (4 tools)\n\n| Tool Name | Description |\n|-----------|-------------|\n| `search_tabs_content` | AI-powered semantic search across browser tabs |\n| `chrome_get_web_content` | Extract HTML/text content from pages |\n| `chrome_get_interactive_elements` | Find clickable elements |\n| `chrome_console` | Capture and retrieve console output |\n\n### Visual Tools (1 tool)\n\n| Tool Name | Description | Parameters |\n|-----------|-------------|------------|\n| `chrome_screenshot` | Advanced screenshot capture | `element`, `fullPage`, `width`, `height` |\n\n资料来源：[app/native-server/src/mcp/register-tools.ts]()\n\n## Tool Parameter Extraction\n\nThe MCP server extracts structured metadata from tool invocations to provide AI clients with meaningful context:\n\n```typescript\n// Bash/shell - command extraction\nif (normalizedName === 'bash' || normalizedName.includes('shell')) {\n  if (typeof input.command === 'string') {\n    metadata.command = input.command;\n  }\n  if (typeof input.description === 'string') {\n    metadata.commandDescription = input.description;\n  }\n}\n```\n\n### Search Tool Metadata\n\n```typescript\n// Search tools (grep, glob)\nif (normalizedName === 'grep' || normalizedName.includes('search')) {\n  if (typeof input.pattern === 'string') metadata.pattern = input.pattern;\n  if (typeof input.path === 'string') metadata.searchPath = input.path;\n  if (typeof input.glob === 'string') metadata.glob = input.glob;\n  if (typeof input.output_mode === 'string') metadata.outputMode = input.output_mode;\n}\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:120-140]()\n\n## Stdio Transport Layer\n\nThe stdio transport layer handles communication between the MCP server and AI clients through standard input/output streams.\n\n```mermaid\nsequenceDiagram\n    participant AI as AI Client\n    participant Stdio as Stdio Transport\n    participant Server as MCP Server Core\n    participant Chrome as Chrome Extension\n\n    AI->>Stdio: JSON-RPC Request (stdin)\n    Stdio->>Server: Parsed Request\n    Server->>Chrome: Tool Invocation\n    Chrome->>Chrome: Execute in Browser\n    Chrome-->>Server: Tool Result\n    Server-->>Stdio: JSON-RPC Response\n    Stdio-->>AI: stdout Response\n```\n\n资料来源：[app/native-server/src/mcp/mcp-server-stdio.ts]()\n\n### Port Configuration\n\nThe stdio transport requires proper port configuration to communicate with the Chrome extension:\n\n```typescript\nconst url = new URL(configValue.url as string);\nconst port = Number(url.port);\nconst portOk = port === EXPECTED_PORT;\n```\n\n资料来源：[app/native-server/src/scripts/doctor.ts:120-128]()\n\n## Agent Session Integration\n\nThe MCP server integrates with the agent session service to support multi-session environments:\n\n```typescript\nexport interface AgentSessionPreviewMeta {\n  /** Compact display text */\n  displayText?: string;\n  /** Client metadata for special rendering */\n  clientMeta?: {\n    kind?: string;\n    // ...\n  };\n}\n```\n\n### Session Management Configuration\n\n```typescript\nexport interface SessionConfig {\n  mcpServers?: Record<string, unknown>;\n  outputFormat?: Record<string, unknown>;\n  enableFileCheckpointing?: boolean;\n  sandbox?: Record<string, unknown>;\n  env?: Record<string, string>;\n  codexConfig?: Partial<CodexEngineConfig>;\n}\n```\n\n资料来源：[app/native-server/src/agent/session-service.ts:15-35]()\n\n## Claude Engine Integration\n\nThe MCP server works seamlessly with the Claude engine through structured tool result handling:\n\n### Tool Input Parsing\n\n```typescript\n// Parse accumulated JSON input\nconst fullJsonStr = pending.inputJsonParts.join('');\nlet input: Record<string, unknown> = {};\ntry {\n  if (fullJsonStr) {\n    input = JSON.parse(fullJsonStr);\n  }\n} catch (e) {\n  console.error(`[ClaudeEngine] Failed to parse tool input JSON: ${e}`);\n}\n```\n\n### Content Preview Extraction\n\n```typescript\n// Write tool - content preview\nif (normalizedName.includes('write') || normalizedName === 'create_file') {\n  if (typeof input.content === 'string') {\n    metadata.contentPreview = input.content.slice(0, 200);\n    metadata.totalLines = input.content.split('\\n').length;\n  }\n}\n\n// Read tool - offset/limit\nif (normalizedName.includes('read')) {\n  if (typeof input.offset === 'number') metadata.offset = input.offset;\n  if (typeof input.limit === 'number') metadata.limit = input.limit;\n}\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:90-110]()\n\n## Chrome Extension Communication\n\nThe MCP server communicates with the Chrome extension through a defined message protocol:\n\n```mermaid\ngraph LR\n    A[MCP Server] -->|chrome.runtime.sendMessage| B[Background Script]\n    B --> C[Content Scripts]\n    C -->|DOM Access| D[Web Pages]\n    B -->|Tabs API| E[Browser Tabs]\n```\n\n### Web Accessible Resources\n\nThe extension exposes necessary resources for tool execution:\n\n```typescript\nweb_accessible_resources: [\n  {\n    resources: [\n      '/models/*',        // AI models\n      '/workers/*',       // Web workers\n      '/inject-scripts/*' // Content script helpers\n    ],\n    matches: ['<all_urls>'],\n  },\n]\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts]()\n\n## Error Handling\n\nThe MCP server implements comprehensive error handling:\n\n### Error Detection Patterns\n\n```typescript\nconst isError =\n  meta.is_error === true ||\n  meta.isError === true ||\n  (typeof msg.content === 'string' && msg.content.trimStart().startsWith('Error:'));\n```\n\n### Tool Severity Classification\n\n| Condition | Severity |\n|-----------|----------|\n| `isError` is true | `error` |\n| Tool execution successful | `success` |\n| Tool execution in progress | `info` |\n\n## Configuration Management\n\n### Environment-Specific Security\n\n```typescript\n...(IS_DEV\n  ? {}\n  : {\n      cross_origin_embedder_policy: { value: 'require-corp' as const },\n      cross_origin_opener_policy: { value: 'same-origin' as const },\n      content_security_policy: {\n        extension_pages:\n          \"script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:;\",\n      },\n    })\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts]()\n\n## Diagnostic Tools\n\nThe MCP server includes diagnostic capabilities:\n\n| Check ID | Title | Purpose |\n|----------|-------|---------|\n| `port.config` | Port config | Verify stdio-config.json port |\n| `port.constant` | Port constant | Verify native server port constant |\n\n### Doctor Script Output\n\n```typescript\nchecks.push({\n  id: 'port.config',\n  title: 'Port config',\n  status: portOk ? 'ok' : 'error',\n  message: configValue.url as string,\n  details: {\n    expectedPort: EXPECTED_PORT,\n    actualPort: port,\n    fix: portOk ? undefined : [`${COMMAND_NAME} update-port ${EXPECTED_PORT}`],\n  },\n});\n```\n\n资料来源：[app/native-server/src/scripts/doctor.ts:130-145]()\n\n## Summary\n\nThe MCP Server Implementation provides a robust bridge between AI coding assistants and Chrome browser automation. Key features include:\n\n- **Protocol Compliance**: Full MCP protocol implementation with JSON-RPC message handling\n- **Comprehensive Tools**: 24+ tools covering navigation, interaction, data management, network monitoring, and content analysis\n- **Structured Metadata**: Rich tool result metadata for AI context understanding\n- **Flexible Transport**: Stdio-based communication for easy integration with various AI clients\n- **Security**: Environment-aware security policies and proper isolation\n- **Debugging**: Built-in diagnostic capabilities for troubleshooting connectivity issues\n\n---\n\n<a id='page-agent-engines'></a>\n\n## AI Agent Engines\n\n### 相关页面\n\n相关主题：[MCP Server Implementation](#page-mcp-server), [Browser Tools and APIs](#page-browser-tools)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/native-server/src/agent/engines/claude.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/engines/claude.ts)\n- [app/native-server/src/agent/engines/codex.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/engines/codex.ts)\n- [app/native-server/src/agent/tool-bridge.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/tool-bridge.ts)\n- [app/native-server/src/agent/chat-service.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/chat-service.ts)\n- [packages/shared/src/agent-types.ts](https://github.com/hangwin/mcp-chrome/blob/main/packages/shared/src/agent-types.ts)\n</details>\n\n# AI Agent Engines\n\n## Overview\n\nThe AI Agent Engines system is a core architectural component of the MCP Chrome project that provides an abstraction layer for interacting with different LLM (Large Language Model) backends. This module enables the browser extension to leverage various AI providers (Claude, Codex) for intelligent automation, workflow execution, and browser control.\n\nThe engine system follows a unified interface pattern, allowing seamless switching between different AI providers while maintaining consistent behavior for tool execution, message handling, and state management.\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:1-50]()\n资料来源：[app/native-server/src/agent/engines/codex.ts:1-50]()\n\n## Architecture\n\n### System Components\n\n```mermaid\ngraph TD\n    A[Chat Service] --> B[Tool Bridge]\n    B --> C[Claude Engine]\n    B --> D[Codex Engine]\n    C --> E[Claude API]\n    D --> F[Codex API]\n    E --> G[Stream Events]\n    F --> G\n    G --> H[Tool Dispatcher]\n    H --> I[Browser/Tools]\n```\n\n### Supported Engines\n\n| Engine | Provider | Status | Primary Use Case |\n|--------|----------|--------|------------------|\n| Claude | Anthropic | Active | General AI assistance, code generation |\n| Codex | OpenAI | Active | Code-focused tasks, GitHub integration |\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:1-30]()\n资料来源：[app/native-server/src/agent/engines/codex.ts:1-30]()\n\n## Engine Interface\n\n### Base Capabilities\n\nAll agent engines implement a common interface that handles:\n\n- **Message Streaming**: Real-time event streaming from AI providers\n- **Tool Execution**: Routing tool calls to appropriate handlers\n- **Content Parsing**: Processing multi-modal content blocks\n- **Error Handling**: Graceful error management and recovery\n\n### Event Processing\n\nThe engines process events through a unified event loop:\n\n```mermaid\nsequenceDiagram\n    participant API as AI API\n    participant Engine as Agent Engine\n    participant Bridge as Tool Bridge\n    participant Browser as Browser/Tools\n    \n    API->>Engine: content_block_start\n    Engine->>Engine: accumulateToolInput()\n    API->>Engine: content_block_delta\n    Engine->>Engine: parseToolInput()\n    API->>Engine: content_block_stop\n    Engine->>Bridge: dispatchToolMessage()\n    Bridge->>Browser: executeTool()\n    Browser->>Bridge: toolResult\n    Bridge->>Engine: forwardResult\n    Engine->>API: streamResponse\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:50-120]()\n资料来源：[app/native-server/src/agent/engines/codex.ts:50-100]()\n\n## Claude Engine\n\n### Overview\n\nThe Claude Engine (`claude.ts`) implements the Anthropic Claude API integration, handling streaming responses and tool execution through the Claude Messages API.\n\n### Core Features\n\n**Content Block Handling**\n\nThe engine processes different content block types:\n\n- `content_block_start`: Initializes tool input accumulation\n- `content_block_delta`: Accumulates tool input JSON chunks\n- `content_block_stop`: Finalizes and parses accumulated tool input\n\n**Tool Result Processing**\n\n```typescript\n// Extract tool result content from content blocks\nconst extractToolResultContent = (contentBlock) => {\n  if (contentBlock.type === 'tool_result') {\n    return contentBlock.content?.text || null;\n  }\n  return null;\n};\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:80-100]()\n\n**Error Handling**\n\nThe engine detects errors through multiple indicators:\n\n| Error Indicator | Source | Priority |\n|-----------------|--------|----------|\n| `is_error: true` | API response | High |\n| `isError: true` | Metadata | High |\n| Content starts with \"Error:\" | Message content | Medium |\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:40-60]()\n\n### Metadata Building\n\nThe Claude engine constructs comprehensive tool metadata:\n\n```typescript\nconst buildToolMetadata = ({\n  name: pending.toolName,\n  id: pending.toolId,\n  input,\n}) => {\n  // Returns structured metadata for tool invocation\n};\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:100-130]()\n\n## Codex Engine\n\n### Overview\n\nThe Codex Engine (`codex.ts`) integrates with OpenAI's Codex API, providing specialized handling for code-related tasks and GitHub integration.\n\n### Core Features\n\n**Tool Message Dispatch**\n\nThe engine implements a sophisticated tool dispatching system:\n\n```typescript\nconst dispatchToolMessage = (\n  content: string,\n  metadata: Record<string, unknown>,\n  type: string,\n  isUpdate: boolean\n) => {\n  // Dispatches tool execution results with metadata\n};\n```\n\n资料来源：[app/native-server/src/agent/engines/codex.ts:30-60]()\n\n**Todo List Management**\n\nThe Codex engine includes specialized support for task tracking:\n\n```mermaid\ngraph LR\n    A[Agent Response] --> B[emitTodoListUpdate]\n    B --> C{Phase}\n    C -->|started| D[Tool Use Event]\n    C -->|update| D\n    C -->|completed| E[Tool Result Event]\n    \n    F[Raw Items] --> G[normalizeTodoListItems]\n    G --> H[buildTodoListContent]\n```\n\n**Item Event Types**\n\n| Event Type | Handler | Output |\n|------------|---------|--------|\n| `command_execution` | `emitCommandStart` | Command start message |\n| `todo_list` | `emitTodoListUpdate` | Todo list state |\n| `agent_message` | Text extraction | Text content |\n\n资料来源：[app/native-server/src/agent/engines/codex.ts:60-100]()\n\n**Command Execution Tracking**\n\n```typescript\nconst emitCommandStart = (record: Record<string, unknown>) => {\n  const command = this.pickFirstString(record.command);\n  const description = this.pickFirstString(record.description);\n  // Emits command start event for UI tracking\n};\n```\n\n资料来源：[app/native-server/src/agent/engines/codex.ts:40-50]()\n\n## Tool Bridge Integration\n\n### Purpose\n\nThe Tool Bridge (`tool-bridge.ts`) acts as the intermediary between agent engines and actual tool implementations, providing:\n\n- **Tool Routing**: Directs tool calls to appropriate handlers\n- **Parameter Transformation**: Converts engine-specific formats to tool formats\n- **Result Formatting**: Standardizes tool responses for engines\n\n### Tool Execution Flow\n\n```mermaid\ngraph LR\n    A[Engine Tool Call] --> B[Tool Bridge]\n    B --> C{toolId match?}\n    C -->|Yes| D[Execute Tool]\n    C -->|No| E[Error Handler]\n    D --> F[Format Result]\n    E --> G[Error Response]\n    F --> H[Return to Engine]\n```\n\n## Chat Service Coordination\n\n### Service Layer\n\nThe Chat Service (`chat-service.ts`) orchestrates the interaction between user interfaces and agent engines:\n\n```mermaid\ngraph TD\n    A[User Request] --> B[Chat Service]\n    B --> C[Select Engine]\n    C --> D[Claude or Codex]\n    D --> E[Stream Events]\n    E --> F[Tool Bridge]\n    F --> G[Execute Tools]\n    G --> H[Return Results]\n    H --> E\n    E --> I[User Response]\n```\n\n### Message Handling\n\nAll engines communicate through a standardized message format defined in `agent-types.ts`:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `content` | string | Message text content |\n| `metadata` | object | Engine-specific metadata |\n| `type` | string | Message type (tool_use, tool_result, etc.) |\n| `isUpdate` | boolean | Whether this is an incremental update |\n\n资料来源：[packages/shared/src/agent-types.ts:1-50]()\n\n## Common Patterns\n\n### Tool Input Accumulation\n\nBoth engines implement a similar pattern for handling streaming tool inputs:\n\n1. **Start**: Initialize input accumulator on `content_block_start`\n2. **Delta**: Append JSON chunks on `content_block_delta`\n3. **Stop**: Parse complete JSON on `content_block_stop`\n\n```typescript\n// Pseudocode for accumulation pattern\nconst pendingToolInputs = new Map<number, PendingInput>();\n\nfunction handleContentBlockStart(index, toolName, toolId) {\n  pendingToolInputs.set(index, {\n    toolName,\n    toolId,\n    inputJsonParts: []\n  });\n}\n\nfunction handleContentBlockDelta(index, chunk) {\n  const pending = pendingToolInputs.get(index);\n  if (pending) {\n    pending.inputJsonParts.push(chunk);\n  }\n}\n```\n\n### Error Detection Strategy\n\nEngines use a layered error detection approach:\n\n| Layer | Check | Action |\n|-------|-------|--------|\n| 1 | `is_error` flag | Immediate error |\n| 2 | `isError` flag | Error from metadata |\n| 3 | Content prefix | Parse \"Error:\" prefix |\n\n### Severity Classification\n\nTool execution results are classified by severity:\n\n| Severity | Trigger | Visual Indicator |\n|----------|---------|------------------|\n| `error` | Error detected | Red highlight |\n| `success` | Tool completed | Green checkmark |\n| `info` | In progress | Neutral/informational |\n\n## Configuration\n\n### Engine Selection\n\nEngines are selected based on:\n\n- User preference/settings\n- Task requirements (code vs. general)\n- API availability\n\n### Environment Variables\n\n| Variable | Engine | Purpose |\n|----------|--------|---------|\n| `ANTHROPIC_API_KEY` | Claude | Authentication |\n| `OPENAI_API_KEY` | Codex | Authentication |\n| `API_BASE_URL` | Both | Endpoint configuration |\n\n## Extension Points\n\n### Adding New Engines\n\nTo add a new engine:\n\n1. Create engine file in `engines/` directory\n2. Implement common interface methods\n3. Register in engine factory/registry\n4. Add tool handlers in Tool Bridge\n\n### Custom Tool Handlers\n\nTool handlers can be extended by:\n\n1. Implementing handler in `tool-bridge.ts`\n2. Registering handler in tool registry\n3. Adding type definitions in `agent-types.ts`\n\n## Best Practices\n\n### Error Handling\n\n- Always check multiple error indicators\n- Provide meaningful error messages\n- Log errors with context for debugging\n\n### Streaming\n\n- Handle partial content gracefully\n- Accumulate tool inputs properly\n- Update UI incrementally\n\n### Resource Management\n\n- Clean up pending inputs after processing\n- Limit retry attempts for failed calls\n- Monitor API rate limits\n\n## Related Documentation\n\n- [Chrome Extension Architecture](../architecture.md)\n- [Tool System](../tools/overview.md)\n- [API Reference](../api/reference.md)\n\n---\n\n<a id='page-storage'></a>\n\n## Storage and Data Management\n\n### 相关页面\n\n相关主题：[Chrome Extension Structure](#page-extension-structure), [Record and Replay Engine](#page-record-replay)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/chrome-extension/entrypoints/background/record-replay/storage/indexeddb-manager.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/storage/indexeddb-manager.ts)\n- [app/chrome-extension/entrypoints/background/record-replay/storage/flows.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/storage/flows.ts)\n- [app/native-server/src/agent/db/client.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/db/client.ts)\n- [app/native-server/src/agent/db/schema.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/db/schema.ts)\n- [app/chrome-extension/utils/content-indexer.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n- [app/native-server/src/agent/session-service.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/session-service.ts)\n- [app/chrome-extension/entrypoints/background/semantic-similarity.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/semantic-similarity.ts)\n</details>\n\n# Storage and Data Management\n\n## Overview\n\nThe mcp-chrome project implements a dual-layer storage architecture that separates concerns between the Chrome Extension (client-side) and the Native Server (server-side). This design enables the extension to operate independently for recording, replaying, and managing browser-related data while delegating persistent storage of agent sessions and workflows to the native backend.\n\n资料来源：[app/native-server/src/agent/db/client.ts:1-50]()\n\nThe storage system handles several key data domains:\n\n| Data Domain | Storage Layer | Primary Use |\n|-------------|---------------|-------------|\n| Recording Flows | IndexedDB | Browser session recording and replay |\n| Semantic Index | chrome.storage.local | Content indexing and similarity search |\n| Agent Sessions | SQLite (better-sqlite3) | Persistent agent workflow management |\n| Model State | chrome.storage.local | ML model download and status tracking |\n| Tab Content | IndexedDB | Web page content caching |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/storage/flows.ts:1-30]()\n资料来源：[app/native-server/src/agent/session-service.ts:1-80]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    subgraph ChromeExtension[\"Chrome Extension\"]\n        A[IndexedDB] -->|Flow Recording| B[indexeddb-manager.ts]\n        C[chrome.storage.local] -->|Settings & State| D[Background Scripts]\n        E[Semantic Engine] -->|Indexing| F[content-indexer.ts]\n    end\n    \n    subgraph NativeServer[\"Native Server\"]\n        G[SQLite Database] -->|Sessions| H[db/client.ts]\n        I[Schema Definitions] -->|Tables| G\n        J[Session Service] -->|CRUD| H\n    end\n    \n    K[MCP Protocol] -->|Communication| L[Native Messaging]\n    \n    B -->|Storage Ops| A\n    F -->|Cache| C\n    H -->|Async Queries| G\n    J -->|Session Mgmt| H\n```\n\n资料来源：[app/native-server/src/agent/db/schema.ts:1-100]()\n\n## Chrome Extension Storage\n\n### IndexedDB Manager\n\nThe IndexedDB manager (`indexeddb-manager.ts`) provides structured access to browser-native storage for recording flows and session data.\n\n#### Core Operations\n\n| Method | Purpose |\n|--------|---------|\n| `initialize()` | Open/create IndexedDB database |\n| `getFlow(id)` | Retrieve a recording flow by ID |\n| `getAllFlows()` | List all stored flows |\n| `saveFlow(flow)` | Persist a new or updated flow |\n| `deleteFlow(id)` | Remove a flow from storage |\n| `clearAll()` | Wipe all stored data |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/storage/indexeddb-manager.ts:1-150]()\n\n#### Database Schema\n\n```typescript\ninterface FlowRecord {\n  id: string;\n  name: string;\n  createdAt: number;\n  updatedAt: number;\n  steps: FlowStep[];\n  triggers?: TriggerConfig[];\n  args?: Record<string, unknown>;\n}\n```\n\nThe IndexedDB schema supports:\n- **Flows**: Complete recording sessions with metadata\n- **Steps**: Individual navigation and interaction steps\n- **Triggers**: DOM-based or URL-based automation triggers\n- **Args**: Configuration parameters for flow execution\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/storage/flows.ts:1-50]()\n\n### Flow Storage Module\n\nThe `flows.ts` module wraps the IndexedDB manager with higher-level operations for flow management.\n\n```mermaid\ngraph LR\n    A[Recording Start] --> B[Create Flow Record]\n    B --> C[Capture Events]\n    C --> D[Append Steps]\n    D --> E[Trigger Detection]\n    E --> F[Save to IndexedDB]\n    F --> G[Recording Complete]\n```\n\n#### Flow Lifecycle\n\n1. **Creation**: Initialize a new flow with timestamp and metadata\n2. **Capture**: Record DOM events, network requests, and navigation\n3. **Trigger Binding**: Associate DOM selectors or URL patterns\n4. **Persistence**: Batch write to IndexedDB on completion or intervals\n5. **Retrieval**: Load flows for replay with full state reconstruction\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/storage/flows.ts:50-150]()\n\n### chrome.storage.local Usage\n\nThe extension uses Chrome's `storage.local` API for lightweight, synchronous state management:\n\n```typescript\n// Model state tracking\nconst modelState = {\n  status: string;\n  downloadProgress: number;\n  isDownloading: boolean;\n  lastUpdated: number;\n  errorMessage: string;\n  errorType: 'network' | 'file' | 'unknown';\n};\n\n// Semantic engine state\nconst semanticEngineState = {\n  isReady: boolean;\n  isInitializing: boolean;\n  modelPath?: string;\n};\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/semantic-similarity.ts:1-80]()\n\n#### Storage Keys\n\n| Key | Type | Purpose |\n|-----|------|---------|\n| `modelState` | Object | ML model download status |\n| `semanticEngineState` | Object | Content indexing engine status |\n| `RR_TRIGGERS` | Array | Record-replay DOM triggers |\n| `contentIndex` | Object | Cached page content metadata |\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:1-60]()\n\n## Native Server Database\n\n### Database Client\n\nThe native server uses `better-sqlite3` for synchronous, high-performance SQLite access.\n\n```typescript\nimport Database from 'better-sqlite3';\n\nclass AgentDatabase {\n  private db: Database.Database;\n  \n  constructor(dbPath: string);\n  initialize(): void;\n  close(): void;\n  // ... query methods\n}\n```\n\n资料来源：[app/native-server/src/agent/db/client.ts:1-80]()\n\n#### Configuration\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `dbPath` | `~/.claude/mcp-chrome.db` | SQLite database file path |\n| WAL Mode | Enabled | Write-Ahead Logging for concurrency |\n| Foreign Keys | Enabled | Referential integrity enforcement |\n\n资料来源：[app/native-server/src/agent/db/client.ts:80-120]()\n\n### Database Schema\n\n```mermaid\nerDiagram\n    SESSIONS {\n        string id PK\n        string name\n        string description\n        string engine\n        timestamp created_at\n        timestamp updated_at\n        json metadata\n    }\n    \n    MESSAGES {\n        string id PK\n        string session_id FK\n        string role\n        text content\n        timestamp created_at\n        json attachments\n        json raw\n    }\n    \n    MESSAGES }o--|| SESSIONS : belongs_to\n```\n\n#### Sessions Table\n\n| Column | Type | Constraints | Description |\n|--------|------|-------------|-------------|\n| `id` | TEXT | PRIMARY KEY | Unique session identifier |\n| `name` | TEXT | NOT NULL | Display name for session |\n| `description` | TEXT | | Session description |\n| `engine` | TEXT | | AI engine (claude, codex, etc.) |\n| `created_at` | INTEGER | NOT NULL | Unix timestamp |\n| `updated_at` | INTEGER | NOT NULL | Last modification time |\n| `metadata` | TEXT | | JSON-encoded metadata |\n\n资料来源：[app/native-server/src/agent/db/schema.ts:1-100]()\n\n#### Messages Table\n\n| Column | Type | Constraints | Description |\n|--------|------|-------------|-------------|\n| `id` | TEXT | PRIMARY KEY | Message UUID |\n| `session_id` | TEXT | FOREIGN KEY | Parent session reference |\n| `role` | TEXT | NOT NULL | Message role (user/assistant/system) |\n| `content` | TEXT | | Message text content |\n| `created_at` | INTEGER | NOT NULL | Timestamp |\n| `attachments` | TEXT | | JSON array of attachments |\n| `raw` | TEXT | | Raw metadata JSON |\n\n资料来源：[app/native-server/src/agent/db/schema.ts:100-200]()\n\n### Session Service\n\nThe session service provides the high-level interface for session and message management:\n\n```typescript\nexport interface ManagementInfo {\n  models?: Array<{ value: string; displayName: string; description: string }>;\n  commands?: Array<{ name: string; description: string; argumentHint: string }>;\n  account?: { email?: string; organization?: string; subscriptionType?: string };\n  mcpServers?: Array<{ name: string; status: string }>;\n  tools?: string[];\n  agents?: string[];\n  plugins?: Array<{ name: string; path?: string }>;\n  skills?: string[];\n  slashCommands?: string[];\n  model?: string;\n  permissionMode?: string;\n  cwd?: string;\n  outputStyle?: string;\n  betas?: string[];\n  claudeCodeVersion?: string;\n  apiKeySource?: string;\n  lastUpdated?: string;\n}\n```\n\n资料来源：[app/native-server/src/agent/session-service.ts:30-70]()\n\n#### Session Preview Metadata\n\n```typescript\nexport interface AgentSessionPreviewMeta {\n  displayText?: string;  // Compact display text\n  clientMeta?: {\n    kind?: 'web_editor_apply_batch' | 'web_editor_apply_single';\n    elementCount?: number;\n  };\n}\n```\n\nThis metadata enables special UI rendering for web editor apply operations.\n\n资料来源：[app/native-server/src/agent/session-service.ts:75-90]()\n\n## Content Indexing System\n\n### ContentIndexer Class\n\nThe content indexer manages semantic search capabilities for browser tab content:\n\n```typescript\nclass ContentIndexer {\n  private options: IndexerOptions;\n  private semanticEngine: SemanticEngine;\n  \n  async indexTabContent(tabId: number): Promise<void>;\n  async removeTabIndex(tabId: number): Promise<void>;\n  private shouldIndexUrl(url: string): boolean;\n  private async extractTabContent(tabId: number): Promise<ContentResult>;\n}\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:20-80]()\n\n### URL Filtering\n\nCertain URLs are automatically excluded from indexing:\n\n| Pattern | Reason |\n|---------|--------|\n| `chrome://*` | Chrome internal pages |\n| `chrome-extension://*` | Extension pages |\n| `edge://*` | Edge internal pages |\n| `about:*` | Browser about pages |\n| `moz-extension://*` | Firefox extension pages |\n| `file://*` | Local file system |\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:50-70]()\n\n### Auto-Indexing Behavior\n\n```mermaid\ngraph TD\n    A[Tab Load Complete] --> B{URL Valid?}\n    B -->|No| C[Skip Indexing]\n    B -->|Yes| D{Engine Ready?}\n    D -->|No| E[Wait 2 seconds]\n    E --> D\n    D -->|Yes| F[Execute Fetcher Script]\n    F --> G[Extract Page Content]\n    G --> H[Update Semantic Index]\n    H --> I[Store in IndexedDB]\n```\n\nThe auto-indexing is triggered with a 2-second delay to allow dynamic content to load.\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:10-40]()\n\n## Data Flow Summary\n\n### Recording Flow\n\n```mermaid\nsequenceDiagram\n    participant U as User\n    participant E as Extension\n    participant IDB as IndexedDB\n    participant NS as Native Server\n    \n    U->>E: Start Recording\n    E->>IDB: Create Flow Record\n    loop User Actions\n        E->>E: Capture Event\n        E->>IDB: Append Step\n    end\n    U->>E: Stop Recording\n    E->>IDB: Finalize Flow\n    E->>NS: Sync Flow Metadata\n```\n\n### Replay Flow\n\n```mermaid\nsequenceDiagram\n    participant T as Trigger\n    participant E as Extension\n    participant IDB as IndexedDB\n    participant B as Browser\n    \n    T->>E: Trigger Matched\n    E->>IDB: Load Flow\n    loop Flow Steps\n        E->>E: Process Step\n        E->>B: Execute Action\n    end\n```\n\n## Error Handling\n\nBoth storage layers implement robust error handling:\n\n| Layer | Error Strategy |\n|-------|----------------|\n| IndexedDB | Graceful degradation, console logging |\n| chrome.storage | Fallback messaging to background script |\n| SQLite | Transaction rollback, WAL recovery |\n| Network sync | Retry with exponential backoff |\n\n资料来源：[app/chrome-extension/entrypoints/offscreen/main.ts:40-80]()\n\n## Best Practices\n\n1. **Batch Writes**: Group multiple IndexedDB operations to reduce I/O\n2. **Index Maintenance**: Periodically clean stale tab indices\n3. **Transaction Scope**: Keep SQLite transactions short to prevent locks\n4. **Memory Management**: Release DOM references after content extraction\n5. **Storage Quotas**: Monitor chrome.storage.local usage for extension limits\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：hangwin/mcp-chrome\n\n摘要：发现 16 个潜在踩坑项，其中 2 个为 high/blocking；最高优先级：安装坑 - 来源证据：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint。\n\n## 1. 安装坑 · 来源证据：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ba76885913a744f0832665f5c62d0f1d | https://github.com/hangwin/mcp-chrome/issues/321 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed to connect to MCP server)\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed to connect to MCP server)\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4ac5f778b292489482bfdb7953190f96 | https://github.com/hangwin/mcp-chrome/issues/319 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 3. 安装坑 · 来源证据：Codex CLI setup guide still points to ~/.codex/config.json and a port-only flow Codex does not pick up\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Codex CLI setup guide still points to ~/.codex/config.json and a port-only flow Codex does not pick up\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_559f34b86ade48e598dac510e9341b9e | https://github.com/hangwin/mcp-chrome/issues/339 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 4. 安装坑 · 来源证据：[Feature] Profile-aware bridge — multi-Chrome-profile support without port collision\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature] Profile-aware bridge — multi-Chrome-profile support without port collision\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_93bfb3c85fbc4c0a8134e7159ddf4511 | https://github.com/hangwin/mcp-chrome/issues/347 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 5. 安装坑 · 来源证据：mcp-chrome-bridge 无法使用\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：mcp-chrome-bridge 无法使用\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5f19fb6526174af2abe5c1eab67e25ff | https://github.com/hangwin/mcp-chrome/issues/333 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 6. 安装坑 · 来源证据：🐛 Status indicator stuck on yellow - Service shows as \"not started\" after connection\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：🐛 Status indicator stuck on yellow - Service shows as \"not started\" after connection\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2b32536c95a7456788ba78e1fc705116 | https://github.com/hangwin/mcp-chrome/issues/342 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 7. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | host_targets=mcp_host, claude\n\n## 8. 能力坑 · 能力判断依赖假设\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:998796026 | https://github.com/hangwin/mcp-chrome | README/documentation is current enough for a first validation pass.\n\n## 9. 运行坑 · 来源证据：v0.0.6\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.0.6\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_035dffafcbe64f4ea112f20258430e71 | https://github.com/hangwin/mcp-chrome/releases/tag/v0.0.6 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 10. 维护坑 · 来源证据：[Feature/Bug] Multi-client MCP support — second Claude Code session kills first via shared MCP Server singleton\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[Feature/Bug] Multi-client MCP support — second Claude Code session kills first via shared MCP Server singleton\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4d4eaf47bd284105af5632bbe220b628 | https://github.com/hangwin/mcp-chrome/issues/345 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 11. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | last_activity_observed missing\n\n## 12. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | no_demo; severity=medium\n\n## 13. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | no_demo; severity=medium\n\n## 14. 安全/权限坑 · 来源证据：issue\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：issue\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_82ad93635a5e4ff5aeb2b35e36cbd02e | https://github.com/hangwin/mcp-chrome/issues/330 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\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:998796026 | https://github.com/hangwin/mcp-chrome | 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:998796026 | https://github.com/hangwin/mcp-chrome | release_recency=unknown\n\n<!-- canonical_name: hangwin/mcp-chrome; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "mcp-chrome",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "github_repo:998796026",
          "kind": "repo",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/hangwin/mcp-chrome"
        },
        {
          "evidence_id": "art_cb521702df06461cb0d74036692bd3d5",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/hangwin/mcp-chrome#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "mcp-chrome 说明书",
      "toc": [
        "https://github.com/hangwin/mcp-chrome 项目说明书",
        "目录",
        "Introduction to Chrome MCP Server",
        "Overview and Purpose",
        "System Architecture",
        "Tool Categories",
        "Content Indexing System",
        "Web Fetcher Tool",
        "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": "f48e71751e00bc09725c7e173423cff4f2ccd12a",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "pnpm-lock.yaml",
      "package.json",
      "README.md",
      "docs/ISSUE.md",
      "docs/VisualEditor.md",
      "docs/TROUBLESHOOTING.md",
      "docs/mcp-cli-config.md",
      "docs/ARCHITECTURE.md",
      "docs/TOOLS.md",
      "docs/ARCHITECTURE_zh.md",
      "docs/TROUBLESHOOTING_zh.md",
      "docs/WINDOWS_INSTALL_zh.md",
      "docs/CONTRIBUTING.md",
      "docs/VisualEditor_zh.md",
      "docs/CONTRIBUTING_zh.md",
      "docs/TOOLS_zh.md",
      "docs/CHANGELOG.md",
      "packages/wasm-simd/Cargo.toml",
      "packages/wasm-simd/package.json",
      "packages/wasm-simd/README.md",
      "packages/wasm-simd/BUILD.md",
      "packages/shared/package.json",
      "packages/shared/tsconfig.json",
      "packages/shared/src/node-spec.ts",
      "packages/shared/src/tools.ts",
      "packages/shared/src/constants.ts",
      "packages/shared/src/node-spec-registry.ts",
      "packages/shared/src/index.ts",
      "packages/shared/src/types.ts",
      "packages/shared/src/rr-graph.ts",
      "packages/shared/src/agent-types.ts",
      "packages/shared/src/step-types.ts",
      "packages/shared/src/labels.ts",
      "packages/shared/src/node-specs-builtin.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": "# mcp-chrome-bridge-monorepo - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 mcp-chrome-bridge-monorepo 编译的 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 mcp-chrome-bridge` 证据：`README.md` Claim：`clm_0003` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：先做角色匹配试用\n- **为什么**：这个项目更像角色库，核心风险是选错角色或把角色文案当执行能力；先用 Prompt Preview 试角色匹配，再决定是否沙盒导入。\n\n### 30 秒判断\n\n- **现在怎么做**：先做角色匹配试用\n- **最小安全下一步**：先用 Prompt Preview 试角色匹配；满意后再隔离导入\n- **先别相信**：角色质量和任务匹配不能直接相信。\n- **继续会触碰**：角色选择偏差、命令执行、本地环境或项目文件\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）：角色库证明有很多角色，不证明每个角色都适合你的具体任务，也不证明角色能产生高质量结果。\n- **不能把角色文案当成真实执行能力。**（unverified）：安装前只能判断角色描述和任务画像是否匹配，不能证明它能在宿主 AI 里完成任务。\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\n### 继续会触碰什么\n\n- **角色选择偏差**：用户对任务应该由哪个专家角色处理的判断。 原因：选错角色会让 AI 从错误专业视角回答，浪费时间或误导决策。\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：先用交互式试用验证任务画像和角色匹配，不要先导入整套角色库。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **保留原始角色选择记录**：如果输出偏题，可以回到任务画像阶段重新选择角色，而不是继续沿着错误角色推进。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\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_0004` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md` Claim：`clm_0005` 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- 文件总数：652\n- 重要文件覆盖：40/652\n- 证据索引条目：52\n- 角色 / Skill 条目：26\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请基于 mcp-chrome-bridge-monorepo 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 mcp-chrome-bridge-monorepo 当作安装前体验资产，而不是已安装工具或真实运行环境。\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请基于 mcp-chrome-bridge-monorepo 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 26 个角色 / Skill / 项目文档条目。\n\n- **Contributing Guide 🤝**（project_doc）：Thank you for your interest in contributing to Chrome MCP Server! This document provides guidelines and information for contributors. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/CONTRIBUTING.md`\n- **Chrome MCP Server 🚀**（project_doc）：! Stars https://img.shields.io/github/stars/hangwin/mcp-chrome https://img.shields.io/github/stars/hangwin/mcp-chrome ! License: MIT https://img.shields.io/badge/License-MIT-yellow.svg https://opensource.org/licenses/MIT ! TypeScript https://img.shields.io/badge/TypeScript-5.8+-blue.svg https://www.typescriptlang.org/ ! Chrome Extension https://img.shields.io/badge/Chrome-Extension-green.svg https://developer.chrome… 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README.md`\n- **Chrome MCP Server Extension - Latest Release**（project_doc）：Chrome MCP Server Extension - Latest Release 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`releases/README.md`\n- **WXT + Vue 3**（project_doc）：This template should help get you started developing with Vue 3 in WXT. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`app/chrome-extension/README.md`\n- **Fastify Chrome Native Messaging服务**（project_doc）：这是一个基于Fastify的TypeScript项目，用于与Chrome扩展进行原生通信。 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`app/native-server/README.md`\n- **@chrome-mcp/wasm-simd**（project_doc）：SIMD-optimized WebAssembly math functions for high-performance vector operations. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`packages/wasm-simd/README.md`\n- **Chrome MCP Bridge 安装指南**（project_doc）：本文档详细说明了 Chrome MCP Bridge 的安装和注册流程。 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`app/native-server/install.md`\n- **Chrome MCP Server Architecture 🏗️**（project_doc）：This document provides a detailed technical overview of the Chrome MCP Server architecture, design decisions, and implementation details. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/ARCHITECTURE.md`\n- **Chrome MCP Server 架构设计 🏗️**（project_doc）：本文档提供 Chrome MCP Server 架构、设计决策和实现细节的详细技术概述。 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/ARCHITECTURE_zh.md`\n- **Changelog**（project_doc）：All notable changes to this project will be documented in this file. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/CHANGELOG.md`\n- **贡献指南 🤝**（project_doc）：感谢您对 Chrome MCP Server 项目的贡献兴趣！本文档为贡献者提供指南和信息。 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/CONTRIBUTING_zh.md`\n- **Issues 总览**（project_doc）：- 总Issue数 : 183 - 开放中 : 116 - 已关闭 : 67 - 关闭率 : 36.6% - 最后更新 : 2025-10-11 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/ISSUE.md`\n- **Chrome MCP Server API Reference 📚**（project_doc）：Complete reference for all available tools and their parameters. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/TOOLS.md`\n- **Chrome MCP Server API 参考 📚**（project_doc）：- 浏览器管理 浏览器管理 - 截图和视觉 截图和视觉 - 网络监控 网络监控 - 内容分析 内容分析 - 交互操作 交互操作 - 数据管理 数据管理 - 响应格式 响应格式 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/TOOLS_zh.md`\n- **🚀 Installation and Connection Issues**（project_doc）：🚀 Installation and Connection Issues 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/TROUBLESHOOTING.md`\n- **🚀 安装和连接问题**（project_doc）：bash 打印 Markdown 报告到终端（复制粘贴到 GitHub Issue） mcp-chrome-bridge report 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/TROUBLESHOOTING_zh.md`\n- **A Visual Editor for Claude Code & Codex**（project_doc）：A Visual Editor for Claude Code & Codex 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/VisualEditor.md`\n- **让Claude Code/Codex也能使用的可视化编辑器**（project_doc）：如何开启： 右键 chrome mcp server 切换网页编辑模式 或者快捷键： cmd/ctrl + shift + o 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/VisualEditor_zh.md`\n- **windows 安装指南 🔧**（project_doc）：Chrome MCP Server 在windows电脑的详细安装和配置步骤 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/WINDOWS_INSTALL_zh.md`\n- **CLI MCP Configuration Guide**（project_doc）：This guide explains how to configure Codex CLI and Claude Code to connect to the Chrome MCP Server. 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`docs/mcp-cli-config.md`\n- **Chrome MCP Server 🚀**（project_doc）：! 许可证: MIT https://img.shields.io/badge/License-MIT-yellow.svg https://opensource.org/licenses/MIT ! TypeScript https://img.shields.io/badge/TypeScript-5.8+-blue.svg https://www.typescriptlang.org/ ! Chrome 扩展 https://img.shields.io/badge/Chrome-Extension-green.svg https://developer.chrome.com/docs/extensions/ 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`README_zh.md`\n- **Role:**（project_doc）：- 背景 : 拥有超过10年的内容分析与信息设计经验。 - 专长 : 1. 认知简化 : 能将复杂、零散的知识快速转化为结构清晰、易于理解的框架。 2. 逻辑提炼 : 擅长识别信息背后的核心逻辑、因果关系和层级结构。 3. 视觉叙事 : 是Excalidraw的顶级专家，精通利用其简洁的工具集构建富有表现力和洞察力的视觉化图表。 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`prompt/content-analize.md`\n- **角色**（project_doc）：你是一位顶级的解决方案架构师，不仅精通复杂的系统设计，更是Excalidraw的专家级用户。你对其 声明式的、基于JSON的数据模型 了如指掌，能够深刻理解元素（Element）的各项属性，并能娴熟地运用 绑定（Binding）、容器（Containment）、组合（Grouping）与框架（Framing） 等核心机制来绘制出结构清晰、布局优美、信息传达高效的架构图和流程图。 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`prompt/excalidraw-prompt.md`\n- **Role:**（project_doc）：- 背景 : 超过10年的前端开发经验，尤其在Chrome/Firefox扩展开发、Content Scripts编写和DOM性能优化方面有深厚造诣。 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`prompt/modify-web.md`\n- **Property Panel UI 重构计划**（project_doc）：当前属性面板的 UI 实现与设计稿 attr-ui.html 存在较大差异。本文档详细规划了重构任务，按照优先级从高到低排列，目标是让属性面板的视觉效果和交互体验与设计稿一致。 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`app/chrome-extension/entrypoints/web-editor-v2/attr-ui-refactor.md`\n- **WASM SIMD 构建指南**（project_doc）：bash 安装 Rust curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs sh 激活提示：当用户需要理解项目结构、安装方式或边界时参考。 证据：`packages/wasm-simd/BUILD.md`\n\n## 证据索引\n\n- 共索引 52 条证据。\n\n- **Contributing Guide 🤝**（documentation）：Thank you for your interest in contributing to Chrome MCP Server! This document provides guidelines and information for contributors. 证据：`docs/CONTRIBUTING.md`\n- **Chrome MCP Server 🚀**（documentation）：! Stars https://img.shields.io/github/stars/hangwin/mcp-chrome https://img.shields.io/github/stars/hangwin/mcp-chrome ! License: MIT https://img.shields.io/badge/License-MIT-yellow.svg https://opensource.org/licenses/MIT ! TypeScript https://img.shields.io/badge/TypeScript-5.8+-blue.svg https://www.typescriptlang.org/ ! Chrome Extension https://img.shields.io/badge/Chrome-Extension-green.svg https://developer.chrome.com/docs/extensions/ ! Release https://img.shields.io/github/v/release/hangwin/mcp-chrome.svg https://img.shields.io/github/v/release/hangwin/mcp-chrome.svg 证据：`README.md`\n- **Chrome MCP Server Extension - Latest Release**（documentation）：Chrome MCP Server Extension - Latest Release 证据：`releases/README.md`\n- **WXT + Vue 3**（documentation）：This template should help get you started developing with Vue 3 in WXT. 证据：`app/chrome-extension/README.md`\n- **Fastify Chrome Native Messaging服务**（documentation）：这是一个基于Fastify的TypeScript项目，用于与Chrome扩展进行原生通信。 证据：`app/native-server/README.md`\n- **@chrome-mcp/wasm-simd**（documentation）：SIMD-optimized WebAssembly math functions for high-performance vector operations. 证据：`packages/wasm-simd/README.md`\n- **Package**（package_manifest）：{ \"name\": \"mcp-chrome-bridge-monorepo\", \"version\": \"1.0.0\", \"private\": true, \"author\": \"hangye\", \"type\": \"module\", \"scripts\": { \"build:shared\": \"pnpm --filter chrome-mcp-shared build\", \"build:native\": \"pnpm --filter mcp-chrome-bridge build\", \"build:extension\": \"pnpm --filter chrome-mcp-server build\", \"build:wasm\": \"pnpm --filter @chrome-mcp/wasm-simd build && pnpm run copy:wasm\", \"build\": \"pnpm -r --filter='!@chrome-mcp/wasm-simd' build\", \"copy:wasm\": \"cp ./packages/wasm-simd/pkg/simd math.js ./packages/wasm-simd/pkg/simd math bg.wasm ./app/chrome-extension/workers/\", \"dev:shared\": \"pnpm --filter chrome-mcp-shared dev\", \"dev:native\": \"pnpm --filter mcp-chrome-bridge dev\", \"dev:extension\": \"… 证据：`package.json`\n- **Package**（package_manifest）：{ \"name\": \"chrome-mcp-server\", \"description\": \"a chrome extension to use your own chrome as a mcp server\", \"author\": \"hangye\", \"private\": true, \"version\": \"1.0.0\", \"type\": \"module\", \"scripts\": { \"dev\": \"wxt\", \"dev:firefox\": \"wxt -b firefox\", \"build\": \"wxt build\", \"build:firefox\": \"wxt build -b firefox\", \"zip\": \"wxt zip\", \"zip:firefox\": \"wxt zip -b firefox\", \"compile\": \"vue-tsc --noEmit\", \"postinstall\": \"wxt prepare\", \"lint\": \"npx eslint .\", \"lint:fix\": \"npx eslint . --fix\", \"format\": \"npx prettier --write .\", \"format:check\": \"npx prettier --check .\", \"test\": \"vitest run\", \"test:watch\": \"vitest\" }, \"dependencies\": { \"@modelcontextprotocol/sdk\": \"^1.11.0\", \"@vue-flow/background\": \"^1.3.2\", \"@… 证据：`app/chrome-extension/package.json`\n- **Package**（package_manifest）：{ \"name\": \"mcp-chrome-bridge\", \"version\": \"1.0.29\", \"description\": \"Chrome Native-Messaging host Node \", \"main\": \"dist/index.js\", \"bin\": { \"mcp-chrome-bridge\": \"./dist/cli.js\", \"chrome-mcp-bridge\": \"./dist/cli.js\", \"mcp-chrome-stdio\": \"./dist/mcp/mcp-server-stdio.js\" }, \"scripts\": { \"dev\": \"nodemon --watch src --ext ts,js,json --ignore dist/ --exec \\\"npm run build && npm run register:dev\\\"\", \"build\": \"ts-node src/scripts/build.ts\", \"test\": \"jest\", \"test:watch\": \"jest --watch\", \"lint\": \"eslint 'src/ / .{js,ts}'\", \"lint:fix\": \"eslint 'src/ / .{js,ts}' --fix\", \"format\": \"prettier --write 'src/ / .{js,ts,json}'\", \"register:dev\": \"node dist/scripts/register-dev.js\", \"postinstall\": \"node dist/scr… 证据：`app/native-server/package.json`\n- **Package**（package_manifest）：{ \"name\": \"chrome-mcp-shared\", \"version\": \"1.0.1\", \"author\": \"hangye\", \"main\": \"dist/index.js\", \"module\": \"./dist/index.mjs\", \"types\": \"dist/index.d.ts\", \"exports\": { \".\": { \"import\": { \"types\": \"./dist/index.d.ts\", \"default\": \"./dist/index.mjs\" }, \"require\": { \"types\": \"./dist/index.d.ts\", \"default\": \"./dist/index.js\" } } }, \"scripts\": { \"build\": \"tsup src/index.ts --format cjs,esm --dts --clean\", \"dev\": \"tsup src/index.ts --format cjs,esm --dts --watch\", \"lint\": \"npx eslint 'src/ / .{js,ts}'\", \"lint:fix\": \"npx eslint 'src/ / .{js,ts}' --fix\", \"format\": \"prettier --write 'src/ / .{js,ts,json}'\" }, \"files\": \"dist\" , \"devDependencies\": { \"@types/node\": \"^18.0.0\", \"@typescript-eslint/parser\":… 证据：`packages/shared/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@chrome-mcp/wasm-simd\", \"version\": \"0.1.0\", \"description\": \"SIMD-optimized WebAssembly math functions for Chrome MCP\", \"main\": \"pkg/simd math.js\", \"types\": \"pkg/simd math.d.ts\", \"files\": \"pkg/\" , \"scripts\": { \"build\": \"wasm-pack build --target web --out-dir pkg --release\", \"build:dev\": \"wasm-pack build --target web --out-dir pkg --dev\", \"clean\": \"rimraf pkg/\", \"test\": \"wasm-pack test --headless --firefox\" }, \"keywords\": \"wasm\", \"simd\", \"webassembly\", \"math\", \"cosine-similarity\", \"vector-operations\" , \"author\": \"hangye\", \"license\": \"MIT\", \"devDependencies\": { \"rimraf\": \"^5.0.0\" }, \"repository\": { \"type\": \"git\", \"url\": \"git+https://github.com/your-repo/chrome-mcp-server.git\", \"dire… 证据：`packages/wasm-simd/package.json`\n- **Chrome MCP Bridge 安装指南**（documentation）：本文档详细说明了 Chrome MCP Bridge 的安装和注册流程。 证据：`app/native-server/install.md`\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- **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: 证据：`app/chrome-extension/LICENSE`\n- **Chrome MCP Server Architecture 🏗️**（documentation）：This document provides a detailed technical overview of the Chrome MCP Server architecture, design decisions, and implementation details. 证据：`docs/ARCHITECTURE.md`\n- **Chrome MCP Server 架构设计 🏗️**（documentation）：本文档提供 Chrome MCP Server 架构、设计决策和实现细节的详细技术概述。 证据：`docs/ARCHITECTURE_zh.md`\n- **Changelog**（documentation）：All notable changes to this project will be documented in this file. 证据：`docs/CHANGELOG.md`\n- **贡献指南 🤝**（documentation）：感谢您对 Chrome MCP Server 项目的贡献兴趣！本文档为贡献者提供指南和信息。 证据：`docs/CONTRIBUTING_zh.md`\n- **Issues 总览**（documentation）：- 总Issue数 : 183 - 开放中 : 116 - 已关闭 : 67 - 关闭率 : 36.6% - 最后更新 : 2025-10-11 证据：`docs/ISSUE.md`\n- **Chrome MCP Server API Reference 📚**（documentation）：Complete reference for all available tools and their parameters. 证据：`docs/TOOLS.md`\n- **Chrome MCP Server API 参考 📚**（documentation）：- 浏览器管理 浏览器管理 - 截图和视觉 截图和视觉 - 网络监控 网络监控 - 内容分析 内容分析 - 交互操作 交互操作 - 数据管理 数据管理 - 响应格式 响应格式 证据：`docs/TOOLS_zh.md`\n- **🚀 Installation and Connection Issues**（documentation）：🚀 Installation and Connection Issues 证据：`docs/TROUBLESHOOTING.md`\n- **🚀 安装和连接问题**（documentation）：bash 打印 Markdown 报告到终端（复制粘贴到 GitHub Issue） mcp-chrome-bridge report 证据：`docs/TROUBLESHOOTING_zh.md`\n- **A Visual Editor for Claude Code & Codex**（documentation）：A Visual Editor for Claude Code & Codex 证据：`docs/VisualEditor.md`\n- **让Claude Code/Codex也能使用的可视化编辑器**（documentation）：如何开启： 右键 chrome mcp server 切换网页编辑模式 或者快捷键： cmd/ctrl + shift + o 证据：`docs/VisualEditor_zh.md`\n- **windows 安装指南 🔧**（documentation）：Chrome MCP Server 在windows电脑的详细安装和配置步骤 证据：`docs/WINDOWS_INSTALL_zh.md`\n- **CLI MCP Configuration Guide**（documentation）：This guide explains how to configure Codex CLI and Claude Code to connect to the Chrome MCP Server. 证据：`docs/mcp-cli-config.md`\n- **Chrome MCP Server 🚀**（documentation）：! 许可证: MIT https://img.shields.io/badge/License-MIT-yellow.svg https://opensource.org/licenses/MIT ! TypeScript https://img.shields.io/badge/TypeScript-5.8+-blue.svg https://www.typescriptlang.org/ ! Chrome 扩展 https://img.shields.io/badge/Chrome-Extension-green.svg https://developer.chrome.com/docs/extensions/ 证据：`README_zh.md`\n- **Role:**（documentation）：- 背景 : 拥有超过10年的内容分析与信息设计经验。 - 专长 : 1. 认知简化 : 能将复杂、零散的知识快速转化为结构清晰、易于理解的框架。 2. 逻辑提炼 : 擅长识别信息背后的核心逻辑、因果关系和层级结构。 3. 视觉叙事 : 是Excalidraw的顶级专家，精通利用其简洁的工具集构建富有表现力和洞察力的视觉化图表。 证据：`prompt/content-analize.md`\n- **角色**（documentation）：你是一位顶级的解决方案架构师，不仅精通复杂的系统设计，更是Excalidraw的专家级用户。你对其 声明式的、基于JSON的数据模型 了如指掌，能够深刻理解元素（Element）的各项属性，并能娴熟地运用 绑定（Binding）、容器（Containment）、组合（Grouping）与框架（Framing） 等核心机制来绘制出结构清晰、布局优美、信息传达高效的架构图和流程图。 证据：`prompt/excalidraw-prompt.md`\n- **Role:**（documentation）：- 背景 : 超过10年的前端开发经验，尤其在Chrome/Firefox扩展开发、Content Scripts编写和DOM性能优化方面有深厚造诣。 证据：`prompt/modify-web.md`\n- **Property Panel UI 重构计划**（documentation）：当前属性面板的 UI 实现与设计稿 attr-ui.html 存在较大差异。本文档详细规划了重构任务，按照优先级从高到低排列，目标是让属性面板的视觉效果和交互体验与设计稿一致。 证据：`app/chrome-extension/entrypoints/web-editor-v2/attr-ui-refactor.md`\n- **WASM SIMD 构建指南**（documentation）：bash 安装 Rust curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs sh 证据：`packages/wasm-simd/BUILD.md`\n- **.Prettierrc**（structured_config）：{ \"semi\": true, \"singleQuote\": true, \"tabWidth\": 2, \"printWidth\": 100, \"endOfLine\": \"auto\", \"proseWrap\": \"preserve\", \"htmlWhitespaceSensitivity\": \"strict\" } 证据：`.prettierrc.json`\n- **Messages**（structured_config）：{ \"extensionName\": { \"message\": \"chrome-mcp-server\", \"description\": \"Erweiterungsname\" }, \"extensionDescription\": { \"message\": \"Stellt Browser-Funktionen mit Ihrem eigenen Chrome zur Verfügung\", \"description\": \"Erweiterungsbeschreibung\" }, \"nativeServerConfigLabel\": { \"message\": \"Native Server-Konfiguration\", \"description\": \"Hauptabschnittstitel für Native Server-Einstellungen\" }, \"semanticEngineLabel\": { \"message\": \"Semantische Engine\", \"description\": \"Hauptabschnittstitel für semantische Engine\" }, \"embeddingModelLabel\": { \"message\": \"Embedding-Modell\", \"description\": \"Hauptabschnittstitel für Modellauswahl\" }, \"indexDataManagementLabel\": { \"message\": \"Index-Datenverwaltung\", \"description… 证据：`app/chrome-extension/_locales/de/messages.json`\n- **Messages**（structured_config）：{ \"extensionName\": { \"message\": \"chrome-mcp-server\", \"description\": \"Extension name\" }, \"extensionDescription\": { \"message\": \"Exposes browser capabilities with your own chrome\", \"description\": \"Extension description\" }, \"nativeServerConfigLabel\": { \"message\": \"Native Server Configuration\", \"description\": \"Main section header for native server settings\" }, \"semanticEngineLabel\": { \"message\": \"Semantic Engine\", \"description\": \"Main section header for semantic engine\" }, \"embeddingModelLabel\": { \"message\": \"Embedding Model\", \"description\": \"Main section header for model selection\" }, \"indexDataManagementLabel\": { \"message\": \"Index Data Management\", \"description\": \"Main section header for data… 证据：`app/chrome-extension/_locales/en/messages.json`\n- **Messages**（structured_config）：{ \"extensionName\": { \"message\": \"Chrome MCPサーバー\" }, \"extensionDescription\": { \"message\": \"自身のChromeブラウザの機能を外部に公開します\" }, \"nativeServerConfigLabel\": { \"message\": \"ネイティブサーバー設定\" }, \"semanticEngineLabel\": { \"message\": \"セマンティックエンジン\" }, \"embeddingModelLabel\": { \"message\": \"埋め込みモデル\" }, \"indexDataManagementLabel\": { \"message\": \"インデックスデータ管理\" }, \"modelCacheManagementLabel\": { \"message\": \"モデルキャッシュ管理\" }, \"statusLabel\": { \"message\": \"ステータス\" }, \"runningStatusLabel\": { \"message\": \"実行ステータス\" }, \"connectionStatusLabel\": { \"message\": \"接続ステータス\" }, \"lastUpdatedLabel\": { \"message\": \"最終更新:\" }, \"connectButton\": { \"message\": \"接続\" }, \"disconnectButton\": { \"message\": \"切断\" }, \"connectingStatus\": { \"message\": \"接続中...\" }… 证据：`app/chrome-extension/_locales/ja/messages.json`\n- **Messages**（structured_config）：{ \"extensionName\": { \"message\": \"chrome-mcp-server\", \"description\": \"확장 프로그램 이름\" }, \"extensionDescription\": { \"message\": \"크롬 브라우저와 연동하여 브라우저 기능을 제어하는 MCP 서버입니다.\", \"description\": \"확장 프로그램 설명\" }, \"nativeServerConfigLabel\": { \"message\": \"네이티브 서버 설정\", \"description\": \"네이티브 서버 설정의 주 섹션 제목\" }, \"semanticEngineLabel\": { \"message\": \"시맨틱 엔진\", \"description\": \"시맨틱 엔진의 주 섹션 제목\" }, \"embeddingModelLabel\": { \"message\": \"임베딩 모델\", \"description\": \"모델 선택의 주 섹션 제목\" }, \"indexDataManagementLabel\": { \"message\": \"인덱스 데이터 관리\", \"description\": \"데이터 관리의 주 섹션 제목\" }, \"modelCacheManagementLabel\": { \"message\": \"모델 캐시 관리\", \"description\": \"캐시 관리의 주 섹션 제목\" }, \"statusLabel\": { \"message\": \"상태\", \"description\": \"일반 상태 레이블\" }, \"run… 证据：`app/chrome-extension/_locales/ko/messages.json`\n- **Messages**（structured_config）：{ \"extensionName\": { \"message\": \"chrome-mcp-server\", \"description\": \"扩展名称\" }, \"extensionDescription\": { \"message\": \"使用你自己的 Chrome 浏览器暴露浏览器功能\", \"description\": \"扩展描述\" }, \"nativeServerConfigLabel\": { \"message\": \"Native Server 配置\", \"description\": \"本地服务器设置的主要节标题\" }, \"semanticEngineLabel\": { \"message\": \"语义引擎\", \"description\": \"语义引擎的主要节标题\" }, \"embeddingModelLabel\": { \"message\": \"Embedding模型\", \"description\": \"模型选择的主要节标题\" }, \"indexDataManagementLabel\": { \"message\": \"索引数据管理\", \"description\": \"数据管理的主要节标题\" }, \"modelCacheManagementLabel\": { \"message\": \"模型缓存管理\", \"description\": \"缓存管理的主要节标题\" }, \"statusLabel\": { \"message\": \"状态\", \"description\": \"通用状态标签\" }, \"runningStatusLabel\": { \"message\": \"运行状态\", \"descriptio… 证据：`app/chrome-extension/_locales/zh_CN/messages.json`\n- **Messages**（structured_config）：{ \"extensionName\": { \"message\": \"chrome-mcp-server\", \"description\": \"擴充功能名稱\" }, \"extensionDescription\": { \"message\": \"使用您自己的 Chrome 瀏覽器暴露瀏覽器功能\", \"description\": \"擴充功能描述\" }, \"nativeServerConfigLabel\": { \"message\": \"原生伺服器設定\", \"description\": \"本機伺服器設定的主要區段標題\" }, \"semanticEngineLabel\": { \"message\": \"語意引擎\", \"description\": \"語意引擎的主要區段標題\" }, \"embeddingModelLabel\": { \"message\": \"Embedding 模型\", \"description\": \"模型選擇的主要區段標題\" }, \"indexDataManagementLabel\": { \"message\": \"索引資料管理\", \"description\": \"資料管理主要區段標題\" }, \"modelCacheManagementLabel\": { \"message\": \"模型快取管理\", \"description\": \"快取管理主要區段標題\" }, \"statusLabel\": { \"message\": \"狀態\", \"description\": \"通用狀態標籤\" }, \"runningStatusLabel\": { \"message\": \"執行狀態\", \"description… 证据：`app/chrome-extension/_locales/zh_TW/messages.json`\n- **Tsconfig**（structured_config）：{ \"extends\": \"./.wxt/tsconfig.json\" } 证据：`app/chrome-extension/tsconfig.json`\n- **Stdio Config**（structured_config）：{ \"url\": \"http://127.0.0.1:12306/mcp\" } 证据：`app/native-server/src/mcp/stdio-config.json`\n- **Tsconfig**（structured_config）：{ \"compilerOptions\": { \"target\": \"ES2018\", \"module\": \"NodeNext\", \"moduleResolution\": \"NodeNext\", \"lib\": \"ES2018\", \"DOM\" , \"outDir\": \"dist\", \"rootDir\": \"src\", \"strict\": true, \"esModuleInterop\": true, \"forceConsistentCasingInFileNames\": true, \"skipLibCheck\": true, \"declaration\": true, \"sourceMap\": true, \"resolveJsonModule\": true, \"baseUrl\": \".\", \"paths\": { \"chrome-devtools-frontend/ \": \"src/shims/devtools.d.ts\" } }, \"include\": \"src/ / \" , \"exclude\": \"node modules\", \"dist\", \" / .spec.ts\", \" / .test.ts\" } 证据：`app/native-server/tsconfig.json`\n- **Tsconfig**（structured_config）：{ \"compilerOptions\": { \"target\": \"ES2020\", \"module\": \"NodeNext\", \"moduleResolution\": \"NodeNext\", \"esModuleInterop\": true, \"declaration\": true, \"outDir\": \"./dist\", \"strict\": true, \"skipLibCheck\": true }, \"include\": \"src/ / \" , \"exclude\": \"node modules\", \"dist\" } 证据：`packages/shared/tsconfig.json`\n- **.gitattributes**（source_file）：.onnx filter=lfs diff=lfs merge=lfs -text 证据：`.gitattributes`\n- **Logs**（source_file）：Logs logs .log npm-debug.log yarn-debug.log yarn-error.log pnpm-debug.log lerna-debug.log 证据：`.gitignore`\n- **Commit Msg**（source_file）：npx --no -- commitlint --edit \"$1\" 证据：`.husky/commit-msg`\n- **Pre Commit**（source_file）：npx lint-staged 证据：`.husky/pre-commit`\n- **构建输出目录**（source_file）：编辑器配置 .vscode !.vscode/extensions.json .idea 证据：`.prettierignore`\n- **Commitlint.Config**（source_file）：module.exports = { extends: '@commitlint/config-conventional' , }; 证据：`commitlint.config.cjs`\n- **Eslint.Config**（source_file）：import globals from 'globals'; import js from '@eslint/js'; import tseslint from 'typescript-eslint'; import eslintConfigPrettier from 'eslint-config-prettier'; 证据：`eslint.config.js`\n- **Pnpm Workspace**（source_file）：packages: - 'app/ ' - 'packages/ ' 证据：`pnpm-workspace.yaml`\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`docs/CONTRIBUTING.md`, `README.md`, `releases/README.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`docs/CONTRIBUTING.md`, `README.md`, `releases/README.md`\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- **Introduction to Chrome MCP Server**：importance `high`\n  - source_paths: README.md, app/chrome-extension/manifest.json\n- **Quick Start Guide**：importance `high`\n  - source_paths: app/chrome-extension/README.md, app/native-server/README.md\n- **System Architecture**：importance `high`\n  - source_paths: docs/ARCHITECTURE.md, app/chrome-extension/common/message-types.ts, app/native-server/src/index.ts\n- **Communication Protocols**：importance `high`\n  - source_paths: app/chrome-extension/entrypoints/background/native-host.ts, app/native-server/src/native-messaging-host.ts, app/native-server/src/mcp/mcp-server-stdio.ts\n- **Chrome Extension Structure**：importance `high`\n  - source_paths: app/chrome-extension/entrypoints/background/index.ts, app/chrome-extension/entrypoints/content.ts, app/chrome-extension/wxt.config.ts, app/chrome-extension/package.json\n- **Browser Tools and APIs**：importance `high`\n  - source_paths: docs/TOOLS.md, app/chrome-extension/entrypoints/background/tools/browser/index.ts, app/chrome-extension/entrypoints/background/tools/browser/computer.ts, app/chrome-extension/shared/tools.ts\n- **Record and Replay Engine**：importance `medium`\n  - source_paths: app/chrome-extension/entrypoints/background/record-replay/index.ts, app/chrome-extension/entrypoints/background/record-replay-v3/index.ts, app/chrome-extension/entrypoints/background/record-replay/flow-runner.ts, app/chrome-extension/entrypoints/background/record-replay/recording/recorder-manager.ts\n- **MCP Server Implementation**：importance `high`\n  - source_paths: app/native-server/src/mcp/mcp-server.ts, app/native-server/src/mcp/register-tools.ts, app/native-server/src/server/index.ts, app/native-server/src/mcp/mcp-server-stdio.ts\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `f48e71751e00bc09725c7e173423cff4f2ccd12a`\n- inspected_files: `pnpm-lock.yaml`, `package.json`, `README.md`, `docs/ISSUE.md`, `docs/VisualEditor.md`, `docs/TROUBLESHOOTING.md`, `docs/mcp-cli-config.md`, `docs/ARCHITECTURE.md`, `docs/TOOLS.md`, `docs/ARCHITECTURE_zh.md`, `docs/TROUBLESHOOTING_zh.md`, `docs/WINDOWS_INSTALL_zh.md`, `docs/CONTRIBUTING.md`, `docs/VisualEditor_zh.md`, `docs/CONTRIBUTING_zh.md`, `docs/TOOLS_zh.md`, `docs/CHANGELOG.md`, `packages/wasm-simd/Cargo.toml`, `packages/wasm-simd/package.json`, `packages/wasm-simd/README.md`\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: 来源证据：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_ba76885913a744f0832665f5c62d0f1d | https://github.com/hangwin/mcp-chrome/issues/321 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 来源证据：Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed to connect to MCP server)\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed to connect to MCP server)\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_4ac5f778b292489482bfdb7953190f96 | https://github.com/hangwin/mcp-chrome/issues/319 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 来源证据：Codex CLI setup guide still points to ~/.codex/config.json and a port-only flow Codex does not pick up\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Codex CLI setup guide still points to ~/.codex/config.json and a port-only flow Codex does not pick up\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_559f34b86ade48e598dac510e9341b9e | https://github.com/hangwin/mcp-chrome/issues/339 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 来源证据：[Feature] Profile-aware bridge — multi-Chrome-profile support without port collision\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature] Profile-aware bridge — multi-Chrome-profile support without port collision\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_93bfb3c85fbc4c0a8134e7159ddf4511 | https://github.com/hangwin/mcp-chrome/issues/347 | 来源类型 github_issue 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 来源证据：mcp-chrome-bridge 无法使用\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：mcp-chrome-bridge 无法使用\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_5f19fb6526174af2abe5c1eab67e25ff | https://github.com/hangwin/mcp-chrome/issues/333 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 来源证据：🐛 Status indicator stuck on yellow - Service shows as \"not started\" after connection\n\n- Trigger: GitHub 社区证据显示该项目存在一个安装相关的待验证问题：🐛 Status indicator stuck on yellow - Service shows as \"not started\" after connection\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能影响升级、迁移或版本选择。\n- Evidence: community_evidence:github | cevd_2b32536c95a7456788ba78e1fc705116 | https://github.com/hangwin/mcp-chrome/issues/342 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 可能修改宿主 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:998796026 | https://github.com/hangwin/mcp-chrome | host_targets=mcp_host, claude\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 能力判断依赖假设\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:998796026 | https://github.com/hangwin/mcp-chrome | README/documentation is current enough for a first validation pass.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 9: 来源证据：v0.0.6\n\n- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.0.6\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_035dffafcbe64f4ea112f20258430e71 | https://github.com/hangwin/mcp-chrome/releases/tag/v0.0.6 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 10: 来源证据：[Feature/Bug] Multi-client MCP support — second Claude Code session kills first via shared MCP Server singleton\n\n- Trigger: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[Feature/Bug] Multi-client MCP support — second Claude Code session kills first via shared MCP Server singleton\n- Host AI rule: 来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_4d4eaf47bd284105af5632bbe220b628 | https://github.com/hangwin/mcp-chrome/issues/345 | 来源类型 github_issue 暴露的待验证使用条件。\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项目：hangwin/mcp-chrome\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\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 来源证据：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint（high）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed to connect to MCP server)（high）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：Codex CLI setup guide still points to ~/.codex/config.json and a port-only flow Codex does not pick up（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：[Feature] Profile-aware bridge — multi-Chrome-profile support without port collision（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 来源证据：mcp-chrome-bridge 无法使用（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/hangwin/mcp-chrome 项目说明书\n\n生成时间：2026-05-16 01:25:43 UTC\n\n## 目录\n\n- [Introduction to Chrome MCP Server](#page-introduction)\n- [Quick Start Guide](#page-quickstart)\n- [System Architecture](#page-architecture)\n- [Communication Protocols](#page-communication)\n- [Chrome Extension Structure](#page-extension-structure)\n- [Browser Tools and APIs](#page-browser-tools)\n- [Record and Replay Engine](#page-record-replay)\n- [MCP Server Implementation](#page-mcp-server)\n- [AI Agent Engines](#page-agent-engines)\n- [Storage and Data Management](#page-storage)\n\n<a id='page-introduction'></a>\n\n## Introduction to Chrome MCP Server\n\n### 相关页面\n\n相关主题：[System Architecture](#page-architecture)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/hangwin/mcp-chrome/blob/main/README.md)\n- [app/native-server/src/scripts/utils.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n- [app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n- [app/native-server/src/scripts/browser-config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/browser-config.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/common.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n- [app/chrome-extension/utils/content-indexer.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n- [packages/wasm-simd/package.json](https://github.com/hangwin/mcp-chrome/blob/main/packages/wasm-simd/package.json)\n</details>\n\n# Introduction to Chrome MCP Server\n\nChrome MCP Server is a Model Context Protocol (MCP) implementation that bridges AI assistants with Chrome/Chromium browsers, enabling AI-powered browser automation, content analysis, and control through a comprehensive set of tools. The project consists of two main components: a Chrome extension that runs in the browser and a native server that communicates with AI clients via the MCP protocol.\n\n## Overview and Purpose\n\nChrome MCP Server provides AI assistants with the ability to interact with web pages, manage browser tabs, capture screenshots, monitor network traffic, and perform automated actions. By exposing browser functionality as MCP tools, developers can create AI agents that can browse the web, fill forms, click elements, search history, and analyze page content.\n\n资料来源：[README.md:1-20](https://github.com/hangwin/mcp-chrome/blob/main/README.md)\n\n## System Architecture\n\nThe Chrome MCP Server architecture consists of multiple interconnected components that work together to provide browser automation capabilities.\n\n### Component Overview\n\n```mermaid\ngraph TD\n    A[\"AI Client<br/>(Claude, etc.)\"] --> B[\"MCP Chrome Bridge<br/>(mcp-chrome-bridge)\"]\n    B --> C[\"Native Server<br/>(Node.js)\"]\n    C <--> D[\"Chrome Extension<br/>(WXT-based)\"]\n    D --> E[\"Chrome Browser\"]\n    F[\"Web Content Scripts\"] --> D\n    G[\"Injected Scripts\"] --> E\n```\n\n### Native Messaging Host Configuration\n\nThe native server registers itself as a Native Messaging Host with the operating system, enabling secure communication between native applications and Chrome extensions.\n\n| Platform | User-Level Path | System-Level Path |\n|----------|-----------------|-------------------|\n| Windows | `%APPDATA%\\Google\\Chrome\\NativeMessagingHosts\\` | `%ProgramFiles%\\Google\\Chrome\\NativeMessagingHosts\\` |\n| macOS | `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/` | `/Library/Google/Chrome/NativeMessagingHosts/` |\n| Linux | `~/.config/google-chrome/NativeMessagingHosts/` | `/etc/opt/chrome/native-messaging-hosts/` |\n\n资料来源：[app/native-server/src/scripts/utils.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n\nThe `HOST_NAME` constant identifies the native messaging host configuration file, which Chrome reads to establish the connection with the native server.\n\n### Chrome Extension Structure\n\nThe Chrome extension is built using WXT, a modern build tool for Chrome extensions. The extension configuration includes security policies, content scripts, and web-accessible resources.\n\n```typescript\n// Key configuration from wxt.config.ts\nweb_accessible_resources: [\n  {\n    resources: [\n      '/models/*',      // ML models for semantic search\n      '/workers/*',     // Web Workers for background tasks\n      '/inject-scripts/*', // Scripts injected into web pages\n    ],\n    matches: ['<all_urls>'],\n  },\n]\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:1-30](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n## Tool Categories\n\nChrome MCP Server organizes its functionality into several tool categories, each targeting specific browser interaction needs.\n\n### Navigation and Tab Management\n\n| Tool | Purpose |\n|------|---------|\n| `chrome_navigate` | Navigate to URLs with viewport control |\n| `chrome_switch_tab` | Switch the current active tab |\n| `chrome_close_tabs` | Close specific tabs or windows |\n| `chrome_go_back_or_forward` | Browser navigation control |\n\nThese tools enable AI assistants to control the browser's navigation state and manage multiple tabs programmatically. The `chrome_close_tabs` function, for example, accepts URL patterns to match and close multiple tabs at once.\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/common.ts:1-80](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n\n### Content Interaction\n\n| Tool | Purpose |\n|------|---------|\n| `chrome_click_element` | Click elements using CSS selectors |\n| `chrome_fill_or_select` | Fill forms and select options |\n| `chrome_keyboard` | Simulate keyboard input and shortcuts |\n| `chrome_inject_script` | Inject content scripts into web pages |\n| `chrome_send_command_to_inject_script` | Send commands to injected content scripts |\n\nThe interaction tools support complex user interaction scenarios by translating high-level commands into browser automation actions.\n\n### Network Monitoring\n\n| Tool | Purpose |\n|------|---------|\n| `chrome_network_capture_start/stop` | Capture network requests via webRequest API |\n| `chrome_network_debugger_start/stop` | Debugger API with response bodies |\n| `chrome_network_request` | Send custom HTTP requests |\n\n资料来源：[README.md:40-55](https://github.com/hangwin/mcp-chrome/blob/main/README.md)\n\n### Content Analysis\n\n| Tool | Purpose |\n|------|---------|\n| `search_tabs_content` | AI-powered semantic search across browser tabs |\n| `chrome_get_web_content` | Extract HTML/text content from pages |\n| `chrome_get_interactive_elements` | Find clickable elements |\n| `chrome_console` | Capture and retrieve console output |\n\nThe content analysis tools leverage semantic search capabilities powered by WebAssembly-optimized math functions for cosine similarity and vector operations.\n\n资料来源：[packages/wasm-simd/package.json:1-30](https://github.com/hangwin/mcp-chrome/blob/main/packages/wasm-simd/package.json)\n\n### Screenshots\n\n| Tool | Purpose |\n|------|---------|\n| `chrome_screenshot` | Advanced screenshot capture with element targeting, full-page support, and custom dimensions |\n\n### Data Management\n\n| Tool | Purpose |\n|------|---------|\n| `chrome_history` | Search browser history with time filters |\n| `chrome_bookmark_search` | Find bookmarks by keywords |\n| `chrome_bookmark_add` | Add new bookmarks with folder support |\n| `chrome_bookmark_delete` | Delete bookmarks |\n\n## Content Indexing System\n\nThe Chrome extension includes a sophisticated content indexing system that enables semantic search across open browser tabs.\n\n```mermaid\ngraph LR\n    A[\"Tab Load Complete\"] --> B[\"ContentIndexer\"]\n    B --> C{\"URL Excluded?\"}\n    C -->|Yes| D[\"Skip\"]\n    C -->|No| E[\"Execute web-fetcher-helper.js\"]\n    E --> F[\"Extract Metadata\"]\n    F --> G[\"Index Content\"]\n    G --> H[\"Searchable Index\"]\n```\n\nThe indexer automatically processes tabs when they complete loading, extracting text content, titles, and metadata. It excludes internal Chrome URLs, extensions, and local files.\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:1-60](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n\n### URL Exclusion Patterns\n\nThe content indexer skips indexing for the following URL patterns:\n\n| Pattern | Description |\n|---------|-------------|\n| `chrome://*` | Internal Chrome pages |\n| `chrome-extension://*` | Extension pages |\n| `edge://*` | Microsoft Edge pages |\n| `about:*` | About pages |\n| `moz-extension://*` | Firefox extension pages |\n| `file://*` | Local files |\n\n## Web Fetcher Tool\n\nThe `chrome_get_web_content` tool provides flexible content extraction from web pages.\n\n```typescript\ninterface WebFetcherToolParams {\n  htmlContent?: boolean;  // Get visible HTML content\n  textContent?: boolean;  // Get visible text content\n  url?: string;           // Optional URL to fetch\n  selector?: string;      // CSS selector for specific elements\n  tabId?: number;         // Target existing tab\n  background?: boolean;   // Don't activate/focus tab\n  windowId?: number;      // Target window\n}\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/web-fetcher.ts:1-30](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/web-fetcher.ts)\n\n### Metadata Extraction\n\nThe injected web fetcher script extracts comprehensive metadata from web pages:\n\n| Field | Source Priority |\n|-------|-----------------|\n| title | JSON-LD → Open Graph → Twitter Cards |\n| byline | JSON-LD → Meta tags |\n| excerpt | JSON-LD → Open Graph → Twitter |\n| siteName | Open Graph |\n| publishedTime | JSON-LD → Article tags |\n\nAll values are automatically unescaped from HTML entities to ensure proper formatting.\n\n资料来源：[app/chrome-extension/inject-scripts/web-fetcher-helper.js:1-100](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/inject-scripts/web-fetcher-helper.js)\n\n## Record and Replay System\n\nThe extension includes a record-replay engine for automating browser interactions. The wait policies ensure that automated actions wait for appropriate page states before proceeding.\n\n```typescript\n// Wait policies monitor various browser events\nchrome.webNavigation.onCommitted  // Page navigation committed\nchrome.webNavigation.onCompleted  // Page fully loaded\nchrome.tabs.onUpdated             // Tab state changes\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts)\n\n## Security Configuration\n\nThe extension implements a multi-layered security model:\n\n| Environment | COEP | COOP | CSP |\n|-------------|------|------|-----|\n| Development | Disabled (WXT default) | Disabled (WXT default) | Relaxed for HMR |\n| Production | `require-corp` | `same-origin` | Strict |\n\nThe Content Security Policy for production enforces:\n- Scripts: `'self' 'wasm-unsafe-eval'`\n- Objects: `'self'`\n- Styles: `'self' 'unsafe-inline'`\n- Images: `'self' data: blob:`\n\n资料来源：[app/chrome-extension/wxt.config.ts:25-40](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n## Browser Configuration Support\n\nThe native server supports multiple browsers and platforms:\n\n| Browser | Windows | macOS | Linux |\n|---------|---------|-------|-------|\n| Chrome | ✅ | ✅ | ✅ |\n| Chromium | ✅ | ✅ | ✅ |\n\nThe configuration system automatically detects the platform and selects appropriate paths for native messaging host manifests.\n\n资料来源：[app/native-server/src/scripts/browser-config.ts:1-100](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/browser-config.ts)\n\n## Installation Flow\n\n```mermaid\ngraph TD\n    A[\"Install mcp-chrome-bridge\"] --> B{\"pnpm config set enable-pre-post-scripts\"}\n    B -->|pnpm| C[\"Auto-register native host\"]\n    B -->|npm| C\n    C --> D[\"Load Chrome Extension\"]\n    D --> E[\"Click Extension Icon\"]\n    E --> F[\"Connect to Bridge\"]\n    F --> G[\"Get MCP Configuration\"]\n```\n\n### Prerequisites\n\n- Node.js >= 20.0.0\n- pnpm/npm\n- Chrome/Chromium browser\n\n### Registration Methods\n\n**Automatic (pnpm):**\n```bash\npnpm config set enable-pre-post-scripts true\npnpm install -g mcp-chrome-bridge\n```\n\n**Manual:**\n```bash\nnpm install -g mcp-chrome-bridge\nmcp-chrome-bridge register\n```\n\n资料来源：[README.md:60-100](https://github.com/hangwin/mcp-chrome/blob/main/README.md)\n\n## Future Roadmap\n\nThe project has planned several enhancements:\n\n| Feature | Status |\n|---------|--------|\n| Authentication | Planned |\n| Recording and Playback | Planned |\n| Workflow Automation | Planned |\n| Firefox Extension | Planned |\n\n## Project Structure\n\n```\nmcp-chrome/\n├── app/\n│   ├── chrome-extension/     # WXT-based Chrome extension\n│   │   ├── entrypoints/      # Extension entry points (background, sidepanel, etc.)\n│   │   ├── inject-scripts/   # Scripts injected into web pages\n│   │   └── utils/            # Utility modules\n│   └── native-server/        # Node.js MCP server\n│       └── src/\n│           ├── agent/        # AI agent integration\n│           └── scripts/      # Native messaging setup\n└── packages/\n    └── wasm-simd/           # WebAssembly SIMD math functions\n```\n\nThis structure enables clear separation between the browser extension (UI and web interaction), the native server (MCP protocol and AI integration), and shared packages (common utilities and optimized algorithms).\n\n---\n\n<a id='page-quickstart'></a>\n\n## Quick Start Guide\n\n### 相关页面\n\n相关主题：[Communication Protocols](#page-communication)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/hangwin/mcp-chrome/blob/main/README.md)\n- [app/chrome-extension/README.md](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/README.md)\n- [app/native-server/README.md](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/README.md)\n- [app/native-server/install.md](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/install.md)\n- [app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n- [app/chrome-extension/entrypoints/sidepanel/composables/useAgentThreads.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/sidepanel/composables/useAgentThreads.ts)\n</details>\n\n# Quick Start Guide\n\n## Overview\n\nThe **mcp-chrome** project provides a Model Context Protocol (MCP) server that enables AI assistants to control and interact with Chrome browser instances. This integration allows AI-powered automation of web browsing tasks through a comprehensive set of tools for navigation, interaction, content extraction, and network monitoring.\n\nThe project consists of two primary components:\n\n| Component | Location | Purpose |\n|-----------|----------|---------|\n| Chrome Extension | `app/chrome-extension/` | Handles browser-level operations via Chrome Extension APIs |\n| Native Server | `app/native-server/` | Bridges MCP clients (Claude Desktop, Cursor, etc.) with the extension |\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[MCP Client<br/>Claude Desktop / Cursor] -->|MCP Protocol| B[Native Server<br/>mcp-chrome-bridge]\n    B -->|Chrome Native Messaging| C[Chrome Extension<br/>Background Script]\n    C -->|Chrome APIs| D[Browser Tabs & Content]\n    E[Content Scripts] -->|Injection| D\n    C -->|scripting.executeScript| E\n```\n\n## Prerequisites\n\nBefore starting, ensure the following requirements are met:\n\n| Requirement | Version/Details |\n|-------------|-----------------|\n| Chrome/Chromium Browser | Version 88+ |\n| Node.js | v18+ |\n| npm | v8+ |\n| MCP Client | Claude Desktop, Cursor, or compatible |\n\n## Installation Steps\n\n### 1. Chrome Extension Installation\n\nThe Chrome extension must be loaded in developer mode:\n\n1. Open Chrome and navigate to `chrome://extensions/`\n2. Enable **Developer mode** (toggle in top-right corner)\n3. Click **Load unpacked**\n4. Select the `app/chrome-extension/` directory from the repository\n\n资料来源：[app/chrome-extension/README.md]()\n\nThe extension provides the following entry points:\n\n| Entry Point | File | Purpose |\n|-------------|------|---------|\n| Side Panel | `entrypoints/sidepanel/` | Main AI chat interface |\n| Popup | `entrypoints/popup/` | Quick access toolbar popup |\n| Options | `entrypoints/options/` | Extension settings |\n| Welcome | `entrypoints/welcome/` | Onboarding page |\n| Builder | `entrypoints/builder/` | Workflow editor |\n\n### 2. Native Server Setup\n\nThe native server acts as the bridge between MCP clients and the Chrome extension.\n\n#### Installation via npm\n\n```bash\nnpm install -g @mcp-chrome/native-server\n```\n\n#### Manual Installation\n\nFor manual installation, use the registry command:\n\n```bash\n# User-level installation (default)\nmcp-chrome-bridge register\n\n# System-level installation (requires admin)\nmcp-chrome-bridge register --system\n```\n\n资料来源：[app/native-server/install.md]()\n\n### 3. Registry Configuration\n\nOn **Windows**, the native messaging host must be registered in the Windows Registry:\n\n```\nHKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\com.mcp.chrome\n```\n\nOr for system-wide installation:\n\n```\nHKLM\\Software\\Google\\Chrome\\NativeMessagingHosts\\com.mcp.chrome\n```\n\n资料来源：[app/native-server/install.md]()\n\n## MCP Client Configuration\n\n### Claude Desktop\n\nAdd the following to your Claude Desktop configuration file:\n\n| OS | Config Location |\n|----|-----------------|\n| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |\n| Windows | `%APPDATA%\\Claude\\claude_desktop_config.json` |\n\n```json\n{\n  \"mcpServers\": {\n    \"chrome\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@mcp-chrome/native-server\"]\n    }\n  }\n}\n```\n\n资料来源：[app/native-server/README.md]()\n\n## Available MCP Tools\n\n### Browser Navigation (4 tools)\n\n| Tool | Description |\n|------|-------------|\n| `chrome_navigate` | Navigate to URL or perform search |\n| `chrome_go_back_or_forward` | Browser history navigation |\n| `chrome_reload` | Reload current page |\n| `chrome_control_viewport` | Zoom and scroll control |\n\n### Tab Management (6 tools)\n\n| Tool | Description |\n|------|-------------|\n| `chrome_new_tab` | Open new tab with optional URL |\n| `chrome_switch_tab` | Switch to specific tab |\n| `chrome_close_tabs` | Close tabs by URL pattern or tab IDs |\n| `chrome_get_tabs` | List all open tabs |\n| `chrome_duplicate_tab` | Duplicate current tab |\n\n资料来源：[README.md]()\n\n### Interaction (3 tools)\n\n| Tool | Parameters | Description |\n|------|------------|-------------|\n| `chrome_click_element` | `selector` (CSS) | Click elements using CSS selectors |\n| `chrome_fill_or_select` | `selector`, `value` | Fill forms and select options |\n| `chrome_keyboard` | `text`, `shortcut` | Simulate keyboard input |\n\n### Content Analysis (4 tools)\n\n| Tool | Description |\n|------|-------------|\n| `chrome_get_web_content` | Extract HTML/text content from pages |\n| `chrome_get_interactive_elements` | Find clickable elements |\n| `chrome_console` | Capture browser console output |\n| `search_tabs_content` | AI-powered semantic search across tabs |\n\n### Screenshot & Visual (1 tool)\n\n| Tool | Features |\n|------|----------|\n| `chrome_screenshot` | Element targeting, full-page capture, custom dimensions |\n\n### Network Monitoring (4 tools)\n\n| Tool | Description |\n|------|-------------|\n| `chrome_network_capture_start/stop` | webRequest API network capture |\n| `chrome_network_debugger_start/stop` | Debugger API with response bodies |\n| `chrome_network_request` | Send custom HTTP requests |\n\n### Data Management (5 tools)\n\n| Tool | Description |\n|------|-------------|\n| `chrome_history` | Search browser history with time filters |\n| `chrome_bookmark_search` | Find bookmarks by keywords |\n| `chrome_bookmark_add` | Add bookmarks with folder support |\n| `chrome_bookmark_delete` | Delete bookmarks |\n\n资料来源：[README.md]()\n\n## Content Script Injection\n\nThe extension uses content scripts for web page interaction. Scripts are injected via the Chrome scripting API:\n\n```typescript\nawait chrome.scripting.executeScript({\n  target: { tabId },\n  files: ['inject-scripts/web-fetcher-helper.js'],\n});\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts]()\n\nWeb-accessible resources are configured in `wxt.config.ts`:\n\n| Resource Path | Purpose |\n|---------------|---------|\n| `/models/*` | Local AI models |\n| `/workers/*` | Web workers |\n| `/inject-scripts/*` | Helper scripts for content scripts |\n\n```typescript\nweb_accessible_resources: [\n  {\n    resources: [\n      '/models/*',\n      '/workers/*',\n      '/inject-scripts/*',\n    ],\n    matches: ['<all_urls>'],\n  },\n]\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts]()\n\n## Security Configuration\n\nThe extension implements Content Security Policy (CSP) for production builds:\n\n```typescript\ncontent_security_policy: {\n  extension_pages:\n    \"script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:;\",\n}\n```\n\nNote: Security policies are disabled in development mode to allow Vite dev server resource loading.\n\n资料来源：[app/chrome-extension/wxt.config.ts]()\n\n## URL Exclusion Patterns\n\nThe content indexer automatically excludes internal browser URLs:\n\n```typescript\nconst excludePatterns = [\n  /^chrome:\\/\\//,\n  /^chrome-extension:\\/\\//,\n  /^edge:\\/\\//,\n  /^about:/,\n  /^moz-extension:\\/\\//,\n  /^file:\\/\\//,\n];\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts]()\n\n## Agent Thread Visualization\n\nThe sidepanel provides visual representation of agent activities:\n\n```typescript\n// Tool kinds tracked in useAgentThreads\nconst toolKinds = ['run', 'grep', 'edit', 'read', 'search'] as const;\n```\n\nEach tool execution is categorized and displayed with:\n\n| Property | Description |\n|----------|-------------|\n| `kind` | Tool category (edit, run, grep, etc.) |\n| `title` | File name or command |\n| `details` | Output content |\n| `severity` | Error, success, or info status |\n| `phase` | Execution phase (input, output, result) |\n\n资料来源：[app/chrome-extension/entrypoints/sidepanel/composables/useAgentThreads.ts]()\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue | Solution |\n|-------|----------|\n| Extension not responding | Reload the extension at `chrome://extensions/` |\n| Native messaging fails | Verify registry entries on Windows |\n| Permission denied | Check that extension has required permissions |\n| Tab access fails | Ensure tab ID is valid and accessible |\n\n资料来源：[app/native-server/install.md]()\n\n### Verbose Logging\n\nEnable verbose logging for debugging:\n\n```bash\nmcp-chrome-bridge --verbose\n```\n\n## Quick Usage Example\n\nOnce installed, you can interact with Chrome using natural language:\n\n```\nNavigate to github.com and search for mcp-chrome repositories\n```\n\nThis triggers the following workflow:\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant MCP\n    participant NativeServer\n    participant Extension\n    participant Chrome\n    \n    User->>MCP: \"Navigate to github.com...\"\n    MCP->>NativeServer: chrome_navigate\n    NativeServer->>Extension: chrome.tabs.update()\n    Extension->>Chrome: Navigate URL\n    Chrome-->>Extension: Page loaded\n    Extension-->>NativeServer: Success response\n    NativeServer-->>MCP: Result\n    MCP-->>User: Confirmation\n```\n\n## Next Steps\n\n- Explore the [Workflow Editor](builder) for advanced automation\n- Configure AI model settings in the [Options page](options)\n- Review [Content Analysis](content-analize) capabilities\n- Set up [Bookmark Management](#bookmarks) workflows\n\n---\n\n<a id='page-architecture'></a>\n\n## System Architecture\n\n### 相关页面\n\n相关主题：[System Architecture](#page-architecture), [Chrome Extension Structure](#page-extension-structure), [MCP Server Implementation](#page-mcp-server)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n- [app/chrome-extension/utils/content-indexer.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/common.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n- [app/native-server/src/scripts/browser-config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/browser-config.ts)\n- [app/native-server/src/scripts/utils.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n- [app/native-server/src/agent/session-service.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/session-service.ts)\n- [app/native-server/src/agent/engines/claude.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/engines/claude.ts)\n</details>\n\n# System Architecture\n\n## Overview\n\nmcp-chrome is a Model Context Protocol (MCP) server implementation that extends AI assistant capabilities to browser automation through a Chrome extension and native messaging host architecture. The system enables AI models to interact with web pages, control browser tabs, capture network traffic, and perform semantic search across browser content.\n\n## High-Level Architecture\n\nThe architecture consists of three primary layers:\n\n| Layer | Component | Responsibility |\n|-------|-----------|----------------|\n| Chrome Extension | Background Service Worker | Hosts MCP tools, manages tab state, handles browser API calls |\n| Native Server | Node.js Application | Manages browser configuration, handles native messaging, coordinates with AI engines |\n| AI Integration | Claude Engine / Codex Engine | Executes AI logic, processes tool requests, manages sessions |\n\n资料来源：[app/chrome-extension/wxt.config.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n## Extension Entrypoint Architecture\n\nThe Chrome extension uses multiple HTML entrypoints, each serving a specific purpose:\n\n```mermaid\ngraph TD\n    A[Chrome Extension] --> B[Background Service Worker]\n    A --> C[Popup]\n    A --> D[Side Panel]\n    A --> E[Options Page]\n    A --> F[Welcome Page]\n    A --> G[Builder]\n    A --> H[Offscreen Document]\n    \n    B --> I[MCP Tools]\n    B --> J[Tab Management]\n    B --> K[Content Indexer]\n    \n    C --> L[Quick Actions]\n    D --> M[Workflow Management]\n    E --> N[Userscripts Manager]\n```\n\n### Entrypoint Components\n\n| Entrypoint | File Path | Purpose |\n|------------|-----------|---------|\n| Background | `entrypoints/background/` | Service worker hosting all MCP tools |\n| Popup | `entrypoints/popup/` | Quick access to AI chat interface |\n| Side Panel | `entrypoints/sidepanel/` | Workflow management and agent threads |\n| Builder | `entrypoints/builder/` | Visual workflow editor |\n| Options | `entrypoints/options/` | Userscripts configuration |\n| Welcome | `entrypoints/welcome/` | Onboarding page |\n| Offscreen | `entrypoints/offscreen/` | Background document for long-running tasks |\n\n资料来源：[app/chrome-extension/entrypoints/popup/index.html:1-12](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/popup/index.html), [app/chrome-extension/entrypoints/sidepanel/index.html:1-12](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/sidepanel/index.html)\n\n## Native Messaging Architecture\n\n### Cross-Platform Manifest Configuration\n\nThe native server uses platform-specific manifest paths for Chrome Native Messaging, enabling secure communication between the native application and Chrome extension:\n\n```mermaid\ngraph TD\n    A[Native Server] --> B{Platform Detection}\n    B -->|win32| C[Windows Registry + JSON]\n    B -->|darwin| D[macOS plist]\n    B -->|linux| E[Linux JSON]\n    \n    C --> F[User Manifest]\n    C --> G[System Manifest]\n    D --> H[User Manifest]\n    D --> I[System Manifest]\n    E --> J[User Manifest]\n    E --> K[System Manifest]\n```\n\n**Manifest Path Locations by Platform:**\n\n| Platform | User-Level Path | System-Level Path |\n|----------|-----------------|-------------------|\n| Windows | `%APPDATA%\\Google\\Chrome\\NativeMessagingHosts\\` | `%ProgramFiles%\\Google\\Chrome\\NativeMessagingHosts\\` |\n| macOS | `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/` | `/Library/Google/Chrome/NativeMessagingHosts/` |\n| Linux | `~/.config/google-chrome/NativeMessagingHosts/` | `/etc/opt/chrome/native-messaging-hosts/` |\n\n资料来源：[app/native-server/src/scripts/browser-config.ts:1-100](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/browser-config.ts), [app/native-server/src/scripts/utils.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n\n### Browser Support Matrix\n\nThe native server supports multiple Chromium-based browsers:\n\n| Browser | Chrome | Chromium | Edge |\n|---------|--------|----------|------|\n| Windows Registry | `HKCU\\Software\\Google\\Chrome\\` | `HKCU\\Software\\Chromium\\` | Not configured |\n| System Registry | `HKLM\\Software\\Google\\Chrome\\` | `HKLM\\Software\\Chromium\\` | Not configured |\n\n## MCP Tool Architecture\n\n### Tool Categories\n\nThe extension exposes MCP tools organized into functional categories:\n\n```mermaid\ngraph LR\n    A[MCP Tools] --> B[Viewport & Navigation]\n    A --> C[Interaction]\n    A --> D[Data Management]\n    A --> E[Screenshots & Visual]\n    A --> F[Network Monitoring]\n    A --> G[Content Analysis]\n    \n    B --> B1[chrome_set_viewport]\n    B --> B2[chrome_switch_tab]\n    B --> B3[chrome_close_tabs]\n    B --> B4[chrome_go_back_or_forward]\n    \n    C --> C1[chrome_click_element]\n    C --> C2[chrome_fill_or_select]\n    C --> C3[chrome_keyboard]\n    \n    D --> D1[chrome_history]\n    D --> D2[chrome_bookmark_*]\n    \n    E --> E1[chrome_screenshot]\n    \n    F --> F1[chrome_network_*]\n    \n    G --> G1[search_tabs_content]\n    G --> G2[chrome_get_web_content]\n```\n\n### Tab Management Tools\n\nTabs can be queried and closed using URL pattern matching:\n\n```typescript\nconst tabs = await chrome.tabs.query({ url: urlPattern });\nawait chrome.tabs.remove(tabIdsToClose);\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/common.ts:1-80](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n\n### Dialog Handling\n\nThe extension can handle JavaScript dialogs using Chrome DevTools Protocol (CDP):\n\n```typescript\nawait cdpSessionManager.sendCommand(tabId, 'Page.handleJavaScriptDialog', {\n  accept: action === 'accept',\n  promptText: action === 'accept' ? promptText : undefined,\n});\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/dialog.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/dialog.ts)\n\n## Content Indexer System\n\nThe content indexer provides semantic search across open browser tabs:\n\n### Indexing Logic\n\n| Step | Action | Trigger |\n|------|--------|---------|\n| 1 | Detect tab update | `chrome.tabs.onUpdated` with `status === 'complete'` |\n| 2 | Check semantic engine readiness | 2-second delay to allow engine initialization |\n| 3 | Extract content | Execute `web-fetcher-helper.js` injection script |\n| 4 | Index content | Store in semantic engine for `search_tabs_content` |\n\n### URL Exclusion Patterns\n\nThe indexer automatically excludes internal Chrome URLs:\n\n```typescript\nconst excludePatterns = [\n  /^chrome:\\/\\//,\n  /^chrome-extension:\\/\\//,\n  /^edge:\\/\\//,\n  /^about:/,\n  /^moz-extension:\\/\\//,\n  /^file:\\/\\//,\n];\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:1-100](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n\n## Agent Session Management\n\n### Session Service Architecture\n\nThe native server manages AI agent sessions with structured metadata:\n\n```mermaid\ngraph TD\n    A[SessionService] --> B[ManagementInfo]\n    A --> C[AgentSessionPreviewMeta]\n    A --> D[Engine Configuration]\n    \n    B --> B1[models]\n    B --> B2[commands]\n    B --> B3[mcpServers]\n    B --> B4[plugins]\n    B --> B5[skills]\n    \n    D --> D1[ClaudeEngine]\n    D --> D2[CodexEngine]\n```\n\n### Session Interface\n\n```typescript\ninterface ManagementInfo {\n  models?: Array<{ value: string; displayName: string; description: string }>;\n  commands?: Array<{ name: string; description: string; argumentHint: string }>;\n  account?: { email?: string; organization?: string; subscriptionType?: string };\n  mcpServers?: Array<{ name: string; status: string }>;\n  tools?: string[];\n  agents?: string[];\n  plugins?: Array<{ name: string; path?: string }>;\n  skills?: string[];\n  model?: string;\n  permissionMode?: string;\n  cwd?: string;\n}\n```\n\n资料来源：[app/native-server/src/agent/session-service.ts:1-60](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/session-service.ts)\n\n## Claude Engine Integration\n\n### Tool Message Processing\n\nThe Claude engine handles streaming tool execution results:\n\n```mermaid\nsequenceDiagram\n    participant AI as Claude API\n    participant Engine as ClaudeEngine\n    participant Dispatch as Tool Dispatch\n    \n    AI->>Engine: content_block_start (tool_use)\n    Engine->>Dispatch: Register pending tool\n    AI->>Engine: content_block_delta (input_json_delta)\n    Engine->>Engine: Accumulate JSON parts\n    AI->>Engine: content_block_stop\n    Engine->>Engine: Parse accumulated JSON\n    Engine->>Dispatch: Execute tool with full input\n    Dispatch->>Engine: Result content\n    Engine->>AI: tool_result\n```\n\n### Tool Result Processing\n\n```typescript\nif (contentBlock.type === 'tool_result') {\n  const metadata = this.buildToolResultMetadata(contentBlock);\n  const content = this.extractToolResultContent(contentBlock);\n  const isError = contentBlock.is_error === true;\n  \n  dispatchToolMessage(\n    isError ? `Error: ${content || 'Tool execution failed'}` : content || 'Tool completed',\n    metadata,\n    'tool_result',\n    false\n  );\n}\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:1-100](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/engines/claude.ts)\n\n## Security Architecture\n\n### Content Security Policy\n\nThe extension implements strict CSP in production:\n\n| Policy | Value | Purpose |\n|--------|-------|---------|\n| script-src | `'self' 'wasm-unsafe-eval'` | Restrict script execution |\n| object-src | `'self'` | Limit object embedding |\n| style-src | `'self' 'unsafe-inline'` | Allow Vite-compiled styles |\n| img-src | `'self' data: blob:` | Permit data URIs for thumbnails |\n\n### Cross-Origin Policies\n\n| Policy | Value | Development | Production |\n|--------|-------|-------------|------------|\n| COOP | `same-origin` | Disabled | Enabled |\n| COEP | `require-corp` | Disabled | Enabled |\n\n资料来源：[app/chrome-extension/wxt.config.ts:20-35](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n### Web Accessible Resources\n\nThe extension exposes specific directories to content scripts:\n\n| Directory | Purpose |\n|-----------|---------|\n| `/models/*` | AI model files |\n| `/workers/*` | Web Worker scripts |\n| `/inject-scripts/*` | Content script helpers |\n\n## Record-Replay System\n\nThe background service includes a record-replay engine for browser automation testing:\n\n### Wait Policy\n\nThe `waitForNetworkIdle` function monitors browser events:\n\n| Event Type | Listener | Purpose |\n|------------|----------|---------|\n| `onCommitted` | webNavigation | Detect navigation commits |\n| `onCompleted` | webNavigation | Detect page load completion |\n| `onHistoryStateUpdated` | webNavigation (optional) | Detect SPA route changes |\n| `onUpdated` | tabs | Detect tab status changes |\n\n```typescript\nconst onUpdated = (updatedId: number, change: chrome.tabs.TabChangeInfo) => {\n  if (updatedId !== tabId) return;\n  if (change.status === 'loading') mark();\n  if (typeof change.url === 'string' && (!prevUrl || change.url !== prevUrl)) mark();\n};\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts:1-60](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts)\n\n## Data Flow Diagram\n\n```mermaid\ngraph LR\n    A[User] -->|Command| B[AI Assistant]\n    B -->|MCP Request| C[Native Server]\n    C -->|Native Messaging| D[Chrome Extension]\n    D -->|Chrome APIs| E[Browser]\n    E -->|Response| D\n    D -->|Tool Result| C\n    C -->|Stream| B\n    B -->|Response| A\n```\n\n## Extension Development Configuration\n\n### Keyboard Shortcuts\n\n| Shortcut | Windows/Linux | macOS | Action |\n|----------|---------------|-------|--------|\n| Quick Panel | `Alt+Shift+U` | `Cmd+Shift+U` | Toggle AI Chat |\n\n### Vite Plugin Stack\n\n| Plugin | Purpose |\n|--------|---------|\n| TailwindCSS v4 | Styling without PostCSS |\n| `@vitejs/plugin-vue` | Vue component auto-registration |\n| WXT | Extension framework |\n\n资料来源：[app/chrome-extension/wxt.config.ts:40-50](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n---\n\n<a id='page-communication'></a>\n\n## Communication Protocols\n\n### 相关页面\n\n相关主题：[System Architecture](#page-architecture), [MCP Server Implementation](#page-mcp-server)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/chrome-extension/entrypoints/background/native-host.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/native-host.ts)\n- [app/native-server/src/scripts/utils.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n- [app/native-server/src/scripts/browser-config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/browser-config.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/common.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n- [app/native-server/README.md](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/README.md)\n</details>\n\n# Communication Protocols\n\n## Overview\n\nThe mcp-chrome project implements a sophisticated communication architecture that bridges Chrome browser extensions with a native Node.js server. This architecture relies on multiple communication protocols working in concert to enable AI-powered browser automation through the Model Context Protocol (MCP).\n\nThe system employs two primary communication mechanisms:\n\n1. **Native Messaging Protocol** - Chrome extension to native host communication using Chrome's `runtime.connectNative` API\n2. **Internal Message Routing** - Communication between background scripts and tool handlers within the extension\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[Chrome Extension UI/Popup] -->|chrome.runtime.sendMessage| B[Background Script]\n    B -->|call_tool messages| C[Tool Handlers]\n    C -->|CDP Commands| D[Chrome DevTools Protocol]\n    B -->|connectNative| E[Native Host]\n    E -->|stdio| F[Node.js MCP Server]\n    F -->|WebSocket/CDP| G[Browser Instance]\n    \n    H[Content Scripts] -->|injected scripts| G\n    \n    I[Offscreen Document] -->|file operations| E\n```\n\n## Native Messaging Protocol\n\n### Purpose and Scope\n\nThe Native Messaging Protocol enables secure communication between the Chrome extension and a standalone native application. This is essential for operations that require direct system access, such as file system operations, native module execution, and port management for the MCP server.\n\n资料来源：[app/native-server/README.md](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/README.md)\n\n### Connection Establishment\n\nThe extension initiates native connections using Chrome's `runtime.connectNative` API with a predefined application ID:\n\n```typescript\nnativePort = chrome.runtime.connectNative('com.yourcompany.fastify_native_host');\n```\n\n资料来源：[app/native-server/README.md:40](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/README.md)\n\n### Auto-Connect Behavior\n\nThe system implements intelligent auto-connect functionality that activates on browser startup and extension installation:\n\n```typescript\n// Auto-connect on Chrome browser startup\nchrome.runtime.onStartup.addListener(() => {\n  void ensureNativeConnected('onStartup').catch(() => {});\n});\n\n// Auto-connect on extension install/update\nchrome.runtime.onInstalled.addListener(() => {\n  void ensureNativeConnected('onInstalled').catch(() => {});\n});\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/native-host.ts:1-20](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/native-host.ts)\n\n### Message Types\n\n| Message Type | Direction | Purpose |\n|--------------|-----------|---------|\n| `call_tool` | Extension → Native | Request tool execution |\n| `ENSURE_NATIVE` | UI → Background | Trigger connection check |\n| `CONNECT_NATIVE` | UI → Background | User-initiated connection |\n| `forward_to_native` | Background → Native | Route messages to native host |\n| `file_operation` | Extension → Native | File preparation for uploads |\n| `started` | Native → Extension | Server startup confirmation |\n| `stopped` | Native → Extension | Server shutdown notification |\n| `error` | Native → Extension | Error reporting |\n\n### Message Format\n\nMessages follow a structured format with `type` and `payload` fields:\n\n```typescript\nchrome.runtime.sendMessage({\n  type: 'forward_to_native',\n  message: {\n    type: 'file_operation',\n    requestId: requestId,\n    payload: {\n      action: 'prepareFile',\n      fileUrl,\n      base64Data,\n      fileName,\n    },\n  },\n});\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts:58-75](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts)\n\n## Internal Message Routing\n\n### Tool Call Routing\n\nThe background script routes tool calls from various sources (UI, content scripts) to appropriate handlers:\n\n```typescript\nchrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {\n  // Allow UI to call tools directly\n  if (message && message.type === 'call_tool' && message.name) {\n    handleCallTool({ name: message.name, args: message.args })\n      .then((res) => sendResponse({ success: true, result: res }))\n      .catch((err) =>\n        sendResponse({ success: false, error: err instanceof Error ? err.message : String(err) }),\n      );\n    return true;\n  }\n  // ... additional routing logic\n});\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/native-host.ts:28-45](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/native-host.ts)\n\n### Connection Management States\n\n```mermaid\nstateDiagram-v2\n    [*] --> Disconnected\n    Disconnected --> Connecting: ensureNativeConnected()\n    Connecting --> Connected: Port established\n    Connecting --> Disconnected: Connection failed\n    Connected --> Disconnected: Port disconnect\n    Connected --> AutoConnectDisabled: User explicit disconnect\n    AutoConnectDisabled --> Connecting: CONNECT_NATIVE message\n    AutoConnectDisabled --> Connecting: ensureNativeConnected()\n```\n\n## File Operation Protocol\n\n### File Upload Flow\n\nThe file upload mechanism uses a request-response pattern with unique request IDs:\n\n```typescript\nconst requestId = `${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;\n\nconst handleMessage = (message: any) => {\n  if (\n    message.type === 'file_operation_response' &&\n    message.responseToRequestId === requestId\n  ) {\n    clearTimeout(timeout);\n    chrome.runtime.onMessage.removeListener(handleMessage);\n    \n    if (message.payload?.success && message.payload?.filePath) {\n      resolve(message.payload.filePath);\n    } else {\n      resolve(null);\n    }\n  }\n};\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts:25-48](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts)\n\n### Timeout Handling\n\nFile operations implement a 30-second timeout to prevent hanging connections:\n\n```typescript\nconst timeout = setTimeout(() => {\n  console.error('File preparation request timed out');\n  resolve(null);\n}, 30000); // 30 second timeout\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts:14-18](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/file-upload.ts)\n\n## Native Host Manifest Configuration\n\n### Platform-Specific Paths\n\nThe native messaging host manifest location varies by operating system:\n\n| Platform | User-Level Path |\n|----------|-----------------|\n| Windows | `%APPDATA%\\Google\\Chrome\\NativeMessagingHosts\\` |\n| macOS | `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/` |\n| Linux | `~/.config/google-chrome/NativeMessagingHosts/` |\n\n| Platform | System-Level Path |\n|----------|-------------------|\n| Windows | `%ProgramFiles%\\Google\\Chrome\\NativeMessagingHosts\\` |\n| macOS | `/Library/Google/Chrome/NativeMessagingHosts/` |\n| Linux | `/etc/opt/chrome/native-messaging-hosts/` |\n\n资料来源：[app/native-server/src/scripts/utils.ts:1-35](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n\n### Browser-Specific Configuration\n\nDifferent Chromium-based browsers have distinct manifest locations:\n\n```typescript\nswitch (browser) {\n  case BrowserType.CHROME:\n    return path.join(home, 'Library', 'Application Support', 'Google', 'Chrome', 'NativeMessagingHosts', `${HOST_NAME}.json`);\n  case BrowserType.CHROMIUM:\n    return path.join(home, 'Library', 'Application Support', 'Chromium', 'NativeMessagingHosts', `${HOST_NAME}.json`);\n}\n```\n\n资料来源：[app/native-server/src/scripts/browser-config.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/browser-config.ts)\n\n### Manifest Validation\n\nThe doctor command validates manifest files for correctness:\n\n| Validation Check | Error Message |\n|------------------|---------------|\n| File existence | Manifest not found |\n| JSON parsing | Failed to parse manifest |\n| Name field | name != HOST_NAME |\n| Type field | type != stdio |\n| Path field | path is missing |\n| Path existence | path target does not exist |\n\n资料来源：[app/native-server/src/scripts/doctor.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/doctor.ts)\n\n## Tab Operation Protocol\n\n### URL Pattern Matching\n\nThe close tabs functionality supports glob-style URL pattern matching:\n\n```typescript\nlet urlPattern = url;\nif (!urlPattern.includes('*')) {\n  try {\n    new URL(urlPattern);\n    urlPattern = urlPattern.endsWith('/') ? `${urlPattern}*` : `${urlPattern}/*`;\n  } catch {\n    urlPattern = urlPattern.endsWith('*')\n      ? urlPattern\n      : urlPattern.endsWith('/')\n        ? `${urlPattern}*`\n        : `${urlPattern}/*`;\n  }\n}\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/common.ts:1-30](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n\n### Tab Query and Response Format\n\n```typescript\nconst tabs = await chrome.tabs.query({ url: urlPattern });\nawait chrome.tabs.remove(tabIdsToClose);\n\nreturn {\n  content: [{\n    type: 'text',\n    text: JSON.stringify({\n      success: true,\n      message: `Closed ${tabIdsToClose.length} tabs with URL: ${url}`,\n      closedCount: tabIdsToClose.length,\n      closedTabIds: tabIdsToClose,\n    }),\n  }],\n  isError: false,\n};\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/common.ts:60-80](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n\n## Port Configuration Protocol\n\n### Stdio Configuration\n\nThe native server communicates over a configured port for MCP operations:\n\n```typescript\nconst url = new URL(configValue.url as string);\nconst port = Number(url.port);\nconst portOk = port === EXPECTED_PORT;\n\nchecks.push({\n  id: 'port.config',\n  title: 'Port config',\n  status: portOk ? 'ok' : 'error',\n  message: configValue.url as string,\n  details: {\n    expectedPort: EXPECTED_PORT,\n    actualPort: port,\n    fix: portOk ? undefined : [`${COMMAND_NAME} update-port ${EXPECTED_PORT}`],\n  },\n});\n```\n\n资料来源：[app/native-server/src/scripts/doctor.ts:80-100](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/doctor.ts)\n\n## Node.js Path Management\n\n### Version Consistency\n\nThe system ensures consistent Node.js versions between installation and runtime to avoid native module version mismatches:\n\n```typescript\nexport function writeNodePathFile(distDir: string, nodeExecPath = process.execPath): void {\n  try {\n    const nodePathFile = path.join(distDir, 'node_path.txt');\n    fs.mkdirSync(distDir, { recursive: true });\n    // Write Node.js executable path for runtime consistency\n  } catch (error) {\n    // Error handling\n  }\n}\n```\n\n资料来源：[app/native-server/src/scripts/utils.ts:80-100](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/utils.ts)\n\n## Security Considerations\n\n### Cross-Origin Policies\n\nProduction builds implement strict COEP and COOP headers:\n\n```typescript\ncross_origin_embedder_policy: { value: 'require-corp' as const },\ncross_origin_opener_policy: { value: 'same-origin' as const },\ncontent_security_policy: {\n  extension_pages: \"script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:;\",\n}\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:1-30](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n### Web Accessible Resources\n\nOnly specific resource paths are accessible to web pages:\n\n```typescript\nweb_accessible_resources: [\n  {\n    resources: [\n      '/models/*',\n      '/workers/*',\n      '/inject-scripts/*',\n    ],\n    matches: ['<all_urls>'],\n  },\n],\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:20-30](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n## Summary\n\nThe mcp-chrome communication architecture consists of multiple protocol layers:\n\n1. **Native Messaging Layer** - Chrome-to-native bridge using Chrome's native messaging API\n2. **Internal Message Routing** - Efficient routing of tool calls within the extension\n3. **File Operation Protocol** - Request-response pattern with timeout handling\n4. **Tab Management Protocol** - URL pattern-based tab operations\n5. **Port Configuration Protocol** - Stdio-based MCP server communication\n\nAll protocols emphasize reliability through timeout handling, error reporting, and connection state management.\n\n---\n\n<a id='page-extension-structure'></a>\n\n## Chrome Extension Structure\n\n### 相关页面\n\n相关主题：[Browser Tools and APIs](#page-browser-tools), [Storage and Data Management](#page-storage)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n- [app/chrome-extension/entrypoints/background/index.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/index.ts)\n- [app/chrome-extension/entrypoints/content.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/content.ts)\n- [app/chrome-extension/entrypoints/background/native-host.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/native-host.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/common.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n- [app/chrome-extension/entrypoints/background/record-replay/index.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/index.ts)\n- [app/chrome-extension/utils/content-indexer.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n</details>\n\n# Chrome Extension Structure\n\n## Overview\n\nThe mcp-chrome project implements a Chrome Extension that serves as a bridge between a Chrome browser instance and an AI-powered automation system. The extension enables Large Language Models (LLMs) to control browser behavior, capture web content, manage tabs, inject scripts, and automate user interactions through the Model Context Protocol (MCP).\n\nThe extension is built using **WXT**, a modern framework for Chrome extension development, which handles manifest generation, build configuration, and hot module replacement. The architecture follows a multi-process model with background service workers, content scripts, and UI entrypoints communicating through Chrome's message passing APIs and native messaging.\n\n资料来源：[app/chrome-extension/wxt.config.ts:1-100]()\n\n---\n\n## Architecture Overview\n\nThe Chrome extension consists of several interconnected layers:\n\n```mermaid\ngraph TD\n    subgraph \"UI Layer\"\n        POPUP[Popup UI]\n        SIDEPANEL[Side Panel]\n        WELCOME[Welcome Page]\n        OPTIONS[Options Page]\n    end\n    \n    subgraph \"Background Layer\"\n        BG[Background Service Worker]\n        NATIVE[Native Host Bridge]\n        RECORDREPLAY[Record/Replay Engine]\n    end\n    \n    subgraph \"Content Layer\"\n        CONTENT[Content Scripts]\n        INJECT[inject-scripts]\n    end\n    \n    subgraph \"Native Layer\"\n        NATIVE_SERVER[mcp-chrome-bridge]\n    end\n    \n    POPUP <-->|chrome.runtime| BG\n    SIDEPANEL <-->|chrome.runtime| BG\n    OPTIONS <-->|chrome.runtime| BG\n    \n    BG <-->|nativeMessaging| NATIVE\n    BG <-->|chrome.tabs.sendMessage| CONTENT\n    CONTENT <-->|window messages| INJECT\n    \n    NATIVE <-->|stdin/stdout| NATIVE_SERVER\n    \n    RECORDREPLAY <-->|chrome.scripting| CONTENT\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:20-60]()\n\n---\n\n## Entry Points\n\nThe extension defines multiple entry points through WXT's manifest configuration. Each entry point represents a distinct execution context within Chrome.\n\n### Entry Point Configuration\n\n| Entry Point | File Path | Purpose | Permissions |\n|-------------|-----------|---------|-------------|\n| `action` (Popup) | `popup.html` | Quick access UI with MCP configuration | Standard |\n| `side_panel` | `sidepanel.html` | Workflow management interface | `sidePanel` |\n| `options_ui` | `options.html` | Extension settings | Storage |\n| `welcome` | `welcome/index.html` | Onboarding page | None |\n| Background | `background/index.ts` | Service worker | All browser APIs |\n\n资料来源：[app/chrome-extension/wxt.config.ts:20-55]()\n\n### Manifest Permissions\n\nThe extension declares extensive permissions to support its automation capabilities:\n\n```typescript\npermissions: [\n  'nativeMessaging',  // Native host communication\n  'tabs',             // Tab management\n  'activeTab',        // Active tab access\n  'scripting',        // Script injection\n  'contextMenus',     // Context menu creation\n  'downloads',        // Download management\n  'webRequest',       // Network monitoring\n  'webNavigation',    // Navigation events\n  'debugger',         // Debugging capabilities\n  'history',          // Browser history\n  'bookmarks',        // Bookmark management\n  'offscreen',        // Offscreen documents\n  'storage',          // Local storage\n  'declarativeNetRequest', // Ad blocking\n  'alarms',           // Scheduled tasks\n  'sidePanel',        // Side panel access\n],\nhost_permissions: ['<all_urls>'],\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:20-40]()\n\n---\n\n## Background Service Worker\n\nThe background service worker (`entrypoints/background/index.ts`) serves as the central coordinator for all extension functionality.\n\n### Core Responsibilities\n\n```mermaid\ngraph LR\n    A[Incoming Messages] --> B[Type Router]\n    B --> C{Message Type}\n    C -->|tool_call| D[Tool Executor]\n    C -->|native| E[Native Host]\n    C -->|rr_trigger| F[Record/Replay]\n    D --> G[chrome.* APIs]\n    E --> H[Native Bridge]\n    F --> I[Content Scripts]\n```\n\n### Native Host Communication\n\nThe background script maintains a persistent connection to the native `mcp-chrome-bridge` server through Chrome's native messaging API:\n\n```typescript\n// Connection lifecycle management\nchrome.runtime.onStartup.addListener(() => {\n  void ensureNativeConnected('onStartup').catch(() => {});\n});\n\nchrome.runtime.onInstalled.addListener(() => {\n  void ensureNativeConnected('onInstalled').catch(() => {});\n});\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/native-host.ts:1-20]()\n\nThe native messaging follows a request-response pattern with auto-reconnect capabilities:\n\n| Message Type | Direction | Purpose |\n|--------------|-----------|---------|\n| `ENSURE_NATIVE` | UI → Background | Trigger connection without changing autoConnect state |\n| `CONNECT_NATIVE` | UI → Background | Explicit user-initiated connection, re-enables auto-connect |\n| `call_tool` | UI → Background | Direct tool execution via message |\n\n资料来源：[app/chrome-extension/entrypoints/background/native-host.ts:25-45]()\n\n### Tool Execution System\n\nTools are executed through the `handleCallTool` function, which routes requests to appropriate handlers:\n\n```typescript\nchrome.runtime.onMessage.addListener((message, _sender, sendResponse) => {\n  if (message && message.type === 'call_tool' && message.name) {\n    handleCallTool({ name: message.name, args: message.args })\n      .then((res) => sendResponse({ success: true, result: res }))\n      .catch((err) => sendResponse({ success: false, error: err.message }));\n    return true;\n  }\n});\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/native-host.ts:30-38]()\n\n---\n\n## Content Scripts Architecture\n\nContent scripts (`entrypoints/content.ts`) run in the context of web pages and provide the bridge between the background service worker and page-level JavaScript.\n\n### Injection Strategy\n\nThe extension uses a multi-file injection approach:\n\n```typescript\n// Files injected into all frames\nfiles: ['inject-scripts/inject-bridge.js', 'inject-scripts/accessibility-tree-helper.js']\n```\n\n| Script | Purpose |\n|--------|---------|\n| `inject-bridge.js` | Message communication bridge |\n| `accessibility-tree-helper.js` | DOM accessibility tree generation |\n| `dom-observer.js` | DOM change monitoring for triggers |\n| `web-fetcher-helper.js` | Content extraction utilities |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/index.ts:15-25]()\n\n### Script Injection Modes\n\nContent scripts can be injected with different world contexts:\n\n| World | Isolation | Use Case |\n|-------|-----------|----------|\n| `ISOLATED` | Full isolation | Script injection via `chrome.scripting.executeScript` |\n| `MAIN` | Shared with page | User scripts requiring DOM access |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/index.ts:20-25]()\n\n---\n\n## Web-Accessible Resources\n\nThe extension exposes certain resources to web pages for content script functionality:\n\n```typescript\nweb_accessible_resources: [\n  {\n    resources: [\n      '/models/*',           // ML models for content analysis\n      '/workers/*',          // Web Workers\n      '/inject-scripts/*',   // Helper scripts\n    ],\n    matches: ['<all_urls>'],\n  },\n]\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:55-65]()\n\n---\n\n## Content Indexing System\n\nThe `ContentIndexer` class manages automatic content indexing for semantic search capabilities.\n\n### Indexing Flow\n\n```mermaid\ngraph TD\n    A[Tab Load Complete] --> B{URL Valid?}\n    B -->|No| C[Skip]\n    B -->|Yes| D{Semantic Engine Ready?}\n    D -->|No| E[Wait + Retry]\n    D -->|Yes| F[Extract Content]\n    F --> G[Update Index]\n    \n    H[Tab Closed] --> I[Remove Index]\n    J[Navigation Committed] --> K[Remove Index]\n```\n\n### URL Filtering\n\nThe indexer excludes internal Chrome pages:\n\n```typescript\nprivate shouldIndexUrl(url: string): boolean {\n  const excludePatterns = [\n    /^chrome:\\/\\//,\n    /^chrome-extension:\\/\\//,\n    /^edge:\\/\\//,\n    /^about:/,\n    /^moz-extension:\\/\\//,\n    /^file:\\/\\//,\n  ];\n  return !excludePatterns.some((pattern) => pattern.test(url));\n}\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:30-50]()\n\nAuto-indexing is triggered with a 2-second delay after page load:\n\n```typescript\nsetTimeout(() => {\n  if (!this.isSemanticEngineReady() && !this.isSemanticEngineInitializing()) {\n    console.log('ContentIndexer: Skipping auto-index - semantic engine not ready');\n    return;\n  }\n  this.indexTabContent(tabId).catch((error) => {\n    console.error('ContentIndexer: Auto-indexing failed:', error);\n  });\n}, 2000);\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:10-20]()\n\n---\n\n## Record/Replay Engine\n\nThe record/replay system enables automation workflow recording and playback.\n\n### Trigger Types\n\n| Type | Description | Configuration |\n|------|-------------|---------------|\n| `dom` | DOM element triggers | selector, appear, once, debounceMs |\n| `network` | Network request patterns | request/response matching |\n| `navigation` | Page navigation events | URL patterns |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/index.ts:5-15]()\n\n### Trigger Initialization\n\n```typescript\nconst domTriggers = triggers\n  .filter((x) => x.type === 'dom' && x.enabled !== false)\n  .map((x: any) => ({\n    id: x.id,\n    selector: x.selector,\n    appear: x.appear !== false,\n    once: x.once !== false,\n    debounceMs: x.debounceMs ?? 800,\n  }));\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/index.ts:10-20]()\n\n### Node Runtimes\n\nThe engine executes steps through node runtimes:\n\n| Node Type | File | Capabilities |\n|-----------|------|--------------|\n| `scroll` | `nodes/scroll.ts` | Page/container scrolling with offset or element targeting |\n| `tabs` | `nodes/tabs.ts` | Tab creation, switching, closing |\n| `wait` | `engine/policies/wait.ts` | Network idle and DOM state waiting |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/nodes/scroll.ts:1-20]()\n\n### Navigation State Tracking\n\n```typescript\nconst onCommitted = (d: any) => {\n  if (d.tabId === tabId && d.frameId === 0 && d.timeStamp >= startedAt) mark();\n};\nconst onHistoryStateUpdated = (d: any) => {\n  if (d.tabId === tabId && d.frameId === 0 && d.timeStamp >= startedAt) mark();\n};\nconst onUpdated = (updatedId: number, change: chrome.tabs.TabChangeInfo) => {\n  if (updatedId !== tabId) return;\n  if (change.status === 'loading') mark();\n  if (typeof change.url === 'string' && (!prevUrl || change.url !== prevUrl)) mark();\n};\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts:15-25]()\n\n---\n\n## Tool System Architecture\n\n### Browser Tool Categories\n\n| Category | Tools |\n|----------|-------|\n| Navigation | go_back_or_forward, switch_tab, close_tabs |\n| Interaction | click_element, fill_or_select, keyboard |\n| Data | history, bookmark_search, bookmark_add, bookmark_delete |\n| Screenshot | screenshot (with element targeting, full-page support) |\n| Network | network_capture_start/stop, network_debugger_start/stop, network_request |\n| Content | get_web_content, get_interactive_elements, console, search_tabs_content |\n\n资料来源：[README.md]()\n\n### Tool Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant UI\n    participant BG as Background Worker\n    participant NATIVE as Native Bridge\n    participant CHROME as Chrome APIs\n    \n    UI->>BG: call_tool { name, args }\n    BG->>BG: Route to Handler\n    alt Native Tool\n        BG->>NATIVE: nativeMessage\n        NATIVE->>CHROME: Browser API\n        CHROME-->>NATIVE: Response\n        NATIVE-->>BG: { success, result }\n    else Browser Tool\n        BG->>CHROME: chrome.* API\n        CHROME-->>BG: Result\n    end\n    BG-->>UI: { success, result }\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/common.ts:1-50]()\n\n---\n\n## Security Configuration\n\nThe extension implements security policies for production builds:\n\n```typescript\n...(IS_DEV\n  ? {}\n  : {\n      cross_origin_embedder_policy: { value: 'require-corp' as const },\n      cross_origin_opener_policy: { value: 'same-origin' as const },\n      content_security_policy: {\n        extension_pages:\n          \"script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:;\",\n      },\n    }),\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:65-80]()\n\n| Policy | Development | Production |\n|--------|-------------|------------|\n| COEP | Disabled | `require-corp` |\n| COOP | Disabled | `same-origin` |\n| CSP | WXT Default | Restricted to self + wasm |\n\n---\n\n## Keyboard Shortcuts\n\nThe extension defines keyboard commands:\n\n```typescript\ncommands: {\n  toggle_quick_panel: {\n    suggested_key: { default: 'Ctrl+Shift+Space', mac: 'Command+Shift+Space' },\n    description: 'Toggle Quick Panel AI Chat',\n  },\n}\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:45-55]()\n\n---\n\n## Side Panel Interface\n\nThe side panel (`sidepanel.html`) provides a workflow management interface with agent thread tracking:\n\n```typescript\n// Message parsing rules\nif (\n  normalize(toolName) === 'bash' ||\n  normalize(toolName).includes('shell') ||\n  typeof command === 'string'\n) {\n  return { kind: 'run', title: commandDescription || extractedCommand };\n}\n\nif (normalize(toolName) === 'grep' || normalize(toolName).includes('search')) {\n  return { kind: 'grep', title: displayPattern };\n}\n```\n\n资料来源：[app/chrome-extension/entrypoints/sidepanel/composables/useAgentThreads.ts:1-30]()\n\n---\n\n## Native Messaging Bridge\n\nThe native messaging layer communicates with `mcp-chrome-bridge` installed on the host system.\n\n### Communication Flow\n\n```mermaid\ngraph LR\n    subgraph \"Chrome Extension\"\n        BG[Background]\n        PORT[Native Port]\n    end\n    \n    subgraph \"Host System\"\n        BRIDGE[mcp-chrome-bridge]\n        NATIVE_HOST[Native Host JSON]\n    end\n    \n    BG <-->|Native Messaging| PORT\n    PORT <-->|stdin/stdout| BRIDGE\n    BRIDGE <-->|Browser APIs| CHROME[(Chrome)]\n    \n    NATIVE_HOST -.->|Manifest Path| BRIDGE\n```\n\n### Manifest Configuration\n\nNative messaging manifests are installed at platform-specific paths:\n\n| Platform | User-Level Path |\n|----------|-----------------|\n| Windows | `%APPDATA%\\Google\\Chrome\\NativeMessagingHosts\\` |\n| macOS | `~/Library/Application Support/Google/Chrome/NativeMessagingHosts/` |\n| Linux | `~/.config/google-chrome/NativeMessagingHosts/` |\n\n| Platform | System-Level Path |\n|----------|-------------------|\n| Windows | `%ProgramFiles%\\Google\\Chrome\\NativeMessagingHosts\\` |\n| macOS | `/Library/Google/Chrome/NativeMessagingHosts/` |\n| Linux | `/etc/opt/chrome/native-messaging-hosts/` |\n\n资料来源：[app/native-server/src/scripts/browser-config.ts:1-80]()\n\n---\n\n## State Management\n\nThe extension uses Chrome's storage API for state persistence:\n\n| Key | Type | Purpose |\n|-----|------|---------|\n| `RR_TRIGGERS` | Array | Record/replay trigger configurations |\n| `USERSCRIPTS_DISABLED` | Boolean | Userscript execution toggle |\n| `autoConnectEnabled` | Boolean | Native connection auto-connect state |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/index.ts:5-10]()\n\n---\n\n## Build Configuration\n\nThe extension uses Vite with TailwindCSS v4:\n\n```typescript\nvite: (env) => ({\n  plugins: [\n    tailwindcss(),\n    Components({\n      dts: true,\n    }),\n  ],\n}),\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts:80-90]()\n\n### Build Requirements\n\n| Dependency | Version | Purpose |\n|------------|---------|---------|\n| Node.js | >= 20.0.0 | Runtime |\n| pnpm/npm | Latest | Package manager |\n| WXT | Latest | Build framework |\n| TailwindCSS v4 | Latest | Styling |\n\n---\n\n## Summary\n\nThe Chrome Extension architecture of mcp-chrome follows a layered design:\n\n1. **UI Layer**: Popup, side panel, welcome page, and options provide user-facing interfaces\n2. **Background Layer**: Service worker coordinates native messaging, tool execution, and automation\n3. **Content Layer**: Injected scripts enable page-level interaction and accessibility tree generation\n4. **Native Layer**: External `mcp-chrome-bridge` process handles OS-level browser automation\n\nThe extension leverages Chrome's extensive APIs for tab management, network monitoring, script injection, and state persistence while maintaining security through manifest-defined permissions and CSP policies.\n\n---\n\n<a id='page-browser-tools'></a>\n\n## Browser Tools and APIs\n\n### 相关页面\n\n相关主题：[Chrome Extension Structure](#page-extension-structure), [Record and Replay Engine](#page-record-replay)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [docs/TOOLS.md](https://github.com/hangwin/mcp-chrome/blob/main/docs/TOOLS.md)\n- [app/chrome-extension/entrypoints/background/tools/browser/index.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/index.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/computer.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/computer.ts)\n- [app/chrome-extension/shared/tools.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/shared/tools.ts)\n- [app/chrome-extension/entrypoints/background/tools/browser/common.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n- [app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n</details>\n\n# Browser Tools and APIs\n\n## Overview\n\nThe Browser Tools and APIs module is a core component of the mcp-chrome extension that provides AI agents with programmatic control over browser functionality. This module bridges the gap between AI decision-making and browser operations, enabling automated web navigation, content extraction, tab management, and user interaction simulation.\n\nThe system operates as a collection of Chrome extension background script tools that expose browser capabilities through a structured MCP (Model Context Protocol) interface, allowing LLM-powered agents to interact with the browser as if performing actions themselves.\n\n资料来源：[docs/TOOLS.md](https://github.com/hangwin/mcp-chrome/blob/main/docs/TOOLS.md)\n\n## Architecture\n\n### High-Level Architecture\n\n```mermaid\ngraph TD\n    A[MCP Client / AI Agent] -->|MCP Protocol| B[Native Server]\n    B -->|Native Messaging| C[Chrome Extension Background]\n    C -->|Chrome APIs| D[Browser Environment]\n    \n    E[Content Scripts] -->|Injection| D\n    F[Injected Scripts] -->|Web Fetcher| D\n    \n    G[Sidepanel UI] -->|User Interaction| C\n    H[Popup UI] -->|Quick Actions| C\n```\n\n### Tool Registration Flow\n\n```mermaid\nsequenceDiagram\n    participant T as Tool Registry\n    participant B as Background Script\n    participant C as Chrome API\n    participant M as MCP Bridge\n    \n    T->>B: Register tool handlers\n    B->>C: Initialize chrome.tabs listeners\n    C->>M: Expose via native messaging\n    M->>T: Forward tool calls\n```\n\nThe extension registers tools through the shared `tools.ts` module, which defines the complete tool schema including names, descriptions, input parameters, and response formats. The background script then connects these tool definitions to actual Chrome API implementations.\n\n资料来源：[app/chrome-extension/shared/tools.ts:1-50](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/shared/tools.ts)\n\n## Tool Categories\n\nThe browser tools are organized into the following functional categories:\n\n| Category | Tools | Purpose |\n|----------|-------|---------|\n| **Navigation** | `chrome_navigate`, `chrome_go_back_or_forward` | Page navigation and history control |\n| **Tab Management** | `chrome_switch_tab`, `chrome_close_tabs`, `chrome_close_other_tabs` | Tab lifecycle management |\n| **View Control** | `chrome_set_viewport`, `chrome_screenshot` | Visual viewport manipulation and capture |\n| **Content Extraction** | `chrome_get_web_content`, `chrome_get_interactive_elements` | Page content retrieval |\n| **User Interaction** | `chrome_click_element`, `chrome_fill_or_select`, `chrome_keyboard` | Simulated user actions |\n| **Data Management** | `chrome_bookmark_*`, `chrome_history` | Bookmark and history access |\n| **Network Monitoring** | `chrome_network_*` | HTTP traffic inspection |\n| **Script Injection** | `chrome_inject_script`, `chrome_send_command_to_inject_script` | Custom script execution |\n\n资料来源：[docs/TOOLS.md](https://github.com/hangwin/mcp-chrome/blob/main/docs/TOOLS.md)\n\n## Navigation Tools\n\n### chrome_navigate\n\nNavigates the current tab to a specified URL or performs search queries.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `url` | `string` | Yes | Target URL or search query |\n| `options` | `object` | No | Navigation options |\n\n**Options:**\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `waitUntil` | `string` | `\"networkidle2\"` | When to consider navigation complete |\n| `timeout` | `number` | `30000` | Navigation timeout in milliseconds |\n\n**Implementation Details:**\n\nThe navigation tool first validates the URL, handling search queries by converting them to search engine URLs. It then attempts to find an existing tab matching the URL before creating a new one, promoting existing tabs to reduce clutter.\n\n```typescript\n// Simplified navigation flow\nasync function chrome_navigate(url: string, options?: NavigationOptions) {\n  const normalizedUrl = validateAndNormalizeUrl(url);\n  const existingTab = await findExistingTab(normalizedUrl);\n  \n  if (existingTab) {\n    await chrome.tabs.update(existingTab.id, { active: true });\n    return existingTab;\n  }\n  \n  return await chrome.tabs.create({ url: normalizedUrl, active: true });\n}\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/index.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/index.ts)\n\n### chrome_go_back_or_forward\n\nNavigates browser history by a specified number of steps.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `historySteps` | `number` | Yes | Number of steps (- for back, + for forward) |\n\n## Tab Management Tools\n\n### Tab Query System\n\n```mermaid\ngraph LR\n    A[URL Pattern] -->|Parse| B[Tab Filter]\n    B -->|Query| C[chrome.tabs.query]\n    C -->|Results| D[Tab IDs Array]\n    \n    E[Tab ID] -->|Direct| D\n    F[Window ID] -->|Window Filter| D\n```\n\nThe tab management system supports multiple query mechanisms:\n\n- **URL Pattern Matching**: Glob-style patterns with wildcard support\n- **Direct Tab ID**: Integer-based tab identification\n- **Window Scoping**: Restricting operations to specific windows\n\n**Pattern Matching Implementation:**\n\n```typescript\nprivate async queryTabsByUrl(urlPattern: string): Promise<number[]> {\n  // Normalize pattern with proper glob-to-regex conversion\n  const pattern = urlPattern\n    .replace(/\\./g, '\\\\.')\n    .replace(/\\*/g, '.*')\n    .replace(/\\?/g, '.');\n  \n  const tabs = await chrome.tabs.query({ url: `<all_urls>` });\n  return tabs\n    .filter(tab => tab.url?.match(new RegExp(pattern)))\n    .map(tab => tab.id)\n    .filter((id): id is number => id !== undefined);\n}\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/tools/browser/common.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/tools/browser/common.ts)\n\n### chrome_close_tabs\n\nCloses tabs matching a URL pattern or specified tab IDs.\n\n**Response Schema:**\n\n```typescript\ninterface CloseTabsResponse {\n  success: boolean;\n  message: string;\n  closedCount: number;\n  closedTabIds: number[];\n}\n```\n\n**Example Response:**\n\n```json\n{\n  \"success\": true,\n  \"message\": \"Closed 3 tabs with URL: https://github.com/*\",\n  \"closedCount\": 3,\n  \"closedTabIds\": [123, 456, 789]\n}\n```\n\n### chrome_switch_tab\n\nActivates a specific tab by ID or switches to adjacent tabs relative to the current tab.\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `tabId` | `number` | Target tab ID |\n| `offset` | `number` | Relative offset from current tab |\n\n## View Control Tools\n\n### chrome_screenshot\n\nCaptures screenshots with multiple targeting modes.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `captureArea` | `string` | No | `\"fullpage\"`, `\"viewport\"`, or CSS selector |\n| `selector` | `string` | No | CSS selector for element targeting |\n| `options` | `object` | No | Screenshot options (quality, format) |\n\n**Capture Modes:**\n\n| Mode | Description | Use Case |\n|------|-------------|----------|\n| `viewport` | Current visible area | Quick preview |\n| `fullpage` | Entire scrollable page | Complete documentation |\n| `element` | Specific element by selector | Targeted capture |\n\n资料来源：[docs/TOOLS.md](https://github.com/hangwin/mcp-chrome/blob/main/docs/TOOLS.md)\n\n### chrome_set_viewport\n\nControls the browser viewport dimensions for responsive testing and content adaptation.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `width` | `number` | Yes | Viewport width in pixels |\n| `height` | `number` | Yes | Viewport height in pixels |\n| `deviceScaleFactor` | `number` | No | Device pixel ratio (default: 1) |\n\n## Content Extraction Tools\n\n### chrome_get_web_content\n\nExtracts structured content from web pages including text, metadata, and semantic elements.\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `extractOptions` | `object` | Configuration for content extraction |\n| `metadata` | `boolean` | Include page metadata (default: true) |\n\n**Extracted Metadata Fields:**\n\n| Field | Source | Description |\n|-------|--------|-------------|\n| `title` | `<title>`, `og:title`, JSON-LD | Page title |\n| `byline` | `author`, `article:author` | Content author |\n| `excerpt` | `description`, `og:description` | Page summary |\n| `siteName` | `og:site_name` | Website name |\n| `publishedTime` | `article:published_time` | Publication date |\n\n**Content Script Injection:**\n\n```typescript\n// Web fetcher helper extracts structured data from pages\nconst response = await chrome.scripting.executeScript({\n  target: { tabId },\n  files: ['inject-scripts/web-fetcher-helper.js'],\n});\n```\n\n资料来源：[app/chrome-extension/inject-scripts/web-fetcher-helper.js](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/inject-scripts/web-fetcher-helper.js)\n\n### chrome_get_interactive_elements\n\nRetrieves clickable and interactive elements from a page for automation targeting.\n\n**Response:**\n\n```typescript\ninterface InteractiveElementsResponse {\n  elements: Array<{\n    selector: string;      // CSS selector for the element\n    tagName: string;       // HTML tag name\n    text: string;          // Visible text content\n    attributes: Record<string, string>;\n    isClickable: boolean;\n    boundingRect: DOMRect;\n  }>;\n}\n```\n\n### search_tabs_content\n\nAI-powered semantic search across all open browser tabs.\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `query` | `string` | Semantic search query |\n| `maxResults` | `number` | Maximum results to return |\n\n## User Interaction Tools\n\n### chrome_click_element\n\nSimulates mouse clicks on elements identified by CSS selectors.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | `string` | Yes | CSS selector for target element |\n| `button` | `string` | No | Mouse button (`left`, `middle`, `right`) |\n| `clickCount` | `number` | No | Number of clicks |\n\n### chrome_fill_or_select\n\nFills form inputs and selects options.\n\n**Supported Input Types:**\n\n| Input Type | Action |\n|------------|--------|\n| `input[type=text]` | Text input |\n| `input[type=email]` | Email input |\n| `input[type=password]` | Password input |\n| `textarea` | Multi-line text |\n| `select` | Dropdown selection |\n| `input[type=checkbox]` | Toggle state |\n| `input[type=radio]` | Radio selection |\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `selector` | `string` | Yes | Target element selector |\n| `value` | `string` | Yes | Value to input or select |\n| `options` | `object` | No | Additional options |\n\n### chrome_keyboard\n\nSimulates keyboard input and shortcuts.\n\n**Parameters:**\n\n| Parameter | Type | Required | Description |\n|-----------|------|----------|-------------|\n| `text` | `string` | No | Text to type |\n| `shortcuts` | `string[]` | No | Keyboard shortcuts to execute |\n| `options` | `object` | No | Keyboard simulation options |\n\n**Supported Shortcuts:**\n\n```typescript\nconst shortcuts = [\n  'Ctrl+C',      // Copy\n  'Ctrl+V',      // Paste\n  'Ctrl+A',      // Select all\n  'Ctrl+K',      // Clear\n  'Enter',       // Submit\n  'Escape',      // Cancel/Dismiss\n  'Tab',         // Next element\n  'Shift+Tab',   // Previous element\n];\n```\n\n## Network Monitoring Tools\n\n### chrome_network_capture_start / stop\n\nControls webRequest API-based network traffic capture.\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `options` | `object` | Capture configuration |\n| `filterUrls` | `string[]` | URL patterns to monitor |\n\n**Captured Data:**\n\n| Field | Description |\n|-------|-------------|\n| `url` | Request URL |\n| `method` | HTTP method |\n| `headers` | Request/response headers |\n| `status` | HTTP status code |\n| `timing` | Request timing data |\n| `bodySize` | Response body size |\n\n### chrome_network_debugger_start / stop\n\nEnables Chrome DevTools Protocol debugger for detailed request/response inspection including response bodies.\n\n### chrome_network_request\n\nSends custom HTTP requests through the browser context, useful for bypassing CORS and maintaining session state.\n\n## Script Injection System\n\n### chrome_inject_script\n\nInjects JavaScript files into web pages for extended functionality.\n\n**Implementation:**\n\n```typescript\nawait chrome.scripting.executeScript({\n  target: { tabId },\n  files: ['inject-scripts/web-fetcher-helper.js'],\n});\n```\n\n**Web Accessible Resources Configuration:**\n\nThe extension allows injection of specific resource categories defined in `wxt.config.ts`:\n\n```typescript\nweb_accessible_resources: [\n  {\n    resources: [\n      '/models/*',           // ML models\n      '/workers/*',          // Web workers\n      '/inject-scripts/*',   // Helper scripts\n    ],\n    matches: ['<all_urls>'],\n  },\n]\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n### chrome_send_command_to_inject_script\n\nSends structured commands to injected content scripts via a messaging bridge.\n\n**Command Flow:**\n\n```mermaid\nsequenceDiagram\n    participant B as Background Script\n    participant C as Content Script\n    participant P as Web Page\n    \n    B->>C: chrome.tabs.sendMessage\n    C->>P: postMessage to page context\n    P-->>C: Response message\n    C-->>B: chrome.runtime.sendResponse\n```\n\n## Bookmark and History Tools\n\n### Bookmark Operations\n\n| Tool | Function |\n|------|----------|\n| `chrome_bookmark_search` | Search bookmarks by keywords |\n| `chrome_bookmark_add` | Create new bookmarks with folder support |\n| `chrome_bookmark_delete` | Remove bookmarks |\n\n### chrome_history\n\nSearches browser history with temporal filtering.\n\n**Parameters:**\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `query` | `string` | Search query |\n| `maxResults` | `number` | Maximum entries |\n| `startTime` | `number` | Unix timestamp lower bound |\n| `endTime` | `number` | Unix timestamp upper bound |\n\n## Error Handling\n\nAll browser tools implement consistent error handling patterns:\n\n```typescript\ninterface ToolResponse {\n  content: Array<{\n    type: 'text';\n    text: string;  // JSON stringified response or error\n  }>;\n  isError: boolean;\n}\n```\n\n**Error Response Format:**\n\n```json\n{\n  \"success\": false,\n  \"error\": \"Error description\",\n  \"code\": \"ERROR_CODE\"\n}\n```\n\n**URL Exclusion Patterns:**\n\nInternal Chrome URLs are automatically excluded from operations:\n\n```typescript\nconst excludePatterns = [\n  /^chrome:\\/\\//,\n  /^chrome-extension:\\/\\//,\n  /^edge:\\/\\//,\n  /^about:/,\n  /^moz-extension:\\/\\//,\n  /^file:\\/\\//,\n];\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n\n## Security Considerations\n\n### Cross-Origin Policies\n\nThe extension implements COOP/COEP headers in production to enable SharedArrayBuffer and other features:\n\n```typescript\n...(IS_DEV\n  ? {}\n  : {\n      cross_origin_embedder_policy: { value: 'require-corp' as const },\n      cross_origin_opener_policy: { value: 'same-origin' as const },\n    })\n```\n\n### Content Security Policy\n\nProduction builds enforce strict CSP:\n\n```\nscript-src 'self' 'wasm-unsafe-eval'; \nobject-src 'self'; \nstyle-src 'self' 'unsafe-inline'; \nimg-src 'self' data: blob:;\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/wxt.config.ts)\n\n## Usage with AI Agents\n\nThe browser tools are designed for seamless integration with AI agents:\n\n```typescript\n// Example: Agent task to research a topic\nconst task = {\n  instruction: \"Search for TypeScript best practices and summarize the top 5 tips\",\n  tools: [\n    \"chrome_navigate\",      // Go to search engine\n    \"chrome_get_web_content\", // Extract results\n    \"chrome_screenshot\",    // Document findings\n  ]\n};\n```\n\nThe tools provide structured, parseable responses that AI agents can use for decision-making and subsequent actions, enabling complex multi-step workflows in the browser environment.\n\n---\n\n<a id='page-record-replay'></a>\n\n## Record and Replay Engine\n\n### 相关页面\n\n相关主题：[Browser Tools and APIs](#page-browser-tools), [Storage and Data Management](#page-storage)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/chrome-extension/entrypoints/background/record-replay/index.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/index.ts)\n- [app/chrome-extension/entrypoints/background/record-replay/recording/browser-event-listener.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/recording/browser-event-listener.ts)\n- [app/chrome-extension/entrypoints/background/record-replay/rr-utils.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/rr-utils.ts)\n- [app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/engine/policies/wait.ts)\n</details>\n\n# Record and Replay Engine\n\n## Overview\n\nThe Record and Replay Engine is a Chrome extension feature within mcp-chrome that enables automatic capture and reproduction of user browser interactions. It records navigation events, user actions, and DOM interactions into a structured flow, then replays these flows to automate repetitive browser tasks.\n\nThe engine operates as a background service within the Chrome extension, using Chrome's webExtension APIs to monitor and control browser behavior across tabs and windows.\n\n## Architecture\n\n```mermaid\ngraph TD\n    subgraph Recording\n        BEL[Browser Event Listener] -->|captures| Session[Recording Session]\n        Session -->|stores| Flow[Flow Data]\n    end\n    \n    subgraph Replay\n        FR[Flow Runner] -->|executes| Steps[Flow Steps]\n        Steps -->|waits for| NI[Network Idle Detection]\n        Steps -->|injects| IS[Injected Scripts]\n    end\n    \n    subgraph Triggers\n        TriggerStore[Trigger Store] -->|activates| FR\n        DOMObs[DOM Observer] -->|detects| TriggerStore\n    end\n    \n    Flow -->|loads| FR\n    TriggerStore -->|manages| Flow\n```\n\n## Core Components\n\n### Session Manager\n\nThe session manager tracks the current recording state and maintains a list of active tabs under observation.\n\n**Key Responsibilities:**\n- Track recording status (`recording`, `idle`, `paused`)\n- Manage set of active tabs during recording\n- Store and retrieve flow data from Chrome storage\n\n**State Management:**\n```typescript\nsession.getStatus() !== 'recording'  // Check if recording is active\nsession.addActiveTab(tabId)           // Track tab for targeted STOP\nsession.removeActiveTab(tabId)        // Cleanup when tab closes\nsession.getFlow()                     // Retrieve current flow data\n```\n\n资料来源：[browser-event-listener.ts:25-30]()\n\n### Browser Event Listener\n\nThe event listener hooks into Chrome's navigation and tab APIs to capture user interactions during recording.\n\n**Monitored Events:**\n\n| Event Source | Event Type | Recording Behavior |\n|--------------|------------|-------------------|\n| `chrome.webNavigation.onCommitted` | Link navigation | Record if `transitionType === 'link'` |\n| `chrome.webNavigation.onCommitted` | reload/typed/generated | Always record |\n| `chrome.webNavigation.onCommitted` | auto_bookmark/keyword | Record |\n| `chrome.webNavigation.onCommitted` | form_submit | Record for search navigations |\n| `chrome.tabs.onRemoved` | Tab close | Remove from active set |\n| `chrome.tabs.onUpdated` | Status/URL change | Mark navigation event |\n\n**Transition Types Tracked:**\n```typescript\nconst shouldRecord = \n  t === 'reload' ||\n  t === 'typed' ||\n  t === 'generated' ||\n  t === 'auto_bookmark' ||\n  t === 'keyword' ||\n  t === 'form_submit';\n```\n\n资料来源：[browser-event-listener.ts:8-22]()\n\n### Flow Runner\n\nThe flow runner executes recorded flows by iterating through steps and performing the recorded actions.\n\n**Execution Pipeline:**\n1. Load flow from storage by `flowId`\n2. Resolve template variables from execution arguments\n3. Execute steps sequentially\n4. Handle variable assignment between steps\n5. Wait for network idle between navigation steps\n\n**Key Features:**\n- Template variable expansion using `\\{variable\\}` syntax\n- Variable assignment from step outputs via `assign` map\n- Network idle detection for reliable page load waits\n- Support for both DOM-based and programmatic triggers\n\n资料来源：[index.ts:1-50]()\n\n### DOM Trigger System\n\nTriggers enable automatic replay initiation based on DOM element presence or changes.\n\n**Trigger Configuration:**\n```typescript\n{\n  id: string,\n  type: 'dom',\n  enabled: boolean,\n  selector: string,       // CSS selector for target element\n  appear: boolean,        // Trigger on element appearance\n  once: boolean,          // Fire only once per session\n  debounceMs: number      // Default: 800ms\n}\n```\n\n**Trigger Lifecycle:**\n1. Store triggers in `chrome.storage.local` under `STORAGE_KEYS.RR_TRIGGERS`\n2. Inject `dom-observer.js` into target tab\n3. Send trigger configuration via message to injected script\n4. DOM observer monitors for selector matches\n5. On match, initiate flow replay\n\n资料来源：[index.ts:60-85]()\n\n### Utility Functions\n\n**applyAssign**: Maps values from a source object to a target using path notation.\n\n```typescript\napplyAssign(target, source, {\n  'variableName': 'path.to.value',\n  'nested.value': 'data[0].field'\n});\n```\n\n**expandTemplatesDeep**: Recursively expands template variables in any value type.\n\n```typescript\n// Input: \"Navigate to \\{baseUrl\\}/home\"\n// Scope: { baseUrl: 'https://example.com' }\n// Output: \"Navigate to https://example.com/home\"\n```\n\n资料来源：[rr-utils.ts:1-50]()\n\n## Recording Process\n\n### 1. Initialization\n\nWhen recording starts:\n1. Session status transitions to `recording`\n2. Active tab list is initialized\n3. Event listeners are attached to Chrome APIs\n\n### 2. Event Capture\n\n```mermaid\nsequenceDiagram\n    participant U as User\n    participant C as Chrome API\n    participant L as Event Listener\n    participant S as Session\n    \n    U->>C: Click/Type/Navigate\n    C->>L: webNavigation.onCommitted\n    L->>L: Check transition type\n    L->>S: getFlow()\n    S-->>L: Current flow object\n    L->>S: addNavigationStep(url)\n    L->>L: ensureRecorderInjected(tabId)\n    L->>L: broadcastControlToTab(START)\n    S->>S: addActiveTab(tabId)\n```\n\n### 3. Navigation Step Recording\n\nNavigation events are captured with the current tab URL:\n\n```typescript\nconst tab = await chrome.tabs.get(tabId);\nconst url = tab.url || details.url;\nif (flow && url) addNavigationStep(flow, url);\n```\n\n### 4. Script Injection\n\nAfter each navigation, the extension ensures content scripts are injected for replay preparation:\n\n```typescript\nawait ensureCoreInjected(details.tabId);\nawait ensureRecorderInjected(tabId);\nawait broadcastControlToTab(tabId, REC_CMD.START);\n```\n\n## Replay Process\n\n### 1. Flow Loading\n\nFlows are retrieved by ID and validated before execution:\n\n```typescript\nconst flow = await getFlow(t.flowId);\nif (!flow) return;\nawait runFlow(flow, { args: t.args || {}, returnLogs: false });\n```\n\n### 2. Variable Expansion\n\nTemplate variables in flow steps are resolved from the execution arguments:\n\n```typescript\nexpandTemplatesDeep(value, { ...scope, ...args });\n```\n\n### 3. Step Execution\n\nEach step in the flow is executed in topological order, with:\n- Network idle waits between navigation steps\n- DOM query waits for element visibility\n- Error handling for selector mismatches\n\n### 4. Network Idle Detection\n\nThe engine waits for network activity to settle before proceeding:\n\n```typescript\nexport async function waitForNetworkIdle(\n  tabId: number,\n  sniffMs: number = 2000\n): Promise<void>\n```\n\n**Detection Strategy:**\n- Monitor `onCommitted`, `onCompleted`, `onHistoryStateUpdated`\n- Track tab loading status via `tabs.onUpdated`\n- Set timeout for sniff period (default: 2000ms)\n\n资料来源：[wait.ts:1-50]()\n\n## Data Models\n\n### Flow Structure\n\n```typescript\ninterface Flow {\n  id: string;\n  name?: string;\n  steps: Step[];\n  variables?: Record<string, any>;\n  createdAt: number;\n}\n\ninterface Step {\n  id: string;\n  type: 'navigation' | 'interaction' | 'wait';\n  action?: string;\n  selector?: string;\n  url?: string;\n  value?: any;\n  assign?: Record<string, string>;  // Variable assignments\n}\n```\n\n### Trigger Storage\n\n```typescript\ninterface StoredTriggers {\n  triggers: Array<{\n    id: string;\n    type: 'dom' | 'network';\n    enabled: boolean;\n    selector?: string;\n    appear?: boolean;\n    once?: boolean;\n    debounceMs?: number;\n  }>;\n}\n```\n\n## Security Considerations\n\n### Content Security Policy\n\nThe extension enforces strict CSP in production:\n\n```typescript\ncontent_security_policy: {\n  extension_pages: \n    \"script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; \" +\n    \"style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:;\"\n}\n```\n\n### Script Injection Safety\n\n- Scripts are injected only into controlled pages\n- DOM observers use isolated worlds\n- Script injection is preheated only for valid flow replays\n\n## Configuration\n\n### Flow Execution Options\n\n```typescript\ninterface RunFlowOptions {\n  args?: Record<string, string>;      // Template variable values\n  returnLogs?: boolean;               // Include execution logs\n  triggerId?: string;                 // Associated trigger ID\n}\n```\n\n### Recording Commands\n\n```typescript\nenum REC_CMD {\n  START = 'start',      // Begin recording in tab\n  STOP = 'stop',        // End recording in tab\n  PAUSE = 'pause',      // Pause current recording\n  RESUME = 'resume'     // Resume paused recording\n}\n```\n\n## Extension Points\n\n### Custom Event Handlers\n\nThe engine supports extension through the shared utility layer:\n\n```typescript\nimport { TOOL_NAMES, topoOrder, mapNodeToStep } from 'chrome-mcp-shared';\n```\n\n### Policy-Based Waiting\n\nAdditional wait policies can be registered for specialized scenarios:\n\n```typescript\n// In engine/policies/wait.ts\nexport { waitForNetworkIdle };\n```\n\n## Related Components\n\n| Component | Location | Purpose |\n|-----------|----------|---------|\n| DOM Observer | `inject-scripts/dom-observer.js` | Monitors DOM for trigger elements |\n| Web Fetcher | `inject-scripts/web-fetcher-helper.js` | Extracts page content |\n| Element Marker | `inject-scripts/element-marker.js` | Visual element selection UI |\n\n## Usage Example\n\n**Recording a flow:**\n1. Open Chrome DevTools → MCP tab\n2. Click \"Start Recording\"\n3. Perform browser actions (navigate, fill forms, click)\n4. Click \"Stop Recording\"\n5. Flow is saved with captured steps\n\n**Replaying a flow:**\n1. Load saved flow by ID\n2. Optionally provide template variable values\n3. Engine executes steps with network idle waits\n4. Variables are assigned and can be used in subsequent steps\n\n## References\n\n- Chrome Extension webNavigation API: [developer.chrome.com](https://developer.chrome.com/docs/extensions/reference/api/webNavigation)\n- Chrome Extension tabs API: [developer.chrome.com](https://developer.chrome.com/docs/extensions/reference/api/tabs)\n- Chrome.scripting API: [developer.chrome.com](https://developer.chrome.com/docs/extensions/reference/api/scripting)\n\n---\n\n<a id='page-mcp-server'></a>\n\n## MCP Server Implementation\n\n### 相关页面\n\n相关主题：[Communication Protocols](#page-communication), [Browser Tools and APIs](#page-browser-tools), [AI Agent Engines](#page-agent-engines)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/native-server/src/mcp/mcp-server.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/mcp/mcp-server.ts)\n- [app/native-server/src/mcp/register-tools.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/mcp/register-tools.ts)\n- [app/native-server/src/server/index.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/server/index.ts)\n- [app/native-server/src/mcp/mcp-server-stdio.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/mcp/mcp-server-stdio.ts)\n- [app/native-server/src/agent/session-service.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/session-service.ts)\n- [app/native-server/src/agent/engines/claude.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/engines/claude.ts)\n- [app/native-server/src/scripts/doctor.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/scripts/doctor.ts)\n</details>\n\n# MCP Server Implementation\n\n## Overview\n\nThe MCP Server Implementation provides a bridge between AI coding assistants and Chrome browser automation through the Model Context Protocol (MCP). This component enables AI agents to interact with the browser by exposing a comprehensive set of tools for navigation, content extraction, interaction, and network monitoring.\n\n资料来源：[app/native-server/src/mcp/register-tools.ts]()\n\n## Architecture\n\n### System Components\n\nThe MCP Server Implementation consists of four primary components that work together to enable AI-browser interaction:\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| MCP Server Core | `mcp-server.ts` | Core protocol implementation and message handling |\n| Tool Registry | `register-tools.ts` | Tool registration and definition |\n| Stdio Transport | `mcp-server-stdio.ts` | Standard I/O communication layer |\n| Server Entry | `server/index.ts` | Server initialization and lifecycle management |\n\n资料来源：[app/native-server/src/mcp/mcp-server.ts](), [app/native-server/src/mcp/register-tools.ts]()\n\n### Communication Flow\n\n```mermaid\ngraph TD\n    A[AI Client] -->|MCP Protocol| B[Stdio Transport Layer]\n    B --> C[MCP Server Core]\n    C --> D[Tool Registry]\n    D --> E[Chrome Extension]\n    E --> F[Browser Tabs]\n    F -->|Results| E\n    E -->|Tool Results| D\n    D -->|Structured Response| C\n    C -->|JSON-RPC| B\n    B -->|stdout| A\n```\n\n## MCP Server Core\n\nThe core server implementation handles the MCP protocol lifecycle, managing tool invocations, tool results, and resource operations.\n\n资料来源：[app/native-server/src/mcp/mcp-server.ts]()\n\n### Message Handling\n\nThe server processes incoming JSON-RPC requests and dispatches them to appropriate handlers:\n\n```typescript\n// Message dispatch pattern\ndispatchToolMessage(\n  isError\n    ? `Error: ${content || 'Tool execution failed'}`\n    : content || 'Tool completed',\n  metadata,\n  'tool_result',\n  false,\n);\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:50-56]()\n\n### Tool Metadata Building\n\nTool metadata is constructed with full input details to provide context to AI clients:\n\n```typescript\nconst metadata = buildToolMetadata({\n  name: pending.toolName,\n  id: pending.toolId,\n  input,\n});\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:85-89]()\n\n## Tool Categories\n\n### Navigation Tools (7 tools)\n\n| Tool Name | Description | Key Parameters |\n|-----------|-------------|----------------|\n| `chrome_navigate` | Navigate to URLs or perform searches | `url`, `query` |\n| `chrome_go_back_or_forward` | Browser navigation control | `direction` |\n| `chrome_switch_tab` | Switch the current active tab | `tabId` |\n| `chrome_close_tabs` | Close specific tabs or windows | `tabIds`, `windowIds` |\n| `chrome_reload` | Reload current page or tabs | `tabId` |\n| `chrome_inject_script` | Inject content scripts into web pages | `script`, `tabId` |\n| `chrome_send_command_to_inject_script` | Send commands to injected scripts | `command`, `tabId` |\n\n### Interaction Tools (3 tools)\n\n| Tool Name | Description |\n|-----------|-------------|\n| `chrome_click_element` | Click elements using CSS selectors |\n| `chrome_fill_or_select` | Fill forms and select options |\n| `chrome_keyboard` | Simulate keyboard input and shortcuts |\n\n### Data Management (5 tools)\n\n| Tool Name | Description | Parameters |\n|-----------|-------------|------------|\n| `chrome_history` | Search browser history with time filters | `query`, `startTime`, `endTime` |\n| `chrome_bookmark_search` | Find bookmarks by keywords | `query` |\n| `chrome_bookmark_add` | Add new bookmarks with folder support | `url`, `title`, `folder` |\n| `chrome_bookmark_delete` | Delete bookmarks | `bookmarkId` |\n\n### Network Monitoring (4 tools)\n\n| Tool Name | Description | API Used |\n|-----------|-------------|----------|\n| `chrome_network_capture_start/stop` | webRequest API network capture | `chrome.webRequest` |\n| `chrome_network_debugger_start/stop` | Debugger API with response bodies | `chrome.debugger` |\n| `chrome_network_request` | Send custom HTTP requests | `fetch` via background |\n\n### Content Analysis (4 tools)\n\n| Tool Name | Description |\n|-----------|-------------|\n| `search_tabs_content` | AI-powered semantic search across browser tabs |\n| `chrome_get_web_content` | Extract HTML/text content from pages |\n| `chrome_get_interactive_elements` | Find clickable elements |\n| `chrome_console` | Capture and retrieve console output |\n\n### Visual Tools (1 tool)\n\n| Tool Name | Description | Parameters |\n|-----------|-------------|------------|\n| `chrome_screenshot` | Advanced screenshot capture | `element`, `fullPage`, `width`, `height` |\n\n资料来源：[app/native-server/src/mcp/register-tools.ts]()\n\n## Tool Parameter Extraction\n\nThe MCP server extracts structured metadata from tool invocations to provide AI clients with meaningful context:\n\n```typescript\n// Bash/shell - command extraction\nif (normalizedName === 'bash' || normalizedName.includes('shell')) {\n  if (typeof input.command === 'string') {\n    metadata.command = input.command;\n  }\n  if (typeof input.description === 'string') {\n    metadata.commandDescription = input.description;\n  }\n}\n```\n\n### Search Tool Metadata\n\n```typescript\n// Search tools (grep, glob)\nif (normalizedName === 'grep' || normalizedName.includes('search')) {\n  if (typeof input.pattern === 'string') metadata.pattern = input.pattern;\n  if (typeof input.path === 'string') metadata.searchPath = input.path;\n  if (typeof input.glob === 'string') metadata.glob = input.glob;\n  if (typeof input.output_mode === 'string') metadata.outputMode = input.output_mode;\n}\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:120-140]()\n\n## Stdio Transport Layer\n\nThe stdio transport layer handles communication between the MCP server and AI clients through standard input/output streams.\n\n```mermaid\nsequenceDiagram\n    participant AI as AI Client\n    participant Stdio as Stdio Transport\n    participant Server as MCP Server Core\n    participant Chrome as Chrome Extension\n\n    AI->>Stdio: JSON-RPC Request (stdin)\n    Stdio->>Server: Parsed Request\n    Server->>Chrome: Tool Invocation\n    Chrome->>Chrome: Execute in Browser\n    Chrome-->>Server: Tool Result\n    Server-->>Stdio: JSON-RPC Response\n    Stdio-->>AI: stdout Response\n```\n\n资料来源：[app/native-server/src/mcp/mcp-server-stdio.ts]()\n\n### Port Configuration\n\nThe stdio transport requires proper port configuration to communicate with the Chrome extension:\n\n```typescript\nconst url = new URL(configValue.url as string);\nconst port = Number(url.port);\nconst portOk = port === EXPECTED_PORT;\n```\n\n资料来源：[app/native-server/src/scripts/doctor.ts:120-128]()\n\n## Agent Session Integration\n\nThe MCP server integrates with the agent session service to support multi-session environments:\n\n```typescript\nexport interface AgentSessionPreviewMeta {\n  /** Compact display text */\n  displayText?: string;\n  /** Client metadata for special rendering */\n  clientMeta?: {\n    kind?: string;\n    // ...\n  };\n}\n```\n\n### Session Management Configuration\n\n```typescript\nexport interface SessionConfig {\n  mcpServers?: Record<string, unknown>;\n  outputFormat?: Record<string, unknown>;\n  enableFileCheckpointing?: boolean;\n  sandbox?: Record<string, unknown>;\n  env?: Record<string, string>;\n  codexConfig?: Partial<CodexEngineConfig>;\n}\n```\n\n资料来源：[app/native-server/src/agent/session-service.ts:15-35]()\n\n## Claude Engine Integration\n\nThe MCP server works seamlessly with the Claude engine through structured tool result handling:\n\n### Tool Input Parsing\n\n```typescript\n// Parse accumulated JSON input\nconst fullJsonStr = pending.inputJsonParts.join('');\nlet input: Record<string, unknown> = {};\ntry {\n  if (fullJsonStr) {\n    input = JSON.parse(fullJsonStr);\n  }\n} catch (e) {\n  console.error(`[ClaudeEngine] Failed to parse tool input JSON: ${e}`);\n}\n```\n\n### Content Preview Extraction\n\n```typescript\n// Write tool - content preview\nif (normalizedName.includes('write') || normalizedName === 'create_file') {\n  if (typeof input.content === 'string') {\n    metadata.contentPreview = input.content.slice(0, 200);\n    metadata.totalLines = input.content.split('\\n').length;\n  }\n}\n\n// Read tool - offset/limit\nif (normalizedName.includes('read')) {\n  if (typeof input.offset === 'number') metadata.offset = input.offset;\n  if (typeof input.limit === 'number') metadata.limit = input.limit;\n}\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:90-110]()\n\n## Chrome Extension Communication\n\nThe MCP server communicates with the Chrome extension through a defined message protocol:\n\n```mermaid\ngraph LR\n    A[MCP Server] -->|chrome.runtime.sendMessage| B[Background Script]\n    B --> C[Content Scripts]\n    C -->|DOM Access| D[Web Pages]\n    B -->|Tabs API| E[Browser Tabs]\n```\n\n### Web Accessible Resources\n\nThe extension exposes necessary resources for tool execution:\n\n```typescript\nweb_accessible_resources: [\n  {\n    resources: [\n      '/models/*',        // AI models\n      '/workers/*',       // Web workers\n      '/inject-scripts/*' // Content script helpers\n    ],\n    matches: ['<all_urls>'],\n  },\n]\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts]()\n\n## Error Handling\n\nThe MCP server implements comprehensive error handling:\n\n### Error Detection Patterns\n\n```typescript\nconst isError =\n  meta.is_error === true ||\n  meta.isError === true ||\n  (typeof msg.content === 'string' && msg.content.trimStart().startsWith('Error:'));\n```\n\n### Tool Severity Classification\n\n| Condition | Severity |\n|-----------|----------|\n| `isError` is true | `error` |\n| Tool execution successful | `success` |\n| Tool execution in progress | `info` |\n\n## Configuration Management\n\n### Environment-Specific Security\n\n```typescript\n...(IS_DEV\n  ? {}\n  : {\n      cross_origin_embedder_policy: { value: 'require-corp' as const },\n      cross_origin_opener_policy: { value: 'same-origin' as const },\n      content_security_policy: {\n        extension_pages:\n          \"script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:;\",\n      },\n    })\n```\n\n资料来源：[app/chrome-extension/wxt.config.ts]()\n\n## Diagnostic Tools\n\nThe MCP server includes diagnostic capabilities:\n\n| Check ID | Title | Purpose |\n|----------|-------|---------|\n| `port.config` | Port config | Verify stdio-config.json port |\n| `port.constant` | Port constant | Verify native server port constant |\n\n### Doctor Script Output\n\n```typescript\nchecks.push({\n  id: 'port.config',\n  title: 'Port config',\n  status: portOk ? 'ok' : 'error',\n  message: configValue.url as string,\n  details: {\n    expectedPort: EXPECTED_PORT,\n    actualPort: port,\n    fix: portOk ? undefined : [`${COMMAND_NAME} update-port ${EXPECTED_PORT}`],\n  },\n});\n```\n\n资料来源：[app/native-server/src/scripts/doctor.ts:130-145]()\n\n## Summary\n\nThe MCP Server Implementation provides a robust bridge between AI coding assistants and Chrome browser automation. Key features include:\n\n- **Protocol Compliance**: Full MCP protocol implementation with JSON-RPC message handling\n- **Comprehensive Tools**: 24+ tools covering navigation, interaction, data management, network monitoring, and content analysis\n- **Structured Metadata**: Rich tool result metadata for AI context understanding\n- **Flexible Transport**: Stdio-based communication for easy integration with various AI clients\n- **Security**: Environment-aware security policies and proper isolation\n- **Debugging**: Built-in diagnostic capabilities for troubleshooting connectivity issues\n\n---\n\n<a id='page-agent-engines'></a>\n\n## AI Agent Engines\n\n### 相关页面\n\n相关主题：[MCP Server Implementation](#page-mcp-server), [Browser Tools and APIs](#page-browser-tools)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/native-server/src/agent/engines/claude.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/engines/claude.ts)\n- [app/native-server/src/agent/engines/codex.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/engines/codex.ts)\n- [app/native-server/src/agent/tool-bridge.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/tool-bridge.ts)\n- [app/native-server/src/agent/chat-service.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/chat-service.ts)\n- [packages/shared/src/agent-types.ts](https://github.com/hangwin/mcp-chrome/blob/main/packages/shared/src/agent-types.ts)\n</details>\n\n# AI Agent Engines\n\n## Overview\n\nThe AI Agent Engines system is a core architectural component of the MCP Chrome project that provides an abstraction layer for interacting with different LLM (Large Language Model) backends. This module enables the browser extension to leverage various AI providers (Claude, Codex) for intelligent automation, workflow execution, and browser control.\n\nThe engine system follows a unified interface pattern, allowing seamless switching between different AI providers while maintaining consistent behavior for tool execution, message handling, and state management.\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:1-50]()\n资料来源：[app/native-server/src/agent/engines/codex.ts:1-50]()\n\n## Architecture\n\n### System Components\n\n```mermaid\ngraph TD\n    A[Chat Service] --> B[Tool Bridge]\n    B --> C[Claude Engine]\n    B --> D[Codex Engine]\n    C --> E[Claude API]\n    D --> F[Codex API]\n    E --> G[Stream Events]\n    F --> G\n    G --> H[Tool Dispatcher]\n    H --> I[Browser/Tools]\n```\n\n### Supported Engines\n\n| Engine | Provider | Status | Primary Use Case |\n|--------|----------|--------|------------------|\n| Claude | Anthropic | Active | General AI assistance, code generation |\n| Codex | OpenAI | Active | Code-focused tasks, GitHub integration |\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:1-30]()\n资料来源：[app/native-server/src/agent/engines/codex.ts:1-30]()\n\n## Engine Interface\n\n### Base Capabilities\n\nAll agent engines implement a common interface that handles:\n\n- **Message Streaming**: Real-time event streaming from AI providers\n- **Tool Execution**: Routing tool calls to appropriate handlers\n- **Content Parsing**: Processing multi-modal content blocks\n- **Error Handling**: Graceful error management and recovery\n\n### Event Processing\n\nThe engines process events through a unified event loop:\n\n```mermaid\nsequenceDiagram\n    participant API as AI API\n    participant Engine as Agent Engine\n    participant Bridge as Tool Bridge\n    participant Browser as Browser/Tools\n    \n    API->>Engine: content_block_start\n    Engine->>Engine: accumulateToolInput()\n    API->>Engine: content_block_delta\n    Engine->>Engine: parseToolInput()\n    API->>Engine: content_block_stop\n    Engine->>Bridge: dispatchToolMessage()\n    Bridge->>Browser: executeTool()\n    Browser->>Bridge: toolResult\n    Bridge->>Engine: forwardResult\n    Engine->>API: streamResponse\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:50-120]()\n资料来源：[app/native-server/src/agent/engines/codex.ts:50-100]()\n\n## Claude Engine\n\n### Overview\n\nThe Claude Engine (`claude.ts`) implements the Anthropic Claude API integration, handling streaming responses and tool execution through the Claude Messages API.\n\n### Core Features\n\n**Content Block Handling**\n\nThe engine processes different content block types:\n\n- `content_block_start`: Initializes tool input accumulation\n- `content_block_delta`: Accumulates tool input JSON chunks\n- `content_block_stop`: Finalizes and parses accumulated tool input\n\n**Tool Result Processing**\n\n```typescript\n// Extract tool result content from content blocks\nconst extractToolResultContent = (contentBlock) => {\n  if (contentBlock.type === 'tool_result') {\n    return contentBlock.content?.text || null;\n  }\n  return null;\n};\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:80-100]()\n\n**Error Handling**\n\nThe engine detects errors through multiple indicators:\n\n| Error Indicator | Source | Priority |\n|-----------------|--------|----------|\n| `is_error: true` | API response | High |\n| `isError: true` | Metadata | High |\n| Content starts with \"Error:\" | Message content | Medium |\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:40-60]()\n\n### Metadata Building\n\nThe Claude engine constructs comprehensive tool metadata:\n\n```typescript\nconst buildToolMetadata = ({\n  name: pending.toolName,\n  id: pending.toolId,\n  input,\n}) => {\n  // Returns structured metadata for tool invocation\n};\n```\n\n资料来源：[app/native-server/src/agent/engines/claude.ts:100-130]()\n\n## Codex Engine\n\n### Overview\n\nThe Codex Engine (`codex.ts`) integrates with OpenAI's Codex API, providing specialized handling for code-related tasks and GitHub integration.\n\n### Core Features\n\n**Tool Message Dispatch**\n\nThe engine implements a sophisticated tool dispatching system:\n\n```typescript\nconst dispatchToolMessage = (\n  content: string,\n  metadata: Record<string, unknown>,\n  type: string,\n  isUpdate: boolean\n) => {\n  // Dispatches tool execution results with metadata\n};\n```\n\n资料来源：[app/native-server/src/agent/engines/codex.ts:30-60]()\n\n**Todo List Management**\n\nThe Codex engine includes specialized support for task tracking:\n\n```mermaid\ngraph LR\n    A[Agent Response] --> B[emitTodoListUpdate]\n    B --> C{Phase}\n    C -->|started| D[Tool Use Event]\n    C -->|update| D\n    C -->|completed| E[Tool Result Event]\n    \n    F[Raw Items] --> G[normalizeTodoListItems]\n    G --> H[buildTodoListContent]\n```\n\n**Item Event Types**\n\n| Event Type | Handler | Output |\n|------------|---------|--------|\n| `command_execution` | `emitCommandStart` | Command start message |\n| `todo_list` | `emitTodoListUpdate` | Todo list state |\n| `agent_message` | Text extraction | Text content |\n\n资料来源：[app/native-server/src/agent/engines/codex.ts:60-100]()\n\n**Command Execution Tracking**\n\n```typescript\nconst emitCommandStart = (record: Record<string, unknown>) => {\n  const command = this.pickFirstString(record.command);\n  const description = this.pickFirstString(record.description);\n  // Emits command start event for UI tracking\n};\n```\n\n资料来源：[app/native-server/src/agent/engines/codex.ts:40-50]()\n\n## Tool Bridge Integration\n\n### Purpose\n\nThe Tool Bridge (`tool-bridge.ts`) acts as the intermediary between agent engines and actual tool implementations, providing:\n\n- **Tool Routing**: Directs tool calls to appropriate handlers\n- **Parameter Transformation**: Converts engine-specific formats to tool formats\n- **Result Formatting**: Standardizes tool responses for engines\n\n### Tool Execution Flow\n\n```mermaid\ngraph LR\n    A[Engine Tool Call] --> B[Tool Bridge]\n    B --> C{toolId match?}\n    C -->|Yes| D[Execute Tool]\n    C -->|No| E[Error Handler]\n    D --> F[Format Result]\n    E --> G[Error Response]\n    F --> H[Return to Engine]\n```\n\n## Chat Service Coordination\n\n### Service Layer\n\nThe Chat Service (`chat-service.ts`) orchestrates the interaction between user interfaces and agent engines:\n\n```mermaid\ngraph TD\n    A[User Request] --> B[Chat Service]\n    B --> C[Select Engine]\n    C --> D[Claude or Codex]\n    D --> E[Stream Events]\n    E --> F[Tool Bridge]\n    F --> G[Execute Tools]\n    G --> H[Return Results]\n    H --> E\n    E --> I[User Response]\n```\n\n### Message Handling\n\nAll engines communicate through a standardized message format defined in `agent-types.ts`:\n\n| Field | Type | Description |\n|-------|------|-------------|\n| `content` | string | Message text content |\n| `metadata` | object | Engine-specific metadata |\n| `type` | string | Message type (tool_use, tool_result, etc.) |\n| `isUpdate` | boolean | Whether this is an incremental update |\n\n资料来源：[packages/shared/src/agent-types.ts:1-50]()\n\n## Common Patterns\n\n### Tool Input Accumulation\n\nBoth engines implement a similar pattern for handling streaming tool inputs:\n\n1. **Start**: Initialize input accumulator on `content_block_start`\n2. **Delta**: Append JSON chunks on `content_block_delta`\n3. **Stop**: Parse complete JSON on `content_block_stop`\n\n```typescript\n// Pseudocode for accumulation pattern\nconst pendingToolInputs = new Map<number, PendingInput>();\n\nfunction handleContentBlockStart(index, toolName, toolId) {\n  pendingToolInputs.set(index, {\n    toolName,\n    toolId,\n    inputJsonParts: []\n  });\n}\n\nfunction handleContentBlockDelta(index, chunk) {\n  const pending = pendingToolInputs.get(index);\n  if (pending) {\n    pending.inputJsonParts.push(chunk);\n  }\n}\n```\n\n### Error Detection Strategy\n\nEngines use a layered error detection approach:\n\n| Layer | Check | Action |\n|-------|-------|--------|\n| 1 | `is_error` flag | Immediate error |\n| 2 | `isError` flag | Error from metadata |\n| 3 | Content prefix | Parse \"Error:\" prefix |\n\n### Severity Classification\n\nTool execution results are classified by severity:\n\n| Severity | Trigger | Visual Indicator |\n|----------|---------|------------------|\n| `error` | Error detected | Red highlight |\n| `success` | Tool completed | Green checkmark |\n| `info` | In progress | Neutral/informational |\n\n## Configuration\n\n### Engine Selection\n\nEngines are selected based on:\n\n- User preference/settings\n- Task requirements (code vs. general)\n- API availability\n\n### Environment Variables\n\n| Variable | Engine | Purpose |\n|----------|--------|---------|\n| `ANTHROPIC_API_KEY` | Claude | Authentication |\n| `OPENAI_API_KEY` | Codex | Authentication |\n| `API_BASE_URL` | Both | Endpoint configuration |\n\n## Extension Points\n\n### Adding New Engines\n\nTo add a new engine:\n\n1. Create engine file in `engines/` directory\n2. Implement common interface methods\n3. Register in engine factory/registry\n4. Add tool handlers in Tool Bridge\n\n### Custom Tool Handlers\n\nTool handlers can be extended by:\n\n1. Implementing handler in `tool-bridge.ts`\n2. Registering handler in tool registry\n3. Adding type definitions in `agent-types.ts`\n\n## Best Practices\n\n### Error Handling\n\n- Always check multiple error indicators\n- Provide meaningful error messages\n- Log errors with context for debugging\n\n### Streaming\n\n- Handle partial content gracefully\n- Accumulate tool inputs properly\n- Update UI incrementally\n\n### Resource Management\n\n- Clean up pending inputs after processing\n- Limit retry attempts for failed calls\n- Monitor API rate limits\n\n## Related Documentation\n\n- [Chrome Extension Architecture](../architecture.md)\n- [Tool System](../tools/overview.md)\n- [API Reference](../api/reference.md)\n\n---\n\n<a id='page-storage'></a>\n\n## Storage and Data Management\n\n### 相关页面\n\n相关主题：[Chrome Extension Structure](#page-extension-structure), [Record and Replay Engine](#page-record-replay)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [app/chrome-extension/entrypoints/background/record-replay/storage/indexeddb-manager.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/storage/indexeddb-manager.ts)\n- [app/chrome-extension/entrypoints/background/record-replay/storage/flows.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/record-replay/storage/flows.ts)\n- [app/native-server/src/agent/db/client.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/db/client.ts)\n- [app/native-server/src/agent/db/schema.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/db/schema.ts)\n- [app/chrome-extension/utils/content-indexer.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/utils/content-indexer.ts)\n- [app/native-server/src/agent/session-service.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/native-server/src/agent/session-service.ts)\n- [app/chrome-extension/entrypoints/background/semantic-similarity.ts](https://github.com/hangwin/mcp-chrome/blob/main/app/chrome-extension/entrypoints/background/semantic-similarity.ts)\n</details>\n\n# Storage and Data Management\n\n## Overview\n\nThe mcp-chrome project implements a dual-layer storage architecture that separates concerns between the Chrome Extension (client-side) and the Native Server (server-side). This design enables the extension to operate independently for recording, replaying, and managing browser-related data while delegating persistent storage of agent sessions and workflows to the native backend.\n\n资料来源：[app/native-server/src/agent/db/client.ts:1-50]()\n\nThe storage system handles several key data domains:\n\n| Data Domain | Storage Layer | Primary Use |\n|-------------|---------------|-------------|\n| Recording Flows | IndexedDB | Browser session recording and replay |\n| Semantic Index | chrome.storage.local | Content indexing and similarity search |\n| Agent Sessions | SQLite (better-sqlite3) | Persistent agent workflow management |\n| Model State | chrome.storage.local | ML model download and status tracking |\n| Tab Content | IndexedDB | Web page content caching |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/storage/flows.ts:1-30]()\n资料来源：[app/native-server/src/agent/session-service.ts:1-80]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    subgraph ChromeExtension[\"Chrome Extension\"]\n        A[IndexedDB] -->|Flow Recording| B[indexeddb-manager.ts]\n        C[chrome.storage.local] -->|Settings & State| D[Background Scripts]\n        E[Semantic Engine] -->|Indexing| F[content-indexer.ts]\n    end\n    \n    subgraph NativeServer[\"Native Server\"]\n        G[SQLite Database] -->|Sessions| H[db/client.ts]\n        I[Schema Definitions] -->|Tables| G\n        J[Session Service] -->|CRUD| H\n    end\n    \n    K[MCP Protocol] -->|Communication| L[Native Messaging]\n    \n    B -->|Storage Ops| A\n    F -->|Cache| C\n    H -->|Async Queries| G\n    J -->|Session Mgmt| H\n```\n\n资料来源：[app/native-server/src/agent/db/schema.ts:1-100]()\n\n## Chrome Extension Storage\n\n### IndexedDB Manager\n\nThe IndexedDB manager (`indexeddb-manager.ts`) provides structured access to browser-native storage for recording flows and session data.\n\n#### Core Operations\n\n| Method | Purpose |\n|--------|---------|\n| `initialize()` | Open/create IndexedDB database |\n| `getFlow(id)` | Retrieve a recording flow by ID |\n| `getAllFlows()` | List all stored flows |\n| `saveFlow(flow)` | Persist a new or updated flow |\n| `deleteFlow(id)` | Remove a flow from storage |\n| `clearAll()` | Wipe all stored data |\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/storage/indexeddb-manager.ts:1-150]()\n\n#### Database Schema\n\n```typescript\ninterface FlowRecord {\n  id: string;\n  name: string;\n  createdAt: number;\n  updatedAt: number;\n  steps: FlowStep[];\n  triggers?: TriggerConfig[];\n  args?: Record<string, unknown>;\n}\n```\n\nThe IndexedDB schema supports:\n- **Flows**: Complete recording sessions with metadata\n- **Steps**: Individual navigation and interaction steps\n- **Triggers**: DOM-based or URL-based automation triggers\n- **Args**: Configuration parameters for flow execution\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/storage/flows.ts:1-50]()\n\n### Flow Storage Module\n\nThe `flows.ts` module wraps the IndexedDB manager with higher-level operations for flow management.\n\n```mermaid\ngraph LR\n    A[Recording Start] --> B[Create Flow Record]\n    B --> C[Capture Events]\n    C --> D[Append Steps]\n    D --> E[Trigger Detection]\n    E --> F[Save to IndexedDB]\n    F --> G[Recording Complete]\n```\n\n#### Flow Lifecycle\n\n1. **Creation**: Initialize a new flow with timestamp and metadata\n2. **Capture**: Record DOM events, network requests, and navigation\n3. **Trigger Binding**: Associate DOM selectors or URL patterns\n4. **Persistence**: Batch write to IndexedDB on completion or intervals\n5. **Retrieval**: Load flows for replay with full state reconstruction\n\n资料来源：[app/chrome-extension/entrypoints/background/record-replay/storage/flows.ts:50-150]()\n\n### chrome.storage.local Usage\n\nThe extension uses Chrome's `storage.local` API for lightweight, synchronous state management:\n\n```typescript\n// Model state tracking\nconst modelState = {\n  status: string;\n  downloadProgress: number;\n  isDownloading: boolean;\n  lastUpdated: number;\n  errorMessage: string;\n  errorType: 'network' | 'file' | 'unknown';\n};\n\n// Semantic engine state\nconst semanticEngineState = {\n  isReady: boolean;\n  isInitializing: boolean;\n  modelPath?: string;\n};\n```\n\n资料来源：[app/chrome-extension/entrypoints/background/semantic-similarity.ts:1-80]()\n\n#### Storage Keys\n\n| Key | Type | Purpose |\n|-----|------|---------|\n| `modelState` | Object | ML model download status |\n| `semanticEngineState` | Object | Content indexing engine status |\n| `RR_TRIGGERS` | Array | Record-replay DOM triggers |\n| `contentIndex` | Object | Cached page content metadata |\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:1-60]()\n\n## Native Server Database\n\n### Database Client\n\nThe native server uses `better-sqlite3` for synchronous, high-performance SQLite access.\n\n```typescript\nimport Database from 'better-sqlite3';\n\nclass AgentDatabase {\n  private db: Database.Database;\n  \n  constructor(dbPath: string);\n  initialize(): void;\n  close(): void;\n  // ... query methods\n}\n```\n\n资料来源：[app/native-server/src/agent/db/client.ts:1-80]()\n\n#### Configuration\n\n| Parameter | Default | Description |\n|-----------|---------|-------------|\n| `dbPath` | `~/.claude/mcp-chrome.db` | SQLite database file path |\n| WAL Mode | Enabled | Write-Ahead Logging for concurrency |\n| Foreign Keys | Enabled | Referential integrity enforcement |\n\n资料来源：[app/native-server/src/agent/db/client.ts:80-120]()\n\n### Database Schema\n\n```mermaid\nerDiagram\n    SESSIONS {\n        string id PK\n        string name\n        string description\n        string engine\n        timestamp created_at\n        timestamp updated_at\n        json metadata\n    }\n    \n    MESSAGES {\n        string id PK\n        string session_id FK\n        string role\n        text content\n        timestamp created_at\n        json attachments\n        json raw\n    }\n    \n    MESSAGES }o--|| SESSIONS : belongs_to\n```\n\n#### Sessions Table\n\n| Column | Type | Constraints | Description |\n|--------|------|-------------|-------------|\n| `id` | TEXT | PRIMARY KEY | Unique session identifier |\n| `name` | TEXT | NOT NULL | Display name for session |\n| `description` | TEXT | | Session description |\n| `engine` | TEXT | | AI engine (claude, codex, etc.) |\n| `created_at` | INTEGER | NOT NULL | Unix timestamp |\n| `updated_at` | INTEGER | NOT NULL | Last modification time |\n| `metadata` | TEXT | | JSON-encoded metadata |\n\n资料来源：[app/native-server/src/agent/db/schema.ts:1-100]()\n\n#### Messages Table\n\n| Column | Type | Constraints | Description |\n|--------|------|-------------|-------------|\n| `id` | TEXT | PRIMARY KEY | Message UUID |\n| `session_id` | TEXT | FOREIGN KEY | Parent session reference |\n| `role` | TEXT | NOT NULL | Message role (user/assistant/system) |\n| `content` | TEXT | | Message text content |\n| `created_at` | INTEGER | NOT NULL | Timestamp |\n| `attachments` | TEXT | | JSON array of attachments |\n| `raw` | TEXT | | Raw metadata JSON |\n\n资料来源：[app/native-server/src/agent/db/schema.ts:100-200]()\n\n### Session Service\n\nThe session service provides the high-level interface for session and message management:\n\n```typescript\nexport interface ManagementInfo {\n  models?: Array<{ value: string; displayName: string; description: string }>;\n  commands?: Array<{ name: string; description: string; argumentHint: string }>;\n  account?: { email?: string; organization?: string; subscriptionType?: string };\n  mcpServers?: Array<{ name: string; status: string }>;\n  tools?: string[];\n  agents?: string[];\n  plugins?: Array<{ name: string; path?: string }>;\n  skills?: string[];\n  slashCommands?: string[];\n  model?: string;\n  permissionMode?: string;\n  cwd?: string;\n  outputStyle?: string;\n  betas?: string[];\n  claudeCodeVersion?: string;\n  apiKeySource?: string;\n  lastUpdated?: string;\n}\n```\n\n资料来源：[app/native-server/src/agent/session-service.ts:30-70]()\n\n#### Session Preview Metadata\n\n```typescript\nexport interface AgentSessionPreviewMeta {\n  displayText?: string;  // Compact display text\n  clientMeta?: {\n    kind?: 'web_editor_apply_batch' | 'web_editor_apply_single';\n    elementCount?: number;\n  };\n}\n```\n\nThis metadata enables special UI rendering for web editor apply operations.\n\n资料来源：[app/native-server/src/agent/session-service.ts:75-90]()\n\n## Content Indexing System\n\n### ContentIndexer Class\n\nThe content indexer manages semantic search capabilities for browser tab content:\n\n```typescript\nclass ContentIndexer {\n  private options: IndexerOptions;\n  private semanticEngine: SemanticEngine;\n  \n  async indexTabContent(tabId: number): Promise<void>;\n  async removeTabIndex(tabId: number): Promise<void>;\n  private shouldIndexUrl(url: string): boolean;\n  private async extractTabContent(tabId: number): Promise<ContentResult>;\n}\n```\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:20-80]()\n\n### URL Filtering\n\nCertain URLs are automatically excluded from indexing:\n\n| Pattern | Reason |\n|---------|--------|\n| `chrome://*` | Chrome internal pages |\n| `chrome-extension://*` | Extension pages |\n| `edge://*` | Edge internal pages |\n| `about:*` | Browser about pages |\n| `moz-extension://*` | Firefox extension pages |\n| `file://*` | Local file system |\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:50-70]()\n\n### Auto-Indexing Behavior\n\n```mermaid\ngraph TD\n    A[Tab Load Complete] --> B{URL Valid?}\n    B -->|No| C[Skip Indexing]\n    B -->|Yes| D{Engine Ready?}\n    D -->|No| E[Wait 2 seconds]\n    E --> D\n    D -->|Yes| F[Execute Fetcher Script]\n    F --> G[Extract Page Content]\n    G --> H[Update Semantic Index]\n    H --> I[Store in IndexedDB]\n```\n\nThe auto-indexing is triggered with a 2-second delay to allow dynamic content to load.\n\n资料来源：[app/chrome-extension/utils/content-indexer.ts:10-40]()\n\n## Data Flow Summary\n\n### Recording Flow\n\n```mermaid\nsequenceDiagram\n    participant U as User\n    participant E as Extension\n    participant IDB as IndexedDB\n    participant NS as Native Server\n    \n    U->>E: Start Recording\n    E->>IDB: Create Flow Record\n    loop User Actions\n        E->>E: Capture Event\n        E->>IDB: Append Step\n    end\n    U->>E: Stop Recording\n    E->>IDB: Finalize Flow\n    E->>NS: Sync Flow Metadata\n```\n\n### Replay Flow\n\n```mermaid\nsequenceDiagram\n    participant T as Trigger\n    participant E as Extension\n    participant IDB as IndexedDB\n    participant B as Browser\n    \n    T->>E: Trigger Matched\n    E->>IDB: Load Flow\n    loop Flow Steps\n        E->>E: Process Step\n        E->>B: Execute Action\n    end\n```\n\n## Error Handling\n\nBoth storage layers implement robust error handling:\n\n| Layer | Error Strategy |\n|-------|----------------|\n| IndexedDB | Graceful degradation, console logging |\n| chrome.storage | Fallback messaging to background script |\n| SQLite | Transaction rollback, WAL recovery |\n| Network sync | Retry with exponential backoff |\n\n资料来源：[app/chrome-extension/entrypoints/offscreen/main.ts:40-80]()\n\n## Best Practices\n\n1. **Batch Writes**: Group multiple IndexedDB operations to reduce I/O\n2. **Index Maintenance**: Periodically clean stale tab indices\n3. **Transaction Scope**: Keep SQLite transactions short to prevent locks\n4. **Memory Management**: Release DOM references after content extraction\n5. **Storage Quotas**: Monitor chrome.storage.local usage for extension limits\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：hangwin/mcp-chrome\n\n摘要：发现 16 个潜在踩坑项，其中 2 个为 high/blocking；最高优先级：安装坑 - 来源证据：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint。\n\n## 1. 安装坑 · 来源证据：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ba76885913a744f0832665f5c62d0f1d | https://github.com/hangwin/mcp-chrome/issues/321 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed to connect to MCP server)\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed to connect to MCP server)\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4ac5f778b292489482bfdb7953190f96 | https://github.com/hangwin/mcp-chrome/issues/319 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 3. 安装坑 · 来源证据：Codex CLI setup guide still points to ~/.codex/config.json and a port-only flow Codex does not pick up\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Codex CLI setup guide still points to ~/.codex/config.json and a port-only flow Codex does not pick up\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_559f34b86ade48e598dac510e9341b9e | https://github.com/hangwin/mcp-chrome/issues/339 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 4. 安装坑 · 来源证据：[Feature] Profile-aware bridge — multi-Chrome-profile support without port collision\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature] Profile-aware bridge — multi-Chrome-profile support without port collision\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_93bfb3c85fbc4c0a8134e7159ddf4511 | https://github.com/hangwin/mcp-chrome/issues/347 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 5. 安装坑 · 来源证据：mcp-chrome-bridge 无法使用\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：mcp-chrome-bridge 无法使用\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5f19fb6526174af2abe5c1eab67e25ff | https://github.com/hangwin/mcp-chrome/issues/333 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 6. 安装坑 · 来源证据：🐛 Status indicator stuck on yellow - Service shows as \"not started\" after connection\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：🐛 Status indicator stuck on yellow - Service shows as \"not started\" after connection\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2b32536c95a7456788ba78e1fc705116 | https://github.com/hangwin/mcp-chrome/issues/342 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 7. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | host_targets=mcp_host, claude\n\n## 8. 能力坑 · 能力判断依赖假设\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:998796026 | https://github.com/hangwin/mcp-chrome | README/documentation is current enough for a first validation pass.\n\n## 9. 运行坑 · 来源证据：v0.0.6\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.0.6\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_035dffafcbe64f4ea112f20258430e71 | https://github.com/hangwin/mcp-chrome/releases/tag/v0.0.6 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 10. 维护坑 · 来源证据：[Feature/Bug] Multi-client MCP support — second Claude Code session kills first via shared MCP Server singleton\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[Feature/Bug] Multi-client MCP support — second Claude Code session kills first via shared MCP Server singleton\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4d4eaf47bd284105af5632bbe220b628 | https://github.com/hangwin/mcp-chrome/issues/345 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 11. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | last_activity_observed missing\n\n## 12. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | no_demo; severity=medium\n\n## 13. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | no_demo; severity=medium\n\n## 14. 安全/权限坑 · 来源证据：issue\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：issue\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_82ad93635a5e4ff5aeb2b35e36cbd02e | https://github.com/hangwin/mcp-chrome/issues/330 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\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:998796026 | https://github.com/hangwin/mcp-chrome | 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:998796026 | https://github.com/hangwin/mcp-chrome | release_recency=unknown\n\n<!-- canonical_name: hangwin/mcp-chrome; 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项目：hangwin/mcp-chrome\n\n摘要：发现 16 个潜在踩坑项，其中 2 个为 high/blocking；最高优先级：安装坑 - 来源证据：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint。\n\n## 1. 安装坑 · 来源证据：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Bug: Singleton McpServer causes 'Already connected to a transport' on HTTP endpoint\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ba76885913a744f0832665f5c62d0f1d | https://github.com/hangwin/mcp-chrome/issues/321 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 2. 安装坑 · 来源证据：Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed to connect to MCP server)\n\n- 严重度：high\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Opencode cannot use chrome-mcp via mcp-server-stdio on Windows (Failed to connect to MCP server)\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4ac5f778b292489482bfdb7953190f96 | https://github.com/hangwin/mcp-chrome/issues/319 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 3. 安装坑 · 来源证据：Codex CLI setup guide still points to ~/.codex/config.json and a port-only flow Codex does not pick up\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Codex CLI setup guide still points to ~/.codex/config.json and a port-only flow Codex does not pick up\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_559f34b86ade48e598dac510e9341b9e | https://github.com/hangwin/mcp-chrome/issues/339 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 4. 安装坑 · 来源证据：[Feature] Profile-aware bridge — multi-Chrome-profile support without port collision\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：[Feature] Profile-aware bridge — multi-Chrome-profile support without port collision\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_93bfb3c85fbc4c0a8134e7159ddf4511 | https://github.com/hangwin/mcp-chrome/issues/347 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 5. 安装坑 · 来源证据：mcp-chrome-bridge 无法使用\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：mcp-chrome-bridge 无法使用\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5f19fb6526174af2abe5c1eab67e25ff | https://github.com/hangwin/mcp-chrome/issues/333 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。\n\n## 6. 安装坑 · 来源证据：🐛 Status indicator stuck on yellow - Service shows as \"not started\" after connection\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：🐛 Status indicator stuck on yellow - Service shows as \"not started\" after connection\n- 对用户的影响：可能影响升级、迁移或版本选择。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_2b32536c95a7456788ba78e1fc705116 | https://github.com/hangwin/mcp-chrome/issues/342 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\n\n## 7. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | host_targets=mcp_host, claude\n\n## 8. 能力坑 · 能力判断依赖假设\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:998796026 | https://github.com/hangwin/mcp-chrome | README/documentation is current enough for a first validation pass.\n\n## 9. 运行坑 · 来源证据：v0.0.6\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.0.6\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_035dffafcbe64f4ea112f20258430e71 | https://github.com/hangwin/mcp-chrome/releases/tag/v0.0.6 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 10. 维护坑 · 来源证据：[Feature/Bug] Multi-client MCP support — second Claude Code session kills first via shared MCP Server singleton\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：[Feature/Bug] Multi-client MCP support — second Claude Code session kills first via shared MCP Server singleton\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_4d4eaf47bd284105af5632bbe220b628 | https://github.com/hangwin/mcp-chrome/issues/345 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 11. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | last_activity_observed missing\n\n## 12. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | no_demo; severity=medium\n\n## 13. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | github_repo:998796026 | https://github.com/hangwin/mcp-chrome | no_demo; severity=medium\n\n## 14. 安全/权限坑 · 来源证据：issue\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：issue\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_82ad93635a5e4ff5aeb2b35e36cbd02e | https://github.com/hangwin/mcp-chrome/issues/330 | 来源讨论提到 node 相关条件，需在安装/试用前复核。\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:998796026 | https://github.com/hangwin/mcp-chrome | 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:998796026 | https://github.com/hangwin/mcp-chrome | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# mcp-chrome - 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 hangwin/mcp-chrome.\n\nProject:\n- Name: mcp-chrome\n- Repository: https://github.com/hangwin/mcp-chrome\n- Summary: Chrome MCP Server is a Chrome extension-based Model Context Protocol (MCP) server that exposes your Chrome browser functionality to AI assistants like Claude, enabling complex browser automation, content analysis, and semantic search.\n- Host target: mcp_host, claude\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: Chrome MCP Server is a Chrome extension-based Model Context Protocol (MCP) server that exposes your Chrome browser functionality to AI assistants like Claude, enabling complex browser automation, content analysis, and semantic search.\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: Chrome MCP Server is a Chrome extension-based Model Context Protocol (MCP) server that exposes your Chrome browser functionality to AI assistants like Claude, enabling complex browser automation, content analysis, and semantic search.\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. page-introduction: Introduction to Chrome MCP Server. Produce one small intermediate artifact and wait for confirmation.\n2. page-quickstart: Quick Start Guide. Produce one small intermediate artifact and wait for confirmation.\n3. page-architecture: System Architecture. Produce one small intermediate artifact and wait for confirmation.\n4. page-communication: Communication Protocols. Produce one small intermediate artifact and wait for confirmation.\n5. page-extension-structure: Chrome Extension Structure. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/hangwin/mcp-chrome\n- https://github.com/hangwin/mcp-chrome#readme\n- README.md\n- app/chrome-extension/manifest.json\n- app/chrome-extension/README.md\n- app/native-server/README.md\n- docs/ARCHITECTURE.md\n- app/chrome-extension/common/message-types.ts\n- app/native-server/src/index.ts\n- app/chrome-extension/entrypoints/background/native-host.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项目：hangwin/mcp-chrome\n\n## 官方安装入口\n\n### Node.js / npm · 官方安装入口\n\n```bash\nnpm install -g mcp-chrome-bridge\n```\n\n来源：https://github.com/hangwin/mcp-chrome#readme\n\n## 来源\n\n- repo: https://github.com/hangwin/mcp-chrome\n- docs: https://github.com/hangwin/mcp-chrome#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_a6d83c5a87334dad90fad29e067b04a9"
}
