forked from microsoft/mcp-for-beginners
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
330 lines (276 loc) · 11.9 KB
/
server.py
File metadata and controls
330 lines (276 loc) · 11.9 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#!/usr/bin/env python3
"""
Web Search MCP Server
This advanced MCP server demonstrates integration with SerpAPI to provide
real-time web data to LLMs through four specialized tools:
- general_search: For broad web search results
- news_search: For recent news articles
- product_search: For e-commerce product information
- qna: For direct question-answer snippets
The server is built using FastMCP and showcases advanced concepts
like external API integration, structured data parsing, and
multi-tool orchestration.
"""
import os
import json
import httpx
import logging
from typing import Dict, Any
from dotenv import load_dotenv
from mcp.server.fastmcp import FastMCP, Context
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
# Load environment variables
load_dotenv()
SERPAPI_KEY = os.getenv("SERPAPI_KEY")
if not SERPAPI_KEY:
logger.error("SERPAPI_KEY environment variable not found. Please set it in .env file.")
raise EnvironmentError("SERPAPI_KEY environment variable is required")
# API configuration
SERPAPI_BASE_URL = "https://serpapi.com/search"
DEFAULT_TIMEOUT = 10.0 # seconds
DEFAULT_RESULTS_LIMIT = 5
# Initialize FastMCP server
mcp = FastMCP("WebSearchServer")
async def make_serpapi_request(ctx: Context, params: Dict[str, Any]) -> Dict[str, Any]:
"""
Make a request to SerpAPI with the given parameters.
Args:
ctx: MCP context object for logging
params: Dictionary of parameters to send to SerpAPI
Returns:
Dict containing the API response
Raises:
Exception: If the API request fails
"""
# Ensure API key is included
request_params = {**params, "api_key": SERPAPI_KEY}
try:
async with httpx.AsyncClient(timeout=DEFAULT_TIMEOUT) as client:
await ctx.info(f"Making SerpAPI request with engine: {params.get('engine', 'google')}")
response = await client.get(SERPAPI_BASE_URL, params=request_params)
response.raise_for_status()
data = response.json()
await ctx.info("SerpAPI request successful")
return data
except httpx.TimeoutException:
await ctx.error("SerpAPI request timed out")
raise Exception("Search request timed out. Please try again.")
except httpx.RequestError as e:
await ctx.error(f"SerpAPI request error: {e}")
raise Exception(f"Failed to fetch data from search API: {e}")
except httpx.HTTPStatusError as e:
await ctx.error(f"SerpAPI HTTP error: {e.response.status_code} - {e.response.text}")
raise Exception(f"Search API returned error status: {e.response.status_code}")
except json.JSONDecodeError:
await ctx.error("Failed to parse SerpAPI response as JSON")
raise Exception("Failed to parse search results")
# Tool for general web search
@mcp.tool()
async def general_search(query: str, num_results: int = DEFAULT_RESULTS_LIMIT, ctx: Context = None) -> str:
"""
Perform a general web search and return formatted results.
Args:
query: The search query
num_results: Number of results to return (default: 5)
ctx: MCP context object
Returns:
Formatted search results as a string
"""
await ctx.info(f"Performing general search for: {query}")
try:
# Prepare parameters for SerpAPI
params = {
"q": query,
"num": num_results,
"engine": "google",
}
# Make the API request
response_data = await make_serpapi_request(ctx, params)
# Extract organic results
organic_results = response_data.get("organic_results", [])
if not organic_results:
await ctx.info("No general search results found")
return "No search results found."
# Format results for return
formatted_results = []
for i, result in enumerate(organic_results[:num_results]):
formatted_results.append(
f"## {i+1}. {result.get('title', 'No title')}\n"
f"**Link**: {result.get('link', 'No link')}\n"
f"**Snippet**: {result.get('snippet', 'No description')}\n"
)
await ctx.info(f"Returning {len(formatted_results)} general search results")
return "\n\n".join(formatted_results)
except Exception as e:
await ctx.error(f"General search failed: {str(e)}")
return f"Error: Unable to fetch results. {str(e)}"
# Tool for news search
@mcp.tool()
async def news_search(query: str, num_results: int = DEFAULT_RESULTS_LIMIT, ctx: Context = None) -> str:
"""
Search for recent news articles related to a query.
Args:
query: The search query
num_results: Number of news articles to return (default: 5)
ctx: MCP context object
Returns:
Formatted news search results as a string
"""
await ctx.info(f"Performing news search for: {query}")
try:
# Prepare parameters for SerpAPI
params = {
"q": query,
"num": num_results,
"engine": "google_news",
}
# Make the API request
response_data = await make_serpapi_request(ctx, params)
# Extract news results
news_results = response_data.get("news_results", [])
if not news_results:
await ctx.info("No news articles found")
return "No news articles found."
# Format results for return
formatted_results = []
for i, result in enumerate(news_results[:num_results]):
formatted_results.append(
f"## {i+1}. {result.get('title', 'No title')}\n"
f"**Source**: {result.get('source', 'Unknown source')} | "
f"**Date**: {result.get('date', 'Unknown date')}\n"
f"**Link**: {result.get('link', 'No link')}\n"
f"**Snippet**: {result.get('snippet', 'No description')}\n"
)
await ctx.info(f"Returning {len(formatted_results)} news results")
return "\n\n".join(formatted_results)
except Exception as e:
await ctx.error(f"News search failed: {str(e)}")
return f"Error: Unable to fetch news. {str(e)}"
# Tool for product search
@mcp.tool()
async def product_search(query: str, num_results: int = DEFAULT_RESULTS_LIMIT, ctx: Context = None) -> str:
"""
Search for products matching a query.
Args:
query: The product search query
num_results: Number of product results to return (default: 5)
ctx: MCP context object
Returns:
Formatted product search results as a string
"""
await ctx.info(f"Performing product search for: {query}")
try:
# Prepare parameters for SerpAPI
params = {
"q": query,
"engine": "google_shopping",
"shopping_intent": "high",
"num": num_results
}
# Make the API request
response_data = await make_serpapi_request(ctx, params)
# Extract shopping results
shopping_results = response_data.get("shopping_results", [])
if not shopping_results:
await ctx.info("No product results found")
return "No product results found."
# Format results for return
formatted_results = []
for i, result in enumerate(shopping_results[:num_results]):
formatted_results.append(
f"## {i+1}. {result.get('title', 'No title')}\n"
f"**Price**: {result.get('price', 'Unknown price')}\n"
f"**Rating**: {result.get('rating', 'No rating')} "
f"({result.get('reviews', 'No')} reviews)\n"
f"**Source**: {result.get('source', 'Unknown source')}\n"
f"**Link**: {result.get('link', 'No link')}\n"
)
await ctx.info(f"Returning {len(formatted_results)} product results")
return "\n\n".join(formatted_results)
except Exception as e:
await ctx.error(f"Product search failed: {str(e)}")
return f"Error: Unable to fetch products. {str(e)}"
# Tool for Q&A search
@mcp.tool()
async def qna(question: str, ctx: Context = None) -> str:
"""
Get direct answers to questions from search engines.
Args:
question: The question to find an answer for
ctx: MCP context object
Returns:
Answer snippet as a string
"""
await ctx.info(f"Searching for answer to: {question}")
try:
# Prepare parameters for SerpAPI
params = {
"q": question,
"engine": "google",
}
# Make the API request
response_data = await make_serpapi_request(ctx, params)
# Try to extract answer box first (direct answer)
answer_box = response_data.get("answer_box", {})
if answer_box:
await ctx.info("Found answer in answer box")
if "answer" in answer_box:
return f"**Answer**: {answer_box['answer']}"
elif "snippet" in answer_box:
return f"**Answer**: {answer_box['snippet']}"
elif "snippet_highlighted_words" in answer_box:
return f"**Answer**: {' '.join(answer_box['snippet_highlighted_words'])}"
# Try knowledge graph if no answer box
knowledge_graph = response_data.get("knowledge_graph", {})
if knowledge_graph and "description" in knowledge_graph:
await ctx.info("Found answer in knowledge graph")
return f"**Answer**: {knowledge_graph['description']}"
# Try featured snippet
if "featured_snippet" in response_data:
await ctx.info("Found answer in featured snippet")
snippet = response_data["featured_snippet"]
if "snippet" in snippet:
return f"**Answer**: {snippet['snippet']}"
# Try related questions
related_questions = response_data.get("related_questions", [])
if related_questions:
await ctx.info("Found answer in related questions")
formatted = []
for i, question in enumerate(related_questions[:3]):
formatted.append(
f"**Question**: {question.get('question', 'Unknown question')}\n"
f"**Answer**: {question.get('snippet', 'No answer available')}\n"
f"**Source**: {question.get('source', {}).get('link', 'No source')}"
)
return "\n\n".join(formatted)
# Fallback to first organic result snippet
organic_results = response_data.get("organic_results", [])
if organic_results and "snippet" in organic_results[0]:
await ctx.info("No direct answer found, using first organic result")
return f"**Possible answer**: {organic_results[0]['snippet']}"
await ctx.info("No answer found")
return "No direct answer found for your question."
except Exception as e:
await ctx.error(f"Q&A search failed: {str(e)}")
return f"Error: Unable to find an answer. {str(e)}"
@mcp.resource("readme://")
async def get_readme() -> str:
"""Get README information for the Web Search MCP Server"""
return """
# Web Search MCP Server
This MCP server provides tools for integrating web search capabilities into LLMs using SerpAPI.
## Available Tools:
1. `general_search(query, num_results=5)` - Perform a general web search
2. `news_search(query, num_results=5)` - Search for recent news articles
3. `product_search(query, num_results=5)` - Search for products
4. `qna(question)` - Get direct answers to questions
## Usage:
Call these tools from an MCP client to retrieve real-time web data.
"""
if __name__ == "__main__":
mcp.run()