Learn how to implement MCP client-server tools for LLM integration with this practical example
This project provides an illustrative implementation of an MCP (Model Context Protocol) server, detailing how to build a custom server that can be used to integrate various AI models with diverse tools and data sources. By leveraging the standardized Model Context Protocol, developers can easily connect their applications to external resources and enhance functionality without requiring extensive code modifications or custom integration efforts.
The Example MCP Server supports two primary tools:
These tools can be seamlessly integrated into AI applications, providing essential functionalities such as health analysis or location-based services without the complexity of direct API handling within the application itself.
The architecture of the Example MCP Server is designed to follow the Model Context Protocol (MCP), ensuring compatibility with a wide range of popular MCP clients. The server exposes its available tools through a standardized interface that adheres to the protocol, allowing seamless communication between the AI application and external data or services.
Here’s a brief example illustrating how the server initializes these tools:
from mcp.server import MCPServer
class ExampleServer(MCPServer):
def __init__(self):
super().__init__()
@self.register_tool('calculate_bmi')
def calculate_bmi(weight, height):
"""Calculate Body Mass Index."""
return weight / (height ** 2)
@self.register_tool('fetch_weather')
async def fetch_weather(coordinates):
"""Fetch weather data from external API."""
# Placeholder for actual implementation
pass
# Example of starting the server:
if __name__ == '__main__':
example_server = ExampleServer()
example_server.run()
graph TD
A[AI Application] -->|MCP Client| B[MCP Protocol]
B --> C[MCP Server]
C --> D[Data Source/Tool]
style A fill:#e1f5fe
style C fill:#f3e5f5
style D fill:#e8f5e8
The diagram above illustrates the flow of interactions between an AI application using an MCP client, the MCP protocol itself, and the Example MCP Server along with its associated data sources or tools.
uv
(Python package manager)To get started quickly, follow these steps:
Install the necessary dependencies:
uv install -e .
Start the Example Server:
uv run src/server/example_server.py
AI applications can use the calculate_bmi
tool to analyze user health data, providing personalized dietary recommendations based on BMI calculations. This integration ensures that applications can offer more accurate and reliable health advice without requiring developers to implement complex mathematical computations.
# Hypothetical AI application using Example MCP Server for BMI analysis
def get_user_profile(user_data):
# Simulating user input data
weight = 75
height = 1.68
bmi_result = uv.call_tool('calculate_bmi', {'weight': weight, 'height': height})
if bmi_result < 18.5:
return "Underweight"
elif 18.5 <= bmi_result < 24.9:
return "Normal Weight"
else:
return "Overweight"
print(get_user_profile({'weight': 75, 'height': 1.68}))
Travel applications can integrate the fetch_weather
tool to provide real-time weather updates, aiding travelers in planning their trips with more accurate and up-to-date information. This integration simplifies the process of accessing external services without the need for direct API handling.
import uv
def get_weather_updates(coordinates):
result = uv.call_tool('fetch_weather', {'coordinates': coordinates})
print(f"Weather data: {result}")
get_weather_updates({'latitude': 40.7128, 'longitude': -74.0060})
The Example MCP Server is compatible with various popular MCP clients such as Claude Desktop, Continue, and Cursor. Below is a compatibility matrix highlighting the status of each client.
MCP Client | Resources | Tools | Prompts |
---|---|---|---|
Claude Desktop | ✅ | ✅ | ✅ |
Continue | ✅ | ✅ | ✅ |
Cursor | ❌ | ✅ | ❌ |
This section outlines the performance metrics and compatibility status of the Example MCP Server, ensuring that it can handle a wide range of use cases with minimal overhead.
For advanced setup, developers can tune the configuration file:
{
"mcpServers": {
"[server-name]": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-[name]"],
"env": {
"API_KEY": "your-api-key"
}
}
}
}
{
"mcpServers": {
"[server-name]": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-[name]", "--secure"],
"env": {
"API_KEY": "your-api-key"
}
}
},
"tools": {
"...": {
"inputValidate": [
{ "key": "age", "validate": { "min": 18, "msg": "Age should be at least 18." } }
]
}
}
}
A: Ensure that your application is using a compatible MCP client, such as Claude Desktop or Continue. Follow the provided example server setup to register tools and handle communication through the MCP protocol.
A: Yes, you can modify the output formats by adjusting the tool definitions within your configuration file. For example, adding custom responses or transforming data as needed.
A: The server is designed to handle concurrent requests efficiently. However, for high-traffic scenarios, consider optimizing resource allocation and implementing load balancing techniques as necessary.
A: The security configuration can be adjusted in the env
section by setting environment variables like API keys and enabling secure connections to encrypt data in transit.
A: Absolutely! You can add any custom logic or tool configurations by following the same pattern demonstrated for the BMI calculator and weather fetcher. Simply define your tool, register it with the ExampleServer
, and call it from within your application as shown.
Contributions to this project are highly encouraged. Developers interested in contributing should:
$ git clone https://github.com/yourusername/example-mcp-server.git
$ cd example-mcp-server
$ uv run test # Run unittests to ensure all is well
$ uv install . # Install dependencies
For more information on setting up and using the Example MCP Server, check out the following resources:
By leveraging this implementation, developers can build robust and flexible AI applications that seamlessly integrate with various data sources and tools through the standardized Model Context Protocol.
RuinedFooocus is a local AI image generator and chatbot image server for seamless creative control
Simplify MySQL queries with Java-based MysqlMcpServer for easy standard input-output communication
Learn to set up MCP Airflow Database server for efficient database interactions and querying airflow data
Build stunning one-page websites track engagement create QR codes monetize content easily with Acalytica
Explore CoRT MCP server for advanced self-arguing AI with multi-LLM inference and enhanced evaluation methods
Access NASA APIs for space data, images, asteroids, weather, and exoplanets via MCP integration