克劳德电报MCP服务器
一个托管的多租户Telegram MCP(模型上下文协议)服务器,使Claude能够代表用户与Telegram进行交互。使用FastAPI、Telethon和OAuth 2.0身份验证构建。
特性
- 73电报工具 -完整的Telegram自动化,包括聊天、消息、联系人、群组、频道等
- 多租户架构 -单一部署通过隔离的Telegram会话为多个用户提供服务
- OAuth 2.0+PKCE -与Claude Teams兼容的安全身份验证流程
- 基于Web的Telegram认证 -用户通过电话/短信验证连接他们的Telegram帐户(不需要CLI)
- 加密会话存储 -使用AES-256加密存储的电报会话
- 铁路准备就绪 -使用PostgreSQL一键部署到Railway
______________________________________________________________________
可用工具(共73个)
Chat & Group Management (21 tools)
| 工具 | 说明 |
|---|---|
get_chats | 获取Telegram聊天记录的分页列表 |
list_chats | 按类型列出聊天记录,并可选择过滤 |
get_chat | 获取特定聊天的详细信息 |
create_group | 创建新的群聊 |
invite_to_group | 邀请用户加入群组或频道 |
create_channel | 创建新频道或超群 |
edit_chat_title | 编辑聊天/频道标题 |
leave_chat | 离开群组或频道 |
get_participants | 获取群组或频道的参与者 |
get_admins | 获取组或频道的管理员 |
get_banned_users | 获取某个群组或频道的被禁用户 |
promote_admin | 将用户提升为管理员 |
demote_admin | 降级管理员 |
ban_user | 禁止用户加入群组或频道 |
unban_user | 取消阻止组或频道中的用户 |
get_invite_link | 获取群组或频道的邀请链接 |
export_chat_invite | 导出新的邀请链接 |
import_chat_invite | 使用邀请哈希加入聊天 |
join_chat_by_link | 使用完整的邀请链接加入聊天 |
subscribe_public_channel | 订阅公共频道 |
get_recent_actions | 获取组或频道中的最近管理员操作 |
Messaging (24 tools)
| 工具 | 说明 |
|---|---|
get_messages | 从聊天中获取分页消息 |
list_messages | 列出带有搜索和日期过滤功能的邮件 |
send_message | 向Telegram聊天发送消息 |
reply_to_message | 回复特定消息 |
edit_message | 编辑消息 |
delete_message | 删除消息 |
forward_message | 将消息转发到另一个聊天室 |
pin_message | 在聊天中固定消息 |
unpin_message | 在聊天中取消发送消息 |
mark_as_read | 将聊天中的所有消息标记为已读 |
get_message_context | 获取围绕特定消息的消息 |
get_history | 获取聊天记录 |
get_pinned_messages | 获取聊天中的所有固定消息 |
search_messages | 在聊天室或全球范围内搜索消息 |
get_last_interaction | 获取与联系人的最后一次交互 |
create_poll | 在聊天中创建投票 |
list_inline_buttons | 在消息中列出内联键盘按钮 |
press_inline_button | 按下内联键盘按钮 |
send_reaction | 在消息中添加反应 |
remove_reaction | 从消息中删除反应 |
get_message_reactions | 获取消息的所有反应 |
get_media_info | 从消息中获取媒体信息 |
Contact Management (12 tools)
| 工具 | 说明 |
|---|---|
list_contacts | 列出所有联系人 |
search_contacts | 按姓名或用户名搜索联系人 |
add_contact | 添加新联系人 |
delete_contact | 删除联系人 |
block_user | 阻止用户 |
unblock_user | 解除用户锁定 |
import_contacts | 导入多个联系人 |
export_contacts | 导出所有联系人 |
get_blocked_users | 获取被阻止用户的列表 |
get_contact_ids | 获取所有联系人ID的列表 |
get_direct_chat_by_contact | 查找与联系人的直接聊天 |
get_contact_chats | 获取涉及特定联系人的所有聊天记录 |
User & Profile (5 tools)
| 工具 | 说明 |
|---|---|
get_me | 获取当前用户的帐户信息 |
update_profile | 更新当前用户的个人资料 |
delete_profile_photo | 删除当前个人资料照片 |
get_user_photos | 获取用户的个人资料照片 |
get_user_status | 获取用户的在线状态 |
Search & Discovery (4 tools)
| 工具 | 说明 |
|---|---|
search_public_chats | 搜索公共聊天/频道 |
resolve_username | 解析用户名以获取用户/频道ID |
get_sticker_sets | 获取用户保存的贴纸集 |
get_bot_info | 获取有关机器人的信息 |
Privacy & Settings (6 tools)
| 工具 | 说明 |
|---|---|
get_privacy_settings | 获取当前隐私设置 |
set_privacy_settings | 为特定密钥设置隐私设置 |
mute_chat | 将聊天通知静音 |
unmute_chat | 取消聊天通知静音 |
archive_chat | 存档聊天记录 |
unarchive_chat | 存档聊天记录 |
Drafts (3 tools)
| 工具 | 说明 |
|---|---|
save_draft | 保存聊天消息草稿 |
get_drafts | 获取所有草稿消息 |
clear_draft | 清除特定聊天的草稿消息 |
______________________________________________________________________
部署
先决条件
- 电报API证书 -从 my.telegram.org:
- 转到“API开发工具” - 创建新应用程序 - 注意 api_id 和 api_hash
- 铁路账户 -注册地址: railway应用程序
部署到铁路
# Clone the repository
git clone https://github.com/your-org/telegram-hosted-mcp.git
cd telegram-hosted-mcp
# Install Railway CLI
npm install -g @railway/cli
# Login to Railway
railway login
# Create a new project
railway init
# Add PostgreSQL
railway add --plugin postgresql
# Set environment variables
railway variables set TELEGRAM_API_ID=your_api_id
railway variables set TELEGRAM_API_HASH=your_api_hash
railway variables set JWT_SECRET=$(openssl rand -hex 32)
railway variables set ENCRYPTION_KEY=$(python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())")
railway variables set BASE_URL=https://your-app.up.railway.app
railway variables set ALLOWED_REDIRECT_URIS=https://claude.ai/oauth/callback
# Deploy
railway up环境变量
| 变量 | 描述 | 如何生成 |
|---|---|---|
DATABASE_URL | PostgreSQL连接字符串 | 由Railway自动设置(确保它有 +asyncpg) |
TELEGRAM_API_ID | 电报API ID | 获取自 my.telegram.org |
TELEGRAM_API_HASH | 电报API散列 | 从 my.telegram.org |
JWT_SECRET | JWT令牌的密钥 | openssl rand -hex 32 |
ENCRYPTION_KEY | 会话加密的Fernet密钥 | 见下文 |
BASE_URL | 服务器的公共URL | 铁路URL |
ALLOWED_REDIRECT_URIS | OAuth重定向URI(逗号分隔) | https://claude.ai/oauth/callback |
生成加密密钥:
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"重要提示: 如果铁路设置 DATABASE_URL 作为 postgresql://...,将其更新为 postgresql+asyncpg://...
______________________________________________________________________
Claude团队设置
步骤1:注册OAuth客户端
部署后,为Claude Teams注册OAuth客户端:
curl -X POST https://your-app.up.railway.app/oauth/register \
-H "Content-Type: application/json" \
-d '{
"client_name": "Claude Teams",
"redirect_uris": ["https://claude.ai/oauth/callback"]
}'答复:
{
"client_id": "abc123...",
"client_secret": "secret456...",
"client_name": "Claude Teams",
"redirect_uris": ["https://claude.ai/oauth/callback"]
}保存 client_id 和 client_secret.
步骤2:在Claude Teams管理中添加MCP服务器
- 去你的 Claude Teams管理仪表板
- 引导到 集成 → MCP服务器
- 点击 添加MCP服务器
- 填写配置:
| 字段 | 值 |
|---|---|
| 名字 | 电报 |
| 服务器URL | https://your-app.up.railway.app/mcp |
| 认证 | OAuth 2.0 |
| 授权URL | https://your-app.up.railway.app/oauth/authorize |
| 令牌URL | https://your-app.up.railway.app/oauth/token |
| 客户端ID | *(从步骤1开始)* |
| 客户端密钥 | *(从步骤1开始)* |
| 范围 | telegram:read telegram:write |
- 点击 保存
步骤3:用户连接Telegram
当团队成员首次使用Telegram工具时:
- 克劳德提示他们授权Telegram连接
- 他们点击“连接”并被重定向到您的OAuth服务器
- 在OAuth之后,他们会看到一个web表单来输入他们的 电报电话号码 (国际格式,例如+1234567890)
- Telegram发送 短信验证码 到他们的手机
- 他们在网络表单上输入代码
- 如果他们启用了2FA,则输入2FA密码
- 成功!他们被重定向回克劳德,并连接了Telegram
用户只需要做一次。 他们的会话在对话中持续进行。
______________________________________________________________________
Claude桌面/个人设置
对于个人Claude用户(不在团队中),请使用支持MCP的Claude Desktop。
步骤1:注册OAuth客户端
curl -X POST https://your-app.up.railway.app/oauth/register \
-H "Content-Type: application/json" \
-d '{
"client_name": "Claude Desktop",
"redirect_uris": ["http://localhost:3000/callback"]
}'步骤2:配置Claude桌面
添加到您的Claude Desktop配置文件中:
macOS: ~/.config/claude/claude_desktop_config.json 窗户: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"telegram": {
"url": "https://your-app.up.railway.app/mcp",
"transport": "http",
"auth": {
"type": "oauth2",
"authorizationUrl": "https://your-app.up.railway.app/oauth/authorize",
"tokenUrl": "https://your-app.up.railway.app/oauth/token",
"clientId": "YOUR_CLIENT_ID",
"clientSecret": "YOUR_CLIENT_SECRET",
"scopes": ["telegram:read", "telegram:write"]
}
}
}
}第三步:连接你的电报
- 重新启动克劳德桌面
- 开始新的对话
- 问克劳德: *“列出我的Telegram聊天记录”*
- Claude将提示您授权-单击链接
- 在浏览器中完成Telegram电话验证
- 回到克劳德身边——你联系上了!
______________________________________________________________________
用法示例
一旦连接,问克劳德这样的问题:
读取消息
"Show me my recent Telegram chats"
"Get the last 20 messages from the 'Family' group"
"Search my Telegram for messages about 'meeting notes'"
"What did John send me yesterday?"发送消息
"Send a message to @username saying 'Hello, how are you?'"
"Reply to the last message in 'Work Team' with 'Sounds good!'"
"Forward that message to the 'Archive' chat"组管理
"Create a new group called 'Project Alpha' and add @user1 and @user2"
"Show me the admins in the 'Company' channel"
"Promote @newadmin to admin in 'My Group'"
"Remove the person who keeps spamming from the group"交互式功能
"Create a poll in the family chat: 'What should we have for dinner?' with options Pizza, Sushi, Tacos"
"React with 👍 to John's last message"
"Press the 'Confirm' button on that bot message"组织
"Archive all chats I haven't messaged in over a month"
"Mute the 'Announcements' channel"
"Show me my blocked users"______________________________________________________________________
API 参考
OAuth端点
| 端点 | 方法 | 描述 |
|---|---|---|
/.well-known/oauth-authorization-server | GET | OAuth服务器元数据(RFC 8414) |
/.well-known/oauth-protected-resource | GET | 受保护的资源元数据(RFC 9728) |
/oauth/register | POST | 注册新的OAuth客户端 |
/oauth/authorize | GET | 启动OAuth授权 |
/oauth/token | POST | 令牌交换代码 |
电报身份验证端点
| 端点 | 方法 | 描述 |
|---|---|---|
/auth/telegram/start | POST | 开始电话验证 |
/auth/telegram/verify | POST | 提交短信代码 |
/auth/telegram/2fa | POST | 提交2FA密码 |
MCP端点
| 端点 | 方法 | 描述 |
|---|---|---|
/mcp | POST | MCP JSON-RPC端点 |
健康检查
| 端点 | 方法 | 描述 |
|---|---|---|
/health | GET | 服务器运行状况 |
______________________________________________________________________
故障排除
“连接到MCP服务器时出错”
- 检查服务器运行状况:
curl https://your-app.up.railway.app/health- 验证OAuth元数据:
curl https://your-app.up.railway.app/.well-known/oauth-authorization-server- 检查环境变量:
- BASE_URL 必须与实际部署的URL完全匹配 - ALLOWED_REDIRECT_URIS 必须包含Claude回调URL
“找不到电报会话”
用户需要完成Telegram身份验证:
- 通过要求Claude使用Telegram工具再次触发OAuth流
- 完成电话/短信验证
“Fernet密钥无效”
加密密钥必须是有效的Fernet密钥。生成一个:
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"“数据库连接失败”
确保 DATABASE_URL 包含异步驱动程序:
postgresql+asyncpg://user:pass@host:port/db如果铁路将其设置为 postgresql://...,更新变量。
“电话号码无效”
电话号码必须采用国际格式,并带有国家代码:
- 对的:
+14155551234 - 错误:
415-555-1234
铁路部署失败
检查日志:
railway logs --build # Build logs
railway logs # Runtime logs______________________________________________________________________
安全
| 功能 | 实现 |
|---|---|
| 会话加密 | 通过Fernet的AES-256(加密电报会话字符串) |
| 手机隐私 | 仅在身份验证期间使用的电话号码,从不以明文形式存储 |
| OAuth安全 | OAuth 2.0+PKCE防止授权代码被拦截 |
| 令牌安全 | 具有可配置过期时间的JWT令牌 |
| 会话隔离 | 每个用户都有自己的Telegram客户端实例 |
| 审计日志 | 仅元数据-从不记录消息内容 |
______________________________________________________________________
本地开发
设置
# Clone repository
git clone https://github.com/your-org/telegram-hosted-mcp.git
cd telegram-hosted-mcp
# Install uv (if not installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
# Install dependencies
uv sync
# Create .env file
cat > .env << EOF
DATABASE_URL=postgresql+asyncpg://postgres:postgres@localhost:5432/telegram_mcp
TELEGRAM_API_ID=your_api_id
TELEGRAM_API_HASH=your_api_hash
JWT_SECRET=$(openssl rand -hex 32)
ENCRYPTION_KEY=$(python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())")
BASE_URL=http://localhost:8000
ALLOWED_REDIRECT_URIS=http://localhost:3000/callback
EOF
# Start PostgreSQL (using Docker)
docker run -d --name postgres -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:15
# Run migrations
alembic upgrade head
# Start server
uvicorn app.main:app --reload测试
# Test OAuth metadata
curl http://localhost:8000/.well-known/oauth-authorization-server
# Register a test client
curl -X POST http://localhost:8000/oauth/register \
-H "Content-Type: application/json" \
-d '{"client_name": "Test", "redirect_uris": ["http://localhost:3000/callback"]}'______________________________________________________________________
项目结构
telegram-hosted-mcp/
├── app/
│ ├── main.py # FastAPI application entry point
│ ├── config.py # Environment configuration (pydantic-settings)
│ ├── database.py # SQLAlchemy async engine setup
│ ├── models.py # Database models (users, clients, sessions)
│ ├── auth/
│ │ ├── oauth.py # OAuth 2.0 endpoints (authorize, token, register)
│ │ ├── tokens.py # JWT token creation and verification
│ │ └── telegram.py # Telegram phone/SMS/2FA auth flow
│ ├── mcp/
│ │ ├── server.py # MCP server (73 tool definitions + routing)
│ │ ├── middleware.py # Bearer token validation, audit logging
│ │ └── tools/
│ │ ├── __init__.py
│ │ ├── chats.py # 21 chat/group management tools
│ │ ├── messages.py # 24 messaging tools
│ │ ├── contacts.py # 12 contact management tools
│ │ ├── users.py # 9 user/profile/discovery tools
│ │ ├── privacy.py # 6 privacy/settings tools
│ │ └── drafts.py # 3 draft tools
│ ├── telegram/
│ │ ├── client_pool.py # Multi-tenant Telethon client pool with LRU
│ │ └── session_store.py # Fernet-encrypted session storage
│ └── templates/ # HTML templates for auth flow
│ ├── phone.html # Phone number entry
│ ├── code.html # SMS code entry
│ ├── 2fa.html # 2FA password entry
│ └── success.html # Success page
├── alembic/ # Database migrations
├── Dockerfile # Container configuration
├── pyproject.toml # Python dependencies
├── railway.toml # Railway deployment config
└── README.md______________________________________________________________________
学分
许可证
MIT许可证
