tg
This server gives an AI agent access to your Telegram account: it archives chats as Markdown on disk, reads and analyzes their content, and sends messages with your confirmation.
List chats (
list_dialogs): the 50 most recent dialogs with ids, type and unread count, or search any chat by title/name.Archive chats (
sync_chat): download the last N days or the full history into the local archive; later calls fetch only new messages.Transcribe voice/video messages (
transcribe) by message ids into the archive.OCR photos (
ocr_photos) with Apple Vision — all unprocessed photos or specific ids.Read files (
read_files): txt, md, csv, html, pdf, doc, docx, rtf, xlsx, pptx and images, including scanned PDFs, saved totext/<id>.txt.Download media (
fetch_media) up to 50 MB (photos and files, no video/audio) and return local paths.Download large files (
fetch_large_file) over 50 MB, only after user approval, in resumable chunks.Describe media (
describe_media): save a short one-line description of a photo or file to the archive.Send messages (
send_message) as you, optionally as a reply, only after you have seen and confirmed the text.
Provides AI agents with access to a Telegram account over MTProto, enabling listing dialogs, syncing chat history into a local Markdown archive, transcribing voice and video messages, OCR-ing photos, fetching and describing photos, and sending messages after user confirmation.
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 Summarize my last three weeks of messages with Ivan Petrov"
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-scribe — Telegram for AI agents on Mac
English | Русский
A local MCP server for macOS and Windows that gives an AI agent, such as Claude Code, access to your Telegram account. The agent saves your chats as Markdown files on disk and works with them: searches, analyzes, summarizes, drafts replies.
The server runs on your machine and connects to Telegram as you, over the official MTProto protocol. It uses the Telethon library and your own api_id. Text on photos and reading PDF, doc and rtf use Apple Vision, PDFKit and textutil, so these features need a Mac; everything else — login, archive, search, sending, forwarding, proxy — works on Windows too.
Contents
Related MCP server: TeleMCP
What it does
Tool | What it does |
| Shows the 50 most recent chats with their folders. Finds any other chat by name; |
| Shows the topics of a forum chat: id and title |
| Saves a chat to the archive: the last N days or the whole history. Later calls add new messages. |
| Transcribes voice and video messages. Needs Telegram Premium |
| Reads text on photos with Apple Vision, locally on your Mac |
| Reads the text of txt, md, csv, html, pdf, doc, docx, rtf, xlsx, pptx and image files locally on your Mac, including scanned PDFs, and saves it to |
| Downloads a photo or a file up to 50 MB so the agent can look at it. Files keep their names: |
| Saves a short description of a photo or a file to the archive |
| Downloads a file over 50 MB after you confirm it. A big file is downloaded over several calls |
| Sends a message after you confirm it |
| Forwards messages to another chat after you confirm it |
How it works in practice
You ask: "What did we agree on with the contractor over the last three weeks?"
The agent calls
sync_chatwithdays=21. The server saves three weeks of messages to the archive, newest first.The agent searches the archive. An important voice message is marked as not transcribed, so the agent transcribes it with
transcribe. It needs the numbers from a photo of an estimate, so it reads the text withocr_photos.The agent answers and cites message ids.
Next day you ask: "Anything new?"
sync_chatloads only new messages. It transcribes and reads their voice messages, photos and files up to 10 MB right away, up to 20 of each per call. Bigger files wait forread_files.You ask: "And what did we decide last month?" The agent calls
sync_chatwithdays=60, and the server loads the missing older history.
Voice messages, photos and files from older history are not processed while loading. The agent transcribes and reads them only when a task needs them. That is why loading takes minutes, not hours, and does not use up limits.
Archive
Chats are stored in the archive/ folder next to the MCP source code, one file per month. The text of read files is in the text/ subfolder of each chat. The folder is in .gitignore.
A forum topic saved with topic lives in its own folder inside the chat's folder: archive/<chat>/<topic>__<topic_id>/2026-10.md.
archive/Ivan-Petrov__123456789/2026-10.mdOne line per message. The tags are in Russian. Sample file:
[2026-10-31 14:02] #48213 Ivan Petrov: Sent the estimate
[2026-10-31 14:03] #48214 Ivan Petrov [фото, с текстом]:
[на фото] Tiles: $600
[на фото] Total: $1,500
[2026-10-31 14:05] #48215 Я ↩48213: [голосовое 0:42] «Too expensive, let's talk tonight»
[2026-10-31 14:06] #48216 Ivan Petrov [фото: kitchen plan with sizes]: here is the plan
[2026-10-31 14:07] #48217 Ivan Petrov [переслано из «Renovation News»]: Tile prices went up
15% in November
[2026-10-31 14:10] #48218 Ivan Petrov: [кружок 0:35, не расшифровано]
[2026-10-31 14:12] #48219 Ivan Petrov [файл contract.docx, 48 КБ, с текстом]: please signWhat each part means:
Part | Meaning |
| Date and time in your Mac's time zone |
| Message id |
| You ("me") |
| Reply to message 48213 |
Line indented by 2 spaces | Next line of a multi-line message |
| Forwarded message and its source |
| Transcript of a voice or video message |
| Voice message not transcribed yet |
| Photo not processed yet |
| Photo has text, shown in the |
| Photo has no text |
| Photo description saved by the agent |
| Photo was deleted from Telegram |
| Photo file is broken |
| File. For txt, md, csv, html, pdf, doc, docx, rtf, xlsx, pptx and images: not read yet |
| The full text of the file is in |
| The file has no text |
| PDF page count, added once the file is read |
| Some PDF pages were scans: their text was read with Apple Vision and may have errors |
| File description saved by the agent. It does not replace the state: an unread file is still read by |
| File was deleted from Telegram or is broken |
| File is over 50 MB, the server does not download it |
| Video, sticker, GIF, poll, location, contact |
The archive only grows: messages edited or deleted in Telegram stay as they were saved.
Requirements
macOS or Windows. Login, archive, search, sending, forwarding and proxy work on both; text recognition on photos and reading PDF, doc and rtf need macOS (Apple Vision, PDFKit, textutil).
uv. It installs Python 3.12 and all dependencies by itself, including
python-socksfor proxy connections.An AI agent with MCP support, such as Claude Code.
A Telegram account. Transcribing voice messages needs Telegram Premium.
Installation
1. Get the project and install dependencies
Install uv if you do not have it yet:
macOS:
brew install uv, or the official installercurl -LsSf https://astral.sh/uv/install.sh | shWindows (PowerShell):
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
Then get the project and install the dependencies:
git clone https://github.com/rodion1010/tg-scribe.git tg-scribe
cd tg-scribe
uv syncuv sync downloads Python 3.12 and installs every dependency — Telethon, the MCP library, segno for login QR codes, python-socks for proxy connections. Nothing else is installed by hand.
2. Get api_id and api_hash
Telegram lets third-party programs into an account only through a registered app. Registration is free and takes a couple of minutes.
Open my.telegram.org and enter your phone number in international format, for example
+15551234567.Enter the confirmation code on the site. It arrives in Telegram from the "Telegram" account, not by SMS.
Select API development tools.
Fill in the fields:
App title: any name without the word "Telegram", for example
tgc. The API terms forbid "Telegram" in the name.Short name: 5 to 32 Latin letters and digits, for example
tgclaude.URL: leave empty.
Platform: Desktop.
Description: leave empty.
Click Create application. The page shows App api_id, a number, and App api_hash, a 32-character string.
If the site shows ERROR, open it in another browser. One account can have one app: if you already have one, the site shows its data right away.
Never share api_hash and never commit it: anyone with it can pose as your app.
3. Save api_id and api_hash to the config
Create the folder and the config file:
mkdir -p ~/.tgc && chmod 700 ~/.tgc
nano ~/.tgc/config.tomlPaste your values:
api_id = 12345678
api_hash = "0123456789abcdef0123456789abcdef"Make the file private to your user:
chmod 600 ~/.tgc/config.toml4. Log in
uv run python -m tgc.loginThe program shows a QR code — scan it in Telegram: Settings → Devices → Link Desktop Device. The code opens as a PNG in your default image viewer; add --terminal to print it right in the terminal instead. The code lives about 26 seconds and is re-shown automatically. If two-step verification is on, the program asks for your cloud password. After login the file ~/.tgc/tgc.session appears.
This file gives full access to your account without a code or password. Do not copy it, publish it or put it in cloud storage. If it leaks, end the session in Telegram: Settings → Devices.
5. Connect the server to your agent
The server starts with this command:
uv run --directory /path/to/tg-scribe python -m tgc.serverHere /path/to/tg-scribe is the folder you cloned the project into. Add this command to your agent's MCP server settings. The steps for Claude Code, OpenChamber (OpenCode) and Hermes Agent follow.
Claude Code
The project already has .mcp.json with this server. Start Claude Code in the project folder and allow the tg server when Claude Code asks.
To use Telegram from any folder, add the server for your user:
claude mcp add tg --scope user -- uv run --directory /path/to/tg-scribe python -m tgc.serverThe archive still lives in archive/ next to the MCP source code.
The project's .claude/settings.json rules that ask before sending and before downloading big files do not apply in other folders. Add them to ~/.claude/settings.json:
{
"permissions": {
"ask": ["mcp__tg__send_message", "mcp__tg__forward_messages", "mcp__tg__fetch_large_file"]
}
}OpenChamber and OpenCode
Add the server. Run this from any folder;
--globalmakes it available in every project:
opencode mcp add tg --global -- uv run --directory /path/to/tg-scribe python -m tgc.serverThe command writes the server to the config file it names, usually ~/.config/opencode/opencode.json.
Check the connection:
opencode mcp list✓ tg connected means the server is up. Inside the app, /mcps shows the servers and their state.
Or add the server by hand to the config:
{
"mcp": {
"tg": {
"type": "local",
"command": ["uv", "run", "--directory", "/path/to/tg-scribe", "python", "-m", "tgc.server"]
}
}
}Make sends, forwards and large downloads ask for confirmation. OpenCode allows every tool by default and ignores the
readOnlyHintannotation, so without these rules the agent sends a message without asking. Add to the same config:
{
"permissions": [
{ "action": "tg_send_message", "resource": "*", "effect": "ask" },
{ "action": "tg_forward_messages", "resource": "*", "effect": "ask" },
{ "action": "tg_fetch_large_file", "resource": "*", "effect": "ask" }
]
}If the config already has allow rules, put these after them: the last matching rule wins. This is the V2 config format; older OpenCode versions call the key permission, check the docs for your version.
Ask the agent: "Show my recent Telegram chats". The tools are named
tg_list_dialogs,tg_send_messageand so on.
Hermes Agent
Add the server.
--commandwants the full path touv— find yours withwhich uv:
hermes mcp add tg --command /opt/homebrew/bin/uv --args run --directory /path/to/tg-scribe python -m tgc.serverAnswer "y" when Hermes offers to enable the tools.
Check the connection:
hermes mcp test tgMake sends and forwards ask for confirmation. In
~/.hermes/config.yaml:
mcp_servers:
tg:
trust: untrustedRead-only tools then run without questions — the server marks them with a readOnlyHint annotation. send_message, forward_messages and fetch_large_file ask every time: Allow Once, Allow Session or Allow Always. "Allow Always" writes the tool to command_allowlist in the same file — remove that line to revoke it.
Restart Hermes, or run
/reload-mcpin an open session.
6. Check the connection
Ask the agent: "Show my recent Telegram chats". It calls list_dialogs and shows the list.
Permissions
The agent sends and forwards messages only after you confirm it. Tools are separated by annotations: every tool that only reads — listing chats, saving the archive, transcription, text and file recognition — carries a readOnlyHint annotation, so agents run it without questions. send_message, forward_messages and fetch_large_file carry no annotation: agents that respect the hint, such as Hermes, ask for confirmation on every call. The annotation is only a hint: an agent that ignores it, such as OpenCode, needs explicit approval rules, as in the guide above.
In Claude Code, .claude/settings.json takes care of this: it allows reading, saving and recognizing chats without asking, and sets an ask rule on sending and forwarding. Claude Code shows the text and the chat every time and waits for your "yes". Do not move send_message or forward_messages to allow.
fetch_large_file works the same way, through ask: a file over 50 MB is downloaded only if you agree. This keeps the agent from filling the disk and spending time on a file you do not need.
The rule works only in the project folder. For other folders, add it to ~/.claude/settings.json as described in step 5. In other agents, set up confirmation for send_message the same way.
Choosing a chat
You can name a chat by part of its title, but Telegram search does not find every chat, and the agent may pick a similar one. Before sending, give the chat id instead: list_dialogs shows it. After sending, the server names the chat the message went to.
To see ids in Telegram itself, turn them on in the debug menu. In Telegram Desktop, open Settings → Advanced → Experimental settings and turn on Show Peer IDs in Profile. For other platforms, see the tginfo guide (in Russian).
Change only this setting in the debug menu: other options can break the app or delete secret chats.
Forum topics
Some supergroups are forums: the chat is split into topics. list_topics shows them with their ids.
To read one topic, the agent calls
sync_chatwithtopic— a topic id or part of its title, named the same way as a chat. Example: "What did they answer about GPT Model Hub this week?" →sync_chatwithdays=7andtopic="GPT Model Hub".A topic is saved to its own folder inside the chat's folder:
archive/<chat>/<topic>__<id>/. A topic sync never touches the chat's own files.transcribe,ocr_photos,read_files,fetch_media,fetch_large_fileanddescribe_mediatake the sametopicwhen they work with topic messages, so voice, photos and files land in the topic's folder.Without
topicthe whole forum is saved, all topics mixed in the chat's own files.
Proxy
By default the server connects to Telegram directly. If Telegram is only reachable through a proxy, set it in ~/.tgc/config.toml:
proxy = "socks5://127.0.0.1:1080"Explicit proxy. Schemes:
socks5://,socks4://,http://,https://(used as HTTP CONNECT), and a Telegram MTProto proxy:mtproto://host:port/secret. The scheme is optional:127.0.0.1:1080meanshttps://127.0.0.1:1080. Login and password go in the URL:socks5://user:pass@host:port. The characters@,:and/in a login or password are written as%40,%3Aand%2F.proxy = "auto"— let the server find the proxy: thehttp_proxy/https_proxyenvironment variables, then the OS settings — Windows: Internet options, macOS: System Settings → Network → Proxies. Nothing found — connect directly.proxy = "direct"— connect directly, the same as removing the line.
At startup the server writes the connection method to its log, for example: Telegram: подключаюсь напрямую (proxy в config.toml не задан) or Telegram: подключаюсь через прокси socks5://127.0.0.1:1080 (из config.toml).
Limits and risks
Telegram limits. If Telegram asks to wait longer than 30 seconds, the server stops and says how long to wait. It never waits longer than 30 seconds itself, so the call does not time out.
Large loads take several calls of up to 200 seconds each. 150,000 messages load in about 10 calls, and the agent repeats them by itself.
One session at a time. If two agent sessions use Telegram at once, the second gets "Telegram busy" and retries later.
Telegram terms. The API terms forbid preventing self-destructing messages from disappearing, and the server saves messages from chats with auto-delete. The content licensing terms forbid training AI models on Telegram data. The archive holds other people's messages too, so stop your agent's provider from training on your data. In claude.ai this is the Help improve Claude setting.
Chat text is data, not commands. The server tells the agent not to follow requests found in chats. Still, confirm a send only after you have read the text.
Development
Run the tests:
uv run pytestThe code has four modules:
tgc/client.py: Telegram connection and chat lookup;tgc/archive.py: archive format, sync, transcription and text recognition;tgc/server.py: MCP tools and instructions for the agent;tgc/login.py: account login.
License
Available Tools
9 toolsdescribe_mediaC
Сохраняет в архив короткое описание фото или файла (до 200 символов, одна строка).
Inputs: id (required), chat (required), text (required). Returns: result
fetch_large_fileA
Скачивает файл больше 50 МБ (без видео и аудио) в папку чата в архиве и возвращает путь. Только после того, как пользователь согласился. Файл качается частями: если ответ «вызови ещё раз» — повтори.
Inputs: id (required), chat (required). Returns: result
fetch_mediaA
Скачивает фото и файлы (до 50 МБ, без видео и аудио) с указанными id в папку чата в архиве и возвращает пути к ним.
Inputs: ids (required), chat (required). Returns: result
list_dialogsA
Чаты пользователя: id, тип, непрочитанные, название. Без query — 50 последних чатов; с query — поиск по названию или имени среди всех чатов.
Inputs: query. Returns: result
ocr_photosA
Распознаёт текст на фото (Apple Vision) и вписывает его в архив. Без ids — все необработанные фото чата.
Inputs: chat (required), ids. Returns: result
read_filesA
Читает текст файлов txt, md, csv, html, pdf, doc, docx, rtf, xlsx, pptx и картинок локально, без скачивания на диск (сканы PDF распознаются), и сохраняет его в text/.txt в папке чата. Без ids — все непрочитанные файлы чата.
Inputs: chat (required), ids. Returns: result
send_messageB
Отправляет сообщение от имени пользователя. Только после того, как пользователь увидел текст.
Inputs: chat (required), text (required), reply_to. Returns: result
sync_chatA
Догружает новые сообщения чата в локальный архив. chat — id, @username или часть названия. days — сколько последних дней истории должно быть в архиве; недостающие старые сообщения догружаются. Без days новый чат выгружается целиком, а у загруженного догружаются только новые сообщения.
Inputs: chat (required), days. Returns: result
transcribeC
Расшифровывает голосовые и кружки с указанными id и вписывает текст в архив.
Inputs: ids (required), chat (required). Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 9 tools
Most tools target distinct resource/action pairs: listing dialogs, syncing chat history, sending messages, processing voice/photo/file media, and downloading files. The main overlap is between fetch_media and fetch_large_file, but the size threshold and consent requirement make the boundary fairly clear. transcribe, ocr_photos, describe_media, and read_files all write text into the archive, but their input types differ enough to avoid serious misselection.
The tools use snake_case and mostly follow an imperative verb_noun pattern such as list_dialogs, sync_chat, send_message, read_files, fetch_media, and fetch_large_file. Minor deviations exist: transcribe lacks an object noun, and ocr_photos uses an acronym plus noun. These are still readable and action-oriented, so consistency is slightly imperfect but not confusing.
Nine tools is a well-scoped set for a Telegram archive and media-processing assistant. Each tool covers a distinct capability area: dialogs, syncing, voice transcription, OCR, media description, sending, local file reading, and two download paths. The count is neither thin nor bloated.
The surface covers chat listing, syncing, media processing, local file reading, sending messages, and downloads. However, there are notable gaps for a Telegram client/archive: no explicit tool to list, search, or read archived messages, and no reply/forward/edit/delete operations. Agents can work around some gaps via sync_chat and local files, but the missing message retrieval surface is significant.
Maintenance
Related MCP Connectors
Your personal Telegram account for AI: read, search and sum up chats. QR login, no API key.
Your Telegram, WhatsApp, Instagram, mail and calendar in Claude or ChatGPT. Never sends messages.
iMessage for AI agents, from your iPhone. No Mac needed, and you choose which chats they read.
Let AI assistants post to your Telegram chats, groups and channels. Not affiliated with Telegram.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to interact with a user's Telegram account: list chats, read history, search, and send messages through Telegram's MTProto API.2MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to search and act on Telegram conversations, groups, channels, files, and links, with semantic search, AI-powered knowledge extraction, human-in-the-loop approvals, and PostgreSQL/pgvector persistence.Apache 2.0
- AlicenseNot gradedqualityDmaintenanceLets any MCP-compatible AI agent read, search, and send Telegram messages through your real account via MTProto.1MIT
- 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