tg-agent
Read-only access to a Telegram account over MCP: list and search joined channels, groups and chats, browse message history, resolve usernames/links and inspect invite links without joining, list and filter files, download files over parallel resumable MTProto connections (completing split archives), export messages/files, build and query a local offline index of chats, compare chats, search archives full-text, extract downloaded archives, and create watches that auto-download new matching files.
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-agentfind the latest videos in @telegram and download the two smallest"
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 Agent
Let your AI agent read Telegram and download files — and watch it work.
TG Agent is a local service that gives AI tools such as Claude Code, Codex, Cursor and ZCode read-only access to your Telegram account over MCP: public channels, private channels you have joined, groups and chats. It can list and search messages and files, keep an offline index of everything it has seen, and download files fast over parallel connections.
Everything the AI does shows up live in a web console as a workflow: one card per request, one node per tool call, arrows showing which step used which result, and progress bars for every download.
🔍 Read — history, search, file listings with filters (kind, name, extension, size, date), invite-link inspection
🗂 Local index — search and compare channels offline, no Telegram requests
⚡ Fast downloads — several MTProto connections per file, resumable; concurrency adapts to Telegram's rate limits by itself
🗜 Split archives —
x.7z.001…,x.part1.rar… are recognised; asking for one volume fetches the whole set and missing volumes are flagged♻ No duplicates — a file already downloaded from another chat is skipped
⏱ Speed limit and download hours, desktop notifications, a tray icon (Windows) and an update check
👁 Watches — automatically download new matching files from a channel
🧭 Workflows — every AI request grouped and drawn as a step graph you can inspect
🛡 Safe by default — never sends messages or joins chats; large AI downloads and AI-created watches wait for your approval; local access token
👥 Multiple accounts, per-account proxies, QR-code or code + 2FA login
🤝 Two-channel work — pair a channel of descriptions with the channel that hosts the files; passwords and versions are pulled out of captions and nearby posts
🙋 Asks instead of guessing — the AI can ask you a question in the console and waits for your answer
📚 Recipes — any workflow can be saved and re-run, scheduled, or used as a slash command in Claude Code
📈 Dashboard — throughput, daily downloads, library make-up, per-AI usage, tool timings, Telegram request budget
🗜 Extraction with 7-Zip (password from the post, split sets from their first volume)
🌗 Calm warm-graphite light and dark themes, English / 中文
Quick start
You need Python 3.10+ and your own Telegram API credentials (api_id / api_hash from my.telegram.org → API development tools).
Windows — download or clone this repository and double-click start.bat.
macOS / Linux — run ./start.sh.
Or with pip / pipx:
pipx install git+https://github.com/Creatfire/TelegramDownloadAgent
tg-agentA pre-built Windows tg-agent.exe is attached to each release.
The first start creates a virtual environment, installs dependencies and opens the console. Then:
Accounts → Add account → enter
api_id,api_hash(phone is optional) → log in with a QR code (scan in Telegram: Settings → Devices → Link Desktop Device) or a login code + 2FA password.Connect AI → copy the configuration for your tool (see below).
Ask your AI: “Use tg-agent to see which videos @telegram posted recently and download the two smallest.”
Closing the TG Agent window stops the service. Logins are kept and unfinished downloads resume on the next start.
Related MCP server: Telegram MCP
Connecting AI tools
Both transports need the service to be running. The console's Connect AI page generates these snippets with your real paths and token.
Claude Code (HTTP, recommended)
claude mcp add --transport http --scope user tg-agent http://127.0.0.1:17865/mcp --header "Authorization: Bearer <TOKEN>"Codex — ~/.codex/config.toml (stdio bridge; it reads the token automatically)
[mcp_servers.tg-agent]
command = "/path/to/tg-agent/.venv/bin/python" # Windows: ...\\.venv\\Scripts\\python.exe
args = ["/path/to/tg-agent/mcp_stdio.py"]
startup_timeout_sec = 20
tool_timeout_sec = 600If you installed with pip, use command = "tg-agent-mcp" and no args. With the exe: command = "C:\\...\\tg-agent.exe", args = ["mcp"].
Cursor / ZCode / any mcpServers JSON config — same command/args as above, or for clients with Streamable HTTP:
{ "url": "http://127.0.0.1:17865/mcp", "headers": { "Authorization": "Bearer <TOKEN>" } }Get the token with tg-agent token (or from the Connect AI page).
Tools
Tool | What it does |
| Open / close a workflow for the current user request (the AI is instructed to always do this) |
| Accounts and login status |
| Joined channels, groups, chats (including private channels) |
| Resolve @username, t.me link, private |
| History with paging, date/id range, keyword, media only |
| Search one chat or all joined chats |
| One message in full, albums included |
| File metadata with filters, counts and total size (also feeds the local index) |
| Background export of all files or messages to csv / json / jsonl / md |
| Dry run: file count, total size, split-archive sets and missing volumes, already-downloaded files, approval needed, estimated time |
| Queue downloads by links, by message ids, or by filter (completes split archives by default) |
| Wait for tasks to finish with progress notifications — no polling loops |
| Progress, speed, ETA, why a task is waiting; pause / resume / retry / cancel |
| Index a whole chat (incrementally) into the local SQLite index |
| Search the local index across chats — no Telegram requests |
| What two chats have in common / only one has (by name, name+size, stem or identical file) |
| Manage watches (AI-created ones need approval) |
| Full-text search over every message the service has read or indexed — offline |
| A file's caption, neighbouring posts and album, with extracted passwords, versions, links; optionally the matching post in an intro chat |
| Pair description posts in one chat with (indexed) files in another, split archives grouped |
| Ask the user a question in the console and wait for the answer |
| Shared notes about a chat that every AI can read (naming patterns, where passwords are posted…) |
| Reusable workflows |
| Test or extract downloaded archives with 7-Zip |
Listing tools accept format="compact" (lists as column/row tables) and fields=[...] to save the AI's context.
The workflow view
Left: workflows grouped by state and day; each shows the AI client, number of steps and time.
Middle: the steps of the selected workflow, drawn as swim lanes — one column per chat. When an AI reads an intro channel and works in a download channel at the same time, the steps sit side by side; a step that relates both chats (e.g. matching) spans both lanes, and dashed orange links show data flowing between chats. Each step reads as a plain sentence (“Read 30 messages”, “Match intro posts to files”); tool names and arguments live in the details panel. A short summary at the top says what the AI did in which chat.
States use one orange at different strengths: pale dashed = waiting (for you or for tasks), vivid = running, muted = done; red = error. Download steps list their files with live progress; questions from the AI can be answered right inside the step. Repeated progress polling doesn't add nodes.
Right: click a node to see its full arguments and result.
Follow the latest activity jumps to whatever the AI is doing now. The Log tab shows the raw event stream.
Save as recipe turns the workflow into a reusable template (chats become parameters); Export report saves it as Markdown; Re-run replays it (downloads still follow the approval rules).
If an AI doesn't call tg_start_workflow, its calls are still recorded, in an untitled workflow per session.
Download speed
Each file is fetched over several MTProto connections in parallel (like tdl), written into a pre-allocated .part file, and finished parts are recorded so downloads survive pauses, restarts and dropped connections.
Telegram limits how many file requests an account may make. Settings give the maximum concurrency (default 2 files × 4 connections); TG Agent halves its in-flight requests whenever Telegram answers with FloodWait, pauses until the wait is over, and slowly adds capacity back while things are quiet. Tasks show why they are waiting (rate-limited 37 s, reconnecting, waiting for download hours), and a download that makes no progress for 3 minutes gets fresh connections automatically.
You can cap total speed (KB/s) and restrict downloads to certain hours (e.g. 23:00–07:00) in Settings.
Your proxy is usually the bottleneck. If it caps throughput, more connections won't help — try a TUN-mode proxy with Direct in TG Agent, or a faster proxy.
Safety and privacy
Read-only: TG Agent never sends messages, reacts, or joins chats.
The service listens on
127.0.0.1only, rejects foreignHostheaders (DNS rebinding) and requires an access token on every API and MCP request. Cookie-authenticated writes also need a custom header (CSRF).AI-initiated downloads above your limits (default 2 GB or 50 files) and AI-created watches wait for approval in the console.
api_hashis encrypted at rest (Windows DPAPI, or the system keychain on macOS/Linux). 2FA passwords are never stored.data/sessions/*.sessionis your login — never share it. Removing an account can also log the session out on Telegram.
Using your account through any third-party client is subject to Telegram's Terms of Service and API terms. Heavy automated use can get an account rate-limited or restricted; you are responsible for how you use this tool.
Data locations
Running from a checkout (start.bat / start.sh), everything lives next to the code; installed packages use ~/.tg-agent. Override with TGA_DATA_DIR. The port (default 17865) can be changed with TGA_PORT.
Path | Contents |
| Accounts (encrypted |
| Telegram sessions |
| Workflows, local file index, watches |
| Access token |
| Exports |
| Default download folder |
Development
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
.venv/bin/python -m pytest # offline unit tests
.venv/bin/python -m tgagent # run the service
.venv/bin/python tests/mcp_check.py # MCP connectivity check (service must be running)
.venv/bin/python tests/workflow_demo.py # simulated agent session for the workflow viewtgagent/
cli.py entry point (tg-agent, tg-agent token, tg-agent mcp)
server.py FastAPI: REST, SSE, auth, console, embedded MCP (/mcp)
mcp_server.py MCP server definition; mcp_stdio.py stdio bridge
tools.py tool registry shared by MCP and the console
workflow.py sessions / workflows / steps and data-flow inference
readers.py read-only Telegram queries
tasks.py download queue, approvals, exports, index scans
fastdl.py parallel chunked downloader
index.py local SQLite file index; watch.py watches
accounts.py accounts, code / 2FA / QR login; secure.py secret storage
web/ console (plain HTML/CSS/JS, no build step)Manual test checklist for testers (human or AI): docs/TESTING.md.
Credits
Built on Telethon. Download approach inspired by tdl; watch/filter ideas from telegram_media_downloader.
License
This server cannot be deployed
Maintenance
Related MCP Connectors
Search your AI chat history (ChatGPT, Claude, Codex) from any MCP client. Remote, private, read-only
Telegram bridge for your MCP-compatible agent. Bidirectional, no LLM in our stack.
Remote streamable-HTTP MCP server running on a single Cloudflare Worker. Your assistant gets live Airbnb, Amazon, Booking.com, Google Flights, Maps and Reddit data, social search on X, Instagram and TikTok, the Meta Ad Library, and image/video generation without any keys. Connect your own accounts to let it send WhatsApp or Telegram messages, work an IMAP inbox, manage Meta Ads campaigns and publish to X and LinkedIn. OAuth 2.1 with PKCE; stored credentials are AES-256-GCM encrypted.
Read-only MCP server: let AI agents read your ORANO saved-video library, tasks, and memory.
Related MCP Servers
- AlicenseAqualityDmaintenanceRead-only Telegram access for Claude and other MCP hosts. Provides tools to list chats, read recent messages, and download media from your own Telegram account without needing an api_id/api_hash.5MIT
- AlicenseBqualityBmaintenanceProvides read-only access to Telegram chats, allowing AI agents to list chats, read messages, and search within chats via local MCP.14MIT
- AlicenseNot gradedqualityCmaintenanceEnables AI agents to search and analyze a Telegram account as a read-only knowledge source, allowing chat discovery, message search, history reading, contact inspection, and media download without exposing any mutating Telegram tools.13Apache 2.0
- AlicenseAqualityCmaintenanceEnables local, privacy-first control of a personal Telegram account through MCP, using TDLib to read chats, send and reply to messages, search, transfer files, and interact with approved inline buttons.20MIT