Skip to main content
Glama
tg-secretary-mcp

tg-secretary-mcp

by developkiko

tg-secretary-mcp

MCP-сервер для Telegram-бота в режиме Secretary Mode: бот привязывается к вашему аккаунту, получает входящие личные сообщения, а ассистент может их читать, искать по ним и отвечать от вашего имени.

Это не «вы в Телеграме». По документации Telegram режим покрывает только лички и только входящие сообщения:

Нужно

Получится

Читать группу или канал

нет

Читать историю до подключения бота

нет

Видеть ваши ответы, написанные вручную в приложении

нет

Читать новые входящие лички

да, пока сервер получает обновления

Отвечать от вашего имени в личке

да, если человек писал за последние 24 часа

Отмечать прочитанным, удалять сообщения бота

да, если разрешено в правах

Всё, что бот увидел, складывается в архив. secretary_read и secretary_search работают по нему, поэтому история накапливается с момента подключения.

Два режима

Код один, различается только способ получать обновления и место архива.

Локально

На Vercel

Кто запускает

ZCode стартует сервер как процесс

Vercel запускает функции по запросу

Как приходят обновления

сервер сам опрашивает Telegram

Telegram присылает их на webhook

Где архив

data/messages.jsonl

Redis (Upstash)

Когда накапливается

пока открыта сессия ZCode

круглосуточно

Как подключается ассистент

stdio

HTTPS с токеном

Токен бота может получать обновления только одним способом. Локальный сервер перед опросом проверяет webhook и уступает, если тот настроен: переключайтесь между режимами целиком.

Related MCP server: Telegram OSINT

Настройка бота

Нужна в обоих режимах.

  1. В @BotFather: /mybots → ваш бот → Bot Settings → включите Secretary Mode.

  2. В Telegram, с того аккаунта, от чьего имени нужно отвечать: Settings → Chat Automation → добавьте бота и разрешите права. Для ответов нужно право can_reply, для отметки прочтения — can_read_messages.

Локальный режим

Нужен Node 24 или новее: TypeScript запускается нативно, без сборки.

  1. Вставьте токен в .env рядом с package.json:

    TELEGRAM_BOT_TOKEN=123456:AA...
  2. Зарегистрируйте сервер в ~/.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"]
          }
        }
      }
    }
  3. Перезапустите сессию ZCode и попросите ассистента «проверь статус секретаря»: secretary_status показывает, на каком шаге что-то не так.

Деплой на Vercel

Нужны аккаунты Vercel и база Redis в Upstash (есть бесплатный тариф; подключается из маркетплейса Vercel или создаётся вручную). Названия пунктов меню у Vercel могут отличаться от приведённых здесь.

  1. Сгенерируйте два секрета, они понадобятся дальше:

    npm run secrets
  2. В Vercel: Add New → Project → импортируйте этот репозиторий. Сборка и функции настраиваются сами через vercel.json и npm run build.

  3. Добавьте переменные окружения проекта:

    Переменная

    Значение

    TELEGRAM_BOT_TOKEN

    токен бота

    TELEGRAM_WEBHOOK_SECRET

    из npm run secrets

    MCP_AUTH_TOKEN

    из npm run secrets

    KV_REST_API_URL, KV_REST_API_TOKEN

    база Upstash Redis (подойдёт и пара UPSTASH_REDIS_REST_URL, UPSTASH_REDIS_REST_TOKEN)

  4. После деплоя укажите Telegram, куда присылать обновления:

    curl -X POST -H "Authorization: Bearer <MCP_AUTH_TOKEN>" https://<проект>.vercel.app/api/setup

    В ответе вернётся состояние webhook. ?action=remove снимает его, если хотите вернуться к локальному режиму.

  5. Подключите ассистента в ~/.zcode/cli/config.json (или в Settings → MCP):

    "tg-secretary": {
      "type": "http",
      "url": "https://<проект>.vercel.app/api/mcp",
      "headers": { "Authorization": "Bearer <MCP_AUTH_TOKEN>" }
    }
  6. Перезапустите сессию ZCode и попросите «проверь статус секретаря».

Инструменты

Инструмент

Что делает

secretary_status

получает ли бот обновления, подключён ли аккаунт, какие права выданы, что в архиве

secretary_chats

список личок, самые свежие сверху

secretary_read

переписка с человеком по имени, @username или id; можно задать диапазон дат

secretary_search

поиск по тексту: сначала точная фраза, потом все слова

secretary_reply

отправить сообщение от вашего имени

secretary_wait

дождаться нового сообщения в чате

secretary_mark_read

отметить прочитанным

secretary_delete_sent

удалить сообщение, отправленное через secretary_reply

secretary_forget

стереть переписку с человеком из архива навсегда

Сервер ничего не навязывает: чтобы узнать, что нового, его нужно попросить, например «что нового в личке?».

Что хранится

Текст входящих сообщений и отправленных ботом ответов, открытым текстом.

  • Локально: 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 tools
secretary_chatsA
Read-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_sentA
Destructive

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_forgetA
Destructive

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_readA
Read-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_statusA
Read-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_waitA
Read-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

    A4.3/5.0

    Scored across 9 tools

    Disambiguation5/5

    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.

    Naming Consistency5/5

    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.

    Tool Count5/5

    Nine tools is well-scoped for a Telegram secretary server. Each tool earns its place and there is no obvious redundancy.

    Completeness4/5

    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

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables an AI agent to interact with your personal Telegram direct messages, allowing it to read unread messages, fetch chat history, and send replies.
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables 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.
      20
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables 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.
      6
      3
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Connects 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