telegram-mcp
MCP server that enables AI agents to send messages, photos, polls, and receive replies via Telegram with persistence and rate limiting.
README
telegram-mcp 🤖✉️
MCP (Model Context Protocol) server for Telegram Bot API integration.
Enables AI agents to send messages, photos, documents, polls, progress updates, and receive user responses via Telegram — all with persistent storage, rate limiting, and robust error handling.
Features
- ✅ 10 MCP Tools — send_message, send_photo, send_document, send_progress, send_todo_update, send_error_alert, ask_user, wait_for_response, create_poll, send_daily_report
- ✅ Bidirectional Communication — AI agents can pause, ask questions, wait for Telegram replies, and resume workflows based on user responses
- ✅ Multi-Chat Support — Configure one or many Telegram chats/groups/channels
- ✅ MarkdownV2 Formatting — Rich text with bold, italic, code blocks, links, tables, progress bars
- ✅ SQLite Persistence — Conversation history, pending response tracking, message logs
- ✅ Rate Limiting — Token-bucket algorithm respects Telegram's API limits
- ✅ Retry with Exponential Backoff — Auto-retries failed API calls
- ✅ Comprehensive Logging — Structured logs with levels (debug/info/warn/error)
- ✅ Type-Safe — Full TypeScript with Zod schemas for all tool inputs
- ✅ Docker Support — Multi-stage Dockerfile + docker-compose
- ✅ Environment Config — All settings via environment variables with
.env.example - ✅ Polling-Based Updates — No webhook needed; polls Telegram for new messages
Architecture
┌─────────────────┐ stdio ┌──────────────────────────┐
│ AI Agent / │ ◄──────────► │ telegram-mcp │
│ MCP Client │ │ │
└─────────────────┘ │ ┌───────────────────┐ │
│ │ MCP Tools Layer │ │
│ │ (Zod schemas) │ │
│ └────────┬──────────┘ │
│ │ │
│ ┌────────▼──────────┐ │
│ │ Telegram Client │ │
│ │ (retry + rate │ │
│ │ limiting) │ │
│ └────────┬──────────┘ │
│ │ │
│ ┌────────▼──────────┐ │
│ │ Update Poller │ │
│ │ (getUpdates loop) │ │
│ └────────┬──────────┘ │
│ │ │
│ ┌────────▼──────────┐ │
│ │ SQLite Storage │ │
│ │ (better-sqlite3) │ │
│ └───────────────────┘ │
└──────────────────────────┘
│
Telegram Bot API
│
Telegram
(Users/Chats)
Prerequisites
- Node.js ≥ 22 (or Docker)
- A Telegram Bot Token from @BotFather
- The Chat ID of your target Telegram chat(s) (use @userinfobot to find)
Installation
Option 1: npm / pnpm (standalone)
# Clone or create the project directory
cd telegram-mcp
# Install dependencies
npm install
# Build TypeScript
npm run build
# Copy and edit environment file
cp .env.example .env
# Edit .env with your BOT_TOKEN and CHAT_ID
Option 2: Docker
# Build the image
docker build -t telegram-mcp .
# Or use docker-compose
cp .env.example .env
# Edit .env with your BOT_TOKEN and CHAT_ID
docker compose up -d
Configuration
All configuration is via environment variables (defined in .env):
| Variable | Required | Default | Description |
|---|---|---|---|
BOT_TOKEN |
✅ | — | Telegram Bot API token from @BotFather |
CHAT_ID |
✅ | — | Comma-separated chat IDs (e.g., 123456789,-987654321) |
OWNER_ID |
❌ | — | Bot owner's Telegram user ID |
DB_PATH |
❌ | ./data/telegram-mcp.db |
SQLite database file path |
LOG_LEVEL |
❌ | info |
Log level: debug, info, warn, error |
POLL_INTERVAL_MS |
❌ | 2000 |
Polling interval for message updates (ms) |
RESPONSE_TIMEOUT_SEC |
❌ | 300 |
Default timeout for wait_for_response (seconds) |
RESPONSE_POLL_INTERVAL_MS |
❌ | 500 |
Poll interval when waiting for a response (ms) |
RATE_LIMIT_RPS |
❌ | 30 |
Telegram API rate limit (requests per second) |
MAX_RETRIES |
❌ | 3 |
Maximum retries for failed API calls |
Usage
Running the Server
# Development mode (with hot reload)
npm run dev
# Production mode
npm start
# With Docker
docker compose up
The server starts an MCP service over stdio, which is automatically used by MCP-compatible clients.
Configure your AI agent or MCP client to launch:
node /path/to/telegram-mcp/dist/index.js
MCP Client Configuration
If using Claude Desktop or another MCP client, add to your claude_desktop_config.json:
{
"mcpServers": {
"telegram": {
"command": "node",
"args": ["/absolute/path/to/telegram-mcp/dist/index.js"],
"env": {
"BOT_TOKEN": "your_bot_token",
"CHAT_ID": "your_chat_id"
}
}
}
}
Tools
send_message
Send a text message to one or all configured chats.
| Parameter | Type | Required | Description |
|---|---|---|---|
text |
string | ✅ | Message content (MarkdownV2) |
chat_id |
string | ❌ | Specific chat ID; omit to broadcast |
parse_mode |
enum | ❌ | MarkdownV2 (default), HTML, Markdown |
disable_web_page_preview |
boolean | ❌ | Disable link previews |
disable_notification |
boolean | ❌ | Send silently |
send_photo
Send a photo (by URL or Telegram file_id).
| Parameter | Type | Required | Description |
|---|---|---|---|
photo |
string | ✅ | URL or file_id |
caption |
string | ❌ | Optional caption |
chat_id |
string | ❌ | Specific chat ID |
parse_mode |
enum | ❌ | MarkdownV2, HTML |
send_document
Send a document (by URL or file_id).
| Parameter | Type | Required | Description |
|---|---|---|---|
document |
string | ✅ | URL or file_id |
caption |
string | ❌ | Optional caption |
chat_id |
string | ❌ | Specific chat ID |
filename |
string | ❌ | Display name |
send_progress
Send a visual progress bar.
| Parameter | Type | Required | Description |
|---|---|---|---|
title |
string | ✅ | Progress title |
current |
number | ✅ | Current value |
total |
number | ✅ | Total value |
status_text |
string | ❌ | Optional status |
chat_id |
string | ❌ | Specific chat ID |
send_todo_update
Notify about a todo item status change.
| Parameter | Type | Required | Description |
|---|---|---|---|
action |
enum | ✅ | created, updated, completed, deleted |
title |
string | ✅ | Todo title |
description |
string | ❌ | Optional description |
status |
string | ❌ | e.g., in progress, done |
priority |
enum | ❌ | low, medium, high, urgent |
chat_id |
string | ❌ | Specific chat ID |
send_error_alert
Send a structured error notification.
| Parameter | Type | Required | Description |
|---|---|---|---|
title |
string | ✅ | Error title |
description |
string | ✅ | Error details |
stack |
string | ❌ | Stack trace |
metadata |
object | ❌ | Key-value pairs |
chat_id |
string | ❌ | Specific chat ID |
create_poll
Create and send a poll.
| Parameter | Type | Required | Description |
|---|---|---|---|
question |
string | ✅ | Poll question |
options |
string[] | ✅ | 2–10 options |
is_anonymous |
boolean | ❌ | Default: true |
allows_multiple_answers |
boolean | ❌ | Default: false |
type |
enum | ❌ | regular, quiz |
correct_option_id |
number | ❌ | For quiz polls |
explanation |
string | ❌ | For quiz polls |
open_period |
number | ❌ | Auto-close seconds |
chat_id |
string | ❌ | Specific chat ID |
send_daily_report
Send a structured daily summary.
| Parameter | Type | Required | Description |
|---|---|---|---|
date |
string | ❌ | ISO date (defaults to today) |
title |
string | ✅ | Report title |
sections |
array | ✅ | [{heading, content}] |
footer |
string | ❌ | Optional footer |
chat_id |
string | ❌ | Specific chat ID |
ask_user
Send a question and create a pending response slot. Returns a response_id.
| Parameter | Type | Required | Description |
|---|---|---|---|
question |
string | ✅ | Question text |
chat_id |
string | ❌ | Specific chat ID |
timeout_seconds |
number | ❌ | Override default timeout |
Returns: response_id string (pass to wait_for_response)
wait_for_response
Block until the user replies to a previously asked question.
| Parameter | Type | Required | Description |
|---|---|---|---|
response_id |
string | ✅ | ID from ask_user |
timeout_seconds |
number | ❌ | Timeout override |
chat_id |
string | ❌ | Narrow chat scope |
Returns:
{
"received": true,
"text": "User's reply message",
"messageId": 42
}
On timeout:
{
"received": false,
"error": "Timeout: No response received within the allowed time."
}
Two-Phase Agent Workflow (ask → wait → resume)
The most powerful feature is the ability for an AI agent to pause execution, ask a question via Telegram, wait for the user's reply, and resume the workflow based on the response.
Flow
Agent telegram-mcp Telegram User
│ │ │
│── ask_user({question}) ──►─────────── message ────►│
│◀── { response_id } ──────│ │
│ │ │
│── wait_for_response({ │ │
│ response_id }) ──────► │
│ │ │
│ │◄──── reply ────────────│
│◀── { received:true, │ │
│ text:"..." } ──────│ │
│ │ │
│ (resumes logic based │ │
│ on user's response) │ │
Example Agent Script
// Phase 1: Ask the user
const { response_id } = await mcp.callTool("ask_user", {
question: "Which report should I generate? (daily/weekly/monthly)"
});
// Phase 2: Wait for their response (blocks up to 5 minutes)
const result = await mcp.callTool("wait_for_response", {
response_id: response_id,
timeout_seconds: 300
});
if (result.received) {
const userChoice = result.text.toLowerCase();
if (userChoice.includes("daily")) {
await generateDailyReport();
} else if (userChoice.includes("weekly")) {
await generateWeeklyReport();
}
await mcp.callTool("send_message", {
text: `✅ Generating ${userChoice} report...`
});
} else {
await mcp.callTool("send_error_alert", {
title: "No Response",
description: "User did not respond within the timeout period."
});
}
Development
# Install dependencies
npm install
# Run in development mode (with hot reload)
npm run dev
# Run tests
npm test
# Run tests in watch mode
npm run test:watch
# Build for production
npm run build
# Lint (if configured)
npm run lint
Project Structure
telegram-mcp/
├── src/
│ ├── index.ts # Entry point — starts MCP server + polling
│ ├── config.ts # Environment variable validation (Zod)
│ ├── logger.ts # Structured logging
│ ├── types.ts # TypeScript interfaces
│ ├── telegram/
│ │ ├── client.ts # Telegram Bot API client (retry, rate limit)
│ │ └── formatter.ts # MarkdownV2 formatting utilities
│ ├── storage/
│ │ └── db.ts # SQLite database (conversations, pending)
│ ├── handlers/
│ │ └── updates.ts # Telegram update polling
│ └── mcp/
│ └── tools.ts # All MCP tool definitions + response handler
├── tests/
│ └── telegram-mcp.test.ts # Vitest unit tests
├── Dockerfile # Multi-stage Docker build
├── docker-compose.yml # Docker Compose setup
├── .env.example # Environment template
├── vitest.config.ts # Test configuration
├── tsconfig.json # TypeScript configuration
└── package.json
Testing
npm test
Tests cover:
- MarkdownV2 escaping and formatting
- Structured message builders (errors, todos, reports, polls)
- Database CRUD operations (in-memory SQLite)
- Config validation logic
- Response ID generation
Error Handling & Reliability
- Exponential backoff — Failed Telegram API calls retry with
1s → 2s → 4sdelays (configurable) - Rate limiting — Token-bucket algorithm prevents hitting Telegram's rate limits
- Graceful shutdown — Cleanly closes database and stops polling on SIGINT/SIGTERM
- Uncaught exception handling — Logs fatal errors before exiting
- Input validation — All tool inputs validated with Zod schemas
Database
The server uses SQLite (via better-sqlite3) for persistence:
- conversations — Full chat history (user + agent messages)
- pending_responses — Active
ask_user/wait_for_responserequests - messages_log — Auditable log of all sent/received messages
The database file is stored at DB_PATH (default: ./data/telegram-mcp.db).
Docker
Build & Run
# Build
docker build -t telegram-mcp .
# Run with .env file
docker run --env-file .env -v telegram-mcp-data:/app/data telegram-mcp
# Or use docker-compose
docker compose up -d
Multi-Stage Build
The Dockerfile uses a multi-stage build:
- Builder stage — Installs dev dependencies, compiles TypeScript
- Production stage — Minimal image with only runtime dependencies
Security
- Bot Token — Keep your
BOT_TOKENsecret. Never commit it to version control. - Chat IDs — Restrict which chats the bot listens to via
CHAT_ID. - Input Validation — All tool inputs are validated with Zod schemas.
- No Webhooks — Uses polling instead, avoiding the need for a public HTTPS endpoint.
License
MIT
Contributing
Contributions are welcome! Please open an issue or PR for:
- Additional Telegram API features
- Improved formatting utilities
- Enhanced response matching (e.g., reply chains)
- Webhook support
- Multi-language support
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。