Overview
This lesson demonstrates how to build a real-world AI agent that integrates with external APIs, handles diverse data types, manages errors, and orchestrates multiple tools. You will build a complete web search MCP server and client using SerpAPI.general_search
Broad web results across all domains
news_search
Recent headlines and news articles
product_search
E-commerce product data
qna
Direct question-and-answer snippets
Prerequisites
- Python 3.8 or higher
- A SerpAPI API key (sign up at serpapi.com — free tier available)
Setup
Server implementation
The server registers four tools and handles all requests from the MCP client.Tool reference
general_search
Performs a general web search and returns formatted results. Parameters:query(string, required): The search query
news_search
Searches for recent news articles. Parameters:query(string, required): The search query
product_search
Searches for products matching a query. Parameters:query(string, required): The product search query
qna
Gets a direct answer to a question from search engine results. Parameters:question(string, required): The question to find an answer for
Writing a custom test script
Advanced concepts
Multi-tool orchestration
Multi-tool orchestration
Running multiple tools (web search, news search, product search, Q&A) within a single MCP server allows the AI to handle a variety of tasks in one interaction.
API rate limit handling
API rate limit handling
External APIs limit request frequency. Implement exponential backoff and quota checks so your app degrades gracefully rather than crashing.
Structured data parsing
Structured data parsing
SerpAPI responses are deeply nested. Flatten them into clean, consistent structures before returning to the AI model.
Error recovery
Error recovery
Network failures and API errors should produce useful messages rather than stack traces. Wrap all external calls in try/except with specific error types.
Parameter validation
Parameter validation
Validate all tool inputs before making API calls. Set sensible defaults and ensure required fields are present.
Debugging
Enable DEBUG logging to see detailed HTTP request/response traces:Troubleshooting
SERPAPI_KEY environment variable not found
SERPAPI_KEY environment variable not found
Create a
.env file in your project root and add SERPAPI_KEY=your_key_here. Make sure python-dotenv or a similar package loads it at startup.ModuleNotFoundError
ModuleNotFoundError
Run
pip install -r requirements.txt to install all required packages. Common missing modules: httpx, mcp, python-dotenv.Error during client execution
Error during client execution
Verify
server.py is running before starting the client. Check that both are using compatible MCP SDK versions.Search API returned error status: 401
Search API returned error status: 401
Your SerpAPI key is missing, incorrect, or expired. Verify the key in your SerpAPI dashboard and update your
.env file. Check if your free-tier quota is exhausted.