Introduction
You have probably heard that AI applications can now leverage external tools and data sources. Perhaps you would like to try it out. The good news is that you can easily build an MCP server using Python within an hour as a novice developer.
This article guides you through the process step by step while minimizing the amount of code you need to type and explaining each line. As a result, at the end of the tutorial, you will have a working server that an AI app can use.
What Is an MCP Server?
Model Context Protocol (MCP) is an open standard that enables AI applications to leverage external tools and data. Specifically, an MCP server is a small program that provides this functionality to the application.
You can think of it as a helper that sits between the AI and your data or tools. First, the AI asks the server for something. Then, the server does it, and finally it relays the answer back to the AI. As a result, the AI is now more powerful than before, as it can do everything the server can do in addition to reasoning.
An MCP server can provide three types of functionalities:
- Tools: Actions that the AI can take. For example, adding two numbers or saving a note to a file.
- Resources: Information that the AI can read. For example, a file or a database record.
- Prompts: Predefined instructions that the AI can use as a template.
Why Use Python to Build an MCP Server?
Python is an accessible programming language that most novice developers are familiar with to some degree. Additionally, the official MCP Python SDK takes care of most of the complex parts for you. In other words, you simply write your own code, and the library handles the communication with the AI.
Furthermore, Python has thousands of libraries that enable you to connect your server to databases, APIs, and other tools with minimal effort.
What You Need to Get Started
Before we dive into coding, make sure you have the following:
- Python 3.10 or newer installed on your machine.
- A code editor of your choice. I recommend VS Code.
- A terminal where you can run commands.
- An MCP-compatible application to test your server. Claude Desktop is a good choice.
That is it. Besides these, you do not need any other software, as everything else is included in the Python library.
Step 1: Set Up Your Project
Let us start by creating a new directory for our project and activating a virtual environment:
mkdir my-mcp-server
cd my-mcp-server
python -m venv venv
source venv/bin/activate
On Windows, the last command will be venv\Scripts\activate.
Step 2: Install the SDK
Next, we can install the official SDK by running the following command:
pip install "mcp[cli]"
This will take a couple of minutes to complete. Once it is done, you can proceed to the next step.
Step 3: Write Your First MCP Server
Create a new file called server.py and copy the code below:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("demo-server")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b
if __name__ == "__main__":
mcp.run(transport="stdio")
Let me walk you through this code. First, the first two lines import the FastMCP class and create a new MCP server instance with the name demo-server.
Then, the next two lines define a function called add that adds two integers. Also, the @mcp.tool() decorator tells the server to expose this function as a tool. Finally, the last two lines run the server in stdio transport mode.
Make sure to pay attention to the description of the add function. The AI uses the text between the triple quotes to understand what this tool does. As such, it should be descriptive enough.
Step 4: Add a Resource and a Prompt
Let us enhance our server by adding a resource and a prompt. A resource is a piece of information that the AI can read. For example, let us add a simple greeting:
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Return a personalized greeting."""
return f"Hello, {name}! Welcome to my MCP server."
Next, let us add a prompt. A prompt is a set of instructions that the AI can use as a template:
@mcp.prompt()
def summarize(text: str) -> str:
"""Ask the AI to summarize some text."""
return f"Please summarize this text in three sentences:\n\n{text}"
We have now added a tool, a resource, and a prompt to our server. Also, make sure to place the code blocks above the if __name__ line.
Step 5: Test Your Server
It is a good idea to test your server before connecting it to an application. For this purpose, the MCP SDK comes with a handy visual tool called the Inspector. Simply run the following command:
mcp dev server.py
This will open a new browser tab where you can see your tools listed. Moreover, you can click on them to see their descriptions and sample inputs. If you try the add tool, you should be able to type two numbers and get their sum.
Step 6: Connect Your Server to an AI Application
Now comes the fun part. First, open the settings of your favorite MCP-compatible application. For Claude Desktop, you will need to edit the claude_desktop_config.json file and add your server:
{
"mcpServers": {
"demo-server": {
"command": "python",
"args": ["/full/path/to/server.py"]
}
}
}
Make sure to replace /full/path/to/server.py with the actual path to your server.py file. Then, save the file and restart the application. After that, you should be able to see your tools in the application and use them to add two numbers.
Common Mistakes to Avoid
As a novice developer, you are likely to make some common mistakes when building an MCP server. Below are some of them:
- Do not use print() statements in a stdio server. The stdio transport uses standard streams for communication. As such, any printing to the console will disrupt the communication. Instead, use the logging module to write to the standard error stream.
- Always use absolute file paths when specifying file locations. Relative paths may work in some cases, but they are not reliable.
- Make sure to describe your tools accurately. Avoid vague descriptions, as the AI will not know what to do with them.
- Use type hints whenever possible. They make your code more readable and, in addition, help the SDK generate better prompts.
Security Tips for Your Server
When you expose your server to the internet, it becomes a security risk. Hence, it is important to follow some security best practices when developing your server. Below are some of them:
- Do not give your tools more privileges than they need. For example, if a tool only needs to read a file, do not give it write permissions.
- Always sanitize user input before using it in your server. Never trust user input, as it can be malicious.
- Never hardcode sensitive information such as API keys in your server. Instead, use environment variables.
- Test your server with non-sensitive data before deploying it to production.
Treat your MCP server like any other application that requires security hardening. Some developers may overlook this step because they think it is a small utility. However, it is important to remember that any application that runs on the internet can be hacked if not secured properly.
Ideas for Your Next MCP Server Project
I hope you have enjoyed this tutorial and are now ready to build your own MCP servers. To help you get started, here are some ideas for your next project:
- A notes server that allows you to save and search your notes.
- A weather tool that uses a public API to get the weather forecast.
- A database tool that allows you to query your database securely.
- A file organizer that helps you organize your downloaded files.
Each project will teach you something new. In addition, they will look great on your portfolio.
Final Thoughts
Building an MCP server using Python is not as difficult as it looks. All you need to do is install the SDK, write a few lines of code, and connect it to an application. Essentially, a small server can greatly enhance the capabilities of an AI application.
So, start with the simple add tool and take it from there.
Contact:
9700841043
Address:
Adityan Enclave, Flat No. 216, Annapurna Block, Ameerpet, Hyderabad, Telangana 500016