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 "Install 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 Serversync 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)
Установка
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 авторизацией
Данные хранятся только локально
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.