server.py
Overview
server.py implements an asynchronous MCP (Modular Cloud Platform) server for querying zoo animal data. It provides two primary API tools that enable clients to retrieve animal information either filtered by species or by individual animal name. These tools are exposed using the FastMCP framework, which manages asynchronous HTTP endpoints in a modular and scalable manner.
The file contains a static in-memory dataset of zoo animals, each represented as a dictionary with attributes such as species, name, age, enclosure, and trail. The MCP server runs on a configurable port (default 8080), listens for incoming HTTP requests, and responds asynchronously with the requested animal data.
This setup supports efficient, concurrent access for clients that need to query zoo animal records, without the overhead of external databases.
Classes and Functions
mcp = FastMCP("Zoo Animal MCP Server 🦁🐧🐻")
Type:
FastMCPinstancePurpose: Creates the MCP server instance named "Zoo Animal MCP Server 🦁🐧🐻".
Usage: Registers tool functions with the
@mcp.tool()decorator and runs the server asynchronously.
get_animals_by_species(species: str) -> List[Dict[str, Any]]
Decorator:
@mcp.tool()Description: Returns a list of all animals matching the given species.
Parameters:
species(str): The species name to filter by (e.g., "lion", "penguin").
Returns: List of dictionaries, each representing an animal with keys:
species,name,age,enclosure,trail.Behavior:
Matches species case-insensitively.
Logs tool invocation.
Usage Example:
lions = get_animals_by_species("lion") for lion in lions: print(lion["name"], lion["age"])Implementation Detail:
Uses a list comprehension filtering the
ZOO_ANIMALSlist by matching the lowercase species string.
get_animal_details(name: str) -> Dict[str, Any]
Decorator:
@mcp.tool()Description: Retrieves detailed information for a single animal identified by name.
Parameters:
name(str): The name of the animal to find.
Returns:
A dictionary of the animal’s details if found.
An empty dictionary
{}if no animal matches the provided name.
Behavior:
Case-insensitive exact match on the animal’s name.
Logs tool invocation.
Usage Example:
details = get_animal_details("Simba") if details: print(details["species"], details["enclosure"]) else: print("Animal not found.")Implementation Detail:
Iterates through the
ZOO_ANIMALSlist, returning the first matching animal.
Main Execution Block
if __name__ == "__main__":
port = int(os.getenv("PORT", 8080))
logger.info(f"🚀 MCP server started on port {port}")
asyncio.run(
mcp.run_async(
transport="http",
host="0.0.0.0",
port=port,
)
)
Purpose: Starts the MCP server asynchronously.
Details:
Reads the
PORTenvironment variable or defaults to 8080.Logs server startup.
Runs the MCP server with HTTP transport, listening on all interfaces.
Interaction: Facilitates deployment flexibility by allowing port configuration via environment variables.
Data Structures
ZOO_ANIMALS
Type: List of dictionaries
Contents: Static dataset representing zoo animals.
Each animal dictionary includes:
species(str): Animal species (e.g., "lion", "penguin").name(str): Animal’s given name.age(int): Animal’s age in years.enclosure(str): Name of the enclosure where the animal is housed.trail(str): Name of the trail or exhibit path the animal is associated with.
Usage: Serves as the in-memory data source for both API tools.
Important Implementation Details
Asynchronous Tool Framework: Both API functions are decorated with
@mcp.tool(), registering them as asynchronous tools managed by the FastMCP server. This enables concurrent, non-blocking processing of requests.Case-Insensitive Matching: Both species and name queries normalize inputs to lowercase to ensure matching is case-insensitive, improving client usability.
In-Memory Dataset: The use of a static list for animal data allows fast lookups without external dependencies but limits data mutability and scalability.
Logging: Each tool logs its invocation along with the query parameter, aiding in monitoring and debugging.
Port Configuration: The server’s listening port is configurable via the
PORTenvironment variable, enabling flexible deployment setups.
Interactions with Other System Components
FastMCP Framework: The MCP server instance (
mcp) orchestrates the registration and execution of API tools. It abstracts the HTTP transport layer, managing asynchronous request/response cycles.Client Applications: External clients send HTTP requests to the MCP server to invoke the
get_animals_by_speciesorget_animal_detailstools, receiving JSON responses containing animal data.Deployment Environment: The server is designed to run in environments like Google Cloud Run, which manage containerized deployments and provide scalable infrastructure for the MCP server.
Logging Infrastructure: Logs generated by the server can be captured by operational monitoring tools, supporting observability as described in Operational Monitoring & Environment Management.
Visual Diagram
classDiagram
class FastMCP {
+tool()
+run_async()
}
class server.py {
-ZOO_ANIMALS: List[Dict]
+get_animals_by_species()
+get_animal_details()
+main()
}
FastMCP <.. server.py : uses
server.py o-- "list" : ZOO_ANIMALS
server.py : +get_animals_by_species()
server.py : +get_animal_details()
This class diagram illustrates the key components of server.py:
The
FastMCPclass instance (mcp) manages the asynchronous tools.The
server.pymodule holds the in-memory datasetZOO_ANIMALSand defines two main tool functions.The
main()function runs the MCP server asynchronously on a given host and port.
References to Related Topics
The
get_animals_by_speciestool corresponds to the Species-Based Animal Lookup subtopic, which details functionality for retrieving animals filtered by species.The
get_animal_detailstool aligns with the Animal Detail Retrieval subtopic, explaining how to fetch detailed data for an individual animal.Deployment and operational considerations for this server are further covered in topics like Cloud Run Deployment Automation and Operational Monitoring & Environment Management.