from server import mcp@mcp.tool()def multiply(first_val: float, second_val: float) -> float: ''' Calculate the product of two numbers Args: first_val: the first value to be multiplied second_val: the second value to be multiplied ''' return round(first_val * second_val, 4)
Comprehensive docstrings help the AI understand when and how to use your tool:
@mcp.tool()def search_database(query: str, limit: int = 10) -> list[dict]: """ Search the database for matching records Args: query: Search query string limit: Maximum number of results to return (default: 10) Returns: List of matching records as dictionaries """ # Implementation pass
Here’s a more complex tool that demonstrates best practices:
from server import mcpfrom typing import Optionalimport json@mcp.tool()def fetch_user_profile( user_id: str, include_history: bool = False, max_items: Optional[int] = None) -> dict: """ Fetch a user's profile information from the database This tool retrieves user profile data and optionally includes their activity history. Use this when you need to look up information about a specific user. Args: user_id: Unique identifier for the user include_history: Whether to include activity history (default: False) max_items: Maximum number of history items to return (optional) Returns: Dictionary containing user profile data with keys: - id: User ID - name: User's full name - email: User's email address - history: Activity history (if include_history=True) Raises: ValueError: If user_id is not found """ # Your implementation here profile = { "id": user_id, "name": "John Doe", "email": "john@example.com" } if include_history: history = get_user_history(user_id, max_items) profile["history"] = history return profile
# Good - focused functionality@mcp.tool()def calculate_average(numbers: list[float]) -> float: """Calculate the arithmetic mean of a list of numbers""" return sum(numbers) / len(numbers)# Avoid - doing too much@mcp.tool()def analyze_data(data: list[float]) -> dict: """Calculate average, median, mode, stddev, and generate charts""" # Too many responsibilities pass
@mcp.tool()def divide(numerator: float, denominator: float) -> float: """ Divide two numbers Args: numerator: The number to be divided denominator: The number to divide by Returns: The quotient Raises: ValueError: If denominator is zero """ if denominator == 0: raise ValueError("Cannot divide by zero") return numerator / denominator