Skip to main content
Glama
Telegram MCP Server

Telegram MCP Server

by raidenyn

Telegram MCP Server

MCP-сервер для извлечения истории чатов Telegram, включая текстовые сообщения, фото и документы. Использует GramJS (MTProto userbot) для полного доступа к личным чатам.

Требования

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:

Переменная

Значение

Описание

TRANSPORT=stdio

по умолчанию

Локальный запуск через stdin/stdout, авторизация не нужна (процесс изолирован)

TRANSPORT=http

сетевой режим

HTTP-сервер на порту PORT (по умолчанию 3000), требуется AUTH_TOKEN

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.js

Claude 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

Описание

telegram_list_chats

Список всех чатов

telegram_find_chat

Поиск чата по имени/username/ID

telegram_get_history

Получить сообщения (без скачивания медиа)

telegram_sync_chat

Основной — полная синхронизация чата с медиа

telegram_download_media

Скачать медиа из конкретного сообщения

telegram_sync_status

Статус последней синхронизации

telegram_list_media

Список скачанных медиафайлов

Типичный 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 tools
telegram_download_mediaDownload Single MediaA
Idempotent

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 ChatA
Read-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 HistoryA
Read-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 ChatsA
Read-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 MediaA
Read-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 ChatA
Idempotent

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 StatusA
Read-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

    A4.4/5.0

    Scored across 7 tools

    Disambiguation5/5

    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.

    Naming Consistency5/5

    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.

    Tool Count5/5

    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).

    Completeness5/5

    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

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to interact with a user's Telegram account: list chats, read history, search, and send messages through Telegram's MTProto API.
      2
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables searching Telegram messages and chats, retrieving recent messages, and extracting text from attached documents (PDF, TXT, MD, CSV) using your personal Telegram account.
      4
      Apache 2.0