telegram-mcp
Gives an AI agent a regular Telegram account: reads messages from private chats, groups, channels and bots (by date, range, or full history with pagination), transcribes voice notes and video notes locally, returns photos, PDFs, text files and video previews as model-friendly content, sends messages and files with formatting and replies, creates groups and channels with invites and members, and interacts with bots (sending /start, clicking inline buttons, waiting for replies).
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 summarize unread messages in my family group and reply that I'm on my way"
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.
Что умеет
Читать что угодно. Личные чаты, группы, каналы и ботов: сообщения за сегодня, за конкретный день, за диапазон дат или всю историю страницами.
Понимать голосовые. Голосовые и кружки расшифровываются на вашем сервере через faster-whisper. Telegram Premium и внешние API не нужны.
Видеть файлы. Фото приходят модели как изображения, PDF и текстовые файлы как текст, у видео есть превью и расшифровка звука.
Писать. Сообщения и файлы в личку, группы и каналы, ответы на конкретные сообщения, форматирование.
Создавать чаты. Группы и каналы (приватные или публичные), добавление участников, ссылки-приглашения.
Работать с ботами. Отправить
/start, нажать кнопку и дождаться ответа бота.Два режима. stdio, когда агент запускает сервер сам, и HTTP с Bearer-токеном, когда агент ходит по адресу.
Удобно для ИИ. Ответы компактным текстом с id сообщений, подсказки о следующем шаге («есть ещё сообщения, вызови с
before_id=…»), понятные ошибки.
Related MCP server: telegram-mcp
Быстрый старт
На VPS с Linux или на Mac:
git clone https://github.com/adsqwui/telegram-mcp.git ~/telegram-mcpcd ~/telegram-mcp && ./install.shСкрипт спросит ключи API, покажет QR-код для входа и в конце напечатает, как подключить сервер к агенту. Всё остальное он поставит сам.
Установка по шагам
Что нужно
Система | Linux (x86_64 или arm64) или macOS |
Память | около 1 ГБ свободной для модели |
Диск | около 1.5 ГБ: зависимости и модель Whisper |
Telegram |
|
Python ставить не нужно: скрипт поставит uv, а тот скачает Python 3.12 в папку проекта.
1. Получите api_id и api_hash
Откройте https://my.telegram.org и войдите по номеру телефона.
Перейдите в API development tools.
Создайте приложение (название и описание любые) и скопируйте
api_idиapi_hash.
2. Запустите установку
git clone https://github.com/adsqwui/telegram-mcp.git ~/telegram-mcpcd ~/telegram-mcp && ./install.shЧто произойдёт:
Зависимости. Ставятся uv, Python 3.12 и пакеты в
.venv. В системе ничего не меняется.Ключи. Скрипт спросит
api_idиapi_hashи сохранит их в.envс правами600.Вход по QR. Пока вы входите, в фоне качается модель Whisper. QR-код появится в терминале, а рядом будет ссылка на страницу с тем же кодом:
на Mac страница откроется в браузере сама;
на VPS откройте ссылку вида
http://IP_сервера:8766/<случайный путь>/. Если порт закрыт файрволом, скрипт напечатает команду SSH-туннеля, а ещё можно сканировать код прямо из терминала.
В Telegram на телефоне: Настройки → Устройства → Подключить устройство, наведите камеру на код. Код обновляется каждые 30 секунд. Если включён облачный пароль, скрипт его спросит.
Токен. Для HTTP-режима генерируется случайный
MCP_BEARER_TOKEN.Автозапуск. На Linux с systemd скрипт предложит поставить службу
telegram-mcp.Итог. В конце печатаются готовые настройки для stdio и HTTP.
В списке устройств Telegram сессия будет называться Telegram MCP. Там же её можно завершить в любой момент.
Отдельные команды
Задача | Команда |
Войти ещё раз (старая сессия завершится) |
|
Только ввести новые ключи API |
|
Скачать модель Whisper заново |
|
Обновление
cd ~/telegram-mcp && git pull && uv sync --frozen --no-dev && sudo systemctl restart telegram-mcpБез службы systemd последнюю часть команды пропустите и просто перезапустите агента.
Подключение к агенту
На одну сессию должен работать один процесс сервера: либо stdio, либо HTTP. Один процесс спокойно обслуживает нескольких агентов.
stdio
Агент сам запускает сервер на той же машине. Пример для клиентов с конфигом в стиле Claude Desktop или Cursor:
{
"mcpServers": {
"telegram": {
"command": "/home/user/telegram-mcp/.venv/bin/telegram-mcp",
"args": ["--transport", "stdio", "--env-file", "/home/user/telegram-mcp/.env"]
}
}
}Для Claude Code:
claude mcp add telegram -- ~/telegram-mcp/.venv/bin/telegram-mcp --transport stdio --env-file ~/telegram-mcp/.envHTTP
~/telegram-mcp/.venv/bin/telegram-mcp --transport httpАдрес |
|
Заголовок |
|
Без правильного токена сервер отвечает 401. По умолчанию он слушает только 127.0.0.1. Чтобы слушать внешний адрес (MCP_HOST=0.0.0.0), токен обязателен, иначе сервер не запустится.
Если агент вызывает MCP из облака по URL, поставьте перед сервером reverse proxy с HTTPS и не открывайте порт 8765 наружу. Пример для Caddy, сертификат он получит сам:
mcp.example.com {
reverse_proxy 127.0.0.1:8765
}systemd
Если вы отказались при установке, службу можно поставить позже:
cd ~/telegram-mcp && ./install.shСкрипт пропустит уже сделанные шаги (ключи, вход, модель) и снова предложит службу. Логи службы: journalctl -u telegram-mcp -f.
Инструменты
Параметр chat везде принимает числовой id из tg_list_chats (самый надёжный вариант), @username, ссылку t.me/... (включая приглашения t.me/+..., если вы уже в чате), me для «Избранного» или точное название чата.
Чтение
Инструмент | Что делает |
| Аккаунт, часовой пояс, режим только чтения, настройки расшифровки |
| Чаты с id, типом, непрочитанными и последним сообщением |
| Описание, участники, ваша роль, ссылка-приглашение, команды бота |
| Сообщения от старых к новым |
| Файлы из сообщений в удобном для модели виде |
date:today,yesterday,2026-11-24или24.11.2026. День считается поTG_TIMEZONE.since/until: диапазон, день или2026-11-24 14:00.limit: до 500 за вызов. Если сообщений больше, ответ заканчивается подсказкой сbefore_idдля следующей страницы. Так читается вся история.after_id: только сообщения новее указанного, удобно для проверки новых.searchиfrom_user: поиск по тексту и сообщения конкретного человека.Голосовые и кружки приходят сразу с расшифровкой. Расшифровка кешируется, одно сообщение обрабатывается один раз.
include_images=trueприкладывает фото как изображения, до 10 за вызов.mark_read=trueотмечает чат прочитанным. По умолчанию сервер ничего прочитанным не отмечает.
Тип | Что получает модель |
Фото, картинки, стикеры | Изображение |
Голосовые, кружки, аудио | Расшифровку |
Видео | Превью и расшифровку звука |
TXT, CSV, JSON, MD, код | Текст файла |
Текст по страницам | |
Любой файл | Путь на сервере, а с |
Файлы сохраняются в files/downloads/<chat_id>/, по этому пути их можно переслать через tg_send_file.
Запись
Инструмент | Что делает |
| Текст в личку, группу, канал или боту |
| Фото, голосовое, кружок, видео или файл |
| Нажать кнопку под сообщением |
format:markdown(**жирный**,__курсив__,`код`,[текст](ссылка)),htmlилиplain.wait_reply: сколько секунд ждать ответ. Сервер вернёт новые и изменённые входящие сообщения. Нужен в первую очередь для ботов.Файл для
tg_send_fileзадаётся одним из трёх способов: путь на сервере (только внутриTG_ALLOWED_ROOTS), публичная ссылка, которую Telegram скачает сам, илиcontent_base64сfilename, если агент работает на другой машине.send_as:auto,photo,document(без сжатия),voice(нужен.oggс opus),video_note.
Группы и каналы
Инструмент | Что делает |
| Группа, сразу с участниками, в ответе id и ссылка |
| Канал, публичный при заданном |
| Добавить людей в группу или канал |
Если настройки приватности не дают кого-то добавить, сервер так и скажет. Таким людям нужно отправить ссылку-приглашение.
Боты
Отдельных инструментов для ботов нет, хватает общих:
Действие | Вызов |
Запустить бота |
|
Deep link |
|
Нажать кнопку |
|
Посмотреть экран |
|
Команды и описание |
|
Кнопки приходят списком вида [row,col] Текст. Кнопки-ссылки и мини-приложения не открываются, сервер возвращает их адрес. Кнопки оплаты, кнопки, которые передают телефон или геопозицию, и кнопки с запросом облачного пароля не нажимаются.
Как выглядит ответ
Отдел продаж [group, id -1001234567890] · 3 message(s) from 2026-11-24 00:00 to 2026-11-25 00:00
#4519 · 2026-11-24 10:02 · Анна · @anna · id 111
Коллеги, кто возьмёт клиента из Казани?
#4520 · 2026-11-24 10:05 · Иван · @ivan · id 222
reply to #4519
[voice 0:14]
transcript: Возьму, только скиньте контакт и сумму заказа.
#4521 · 2026-11-24 10:06 · Анна · @anna · id 111
[file КП Казань.pdf (240.1 KB, application/pdf)]
Messages with media: 4521. tg_get_media returns images, transcripts and file contents.Настройки
Все переменные с пояснениями лежат в .env.example. Главные:
Переменная | По умолчанию | Что это |
|
| Пояс для |
|
|
|
|
|
|
| авто | Например |
|
| Более длинные голосовые расшифровываются только через |
|
| Папки, откуда можно отправлять локальные файлы, через |
|
| Файлы больше сохраняются на сервере, но не передаются в ответе |
|
| Пауза между отправками в секундах |
|
| Адрес HTTP-режима |
| генерируется | Токен HTTP-режима |
После смены TG_WHISPER_MODEL выполните uv run telegram-mcp-model.
Безопасность
Сервер работает от имени настоящего аккаунта, поэтому несколько вещей устроены строже обычного:
Служебный чат Telegram (777000) скрыт. Туда приходят коды входа, и агента, которого обманули через чужое сообщение, нельзя заставить их переслать.
Файлы сессии и
.envне отправляются никогда, даже если они лежат в разрешённой папке. Симлинки проверяются по настоящему пути.Отправка с диска ограничена папками из
TG_ALLOWED_ROOTS.HTTP закрыт токеном, сравнение идёт за постоянное время. Без токена сервер слушает только loopback.
Режим только чтения (
TG_READ_ONLY=true) удобен, пока вы проверяете нового агента.
Что сделать вам:
Храните
sessions/mcp.sessionв секрете: этот файл даёт полный доступ к аккаунту. Он уже в.gitignore. Если файл утёк, завершите сессию «Telegram MCP» в разделе Настройки → Устройства.Помните, что всё отправленное агентом уходит от вашего имени. Для экспериментов лучше завести отдельный аккаунт.
Не злоупотребляйте массовыми действиями. Telegram ограничивает частоту запросов, а массовые приглашения и создание чатов могут закончиться FloodWait на несколько часов.
Разработка
git clone https://github.com/adsqwui/telegram-mcp.git && cd telegram-mcpuv sync && uv run pytest -qsrc/telegram_mcp/
├── server.py # инструменты MCP, stdio и HTTP
├── client.py # клиент Telethon, поиск чата по id, нику, ссылке или названию
├── render.py # даты и форматирование сообщений
├── media.py # скачивание файлов и превращение их в контент для модели
├── transcribe.py # faster-whisper и кеш расшифровок
├── login.py # вход по QR (страница в браузере и код в терминале)
└── config.py # настройки из .envЛицензия
Available Tools
11 toolstg_add_membersB
Add people to a group or channel where this account may invite. members: ids or @usernames.
Inputs: chat (required), members (required).
tg_chat_infoARead-only
Details of a chat, group, channel, user or bot: description, members, your rights, invite link, bot commands.
Inputs: chat (required).
tg_clickA
Press an inline or keyboard button on a message (usually a bot's) and return what changed.
row and col come from the "[row,col]" list under the message. Link and mini app buttons are not
opened, their URL is returned instead.
Inputs: col (required), row (required), chat (required), message_id (required), +1 more.
tg_create_channelA
Create a channel owned by this account. username makes it public (t.me/username), otherwise it is private. members: ids or @usernames to add as subscribers. Returns the new chat id and an invite link.
Inputs: title (required), about, members, username.
tg_create_groupB
Create a group (supergroup) owned by this account. members: ids or @usernames to add right away. Returns the new chat id and an invite link.
Inputs: title (required), about, members.
tg_get_mediaARead-only
Download the media of up to 10 messages and return it in a usable form.
Photos and images come back as images, video as a thumbnail plus transcript, voice/audio as a
transcript, text and PDF files as their text. Every file is saved on the server and its path is
returned (it can be sent again with tg_send_file). embed_file also attaches the raw file bytes.
Inputs: chat (required), message_ids (required), embed_file, transcribe.
tg_list_chatsARead-only
List dialogs in Telegram's order (pinned first, then newest activity): id, title, type, unread count, last message.
kind filters by type ("private" includes Saved Messages). query matches the title or @username.
Inputs: kind, limit, query, unread_only.
tg_read_messagesARead-only
Read messages of any chat, group or channel, oldest first.
date: one day, "today", "yesterday", "2026-11-24" or "24.11.2026" (in TG_TIMEZONE).
since / until: a range instead of date, a day or "2026-11-24 14:00".
limit: up to 500 per call. To read the whole history, repeat the call with before_id set to the
smallest id from the previous page until no more pages are reported. after_id returns only newer messages.
search: only messages containing this text. from_user: only messages from this person.
transcribe_voice: voice and round video messages come with a text transcript.
include_images: photos are attached as images (at most 10 per call).
mark_read: mark the chat as read up to the newest returned message.
Inputs: chat (required), date, limit, since, +8 more.
tg_send_fileA
Send a photo, voice message, video or any file. Give exactly one source:
path: a file on the server (from tg_get_media or inside TG_ALLOWED_ROOTS);
url: a public http(s) link that Telegram downloads itself;
content_base64 + filename: the file bytes, for clients that are not on the server.
send_as: auto picks by type, document keeps the original file, voice needs .ogg (opus) audio.
caption supports the same markdown as tg_send_message.
Inputs: chat (required), url, path, silent, +6 more.
tg_send_messageA
Send a text message to a private chat, group, channel (you must be allowed to post) or bot.
format "markdown": **bold**, __italic__, `code`, [text](https://link). reply_to: message id to reply to.
silent: no notification sound. wait_reply: seconds to wait and return incoming replies (useful for bots).
Inputs: chat (required), text (required), format, silent, +2 more.
tg_statusBRead-only
Which account the server uses and how it is configured. Call it first if anything fails.
Inputs: no named parameters.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 11 tools
Each tool targets a distinct action/resource: read vs send vs media download vs chat metadata vs creation vs membership vs button clicks. The only soft overlap is tg_read_messages carrying include_images/transcribe_voice options that partly duplicate tg_get_media's purpose, and tg_create_channel vs tg_create_group, but descriptions make the boundary clear enough.
All tools share a consistent tg_ prefix with a predictable verb_noun shape (tg_list_chats, tg_send_file, tg_create_group, tg_add_members). Minor deviations like tg_status (noun only) and tg_click (bare verb) break the pattern slightly but remain obvious in context.
11 tools is a well-scoped surface for a Telegram client: coverage of status, chats, messages, media, sending, bot interactions and chat administration without redundancy. Every tool earns its place and none feel like padding.
The core lifecycle (list/inspect chats, read history with pagination/search, send text and files, download media, interact with bot buttons, create channels/groups, add members) is well covered. Notable gaps remain around message edit/delete/forward and leaving or managing existing chats, which agents cannot work around with the current surface.
Maintenance
Related MCP Connectors
Multi-tenant Telegram gateway for AI agents — HTTP+stdio, 8 tools, MTProto User API
Telegram bridge for your MCP-compatible agent. Bidirectional, no LLM in our stack.
Your personal Telegram account for AI: read, search and sum up chats. QR login, no API key.
Let AI assistants post to your Telegram chats, groups and channels. Not affiliated with Telegram.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables AI assistants to control a personal Telegram account for sending/reading messages, media, group management, and more via the MTProto API.MIT
- AlicenseNot gradedqualityDmaintenanceGives an AI assistant full control of a real Telegram user account over MTProto, enabling it to read chats, search history, send and manage messages, and dynamically create new tools as needed.MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to operate a Telegram account through the same commands as the terminal client: messaging, chat management, voice transcription, calls, stickers, and privacy settings.1MIT
- AlicenseNot gradedqualityDmaintenanceLets any MCP-compatible AI agent read, search, and send Telegram messages through your real account via MTProto.1MIT