Create a Model Context Protocol (MCP) server in Python that Claude can use as a tool. Expose custom functions, databases, and APIs to Claude Code and Claude Desktop.
An MCP server exposes tools Claude can call during any session — without you modifying API calls. This example builds a minimal MCP server in Python using the official mcp SDK.
pip install mcp
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("my-tools")
@mcp.tool()
def get_word_count(text: str) -> int:
"""Count the number of words in a text string."""
return len(text.split())
@mcp.tool()
def calculate(expression: str) -> float:
"""Safely evaluate a mathematical expression like '2 + 3 * 4'."""
import ast, operator
ops = {ast.Add: operator.add, ast.Sub: operator.sub,
ast.Mult: operator.mul, ast.Div: operator.truediv}
def eval_node(node):
if isinstance(node, ast.Constant):
return node.value
if isinstance(node, ast.BinOp):
return ops[type(node.op)](eval_node(node.left), eval_node(node.right))
raise ValueError(f"Unsupported: {node}")
tree = ast.parse(expression, mode="eval")
return eval_node(tree.body)
if __name__ == "__main__":
mcp.run()
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("company-data")
@mcp.resource("company://team-roster")
def get_team_roster() -> str:
"""Current team roster in CSV format."""
return "name,role,team
Alice,Engineer,Platform
Bob,Designer,Product"
@mcp.tool()
def lookup_employee(name: str) -> dict:
"""Look up an employee by name. Returns role and team."""
roster = {
"Alice": {"role": "Engineer", "team": "Platform"},
"Bob": {"role": "Designer", "team": "Product"}
}
return roster.get(name, {"error": f"{name} not found"})
if __name__ == "__main__":
mcp.run(transport="stdio")
# ~/.claude/settings.json
{
"mcpServers": {
"my-tools": {
"command": "python",
"args": ["/path/to/your/server.py"],
"env": {}
}
}
}
mcp dev /path/to/server.py
Browse available MCP servers and skills at the Claude Skills Browser. For API-level tool use (without MCP), see the tool use Python example.