TellWorldAI World Archive
Ask中文

Home›Practice›Practice

Practice

Building a web-search MCP server

Build a web-search MCP server with FastMCP and SerpAPI, offering web, news, product and Q&A tools, and learn to fix the common errors.

Who this is for and what you will be able to do

This guide is for developers who can write some Python and want a language model to reach live web information. After reading it you should be able to run an MCP server that calls an external API, know which tools it offers, call it from a short SDK script, and diagnose common errors such as a missing SERPAPI_KEY or a 401 response.

What it does

This guide builds an MCP server and client that give an LLM real-time web data through SerpAPI[1]. A model's built-in knowledge stops at a training cutoff, so connecting a search tool lets it look up newer information. The server is built with FastMCP and offers four tools[1]:

  • general_search: a general web search that returns formatted results, taking a string query[1].
  • news_search: a search for recent news articles related to a query, taking query[1].
  • product_search: a search for products that match a query, taking query[1].
  • qna: direct answers to questions from search engines, taking question[1].

All four tools share one SerpAPI account, so they draw on the same key quota. The server also parses API responses into structured results that are easier for an LLM to use[1].

Prerequisites: Python and a SerpAPI key

You need Python 3.8 or later and a SerpAPI API key. SerpAPI offers a free tier, and you can sign up to get a key[1][2]. When the free quota runs out, requests can fail, as described in the troubleshooting section below.

Installation and configuration

The dependencies are listed in requirements.txt. uv is recommended, but pip works too[1]:

# Using uv (recommended)
uv pip install -r requirements.txt

# Using pip
pip install -r requirements.txt

Next, create a .env file in the project root containing SERPAPI_KEY=your_serpapi_key_here, replacing the placeholder with your own key[1]. Keep the key in .env rather than in code.

Running the server and the client

The server runs as a stdio-based MCP server that a client can connect to directly. Start it with python server.py[1].

The client, client.py, has two modes[1]:

  • Normal mode runs automated tests that call every tool and check the responses. Use it to confirm that the server works.
  • Interactive mode shows a menu where you pick tools, enter your own queries and see results immediately. Use it to try different inputs.

python client.py runs the automated tests and starts the server for you. python client.py --interactive opens the menu[1].

How the server defines a tool

The excerpt below shows the skeleton. FastMCP creates the server, @mcp.tool() registers an async function as a tool, and mcp.run() starts the server[1]:

# server.py (excerpt)
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("WebSearchServer")

@mcp.tool()
async def general_search(query: str, num_results: int = 5, ctx: Context = None) -> str:
    # ...implementation (see server.py)...
    raise NotImplementedError

if __name__ == "__main__":
    mcp.run()

This is an excerpt, so the real implementation is in the full server.py. Note that the excerpt declares a num_results parameter with a default of 5, while the tool documentation lists only query[1]. Check the actual server.py before you rely on either version.

The server also uses the MCP Context object to log and track requests[1].

Calling the tools from an SDK script

To call the tools from your own code, use the MCP Python SDK. The example below starts the server over stdio, initializes a session and calls general_search[1]:

# Example usage of the general_search tool
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

async def run_search():
    server_params = StdioServerParameters(
        command="python",
        args=["server.py"],
    )
    async with stdio_client(server_params) as (reader, writer):
        async with ClientSession(reader, writer) as session:
            await session.initialize()
            result = await session.call_tool("general_search", arguments={"query": "open source LLMs"})
            print(result)

Such scripts are useful for trying new queries, checking how the server handles different inputs, automating repeated calls, or building a workflow on top of the server[1].

Common errors

Four problems come up most often[1]:

  1. SERPAPI_KEY environment variable not found: the key cannot be found. Add SERPAPI_KEY=... to the .env file in the project root.
  2. ModuleNotFoundError: No module named 'httpx': a dependency is missing. Run pip install -r requirements.txt.
  3. Error during client execution: usually the client cannot reach the server. Check that server.py is present and running in the right directory, check that the client and server versions are compatible, and restart both.
  4. Search API returned error status: 401: the SerpAPI key is missing, wrong or expired. Check it in the SerpAPI dashboard and confirm that the free quota has not run out.

Debug mode

By default the program logs only important information. For harder problems, set the logging level to DEBUG at the top of client.py or server.py[1]:

# At the top of your client.py or server.py
import logging
logging.basicConfig(
    level=logging.DEBUG,  # Change from INFO to DEBUG
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)

DEBUG output adds lines about each HTTP request and response made through httpx[1]. Switch back to INFO after debugging to keep the logs manageable.

Limits and common questions

  • External APIs limit how many requests you can make in a period. Code should check those limits and handle them without crashing[1].
  • Validate tool parameters, including default values and types, to reduce bugs and confusion[1].
  • Search results come from outside sources, so check their freshness and origin. Judging whether a result is reliable needs a separate check.
  • The excerpt's num_results parameter does not match the tool documentation, so confirm it in the code before changing anything.

Next step

The next section in the chapter is Real Time Streaming[1]. For details of SerpAPI's services and plans, see its website[2].

Adapted from the web-search lesson of Microsoft's open-source course *MCP for Beginners*[1], released under the MIT License.

Sources

  1. 1
    Lesson: Building a Web Search MCP ServerMicrosoft mcp-for-beginners (MIT)
  2. 2
    SerpAPISerpAPI

Cite this page: Building a web-search MCP server. TellWorld, https://www.tellworld.net/practice/practice-mcp-web-search. Updated 2026-11-14

Related news

View all