Files
ds_mcp_template/examples/demo_server.py
T
2025-09-11 23:13:58 +01:00

181 lines
5.7 KiB
Python

#!/usr/bin/env python3
"""
MCP Template Demo Server
Demonstrates how to create and run different types of MCP servers
"""
import asyncio
import sys
import os
# Add src to path for imports
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
from server.server_factory import MCPServerFactory
async def demo_calculator_server():
"""Demo: Create and run a calculator server with SSE transport"""
print("🚀 Starting Calculator Server with SSE transport...")
server = MCPServerFactory.create_basic_calculator_server(
name="Demo Calculator Server",
transport="sse",
host="localhost",
port=8050
)
print("📊 Available tools:")
tools = await server.list_tools()
for tool in tools:
print(f"{tool['name']}: {tool['description']}")
print("🌐 Server will be available at: http://localhost:8050/sse")
print("💡 To test: Run 'python examples/demo_client.py' in another terminal")
await server.start()
async def demo_knowledge_base_server():
"""Demo: Create and run a knowledge base server with STDIO transport"""
print("🚀 Starting Knowledge Base Server with STDIO transport...")
# Custom knowledge base data
kb_data = {
"company_info": "TechCorp is a leading AI solutions provider founded in 2020.",
"mission": "Our mission is to democratize AI through open-source tools and education.",
"values": "Innovation, transparency, collaboration, and ethical AI development.",
"contact": "Email: info@techcorp.com | Phone: (555) 123-4567"
}
server = MCPServerFactory.create_knowledge_base_server(
name="Demo Knowledge Base Server",
transport="stdio",
kb_data=kb_data
)
print("📚 Available tools:")
tools = await server.list_tools()
for tool in tools:
print(f"{tool['name']}: {tool['description']}")
print("💻 Server running in STDIO mode")
print("💡 To test: Run 'python examples/demo_client.py' in another terminal")
await server.start()
async def demo_custom_server():
"""Demo: Create a custom server with mixed tools and resources"""
print("🚀 Starting Custom Server with mixed capabilities...")
# Custom tools
async def greet_user(name: str, style: str = "formal") -> str:
"""Generate a personalized greeting"""
if style == "casual":
return f"Hey {name}! Welcome aboard! 🎉"
elif style == "professional":
return f"Good day, {name}. Welcome to our platform."
else:
return f"Hello, {name}. Welcome!"
async def calculate_bmi(weight_kg: float, height_m: float) -> str:
"""Calculate BMI and provide health category"""
bmi = weight_kg / (height_m ** 2)
if bmi < 18.5:
category = "Underweight"
elif bmi < 25:
category = "Normal weight"
elif bmi < 30:
category = "Overweight"
else:
category = "Obese"
return f"Your BMI is {bmi:.1f} ({category})"
from core.types import MCPTool
tools = [
MCPTool(
name="greet_user",
description="Generate a personalized greeting with different styles",
input_schema={
"type": "object",
"properties": {
"name": {"type": "string", "description": "User's name"},
"style": {
"type": "string",
"enum": ["casual", "formal", "professional"],
"description": "Greeting style"
}
},
"required": ["name"]
},
handler=greet_user
),
MCPTool(
name="calculate_bmi",
description="Calculate BMI and provide health assessment",
input_schema={
"type": "object",
"properties": {
"weight_kg": {"type": "number", "description": "Weight in kilograms"},
"height_m": {"type": "number", "description": "Height in meters"}
},
"required": ["weight_kg", "height_m"]
},
handler=calculate_bmi
)
]
server = MCPServerFactory.create_server(
name="Demo Custom Server",
transport="stdio",
tools=tools
)
print("🛠️ Available tools:")
tools_list = await server.list_tools()
for tool in tools_list:
print(f"{tool['name']}: {tool['description']}")
print("💻 Server running in STDIO mode")
print("💡 To test: Run 'python examples/demo_client.py' in another terminal")
await server.start()
async def main():
"""Main demo function"""
if len(sys.argv) != 2:
print("Usage: python demo_server.py <server_type>")
print("Available server types:")
print(" calculator - Basic calculator with math operations")
print(" knowledge - Knowledge base with searchable content")
print(" custom - Custom server with mixed capabilities")
sys.exit(1)
server_type = sys.argv[1].lower()
try:
if server_type == "calculator":
await demo_calculator_server()
elif server_type == "knowledge":
await demo_knowledge_base_server()
elif server_type == "custom":
await demo_custom_server()
else:
print(f"Unknown server type: {server_type}")
sys.exit(1)
except KeyboardInterrupt:
print("\n👋 Server stopped by user")
except Exception as e:
print(f"❌ Error running server: {e}")
sys.exit(1)
if __name__ == "__main__":
asyncio.run(main())