Content
# Tool List
## 🚀 MCP Tool Management Server
A tool management server based on the MCP (Model Context Protocol) protocol, providing secure tool registration, management, and execution functions.
## 🎯 Core Features
### 🔧 Tool Management
- **Secure Tool Execution**: Built-in secure calculator to prevent code injection
- **Dynamic Tool Discovery**: Automatic discovery and registration of MCP tools
- **Distributed Testing Architecture**: Test cases and tool modules managed in the same location
- **Modular Design**: Clear architecture design, easy to extend
### 🗄️ Data Management
- **MySQL Database Support**: Complete database connection pool management
- **Connection Pool Optimization**: Intelligent connection pool management with retry mechanism
- **Data Model**: Complete tool data model and CRUD operations
### 📊 System Monitoring
- **Performance Monitoring**: Real-time system performance indicators monitoring
- **Health Check**: Built-in health check endpoint
- **Cache System**: High-performance cache mechanism
### 🧪 Testing System
- **Dynamic Testing Discovery**: Automatic discovery of distributed test functions
- **Interactive Testing**: Support for command line and interactive testing modes
- **Test Classification**: Test management by functional classification
## 🏗️ System Architecture
### Design Principles
#### 1. Modular Design
- **Single Responsibility**: Each module focuses on a specific function
- **Loose Coupling**: Modules communicate through clear interfaces
- **High Cohesion**: Related functions are concentrated in the same module
#### 2. Layered Architecture
- **Presentation Layer**: MCP protocol interface and HTTP endpoint
- **Business Layer**: Tool logic and business rules
- **Data Layer**: Database operations and persistence
#### 3. Scalability
- **Plugin-based**: Tool modules can be dynamically loaded
- **Configurable**: System behavior is controlled by configuration
- **Standardized**: Unified interfaces and protocols
### Architecture Diagram
```
┌─────────────────────────────────────────────────────────────┐
│ MCP Tool Management Server Architecture │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────────┐ ┌─────────────┐ │
│ │ Client App │◄──►│ MCP Protocol Interface │◄──►│ Tool Registry │ │
│ │ (AI Assistants, etc.) │ │ │ │ │ │
│ └─────────────┘ └─────────────────┘ └─────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Business Logic Layer │ │
│ ├─────────────────────────────────────────────────────────┤ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │ │
│ │ │ Time Tool │ │ Calculator Tool │ │ Tool Manager │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────────┘ │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Data Access Layer │ │
│ ├─────────────────────────────────────────────────────────┤ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │ │
│ │ │ Connection Management │ │ Data Model │ │ Cache System │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────────┘ │ │
│ └─────────────────────────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────────────────────────┐ │
│ │ Infrastructure Layer │ │
│ ├─────────────────────────────────────────────────────────┤ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────┐ │ │
│ │ │ MySQL Database │ │ Configuration Management │ │ Log System │ │ │
│ │ │ │ │ │ │ │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────────┘ │ │
│ └─────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
### Core Module Description
#### 1. Configuration Management Module (`src/core/config.py`)
**Responsibility**: Unified management of application configuration, supporting environment variables and default values
```python
class DevelopmentConfig:
"""Development environment configuration class"""
# Server configuration
SERVER_HOST: str = os.getenv("SERVER_HOST", "localhost")
SERVER_PORT: int = int(os.getenv("SERVER_PORT", "3000"))
# Database configuration
DATABASE_HOST: str = os.getenv("DATABASE_HOST", "localhost")
DATABASE_PORT: int = int(os.getenv("DATABASE_PORT", "3306"))
@property
def DATABASE_URL(self) -> str:
"""Dynamically generate database connection URL"""
return f"mysql+pymysql://{self.DATABASE_USER}:{self.DATABASE_PASSWORD}@{self.DATABASE_HOST}:{self.DATABASE_PORT}/{self.DATABASE_NAME}"
```
#### 2. Server Main Entrance (`src/core/server.py`)
**Responsibility**: Create and configure MCP server instance
```python
def create_server() -> FastMCP:
"""Create and configure MCP server"""
# 1. Create server instance
mcp = FastMCP(config.SERVER_NAME)
# 2. Initialize database
db_manager = DatabaseManager(config.DATABASE_URL)
# 3. Register tools
register_all_tools(mcp, db_manager)
# 4. Configure health check
@mcp.resource("mcp://health")
def health_check() -> dict:
return {"status": "healthy"}
return mcp
```
#### 3. Database Connection Management (`src/database/connection.py`)
**Responsibility**: Manage database connection pool and session
```python
class DatabaseManager:
"""Database manager"""
def __init__(self, database_url: str):
# Create connection engine
self.engine = create_engine(
database_url,
poolclass=QueuePool,
pool_size=config.POOL_SIZE,
max_overflow=config.MAX_OVERFLOW
)
# Create session factory
self.SessionLocal = sessionmaker(
autocommit=False,
autoflush=False,
bind=self.engine
)
```
#### 4. Tool Registry (`src/tools/registry.py`)
**Responsibility**: Unified management of tool registration process
```python
def register_all_tools(mcp: FastMCP, db_manager: DatabaseManager) -> None:
"""Register all tools"""
# Register simple tools (no dependencies)
register_echo_tool(mcp)
register_calculator_tool(mcp)
register_datetime_tool(mcp)
# Register management tools (dependent on database)
register_tool_manager_tools(mcp, db_manager)
```
## 📦 Project Structure
```
mcp-test/
├── src/ # Source code directory
│ ├── core/ # Core module
│ │ ├── config.py # Configuration management - environment variables and default configuration
│ │ └── server.py # Server main entrance - MCP server creation and startup
│ ├── database/ # Database module
│ │ ├── connection.py # Connection management - database connection pool and session management
│ │ ├── models.py # Data model - ORM model definition
│ │ └── operations.py # Database operation - CRUD operation encapsulation
│ ├── tools/ # Tool module
│ │ ├── simple/ # Simple tools (no dependencies)
│ │ │ ├── calculator.py # Secure calculator - mathematical expression calculation
│ │ │ ├── datetime_tool.py # Time and date tool - multi-timezone time conversion
│ │ │ └── echo.py # Echo tool - message echo function
│ │ ├── management/ # Management tools (dependent on database)
│ │ │ └── tool_manager.py # Tool manager - tool CRUD operation
│ │ └── registry.py # Tool registry - unified tool registration
│ └── utils/ # Utility class
│ ├── cache.py # Cache system - high-performance cache mechanism
│ └── monitor.py # Performance monitoring - system performance indicators
├── test.py # Main test script - distributed testing architecture
├── start.py # Startup script - server startup entrance
├── init_mysql.py # Database initialization - database table creation
└── requirements.txt # Dependency management - Python package dependency
```
## 🚀 Quick Start
### Environment Requirements
- Python 3.8+
- MySQL 5.7+
- Virtual environment support
### Install Dependencies
```bash
# Create virtual environment
python -m venv .venv
# Activate virtual environment
# Windows
.venv\Scripts\activate
# Linux/Mac
source .venv/bin/activate
# Install dependencies
pip install -r requirements.txt
```
### Configure Environment
Copy `.env.example` file and configure your environment variables:
```bash
# Server configuration
SERVER_HOST=localhost
SERVER_PORT=3000
SERVER_NAME=mcp-tool-server-dev
# MySQL database configuration
DATABASE_HOST=localhost
DATABASE_PORT=3306
DATABASE_USER=root
DATABASE_PASSWORD=123456
DATABASE_NAME=mcp_dev
# Application configuration
DEBUG=true
LOG_LEVEL=DEBUG
SECRET_KEY=dev-secret-key-for-development
```
### Initialize Database
```bash
# Initialize database
python init_mysql.py
```
### Start Server
```bash
# Start in development environment
python start.py
# Or directly run
python -m src.core.server
```
## 🔧 Available Tools
### Built-in Tools
#### 1. **Secure Calculator** (`calculator`)
- **Function**: Secure mathematical expression calculation
- **Features**: Prevent code injection attacks, support basic operations and complex expressions
- **Location**: `src/tools/simple/calculator.py`
#### 2. **Time and Date Tool** (`datetime_tool`)
- **Function**: Multi-timezone time conversion, timestamp formatting, time difference calculation
- **Features**: Support major timezones, accurate time calculation
- **Location**: `src/tools/simple/datetime_tool.py`
#### 3. **Echo Tool** (`echo`)
- **Function**: Simple message echo
- **Features**: Special character processing, performance optimization
- **Location**: `src/tools/simple/echo.py`
#### 4. **Tool Manager** (`tool_manager`)
- **Function**: Tool CRUD operation, search and statistics
- **Features**: Database dependency, classification management
- **Location**: `src/tools/management/tool_manager.py`
### Extended Tools
The project supports dynamic tool discovery. New tools can be added by creating corresponding modules in the `src/tools/` directory.
## 🧪 Testing System
The project adopts an advanced distributed testing architecture, with test cases and tool modules managed in the same location.
### Run Tests
```bash
# Run all tests
python test.py --all
# Run specified tool tests
python test.py --test datetime_tool calculator
# Run tests by category
python test.py --category Tool Function
# Interactive testing mode
python test.py --interactive
```
### Test Features
- **Dynamic Discovery**: Automatically discover test functions in tool modules
- **Distributed Management**: Test cases and tool code are managed together
- **Detailed Report**: Complete test result summary
- **Performance Testing**: Built-in performance benchmark testing
## 🔧 Tool Development Guide
### Development Principles
#### 1. Single Responsibility Principle
- Each tool focuses on a specific functional area
- Avoid overly complex or overlapping tool functions
- Keep tool interfaces concise and clear
#### 2. Interface Consistency Principle
- Follow unified tool registration pattern
- Use standard parameter and return value formats
- Maintain consistent error handling
#### 3. Test-Driven Principle
- Tools and test code are managed together
- Write comprehensive test cases
- Ensure tests cover core functions
### Development Process
#### 1. Determine Tool Type
**Simple Tools** (no external dependencies)
- Location: `src/tools/simple/`
- Characteristics: Pure calculation, no state, no database dependencies
- Examples: Calculator, Time Tool, Echo Tool
**Management Tools** (dependent on database)
- Location: `src/tools/management/`
- Characteristics: Data operation, state management, database dependencies
- Examples: Tool Manager, User Management
#### 2. Create Tool Module
**Simple Tool Template**
```python
"""
MCP Tool Management Server - [Tool Name] Tool Module
[Tool Function Description]
[Feature Description]
[Usage Example]
"""
from typing import Dict, List, Optional
from mcp.server.fastmcp import FastMCP
class [ToolName]Tool:
"""
[Tool Name] Tool Class
[Class Function Description]
[Method Description]
"""
@staticmethod
def [method_name](param1: type, param2: type) -> Dict[str, any]:
"""
[Method Function Description]
Args:
param1 (type): [Parameter Description]
param2 (type): [Parameter Description]
Returns:
Dict[str, any]: [Return Value Description]
"""
# Method Implementation
pass
def register_[tool_name]_tool(mcp: FastMCP) -> None:
"""
Register [Tool Name] Tool to MCP Server
Args:
mcp (FastMCP): FastMCP Server Instance
"""
@mcp.tool()
def [tool_function](param1: type, param2: type) -> Dict[str, any]:
"""[Tool Function Description]"""
return [ToolName]Tool.[method_name](param1, param2)
```
#### 3. Add Test Functions
```python
# =============================================================================
# [Tool Name] Tool Specific Test Functions
# =============================================================================
def test_[tool_name]_functionality() -> bool:
"""Test [Tool Name] Tool's Core Functionality"""
print("🧪 Testing [Tool Name] Tool Core Functionality...")
try:
# Test Case Implementation
result = [ToolName]Tool.[method_name](test_value)
assert "expected_field" in result, "Functionality Test Failed"
print("✅ [Function Name] Functionality Normal")
return True
except Exception as e:
print(f"❌ [Tool Name] Tool Functionality Test Failed: {e}")
return False
```
### Development Best Practices
#### 1. Parameter Validation
```python
@staticmethod
def safe_method(param: str) -> Dict[str, any]:
"""Safe Method Implementation"""
# Parameter Type Validation
if not isinstance(param, str):
return {"error": "Parameter Type Error"}
# Parameter Content Validation
if not param.strip():
return {"error": "Parameter Cannot Be Empty"}
# Normal Processing Logic
# ...
```
#### 2. Error Handling
```python
@staticmethod
def robust_method(param: str) -> Dict[str, any]:
"""Robust Method Implementation"""
try:
# Business Logic
result = do_something(param)
return {
"success": True,
"data": result,
"message": "Operation Successful"
}
except Exception as e:
# Error Handling
return {
"success": False,
"error": f"Operation Failed: {str(e)}",
"error_type": "internal_error"
}
```
---
## 📊 System Monitoring
### Health Check
Access the health check endpoint to get the system status:
```bash
# Health Check
GET /health
# Response Example
{
"status": "healthy",
"server": "mcp-tool-server-dev",
"environment": "development"
}
```
### Performance Metrics
The system has built-in performance monitoring, which can be viewed through logs:
```bash
# View Performance Logs
tail -f logs/performance.log
```
---
## 🐛 Troubleshooting
### Common Issues
#### 1. **Database Connection Failure**
- **Cause**: MySQL service not running or configuration error
- **Solution**: Check MySQL service, verify database configuration information
- **Command**: `python init_mysql.py` Initialize Database
#### 2. **Tool Registration Failure**
- **Cause**: Tool module import path error or function implementation issue
- **Solution**: Check tool module import path, verify `register_*_tool` function implementation
- **View**: Log files for detailed error information
#### 3. **Test Failure**
- **Cause**: Test dependency not installed or environment configuration issue
- **Solution**: Check test dependency installation, verify test environment configuration
- **Debug**: Use `--interactive` mode for debugging
### Log Viewing
```bash
# View Application Logs
tail -f logs/app.log
# View Error Logs
tail -f logs/error.log
# View Performance Logs
tail -f logs/performance.log
```
---
## 🤝 Contribution Guide
Welcome to contribute code! Please follow these guidelines:
### Contribution Process
1. **Fork Project**: Fork the project to your account on GitHub
2. **Create Branch**: Create a feature branch (`git checkout -b feature/amazing-feature`)
3. **Commit Changes**: Commit your changes (`git commit -m 'Add amazing feature'`)
4. **Push to Branch**: Push the branch to the remote repository (`git push origin feature/amazing-feature`)
5. **Create Pull Request**: Create a Pull Request on GitHub
### Development Specifications
- **Code Style**: Follow PEP 8 code style
- **Documentation Comments**: Add proper documentation and comments
- **Test Cases**: Write complete test cases
- **Commit Information**: Use clear commit information
- **README Update**: Update relevant documentation
---
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
everything-claude-code
Complete Claude Code configuration collection - agents, skills, hooks,...
markitdown
MarkItDown-MCP is a lightweight server for converting URIs to Markdown.
cc-switch
All-in-One Assistant for Claude Code, Codex & Gemini CLI across platforms.
servers
Model Context Protocol Servers
servers
Model Context Protocol Servers
Time
A Model Context Protocol server for time and timezone conversions.