MCP关键字搜索服务器
基于FastAPI的MCP(模型上下文协议)服务器,提供用于在文件中搜索的关键字搜索工具。
特性
- 关键字搜索:使用行号和出现次数在文本文件中搜索关键字
- 区分大小写:在区分大小写和不区分大小写的搜索之间切换
- RESTful API:简单的HTTP端点,便于集成
- 错误处理:处理丢失的文件、非文本文件和无效路径
- 交互式文档:内置Swagger UI用于测试
设置
# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt用法
启动服务器:
python server.py服务器运行于 http://127.0.0.1:8000
测试服务器(在另一个终端中):
python test_client.pyAPI终点
发布 /search
在文件中搜索关键字并获取所有匹配的行。
请求正文:
{
"file_path": "example.txt",
"keyword": "python",
"case_sensitive": false
}答复:
{
"file_path": "example.txt",
"keyword": "python",
"total_matches": 5,
"matches": [
{
"line_number": 2,
"content": "Python is a popular programming language.",
"occurrences": 1
}
]
}参数:
file_path(string,必填):要搜索的文件的路径keyword(字符串,必填):要搜索的关键字case_sensitive(布尔值,可选):启用区分大小写的搜索(默认值:false)
响应字段:
file_path:搜索的文件路径keyword:搜索的关键字total_matches:包含关键字的行数matches:具有行号、内容和出现次数的匹配行数组
获取 /health
运行状况检查端点以验证服务器状态。
答复:
{
"status": "healthy"
}获取 /
具有服务器信息的根终结点。
例子
使用curl:
curl -X POST http://127.0.0.1:8000/search \
-H "Content-Type: application/json" \
-d '{"file_path": "example.txt", "keyword": "python", "case_sensitive": false}'使用Python:
import requests
response = requests.post(
"http://127.0.0.1:8000/search",
json={
"file_path": "example.txt",
"keyword": "python",
"case_sensitive": False
}
)
result = response.json()
print(f"Found {result['total_matches']} matches")测试
这 test_client.py 脚本演示了各种搜索场景:
- 不区分大小写的搜索
- 区分大小写的搜索
- 不同的关键字
- 丢失文件的错误处理
在服务器运行时运行它以查看示例输出。
错误响应
- 404:在指定路径中找不到文件
- 400:文件路径无效或文件无法以文本形式读取
- 500:处理文件时发生内部服务器错误
文档
交互式API文档可在以下网址获取:
- Swagger用户界面:
http://127.0.0.1:8000/docs - 重新记录:
http://127.0.0.1:8000/redoc
项目结构
mcp-keyword-search/
├── server.py # Main FastAPI server
├── test_client.py # Test script with examples
├── example.txt # Sample file for testing
├── requirements.txt # Python dependencies
└── README.md # This file