🐍 Chaster Locks MCP服务器-Python版
现代 模型上下文协议(MCP) 服务器内置Python 快速API, 派丹蒂克,以及 httpx 用于Chaster Locks API。
✨ Python版本优势
- 🚀 快速API -具有自动生成文档的本机异步性能
- 🔒 Pydantic V2 -使用Rust进行稳健的数据验证和优化的序列化
- 🌐 httpx -具有自动重试功能的现代异步HTTP客户端
- 🐍 Python 3.11+ -现代语法和改进的性能
- 📝 键入提示 -静态检查更安全的代码
- 🛡️ Python错误处理 -直观的异常管理
📁 Python项目结构
chaster-locks-mcp-server-python/
├── main.py # Main FastAPI server with MCP routes
├── chaster_service.py # Chaster API service with async httpx
├── requirements.txt # Optimized Python dependencies
├── Dockerfile # Python 3.11 slim Docker image
├── docker-compose.yml # Orchestration with healthcheck
├── .env.example # Python configuration template
└── README.md # This documentation🚀 安装和设置
先决条件
- Python 3.11+ (推荐)
- Docker&Docker编写 (可选但推荐)
方法一:Docker(推荐)
# 1. Clone and configure
git clone chaster-mcp-python
cd chaster-mcp-python
# 2. Configuration
cp .env.example .env
# Edit .env with your tokens
# 3. Build and launch
docker-compose up -d
# 4. Verify status
curl http://localhost:3000/health方法2:本地安装
# 1. Create virtual environment
python -m venv venv
source venv/bin/activate # Linux/Mac
# or venv\Scripts\activate # Windows
# 2. Install dependencies
pip install -r requirements.txt
# 3. Configuration
cp .env.example .env
# Configure your tokens
# 4. Start server
python main.py
# Or with uvicorn directly
uvicorn main:app --host 0.0.0.0 --port 3000 --reload🔧 配置
环境变量
# MCP Token (generate with: python -c "import secrets; print(secrets.token_hex(32))")
MCP_AUTH_TOKEN=your_64_char_hex_token
# Chaster API Token (from https://chaster.app/settings/developer)
CHASTER_API_TOKEN=your_chaster_api_token
# Server port (optional)
PORT=3000
# Environment (development for auto-reload and docs)
NODE_ENV=production📡 API和文件
交互式文档
在开发模式下,FastAPI会自动生成文档:
- Swagger用户界面: http://localhost:3000/docs
- ReDoc: http://localhost:3000/redoc
可用端点
GET /health-服务器健康检查POST /mcp-主MCP端点(经过身份验证)
🔧 可用的底盘MCP工具(共86个)
Python版本现在支持 所有86 Chaster Public API端点!
备注:Chaster API共有114个端点,但有28个端点是专门针对扩展开发人员的API合作伙伴扩展的一部分。该服务器实现了所有86个面向公共用户的端点。
📋 锁(18个工具)
get_locks-列出带有状态过滤器的锁get_lock_details-完整的锁详细信息archive_lock/archive_lock_keyholder-档案锁unlock_lock-永久解锁update_lock_time-工期修改freeze_lock-冻结/解冻锁update_lock_settings-显示设置update_max_limit_date-增加最大限制日期trust_keyholder-Mark Keyworder值得信赖get_lock_combination-检索组合get_lock_history-活动历史set_test_lock-标记为测试锁get_user_public_locks-获取用户的公共锁search_locks-高级搜索get_lock_extension-分机信息trigger_lock_extension_action-触发扩展操作convert_to_self_lock-转换为自锁
🔨 锁创建(3个工具)
create_lock-创建新锁edit_lock_extensions-编辑锁扩展名create_lock_from_shared-从共享锁创建
👤 配置文件(7个工具)
get_user_profile_by_id-按ID获取用户get_user_profile-按用户名获取用户get_user_profile_details-详细简介get_badge_count-用户徽章计数update_profile_from_auth-从身份验证服务器更新get_auth_profile-记录的用户信息set_user_profile-更新个人资料
💬 消息传递(9个工具)
find_conversation_by_user-查找对话create_conversation-开始新对话get_conversations-列出对话add_message-发送消息get_conversation-获取对话详细信息set_conversation_status-更新状态set_conversation_unread-设置为未读get_messages-获取消息get_ignored_users-列出忽略的用户
🔑 钥匙扣(1个工具)
search_locked_users-搜索锁定用户
🔓 共享锁(11个工具)
get_shared_locks-列出共享锁create_shared_lock-创建共享锁get_shared_lock-获取共享锁详细信息update_shared_lock-更新共享锁archive_shared_lock-存档共享锁get_shared_lock_tags-获取所有标签get_suggested_tags-获取建议标签check_favorite_shared_lock-检查收藏夹状态add_favorite_shared_lock-添加到收藏夹remove_favorite_shared_lock-从收藏夹中删除get_favorite_shared_locks-列出收藏夹
🌐 公用锁(4个工具)
get_public_lock-获取公共锁get_lock_image-生成锁图像search_public_locks-搜索公用锁get_explore_categories-探索类别
🤝 课程优惠(7个工具)
create_keyholding_offer-创建报价accept_keyholding_request-接受请求get_keyholding_offer_status-获取状态get_offer_public_info-获取报价信息respond_to_keyholding_offer-接受/拒绝archive_keyholding_offer-存档优惠get_keyholding_requests-列出请求
🚫 积木(4个工具)
get_blocked_users-列出被阻止的用户block_user-阻止用户get_block_interaction-检查块状态unblock_user-解除用户锁定
🧩 扩展(1个工具)
get_extensions-列出可用扩展名
🔢 组合(2个工具)
upload_combination_image-上传图片create_code_combination-创建代码
⚖️ 扩展-处罚(4个工具)
get_penalties-列出处罚get_penalty_session-获得点球机会search_penalty_periods-搜索时段get_punishable_actions-列出操作
🔓 扩展-临时打开(3个工具)
get_temporary_combination-获取组合set_temporary_combination-设置组合get_action_log_combination-从日志获取
📸 扩展-验证图片(2个工具)
submit_verification_picture-提交图片get_verification_pictures-获取历史记录
📁 文件(2个工具)
upload_files-上传附件get_file-按密钥获取文件
👥 用户(4个工具)
search_users-搜索用户search_user_by_username-按用户名搜索search_user_by_discord-按Discord ID搜索update_current_user-更新当前用户
🎉 社区活动(2个工具)
get_event_categories-活动类别get_event_task_details-任务详细信息
⚙️ 设置(1个工具)
get_app_settings-应用程序设置
🚨 报告(1个工具)
create_report-创建报告
🧪 测试和验证
基本测试
# Server health
curl http://localhost:3000/health
# MCP authentication test
curl -X POST http://localhost:3000/mcp \
-H "Authorization: Bearer YOUR_MCP_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "tools/list",
"params": {},
"id": 1
}'
# Chaster tool test
curl -X POST http://localhost:3000/mcp \
-H "Authorization: Bearer YOUR_MCP_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "get_locks",
"arguments": {"status": "active"}
},
"id": 2
}'使用pytest进行Python测试(可选)
# Install pytest
pip install pytest pytest-asyncio httpx
# Create test_main.py
pytest test_main.py -v🐳 有用的Docker命令
# Manual build with tag
docker build -t chaster-mcp-python .
# Run with environment variables
docker run -p 3000:3000 \
-e MCP_AUTH_TOKEN=your_token \
-e CHASTER_API_TOKEN=your_chaster_token \
chaster-mcp-python
# Development with volume and reload
docker-compose -f docker-compose.yml -f docker-compose.dev.yml up
# Real-time logs
docker-compose logs -f chaster-mcp-python
# Shell into container
docker-compose exec chaster-mcp-python bash
# Complete cleanup
docker-compose down -v --remove-orphans🔍 监控与调试
结构化日志
Python服务器生成详细的日志:
# Docker logs
docker-compose logs -f
# Chaster API specific logs
docker-compose logs | grep "Chaster API"
# Error logs only
docker-compose logs | grep "ERROR"度量与健康
# Health endpoint with system info
curl http://localhost:3000/health | jq
# Dependency check
pip check
# Environment info
python -c "import sys; print(sys.version)"🏗️ 开发与推广
添加新工具
- 添加定义 在
get_available_tools() - 实现方法 在
ChasterLocksService - 添加案例 在
call_tool() - 测试 使用curl或FastAPI文档
MCP响应结构
def format_response(self, data: Any, message: str = "") -> Dict[str, Any]:
return {
"content": [
{
"type": "text",
"text": f"{message}\n\n{json.dumps(data, indent=2)}"
}
]
}自定义错误处理
async def handle_request(self, method: str, endpoint: str, data: Optional[Dict] = None):
try:
# Request logic
response = await self.client.request(method, endpoint, json=data)
response.raise_for_status()
return response.json()
except httpx.HTTPStatusError as e:
# Specific HTTP error handling
raise Exception(f"API Error ({e.response.status_code}): {e.response.text}")🔒 安全和最佳实践
- ✅ 承载身份验证 必填项
/mcp - ✅ Pydantic验证 所有JSON-RPC输入
- ✅ 可配置的HTTP超时 (默认值:30秒)
- ✅ 非root用户 在Docker容器中
- ✅ 环境变量 为了所有的秘密
- ✅ CORS已配置 适用于web环境
- ✅ 集成Docker健康检查
🚀 演出
Python优化
- Fastapi异步 -并发请求处理
- httpx异步 -非阻塞HTTP客户端
- Pydantic V2 -使用Rust进行超快速验证
- Python 3.11+ -性能提高25%
Docker优化
- Python瘦图像 -尺寸减小60%
- 多阶段构建 -依赖缓存
- 健康检查 -必要时自动重启
🆚 Node.js与Python的比较
| 特性 | Node.js | Python |
|---|---|---|
| 演出 | 本机事件循环 | FastAPI异步(可比) |
| MCP生态系统 | 原生 | 改编 |
| 可读性 | 一般 | 优秀 |
| 验证 | 手动/joi | Pydantic集成 |
| 文档 | 手动开关 | FastAPI自动 |
| 调试 | 控制台/日志 | 丰富的日志+pdb |
🤝 支持和维护
______________________________________________________________________
版本: 2.0.0 | 许可证: 麻省理工学院| python 3.11+ | FastAPI: 0.104+
🆕 2.0.0版-API全面覆盖
新增内容:
- ✨ 所有86 Chaster Public API端点 现已实施(13)
- 📦 73新工具 增加覆盖:
- 配置文件管理和用户搜索 - 完整的消息系统 - 共享锁和公用锁管理 - 密钥持有服务和会话管理 - 用户屏蔽和报告 - 延期(处罚、临时开放、验证) - 文件上传和组合 - 社区活动
- 🏗️ 维护架构:相同的异步HTTP结构
- 🔄 向后兼容:所有原始的13个工具都以相同的方式工作
- 📚 完整文档:README和Swagger中记录的所有工具
______________________________________________________________________
🐍 服务器MCP Chaster Locks-Python版
服务器 模型上下文协议(MCP) 用Python开发的现代 快速API, 派丹蒂克 和 httpx 注入API Chaster锁。
✨ Python版本的好处
- 🚀 快速API -本机异步性能和自生成文档
- 🔒 Pydantic V2 -使用Rust进行稳健的数据验证和优化的序列化
- 🌐 httpx -具有自动重试功能的现代异步HTTP客户端
- 🐍 Python 3.11+ -现代语法和改进的性能
- 📝 键入提示 -具有静态验证的更安全代码
- 🛡️ Pythonic错误管理 -异常处理直觉
📁 Python项目的结构
chaster-locks-mcp-server-python/
├── main.py # Serveur FastAPI principal avec routes MCP
├── chaster_service.py # Service API Chaster avec httpx async
├── requirements.txt # Dépendances Python optimisées
├── Dockerfile # Image Docker Python 3.11 slim
├── docker-compose.yml # Orchestration avec healthcheck
├── .env.example # Template configuration Python
└── README.md # Cette documentation🚀 安装和启动
先决条件
- Python 3.11+ (推荐)
- Docker&Docker编写 (可选,但推荐)
方法1:Docker(推荐)
# 1. Cloner et configurer
git clone chaster-mcp-python
cd chaster-mcp-python
# 2. Configuration
cp .env.example .env
# Éditer .env avec vos tokens
# 3. Build et lancement
docker-compose up -d
# 4. Vérifier le statut
curl http://localhost:3000/health方法2:本地安装
# 1. Créer un environnement virtuel
python -m venv venv
source venv/bin/activate # Linux/Mac
# ou venv\Scripts\activate # Windows
# 2. Installer les dépendances
pip install -r requirements.txt
# 3. Configuration
cp .env.example .env
# Configurer vos tokens
# 4. Lancer le serveur
python main.py
# Ou avec uvicorn directement
uvicorn main:app --host 0.0.0.0 --port 3000 --reload🔧 配置
环境变量
# Token MCP (générer avec: python -c "import secrets; print(secrets.token_hex(32))")
MCP_AUTH_TOKEN=your_64_char_hex_token
# Token API Chaster (depuis https://chaster.app/settings/developer)
CHASTER_API_TOKEN=your_chaster_api_token
# Port du serveur (optionnel)
PORT=3000
# Environnement (development pour auto-reload et docs)
NODE_ENV=production📡 API等文件
交互式文档
在开发模式下,FastAPI自动生成文档:
- Swagger用户界面: http://localhost:3000/docs
- ReDoc: http://localhost:3000/redoc
可用端点
GET /health-服务器运行状况检查POST /mcpMCP主端点(已验证)
🔧 MCP Chaster工具可用
Python版本支持Chaster API的所有工具:
📋 锁的管理
get_locks-带过滤器的列表(活动/存档/全部)get_lock_details-锁的完整细节archive_lock/archive_lock_keyholder-存档unlock_lock-最终解锁
⚙️ 控制和修改
update_lock_time-持续时间的变化freeze_lock-锁的冻结/解冻update_lock_settings-显示设置convert_to_self_lock-转换为自动变速器
📊 信息与研究
get_lock_combination-组合恢复get_lock_history-活动历史search_locks-带过滤器的高级搜索trust_keyholder-将守门员标记为可靠
🧪 测试与验证
基础测试
# Santé du serveur
curl http://localhost:3000/health
# Test authentification MCP
curl -X POST http://localhost:3000/mcp \
-H "Authorization: Bearer YOUR_MCP_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "tools/list",
"params": {},
"id": 1
}'
# Test d'un outil Chaster
curl -X POST http://localhost:3000/mcp \
-H "Authorization: Bearer YOUR_MCP_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"name": "get_locks",
"arguments": {"status": "active"}
},
"id": 2
}'使用Pytest进行Python测试(可选)
# Installer pytest
pip install pytest pytest-asyncio httpx
# Créer test_main.py
pytest test_main.py -v🐳 有用的Docker命令
# Build manuel avec tag
docker build -t chaster-mcp-python .
# Lancement avec variables d'environnement
docker run -p 3000:3000 \
-e MCP_AUTH_TOKEN=your_token \
-e CHASTER_API_TOKEN=your_chaster_token \
chaster-mcp-python
# Développement avec volume et reload
docker-compose -f docker-compose.yml -f docker-compose.dev.yml up
# Logs en temps réel
docker-compose logs -f chaster-mcp-python
# Shell dans le container
docker-compose exec chaster-mcp-python bash
# Nettoyage complet
docker-compose down -v --remove-orphans🔍 监控与调试
结构化日志
Python服务器生成详细的日志:
# Logs Docker
docker-compose logs -f
# Logs spécifiques aux requêtes Chaster
docker-compose logs | grep "Chaster API"
# Logs d'erreurs seulement
docker-compose logs | grep "ERROR"指标与健康
# Endpoint de santé avec informations système
curl http://localhost:3000/health | jq
# Vérification des dépendances
pip check
# Informations sur l'environnement
python -c "import sys; print(sys.version)"🏗️ 发展和扩展
添加新工具
- 添加定义 在
get_available_tools() - 实现该方法 在
ChasterLocksService - 添加案例 在
call_tool() - 测试员 使用curl或FastAPI文档
MCP响应的结构
def format_response(self, data: Any, message: str = "") -> Dict[str, Any]:
return {
"content": [
{
"type": "text",
"text": f"{message}\n\n{json.dumps(data, indent=2)}"
}
]
}自定义错误管理
async def handle_request(self, method: str, endpoint: str, data: Optional[Dict] = None):
try:
# Logique de requête
response = await self.client.request(method, endpoint, json=data)
response.raise_for_status()
return response.json()
except httpx.HTTPStatusError as e:
# Gestion spécifique des erreurs HTTP
raise Exception(f"Erreur API ({e.response.status_code}): {e.response.text}")🔒 安全和良好做法
- ✅ 认证持有者 强制
/mcp - ✅ 验证Pydantic 所有JSON-RPC输入
- ✅ 超时HTTP 可配置(默认值:30s)
- ✅ 非root用户 在Docker容器中
- ✅ 环境变量 为了所有的秘密
- ✅ CORS 已配置 对于web环境
- ✅ 健康检查 集成Docker
🚀 演出
Python优化
- Fastapi异步 -请求的并发处理
- httpx异步 -客户端HTTP非阻塞
- Pydantic V2 -使用Rust进行超快验证
- Python 3.11+ 性能提高25%
Docker优化
- 图像Python slim -尺寸减少60%
- 多阶段构建 -依赖项缓存
- 健康检查 -必要时自动重新启动
🆚 Node.js与Python的比较
| 特性 | Node.js | Python |
|---|---|---|
| 演出 | 事件循环natif | FastAPI异步(可比) |
| MCP生态系统 | 原生 | 改编 |
| 可读性 平均 | 优秀 | |
| 验证 | 手动/JOI | 集成Pydantic |
| 文档 | Swagger手动 | FastAPI自动 |
| 调试 | 控制台/日志 | 丰富的日志+pdb |
🤝 支持和维护
______________________________________________________________________
版本: 2.0.0 | 许可证: 麻省理工学院| python 3.11+ | FastAPI: 0.104+
🆕 版本2.0.0-全面API覆盖
新闻:
- ✨ Chaster公共API的所有86个端点 现已实施(当时为13个)
- 📦 73新工具 添加包括:
- 配置文件管理和用户搜索 - 完整的消息系统 - 共享和公共锁的管理 - 警卫和会话管理优惠 - 阻止用户和报告 - 延期(罚款、临时开放、验证) - 上传文件和组合 - 社区活动
- 🏗️ 保存的建筑:相同的HTTP异步结构
- 🔄 向后兼容:13个原始工具的工作方式相同
- 📚 完整文档:自述和Swagger中记录的所有工具
