Building Your First MCP Server with Python
A step-by-step tutorial on how to create and run a basic Model Context Protocol (MCP) server using the Python SDK, FastMCP.
What You'll Learn
- Introduction to MCP and FastMCP
- Setting up Python environment with uv
- +3 more
Time & Difficulty
Time: 15-20 minutes
Level: Beginner
What You'll Need
- Python installed
- uv installed
- +1 more
Introduction to Model Context Protocol (MCP) and FastMCP
The Model Context Protocol (MCP) is an open standard and open-source framework designed to standardize how AI models, particularly large language models (LLMs), integrate and share data with external tools, systems, and data sources. It acts as a universal connector, enabling AI agents to read files, execute functions, and handle contextual prompts in a standardized way.
For Python developers, FastMCP is a high-level framework within the official Python SDK that simplifies the creation of MCP servers. It allows you to quickly define tools, resources, and prompts using decorators, abstracting away much of the underlying protocol complexity.
Business Applications of MCP
MCP transforms how businesses can leverage AI by connecting models directly to their existing systems and data. Common business applications include:
- API Integration: Connect AI to your CRM (Salesforce, HubSpot), accounting software (QuickBooks), or any REST/GraphQL API
- Document Processing: Enable AI to read, analyze, and extract insights from business documents, contracts, and reports
- Tool Automation: Integrate AI with project management tools, communication platforms, and business workflows
- Data Analysis: Connect AI to databases, spreadsheets, and business intelligence tools for automated reporting
New to MCP? We recommend starting with Getting Started with MCP: Your First Integration to understand the basics before building your own servers.
This tutorial covers the basics, but for real business implementations, you’ll typically want to explore our advanced guides on API integration, document processing, and business tool integration.
In this tutorial, you will learn how to set up your environment, create a simple MCP server with a tool and a resource, and run it locally using FastMCP.
Step 1: Setting Up Your Python Environment
We’ll use uv
for efficient dependency management and project initialization. If you’re new to uv
, you can learn more about it in our guide: What is uv?. If you don’t have uv
installed, you can install it via pip
:
pip install uv
Now, let’s create a new project directory and initialize it with uv
, adding the mcp[cli]
dependency:
uv init mcp-server-demo
cd mcp-server-demo
uv add "mcp[cli]"
This sets up a new Python project with the necessary MCP command-line tools.
Step 2: Creating Your First MCP Server
Inside your mcp-server-demo
directory, create a new Python file named server.py
. This file will contain the code for your MCP server.
# server.py
from mcp.server.fastmcp import FastMCP
# Create an MCP server instance
# The name "DemoServer" will be visible to clients connecting to your server.
mcp = FastMCP("DemoServer")
# Define a tool: Tools allow LLMs to perform actions or computations.
# This tool adds two numbers.
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers and return their sum."""
return a + b
# Define a resource: Resources expose data to LLMs, similar to a GET endpoint.
# This resource provides a personalized greeting.
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Get a personalized greeting for a given name."""
return f"Hello, {name}! Welcome to your first MCP server."
# You can also define prompts, which are structured inputs for LLMs.
# For simplicity, we'll stick to tools and resources in this basic example.
# @mcp.prompt()
# def simple_prompt(message: str) -> str:
# return f"Please process this message: {message}"
if __name__ == "__main__":
# This block ensures the server runs when the script is executed directly.
# The 'dev' command is great for development as it provides live reloading.
mcp.run()
Explanation of the code:
from mcp.server.fastmcp import FastMCP
: Imports the necessary class from the FastMCP framework.mcp = FastMCP("DemoServer")
: Initializes your MCP server with a unique name.@mcp.tool()
: This decorator registers theadd
function as an MCP tool. The function’s signature (type hints fora
,b
, and return type) helps define the tool’s arguments and expected output for LLMs. The docstring serves as the tool’s description.@mcp.resource("greeting://{name}")
: This decorator registersget_greeting
as an MCP resource. The URIgreeting://{name}
defines how clients can access this resource, with{name}
being a dynamic path parameter.if __name__ == "__main__": mcp.run()
: This standard Python construct ensures thatmcp.run()
is called when the script is executed directly, starting your MCP server.
Step 3: Running Your MCP Server
To run your newly created MCP server, navigate to your mcp-server-demo
directory in the terminal and execute the server.py
file using uv run
:
uv run server.py
You should see output indicating that your MCP server is starting up, typically listening on a local port (e.g., http://localhost:8000
).
For development, you can also use the mcp dev
command, which provides live reloading:
mcp dev server.py
This command will automatically restart your server whenever you make changes to server.py
, which is very convenient during development.
Step 4: Interacting with Your Server (Conceptual)
Once your MCP server is running, an AI model or an MCP-compatible client application can discover and interact with the tools and resources you’ve defined.
For example:
- An LLM could call the
add
tool with arguments likeadd(a=5, b=3)
and receive8
as the result. - An LLM or client could request the
greeting://John
resource and receive"Hello, John! Welcome to your first MCP server."
as the content.
The MCP handles the communication and serialization, allowing the AI to seamlessly use your Python functions and access your data.
Conclusion
You have successfully built and run your first basic Model Context Protocol (MCP) server using FastMCP in Python. You’ve learned how to define tools for actions and resources for data exposure, laying the foundation for more complex AI integrations.
Next Steps for Business Implementation
Ready to connect MCP to your business systems? Explore these specialized guides:
Core Business Integrations:
- Connecting MCP to Business APIs - REST, GraphQL, authentication patterns
- MCP for Business Documents - PDF processing, document workflows
- Business Tool Integration - CRM, project management, accounting software
Specific Business Solutions:
- Salesforce MCP Integration - Complete CRM setup with ROI metrics
- Contract Analysis Automation - Legal document processing
- QuickBooks MCP Integration - Financial data access and reporting
Enterprise Considerations:
- A Developer’s Guide to MCP Security - Authentication, compliance, data protection
- Scaling MCP in Organizations - Performance and monitoring
From here, you can explore more advanced FastMCP features like prompts, authentication, and integrating with external services to build powerful AI applications that deliver real business value.
Related Guides
A Developer's Guide to MCP Security: Beyond the Basics
Centralize your understanding of MCP security with this comprehensive guide. Learn practical steps for authenticating servers, preventing prompt injection, validating URIs, and managing secrets.
Connect Claude to Your Business Files with MCP
Step-by-step guide to setting up Claude AI to read, analyze, and work with your business documents and spreadsheets automatically.
Set Up Your First MCP Email Assistant
Create an AI assistant that can read emails, analyze content, and help you respond faster. Perfect for managing customer inquiries and business communications.
Want More Step-by-Step Guides?
Get weekly implementation guides and practical MCP tutorials delivered to your inbox.
Subscribe for Weekly Guides