Telegram MCP服务器

一个生产就绪的Telegram集成模型上下文协议服务器,提供聊天操作、搜索解析、消息操作和账号管理等功能。

  • by Enot-Racoon
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 Enot-Racoon/telegram-mcp

使用说明

电报MCP服务器

用于Telegram集成的生产就绪MCP(模型上下文协议)服务器。

第一阶段:基础

这是初始基础阶段,包括:

  • ✅ 带工具的MCP服务器脚手架
  • ✅ 带接口的电报抽象层
  • ✅ 用于离线测试的模拟电报提供商
  • ✅ SQLite存储层
  • ✅ 高速缓存子系统
  • ✅ 日志记录子系统
  • ✅ 帐户/会话管理
  • ✅ CLI行为(不作为MCP运行时提供帮助)
  • ✅ 使用Vitest进行完全TDD设置
  • ✅ 零真正的Telegram API调用

可用工具

聊天操作

工具 说明
list_chats 列出所有Telegram聊天记录(按类型/未读筛选)
get_messages 从聊天中获取消息(限制、偏移、before_id、after_id)
send_message 发送消息(reply_to、parse_mode、disable_link_preview)
mark_as_read 将聊天中的消息标记为已读
get_chat_info 获取详细的聊天信息(类型、id、参与者、最后/固定消息)

搜索和解决

工具 说明
search_chats 按标题或用户名搜索聊天记录
resolve_chat 将@username、t.me/link或原始ID转换为内部chat_ID
search_messages 按文本搜索消息(每次聊天或全局搜索,带过滤器)

消息操作

工具 说明
reply_to_message 发送对特定消息的回复
edit_message 编辑现有邮件的文本
delete_message 从聊天中删除消息

更新和未读

工具 说明
get_unread_messages 获取未读消息(来自特定聊天或所有聊天)
get_updates_since 获取特定消息ID之后的新消息(增量更新)

帐户和身份验证操作

工具 说明
login_start 使用电话号码启动登录过程
login_submit_code 从Telegram提交验证码
login_submit_password 如果需要,请提交2FA密码
logout 退出当前Telegram会话
list_accounts 列出所有Telegram帐户
set_default_account 设置默认活动帐户
switch_account 切换到其他帐户
is_logged_in 检查当前是否已登录
get_auth_status 获取详细的身份验证状态
get_me 获取当前账户信息
login 传统登录(直接、模拟)
is_authenticated 传统身份验证检查(模拟)

系统和管理

工具 说明
get_logs 使用过滤器(级别、工具、会话、日期范围)查询系统日志
clear_cache 清除缓存(全部或按前缀)
get_cache_stats 获取缓存统计信息(条目、命中/未命中、命中率、大小)

高级聊天操作

工具 说明
send_to_saved_messages 将消息发送到您的已保存消息(个人云存储)
get_participants 获取具有角色(创建者/管理员/成员)的组/渠道参与者
resolve_peer 将@username、t.me/link、title或ID标准化为内部chat_ID
subscribe_to_chat 订阅聊天以进行基于轮询的新消息检测
wait_for_new_message 阻止在已订阅聊天中等待新消息

项目结构

telegram-mcp/
├── src/
│   ├── index.ts              # Main entry point with CLI
│   ├── server.ts             # MCP server implementation
│   ├── core/
│   │   ├── config/           # Configuration management
│   │   ├── database/         # SQLite database initialization
│   │   ├── cache/            # Cache manager
│   │   └── logging/          # Structured logging
│   ├── telegram/
│   │   ├── TelegramProvider.ts    # Provider interface
│   │   ├── MockTelegramProvider.ts # Mock implementation
│   │   └── TelegramService.ts      # Service layer
│   ├── accounts/
│   │   └── AccountManager.ts # Account/session management
│   ├── tools/                # MCP tools (future)
│   └── types/                # TypeScript types
├── tests/
│   ├── unit/                 # Unit tests
│   └── integration/          # Integration tests
├── package.json
├── tsconfig.json
├── vitest.config.ts
└── README.md

安装

npm install

发展

# Run in development mode
npm run dev

# Build for production
npm run build

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

# Type check
npm run typecheck

用法

作为MCP服务器

# Run as MCP server (via stdio)
npm start

# Or directly
node dist/index.js

CLI帮助

# Show help
npm run dev -- --help

# Show version
npm run dev -- --version

环境变量

