Telegram MCP Server
The Telegram MCP Server lets you extract, synchronize, and manage Telegram chat history and media locally via a userbot (MTProto) connection.
List all chats (
telegram_list_chats): Retrieve all Telegram dialogs (chats, groups, channels) with their IDs, titles, types, and usernames.Find a specific chat (
telegram_find_chat): Search for a chat by name, username, or numeric ID.Fetch chat history (
telegram_get_history): Preview messages (text, sender, date, media info) without downloading media; supports pagination.Full chat sync (
telegram_sync_chat): Download all messages and media (photos, documents, videos, voice notes) to local storage; supports incremental sync for new messages only and optional date filtering.Download individual media (
telegram_download_media): Download media from a specific message by ID, with optional custom output directory.Check sync status (
telegram_sync_status): View last sync date, total synced messages, and last message ID for a chat.List downloaded media (
telegram_list_media): Browse locally saved media files for a chat, filterable by type (photo, document, video, voice).Flexible deployment: Run locally via stdio or as an HTTP server with Bearer token authentication; Docker support included.
Claude integration: Connect to Claude Code or Claude Desktop as an MCP server for chat data analysis.
Enables extraction and synchronization of Telegram chat history, including text messages, photos, and documents, with tools to search chats and manage downloaded media.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Telegram MCP Server sync my recent chat history with John Doe"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Telegram MCP Server
MCP-сервер для извлечения истории чатов Telegram, включая текстовые сообщения, фото и документы. Использует GramJS (MTProto userbot) для полного доступа к личным чатам.
Требования
Node.js 18+
Telegram API credentials (my.telegram.org)
Related MCP server: telegram-mcp
Установка
npm install
cp .env.example .env
# Заполнить TELEGRAM_API_ID и TELEGRAM_API_HASH в .envПервый запуск — аутентификация
npm run authВведи номер телефона → код из Telegram → пароль 2FA (если есть).
Сессия сохранится в telegram.session.
Сборка и запуск
npm run build
npm startТранспорты
Сервер поддерживает два режима работы, выбираемых переменной TRANSPORT:
Переменная | Значение | Описание |
| по умолчанию | Локальный запуск через stdin/stdout, авторизация не нужна (процесс изолирован) |
| сетевой режим | HTTP-сервер на порту |
stdio (по умолчанию)
Сервер общается с клиентом через stdin/stdout. Безопасность обеспечивается изоляцией процесса — доступ имеет только тот, кто его запустил.
HTTP с Bearer token авторизацией
Для сетевого доступа (например, сервер на удалённой машине). Каждый запрос должен содержать заголовок:
Authorization: Bearer <ваш_токен>Без валидного токена сервер вернёт 401 Unauthorized.
Сгенерировать токен:
node -e "console.log(crypto.randomUUID())"Настроить в .env:
TRANSPORT=http
PORT=3000
AUTH_TOKEN=ваш-секретный-токенПодключение к Claude Code / Claude Desktop
Claude Code — stdio (локально)
claude mcp add telegram-mcp -- node /path/to/telegram-mcp-server/dist/index.jsClaude Code — HTTP (удалённый сервер)
claude mcp add telegram-mcp \
--transport http \
--url http://your-server:3000/mcp \
--header "Authorization: Bearer ваш-секретный-токен"Claude Desktop (config)
{
"mcpServers": {
"telegram": {
"command": "node",
"args": ["/path/to/telegram-mcp-server/dist/index.js"],
"env": {
"TELEGRAM_API_ID": "your_id",
"TELEGRAM_API_HASH": "your_hash",
"TELEGRAM_SESSION_PATH": "/path/to/telegram.session",
"DATA_DIR": "/path/to/data"
}
}
}
}Docker
Сборка
docker build -t telegram-mcp .Запуск — stdio
docker run --rm -i \
-e TELEGRAM_API_ID=12345 \
-e TELEGRAM_API_HASH=abc123 \
-v ./telegram.session:/app/telegram.session \
-v ./data:/app/data \
telegram-mcpЗапуск — HTTP с авторизацией
docker run -d \
-e TRANSPORT=http \
-e AUTH_TOKEN=ваш-секретный-токен \
-e TELEGRAM_API_ID=12345 \
-e TELEGRAM_API_HASH=abc123 \
-v ./telegram.session:/app/telegram.session \
-v ./data:/app/data \
-p 3000:3000 \
telegram-mcpИнструменты (Tools)
Tool | Описание |
| Список всех чатов |
| Поиск чата по имени/username/ID |
| Получить сообщения (без скачивания медиа) |
| Основной — полная синхронизация чата с медиа |
| Скачать медиа из конкретного сообщения |
| Статус последней синхронизации |
| Список скачанных медиафайлов |
Типичный workflow
1. telegram_find_chat("Мама") → получаем chat_id
2. telegram_sync_chat(chat_id) → скачиваем всё
3. telegram_list_media(chat_id, "photo") → список фотографий
4. Загружаем файлы из data/raw/{chat_id}/media/ в Claude для анализаЧерез 2 недели:
telegram_sync_chat(chat_id) → скачает только новые сообщенияСтруктура данных
data/
└── raw/
└── {chat_id}/
├── messages.json # все сообщения
├── media_index.json # индекс медиафайлов
├── sync_state.json # состояние синхронизации
└── media/ # скачанные файлы
├── photo_123.jpg
├── doc_456.pdf
└── ...Безопасность
Сессия Telegram хранится в файле (добавлен в .gitignore)
API credentials в .env (добавлен в .gitignore)
HTTP транспорт защищён Bearer token авторизацией
Данные хранятся только локально
Available Tools
7 toolstelegram_download_mediaDownload Single MediaAIdempotent
Download media from a specific message. Use this for targeted downloads instead of a full sync. Returns file path and metadata.
Inputs: chat_id (required), message_id (required), output_dir.
telegram_find_chatFind Telegram ChatARead-onlyIdempotent
Search for a specific chat by name, username, or ID. Returns the matching chat info or null if not found.
Inputs: query (required).
telegram_get_historyGet Chat HistoryARead-onlyIdempotent
Fetch messages from a Telegram chat. Returns message text, sender, date, and media info. Does NOT download media files — use telegram_sync_chat for that. Useful for previewing chat contents before a full sync.
Inputs: chat_id (required), limit, offset_id.
telegram_list_chatsList Telegram ChatsARead-onlyIdempotent
List your Telegram dialogs (chats, groups, channels). Returns chat ID, title, type, and username. Use this to find the chat_id needed for other tools.
Inputs: limit.
telegram_list_mediaList Synced MediaARead-onlyIdempotent
List all media files that have been downloaded for a chat. Requires a previous telegram_sync_chat run. Filter by type: photo, document, video, voice, or all.
Inputs: chat_id (required), media_type.
telegram_sync_chatSync Telegram ChatAIdempotent
Full sync: downloads all messages and media files from a chat to local storage. Supports incremental sync — on subsequent runs, only fetches new messages. Files are saved to data/raw/{chat_id}/. This is the main tool for extracting chat data including photos and documents. Use since_date to limit the sync range, or omit for full/incremental sync.
Inputs: chat_id (required), since_date.
telegram_sync_statusGet Sync StatusARead-onlyIdempotent
Check the sync status for a chat: last sync date, total synced messages, last message ID. Useful before deciding whether to run a new sync.
Inputs: chat_id (required).
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
Each tool has a clearly distinct purpose with no overlap: download_media, find_chat, get_history, list_chats, list_media, sync_chat, and sync_status all target specific operations in the Telegram data extraction workflow. The descriptions explicitly differentiate tools like get_history (preview without downloads) versus sync_chat (full sync with downloads), preventing misselection.
All tools follow a consistent 'telegram_verb_noun' pattern throughout, using snake_case and clear action verbs (download, find, get, list, sync). This predictable naming makes the tool set easy to navigate and understand at a glance.
With 7 tools, this server is well-scoped for its purpose of Telegram data extraction and management. Each tool earns its place by covering distinct aspects like discovery (list_chats, find_chat), preview (get_history), full sync (sync_chat), media handling (download_media, list_media), and status checking (sync_status).
The tool surface provides complete coverage for the Telegram data extraction domain: it supports chat discovery, message history retrieval, full sync with incremental updates, media download and listing, and status monitoring. There are no obvious gaps—agents can perform end-to-end workflows from finding chats to extracting and managing their data.
Related MCP Connectors
Your personal Telegram account for AI: read, search and sum up chats. QR login, no API key.
Your WhatsApp history in Claude and ChatGPT: search years of chats, voice notes transcribed.
Extract public Telegram channel messages, media metadata, crypto addresses, and RAG Markdown.
1Search, read and reply to your Telegram Business chats, transcribed voice included.
Related MCP Servers
- FlicenseBqualityDmaintenanceEnables interaction with Telegram groups via MTProto, including message retrieval, sending, and semantic search with RAG support.12-
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to interact with a user's Telegram account: list chats, read history, search, and send messages through Telegram's MTProto API.2MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to interact with Telegram Web through a clean text-based API, including chat search, message history, sending messages, and profile retrieval via a persistent Playwright session.MIT
- AlicenseAqualityBmaintenanceEnables searching Telegram messages and chats, retrieving recent messages, and extracting text from attached documents (PDF, TXT, MD, CSV) using your personal Telegram account.4Apache 2.0