news 2026/3/23 6:24:39

【原创】使用langchain与MCP 与 Chrome DevTools 打造可调用浏览器工具的 Chat Agent

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
【原创】使用langchain与MCP 与 Chrome DevTools 打造可调用浏览器工具的 Chat Agent

本文介绍如何搭建基于Chrome开发者工具多客户端协议(MCP)的智能对话代理。通过整合chrome-devtools-mcp和LangChain框架,实现了自动注册MCP工具、支持Ollama/OpenAI双模型后端、异步非阻塞运行的Chat Agent。文章详细说明了环境配置方法,包括Chrome调试模式启动命令和Node.js环境准备,并提供了可直接运行的Python完整代码。该代理支持网页操作指令如打开网页、截图和网络请求分析等功能,通过LangGraph构建状态图实现对话流程管理。代码展示了模型绑定、工具自动发现和异步交互的实现方式,为开发者提供了开箱即用的MCP集成方案。


效果


简介 ✨

本文示例展示了一个稳定的 MCP Chat Agent:

  • 自动注册并绑定 MCP 工具(无需手动查找工具)
  • 支持Ollama / OpenAI两种模型
  • 异步运行,不会阻塞主线程

下面是使用前的准备和代码说明。


环境与准备 🔧

  1. 启动 Chrome(带远程调试端口):
    macOS
/Applications/Google\Chrome.app/Contents/MacOS/Google\Chrome --remote-debugging-port=9222--user-data-dir=/tmp/chrome-profile-stable

Linux

/usr/bin/google-chrome --remote-debugging-port=9222--user-data-dir=/tmp/chrome-profile-stable

Windows

"C:\Program Files\Google\Chrome\Application\chrome.exe"--remote-debugging-port=9222--user-data-dir="%TEMP%\chrome-profile-stable"

要安装node环境

npx -y chrome-devtools-mcp@latest --browser-url=http://127.0.0.1:9222

请确保 Chrome 已用--remote-debugging-port=9222启动,且npx -y chrome-devtools-mcp@latest能单独运行。

  1. Python 环境需要安装对应依赖(示例中使用的包有langchain_ollama,langchain_openai,langchain_mcp_adapters,langgraph等)。

完整代码(可直接保存并运行)

下面是new_chat_agent.py的完整代码:

#!/usr/bin/env python3""" 最终稳定版 MCP Chat Agent - 自动注册 MCP 工具(无需手动找) - 支持 Ollama / OpenAI 二选一 - 不会阻塞 / 不会 silent """importasynciofromtypingimportAnnotated,TypedDictfromlangchain_ollamaimportChatOllamafromlangchain_openaiimportChatOpenAIfromlangchain_mcp_adapters.clientimportMultiServerMCPClientfromlanggraph.graphimportStateGraph,STARTfromlanggraph.prebuiltimportToolNode,tools_conditionfromlanggraph.checkpoint.memoryimportMemorySaverfromlanggraph.graph.messageimportadd_messages# ================== 配置 ==================OPENAI_API_KEY="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"OPENAI_API_BASE="https://dashscope.aliyuncs.com/compatible-mode/v1"classState(TypedDict):messages:Annotated[list,add_messages]classMCPAgent:def__init__(self,backend:str="ollama"):print("🚀 初始化 MCPAgent",flush=True)# -------- 模型选择 --------ifbackend=="ollama":self.llm=ChatOllama(model="qwen2.5:7b",temperature=0.7,)print("🔹 使用 Ollama",flush=True)else:self.llm=ChatOpenAI(model="qwen3-30b-a3b-instruct-2507",temperature=0.7,api_key=OPENAI_API_KEY,base_url=OPENAI_API_BASE,)print("🔹 使用 OpenAI API",flush=True)# -------- MCP 工具(关键)--------print("🔄 连接 chrome-devtools-mcp(不会阻塞)",flush=True)client=MultiServerMCPClient({"chrome":{"transport":"stdio","command":"npx","args":["-y","chrome-devtools-mcp@latest","--browser-url=http://127.0.0.1:9222",],}})# ⚠️ get_tools 是唯一需要等的地方self.tools=asyncio.run(client.get_tools())ifnotself.tools:raiseRuntimeError("❌ MCP 工具为空,请确认 Chrome 是否启动")print(f"✅ 已自动注册{len(self.tools)}个 MCP 工具",flush=True)# ⭐ 核心:直接 bind_tools,不要自己管工具self.llm=self.llm.bind_tools(self.tools)# -------- LangGraph --------self.graph=self._build_graph()self.history=[]def_agent(self,state:State):return{"messages":[self.llm.invoke(state["messages"])]}def_build_graph(self):g=StateGraph(State)g.add_node("agent",self._agent)g.add_node("tools",ToolNode(self.tools))g.add_edge(START,"agent")g.add_conditional_edges("agent",tools_condition)g.add_edge("tools","agent")returng.compile(checkpointer=MemorySaver())asyncdefrun(self):print("\n🤖 MCP Chat Agent 已启动",flush=True)print("示例:",flush=True)print(" 打开 https://www.baidu.com",flush=True)print(" 截图当前页面",flush=True)print(" 列出 network 里的 JSON 请求\n",flush=True)whileTrue:user=input("你: ").strip()ifuserin("exit","quit"):breakself.history.append(("user",user))asyncforeventinself.graph.astream_events({"messages":self.history},config={"configurable":{"thread_id":"default"}},version="v2",):ifevent["event"]=="on_chat_model_stream":chunk=event["data"]["chunk"]ifchunk.content:print(chunk.content,end="",flush=True)elifevent["event"]=="on_tool_start":print(f"\n🛠️ 调用工具:{event['name']}",flush=True)elifevent["event"]=="on_tool_end":print("\n✅ 工具执行完成",flush=True)print()# ================== 启动 ==================if__name__=="__main__":try:choice=input("选择模型(1=Ollama,2=OpenAI):").strip()backend="ollama"ifchoice!="2"else"openai"agent=MCPAgent(backend=backend)asyncio.run(agent.run())exceptExceptionase:print(f"\n❌ 启动失败:{e}",flush=True)print("\n排查顺序:",flush=True)print("1. Chrome 是否用 --remote-debugging-port=9222 启动",flush=True)print("2. npx -y chrome-devtools-mcp@latest 是否能单独运行",flush=True)print("3. node / npm 是否正常",flush=True)

