Skip to main content
Glama
advanced_server.py5.06 kB
"""Advanced MCP server example with custom classes.""" import sys from pathlib import Path # Add parent directory to path for imports sys.path.insert(0, str(Path(__file__).parent.parent.parent)) import anyio from typing import Any import mcp.types as types from mcp.server.stdio import stdio_server from mcp_server_hero.core.server import MCPServerHero from mcp_server_hero.tools.base import BaseTool from mcp_server_hero.resources.base import BaseResource from mcp_server_hero.prompts.base import BasePrompt class CalculatorTool(BaseTool): """Calculator tool with multiple operations.""" def __init__(self) -> None: super().__init__( name="calculator", description="Perform mathematical calculations", schema={ "type": "object", "properties": { "operation": { "type": "string", "enum": ["add", "subtract", "multiply", "divide"], "description": "Mathematical operation to perform", }, "a": {"type": "number", "description": "First number"}, "b": {"type": "number", "description": "Second number"}, }, "required": ["operation", "a", "b"], }, ) async def execute(self, arguments: dict[str, Any]) -> list[types.ContentBlock]: """Execute the calculator tool.""" operation = arguments["operation"] a = float(arguments["a"]) b = float(arguments["b"]) 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 [types.TextContent(type="text", text="Error: Division by zero")] result = a / b else: return [types.TextContent(type="text", text=f"Error: Unknown operation {operation}")] return [types.TextContent(type="text", text=f"Result: {result}")] class StatusResource(BaseResource): """Server status resource.""" def __init__(self) -> None: super().__init__( uri="status://server", name="server_status", description="Current server status information", mime_type="application/json", ) async def read(self) -> str: """Read the server status.""" import json import time status = { "status": "running", "uptime": time.time(), "server": "MCP Server Hero", "version": "0.1.0", } return json.dumps(status, indent=2) class CodePrompt(BasePrompt): """Code generation prompt.""" def __init__(self) -> None: super().__init__( name="code", description="Generate code in specified language", arguments=[ {"name": "language", "description": "Programming language", "required": True}, {"name": "task", "description": "Task description", "required": True}, {"name": "style", "description": "Code style preference", "required": False}, ], ) async def generate(self, arguments: dict[str, str] | None = None) -> types.GetPromptResult: """Generate the code prompt.""" if arguments is None: arguments = {} language = arguments.get("language", "python") task = arguments.get("task", "") style = arguments.get("style", "clean") prompt_text = f"""Please write {style} {language} code that accomplishes the following task: {task} Requirements: - Follow best practices for {language} - Include appropriate comments - Handle edge cases and errors - Make the code maintainable and readable""" return types.GetPromptResult( messages=[ types.PromptMessage( role="user", content=types.TextContent(type="text", text=prompt_text), ) ], description=f"Code generation prompt for {language}", ) async def main() -> None: """Run the advanced MCP server example.""" # Create server instance server = MCPServerHero(name="Advanced Example Server", debug=True) # Register custom tool calculator = CalculatorTool() server.add_tool( name=calculator.name, tool_func=calculator, ) # Register custom resource status = StatusResource() server.add_resource( uri=status.uri, resource_func=status, ) # Register custom prompt code_prompt = CodePrompt() server.add_prompt( name=code_prompt.name, prompt_func=code_prompt, ) # Run the server async with stdio_server() as streams: await server.run(streams[0], streams[1], server.create_initialization_options()) if __name__ == "__main__": anyio.run(main)

Latest Blog Posts

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/namnd00/mcp-server-hero'

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