变量 描述 默认值
TELEGRAM_MCP_DB_PATH SQLite数据库的路径 ~/.telegram-mcp/telegram.db
TELEGRAM_MCP_LOG_LEVEL 日志级别:调试、信息、警告、错误 info
TELEGRAM_MCP_CACHE_TTL 默认缓存TTL(毫秒) 3600000 (1小时)
TELEGRAM_MCP_MAX_LOGS 要保留的最大日志条目数 10000

建筑

电报摘要

这 TelegramProvider 接口抽象了所有Telegram API交互:

interface TelegramProvider {
  login(phone: string): Promise<void>;
  listChats(): Promise<Chat[]>;
  getMessages(chatId: string, limit: number): Promise<Message[]>;
  sendMessage(chatId: string, text: string): Promise<void>;
  logout(): Promise<void>;
  isAuthenticated(): boolean;
  getCurrentUser(): Promise<UserInfo | null>;
  getChatInfo(chatId: string): Promise<ChatInfo | null>;
}

这 MockTelegramProvider 使用内存中的数据实现此接口以进行测试。

账户管理

这 AccountManager 处理多帐户支持:

interface AccountManager {
  createAccount(phone: string): Account;
  getAccount(id: string): Account | null;
  getAllAccounts(): Account[];
  getActiveAccounts(): Account[];
  setDefaultAccount(id: string): boolean;
  setDefaultAccountByPhone(phone: string): boolean;
  getAuthStatus(): AuthStatus;
  activateSession(id: string, userId: string): void;
  deactivateSession(id: string): void;
  deleteAccount(id: string): boolean;
}

身份验证流程

身份验证流程支持多步登录:

  1. login_start(phone) -发送电话号码,接收代码
  2. login_submit_code(phone, code) -提交验证码
  3. login_submit_password(phone, password) -提交2FA密码(如果需要)
  4. 帐户已激活并准备好使用

数据库模式

SQLite表:

  • sessions -帐户会话
  • cache -带TTL的键值缓存
  • logs -结构化操作日志
  • config -配置存储
  • stats -度量和统计

缓存系统

特征:

  • 基于TTL的过期
  • 基于前缀的清除
  • 统计跟踪
  • 自动清理

记录系统

特征:

  • 结构化JSON日志记录
  • SQLite存储
  • 基于级别的过滤
  • 工具执行跟踪
  • 使用上下文记录错误

用法示例

搜索和解决聊天

// Search for a chat by username
{
  "name": "search_chats",
  "arguments": { "query": "project", "limit": 5 }
}

// Resolve a username to chat_id
{
  "name": "resolve_chat",
  "arguments": { "ref": "@my_channel" }
}

// Resolve a t.me link
{
  "name": "resolve_chat",
  "arguments": { "ref": "t.me/my_channel" }
}

搜索邮件

// Search messages globally
{
  "name": "search_messages",
  "arguments": { "query": "meeting", "limit": 10 }
}

// Search within a specific chat
{
  "name": "search_messages",
  "arguments": {
    "query": "deadline",
    "chatId": "chat-123",
    "limit": 20
  }
}

// Search with date filter
{
  "name": "search_messages",
  "arguments": {
    "query": "report",
    "minDate": 1709251200000,
    "maxDate": 1709337600000
  }
}

消息操作

// Reply to a message
{
  "name": "reply_to_message",
  "arguments": {
    "chatId": "chat-123",
    "messageId": "msg-456",
    "text": "Got it, thanks!"
  }
}

// Edit a message
{
  "name": "edit_message",
  "arguments": {
    "chatId": "chat-123",
    "messageId": "msg-456",
    "newText": "Updated content"
  }
}

// Delete a message
{
  "name": "delete_message",
  "arguments": {
    "chatId": "chat-123",
    "messageId": "msg-456"
  }
}

获取更新和未读

// Get unread messages from all chats
{
  "name": "get_unread_messages",
  "arguments": { "limit": 50 }
}

// Get unread from specific chat
{
  "name": "get_unread_messages",
  "arguments": { "chatId": "chat-123", "limit": 20 }
}

// Get updates since last known message
{
  "name": "get_updates_since",
  "arguments": {
    "chatId": "chat-123",
    "afterMessageId": "msg-789",
    "limit": 50
  }
}

增强的获取消息

// Get messages with pagination
{
  "name": "get_messages",
  "arguments": {
    "chatId": "chat-123",
    "limit": 20,
    "offset": 40
  }
}

// Get messages before a specific ID
{
  "name": "get_messages",
  "arguments": {
    "chatId": "chat-123",
    "beforeId": "msg-100",
    "limit": 50
  }
}