关键点解析 💡

  • 自动注册 MCP 工具:通过MultiServerMCPClient(...).get_tools()自动发现并注册 chrome-devtools-mcp 提供的工具集合。
  • 绑定工具到 LLM:使用self.llm.bind_tools(self.tools),让 LLM 可以直接以工具调用的方式操控浏览器。
  • LangGraph 驱动:使用StateGraphToolNode管理对话和工具调用的流程,并以MemorySaver做检查点。
  • 运行模式:交互式命令行会持续接收用户输入,并以事件流打印模型输出与工具调用状态。

使用示例 🧪

  1. 启动 Chrome(见上文命令)。
  2. 运行脚本:
python new_chat_agent.py

  1. 根据提示选择模型(1=Ollama,2=OpenAI),然后在命令行输入如:
打开 https://www.baidu.com 截图当前页面 列出 network 里的 JSON 请求

Agent 会根据工具能力返回结果并在终端打印执行过程。

参考:
https://github.com/ChromeDevTools/chrome-devtools-mcp


如果本文对你有帮助,欢迎点赞 + 关注,你的关注是我持续更新的最大动力 🙏

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/3/15 13:09:30

C++ RAII封装结构体成员变量自动加锁性能开销分析

在C中通过RAII(Resource Acquisition Is Initialization)机制封装结构体成员变量的自动加锁/解锁操作,其性能开销需从锁机制成本、编译器优化空间、运行时场景适配三个维度进行系统性分析: 一、RAII加锁封装的核心机制 以典型实现…

作者头像 李华
网站建设 2026/3/23 16:05:50

6款AI论文降重神器实操教程:AI率从72%降至13%

一、AI论文降重工具快速对比:哪款最适合你? 作为学生或科研人员,你是否曾遇到以下痛点: 用ChatGPT写的论文AI检测率高达70%,被导师打回重写?降重时逐句改写,耗时又容易破坏逻辑?找…

作者头像 李华
网站建设 2026/3/21 1:45:38

我用 XinServer 做了个文件系统,比想象简单

我用 XinServer 做了个文件系统,比想象简单 最近有个朋友找我帮忙,说他们团队想做个内部文件管理系统,让不同部门的同事能上传、下载、共享文档,还要有权限控制。他问我:“这个后端大概要搞多久?我们前端倒…

作者头像 李华
网站建设 2026/3/13 15:00:12

救命神器2026TOP9AI论文写作软件:本科生毕业论文必备测评

救命神器2026TOP9AI论文写作软件:本科生毕业论文必备测评 2026年AI论文写作软件测评:为什么你需要这份榜单? 随着人工智能技术的不断进步,AI论文写作工具已经成为本科生撰写毕业论文时不可或缺的辅助工具。然而,市面上…

作者头像 李华
网站建设 2026/3/23 8:12:10

hal_uart_transmit支持多协议切换的控制系统设计方案

基于hal_uart_transmit的多协议动态切换系统设计:从理论到实战在嵌入式控制系统中,我们常常面临一个看似简单却极具挑战的现实问题:如何让一块MCU通过同一个UART接口,与使用不同通信协议的多个外设稳定“对话”?比如&a…

作者头像 李华
网站建设 2026/3/18 8:29:24

微博开源模型实战:VibeThinker-1.5B WEBUI界面使用详解

微博开源模型实战:VibeThinker-1.5B WEBUI界面使用详解 1. 引言 1.1 业务场景描述 随着大模型在数学推理与代码生成领域的广泛应用,如何在有限算力条件下实现高效、低成本的推理能力成为中小团队和开发者关注的核心问题。微博近期开源的 VibeThinker-…

作者头像 李华