Skip to main content
Glama

Calculator MCP Server

by TechSuvam
MCP_SERVER_GUIDE.md9.88 kB
# MCP Server: How It Works & Use Cases ## What is MCP (Model Context Protocol)? **Model Context Protocol (MCP)** is an open protocol that enables AI assistants and applications to securely connect to external data sources and tools. It provides a standardized way for AI models to interact with external resources like databases, APIs, file systems, and custom tools. ## How MCP Servers Work ### Architecture Overview ``` ┌─────────────┐ JSON-RPC over stdio ┌──────────────┐ │ MCP Client │ ◄─────────────────────────────────► │ MCP Server │ │ (AI/App) │ (Standard Input/Output) │ (Your Tool) │ └─────────────┘ └──────────────┘ ``` ### Communication Flow 1. **Transport Layer**: Uses stdio (standard input/output) for communication - Client sends JSON-RPC requests to server's stdin - Server sends JSON-RPC responses to client's stdout - Simple, universal, no network complexity 2. **Protocol**: JSON-RPC 2.0 - Standardized request/response format - Supports method calls, notifications, and error handling - Language-agnostic (works with any language) 3. **Initialization Sequence**: ``` Client → initialize request Server → initialization options (capabilities) Client → initialized notification Client ↔ Server (ready for communication) ``` 4. **Tool Discovery**: ``` Client → tools/list request Server → list of available tools with schemas ``` 5. **Tool Execution**: ``` Client → tools/call request (tool name + arguments) Server → result (text, data, or error) ``` ### Key Components #### 1. **Server Instance** ```python server = Server("my-server-name") ``` - Creates the server that handles protocol communication - Manages request routing and response formatting #### 2. **Tool Handlers** ```python @server.list_tools() async def list_tools() -> list[Tool]: # Return available tools @server.call_tool() async def call_tool(name: str, arguments: dict) -> Sequence[TextContent]: # Execute the requested tool ``` #### 3. **Transport** ```python async with stdio_server() as (read_stream, write_stream): await server.run(read_stream, write_stream, init_options) ``` - Sets up bidirectional communication - Handles JSON-RPC message parsing and routing ## Real-World Use Cases ### 1. **Database Integration** **Use Case**: Allow AI to query databases ``` Server Tools: - query_database: Execute SQL queries - list_tables: Show available tables - describe_schema: Get table structure ``` **Example**: AI assistant can answer questions like "How many users signed up this month?" by querying your database. ### 2. **File System Access** **Use Case**: AI can read/write files in controlled directories ``` Server Tools: - read_file: Read file contents - write_file: Write to files - list_directory: Browse directories - search_files: Find files by pattern ``` **Example**: AI can analyze codebases, generate documentation, or manage project files. ### 3. **API Integration** **Use Case**: Connect AI to external services ``` Server Tools: - fetch_weather: Get weather data - send_email: Send emails - create_calendar_event: Manage calendar - search_github: Query GitHub API ``` **Example**: "Schedule a meeting tomorrow at 3pm" → AI uses calendar API through MCP server. ### 4. **Calculator/Math Operations** (Your Example!) **Use Case**: Perform calculations and mathematical operations ``` Server Tools: - add, subtract, multiply, divide - power, sqrt, evaluate expressions ``` **Example**: AI can solve math problems, perform calculations, or verify mathematical expressions. ### 5. **Code Execution** **Use Case**: Safely execute code in sandboxed environments ``` Server Tools: - execute_python: Run Python code - execute_sql: Run SQL queries - lint_code: Check code quality ``` **Example**: AI can test code snippets, run queries, or validate code. ### 6. **Web Scraping/Content Fetching** **Use Case**: Fetch and analyze web content ``` Server Tools: - fetch_url: Get webpage content - extract_text: Parse HTML - search_web: Web search integration ``` **Example**: AI can research topics, analyze web pages, or gather real-time information. ### 7. **Authentication & Authorization** **Use Case**: Manage user credentials and permissions ``` Server Tools: - validate_user: Check authentication - check_permissions: Verify access rights - generate_token: Create auth tokens ``` **Example**: Secure access to sensitive data or operations. ### 8. **Development Tools** **Use Case**: Support software development workflows ``` Server Tools: - git_status: Check git status - run_tests: Execute test suites - deploy_app: Deploy applications - check_logs: View application logs ``` **Example**: AI can help with development tasks, debugging, and deployment. ### 9. **Data Processing** **Use Case**: Transform and analyze data ``` Server Tools: - process_csv: Parse CSV files - transform_data: Apply data transformations - generate_report: Create reports ``` **Example**: AI can analyze datasets, generate insights, or process files. ### 10. **IoT & Hardware Control** **Use Case**: Control devices and sensors ``` Server Tools: - get_sensor_data: Read sensor values - control_device: Send commands - monitor_status: Check device status ``` **Example**: Home automation, industrial monitoring, or device control. ## Benefits of MCP Servers ### 1. **Security** - Servers run as separate processes - Isolated from main application - Can enforce access controls - Prevents direct code execution in AI context ### 2. **Modularity** - Each server handles specific functionality - Easy to add/remove capabilities - Independent development and deployment - Reusable across different AI clients ### 3. **Standardization** - Universal protocol (JSON-RPC) - Works with any language - Consistent interface - Easy to integrate ### 4. **Extensibility** - Add new tools without changing AI code - Update servers independently - Version control per server - Flexible architecture ### 5. **Testing & Debugging** - Test servers independently - Easy to mock for testing - Clear request/response format - Simple error handling ## How Your Calculator Server Fits In Your **Calculator MCP Server** demonstrates a perfect use case: ### What It Does - Provides mathematical calculation capabilities - Exposes 7 calculator tools - Handles complex expressions safely ### Why It's Useful 1. **AI Integration**: AI assistants can perform math without built-in calculator 2. **Safe Evaluation**: Restricted expression evaluation prevents code injection 3. **Modular**: Can be used by multiple AI clients 4. **Extensible**: Easy to add more math functions ### Integration Example ``` User asks AI: "What's 15% of 250?" AI client → calls calculator MCP server → multiply tool → 250 * 0.15 Server → returns 37.5 AI client → "37.5" ``` ## Common Patterns ### Pattern 1: Query Handler ```python @server.call_tool() async def call_tool(name: str, arguments: dict): if name == "query": # Execute query and return results return [TextContent(text=result)] ``` ### Pattern 2: CRUD Operations ```python # Create, Read, Update, Delete operations - create_item - read_item - update_item - delete_item ``` ### Pattern 3: Data Transformation ```python # Transform input to output - transform_data(input_format, output_format, data) ``` ### Pattern 4: Status Checking ```python # Monitor and report status - get_status - health_check - list_resources ``` ## Best Practices 1. **Error Handling**: Always handle errors gracefully ```python try: result = perform_operation() except Exception as e: return [TextContent(text=f"Error: {str(e)}")] ``` 2. **Input Validation**: Validate all inputs ```python if not numbers: return [TextContent(text="Error: No numbers provided")] ``` 3. **Security**: Restrict dangerous operations ```python # Only allow safe operations allowed_functions = {"safe_func1", "safe_func2"} ``` 4. **Documentation**: Clear tool descriptions ```python Tool( name="add", description="Add numbers together", inputSchema={...} ) ``` 5. **Async Operations**: Use async/await for I/O ```python async def call_tool(...): result = await some_async_operation() ``` ## Example: Building Your Own MCP Server ### Step 1: Define Your Use Case "What do I want the AI to be able to do?" - Example: "I want AI to search my bookmarks" ### Step 2: Design Your Tools "What operations does the AI need?" - Example: `search_bookmarks`, `add_bookmark`, `list_bookmarks` ### Step 3: Implement the Server ```python server = Server("bookmark-server") @server.list_tools() async def list_tools(): return [ Tool(name="search_bookmarks", ...), Tool(name="add_bookmark", ...), ] @server.call_tool() async def call_tool(name: str, arguments: dict): if name == "search_bookmarks": query = arguments.get("query") results = search_bookmarks(query) return [TextContent(text=results)] ``` ### Step 4: Test Your Server Use the MCP Inspector or create test scripts ### Step 5: Integrate with AI Client Add to client configuration and start using! ## Conclusion MCP servers are a powerful way to extend AI capabilities by connecting them to: - **Data sources** (databases, APIs, files) - **Tools** (calculators, validators, processors) - **Services** (email, calendar, notifications) - **Hardware** (sensors, devices, actuators) Your calculator server is a great example of how simple, focused tools can enhance AI functionality!

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/TechSuvam/MCP'

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