Guide Published: 6 min read

Build an MCP Server: Code and Tests

Build a Python MCP server, add a search tool, and test it locally.

Build an MCP Server: Code and Tests

Understanding MCP and Why It Matters

Model Context Protocol (MCP) is a shared way for AI apps to use tools and data. An MCP server offers features to a compatible client, such as an AI app or agent. This helps teams connect an agent to useful services without building a custom link for every app.

A server can provide tools, resources, and prompts. A tool performs an action, such as searching products. A resource shares data for a client to read. A prompt provides reusable instructions. Start with one feature that solves a real task.

MCP uses JSON-RPC messages for requests and replies. The SDK handles much of this message flow. You do not need to write a protocol layer for a basic build. The official MCP server build guide covers the current SDK setup.

If you are asking how to build an MCP server, begin with a small tool and a narrow job. This MCP server tutorial uses Python to search a sample product list. It then covers testing and local or remote use. Keep access limited from the start.

Set Up Your Python Development Environment

Use Python 3.10 or newer and the MCP Python SDK. A virtual environment keeps this project’s packages apart from other work. FastAPI is optional. It can help when you already have HTTP routes, but a basic MCP server does not need it.

Create a folder, enter it, and make a virtual environment. Then install the SDK and pytest, a tool for running tests. The SDK’s command-line tools can help with local development. Keep the first build small.

  1. Create a folder named mcp-product-server, then open it in your terminal.

  2. Run python -m venv .venv and activate the new environment.

  3. Install the SDK with pip install "mcp[cli]".

  4. Install tests with pip install pytest, then save the package versions.

You can start with one Python file and sample data. Add a database only if the task needs one. Docker can make test setups more alike across a team. It is not needed for your first build.

A regular REST route is not an MCP server. MCP clients expect protocol messages and session handling. For remote use, pick an HTTP transport supported by your SDK version. Set access rules before you expose the service.

Build Your First MCP Server in Python

To build your own MCP server from scratch, create a file named server.py. Use the SDK’s FastMCP helper to define a server and tool. This example searches a short list kept in memory.

Give each tool one clear job. This search checks product names and descriptions. It returns matches, or an empty list when the query has no text. Add input checks before using live prices or customer data.

Put this code in server.py. Each line below belongs in the same file, in the shown order.

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Product Search")

products = [

{"id": "p-1", "name": "Desk lamp", "description": "Dimmable LED lamp"},

{"id": "p-2", "name": "Notebook", "description": "Hard-cover paper notebook"},

]

@mcp.tool()

def search_products(query: str) -> list[dict]:

"""Find products by name or description."""

term = query.strip().lower()

if not term:

return []

return [p for p in products

if term in p["name"].lower()

or term in p["description"].lower()]

if __name__ == "__main__":

mcp.run(transport="stdio")

Run the file from the project folder. With standard input and output transport, the client starts the server process and sends messages through that stream. Do not print debug notes there. Send logs to standard error, or they may disrupt the message flow.

Frosted glass server module with blank geometric blocks in a dark violet and magenta scene
Geometric model of a simple MCP server

Handle MCP Messages and Add Core Features

The client and server begin with an initialization exchange. They share protocol details and supported features, then handle later requests with JSON-RPC. The SDK runs this exchange when you define tools through its server API.

You do not need to create a separate capabilities endpoint for this example. The SDK reports the features that your server supports. A client can list tools, then call search_products with a query. The SDK checks the input and returns the result in the expected form.

Use tools for actions, resources for data, and prompts for reusable instructions. A product search is a tool. A known product record may fit a resource. Add features only when a client needs them.

  • Give every tool a clear name and a short description.

  • Check inputs before using them in a query or other action.

  • Return useful errors without exposing secrets or private data.

  • Grant only the access each tool needs.

An MCP client is a separate part of the setup. It connects to the server and calls its features. If you are learning how to build an MCP client, begin by using an existing client to check this server. Build a custom client only when your app needs its own connection flow.

Abstract MCP feature modules linked by violet and magenta data paths on an indigo background
MCP tools and data paths in an abstract network

Test Your MCP Server

Test the search function before connecting an AI app. Check a query that should match, one with no match, and a blank query. These cases catch common mistakes in search and input handling.

For a quick manual check, start the server with the SDK’s local inspector tool. Connect to the process, list its tools, and call search_products with a term such as “lamp.” Check that the result has the expected product fields. Tool names and commands can change by SDK version, so check the installed SDK help.

Use pytest for repeatable checks as the project grows. Keep the search function easy to test by checking its output with known sample data. Then test the MCP connection through a client, so you check both the function and message flow.

  • Test a matching word, such as “lamp.”

  • Test text that should return no products.

  • Test empty input and any input limits you set.

  • Confirm the client can list and call the tool.

Do not rely only on a successful server start. A process can run while a tool has broken logic or poor input checks. Retest after changing the tool, SDK, or transport.

Blank geometric modules forming a tested connection against a dark violet-indigo backdrop
Abstract view of a tested server connection

Deploy Your MCP Server Locally or Remotely

For local use, a client can start the server as a child process over standard input and output. This suits development and tools that run on one machine. Keep logs off the message stream, and store settings outside the source file.

Remote use needs an HTTP transport supported by the SDK. Run the service behind a trusted host, use encrypted connections, and limit who can reach it. OAuth authentication may be needed when users or apps must prove who they are. Do not expose tools that can change data until access checks are in place.

FastAPI can serve regular web routes beside an MCP service when your app needs both. It does not replace MCP message handling. Docker can package the service and its Python setup for a more repeatable release. Test the container and its access rules before sharing it.

Keep the first release narrow. Track errors, review tool access, and update the SDK with care. A small server with clear limits is easier to trust and maintain.

So, how do you build an MCP server? Choose a useful task, define a tool, then test the client connection. The same steps work whether you searched for how to build MCP server in Python or how to build an MCP server from scratch. Let the tool’s real needs shape the next feature.

Frequently asked questions

How do I build an MCP server in Python?
Install the MCP Python SDK, define a server with FastMCP, and add a tool with a clear task. Test it with a client before you deploy it.
What do I need to build an MCP server?
You need Python, the MCP SDK, and a task for the server to perform. FastAPI and Docker are optional, depending on how you plan to host and connect the service.
Does an MCP server need a capabilities endpoint?
Not when you use the SDK’s server API for a basic build. The SDK shares the features your server supports during the client connection.
How can I test an MCP server?
Test each tool with matching, missing, and empty inputs. Then connect with an MCP client and check that it can list and call the tool.
Can I run an MCP server remotely?
Yes. Use an HTTP transport supported by your SDK version, and add encrypted connections and access checks. OAuth may be useful when users or apps need sign-in.
How do I build an MCP client?
An MCP client connects to a server and calls its features. For a first server test, use an existing compatible client before writing your own connection code.
  • MCP server in Python
  • Model Context Protocol server
  • MCP server tutorial
  • Python MCP SDK
  • MCP tool testing

Keep reading