Feedback

Chat Icon

Practical MCP with FastMCP & LangChain

Engineering the Agentic Experience

Error Handling in FastMCP Servers
47%

Exception Types

FastMCP offers specific exception types for different operations, for example:

  • ToolError: For tool execution failures
  • ResourceError: For resource read failures
  • PromptError: For prompt retrieval failures
  • McpError: For general MCP protocol errors (imported from mcp, not fastmcp.exceptions)
  • AuthorizationError: For authentication/authorization failures

These exceptions can be raised with custom messages that are intended to be seen by the parts of the system that consume them.

Basic Pattern: Raising ToolError

Our tool code looks like this:

@mcp.tool
def dog_to_human_age(
    age: Annotated[int, Field(ge=0, le=30, description="The dog's age in years")],
    multiplier: int = Depends(get_age_multiplier),
) -> int:
    """Calculate the real age of a dog in human years."""
    return age * multiplier

We are going to evolve this tool to do more complex things. We will base our age calculator on the dog breed, which we will fetch from an external function:

def get_breed_multiplier(breed: str) -> int | None:
    """Fetch the age multiplier for a given dog breed."""
    breed_multipliers = {
        "labrador": 7,
        "chihuahua": 5,
        "german shepherd": 8,
        "bulldog": 6,
        # We have a lot more breeds
        # but for brevity we only list a few here
    }
    return breed_multipliers.get(breed.lower())

@mcp.tool
def dog_to_human_age(
    age: Annotated[int, Field(ge=0, le=30, description="The dog's age in years")],
    breed: str,
) -> int:
    """Calculate the real age of a dog in human years based on its breed."""
    multiplier = get_breed_multiplier(breed)
    return age *

Practical MCP with FastMCP & LangChain

Engineering the Agentic Experience

Enroll now to unlock current content and receive all future updates for free. Your purchase supports the author and fuels the creation of more exciting content. Act fast, as the price will rise as the course nears completion!