// Get messages after a specific ID (for loading new messages)
{
  "name": "get_messages",
  "arguments": {
    "chatId": "chat-123",
    "afterId": "msg-50",
    "limit": 50
  }
}

增强型发送消息

// Send with reply
{
  "name": "send_message",
  "arguments": {
    "chatId": "chat-123",
    "text": "Sure!",
    "replyToMessageId": "msg-456"
  }
}

// Send with markdown
{
  "name": "send_message",
  "arguments": {
    "chatId": "chat-123",
    "text": "**Bold** and _italic_",
    "parseMode": "markdown"
  }
}

// Send without link preview
{
  "name": "send_message",
  "arguments": {
    "chatId": "chat-123",
    "text": "Check this: https://example.com",
    "disableLinkPreview": true
  }
}

系统和管理

// Query logs by level
{
  "name": "get_logs",
  "arguments": {
    "level": "error",
    "limit": 50
  }
}

// Query logs by tool and date range
{
  "name": "get_logs",
  "arguments": {
    "tool": "send_message",
    "startDate": 1709251200000,
    "endDate": 1709337600000,
    "limit": 100
  }
}

// Clear all cache
{
  "name": "clear_cache",
  "arguments": {}
}

// Clear cache by prefix
{
  "name": "clear_cache",
  "arguments": {
    "prefix": "user:"
  }
}

// Get cache statistics
{
  "name": "get_cache_stats",
  "arguments": {}
}

高级聊天操作

// Send to Saved Messages
{
  "name": "send_to_saved_messages",
  "arguments": {
    "text": "Important note to remember"
  }
}

// Get group participants
{
  "name": "get_participants",
  "arguments": {
    "chatId": "chat-123",
    "limit": 50,
    "offset": 0
  }
}

// Resolve peer reference to chat_id
{
  "name": "resolve_peer",
  "arguments": {
    "ref": "@my_channel"
  }
}

// Resolve t.me link
{
  "name": "resolve_peer",
  "arguments": {
    "ref": "t.me/my_channel"
  }
}

// Resolve by chat title
{
  "name": "resolve_peer",
  "arguments": {
    "ref": "Project Team"
  }
}

// Subscribe to chat for new messages
{
  "name": "subscribe_to_chat",
  "arguments": {
    "chatId": "chat-123"
  }
}

// Wait for new message in subscribed chat
{
  "name": "wait_for_new_message",
  "arguments": {
    "chatId": "chat-123"
  }
}

// Wait for message from specific user
{
  "name": "wait_for_new_message",
  "arguments": {
    "chatId": "chat-123",
    "fromUserId": "user-456"
  }
}

测试

所有测试都使用模拟提供者,不需要网络访问。

# Run all tests
npm test

# Run specific test file
npx vitest tests/unit/MockTelegramProvider.test.ts

# Run with coverage
npm run test:coverage

路线图

第一阶段(当前)-基础✅

  • 核心架构和接口
  • 用于测试的模拟提供者
  • 数据库、缓存、日志记录子系统
  • 聊天操作 (list_chats、get_message、send_message、mark_as_read、get_chat_info)
  • 搜索和解决 (搜索帽、解析帽、搜索消息)
  • 消息操作 (回复消息、编辑消息、删除消息)
  • 更新和未读 (get_end_message,get_updates_since)
  • 用户信息和对话框 (get_user_info、list_recent_chats、get_dialogs_page、get_read_count、get_last_message)
  • 连接 (get_connection_status)
  • 账户管理 (列表计数、设置故障计数、开关计数)
  • 认证 (登录开始、登录提交代码、登录提交密码、注销)
  • 状态工具 (is_logged_in、get_auth_status、get_me、is_authenticated)
  • 系统和管理 (get_logs、clear_cache、get_cache_stats)
  • 高级聊天 (send_to_saved_message、get_participants、resolve_peer、subscribe_to_chat、wait_for_new_message)

第二阶段——真正的整合

  • MTProto实施
  • 真实电报API连接
  • 使用真实代码的身份验证流程
  • 真实消息发送/接收

第3阶段-增强工具

  • 转发消息工具
  • send_media工具(照片、视频、文档)
  • send_voice_message工具
  • pin_message/unpin_message工具
  • get_chat_members工具
  • export_chat_invite_link工具

第4阶段-生产准备就绪

  • 错误恢复和重试逻辑
  • 速率限制和节流
  • 连接池
  • 监控和指标
  • Webhook支持实时更新

许可证

麻省理工学院