SearchAPI MCP服务器
  
一个生产就绪的模型上下文协议(MCP)服务器,通过SearchAPI.io提供全面的搜索功能。通过内置缓存、重试逻辑和断路器,使AI助手能够搜索谷歌、地图、航班、酒店等。
一个基于 Model Context Protocol (MCP) 的生产级搜索服务器,通过 SearchAPI.io 提供全面的搜索功能。使 AI 助手能够搜索 Google、地图、航班、酒店等,内置缓存、重试逻辑和熔断器。
______________________________________________________________________
特性
🔍 搜索引擎
- 谷歌搜索 -网络结果、知识图谱、答案框、相关问题
- 谷歌视频 -按持续时间、来源和上传时间过滤的视频搜索
- 谷歌人工智能模式 -人工智能生成的概述,包括引用的来源和结构化内容
- 谷歌地图 -地点、企业、评论和位置详细信息
- 谷歌地图地点 -具体地点的详细信息(时间、照片、设施)
- 谷歌活动 -查找音乐会、会议、节日和当地活动
- 谷歌航班 -通过全面过滤和价格日历进行航班搜索
- 谷歌航班位置搜索 -机场代码查找和自动完成
- 谷歌旅游探索 -探索目的地和旅行灵感
- 谷歌酒店 -使用设施、评级和价格过滤器搜索住宿
🏗️ 生产就绪架构
- 连接池 -使用httpx进行高效的HTTP连接管理
- 响应缓存 -可配置的基于TTL的缓存,带有LRU驱逐功能
- 重试逻辑 -瞬态故障的指数回退
- 断路器 -防止级联故障的故障安全模式
- 指标收集 -请求计数、延迟、缓存命中率、错误跟踪
- 健康检查 -监控API连接和服务状态
⚙️ 配置和监控
- Pydantic验证 -支持环境变量的类型安全配置
- 结构化日志记录 -可配置的日志级别,具有详细的请求跟踪功能
- 资源管理 -自动清理和优雅关机
- 环境变量 -针对不同部署的灵活配置
______________________________________________________________________
快速开始
先决条件
- Python 3.10或更高版本
- SearchAPI.io API键(在这里买一个)
紫外线安装(推荐)
最快的入门方法是使用 uvx:
# Set your API key
export SEARCHAPI_API_KEY="your_api_key_here"
# Run directly with uvx (no installation needed)
uvx --from git+https://github.com/RmMargt/searchAPI-mcp.git mcp-server-searchapi______________________________________________________________________
安装
方法1:UV(推荐)
紫外线是最快、最方便的方法:
# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh
# Clone the repository
git clone https://github.com/RmMargt/searchAPI-mcp.git
cd searchAPI-mcp
# Install dependencies
uv pip install -r requirements.txt方法2:pip
# Clone the repository
git clone https://github.com/RmMargt/searchAPI-mcp.git
cd searchAPI-mcp
# Create and activate virtual environment
python -m venv venv
source venv/bin/activate # On Windows: .\venv\Scripts\activate
# Install dependencies
pip install -r requirements.txt方法3:来源
git clone https://github.com/RmMargt/searchAPI-mcp.git
cd searchAPI-mcp
# Using uv
uv pip install httpx fastmcp python-dotenv pydantic pydantic-settings
# Or using pip
pip install httpx fastmcp python-dotenv pydantic pydantic-settings______________________________________________________________________
配置
环境变量
创建一个 .env 项目根目录中的文件:
# Required
SEARCHAPI_API_KEY=your_api_key_here
# Optional - API Configuration
SEARCHAPI_API_URL=https://www.searchapi.io/api/v1/search
TIMEOUT=30.0
MAX_RETRIES=3
RETRY_BACKOFF=1.0
# Optional - Cache Configuration
ENABLE_CACHE=true
CACHE_TTL=3600
CACHE_MAX_SIZE=1000
# Optional - Connection Pool
POOL_CONNECTIONS=10
POOL_MAXSIZE=10
# Optional - Monitoring
ENABLE_METRICS=true
LOG_LEVEL=INFOMCP客户端配置
克劳德桌面
添加到您的Claude Desktop配置文件中:
地点:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - 窗户:
%APPDATA%\Claude\claude_desktop_config.json - Linux:
~/.config/Claude/claude_desktop_config.json
使用紫外线(推荐):
{
"mcpServers": {
"searchapi": {
"command": "uvx",
"args": [
"--directory",
"/absolute/path/to/searchAPI-mcp",
"python",
"mcp_server_refactored.py"
],
"env": {
"SEARCHAPI_API_KEY": "your_api_key_here"
}
}
}
}直接使用Python:
{
"mcpServers": {
"searchapi": {
"command": "python",
"args": [
"/absolute/path/to/searchAPI-mcp/mcp_server_refactored.py"
],
"env": {
"SEARCHAPI_API_KEY": "your_api_key_here"
}
}
}
}使用虚拟环境:
{
"mcpServers": {
"searchapi": {
"command": "/absolute/path/to/searchAPI-mcp/venv/bin/python",
"args": [
"/absolute/path/to/searchAPI-mcp/mcp_server_refactored.py"
],
"env": {
"SEARCHAPI_API_KEY": "your_api_key_here"
}
}
}
}VS代码(继续,点击)
增添 .vscode/mcp.json 在您的工作区中,或使用“MCP:打开用户配置”命令:
{
"servers": {
"searchapi": {
"command": "python",
"args": [
"/absolute/path/to/searchAPI-mcp/mcp_server_refactored.py"
],
"env": {
"SEARCHAPI_API_KEY": "your_api_key_here"
}
}
}
}使用紫外线:
{
"servers": {
"searchapi": {
"command": "uvx",
"args": [
"--directory",
"/absolute/path/to/searchAPI-mcp",
"python",
"mcp_server_refactored.py"
],
"env": {
"SEARCHAPI_API_KEY": "your_api_key_here"
}
}
}
}Zed编辑
增添 ~/.config/zed/settings.json:
{
"context_servers": {
"searchapi": {
"command": {
"path": "python",
"args": [
"/absolute/path/to/searchAPI-mcp/mcp_server_refactored.py"
],
"env": {
"SEARCHAPI_API_KEY": "your_api_key_here"
}
}
}
}
}Cline(VS代码扩展)
在临床设置中,向MCP服务器添加:
{
"mcpServers": {
"searchapi": {
"command": "python",
"args": [
"/absolute/path/to/searchAPI-mcp/mcp_server_refactored.py"
],
"env": {
"SEARCHAPI_API_KEY": "your_api_key_here"
}
}
}
}通用MCP客户端
对于任何兼容MCP的客户端:
# Using stdio transport (default)
python /path/to/searchAPI-mcp/mcp_server_refactored.py
# With environment variable
SEARCHAPI_API_KEY=your_key python mcp_server_refactored.py______________________________________________________________________
可用工具
健康与监测
health_check
检查SearchAPI服务的运行状况和性能。
退货:
- API连接状态
- 响应延迟
- 断路器状态
- 缓存统计
- 请求度量值
例子:
{
"api_status": {
"status": "healthy",
"latency_ms": 145.23,
"circuit_breaker": "closed"
},
"cache_stats": {
"size": 42,
"max_size": 1000,
"ttl": 3600
},
"metrics": {
"request_count": 156,
"error_count": 2,
"cache_hit_rate": 0.67
}
}______________________________________________________________________
时间和日期实用程序
get_current_time
获取当前时间和旅行日期建议。对于航班和酒店预订至关重要。
参数:
format-日期格式:“iso”、“斜线”、“中文”、“时间戳”、“完整”days_offset-从今天开始的天数(可以是负数)return_future_dates-返回未来日期数组future_days-未来日期数(如果return_future_dates=true)
例子:
# Get today's date in ISO format
get_current_time(format="iso")
# Returns: {"date": "2025-11-16", "now": {...}, "travel_dates": {...}}
# Get date 7 days from now with future dates array
get_current_time(days_offset=7, return_future_dates=True, future_days=30)______________________________________________________________________
谷歌搜索
search_google
在谷歌上搜索网络结果、知识图表和答案框。
参数:
q(必填)-搜索查询location-地点名称(例如,“纽约州纽约市”)gl-国家代码(默认:“us”)hl-语言代码(默认:“en”)time_period-时间过滤器:“last_hour”、“last_day”、“last_week”、“last \_month”、“last_year”num-每页结果(默认值:“10”)safe-安全搜索:“关闭”、“活动”
例子:
search_google(
q="Python programming tutorials",
location="San Francisco, CA",
time_period="last_month",
num="20"
)search_google_videos
在谷歌视频中搜索视频内容。
参数: 类似于 search_google 带有视频专用过滤器
q(必填)-搜索查询time_period-按上传时间筛选device-“桌面”或“移动”
例子:
search_google_videos(
q="machine learning tutorial",
time_period="last_week",
num="10"
)search_google_ai_mode
使用人工智能生成的概述和引用的来源进行搜索。
参数:
q-搜索查询(除非提供url,否则为必填项)url-要搜索的图像URLlocation-本地化结果的位置
退货:
- 人工智能生成的带有引文的概述
- 结构化内容块(段落、列表、表格、代码)
- 参考链接
- Web结果
例子:
search_google_ai_mode(
q="How does machine learning work?",
location="United States"
)______________________________________________________________________
谷歌地图
search_google_maps
搜索地点、企业和服务。
参数:
query(必填)-搜索查询location_ll-纬度/lng坐标(格式:“@Lat,lng,zoom”)
例子:
search_google_maps(
query="coffee shops near Central Park",
location_ll="@40.7829,-73.9654,15z"
)search_google_maps_place
获取特定地点的详细信息。
参数:
place_id(如果没有data_id,则需要)-谷歌地图地点iddata_id-备选地点标识符google_domain-谷歌域名(默认:“Google.com”)hl-语言代码(默认:“en”)
例子:
search_google_maps_place(
place_id="ChIJN1t_tDeuEmsRUsoyG83frY4"
)search_google_maps_reviews
获取特定地点的评论。
参数:
place_id(如果没有data_id,则需要)-谷歌地图地点iddata_id-备选地点标识符sort_by-“最相关”、“最新”、“最高评级”、“最低评级”rating-按等级筛选:“1”-“5”
例子:
search_google_maps_reviews(
place_id="ChIJN1t_tDeuEmsRUsoyG83frY4",
sort_by="newest",
rating="5"
)______________________________________________________________________
谷歌活动
search_google_events
搜索活动、音乐会、会议和活动。
参数:
q(必填)-搜索查询(例如,“纽约音乐会”、“技术会议”)location-本地化结果的位置名称chips-日期过滤器(“今天”、“明天”、“周”、“周末”、“月”)或事件类型gl-国家代码(默认:“us”)hl-语言代码(默认:“en”)page-页码(默认值:“1”)
例子:
search_google_events(
q="music festivals in Austin",
chips="weekend",
location="Austin, TX"
)______________________________________________________________________
谷歌航班
search_google_flights
通过全面过滤搜索航班。
参数:
departure_id(必填)-机场代码(例如“JFK”)arrival_id(必填)-机场代码(例如“LAX”)outbound_date(必填)-出发日期(YYYY-MM-DD)flight_type-“单程”、“往返”、“多城市”return_date-返回日期(往返需要)travel_class-“经济”、“溢价经济”、”商业”、“第一”stops-“0”(不间断)、“1”、“2”adults-成年人人数currency-货币代码(例如“USD”)
例子:
search_google_flights(
departure_id="JFK",
arrival_id="LAX",
outbound_date="2025-12-15",
return_date="2025-12-22",
flight_type="round_trip",
travel_class="economy",
stops="0",
adults="2"
)search_google_flights_calendar
获取价格日历,以便灵活规划日期。
参数:
flight_type(必填)-“单程”或“往返”departure_id(必填)-机场代码arrival_id(必填)-机场代码outbound_date(必填)-参考日期return_date-往返需要
例子:
search_google_flights_calendar(
flight_type="round_trip",
departure_id="SFO",
arrival_id="NYC",
outbound_date="2025-12-01",
return_date="2025-12-08"
)search_google_flights_location_search
搜索机场代码和位置。
参数:
q(必填)-搜索查询(机场名称、城市或代码)gl-国家代码(默认:“us”)hl-语言代码(默认:“en”)
例子:
search_google_flights_location_search(
q="Tokyo"
)search_google_travel_explore
探索旅游目的地,寻找灵感。
参数:
departure_id(必填)-出发机场代码或位置arrival_id-目的地(默认为任何地方)time_period-旅行时间(例如,“双周旅行”)interests-按兴趣筛选:“流行”、“户外”、“海滩”、“博物馆”、“历史”、“滑雪”travel_class-“经济”、“优质经济”、”商业”、“一流”adults-成年人数量(默认值:“1”)currency-货币代码(默认值:“USD”)
例子:
search_google_travel_explore(
departure_id="JFK",
interests="beaches",
time_period="two_week_trip_in_december"
)______________________________________________________________________
谷歌酒店
search_google_hotels
搜索酒店和住宿。
参数:
q(必填)-位置查询check_in_date(必填)-入住日期(YYYY-MM-DD)check_out_date(必填)-退房日期(YYYY-MM-DD)adults-成年人数量(默认值:“2”)rating-最低评级:“3”、“4”、“5”hotel_class-星级:“2”-“5”price_min/price_max-价格范围amenities-按设施过滤(例如,“游泳池、wifi、停车场”)free_cancellation-“真”或“假”
例子:
search_google_hotels(
q="hotels in Paris",
check_in_date="2025-12-20",
check_out_date="2025-12-25",
adults="2",
rating="4",
amenities="wifi,pool",
price_max="300",
free_cancellation="true"
)search_google_hotels_property
获取特定酒店的详细信息。
参数:
property_token(必填)-搜索结果中的物业IDcheck_in_date(必填)-入住日期check_out_date(必填)-退房日期adults-成年人人数
例子:
search_google_hotels_property(
property_token="ChIJd8BlQ2BZwokRAFUEcm_qrcA",
check_in_date="2025-12-20",
check_out_date="2025-12-25",
adults="2"
)______________________________________________________________________
用法示例
示例1:发现并计划旅行
# 1. Explore destinations from New York
destinations = search_google_travel_explore(
departure_id="JFK",
interests="beaches",
time_period="two_week_trip_in_december"
)
# 2. Get current date and travel dates
dates = get_current_time(return_future_dates=True, future_days=30)
check_in = dates["travel_dates"]["next_week"]
check_out = dates["travel_dates"]["next_month"]
# 3. Search for flights
flights = search_google_flights(
departure_id="JFK",
arrival_id="CDG",
outbound_date=check_in,
return_date=check_out,
flight_type="round_trip",
travel_class="economy",
adults="2"
)
# 4. Search for hotels
hotels = search_google_hotels(
q="hotels in Paris",
check_in_date=check_in,
check_out_date=check_out,
adults="2",
rating="4",
amenities="wifi,breakfast"
)
# 5. Find nearby restaurants
restaurants = search_google_maps(
query="restaurants near Eiffel Tower"
)
# 6. Get detailed place info
place_details = search_google_maps_place(
place_id=restaurants["local_results"][0]["place_id"]
)
# 7. Find local events
events = search_google_events(
q="concerts in Paris",
chips="weekend"
)示例2:使用AI模式进行研究
# Get AI-generated overview with sources
result = search_google_ai_mode(
q="What are the health benefits of Mediterranean diet?",
location="United States"
)
# Result includes:
# - result["markdown"] - AI overview in markdown format
# - result["text_blocks"] - Structured content blocks
# - result["reference_links"] - Cited sources
# - result["web_results"] - Traditional search results示例3:监控服务运行状况
# Check API health and metrics
health = health_check()
print(f"Status: {health['api_status']['status']}")
print(f"Latency: {health['api_status']['latency_ms']}ms")
print(f"Cache hit rate: {health['metrics']['cache_hit_rate']:.2%}")
print(f"Total requests: {health['metrics']['request_count']}")______________________________________________________________________
发展
运行测试
# Run all tests
python -m pytest
# Run specific test file
python test_refactored.py编码结构
searchAPI-mcp/
├── mcp_server_refactored.py # Main MCP server with FastMCP
├── config.py # Configuration with Pydantic validation
├── client.py # HTTP client with pooling, retry, caching
├── requirements.txt # Python dependencies
├── .env.example # Example environment variables
└── tests/ # Test files关键组件
- mcp_server_refactored.py -使用FastMCP实现MCP服务器
- 具有全面文档字符串的工具定义 - 健康检查和监控端点 - 清洁停机和资源管理
- config.py -配置管理
- 用于类型安全配置的Pydantic模型 - 环境变量验证 - 具有覆盖选项的合理默认值
- 客户端.py -生产就绪HTTP客户端
- 使用httpx进行连接池 - 指数退避重试逻辑 - 基于TTL的响应缓存 - 断路器型式 - 指标收集
调试
使用MCP检查器测试工具:
# Install inspector
npm install -g @modelcontextprotocol/inspector
# Run inspector
npx @modelcontextprotocol/inspector python mcp_server_refactored.py设置详细日志记录的环境变量:
LOG_LEVEL=DEBUG python mcp_server_refactored.py______________________________________________________________________
故障排除
常见问题
问题:“无效的API密钥”错误
- 解决方案:确保
SEARCHAPI_API_KEY在环境或.env文件中设置正确 - 在获取API密钥https://www.searchapi.io/
问题:“断路器打开”错误
- 原因:API连续故障过多
- 解决方案:检查您的互联网连接和API密钥。等待60秒电路重置,或重新启动服务器
问题:连接超时
- 解决方案:增加.env中的超时时间:
TIMEOUT=60.0 - 检查SearchAPI.io的网络连接
问题:高延迟
- 解决方案:启用缓存(如果禁用):
ENABLE_CACHE=true - 增加缓存大小:
CACHE_MAX_SIZE=5000 - 检查
health_check度量工具
问题:Windows编码错误
- 解决方案:在MCP客户端配置中设置环境变量:
"env": {
"PYTHONIOENCODING": "utf-8",
"SEARCHAPI_API_KEY": "your_key"
}获取帮助
- 检查 MCP文件
- 审查 SearchAPI.io文档
- 打开一个问题
______________________________________________________________________
性能调整
缓存配置
要获得更高的缓存命中率:
CACHE_TTL=7200 # 2 hours
CACHE_MAX_SIZE=5000 # Store more results对于内存受限的环境:
CACHE_TTL=1800 # 30 minutes
CACHE_MAX_SIZE=100 # Smaller cache连接池
对于高流量场景:
POOL_CONNECTIONS=50
POOL_MAXSIZE=50对于低流量场景:
POOL_CONNECTIONS=5
POOL_MAXSIZE=5______________________________________________________________________
安全考虑
⚠️ 重要安全注意事项:
- API密钥保护
- 永不承诺 .env 文件到版本控制 - 在生产中使用环境变量 - 定期旋转API键
- 速率限制
- SearchAPI.io根据您的计划有费率限制 - 内置重试逻辑遵守速率限制 - 监控使用情况 health_check 工具
- 数据隐私
- 搜索查询被发送到SearchAPI.io - 响应在本地缓存(可配置) - 查看SearchAPI.io隐私政策
______________________________________________________________________
许可证
此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。
______________________________________________________________________
致谢
- 模型上下文协议 -Anthropic的协议规范
- FastMCP -Python MCP框架
- SearchAPI.io -搜索API服务提供商
- httpx -Python的现代HTTP客户端
- 派丹蒂克 -数据验证框架
______________________________________________________________________
贡献
欢迎投稿!请随时提交拉取请求。对于重大更改,请先打开一个问题来讨论您想要更改的内容。
- 分叉存储库
- 创建功能分支(
git checkout -b feature/AmazingFeature) - 提交您的更改(
git commit -m 'Add some AmazingFeature') - 推到分支(
git push origin feature/AmazingFeature) - 打开拉取请求
______________________________________________________________________
更新日志
v1.1.0(当前)
- ✅ 新 谷歌地图地点API-详细的地点信息
- ✅ 新 谷歌活动API-活动和活动搜索
- ✅ 新 谷歌旅游探索API-目的地发现
- ✅ 新 谷歌航班位置搜索API-机场查找
- ✅ 增强旅游和旅行研究能力
- ✅ 全面的旅行计划工作流程支持
v1.0.0
- ✅ 使用FastMCP的生产就绪架构
- ✅ 连接池和重试逻辑
- ✅ TTL响应缓存
- ✅ 断路器型式
- ✅ 全面的健康检查和指标
- ✅ 谷歌搜索、视频、人工智能模式
- ✅ 谷歌地图和评论
- ✅ 谷歌航班和日历
- ✅ 谷歌酒店和酒店详情
- ✅ 旅行计划的时间工具
______________________________________________________________________
由以下材料制成❤️ 对于MCP社区
