fast_mcp_server.py•3.46 kB
#!/usr/bin/env python3
"""
FastMCP Server - A simple, fast-to-setup MCP server example
Demonstrates core MCP capabilities with minimal code using FastMCP framework
"""
import json
from datetime import datetime
from typing import Any, Dict, List, Literal
from mcp.server.fastmcp import FastMCP
# Create the FastMCP server instance
app = FastMCP(name="fast-mcp-server")
# In-memory storage for demonstration
notes_db: List[Dict[str, Any]] = []
# Tool definitions using FastMCP decorators
@app.tool()
def echo(message: str) -> str:
"""Echo back a message (simple test tool)"""
return f"Echo: {message}"
@app.tool()
def get_time() -> str:
"""Get the current server time"""
return f"Current server time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
@app.tool()
def calculate(a: float, b: float, operation: Literal["add", "subtract", "multiply", "divide"]) -> str:
"""Perform basic arithmetic operations
Args:
a: First number
b: Second number
operation: Operation to perform (add, subtract, multiply, divide)
"""
if operation == "add":
result = a + b
elif operation == "subtract":
result = a - b
elif operation == "multiply":
result = a * b
elif operation == "divide":
if b == 0:
return "Error: Division by zero"
result = a / b
else:
return f"Error: Unknown operation '{operation}'"
return f"Result: {result}"
@app.tool()
def create_note(title: str, content: str) -> str:
"""Create a new note with title and content
Args:
title: Note title
content: Note content
"""
note = {
"id": len(notes_db),
"title": title,
"content": content,
"created_at": datetime.now().isoformat()
}
notes_db.append(note)
return f"Note created successfully! ID: {note['id']}"
@app.tool()
def list_notes() -> str:
"""List all notes"""
if not notes_db:
return "No notes found."
notes_list = "\n".join([
f"{i}. {note['title']} (ID: {note['id']}) - Created: {note['created_at']}"
for i, note in enumerate(notes_db)
])
return f"Notes:\n{notes_list}"
@app.tool()
def get_note(index: int) -> str:
"""Get a specific note by index
Args:
index: Note index (0-based)
"""
if index < 0 or index >= len(notes_db):
return f"Error: Note index {index} out of range"
note = notes_db[index]
return json.dumps({
"id": note["id"],
"title": note["title"],
"content": note["content"],
"created_at": note["created_at"]
}, indent=2)
# Resource definitions using FastMCP decorators
@app.resource("fastmcp://server/info")
def server_info() -> str:
"""Server information resource"""
info = {
"server_name": "fast-mcp-server",
"version": "1.0.0",
"description": "A simple, fast-to-setup MCP server",
"capabilities": {
"tools": 6,
"resources": 2
}
}
return json.dumps(info, indent=2)
@app.resource("fastmcp://server/stats")
def server_stats() -> str:
"""Server statistics resource"""
stats = {
"total_notes": len(notes_db),
"server_time": datetime.now().isoformat()
}
return json.dumps(stats, indent=2)
if __name__ == "__main__":
# Run the server using stdio transport (standard for MCP)
app.run(transport="stdio")