Telegram MCP Server

repository·main·Indexed 23 days ago

https://github.com/chigwell/telegram-mcp

A Model Context Protocol (MCP) implementation that enables AI clients like Claude and Cursor to interact with Telegram accounts. Built using the Telethon library, it provides tools for managing chats, messages, contacts, media, and account settings. It supports multi-account setups, session pooling for concurrent clients, various transport protocols (stdio, http, sse), and proxy support (SOCKS, HTTP, MTProxy).

Tokens
6.8K
Snippets
13
Records
36
Agent score
72%

What's inside telegram-mcp

  1. Use a Session Pool for Concurrent Clients

    main

    If you need to run multiple MCP clients against the same Telegram account simultaneously (e.g., a desktop app and a terminal CLI), you must provide multiple authorized session strings. Telegram forbids using a single auth key from two different IPs/connections at once.

    To solve this, provide a list of interchangeable session strings in the TELEGRAM_SESSION_STRINGS variable. The server uses an advisory file lock to ensure each process claims a unique session from the pool.

    Configuration

    TELEGRAM_SESSION_STRINGS=<session A> <session B> <session C>

    This pool takes precedence over the single TELEGRAM_SESSION_STRING variable for the default account.

  2. Configure Multi-Account Setup

    main

    You can manage multiple Telegram accounts by using suffixed session variables. Labels are derived from the suffix (lowercased) and used as the account parameter in tool calls.

    Environment Variables

    TELEGRAM_API_ID=your_api_id_here
    TELEGRAM_API_HASH=your_api_hash_here
    TELEGRAM_SESSION_STRING_WORK=session_string_for_work
    TELEGRAM_SESSION_STRING_PERSONAL=session_string_for_personal

    Behavior

    • Single-account mode: The account parameter is optional.
    • Multi-account mode: Write tools require an account parameter.
    • Read-only tools: If the account parameter is omitted, read-only tools will fan out and return results from all configured accounts.

    Example Prompts

    • "List my accounts"
    • "Show unread messages from all accounts"
    • "Send this from my work account to @example"
  3. Configure file-path security and allowed roots

    main

    File-path tools (e.g., send_file, download_media, upload_file) are disabled by default for security. You must explicitly configure allowed roots.

    Roots can be provided via:

    1. Server CLI arguments (fallback).
    2. MCP client Roots (takes precedence).

    Security Rules:

    • Paths must resolve to a real path inside an allowed root.
    • Traversal, wildcard, shell-like, and null-byte patterns are rejected.
    • Downloads default to <first_root>/downloads/.
    • If a client provides an empty list of roots, it acts as a deny-all. To force fallback to CLI roots in this case, set TELEGRAM_ALLOW_SERVER_ROOTS_FALLBACK=1.

    Usage Examples

    Via CLI:

    uv run main.py /data/telegram /tmp/telegram-mcp

    Via MCP Client Configuration (JSON):

    {
      "mcpServers": {
        "telegram-mcp": {
          "command": "uv",
          "args": [
            "--directory",
            "/full/path/to/telegram-mcp",
            "run",
            "main.py",
            "/data/telegram",
            "/tmp/telegram-mcp"
          ],
          "env": {
            "TELEGRAM_API_ID": "your_api_id_here",
            "TELEGRAM_API_HASH": "your_api_hash_here",
            "TELEGRAM_SESSION_STRING": "your_session_string_here"
          }
        }
      }
    }
  4. Generate a Telegram Session String

    main

    A session string is required to authenticate the server with your Telegram account. You can generate one using the provided script.

    Methods

    • Interactive: Run the script and follow the prompts.
    • QR Login (Recommended): Best if you already have Telegram open on another device.
    • Phone Login: Use your phone number and the verification code sent by Telegram.

    Commands

    # Interactive method
    uv run session_string_generator.py
    
    # QR login
    uv run session_string_generator.py --qr
    
    # Phone number + verification code login
    uv run session_string_generator.py --phone
    uv run session_string_generator.py --qr
  5. Deploy with Docker

    main

    Build the image

    docker build -t telegram-mcp:latest .

    Run a single long-lived container using HTTP transport. This is preferred for multiple clients to avoid Telegram throttling.

    docker run -d --name telegram-mcp --restart unless-stopped \
      --env-file .env \
      -e MCP_TRANSPORT=http \
      -e MCP_HOST=0.0.0.0 \
      -p 127.0.0.1:8765:8765 \
      telegram-mcp:latest

    Note: MCP_HOST=0.0.0.0 binds inside the container, while -p 127.0.0.1:8765:8765 ensures the unauthenticated endpoint is only reachable from your local machine.

    One container per client (stdio)

    Use this if a client (like Cursor) spawns the container directly via stdio:

    {
      "mcpServers": {
        "telegram-mcp": {
          "command": "docker",
          "args": ["run", "-i", "--rm", "--env-file", "/full/path/to/.env", "telegram-mcp:latest"]
        }
      }
    }
  6. Install and set up Telegram MCP Server

    main

    To install the Telegram MCP server, clone the repository and use uv to sync dependencies.

    Warning: Do not use pip install telegram-mcp or uvx telegram-mcp, as the name telegram-mcp on PyPI is owned by a different project and could expose your credentials to malicious code.

    Installation Steps

    1. Clone the repository:
      git clone https://github.com/chigwell/telegram-mcp.git
      cd telegram-mcp
    2. Sync dependencies using uv:
      uv sync
    git clone https://github.com/chigwell/telegram-mcp.git
    cd telegram-mcp
    uv sync
  7. Configure MCP Client (Claude Desktop or Cursor)

    main

    To use the server with Claude Desktop or Cursor, add a configuration entry pointing to your local clone of the repository.

    Configuration via Local Clone

    {
      "mcpServers": {
        "telegram-mcp": {
          "command": "uv",
          "args": [
            "--directory",
            "/full/path/to/telegram-mcp",
            "run",
            "main.py"
          ],
          "env": {
            "TELEGRAM_API_ID": "your_api_id_here",
            "TELEGRAM_API_HASH": "your_api_hash_here",
            "TELEGRAM_SESSION_STRING": "your_session_string_here"
          }
        }
      }
    }

    Configuration via Installed Package

    If you installed the repository directly via pip install "git+..." into a virtual environment:

    {
      "mcpServers": {
        "telegram-mcp": {
          "command": "/full/path/to/.venv/bin/telegram-mcp",
          "env": {
            "TELEGRAM_API_ID": "your_api_id_here",
            "TELEGRAM_API_HASH": "your_api_hash_here",
            "TELEGRAM_SESSION_STRING": "your_session_string_here"
          }
        }
      }
    }
  8. How file path resolution and security works

    main

    The runtime implements a strict security model for file-path tools to prevent path traversal and unauthorized access.

    1. Root Validation

    All file operations must occur within 'allowed roots'. These roots are determined by:

    1. The MCP client's list_roots capability (preferred).
    2. Recovered absolute paths from client validation errors (e.g., when clients send bare paths instead of file:// URIs).
    3. Server-side CLI arguments (if fallback is enabled).

    2. Path Resolution Logic

    • Absolute Paths: Checked directly against allowed roots.
    • Relative Paths: Resolved relative to the first available resolution root.
    • Security Checks:
      • Path traversal (..) is strictly forbidden.
      • Wildcard/shell patterns are disallowed.
      • The resolved path must be within an allowed root.

    3. Tool-Specific Constraints

    Tools may enforce additional constraints:

    • Extension Allowlists: Only specific file extensions (e.g., .txt, .md) may be allowed for certain tools.
    • Size Limits: Files exceeding MAX_FILE_BYTES for a specific tool will be rejected.
    • Permissions: Files must be readable (for read tools) or the parent directory must be writable (for write tools).
  9. Configure proxy support for Telegram traffic

    main

    Route Telegram traffic through a proxy using TELEGRAM_PROXY_* environment variables. Supported types are socks5, socks4, http, and mtproxy.

    Note: SOCKS and HTTP proxies require the python-socks package. Install it via:

    uv sync --extra proxy
    # or
    pip install python-socks

    SOCKS/HTTP Configuration

    TELEGRAM_PROXY_TYPE=socks5
    TELEGRAM_PROXY_HOST=127.0.0.1
    TELEGRAM_PROXY_PORT=1080
    TELEGRAM_PROXY_USERNAME=optional_user
    TELEGRAM_PROXY_PASSWORD=optional_pass
    TELEGRAM_PROXY_RDNS=true

    MTProxy Configuration

    TELEGRAM_PROXY_TYPE=mtproxy
    TELEGRAM_PROXY_HOST=mtproxy.example
    TELEGRAM_PROXY_PORT=443
    TELEGRAM_PROXY_SECRET=ee0123456789abcdef...

    Per-account Overrides

    Use the _<LABEL> suffix to override global proxy settings for specific accounts (e.g., TELEGRAM_PROXY_TYPE_WORK).

    TELEGRAM_PROXY_TYPE=socks5
    TELEGRAM_PROXY_HOST=127.0.0.1
    TELEGRAM_PROXY_PORT=1080
    
    TELEGRAM_PROXY_TYPE_WORK=http
    TELEGRAM_PROXY_HOST_WORK=proxy.work.example
    TELEGRAM_PROXY_PORT_WORK=3128
  10. Configure device identity for Telegram

    main

    You can control how the client appears in Telegram's Settings > Devices list by setting these environment variables. Setting them ensures a stable, recognizable name across reconnections, as Telethon re-sends these values on every connection.

    TELEGRAM_DEVICE_MODEL=Telegram MCP
    TELEGRAM_SYSTEM_VERSION=1.0
    TELEGRAM_APP_VERSION=1.0
  11. Configure Telegram MCP Environment Variables

    main

    The server requires several environment variables for authentication and tool access control. Copy .env.example to .env to get started.

    Authentication (Single Account)

    • TELEGRAM_API_ID: Your Telegram API ID from my.telegram.org/apps.
    • TELEGRAM_API_HASH: Your Telegram API Hash.
    • TELEGRAM_SESSION_STRING: The session string generated via the session_string_generator.py script.

    Tool Access Control

    You can restrict the tools exposed to the MCP client using TELEGRAM_EXPOSED_TOOLS:

    • all (default): All tools are exposed.
    • read-only: Only tools with readOnlyHint=True are exposed.
    • read-only+<tool1>,<tool2>: Read-only tools plus specific write tools (e.g., read-only+send_message,reply_to_message).

    Note: An unknown tool name in the allowlist will cause the server to abort startup.

    TELEGRAM_API_ID=your_api_id_here
    TELEGRAM_API_HASH=your_api_hash_here
    TELEGRAM_SESSION_STRING=your_session_string_here
    TELEGRAM_EXPOSED_TOOLS=read-only+send_message,reply_to_message