MCP Server Demo
A demonstration project showcasing the Model Context Protocol (MCP) server implementation using FastMCP.
Overview
This project demonstrates how to build a simple MCP server using the FastMCP framework. The server provides:
- A basic arithmetic tool (add) that adds two integers
- A dynamic greeting resource that generates personalized greetings
What is MCP?
The Model Context Protocol (MCP) is a standardized protocol for connecting AI models with external tools and resources. It enables:
- Tools: Functions that AI models can call to perform actions
- Resources: Data sources that AI models can read from
- Prompts: Templates for AI interactions
Project Structure```
mcp-server-demo/
├── README.md # This file
├── pyproject.toml # Project configuration and dependencies
├── uv.lock # Dependency lock file
├── main.py # Simple entry point
├── server.py # MCP server implementation
├── .python-version # Python version specification (3.12)
├── .gitignore # Git ignore patterns
└── prompt/ # Status reports directory
## Features
### Tools
- **add(a: int, b: int) -> int**: Adds two integers and returns the result
### Resources
- **greeting://{name}**: Dynamic resource that generates a greeting message for the specified name
## Requirements
- Python 3.12+ (specified in `.python-version`)
- uv (for dependency management)
- MCP library with CLI extras
## Dependencies
The project uses the following main dependencies:
- `mcp[cli]>=1.9.0`: The Model Context Protocol library with CLI support
### Key transitive dependencies:
- `anyio`: Async I/O library
- `httpx`: HTTP client library
- `pydantic`: Data validation library
- `starlette`: Web framework
- `uvicorn`: ASGI server
- `typer`: CLI framework
## Installation
1. Clone the repository:```bash
git clone <repository-url>
cd mcp-server-demo
```
2. Install dependencies using uv:```bash
uv sync
```
## Usage
### Running the Basic Script```bash
uv run python main.py
This will output: Hello from mcp-server-demo!
Running the MCP Server
The server can be run in different modes:
STDIO Mode (Standard Input/Output)```bash
uv run python -c "from server import mcp; import asyncio; asyncio.run(mcp.run_stdio_async())"
#### SSE Mode (Server-Sent Events)```bash
uv run python -c "from server import mcp; import asyncio; asyncio.run(mcp.run_sse_async())"
HTTP Streaming Mode```bash
uv run python -c "from server import mcp; import asyncio; asyncio.run(mcp.run_streamable_http_async())"
### Testing the Server Functionality
You can test the server components programmatically:```python
from server import mcp
import asyncio
async def test_server():
# Test the add tool
result = await mcp.call_tool('add', {'a': 5, 'b': 3})
print(f"5 + 3 = {result}")
# Test the greeting resource
greeting = await mcp.read_resource('greeting://World')
print(greeting)
# Run the test
asyncio.run(test_server())
Code Examples
Server Implementation (server.py)```python
from mcp.server.fastmcp import FastMCP
Create an MCP server instance
mcp = FastMCP("Demo")
Define a tool (function that can be called)
@mcp.tool()
def add(a: int, b: int) -> int:
"""Add two integers together."""
return a + b
Define a dynamic resource
@mcp.resource("greeting://{name}")
def get_greeting(name: str) -> str:
"""Generate a personalized greeting."""
return f"Hello, {name}!"
### Main Entry Point (main.py)```python
def main():
print("Hello from mcp-server-demo!")
if __name__ == "__main__":
main()
Development
Setting up the Development Environment
- Ensure you have Python 3.12+ installed
- Install uv:
curl -LsSf https://astral.sh/uv/install.sh | sh - Clone the repository and install dependencies:
bash git clone <repository-url> cd mcp-server-demo uv sync
Project Configuration
The project uses pyproject.toml for configuration:```toml
[project]
name = "mcp-server-demo"
version = "0.1.0"
description = "Add your description here"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"mcp[cli]>=1.9.0",
]
### Adding New Tools
To add a new tool to the server:```python
@mcp.tool()
def your_tool_name(param1: type, param2: type) -> return_type:
"""Tool description."""
# Your implementation here
return result
Adding New Resources
To add a new resource:python
@mcp.resource("resource://pattern/{param}")
def get_resource(param: str) -> str:
"""Resource description."""
# Your implementation here
return resource_content
Architecture
The MCP server is built using the FastMCP framework, which provides:
- Async Support: Built on asyncio for concurrent operations
- Multiple Transport Modes: STDIO, SSE, and HTTP streaming
- Type Safety: Uses Pydantic for data validation
- Easy Integration: Simple decorators for tools and resources
Troubleshooting
Common Issues
- Python Version: Ensure you're using Python 3.12+
- Dependencies: Run
uv syncto install all dependencies - Import Errors: Make sure you're in the correct directory and using
uv run
Development Tips
- Use
uv runto execute Python scripts in the project environment - The server functions are async, so use
asyncio.run()for testing - Check the
prompt/directory for status reports during development
License
This project is for demonstration purposes. Please check the MCP library license for usage rights.
Contributing
This is a demo project. For contributing to the MCP library itself, please refer to the main MCP repository.
Resources
- MCP Documentation
- FastMCP Documentation
- uv Documentation
Last updated: 2024-07-16
