tg-mcp
MCP server that exposes a Telegram user account over HTTP, enabling message sending, dialog listing, history retrieval, and message search via tools like send_message and list_dialogs.
README
tg-mcp
An MCP server that exposes a Telegram user account (not a bot) over a streamable HTTP endpoint, built with FastMCP and Telethon.
It's multi-account: anyone can register a login on the server and link their own Telegram account to it. Each account maps to exactly one linked Telegram account, and tools always act on the caller's own linked account — never someone else's.
Tools
| Tool | Description |
|---|---|
get_me |
Info about the logged-in account |
list_dialogs |
Recent dialogs (chats, groups, channels) with ids for the other tools |
get_chat_history |
Recent messages from a chat, newest first |
send_message |
Send a text message (optionally as a reply) |
search_messages |
Search messages in one chat or across the whole account |
chat arguments accept a numeric id, an @username, a phone number, or "me" (Saved Messages).
Authentication
The MCP endpoint is protected by a self-hosted OAuth 2.1 authorization server (no third-party IdP). When an MCP client connects, it's redirected through a browser flow:
- Sign in or register with a username and password.
- Link Telegram (first time only): enter your phone number, the code Telegram sends you, and your two-factor password if you have one set. This is the same handshake the official Telegram apps use — nothing is stored until it succeeds.
- The client gets back an access/refresh token pair (JWT, 1h/30d) scoped to your account.
Registration is open: anyone who can reach the /login page can create an account, but every account is only ever able to act on the Telegram account they personally linked to it. If you don't want that, put the server behind something that gates access first (reverse proxy auth, a gateway like ContextForge, network-level restriction, etc.) — this server doesn't do invite codes itself.
Linked Telegram sessions are stored encrypted at rest (Fernet, key from MCP_SESSION_ENCRYPTION_KEY). A leaked database dump is not enough to hijack an account; a leaked database dump plus the encryption key is.
Requirements
- Python 3.12+ and uv
- Telegram api_id / api_hash from https://my.telegram.org/apps
- PostgreSQL (accounts, OAuth clients, revoked tokens)
Setup
uv sync
cp .env.example .env
Fill in .env:
TELEGRAM_API_ID/TELEGRAM_API_HASH— from my.telegram.orgMCP_BASE_URL— how clients actually reach this server (used as the OAuth issuer)MCP_DB_URL— Postgres connection stringMCP_OAUTH_JWT_SECRET—python -c "import secrets; print(secrets.token_urlsafe(32))"MCP_SESSION_ENCRYPTION_KEY—python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
Tables are created automatically on startup (no migration step).
Running
Local (requires a reachable Postgres, see MCP_DB_URL):
python -m tg_mcp
# -> http://127.0.0.1:8000/mcp
Docker Compose (bundles Postgres):
docker compose up --build
The image binds to 0.0.0.0:8000 inside the container; credentials are read from .env.
Configuration
All settings come from the environment (or .env).
| Variable | Default | Description |
|---|---|---|
TELEGRAM_API_ID |
— | API id from my.telegram.org |
TELEGRAM_API_HASH |
— | API hash from my.telegram.org |
MCP_HOST |
127.0.0.1 |
HTTP bind host |
MCP_PORT |
8000 |
HTTP port |
MCP_PATH |
/mcp |
HTTP endpoint path |
MCP_BASE_URL |
http://127.0.0.1:8000 |
Externally reachable base URL (OAuth issuer/audience, login links) |
MCP_DB_URL |
postgresql+asyncpg://tgmcp:tgmcp@localhost/tgmcp |
Async SQLAlchemy URL for Postgres |
MCP_DB_ECHO |
false |
Log SQL statements |
MCP_OAUTH_JWT_SECRET |
(insecure default) | Signs OAuth access/refresh tokens — change this |
MCP_SESSION_ENCRYPTION_KEY |
— | Fernet key encrypting stored Telegram sessions |
Connecting an MCP client
A ready-to-use config is in .mcp.json:
{
"mcpServers": {
"tg-mcp": {
"type": "http",
"url": "http://127.0.0.1:8000/mcp"
}
}
}
Clients that support the MCP OAuth flow will open a browser to /login automatically on first connection.
Project layout
tg_mcp/
├── server.py # FastMCP app, lifespan, mounts the tool sub-servers
├── oauth.py # OAuth 2.1 authorization server: login/register + Telegram linking
├── telegram_login.py # phone/code/2FA handshake used by the linking flow
├── client.py # per-account Telethon client cache + FastMCP dependency
├── auth.py # password hashing, session encryption, caller resolution
├── config.py # pydantic-settings (TELEGRAM_* and MCP_*)
├── db.py # async engine/session, schema creation
├── models.py # Pydantic result models returned by tools
├── orm/ # SQLAlchemy models: User, OAuthClient, RevokedToken
├── dao/ # data-access objects
├── utils/ # OAuth protocol helpers
└── tools/ # one FastMCP sub-server per tool
├── get_me.py
├── list_dialogs.py
├── get_chat_history.py
├── send_message.py
└── search_messages.py
The connected Telethon client for the calling account is provided to tools through a FastMCP dependency (TelegramClientDep), so each tool just declares client: TelegramClient = TelegramClientDep.
Development
ruff check .
ruff format --check .
CI (GitHub Actions) runs ruff and, on main/tags, builds and pushes a multi-arch image to GHCR.
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。