这是一个基于 Locust 进行负载测试的模型上下文协议 (MCP) 服务器实现,它实现了 Locust 负载测试功能与 AI 驱动开发环境的无缝集成,能帮助用户高效开展负载测试工作。
在开始之前,请确保安装以下内容:
git clone https://github.com/qainsights/locust-mcp-server.git
uv pip install -r requirements.txt
.env 文件:LOCUST_HOST=http://localhost:8089 # 测试默认主机
LOCUST_USERS=3 # 默认用户数
LOCUST_SPAWN_RATE=1 # 用户生成率
LOCUST_RUN_TIME=10s # 默认测试时长
创建一个 Locust 测试脚本(例如 hello.py):
from locust import HttpUser, task, between
class QuickstartUser(HttpUser):
wait_time = between(1, 5)
@task
def hello_world(self):
self.client.get("/hello")
self.client.get("/world")
@task(3)
def view_items(self):
for item_id in range(10):
self.client.get(f"/item?id={item_id}", name="/item")
time.sleep(1)
def on_start(self):
self.client.post("/login", json={"username":"foo", "password":"bar"})
使用以下配置在您的首选 MCP 客户端(Claude Desktop、Cursor、Windsurf 等)中配置 MCP 服务器:
{
"mcpServers": {
"locust": {
"command": "/Users/naveenkumar/.local/bin/uv",
"args": [
"--directory",
"/Users/naveenkumar/Gits/locust-mcp-server",
"run",
"locust_server.py"
]
}
}
}
现在让大语言模型运行测试,例如:运行 locust 测试以分析 hello.py。Locust MCP 服务器将使用以下工具来启动测试:
run_locust:根据配置选项运行测试(包括无头模式、主机、时长、用户数和生成率)from locust import HttpUser, task, between
class QuickstartUser(HttpUser):
wait_time = between(1, 5)
@task
def hello_world(self):
self.client.get("/hello")
self.client.get("/world")
@task(3)
def view_items(self):
for item_id in range(10):
self.client.get(f"/item?id={item_id}", name="/item")
time.sleep(1)
def on_start(self):
self.client.post("/login", json={"username":"foo", "password":"bar"})
# 这里可以根据不同的使用场景,对测试脚本进行更复杂的配置,如添加更多任务、调整参数等
# 例如,可以创建多个不同的 HttpUser 类,每个类代表不同的用户行为
from locust import HttpUser, task, between
class AdvancedUser1(HttpUser):
wait_time = between(2, 6)
@task
def special_task1(self):
self.client.get("/special/endpoint1")
class AdvancedUser2(HttpUser):
wait_time = between(3, 7)
@task
def special_task2(self):
self.client.get("/special/endpoint2")
run_locust(
test_file: str,
headless: bool = True,
host: str = "http://localhost:8089",
runtime: str = "10s",
users: int = 3,
spawn_rate: int = 1
)
参数说明:
test_file:Locust 测试脚本的路径headless:是否以无头模式(True)或有图形界面(False)运行host:默认测试主机地址runtime:默认测试时长users:默认用户数spawn_rate:用户生成率⚠️ 重要提示
- 确保安装的 Python 版本符合要求(3.13 或更高)。
- 在运行高负载测试时,建议监控系统资源使用情况。
- 如果遇到性能问题,请考虑优化代码或增加硬件资源。
通过以上步骤,您可以轻松配置和运行基于 Locust 的负载测试,并将其集成到 AI 驱动的开发环境中。