MCP Demo UI & Server Suite
A comprehensive interactive UI and demo server suite for learning and experimenting with the Model Context Protocol (MCP). This project includes:
- 🖥️ Interactive Web UI - Visual MCP architecture explorer and server manager
- 🔧 4 Demo MCP Servers - Calculator, Database, API Integration, and File System servers
- 📚 Educational Content - Learn MCP concepts through hands-on examples
- 🛠️ Tool Testing Interface - Execute MCP tools in real-time
- 📡 Protocol Inspector - Monitor MCP communication messages
- 🎯 Production-Ready Code - Async/await patterns with proper error handling
🚀 Quick Start
1. Install Dependencies
uv sync
2. Start the Demo UI
uv run python ui_backend.py
3. Open in Browser
Navigate to: http://localhost:8000
4. Explore & Learn
- View MCP architecture diagrams
- Start/stop demo servers
- Test tools interactively
- Monitor protocol messages
- Learn MCP concepts
📖 What is MCP?
Model Context Protocol (MCP) is an open protocol that enables AI assistants and applications to securely access external data sources and tools. It provides a standardized way for AI models to:
- 🔌 Connect to External APIs - Weather, news, databases, etc.
- 💾 Access File Systems - Read/write files and directories
- 🛠️ Execute Custom Functions - Domain-specific business logic
- 📊 Query Databases - SQL operations and data retrieval
- 🤖 Extend AI Capabilities - Beyond training data limitations
MCP acts as a bridge between AI applications and external resources, allowing models to extend their capabilities through secure, standardized interfaces.
🎯 Why MCP Matters
MCP solves critical challenges in AI application development:
🔒 Security & Control
- Problem: Direct API access from AI models raises security concerns
- Solution: MCP servers act as controlled gateways with proper authentication
📊 Real-Time Data Access
- Problem: AI models have training cutoffs and can't access live data
- Solution: MCP servers provide access to live APIs, databases, and services
🏗️ Standardization
- Problem: Each AI application needs custom integration code
- Solution: Standardized MCP protocol works across different AI applications
🛠️ Custom Business Logic
- Problem: Generic AI models don't know your specific business processes
- Solution: MCP servers expose domain-specific tools and workflows
⚡ Action Execution
- Problem: AI models can only generate text, not perform actions
- Solution: MCP servers execute tools on behalf of the AI model
🏛️ MCP Architecture
MCP follows a client-server architecture with multiple transport options:
Visual Architecture
┌─────────────┐ MCP Protocol ┌─────────────┐
│ │ ◄──────────────────────────► │ │
│ MCP Client │ (JSON-RPC over stdio) │ MCP Server │
│ (AI App) │ │ (This App) │
│ │ │ │
└─────────────┘ └─────────────┘
│
│
┌───────┴───────┐
│ │
External APIs Databases
File Systems Services
Key Components
| Component | Description | Example |
|---|---|---|
| MCP Client | AI application making requests | Claude Desktop, custom AI app |
| MCP Server | Your application exposing tools | This demo server |
| Transport Layer | JSON-RPC protocol | stdio or HTTP |
| Tools | Functions client can call | add(), list_expenses() |
| Resources | Data sources to access | File contents, API data |
| Prompts | Pre-defined prompt templates | Custom instruction sets |
Transport Mechanisms
1. Stdio (Standard I/O)
- Use Case: Local development, Claude Desktop integration
- Communication: Direct process stdin/stdout
- Pros: Low latency, simple, secure
- Cons: Single client, local only
2. HTTP
- Use Case: Production, multiple clients, remote access
- Communication: HTTP requests/responses
- Pros: Network-based, scalable, multiple clients
- Cons: Higher latency, network configuration needed
Communication Flow
- Client sends JSON-RPC request
- Server processes request (calls tools/fetches resources)
- Server sends JSON-RPC response
- Client uses response in AI context
🔄 MCP Server Lifecycle
1. Initialization
- Server starts and listens on transport (stdio/HTTP)
- Server registers available tools, resources, and prompts
- Server sends initialization message to client
2. Handshake
- Client and server exchange capabilities
- Client requests server information (name, version, available tools)
- Server responds with its capabilities
3. Operation
- Client sends tool execution requests
- Server processes requests and executes tools
- Server returns results to client
- This cycle repeats for each interaction
4. Shutdown
- Client sends shutdown signal
- Server cleans up resources
- Server terminates gracefully
Start Server → Initialize FastMCP → Register Tools → Listen on stdio/HTTP
│
▼
Client Connects → Handshake → Request Tool → Execute Tool → Return Result
│
▼
Continue Listening...
🛠️ Demo MCP Servers
The suite includes 4 comprehensive demo servers showcasing different MCP use cases:
1. 🧮 Calculator Server (Port 8081)
Basic arithmetic operations with async/await patterns
add(a, b)- Additionsubtract(a, b)- Subtractionmultiply(a, b)- Multiplicationdivide(a, b)- Divisionpower(base, exponent)- Exponentiationsquare_root(number)- Square root calculation
2. 💾 Database Server (Port 8082)
Expense tracking with SQLite and proper error handling
add_expense(description, amount, category, ...)- Add expenselist_expenses(limit)- List expensesget_expense(expense_id)- Get specific expensedelete_expense(expense_id)- Delete expenseget_expense_summary()- Get expense statistics
3. 🌐 API Integration Server (Port 8083)
External API integrations (mock implementations)
get_weather(city)- Weather dataget_news(category, limit)- News articlessearch_github(query, limit)- GitHub repository searchget_crypto_price(symbol)- Cryptocurrency pricestranslate_text(text, target_language)- Text translation
4. 📁 File System Server (Port 8084)
Safe file system operations within project directory
list_directory(path)- List directory contentsread_file(path, max_lines)- Read text fileswrite_file(path, content, append)- Write to filessearch_files(query, path, file_types)- Search file contentsget_file_info(path)- Get file/directory metadata
🎮 Using the Demo UI
Prerequisites
- Python 3.12 or higher
uvpackage manager (recommended)
Installation
# Clone or navigate to project directory
cd fastmcp-demo-server
# Install dependencies
uv sync
Start the Interactive UI
# Start the demo UI server
uv run python ui_backend.py
Access the UI at: http://localhost:8000
UI Features
🏗️ Architecture Tab
- Interactive MCP architecture diagram
- Key components explanation
- Transport mechanism comparison
- Communication flow visualization
🖥️ Servers Tab
- Server Management: Start/stop individual demo servers
- Real-time Status: See which servers are running and their ports
- Auto-refresh: Server status updates automatically
🔧 Tools Tab
- Tool Selection: Choose from available tools across servers
- Parameter Input: Dynamic form generation for tool parameters
- Live Execution: Execute tools and see results in real-time
- Execution History: Track previous tool calls and responses
📡 Protocol Tab
- Message Inspector: Monitor JSON-RPC communication
- Protocol Viewer: See raw MCP protocol messages
- Debugging Tools: Clear logs and refresh monitoring
📚 Learn Tab
- Educational Content: MCP concepts and best practices
- Code Examples: Working implementations with explanations
- Use Cases: Real-world applications of MCP
- Further Reading: Links to documentation and resources
Testing Individual Servers
You can also test servers individually:
# Test Calculator Server
uv run python demo_servers/calculator_server.py
# Test Database Server
uv run python demo_servers/database_server.py
# Test API Server
uv run python demo_servers/api_server.py
# Test File System Server
uv run python demo_servers/filesystem_server.py
Using with Claude Desktop
- Configure MCP Server:
uv run fastmcp install claude-desktop main.py
-
Restart Claude Desktop to load the new server
-
Use tools in chat - Claude will now have access to your MCP tools
✨ Key Features & Benefits
🎓 Educational Value
- Interactive Learning: Hands-on experience with MCP concepts
- Visual Architecture: See how MCP components work together
- Protocol Inspection: Understand JSON-RPC communication
- Best Practices: Learn production-ready patterns
🛠️ Development Features
- Async/Await Patterns: Modern Python concurrency
- Error Handling: Comprehensive try/except blocks
- Type Safety: Proper parameter validation
- Resource Management: Safe database and file operations
🔧 Practical Applications
- Database Integration: SQLite operations with async support
- API Orchestration: Multiple external service integrations
- File System Operations: Safe file manipulation within project bounds
- Mathematical Computing: Calculator with advanced operations
🌐 Production Ready
- Scalable Architecture: HTTP transport for multiple clients
- Security Considerations: Controlled file access, input validation
- Monitoring: Logging and error reporting
- Documentation: Comprehensive code comments and docstrings
📁 Project Structure
fastmcp-demo-server/
├── ui_backend.py # FastAPI backend for the demo UI
├── main.py # Original expense tracker server
├── local-guide.md # Development and deployment guide
├── pyproject.toml # Project dependencies and metadata
├── uv.lock # Dependency lock file
├── expenses.db # SQLite database (auto-created)
├── .gitignore # Git ignore rules
└── demo_servers/ # Individual demo MCP servers
├── calculator_server.py # Arithmetic operations server
├── database_server.py # Expense tracking server
├── api_server.py # External API integrations
└── filesystem_server.py # File system operations server
🏗️ Architecture Overview
UI Backend (FastAPI)
- Purpose: Serves the interactive web UI and manages demo servers
- Features: Server lifecycle management, tool testing, protocol inspection
- Endpoints: REST API for server control and tool execution
- Frontend: Bootstrap-based responsive web interface
Demo Servers (FastMCP)
- Framework: FastMCP for simplified MCP server development
- Transport: HTTP for network access and multiple clients
- Async Support: Full async/await implementation with error handling
- Security: Controlled access boundaries (especially for file operations)
Key Implementation Details
Async/Await Patterns
@mcp.tool
async def add_expense(description: str, amount: float, category: str) -> dict:
try:
async with aiosqlite.connect(DB_PATH) as conn:
# Async database operations
await conn.execute(...)
await conn.commit()
return {"status": "success"}
except Exception as e:
return {"status": "error", "message": str(e)}
Error Handling Strategy
- Database Errors:
aiosqlite.Errorfor connection/query issues - Validation Errors: Custom validation with descriptive messages
- System Errors: General
Exceptionhandling with logging - Graceful Degradation: Return structured error responses
Security Measures
- File Operations: Restricted to project directory only
- Input Validation: Type checking and parameter validation
- Resource Limits: Connection pooling, timeout handling
- Access Control: Path traversal prevention
🚀 Advanced Usage
Development Workflow
1. Using uv Package Manager
# Initialize new MCP project
mkdir my-mcp-server
cd my-mcp-server
uv init .
uv add fastmcp aiosqlite aiofiles aiohttp
# Create server
# ... add your server code ...
# Run in development mode
uv run fastmcp dev main.py
# Run production server
uv run fastmcp run main.py
# Install to Claude Desktop
uv run fastmcp install claude-desktop main.py
2. MCP Inspector for Debugging
# Start inspector (usually at http://localhost:8000)
uv run fastmcp dev main.py
# Test tools and inspect protocol messages
# Monitor server behavior in real-time
Production Deployment
Environment Configuration
# Set environment variables
export MCP_SERVER_PORT=8080
export MCP_SERVER_HOST=0.0.0.0
export DATABASE_URL=sqlite:///production.db
# Run with production settings
uv run python main.py
Docker Deployment
FROM python:3.12-slim
WORKDIR /app
COPY . .
RUN pip install uv && uv sync --no-dev
EXPOSE 8080
CMD ["uv", "run", "python", "main.py"]
📚 Learning Path
Beginner Level
- Start the Demo UI - Explore the interactive interface
- Run Individual Servers - Test each demo server separately
- Examine Code - Read through the implementations
- Modify Tools - Add your own simple tools
Intermediate Level
- Add New Tools - Extend existing servers with new functionality
- Create Resources - Implement MCP resources (not just tools)
- Add Prompts - Create reusable prompt templates
- Error Handling - Improve error handling and validation
Advanced Level
- Custom Transport - Implement custom transport mechanisms
- Authentication - Add authentication and authorization
- Monitoring - Add metrics and logging
- Scaling - Handle multiple concurrent clients
- Production Deployment - Deploy to cloud platforms
🔗 Resources
Official Documentation
Community Resources
Development Tools
- MCP Inspector: Built-in tool for debugging MCP servers
- uv: Fast Python package manager and project manager
- FastAPI: Modern async web framework (used in UI backend)
🤝 Contributing
Ways to Contribute
- Add New Demo Servers - Create servers for different use cases
- Improve UI Features - Enhance the interactive interface
- Add Educational Content - Create more learning materials
- Fix Bugs - Report and fix issues
- Documentation - Improve guides and examples
Development Setup
# Fork and clone
git clone https://github.com/yourusername/fastmcp-demo-server.git
cd fastmcp-demo-server
# Install dependencies
uv sync
# Start development
uv run python ui_backend.py
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
🙏 Acknowledgments
- Anthropic for creating the Model Context Protocol
- FastMCP team for the excellent framework
- uv team for the amazing package manager
- Bootstrap team for the UI framework
Happy MCP Development! 🎉
Learn, experiment, and build amazing AI-powered applications with the Model Context Protocol.