Step-by-step guide to creating a Model Context Protocol server from scratch, enabling seamless AI integration with your business systems.
Model Context Protocol (MCP) is an open standard that enables AI models to securely access and interact with external data sources, tools, and services. Think of it as a bridge that allows AI assistants to connect with your business systems, databases, and APIs in a standardized way.
# Create a new project directory mkdir my-mcp-server && cd my-mcp-server # Initialize Python environment python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate # Install MCP SDK pip install mcp-sdk fastapi uvicorn
# server.py from mcp import Server, Tool, Resource from typing import Dict, Any import json class MyMCPServer: def __init__(self): self.server = Server("my-first-mcp-server") self.setup_tools() self.setup_resources() def setup_tools(self): @self.server.tool("calculator") async def calculator(operation: str, a: float, b: float) -> Dict[str, Any]: """Perform basic mathematical operations""" try: if operation == "add": result = a + b elif operation == "subtract": result = a - b elif operation == "multiply": result = a * b elif operation == "divide": result = a / b if b != 0 else "Error: Division by zero" else: return {"error": "Unsupported operation"} return { "operation": operation, "operands": [a, b], "result": result } except Exception as e: return {"error": str(e)} def setup_resources(self): @self.server.resource("company-info") async def get_company_info() -> Dict[str, Any]: """Get basic company information""" return { "name": "My Company", "founded": "2020", "employees": 50, "description": "A growing tech company" } def run(self, host: str = "localhost", port: int = 8000): import uvicorn uvicorn.run(self.server.app, host=host, port=port)
# main.py from server import MyMCPServer if __name__ == "__main__": server = MyMCPServer() print("Starting MCP Server on http://localhost:8000") server.run()
python main.py # Server will start on http://localhost:8000 # API documentation available at http://localhost:8000/docs
# Using curl to test the calculator curl -X POST "http://localhost:8000/tools/calculator" \ -H "Content-Type: application/json" \ -d '{ "operation": "add", "a": 10, "b": 5 }' # Expected response: { "operation": "add", "operands": [10, 5], "result": 15 }
# Get company information curl "http://localhost:8000/resources/company-info" # Expected response: { "name": "My Company", "founded": "2020", "employees": 50, "description": "A growing tech company" }
# Add to server.py from fastapi import HTTPException, Depends from fastapi.security import HTTPBearer security = HTTPBearer() async def verify_api_key(token: str = Depends(security)): if token.credentials != "your-secret-api-key": raise HTTPException(status_code=401, detail="Invalid API key") return token # Add to your tool decorators @self.server.tool("calculator", dependencies=[Depends(verify_api_key)])
Congratulations! You've built your first MCP server. Here's what to explore next:
Create tools for file operations, API calls, or business-specific functions.
Connect your server to AI agents for automated business processes.
Add logging, monitoring, and scaling capabilities for production use.