FASTMCP_README.mdā¢11.6 kB
# FastMCP Server
A simple, fully functional MCP (Model Context Protocol) server built using the **FastMCP** framework. This server demonstrates core MCP capabilities with minimal, clean code.
## š Features
- **Simple Setup**: Minimal code required thanks to FastMCP decorators
- **6 Tools**: Echo, time, calculator, and note management
- **2 Resources**: Server information and statistics
- **Fully Working**: Ready to use out of the box
- **Clean Code**: Uses FastMCP's elegant decorator-based API
## š Table of Contents
- [What is FastMCP?](#what-is-fastmcp)
- [Prerequisites](#prerequisites)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Available Tools](#available-tools)
- [Available Resources](#available-resources)
- [Usage Examples](#usage-examples)
- [Running the Server](#running-the-server)
- [Integration with MCP Clients](#integration-with-mcp-clients)
- [Code Structure](#code-structure)
- [Extending the Server](#extending-the-server)
- [Troubleshooting](#troubleshooting)
## What is FastMCP?
FastMCP is a high-level framework built on top of the MCP (Model Context Protocol) that makes it incredibly easy to create MCP servers. Instead of manually handling protocols, you simply use decorators like `@app.tool()` and `@app.resource()` to expose functionality.
### Why FastMCP?
- **Less Boilerplate**: No need to manually define input schemas
- **Type Safety**: Leverages Python type hints for automatic schema generation
- **Clean Code**: Decorator-based API is intuitive and readable
- **Built-in Validation**: Automatic parameter validation from type hints
## Prerequisites
- Python 3.12 or higher
- pip (Python package manager)
- Virtual environment (recommended)
## Installation
### 1. Navigate to the MCP Directory
```bash
cd MCP
```
### 2. Create and Activate Virtual Environment (if not already done)
```bash
# Create virtual environment
python3 -m venv venv
# Activate virtual environment
source venv/bin/activate # On Linux/Mac
# OR
venv\Scripts\activate # On Windows
```
### 3. Install Dependencies
The FastMCP server requires the `mcp` package, which is already included in `requirements.txt`:
```bash
pip install -r requirements.txt
```
Or install directly:
```bash
pip install mcp>=1.0.0
```
### 4. Verify Installation (Optional)
Test that everything is set up correctly:
```bash
python test_fastmcp.py
```
This will verify:
- All required modules can be imported
- Server can be created
- Tools and resources can be registered
- The main server file works correctly
## Quick Start
### 1. Verify Setup
```bash
# Activate virtual environment (if not already active)
source venv/bin/activate
# Run tests to verify setup
python test_fastmcp.py
```
### 2. Run the Server
```bash
python fast_mcp_server.py
```
The server will start in stdio mode, which is the standard transport for MCP servers. It's now ready to accept connections from MCP clients.
**Note:** The server will appear to hang - this is normal! It's waiting for MCP client connections via stdin/stdout.
## Available Tools
The server provides 6 tools for various operations:
### 1. `echo`
Echo back a message (simple test tool)
**Parameters:**
- `message` (string): The message to echo back
**Example:**
```json
{
"name": "echo",
"arguments": {
"message": "Hello, MCP!"
}
}
```
### 2. `get_time`
Get the current server time
**Parameters:** None
**Example:**
```json
{
"name": "get_time",
"arguments": {}
}
```
### 3. `calculate`
Perform basic arithmetic operations
**Parameters:**
- `a` (float): First number
- `b` (float): Second number
- `operation` (string): Operation to perform - one of: "add", "subtract", "multiply", "divide"
**Example:**
```json
{
"name": "calculate",
"arguments": {
"a": 10,
"b": 5,
"operation": "multiply"
}
}
```
### 4. `create_note`
Create a new note with title and content
**Parameters:**
- `title` (string): Note title
- `content` (string): Note content
**Example:**
```json
{
"name": "create_note",
"arguments": {
"title": "My First Note",
"content": "This is a sample note created via MCP"
}
}
```
### 5. `list_notes`
List all notes
**Parameters:** None
**Example:**
```json
{
"name": "list_notes",
"arguments": {}
}
```
### 6. `get_note`
Get a specific note by index
**Parameters:**
- `index` (integer): Note index (0-based)
**Example:**
```json
{
"name": "get_note",
"arguments": {
"index": 0
}
}
```
## Available Resources
The server provides 2 resources:
### 1. `fastmcp://server/info`
Server information resource
**Description:** Returns JSON with server name, version, description, and capabilities
**Example Response:**
```json
{
"server_name": "fast-mcp-server",
"version": "1.0.0",
"description": "A simple, fast-to-setup MCP server",
"capabilities": {
"tools": 6,
"resources": 2
}
}
```
### 2. `fastmcp://server/stats`
Server statistics resource
**Description:** Returns JSON with current statistics about the server state
**Example Response:**
```json
{
"total_notes": 3,
"server_time": "2024-01-15T10:30:45.123456"
}
```
## Usage Examples
### Example 1: Testing Basic Functionality
```python
# Using echo tool
echo("Hello from FastMCP")
# Get current time
get_time()
# Perform calculation
calculate(a=15, b=3, operation="divide")
```
### Example 2: Note Management Workflow
```python
# Create notes
create_note(title="Meeting Notes", content="Discuss project timeline")
create_note(title="Todo List", content="1. Review code\n2. Write tests")
# List all notes
list_notes()
# Get specific note
get_note(index=0)
```
### Example 3: Resource Access
```python
# Read server info
read_resource("fastmcp://server/info")
# Read server stats
read_resource("fastmcp://server/stats")
```
## Running the Server
### Stdio Mode (Default)
This is the standard mode for MCP servers. The server communicates via standard input/output:
```bash
python fast_mcp_server.py
```
### Testing the Server Locally
You can test the server using the MCP CLI or by connecting it to an MCP client like Cursor, Claude Desktop, or other MCP-compatible applications.
## Integration with MCP Clients
### Integration with Cursor
1. Open Cursor settings
2. Navigate to Features ā MCP Servers
3. Click "Add new MCP server"
4. Configure:
- **Name:** `fast-mcp-server`
- **Type:** `command`
- **Command:** `python`
- **Args:** `["/path/to/fast_mcp_server.py"]`
- **Working Directory:** `/path/to/MCP`
### Integration with Claude Desktop
Add to your Claude Desktop MCP configuration file:
```json
{
"mcpServers": {
"fast-mcp-server": {
"command": "python",
"args": ["/absolute/path/to/fast_mcp_server.py"],
"cwd": "/absolute/path/to/MCP"
}
}
}
```
### Integration with Other MCP Clients
The server uses standard stdio transport, so it should work with any MCP-compatible client that supports command-based servers.
## Code Structure
```
fast_mcp_server.py
āāā FastMCP Server Instance
ā āāā app = FastMCP(name="fast-mcp-server")
āāā Data Storage
ā āāā notes_db: List[Dict[str, Any]]
āāā Tool Definitions
ā āāā @app.tool() echo()
ā āāā @app.tool() get_time()
ā āāā @app.tool() calculate()
ā āāā @app.tool() create_note()
ā āāā @app.tool() list_notes()
ā āāā @app.tool() get_note()
āāā Resource Definitions
āāā @app.resource() server_info()
āāā @app.resource() server_stats()
```
### Key Components
1. **FastMCP Instance**: The main server object that manages tools, resources, and MCP protocol
2. **Tool Decorators**: `@app.tool()` automatically registers functions as MCP tools
3. **Resource Decorators**: `@app.resource()` registers functions as MCP resources
4. **Type Hints**: Used for automatic schema generation and validation
## Extending the Server
### Adding a New Tool
Simply add a function with the `@app.tool()` decorator:
```python
@app.tool()
def my_new_tool(param1: str, param2: int) -> str:
"""Description of what the tool does
Args:
param1: Description of param1
param2: Description of param2
"""
# Your implementation here
return f"Result: {param1} and {param2}"
```
### Adding a New Resource
Add a function with the `@app.resource()` decorator:
```python
@app.resource("fastmcp://my-resource")
def my_resource() -> str:
"""Description of the resource"""
return json.dumps({"data": "value"}, indent=2)
```
### Adding Async Tools
FastMCP supports both sync and async functions:
```python
@app.tool()
async def async_tool(param: str) -> str:
"""Async tool example"""
# Async operations here
await some_async_operation()
return "Done"
```
### Using Context in Tools
FastMCP provides a Context object for advanced features like logging and progress reporting:
```python
from mcp.server.fastmcp import Context
@app.tool()
async def tool_with_context(param: str, ctx: Context) -> str:
"""Tool that uses context for logging"""
await ctx.info(f"Processing {param}")
await ctx.report_progress(50, 100)
return "Result"
```
## Troubleshooting
### Issue: "ModuleNotFoundError: No module named 'mcp'"
**Solution:**
```bash
pip install mcp>=1.0.0
```
### Issue: "Command not found: python"
**Solution:**
- Use `python3` instead of `python`
- Make sure Python is installed and in your PATH
- Activate your virtual environment
### Issue: Server starts but client can't connect
**Solution:**
1. Verify the server is running in stdio mode
2. Check that the path to the script is correct and absolute
3. Ensure the working directory is set correctly
4. Check that all dependencies are installed in the same environment
### Issue: Tools not appearing in client
**Solution:**
1. Verify the server is running correctly
2. Check client logs for connection errors
3. Ensure the MCP client configuration is correct
4. Try restarting both server and client
### Debug Mode
To run with more verbose logging, you can modify the server initialization:
```python
app = FastMCP(name="fast-mcp-server", debug=True, log_level="DEBUG")
```
## Architecture Notes
### Why FastMCP?
FastMCP abstracts away the low-level MCP protocol details, allowing you to focus on your business logic:
- **Automatic Schema Generation**: Type hints automatically generate JSON schemas
- **Parameter Validation**: Automatic validation based on type hints
- **Clean API**: Decorator-based approach is more Pythonic
- **Less Code**: Significantly less boilerplate compared to low-level MCP server implementation
### Transport Layer
This server uses **stdio transport**, which is the standard for MCP servers. The server communicates via standard input/output, making it compatible with all MCP clients.
### Data Persistence
Currently, the server uses in-memory storage (`notes_db`). For production use, you might want to:
- Add database integration (SQLite, PostgreSQL, etc.)
- Implement file-based persistence
- Add persistence to the lifespan context
## Contributing
To extend this server:
1. Follow the existing pattern for tools and resources
2. Use type hints for automatic schema generation
3. Add docstrings for tool descriptions
4. Test with an MCP client before committing
## License
This is a demonstration project for educational purposes.
## Resources
- [MCP Documentation](https://modelcontextprotocol.io)
- [FastMCP GitHub](https://github.com/modelcontextprotocol/python-sdk)
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
---
**Happy Coding with FastMCP!** š