Building and Testing Servers
local graph
Chapter 3 — Building and Testing Servers
Section titled “Chapter 3 — Building and Testing Servers”In this chapter, we will cover the basics of building and testing servers. We will start with a simple server that uses the STDIO transport. The STDIO transport is a simple way to communicate with the server using standard input and output streams. Building STDIO servers is a great way to get started with the Model Context Protocol (MCP) and understand how it works. It should also be added that the STDIO transport is the most common way to communicate with the server, and it’s meant for servers running on your machine.
As part of the chapter, we will also cover different ways of testing the server. It’s important that what we build works as expected. We will cover different tools that can be used visually, in the CLI, and in code.
In this chapter, you will learn how to do the following:
- Build a simple server using the STDIO transport
- Describe the core concepts of the server
- Test the server using different tools
The chapter covers the following topics:
- A STDIO server
- Concepts
- Runtimes
- Testing the server
- First server
A STDIO server
Section titled “A STDIO server”Using STDIO transport means that the server communicates with the client through standard input and output streams. This means that the server can read input from the client via standard input (stdin) and send output back to the client via standard output (stdout). Okay, that sounds simple, but how does it work?
MCP uses JSON-RPC 2.0 as its wire format. Thereby, it needs to convert stream messages into JSON-RPC format for transmission and convert received JSON-RPC messages back into stream messages. Imagine the following example in the terminal:
>> hello worldTo be used in a STDIO server, the preceding message would be converted into JSON-RPC format, and it would look like this:
{ "jsonrpc": "2.0", "method": "sendMessage", "params": { "message": "hello world" }, "id": 1}That’s an interesting example, but what really matters to you as a developer is two things:
- How to build a STDIO server. We’ll show this shortly in an upcoming section.
- Why it matters, and what it means that your server is a STDIO server. It means that your server is running on your local machine and is communicating with the client through standard input and output streams. In Chapter 4 and Chapter 5, we’ll show you how to build a server that can communicate with servers over the internet.
Concepts
Section titled “Concepts”Let’s take a look at the core concepts (features, if you will) that the server can offer.
Resources
Section titled “Resources”These are the data and context that the server can provide to the client. The way MCP is meant to be used is by the client having an LLM when they communicate with the server. Resources in this use case serve as context that could be added to the LLM at the time of the prompt. Imagine the following scenario playing out:

Figure 3.1 – Resources scenario
Figure 3.1 – Resources scenario
In this scenario, the context ensures that the end user gets a better result as the server’s context is paired with the user’s prompt, like a simplified retrieval-augmented generation (RAG) pattern. That is, you pair the user’s prompt with your data to get a better response.
A specific example implementing this way of thinking could be where the user asks for products like so:
Prompt
User: I'm looking for a new laptop
Figure 3.2 – Example of a resource interaction
Figure 3.2 – Example of a resource interaction
In this specific product query, we call resources first to learn what table to query, and then we let the LLM identify which tool to call. Thanks to calling the resource, we gain extra knowledge on what tools to select and what parameters to use.
Resources can also be used in a manner where the LLM isn’t used, but the way you should think about your server is that it’s here to empower a client’s LLM. That means the tools, resources, and prompts you provide should be helpful.
Now that we understand when resources are used, let’s talk more about the nature of them. Resources are static and can be anything that the server can access and share with the client. What’s important to know is that you can ask for a resource either with or without a template. If there’s only one file or one app setting configuration, it makes sense to create that with a set name such as config:
server.resource( "config", "config://app", async (uri) => ({ contents: [{ uri: uri.href, text: "App configuration here" }] }));Here, we are returning the same type of information each time.
However, if there are many types of settings, such as user settings, calendar settings, and so on, it might make sense to create a more templated version such as settings://{type}:
@mcp.resource("settings://{type}")def get_setting(type: str) -> str: """Get a specific setting""" return f"Setting from file {type}!"The settings are still non-changing, but there are many of them, so we choose to group them under one namespace.
In this case, the resource is called settings and takes type as a parameter. For example, settings://hello would match this pattern.
Tools are the functions or capabilities that the server can perform. Examples of tools include data processing functions, tools that call an API to fetch data, and more. For tools, we need to define the input and output by providing a schema. How this is done looks different depending on the used runtime, but the idea is that it should be clear to the consumer of the tool what the input and output are. For example, if we have a tool that takes two numbers and returns their product, we can define it like this:
# Add a multiplication tool@mcp.tool()def multiply(a: int, b: int) -> int: """Multiply two numbers""" return a * bIn this example, we define a tool called multiply that takes two numbers as input and returns their product. The input and output are defined using Python type hints.
Prompts
Section titled “Prompts”Prompts are the templated messages or workflows that guide the interactions between the client and server. A good example of a prompt is a template that helps the client write a product description or slogan in the context of an e-commerce application. Just like resources and tools, prompts can take input. Here’s an example of a prompt that takes a product name and returns a product description:
@mcp.prompt()def describe_product(product: str) -> str: return f"Write a product description for {product}"Here, we define a prompt called describe_product that takes a product name as input and returns a product description. The input is defined using Python type hints.
Now that we know what our server can contain, what else do we need to know?
Runtimes
Section titled “Runtimes”The officially supported runtimes at present for MCP are TypeScript, Python,.NET, Java and Kotlin, Rust, and Go. More are being added all the time. For an updated list of runtimes, please refer to the MCP documentation here: https://modelcontextprotocol.io/docs/sdk. Each of these runtimes has its own SDK you can use. The implementation of the runtimes is similar, but there are some differences.
Excited? Let’s get started!
Testing the server
Section titled “Testing the server”There are many tools at your disposal to test the server. Why we test is that we want to ensure that the server is working as expected. The tools we will cover in this chapter are as follows.
Inspector
Section titled “Inspector”This is a CLI tool that can present both a UI and a CLI interface. The latter is meant for scripting and automation.
The inspector tool runs a Node.js package with npx, so ensure that you have the Node.js runtime installed. This is also true even if you run the inspector tool via a Python command, as Python wraps a call to the underlying Node.js process.
The UI is meant for manual testing and debugging. In this example command, we run the inspector tool. Ensure that you stand in the same directory as the server file when you run the following commands.
The Python SDK installed an executable mcp that helps run the server:
mcp dev server.pyBy running this tool, we can test the server in visual mode. Here’s a screenshot of the inspector tool:

