电报MCP服务器
  ](https://www.docker.com/)  
一个模型上下文协议(MCP)服务器,使AI助手(如Kilo Code)能够通过Telegram向您提问并等待您的回复。这创建了一个“人在循环”的工作流程,人工智能可以在长时间运行的任务中请求决策、批准或特定输入。
特性
- 🤖 交互式人工智能工作流程:AI可以暂停并通过Telegram向您提问
- 📱 按钮支持:将多选选项显示为可点击按钮
- ⏱️ 长轮询:等待您的回复最多2分钟
- 🔒 安全:使用环境变量作为凭据
- 🎯 简单集成:可与任何兼容MCP的AI助手配合使用
- 🐳 Docker支持:本机运行或在容器中运行
先决条件
- Python 3.10+(用于本机安装)
- 或者Docker和Docker Compose(用于容器化安装)
- Telegram帐户
- 电报机器人令牌(来自@BotFather)
安装方法
您可以通过两种方式运行此MCP服务器:
- 原生Python安装 -直接在您的系统上运行
- **** -在容器中运行(建议用于生产)
本地安装
1.创建Telegram Bot
- 打开Telegram并搜索 @植物学家
- 发送
/newbot并按照提示进行操作 - 为您的机器人命名(例如,“MyDevBot”)
- 复制 HTTP API令牌 提供
- 重要:发送
/start发送到您的新机器人,以便它可以向您发送消息
2.查找您的Telegram用户ID(可选)
- 搜索 @用户信息机器人 在Telegram上
- 发送任何消息
- 复制您的用户名
3.克隆和设置
# Clone the repository
git clone https://github.com/yourusername/telegram-mcp-server.git
cd telegram-mcp-server
# Create virtual environment
python3 -m venv venv
# Activate virtual environment
source venv/bin/activate # On Linux/Mac
# OR
venv\Scripts\activate # On Windows
# Install dependencies
pip install -r requirements.txt4.配置
创建一个 .env 示例中的文件:
cp .env.sample .env编辑 .env 并添加您的凭据:
TELEGRAM_BOT_TOKEN=your_bot_token_here
TELEGRAM_USER_ID=your_user_id_here # Optional - bot will auto-detect if not set⚠️ 安全说明:The .env 为了保护您的凭据,文件被忽略了。
5.在本地测试服务器
# Activate virtual environment
source venv/bin/activate
# Run the server
python telegram_server.py您应该看到:
╭──────────────────────────────────────────────────────────────────────────────╮
│ ▄▀▀ ▄▀█ █▀▀ ▀█▀ █▀▄▀█ █▀▀ █▀█ │
│ █▀ █▀█ ▄▄█ █ █ ▀ █ █▄▄ █▀▀ │
│ FastMCP 2.14.2 │
│ 🖥 Server: Telegram Human Loop │
╰──────────────────────────────────────────────────────────────────────────────╯按 Ctrl+C 停止测试。
Docker安装
1.配置环境
cp .env.sample .env
# Edit .env with your credentials2.构建和运行
# Build the Docker image
docker-compose build
# Start the container in detached mode
docker-compose up -d3.查看日志
docker-compose logs -f telegram-mcp4.停止服务器
docker-compose downDocker命令参考
建筑:
# Build the image
docker-compose build
# Build without cache (force rebuild)
docker-compose build --no-cache正在运行:
# Start in detached mode (background)
docker-compose up -d
# Start in foreground (see logs directly)
docker-compose up
# Start and rebuild if needed
docker-compose up -d --build监控:
# View logs
docker-compose logs -f telegram-mcp
# View last 100 lines of logs
docker-compose logs --tail=100 telegram-mcp
# Check container status
docker-compose ps
# Execute commands inside the container
docker-compose exec telegram-mcp python --version停止和清洁:
# Stop the container
docker-compose stop
# Stop and remove containers
docker-compose down
# Stop, remove containers, and remove volumes
docker-compose down -v
# Remove all (containers, networks, images)
docker-compose down --rmi all重新启动:
# Restart the container
docker-compose restart
# Rebuild and restart from scratch
docker-compose down
docker-compose build --no-cache
docker-compose up -d发展:
# Open a shell in the running container
docker-compose exec telegram-mcp /bin/bash
# Test the server locally (without Docker)
source venv/bin/activate && python telegram_server.py连接到MCP客户端
适用于Kilo Code(或类似的MCP客户端)
方法1:使用启动脚本(推荐)
- 打开MCP设置文件:
- 地点: ~/.config/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/mcpSettings.json - 或者使用客户的UI:设置→ MCP服务器→ 编辑配置
- 添加此配置(替换
/absolute/path/to/telegram-mcp-server使用您的实际安装路径):
{
"mcpServers": {
"telegram": {
"command": "bash",
"args": ["/absolute/path/to/telegram-mcp-server/run.sh"]
}
}
}例子: 如果你克隆到 /home/user/projects/telegram-mcp-server,使用:
{
"mcpServers": {
"telegram": {
"command": "bash",
"args": ["/home/user/projects/telegram-mcp-server/run.sh"]
}
}
}- 重新启动MCP客户端或重新加载MCP服务器
注: 示例配置在 mcp-config.example.json 以供参考。
方法2:直接执行Python
{
"mcpServers": {
"telegram": {
"command": "/absolute/path/to/telegram-mcp-server/venv/bin/python",
"args": ["/absolute/path/to/telegram-mcp-server/telegram_server.py"]
}
}
}方法3:使用Docker
选项A:Docker编写执行
{
"mcpServers": {
"telegram": {
"command": "docker-compose",
"args": [
"-f",
"/absolute/path/to/telegram-mcp-server/docker-compose.yml",
"exec",
"-T",
"telegram-mcp",
"python",
"telegram_server.py"
],
"cwd": "/absolute/path/to/telegram-mcp-server"
}
}
}选项B:Docker运行
{
"mcpServers": {
"telegram": {
"command": "docker",
"args": [
"run",
"--rm",
"-i",
"--env-file",
"/absolute/path/to/telegram-mcp-server/.env",
"telegram-mcp-server",
"python",
"telegram_server.py"
]
}
}
}可用工具
一旦连接,您的AI助手将可以访问这些工具:
- ask_human(问题、选项、等待、超时秒数、允许自定义) -向Telegram发送问题
- wait=True (默认):阻止,直到您响应或超时 - wait=False:发送问题并立即返回(非阻塞模式) - options:按钮选项的可选列表 - allow_custom=True (默认):在提供选项时添加“自定义答案”按钮 - 可在阻塞和非阻塞模式下工作
- get_telegram_response(mark_as_read) -检索您最新的Telegram消息
- 使用后 ask_human(wait=False) 获取您的回复 - mark_as_read=True (默认):不会检索同一消息两次
- send_telegram_notiation(消息) -发送单向状态更新
- 用于进度报告、完成通知或状态更新 - 不期望得到回应 - 非常适合在长时间运行的任务中让您了解情况
- list_telegram_message(限制) -查看最近的对话历史记录
- 显示最后5-20条消息以获取上下文 - 可用于检查您是否已回复
使用示例
示例1:简单问题
你对你的AI说:
“我要去喝咖啡。如果你需要知道使用哪个数据库,可以通过Telegram问我。”
AI呼叫:
ask_human(question="Should I use PostgreSQL or MongoDB for this project?")发生了什么:
- 你的手机发出一条电报信息
- 你回复:“PostgreSQL”
- AI收到“PostgreSQL”并继续
示例2:带按钮的多项选择
AI呼叫:
ask_human(
question="How should I structure the authentication?",
options=["JWT", "Session Cookies", "OAuth2", "Skip for now"]
)发生了什么:
- 您收到一条带有4个可点击按钮的Telegram消息
- 点击“JWT”
- AI立即收到“JWT”
示例3:审批工作流
你对你的AI说:
“重构整个代码库,但在做出任何重大更改之前请先问我。”
AI呼叫:
ask_human(
question="I want to rename `getUserData()` to `fetchUser()`. This will break 23 files. Proceed?",
options=["Yes, proceed", "No, skip this", "Show me the files first"]
)示例4:复杂问题的非阻塞模式
AI没有等待就问道:
ask_human(
question="Please review this 500-line refactor and provide detailed feedback",
wait=False
)发生了什么:
- 您在Telegram上收到问题
- 你慢慢复习(没有超时)
- 准备好后,你告诉人工智能:“我已经在Telegram上回复了”
- AI检索您的答案:
get_telegram_response()
示例5:进度通知
AI发送状态更新:
send_telegram_notification("🚀 Starting database migration...")
send_telegram_notification("✅ Step 1/5 complete: Schema created")
send_telegram_notification("🎉 Migration complete! All 1,247 records migrated successfully.")运作原理
- AI呼叫
ask_human()带有问题和可选按钮选项 - 服务器发送电报消息 到您配置的聊天
- 长轮询循环 每2秒检查一次Telegram以获取您的回复
- 你回答 通过文本或按钮点击
- 服务器返回您的答案 对于AI
- AI继续 根据您的意见
超时行为
- 默认超时时间: 120秒 (2分钟)
- 可通过配置
timeout_seconds参数输入ask_human() - 如果你不及时回应,AI会收到:
"Timeout: User did not respond in time..."
非阻塞模式
对于需要延长思考时间的复杂问题,请使用 非阻塞模式 为了避免超时:
- AI没有等待就问道:
ask_human("Please review this architecture and provide feedback", wait=False)- 您收到问题 并且可以根据需要进行思考和回应
- 准备好后,告诉AI你已经回复:
> “我已经在Telegram上回复了”
- AI检索您的答案:
answer = get_telegram_response()带按钮的自定义答案
当你提供按钮选项时,AI会自动添加一个“✏️ “自定义答案”按钮(除非 allow_custom=False).这使您可以:
- 点击按钮快速选择
- 或者键入您自己的自定义响应
例子:
ask_human(
"Which database?",
options=["PostgreSQL", "MongoDB", "MySQL"],
wait=False
)您将看到4个按钮:
- PostgreSQL
- MongoDB
- MySQL
- ✏️ 自定义答案(在下面键入)
最佳实践
使用非阻塞模式(wait=False)何时:
- 问题需要代码审查或深入分析
- 您可能远离您的设备
- 该决定需要研究或咨询
- 您需要2分钟以上的时间才能回复
使用阻塞模式(wait=True)何时:
- 问题很简单,是/否决定
- 你正在积极与人工智能合作
- 预计会有快速反应
- 使用按钮选项进行多项选择
使用通知(send_telegram_notification)用于:
- 长时间运行任务期间的进度更新
- 任务完成通知
- 错误或警告警报
- 不需要响应的状态更新
- 远离电脑时随时了解情况
项目结构
telegram-mcp-server/
├── telegram_server.py # Main MCP server code
├── .env # Your credentials (gitignored)
├── .env.sample # Template for environment variables
├── .gitignore # Protects secrets
├── requirements.txt # Python dependencies
├── run.sh # Startup script (executable)
├── mcp-config.example.json # Example MCP configuration (customize for your setup)
├── Dockerfile # Docker image definition
├── docker-compose.yml # Docker Compose configuration
├── .dockerignore # Docker build exclusions
└── README.md # This file故障排除
“找不到命令‘python’”
解决方案:使用 python3 或者安装符号链接:
sudo apt install python-is-python3这 run.sh 脚本已经使用了虚拟环境中的正确Python。
“错误:找不到Telegram聊天ID”
解决方案:确保你已经发送 /start 至少向你的机器人发送一次。
“权限被拒绝:./run.sh”
解决方案:使脚本可执行:
chmod +x run.sh“超时:用户未及时响应”
解决方案:
- 响应速度更快(2分钟内)
- 增加超时时间
ask_human()呼叫 - 使用非阻塞模式(
wait=False)对于复杂的问题
客户端中未显示MCP服务器
解决方案:
- 检查MCP设置文件路径是否正确
- 验证配置中的绝对路径
- 完全重新启动MCP客户端
- 检查客户端日志中的连接错误
Docker容器无法启动
检查日志:
docker-compose logs telegram-mcp环境变量未加载
确保 .env 文件存在并且格式正确:
cat .envDocker的权限问题
如果您遇到权限问题,请确保 .env 文件可读:
chmod 644 .env高级配置
更改默认超时
您可以自定义每个问题的超时时间:
# Short timeout for quick questions
ask_human("Proceed?", options=["Yes", "No"], timeout_seconds=30)
# Longer timeout for thoughtful questions
ask_human("Which approach?", timeout_seconds=300) # 5 minutes仅限于特定用户
服务器使用 TELEGRAM_USER_ID 从 .env。只接受来自此用户ID的消息。
使用多个机器人
创建不同目录 .env 将每个文件注册为不同的MCP服务器:
{
"mcpServers": {
"telegram-work": {
"command": "bash",
"args": ["/path/to/work-bot/run.sh"]
},
"telegram-personal": {
"command": "bash",
"args": ["/path/to/personal-bot/run.sh"]
}
}
}安全最佳实践
- ✅ 永不承诺
.env-已经在.gitignore - ✅ 使用
TELEGRAM_USER_ID-防止未经授权的用户控制您的AI - ✅ 重新生成令牌 如果意外暴露
- ✅ 使用私人电报机器人 -不要与他人共享您的机器人
- ✅ 使用Docker秘密 用于生产中的敏感数据
- ✅ 定期更新 安全补丁的基本Python映像
生产部署
对于生产部署:
- 从中删除开发卷装载
docker-compose.yml - 使用环境变量或机密管理,而不是
.env文件 - 考虑使用流程管理器或编排工具(Kubernetes、Docker Swarm)
- 设置适当的日志记录和监控
- 适当配置重启策略
示例生产码头-compose.yml:
version: '3.8'
services:
telegram-mcp:
build:
context: .
dockerfile: Dockerfile
container_name: telegram-mcp-server
environment:
- TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
- TELEGRAM_USER_ID=${TELEGRAM_USER_ID}
- PYTHONUNBUFFERED=1
restart: always
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"依赖项
- fastmcp (2.14.2+)-MCP服务器框架
- httpx (0.28.1+)-Telegram API的异步HTTP客户端
- python dotenv (1.2.1+)-环境变量管理
看 requirements.txt 查看完整列表。
贡献
欢迎投稿!请随时提交拉取请求。
许可证
MIT许可证-自由使用!
支持
对于以下问题:
- MCP协议:检查 模型上下文协议文档
- FastMCP:参观 FastMCP文档
- 电报机器人API:参见 Telegram Bot API文档
更新日志
v1.0.0(2026-01-02)
- 初始版本
- 支持阻塞和非阻塞问题模式
- 按钮支持多项选择题
- 进度通知系统
- Docker支持
- 全面的文件
