什么是模型上下文协议(MCP)

Model Context Protocol(模型上下文协议)是一个开源的标准,用于将人工智能应用与外部系统连接起来。

通过MCP,像Claude或ChatGPT这样的AI应用可以连接数据源(如本地文件,数据库)、工具(如搜索引擎,计算器)和工作流程(如专门提示)-使它们能够访问关键信息并执行任务。

Playwright MCP

1、安装

1、直接使用npx(不用全局安装)

前提:node版本20或更晚

MCP客户端:MCP Client、VS Code、Claude Code

1
npx @playwright/mcp@latest

官方推荐配置:

1
2
3
4
5
6
7
8
9
10
{
"mcpServers": {
"playwright":{
"command":"npx",
"args":[
"@playwright/mcp@latest"
]
}
}
}

2、全局安装

1
npm install -g @playwright/mcp

检查:

1
playwright-mcp --version

Python 调用

1、安装Python MCP

1
python -m pip install mcp

它是Anthropic提出的MCP(Model Context Protocol, 模型上下文协议)的Python实现。

Python的mcp库主要用于:

1、开发MCP Server(给AI提供工具)

2、开发MCP Client(让Python Agent调用MCP工具)

3、连接外部MCP服务(例如Playwright MCP,数据库 MCP,文件MCP)

官方SDK支持创建Server、Client、以及Stdio、SSE、Streamable HTTP等通信方式。

通过python mcp实现playwright MCP工具调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from mcp import ClientSession

from mcp.client.stdio import (stdio_client,stdioServerParameters)
"""
启动playwright MCP服务
"""
params = StdioServerParameters(
command="npx",
args=[
"@playwright/mcp@latest"
]
)

async def run():
async with stdio_client(params) as (read, write): #创建client与MCP服务之间的通信,通信方式是stdio_client
async with ClientSession(read,write) as session: #创建MCP Session
await session.initialize() #初始化playwright MCP 会话

result = await session.call_tool(
"browser_navigate",
{
"url":"https://www.baidu.com"
}
) #调用Tool

tools_result = await session.list_tools()

for tool in tools_result.tools:
print("工具名称:",tool.name)
print("工具参数:",tool.input_schema)

AI Agent结合Playwright MCP可实现自动化测试或AI Agent结合pytest+Playwright,届时多元化的技术融合,一种依赖LLM辅助自动化测试的全新面孔。