tg-secretary-mcp
Reads incoming Telegram private messages in Secretary Mode, archives them, and provides tools to list chats, read and search conversations, wait for new messages, reply as the user, mark messages read, delete bot-sent replies, and forget archived conversations.
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., "@tg-secretary-mcp check my new Telegram direct messages and summarize them"
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.
tg-secretary-mcp
MCP-сервер для Telegram-бота в режиме Secretary Mode: бот привязывается к вашему аккаунту, получает входящие личные сообщения, а ассистент может их читать, искать по ним и отвечать от вашего имени.
Это не «вы в Телеграме». По документации Telegram режим покрывает только лички и только входящие сообщения:
Нужно | Получится |
Читать группу или канал | нет |
Читать историю до подключения бота | нет |
Видеть ваши ответы, написанные вручную в приложении | нет |
Читать новые входящие лички | да, пока сервер получает обновления |
Отвечать от вашего имени в личке | да, если человек писал за последние 24 часа |
Отмечать прочитанным, удалять сообщения бота | да, если разрешено в правах |
Всё, что бот увидел, складывается в архив. secretary_read и secretary_search работают по нему, поэтому история накапливается с момента подключения.
Два режима
Код один, различается только способ получать обновления и место архива.
Локально | На Vercel | |
Кто запускает | ZCode стартует сервер как процесс | Vercel запускает функции по запросу |
Как приходят обновления | сервер сам опрашивает Telegram | Telegram присылает их на webhook |
Где архив |
| Redis (Upstash) |
Когда накапливается | пока открыта сессия ZCode | круглосуточно |
Как подключается ассистент | stdio | HTTPS с токеном |
Токен бота может получать обновления только одним способом. Локальный сервер перед опросом проверяет webhook и уступает, если тот настроен: переключайтесь между режимами целиком.
Related MCP server: Telegram OSINT
Настройка бота
Нужна в обоих режимах.
В @BotFather:
/mybots→ ваш бот → Bot Settings → включите Secretary Mode.В Telegram, с того аккаунта, от чьего имени нужно отвечать: Settings → Chat Automation → добавьте бота и разрешите права. Для ответов нужно право
can_reply, для отметки прочтения —can_read_messages.
Локальный режим
Нужен Node 24 или новее: TypeScript запускается нативно, без сборки.
Вставьте токен в
.envрядом сpackage.json:TELEGRAM_BOT_TOKEN=123456:AA...Зарегистрируйте сервер в
~/.zcode/cli/config.json(переменная окружения с тем же именем имеет приоритет над.env):{ "mcp": { "servers": { "tg-secretary": { "type": "stdio", "command": "C:\\Program Files\\nodejs\\node.exe", "args": ["C:\\path\\to\\tg-secretary-mcp\\src\\server.ts"] } } } }Перезапустите сессию ZCode и попросите ассистента «проверь статус секретаря»:
secretary_statusпоказывает, на каком шаге что-то не так.
Деплой на Vercel
Нужны аккаунты Vercel и база Redis в Upstash (есть бесплатный тариф; подключается из маркетплейса Vercel или создаётся вручную). Названия пунктов меню у Vercel могут отличаться от приведённых здесь.
Сгенерируйте два секрета, они понадобятся дальше:
npm run secretsВ Vercel: Add New → Project → импортируйте этот репозиторий. Сборка и функции настраиваются сами через
vercel.jsonиnpm run build.Добавьте переменные окружения проекта:
Переменная
Значение
TELEGRAM_BOT_TOKENтокен бота
TELEGRAM_WEBHOOK_SECRETиз
npm run secretsMCP_AUTH_TOKENиз
npm run secretsKV_REST_API_URL,KV_REST_API_TOKENбаза Upstash Redis (подойдёт и пара
UPSTASH_REDIS_REST_URL,UPSTASH_REDIS_REST_TOKEN)После деплоя укажите Telegram, куда присылать обновления:
curl -X POST -H "Authorization: Bearer <MCP_AUTH_TOKEN>" https://<проект>.vercel.app/api/setupВ ответе вернётся состояние webhook.
?action=removeснимает его, если хотите вернуться к локальному режиму.Подключите ассистента в
~/.zcode/cli/config.json(или в Settings → MCP):"tg-secretary": { "type": "http", "url": "https://<проект>.vercel.app/api/mcp", "headers": { "Authorization": "Bearer <MCP_AUTH_TOKEN>" } }Перезапустите сессию ZCode и попросите «проверь статус секретаря».
Инструменты
Инструмент | Что делает |
| получает ли бот обновления, подключён ли аккаунт, какие права выданы, что в архиве |
| список личок, самые свежие сверху |
| переписка с человеком по имени, @username или id; можно задать диапазон дат |
| поиск по тексту: сначала точная фраза, потом все слова |
| отправить сообщение от вашего имени |
| дождаться нового сообщения в чате |
| отметить прочитанным |
| удалить сообщение, отправленное через |
| стереть переписку с человеком из архива навсегда |
Сервер ничего не навязывает: чтобы узнать, что нового, его нужно попросить, например «что нового в личке?».
Что хранится
Текст входящих сообщений и отправленных ботом ответов, открытым текстом.
Локально:
data/messages.jsonl. Каталогdata/и.envв.gitignore.На Vercel: список
tg-secretary:logв Redis. Это облачное хранилище третьей стороны: доступ к нему определяется доступом к вашему аккаунту Upstash.
Переключатели:
TG_SECRETARY_READONLY=1— запретить отправку, отметку прочтения и удаление.TG_SECRETARY_NO_ARCHIVE=1— только локально: не писать сообщения на диск, архив живёт в памяти сессии.TG_SECRETARY_DATA_DIR— только локально: другое место для архива (по умолчанию./data).
Разработка
npm run check # проверка типов
npm test # тесты, включая сборку функций и запуск собранных файлов
npm run build # собрать функции для Vercel в api/Стек: grammY, официальный SDK MCP, zod, клиент Upstash Redis. Функции для Vercel лежат в src/vercel/, сборщик — scripts/build-api.mjs: он упаковывает каждую в один файл в api/.
Тесты работают без сети. Один тест обращается к Telegram с заведомо неверным токеном и включается переменной TG_TEST_NETWORK=1.
Available Tools
9 toolssecretary_chatsARead-only
List the private chats the archive has seen, most recent first. The bot only sees private chats that wrote to the owner after it was connected (Settings → Chat Automation), and only while the server was running. Groups, channels and older history are never available.
Inputs: limit.
secretary_delete_sentADestructive
Delete a message that was sent through secretary_reply, on the owner's behalf. Only this bot's own messages can be deleted this way.
Inputs: chat (required), message_id (required).
secretary_forgetADestructive
Drop the archived conversation with one person for good. Nothing changes on Telegram. Use when the owner asks to remove stored messages.
Inputs: chat (required).
secretary_mark_readA
Mark an incoming message as read on the owner's behalf; everything before it in that chat is read too. Pass the latest message_id to clear the whole chat.
Inputs: chat (required), message_id (required).
secretary_readARead-only
Read the archived conversation with one person, oldest first. The bot only sees private chats that wrote to the owner after it was connected (Settings → Chat Automation), and only while the server was running. Groups, channels and older history are never available.
Inputs: chat (required), limit, since, until.
secretary_replyA
Send a text message to a private chat AS THE OWNER: the recipient sees it written by the owner, not by a bot. Use only for text the owner has approved for this chat. Replies only work in private chats that wrote to the owner during the last 24 hours.
Inputs: chat (required), text (required), reply_to.
secretary_searchARead-only
Search message text across the archive, or within one chat. Full phrase matches come first, then messages with all the words. The bot only sees private chats that wrote to the owner after it was connected (Settings → Chat Automation), and only while the server was running. Groups, channels and older history are never available.
Inputs: query (required), chat, limit, since, +1 more.
secretary_statusARead-only
Health check: does the bot receive updates, is a Telegram account connected, which rights did the owner grant, what is in the archive. Call this first when something does not work.
Inputs: no named parameters.
secretary_waitARead-only
Wait for new incoming messages from one chat and return them. Resolves as soon as a message arrives (a short burst is collected together), or when the time is out. Use after secretary_reply to get the answer.
Inputs: chat (required), timeout_seconds.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 9 tools
Each tool targets a distinct operation: status, chat listing, reading, searching, replying, waiting, marking read, deleting sent messages, and forgetting an archive. The descriptions clearly separate potentially adjacent tools such as delete_sent versus forget and read versus search.
All tools use the same secretary_ prefix with snake_case operation names. The set is predictable and readable, even though some suffixes are nouns (status, chats) and others are verbs.
Nine tools is well-scoped for a Telegram secretary server. Each tool earns its place and there is no obvious redundancy.
The core private-chat lifecycle is covered: health, listing, reading, searching, replying, waiting, marking read, deleting sent messages, and forgetting archives. Minor gaps remain around editing sent messages and sending non-text media, but the stated text-focused scope is largely complete.
Maintenance
Related MCP Connectors
Your personal Telegram account for AI: read, search and sum up chats. QR login, no API key.
Read, search and summarize your WhatsApp, Telegram, Slack and Discord chats. Replies need your OK.
Let AI assistants post to your Telegram chats, groups and channels. Not affiliated with Telegram.
Telegram automation for AI: read and search channel summaries, get digests, manage auto-publishing.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables an AI agent to interact with your personal Telegram direct messages, allowing it to read unread messages, fetch chat history, and send replies.MIT
- AlicenseAqualityBmaintenanceEnables an AI assistant to read and search the user's own Telegram account chats through a local server with no write operations. It also runs a background watcher that pre-filters incoming messages with substring, word, or regex rules and, optionally, has Claude judge each hit against plain-language criteria to surface only the alerts that matter.20MIT
- AlicenseAqualityBmaintenanceEnables AI assistants to search and read a private, local archive of your own Telegram chats, groups and media, so they can answer questions about past conversations. It keeps access read-only toward Telegram, treats message text as untrusted, and lets you choose which chats AI apps may see.63MIT
- AlicenseNot gradedqualityCmaintenanceConnects your own Telegram account or a bot to Claude and other AI assistants so they can read, search, send, and wait for Telegram messages, with everything stored in a local database.MIT