Skip to main content
Glama

MCP Server Demo

by bollam1818
server.py6.46 kB
#!/usr/bin/env python3 """ MCP Server Demo A demonstration server showcasing various MCP capabilities including: - Tools for calculations and data processing - Resources for dynamic data access - Prompts for common LLM interactions """ import json import datetime from typing import List, Dict, Any from mcp.server.fastmcp import FastMCP # Create the MCP server mcp = FastMCP("Demo Server", dependencies=["pandas", "numpy"]) # ============================================================================= # TOOLS - Functions that LLMs can call to perform actions # ============================================================================= @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 calculate_bmi(weight_kg: float, height_m: float) -> float: """Calculate Body Mass Index (BMI) given weight in kg and height in meters""" if height_m <= 0: raise ValueError("Height must be greater than 0") return round(weight_kg / (height_m ** 2), 2) @mcp.tool() def analyze_numbers(numbers: List[int]) -> Dict[str, Any]: """Analyze a list of numbers and return statistics""" if not numbers: return {"error": "No numbers provided"} return { "count": len(numbers), "sum": sum(numbers), "average": round(sum(numbers) / len(numbers), 2), "minimum": min(numbers), "maximum": max(numbers), "sorted": sorted(numbers) } @mcp.tool() def get_current_time() -> str: """Get the current date and time""" return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # ============================================================================= # RESOURCES - Data that LLMs can access (like GET endpoints) # ============================================================================= @mcp.resource("greeting://{name}") def get_greeting(name: str) -> str: """Get a personalized greeting for a given name""" current_hour = datetime.datetime.now().hour if 5 <= current_hour < 12: time_greeting = "Good morning" elif 12 <= current_hour < 17: time_greeting = "Good afternoon" elif 17 <= current_hour < 21: time_greeting = "Good evening" else: time_greeting = "Good night" return f"{time_greeting}, {name}! Welcome to the MCP server demo." @mcp.resource("config://app") def get_app_config() -> str: """Get the application configuration""" config = { "server_name": "Demo MCP Server", "version": "1.0.0", "features": [ "Calculator tools", "Personalized greetings", "Number analysis", "Time utilities" ], "created_at": "2024-01-27", "author": "MCP Demo Team" } return json.dumps(config, indent=2) @mcp.resource("weather://{city}") def get_weather_info(city: str) -> str: """Get mock weather information for a city""" # This is mock data - in a real implementation, you'd call a weather API weather_data = { "city": city, "temperature": "22°C", "condition": "Sunny", "humidity": "45%", "wind": "10 km/h", "last_updated": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") } return json.dumps(weather_data, indent=2) # ============================================================================= # PROMPTS - Reusable templates for LLM interactions # ============================================================================= @mcp.prompt() def review_code(code: str) -> str: """Create a prompt for code review""" return f"""Please review the following code and provide feedback on: 1. Code quality and readability 2. Potential bugs or issues 3. Performance considerations 4. Best practices adherence 5. Suggestions for improvement Code to review: ```python {code} ``` Please provide a detailed review with specific recommendations.""" @mcp.prompt() def debug_error(error_message: str) -> str: """Create a prompt for debugging an error""" return f"""I'm encountering the following error and need help debugging: **Error Message:** ``` {error_message} ``` **Context:** - I'm working on a Python project using the MCP (Model Context Protocol) SDK - The error occurred recently and I'm not sure what's causing it **What I've tried so far:** - [Please list any troubleshooting steps you've attempted] **Questions:** 1. What could be causing this error? 2. How can I fix it? 3. How can I prevent similar issues in the future? 4. Are there any debugging tools or techniques you'd recommend? Please provide a step-by-step solution and explain the root cause.""" @mcp.prompt() def explain_concept(concept: str) -> str: """Create a prompt for explaining a technical concept""" return f"""Please explain the concept of "{concept}" in a clear and comprehensive way. Please include: 1. **Definition**: What is {concept}? 2. **How it works**: The underlying mechanism or process 3. **Use cases**: When and why would you use {concept}? 4. **Examples**: Practical examples or code snippets 5. **Best practices**: Important considerations and tips 6. **Common pitfalls**: Things to avoid or watch out for Make the explanation accessible to someone with intermediate programming knowledge. Use analogies or real-world comparisons where helpful.""" # ============================================================================= # SERVER INITIALIZATION # ============================================================================= if __name__ == "__main__": # This allows the server to be run directly # In development mode, use: mcp dev server.py import asyncio async def main(): print("Starting MCP Demo Server...") print("Available tools: add, multiply, calculate_bmi, analyze_numbers, get_current_time") print("Available resources: greeting://, config://app, weather://") print("Available prompts: review_code, debug_error, explain_concept") print("\nTo run in development mode: mcp dev server.py") print("To install in Claude Desktop: mcp install server.py") # The FastMCP server will handle the protocol automatically # This is just for demonstration - in practice, use mcp dev server.py asyncio.run(main())

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/bollam1818/MCPServer'

If you have feedback or need assistance with the MCP directory API, please join our Discord server