TGMCP is a Python package that implements the Model Context Protocol (MCP) for Telegram. It allows AI agents to seamlessly interact with Telegram accounts, providing access to messaging, contacts, groups, media sharing, and more.
This package acts as a bridge between AI assistants and Telegram, enabling them to:
- Read and send messages
- Manage contacts and groups
- Handle media (images, documents, stickers, GIFs)
- Perform administrative functions
- Update profile information
All data is handled locally and securely through the Telegram API.
- Chat Operations: List chats, retrieve messages, send messages
- Contact Management: Add, delete, block/unblock, search contacts
- Group Administration: Create groups, add members, manage permissions
- Media Handling: Send/receive files, stickers, GIFs, voice messages
- Profile Management: Update profile info, privacy settings
- Message Operations: Forward, edit, delete, pin messages
- Administrative Functions: Promote/demote admins, ban users
pip install tgmcp
# Clone the repository
git clone https://github.com/OEvortex/tgmcp.git
cd tgmcp
# Install with pip
pip install -e .
Create a .env
file in your project directory with your Telegram API credentials:
TELEGRAM_API_ID=your_api_id
TELEGRAM_API_HASH=your_api_hash
TELEGRAM_SESSION_NAME=your_session_name
# Optional: Use string session instead of file session
# TELEGRAM_SESSION_STRING=your_session_string
# Optional: Tool Configuration
# Control which tool sets are enabled (default is true for all)
# TGMCP_ENABLE_CHAT_TOOLS=true
# TGMCP_ENABLE_CONTACT_TOOLS=true
# TGMCP_ENABLE_MESSAGE_TOOLS=true
# TGMCP_ENABLE_GROUP_TOOLS=true
# TGMCP_ENABLE_MEDIA_TOOLS=true
# TGMCP_ENABLE_PROFILE_TOOLS=true
# TGMCP_ENABLE_ADMIN_TOOLS=true
To use TGMCP with VS Code or other MCP-compatible applications, add it to your MCP configuration:
{
"mcp": {
"servers": {
"mcp-telegram": {
"command": "tgmcp",
"args": ["start"],
"env": {
"TELEGRAM_API_ID": "your_api_id",
"TELEGRAM_API_HASH": "your_api_hash",
"TELEGRAM_SESSION_STRING": "your_session_string",
"MCP_NONINTERACTIVE": "true",
"TGMCP_ENABLE_CHAT_TOOLS": "true",
"TGMCP_ENABLE_CONTACT_TOOLS": "true",
"TGMCP_ENABLE_MESSAGE_TOOLS": "true",
"TGMCP_ENABLE_GROUP_TOOLS": "true",
"TGMCP_ENABLE_MEDIA_TOOLS": "true",
"TGMCP_ENABLE_PROFILE_TOOLS": "true",
"TGMCP_ENABLE_ADMIN_TOOLS": "true"
}
}
}
}
}
IMPORTANT:
- Replace
your_api_id
,your_api_hash
, andyour_session_string
with your actual Telegram API credentials. - For most reliable operation, use the session string method (Option 1).
- The
MCP_NONINTERACTIVE
setting prevents interactive prompts during startup.
{
"mcp": {
"servers": {
"mcp-telegram": {
"command": "tgmcp",
"args": ["start"],
"env": {
"TELEGRAM_API_ID": "your_api_id",
"TELEGRAM_API_HASH": "your_api_hash",
"TELEGRAM_SESSION_NAME": "your_session_name",
"MCP_NONINTERACTIVE": "true",
"TGMCP_ENABLE_CHAT_TOOLS": "true",
"TGMCP_ENABLE_CONTACT_TOOLS": "true",
"TGMCP_ENABLE_MESSAGE_TOOLS": "true",
"TGMCP_ENABLE_GROUP_TOOLS": "true",
"TGMCP_ENABLE_MEDIA_TOOLS": "true",
"TGMCP_ENABLE_PROFILE_TOOLS": "true",
"TGMCP_ENABLE_ADMIN_TOOLS": "true"
}
}
}
}
}
TGMCP allows you to selectively enable or disable specific tool sets using environment variables. This can be useful for:
- Reducing the number of available tools for security or simplicity
- Limiting functionality for specific use cases
- Improving performance by loading only necessary components
You can configure which tool sets are enabled by setting the following environment variables:
Environment Variable | Description | Default |
---|---|---|
TGMCP_ENABLE_CHAT_TOOLS |
Enable/disable chat-related tools | true |
TGMCP_ENABLE_CONTACT_TOOLS |
Enable/disable contact management tools | true |
TGMCP_ENABLE_MESSAGE_TOOLS |
Enable/disable message operation tools | true |
TGMCP_ENABLE_GROUP_TOOLS |
Enable/disable group administration tools | true |
TGMCP_ENABLE_MEDIA_TOOLS |
Enable/disable media handling tools | true |
TGMCP_ENABLE_PROFILE_TOOLS |
Enable/disable profile management tools | true |
TGMCP_ENABLE_ADMIN_TOOLS |
Enable/disable administrative function tools | true |
Set these variables to true
or false
to enable or disable the corresponding tool set. For example:
# Disable admin and group tools, enable everything else
TGMCP_ENABLE_ADMIN_TOOLS=false
TGMCP_ENABLE_GROUP_TOOLS=false
Before using TGMCP, you need to authenticate with Telegram. You can do this in two ways:
# Run the session string generator
python -m tgmcp.session_string_generator
This will generate a session string that you can use in your MCP configuration. This method is more reliable and portable, especially for cloud environments.
# Run the authentication script
python -m tgmcp.authenticate
This will create a .session
file that TGMCP will use for authentication.
python -m tgmcp
import asyncio
import os
from tgmcp import client, get_tool_config
async def main():
# Optional: Configure which tools to enable
# These should be set before importing any tools
os.environ["TGMCP_ENABLE_ADMIN_TOOLS"] = "false" # Disable admin tools
# Connect to Telegram
await client.start()
# Get user info
me = await client.get_me()
print(f"Logged in as: {me.first_name} {getattr(me, 'last_name', '')}")
# Send a message
await client.send_message('username', 'Hello from TGMCP!')
# Check which tool sets are enabled
tool_config = get_tool_config()
print("Enabled tool sets:", [k for k, v in tool_config.items() if v])
# Disconnect when done
await client.disconnect()
asyncio.run(main())
TGMCP provides a comprehensive set of tools that can be utilized through the MCP protocol:
get_chats
- List available chats with paginationlist_chats
- Detailed metadata for users, groups, and channelsget_chat
- Information about a specific chatget_direct_chat_by_contact
- Find a direct chat with a specific contactsend_message
- Send text messages to any chatarchive_chat
- Archive a chatunarchive_chat
- Unarchive a chatmute_chat
- Mute notifications for a chatunmute_chat
- Unmute notifications for a chatget_invite_link
- Get the invite link for a group or channelexport_chat_invite
- Export a chat invite linkjoin_chat_by_link
- Join a chat by invite linkimport_chat_invite
- Import a chat invite by hash
get_messages
- Get paginated messages from a specific chatlist_messages
- List messages with detailed informationget_message_context
- Get context around a specific messageforward_message
- Forward a message to another chatedit_message
- Edit a previously sent messagedelete_message
- Delete messagespin_message
- Pin a message in a chatunpin_message
- Unpin a message from a chatmark_as_read
- Mark messages as readreply_to_message
- Reply to a specific messagesearch_messages
- Search for messages in a chatget_pinned_messages
- Get all pinned messages in a chatget_history
- Get chat history with customizable filters
list_contacts
- View all contacts in your Telegram accountsearch_contacts
- Find contacts by name, username, or phoneget_contact_ids
- Get contact IDs for specific contactsget_contact_chats
- Get chats with specific contactsget_last_interaction
- Get last interaction with a contactadd_contact
- Add new contacts to your Telegram accountdelete_contact
- Delete contacts from your accountblock_user
- Block users from contacting youunblock_user
- Unblock previously blocked usersimport_contacts
- Import multiple contacts at onceexport_contacts
- Export all contacts to a structured formatget_blocked_users
- Get a list of blocked usersresolve_username
- Resolve a username to a Telegram entitysearch_public_chats
- Search for public chats
create_group
- Create new groups and add memberscreate_channel
- Create a new broadcast channelinvite_to_group
- Invite users to existing groupsleave_chat
- Leave a group or channelget_participants
- List members of a group or channeledit_chat_title
- Change the title of a group or channeledit_chat_photo
- Change the photo of a group or channeldelete_chat_photo
- Remove the photo from a group or channelpromote_admin
- Give administrator privileges to usersdemote_admin
- Revoke administrator privilegesban_user
- Ban users from a group or channelunban_user
- Unban previously banned usersget_admins
- List administrators of a group or channelget_banned_users
- List banned usersget_recent_actions
- Get recent administrative actions
send_file
- Send documents, photos, or videosdownload_media
- Save media from messages to your deviceget_media_info
- Get information about media in messagessend_voice
- Send voice messagessend_sticker
- Send stickers to chatsget_sticker_sets
- Get available sticker setsget_gif_search
- Search for GIFssend_gif
- Send GIFs to chats
get_me
- Get information about your own accountupdate_profile
- Update profile information (name, bio)set_profile_photo
- Set a new profile photodelete_profile_photo
- Remove profile photosget_privacy_settings
- Get current privacy settingsset_privacy_settings
- Update privacy settingsget_user_photos
- Get a user's profile photosget_user_status
- Check a user's online statusget_bot_info
- Get information about a botset_bot_commands
- Configure bot commands
import asyncio
import os
from dotenv import load_dotenv
from tgmcp import client, get_tool_config
# Load environment variables
load_dotenv()
# Optional: Configure which tools to enable
# os.environ["TGMCP_ENABLE_ADMIN_TOOLS"] = "false" # Uncomment to disable admin tools
async def example():
# Start the client
await client.start()
# Get recent chats
dialogs = await client.get_dialogs(limit=5)
print("\nRecent chats:")
for dialog in dialogs:
chat_name = getattr(dialog.entity, "title", None) or getattr(dialog.entity, "first_name", "Unknown")
print(f"- {chat_name} (ID: {dialog.entity.id})")
# Display which tool sets are enabled
tool_config = get_tool_config()
print("\nEnabled tool sets:")
for tool_set, enabled in tool_config.items():
status = "β
Enabled" if enabled else "β Disabled"
print(f"- {tool_set}: {status}")
# Disconnect when done
await client.disconnect()
if __name__ == "__main__":
asyncio.run(example())
- All data remains on your local machine
- Authentication with Telegram is handled securely
- No data is sent to third parties
- Session files should be kept secure
Contributions are welcome! Feel free to open issues or submit pull requests.
For issues and questions, please open an issue on the GitHub repository.
This package is available on PyPI:
You can install it using pip:
pip install tgmcp
Made with β€οΈ for AI-assisted Telegram interaction