Figure 3.3 – Inspector tool
Figure 3.3 – Inspector tool
Ensure that the visual tool specifies the following fields:
- Transport Type: STDIO
- Command:
mcp - Arguments:
run server.py
You can also run the inspector tool in CLI mode. This is useful for scripting and automation. You type almost the same command as earlier, but you add the --cli flag:
npx @modelcontextprotocol/inspector --cli mcp run server.py --method tools/listHere, we are adding the --method command followed by the tools/list argument, which says we want to list all tools on the server.
Note that mcp dev in the Python pivot earlier wraps a Node.js tool, which is the inspector. If you want full access to all the features of the inspector, you can run it directly for both Node.js and Python, and that’s what we recommend doing (that is, run it like so: npx @modelcontextprotocol/inspector).
A standard command-line tool such as cURL can be used to send requests to the server. This is normally used to test servers using SSE or streamable HTTP as transport. Other tools capable of making web requests can be used as well. A curl command will only work if the server is running on the internet, which is the case with SSE servers. For STDIO servers, you need to use the inspector or a custom client to send requests to the server. Let’s see a typical curl command:
curl -X POST -H "Content-Type: application/json" -d '{"method": "tools/list", "params": {}, "id": 1}' http://localhost:3000/sseIn the preceding command, we are sending a POST request to the server with the tools/list method. The server will respond with a list of tools available on the server. This is a good alternative to using the inspector in CLI mode.
It’s possible to write unit tests for the server. This is a good practice in addition to using the inspector. The tests can be run in a CI/CD pipeline and are useful to ensure that the server is working as expected. You can use any testing framework you like, and you can add resources, tools, and prompts to the server and then test them. Let’s see an example of a test:
@pytest.mark.anyioasync def test_add_tool_decorator(self): mcp = FastMCP() @mcp.tool() def add(x: int, y: int) -> int: return x + y assert len(mcp._tool_manager.list_tools()) == 1In the preceding example, we do the following:
- Use the
pytestframework to test the server - Create a new server instance and add a tool called
add - Test that the tool is added to the server and that the number of tools is equal to
1
This is a simple test, but it shows how you can use pytest to test the server.
Now, we have a good grasp of the concepts and features of the server; let’s write down the plan for how we will go about building our first server.
First server
Section titled “First server”To build our first server, let’s first go through the steps to build a simple server:
- Create a new project: We will create a new project with the needed dependencies and set up any environment specifics. You’re highly encouraged to create a virtual environment to ensure you don’t install libraries globally. By using a virtual environment, each project is isolated from other projects and you don’t have to worry about conflicting library versions that might otherwise occur.
- Install dependencies: Here, we will list and install dependencies for the project, which differ, of course, depending on the runtime you are using.
- Add server code: This is where we will add the server’s features. As part of this, we will discuss the feature, its input and output, and schemas.
- Test the server with inspector: Inspector is a tool that helps you ensure new features work okay. The tool allows you to run it in both CLI mode and a visual mode, where it shows a web browser UI:
- The CLI mode is appropriate for CI/CD scenarios, as it responds with JSON in a terminal
- The visual mode is more appropriate when you, as a developer, try to ensure that the server is working as it should
- The CLI mode is appropriate for CI/CD scenarios, as it responds with JSON in a terminal
Let’s write some code!
Step 1: Create a new project
Section titled “Step 1: Create a new project”Before we write any code, we need a project. This will set us up for success. The project will contain everything we need to write our server and define tests and scripts for testing and running the server:
- Create the following folder structure:
├── src/|---- server.py
- Create a virtual environment:
python -m venv venv
- Activate the virtual environment:
venv\Scripts\activate
You should see the name of the virtual environment in the terminal prompt. This means that the virtual environment is activated, and any packages you install will be installed in this environment.
Great, now we have a virtual environment and a folder structure. Next, we need to install the dependencies.
Step 2: Install dependencies
Section titled “Step 2: Install dependencies”Run the following command in the terminal:
pip install "mcp[cli]"This will install the MCP SDK and the CLI tools.
Step 3: Add server code
Section titled “Step 3: Add server code”Add the following code to server.py:
from mcp.server.fastmcp import FastMCP# Create an MCP servermcp = FastMCP("Demo")# Add a multiply tool@mcp.tool()def multiply(first: int, second: int) -> int: """Multiply two numbers""" return first * second# Add a dynamic greeting resource@mcp.resource("greeting://{name}")def get_greeting(name: str) -> str: """Get a personalized greeting""" return f"Hello, {name}!"@mcp.prompt()def review_code(code: str) -> str: return f"Please review this code:\n\n{code}"The preceding code does the following:
- Creates an MCP server instance with the name
Demo - Adds a tool called
multiplythat takes two numbers as input and returns their sum - Adds a resource called
greetingthat takes a name as input and returns a personalized greeting - Creates a prompt called
review_codethat takes a code snippet as input and returns a review of the code
Step 4: Test the server with the inspector
Section titled “Step 4: Test the server with the inspector”Here, we will use the inspector to test the server. The inspector is a CLI tool that can present both a UI and a CLI interface. The latter is meant for scripting and automation. The UI is meant for manual testing and debugging:
- Run the following command in the terminal:
mcp dev server.py
This will start the inspector tool on port 6274.
- Navigate to
http://localhost:6274in your web browser. This should start a web server with a visual interface, allowing you to test the sample. - In the visual interface, ensure you fill in the fields like so:
- Command:
"mcp"- Arguments:
"run server.py"
- Arguments:
- Command:
Click Connect.
- Select the Tools tab and List Tools, and multiply should be listed. Click multiply and fill in the fields like so:
- first:
2- second:
4
- second:
- first:
You should see the result 8 in the Tool Result field.
Great, now we have a working server, and we can test it using the inspector.
Step 5: Test the server with the inspector in CLI mode
Section titled “Step 5: Test the server with the inspector in CLI mode”In this subsection, we will run the inspector directly in CLI mode. The inspector is a Node.js app, and mcp dev is a wrapper around it.
At the time of this writing, mcp dev does not support all the features made available in the inspector. We will therefore show how to run the inspector directly as a Node.js app as that’s what it’s been written in.
Let’s show some useful commands you can run in the inspector:
- List tools: Run the following command in the terminal:
npx @modelcontextprotocol/inspector --cli mcp run server.py --method tools/list
This will list all the tools available on the server, and you should see the following output:
{ "tools": [ { "name": "multiply", "description": "Multiply two numbers", "inputSchema": { "type": "object", "properties": { "first": { "title": "First", "type": "integer" }, "second": { "title": "Second", "type": "integer" } }, "required": [ "first", "second" ], "title": "multiplyArguments" }, "outputSchema": { "type": "object", "properties": { "result": { "title": "Result", "type": "integer" } }, "required": [ "result" ], "title": "multiplyOutput" } } ]}Here, you see all the tools on the server in JSON format. We only have one tool, multiply, but we can see that it has an inputSchema with first and second parameters.
- Call a tool: Run the following command in the terminal:
npx @modelcontextprotocol/inspector --cli mcp run server.py --method tools/call --tool-name multiply --tool-arg first=2 --tool-arg second=4
You should see a response like this:
{ "content": [ { "type": "text", "text": "8" } ], "structuredContent": { "result": "8" }, "isError": false}- List resources: Run the following command in the terminal:
npx @modelcontextprotocol/inspector --cli mcp run server.py --method resources/list
This will list all the resources available in the server, and you should see the following output:
{ "resources": []}Empty? The reason is that there’s a difference between a resource and a templated resource. Here’s how you can list the templated resources:
npx @modelcontextprotocol/inspector --cli mcp run server.py --method resources/templates/listYou should get a response like this:
{ "resourceTemplates": [ { "uriTemplate": "greeting://{name}", "name": "get_greeting", "description": "Get a personalized greeting" } ]}- Let’s call our templated resource:
npx @modelcontextprotocol/inspector --cli mcp run server.py --method resources/read --uri greeting://chris
You should see a response like this:
{ "contents": [ { "uri": "greeting://chris", "mimeType": "text/plain", "text": "Hello, chris!" } ]}- Let’s list prompts next with the following command:
npx @modelcontextprotocol/inspector --cli mcp run server.py --method prompts/list
You should see an output similar to the following:
{ "prompts": [ { "name": "review_code", "description": "", "arguments": [ { "name": "code", "required": true } ] } ]}- To call a prompt, we would type the name of the prompt and
prompts/get, like so:npx @modelcontextprotocol/inspector --cli mcp run server.py --method prompts/get --prompt-name review_code --prompt-args code="print('Hello World')"
You should see a response like this:
{ "messages": [ { "role": "user", "content": { "type": "text", "text": "Please review this code:\n\nprint('Hello World')" } } ]}Optionally, you could add a resource in server.py, like so:
@mcp.resource("command://ping")def get_echo() -> str: """Send pong""" return "Pong"Read it like so:
npx @modelcontextprotocol/inspector --cli mcp run server.py --method resources/read --uri command://pingYou should see a response like this:
{ "contents": [ { "uri": "command://ping", "mimeType": "text/plain", "text": "Pong" } ]}Note how you invoke resources and resource templates in the same way using the uri parameter.
Summary
Section titled “Summary”In this chapter, we covered how to build your first server. For our first server, we used the STDIO transport to create a server meant to be run on our machine. We also looked into various ways of testing out the server features using a tool called the inspector. The inspector tool has two different modalities, CLI mode and visual mode. The former mode is used for CI/CD scenarios, and the latter for you as a developer quickly trying out features.
In our upcoming chapter, we’ll describe the SSE transport, which you can use if you want the server to be consumed via a URL address.
Assignment – an e-commerce STDIO server
Section titled “Assignment – an e-commerce STDIO server”For this MCP server, we will add capabilities that can be used in the context of an e-commerce application. Therefore, the server will need the following features.
It will need these tools:
get-orders: This tool will return a list of orders. The optional input is a customer ID, and the output is a list of orders. Each order should contain the following fields: ID, customer ID, quantity, total price, and status.get-order: This tool will return a specific order. The input is the order ID, and the output is an order. The order should contain the following fields: ID, customer ID, quantity, total price, and status.place-order: This tool will place an order. The input is the customer ID and the cart ID.get-cart: This tool will return a cart.get-cart-items: This tool will return a list of items in the cart. The input is the cart ID, and the output is a list of items. Each item should contain the following fields: ID, name, description, price, quantity, and product ID.add-to-cart: This tool will add an item to the cart. The input is the cart ID, product ID, and quantity. The output is a success message. If the cart ID is not provided, the tool should create a new cart and add the item to the new cart. The output should be a success message and the cart ID.products: This tool will return a list of products. The optional input is a category, and the output is a list of products. The product should contain the following fields: ID, name, description, price, and category. The output should be in JSON format.product: This tool should return a specific product. The input is the product ID, and the output is a product. The product should contain the following fields: name, description, price, category, and ID. The output should be in JSON format.categories: This tool will return a list of categories. The output should be in JSON format. The categories should contain the following fields: ID, name, and description. The output should be in JSON format.get-customers: This tool will return a list of customers. The output should be in JSON format. It should contain the following fields: ID, name, and email.
It will need this resource:
product_catalog: This resource will return a list of products in the catalog. The optional input is a category, and the output is a list of products. Each product should contain the following fields: name, description, and category. The idea is that the resource will return a list of products in the catalog, in case potential customers want to see them.
As you can see, this will support a simple e-commerce application and a customer trying to either put items in a cart or place an order.
You can keep state within memory data structures.
Solution
Section titled “Solution”You can find the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter03/solutions/README.md.
What of the following is something a server can expose?
- A: Tools, prompts, and services
- B: Tools and prompts
- C: Prompts, tools, and resources
You can find the solution at https://github.com/PacktPublishing/Learn-Model-Context-Protocol-with-Python/blob/main/Chapter03/solutions/solution-quiz.md.
References
Section titled “References”- Inspector tool: https://github.com/modelcontextprotocol/inspector
- Model Context Protocol: https://github.com/modelcontextprotocol/
- Python SDK: https://github.com/modelcontextprotocol/python-sdk