telegram mcp server
A Model Context Protocol server that enables AI assistants to interact with Telegram, allowing them to search channels, list available channels, retrieve messages, and filter messages by regex patterns.
A Model Context Protocol server that enables AI assistants to interact with Telegram, allowing them to search channels, list available channels, retrieve messages, and filter messages by regex patterns.
This project provides both a Telegram client library (telegram-client.js
) and an MCP (Model Context Protocol) server (mcp-server.js
) enabling AI assistants (such as Claude, Cline, or Cursor) to interact with Telegram via the user client API (not bot API). This enables capabilities such as reading message history from channels and chats, with potential for sending messages on behalf of users in future updates. The server component is built using the FastMCP library.
telegram-client.js
)mcp-server.js
)./data/dialog_cache.json
) for faster responses and reduced API calls.Create a .env
file with your Telegram API credentials:
TELEGRAM_API_ID=your_api_id
TELEGRAM_API_HASH=your_api_hash
TELEGRAM_PHONE_NUMBER=your_phone_number
# PORT=8080 # Optional: The MCP server defaults to 8080 if not set here or overridden in code
Install dependencies:
npm install
telegram-client.js
)This library allows direct programmatic interaction with Telegram.
// Example using the client library (see client.js for a more complete example)
import TelegramClient from "./telegram-client.js";
import dotenv from "dotenv";
dotenv.config();
async function main() {
// Create a new client instance
const client = new TelegramClient(
process.env.TELEGRAM_API_ID,
process.env.TELEGRAM_API_HASH,
process.env.TELEGRAM_PHONE_NUMBER
// Optional: specify session path, default is './data/session.json'
);
// Login to Telegram (will prompt for code/password if needed)
await client.login();
// Load dialog cache (optional, but recommended for performance)
// Or use getAllDialogs() to fetch and populate the cache
await client.loadDialogCache(); // Default path: './data/dialog_cache.json'
if (client.dialogCache.size === 0) {
console.log("Cache empty, fetching all dialogs to build cache...");
await client.getAllDialogs(); // Fetches all dialogs and populates cache
await client.saveDialogCache(); // Save cache for next time
}
// Get dialogs from the cache
const dialogs = Array.from(client.dialogCache.values());
// Print all cached chats
dialogs.forEach((chat) => {
if (chat.title) {
console.log(`Chat: ${chat.title} (ID: ${chat.id})`);
}
});
// Example: Get messages (replace 'your_channel_id' with an actual ID from the cache)
// const messages = await client.getMessagesByChannelId('your_channel_id', 50);
// console.log(messages);
}
main().catch(console.error);
Run the standalone client example:
node client.js
mcp-server.js
)This server exposes Telegram interactions as tools for MCP-compatible AI assistants (like Claude).
Start the MCP server:
(First, ensure you have logged in at least once via the client or by running the server previously, creating ./data/session.json
)
npm start
The server will initialize the Telegram client and attempt to load/build the dialog cache (./data/dialog_cache.json
). This might take time on the first run.
The MCP server endpoint will be available via Server-Sent Events (SSE) at:
http://localhost:8080/sse
You can connect an MCP-compatible client (like an AI assistant) to this endpoint.
telegram-client.js
)const client = new TelegramClient(apiId, apiHash, phoneNumber, sessionPath);
apiId
: Your Telegram API IDapiHash
: Your Telegram API HashphoneNumber
: Your phone number in international formatsessionPath
: (Optional) Path to save the session file (default: './data/session.json')login()
: Authenticates with Telegram (handles new logins, 2FA, and session reuse).hasSession()
: Checks if a valid session file exists.getDialogs(limit, offset)
: Gets a batch of dialogs (chats) directly from Telegram API.getAllDialogs(batchSize)
: Fetches all dialogs progressively, populating the internal cache (dialogCache
)._updateDialogCache(chats)
: Internal method to update the cache.getPeerInputById(id)
: Gets the necessary InputPeer
object from the cache for API calls.getChatMessages(chatObject, limit)
: Gets messages from a specific chat object (less commonly used now).getMessagesByChannelId(channelId, limit)
: Gets messages from a specific chat/channel using its ID (uses cached peer info).filterMessagesByPattern(messages, pattern)
: Filters an array of message strings by a regex pattern.saveDialogCache(cachePath)
: Saves the internal dialogCache
Map to a JSON file (default: ./data/dialog_cache.json
).loadDialogCache(cachePath)
: Loads the dialogCache
Map from a JSON file.client.js
: An example script demonstrating usage of the telegram-client.js
library.telegram-client.js
: The core Telegram client library handling authentication and API interaction.mcp-server.js
: The MCP server implementation (using FastMCP) providing Telegram tools over SSE.The MCP server (mcp-server.js
) can be used with Claude or other assistants supporting the Model Context Protocol over Server-Sent Events.
Example workflow:
npm start
).http://localhost:8080/sse
.listChannels
searchChannels
getChannelMessages
(optionally with filterPattern
)When connected to the MCP server, you can ask Claude natural language questions like:
You can use the filterPattern
parameter with getChannelMessages
to find specific types of messages. Some examples:
[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}
- Find UUIDshttps?://S+
- Find URLs#[a-zA-Z0-9]+
- Find hashtagsdata/
directory and restart the server to re-authenticate.This project is licensed under the MIT License - see the LICENSE file for details.