Building Your First MCP Server in Python
These articles are AI-generated summaries. Please check the original sources for full details.
Why Construct a Server from Scratch?
While existing MCP servers may cover common use cases, custom business logic, local file manipulation, and unique automation require bespoke implementations; Python’s prevalence in AI makes it the ideal platform, despite the overhead of maintaining custom code versus leveraging existing solutions. Ignoring this can lead to significant technical debt and hinder integration with specialized systems.
Key Insights
uvpackage manager simplifies Python dependency management: Released 2023- MCP separates LLM interaction into Tools, Resources, and Prompts: Enables modularity and clearer architectural boundaries.
- FastMCP framework boosts developer velocity: Reduces boilerplate and streamlines server construction.
Working Example
from mcp.server.fastmcp import FastMCP
import math
# Initialize the server
mcp = FastMCP("Calculator Server")
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two numbers together."""
return a + b
@mcp.tool()
def multiply(a: int, b: int) -> int:
"""Multiply two numbers together."""
return a * b
@mcp.tool()
def sqrt(x: float) -> str:
"""Calculate the square root of a number."""
if x < 0:
return "Cannot calculate square root of a negative number"
return str(math.sqrt(x))
@mcp.resource("resource://docs/typescript-sdk")
def get_typescript_sdk_docs() -> str:
"""Reads the TypeScript SDK documentation."""
path = "./docs/typescript_sdk.md"
try:
with open(path, "r") as f:
return f.read()
except FileNotFoundError:
return "Documentation file not found."
@mcp.prompt()
def meeting_summary(date: str, title: str, transcript: str) -> str:
"""Generates a structured meeting summary."""
return f"""
You are an executive assistant. Analyze the following meeting.
Data: {date}
Title: {title}
Transcript:
{transcript}
Provide a comprehensive analysis including participants and key decisions.
"""
if __name__ == "__main__":
#Allows switching based on deployment needs
mcp.run(transport="stdio")
Practical Applications
- Financial Modeling: Integrate a server with a live stock API as a tool and company reports as resources.
- Pitfall: Overly complex prompts can overwhelm the LLM, leading to irrelevant or incoherent outputs. Keep prompts focused and use clear variable names.
References:
Continue reading
Next article
Compromised IAM Credentials Power a Large AWS Crypto Mining Campaign
Related Content
LangChain Complete Guide: Building Production-Ready LLM Applications
Master LangChain for building production LLM applications. Learn chains, agents, memory systems, RAG, vector stores, evaluation, and deployment strategies with practical Python examples.
Building a Movie Search App with Python and Streamlit: A Practical Guide
A Python-based movie search app using Streamlit and OMDb API, demonstrating API integration and UI design.
How to Extract Tables from PDFs Using Python (Without Losing Your Mind)
This article details methods for extracting tables from PDFs using Python, acknowledging the complexities beyond simple text extraction and offering an API solution.