Skip to main content
Glama
sparfenyuk

Telegram MCP Server

by sparfenyuk

Servidor MCP de Telegram

Acerca de

El servidor es un puente entre la API de Telegram y los asistentes de IA y se basa en el Protocolo de Contexto de Modelo .

[!IMPORTANTE] Asegúrate de leer y comprender los Términos de Servicio de la API de Telegram antes de usar este servidor. Cualquier uso indebido de la API de Telegram puede resultar en la suspensión de tu cuenta.

Related MCP server: telegram-briefing-mcp

¿Qué es MCP?

El Protocolo de Contexto de Modelo (MCP) es un sistema que permite que las aplicaciones de IA, como Claude Desktop, se conecten a herramientas y fuentes de datos externas. Ofrece una forma clara y segura para que los asistentes de IA trabajen con servicios y API locales, manteniendo al usuario en control.

¿Qué hace este servidor?

Hasta el momento, el servidor proporciona acceso de solo lectura a la API de Telegram.

  • [x] Obtener la lista de diálogos (chats, canales, grupos)

  • [x] Obtener la lista de mensajes (no leídos) en el cuadro de diálogo dado

  • [ ] Marcar canal como leído

  • [ ] Recuperar mensajes por fecha y hora

  • [ ] Descargar archivos multimedia

  • [ ] Obtener la lista de contactos

  • [ ] Redactar un mensaje

  • ...

Casos de uso prácticos

  • [x] Crear un resumen de los mensajes no leídos

  • [ ] Encuentra contactos con próximos cumpleaños y programa un saludo

  • [ ] Encuentre discusiones sobre un tema determinado, resúmalas y proporcione una lista de enlaces.

Prerrequisitos

Instalación

uv tool install git+https://github.com/sparfenyuk/mcp-telegram

[!NOTA] Si ya ha instalado el servidor, puede actualizarlo utilizando el comando uv tool upgrade --reinstall .

[!NOTA] Si desea eliminar el servidor, utilice el comando de la uv tool uninstall mcp-telegram .

Configuración

Configuración de la API de Telegram

Antes de poder utilizar el servidor, debe conectarse a la API de Telegram.

  1. Obtenga el ID de API y el hash de la API de Telegram

  2. Ejecute el siguiente comando:

    mcp-telegram sign-in --api-id <your-api-id> --api-hash <your-api-hash> --phone-number <your-phone-number>

    Ingresa el código que recibiste de Telegram para conectarte a la API.

    Es posible que se requiera la contraseña si tiene habilitada la autenticación de dos factores.

[!NOTA] Para cerrar sesión en la API de Telegram, utilice el comando mcp-telegram logout .

Configuración del escritorio de Claude

Configure Claude Desktop para reconocer el servidor Exa MCP.

  1. Abra el archivo de configuración de Claude Desktop:

    • En MacOS, el archivo de configuración se encuentra en ~/Library/Application Support/Claude/claude_desktop_config.json

    • En Windows, el archivo de configuración se encuentra en %APPDATA%\Claude\claude_desktop_config.json

    Nota: También puedes encontrar claude_desktop_config.json dentro de la configuración de la aplicación Claude Desktop

  2. Agregar la configuración del servidor

    {
      "mcpServers": {
        "mcp-telegram": {
            "command": "mcp-server",
            "env": {
              "TELEGRAM_API_ID": "<your-api-id>",
              "TELEGRAM_API_HASH": "<your-api-hash>",
            },
          }
        }
      }
    }

Configuración de Telegram

Antes de trabajar con la API de Telegram, necesitas obtener tu propio ID de API y hash:

  1. Inicie sesión en su cuenta de Telegram con el número de teléfono de la cuenta de desarrollador que desea utilizar.

  2. Haga clic en Herramientas de desarrollo de API.

  3. Aparecerá la ventana "Crear nueva aplicación". Complete los datos de su aplicación. No es necesario introducir ninguna URL; por el momento, solo los dos primeros campos (título de la aplicación y nombre corto) se pueden modificar posteriormente.

  4. Haz clic en "Crear aplicación" al final. Recuerda que el hash de tu API es secreto y Telegram no te permitirá revocarlo. ¡No lo publiques en ningún sitio!

Desarrollo

Empezando

  1. Clonar el repositorio

  2. Instalar las dependencias

    uv sync
  3. Ejecutar el servidor

    uv run mcp-telegram --help

Se pueden agregar herramientas al archivo src/mcp_telegram/tools.py .

Cómo agregar una nueva herramienta:

  1. Crea una nueva clase que herede de ToolArgs

    class NewTool(ToolArgs):
        """Description of the new tool."""
        pass

    Los atributos de la clase se usarán como argumentos para la herramienta. La cadena de documentación de la clase se usará como descripción de la herramienta.

  2. Implementar la función tool_runner para la nueva clase

    @tool_runner.register
    async def new_tool(args: NewTool) -> t.Sequence[TextContent | ImageContent | EmbeddedResource]:
        pass

    La función debe devolver una secuencia de TextContent, ImageContent o EmbeddedResource. Debe ser asíncrona y aceptar un único argumento de la nueva clase.

  3. ¡Listo! Reinicia el cliente y la nueva herramienta debería estar disponible.

La validación se puede realizar a través de Claude Desktop o ejecutando la herramienta directamente.

Depuración del servidor en la terminal

Para ejecutar la herramienta directamente, utilice el siguiente comando:


# List all available tools
uv run cli.py list-tools

# Run the concrete tool
uv run cli.py call-tool --name ListDialogs --arguments '{"unread": true}'

Depuración del servidor en el Inspector

El inspector MCP es una herramienta que ayuda a depurar el servidor mediante una interfaz de usuario sofisticada. Para ejecutarlo, use el siguiente comando:

npx @modelcontextprotocol/inspector uv run mcp-telegram

[!ADVERTENCIA] No olvide definir las variables de entorno TELEGRAM_API_ID y TELEGRAM_API_HASH en el inspector.

Solución de problemas

Mensaje 'No se pudo conectar al servidor MCP mcp-telegram'

Si ve el mensaje 'No se pudo conectar al servidor MCP mcp-telegram' en Claude Desktop, significa que la configuración del servidor es incorrecta.

Pruebe lo siguiente:

  • Utilice la ruta completa al binario uv en el archivo de configuración

  • Verifique la ruta al repositorio clonado en el archivo de configuración

Available Tools

2 tools
ListDialogsC

List available dialogs, chats and channels.

ParametersJSON Schema
NameRequiredDescriptionDefault
unreadNo
archivedNo
ignore_pinnedNo

TDQS

C2.3/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It only states what the tool does (listing) without mentioning permissions, rate limits, pagination, or response format. For a list tool with zero annotation coverage, this leaves critical behavioral traits unspecified, making it inadequate for safe and effective use.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose without unnecessary words. It is appropriately sized and front-loaded, making it easy to parse quickly. However, it lacks depth, which affects completeness but not conciseness.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (a list operation with 3 parameters), no annotations, no output schema, and low schema coverage, the description is incomplete. It doesn't explain what 'available' means, how results are returned, or parameter usage, leaving significant gaps for the agent to operate effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The description repeats the tool name and provides no information about parameters. With 3 parameters (unread, archived, ignore_pinned) and 0% schema description coverage, the schema only provides titles and types without explanations. The description fails to compensate by adding any meaning or context for these parameters, leaving them undocumented.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose3/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description states the tool's purpose as listing available dialogs, chats, and channels, which is clear but vague. It uses the verb 'list' with the resources 'dialogs, chats and channels', but doesn't specify scope (e.g., all or filtered) or distinguish it from the sibling tool ListMessages. This makes it adequate but with gaps in specificity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention the sibling tool ListMessages, prerequisites, or exclusions. Without any usage context, the agent must infer when this tool is appropriate, which is insufficient for effective tool selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

ListMessagesA
List messages in a given dialog, chat or channel. The messages are listed in order from newest to oldest.

If `unread` is set to `True`, only unread messages will be listed. Once a message is read, it will not be
listed again.

If `limit` is set, only the last `limit` messages will be listed. If `unread` is set, the limit will be
the minimum between the unread messages and the limit.
ParametersJSON Schema
NameRequiredDescriptionDefault
dialog_idYes
unreadNo
limitNo

TDQS

A3.6/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: the ordering (newest to oldest), the effect of 'unread' (filters to unread only and excludes read messages), and how 'limit' interacts with 'unread' (minimum between them). However, it misses details like pagination, error handling, or authentication needs, leaving gaps for a mutation-like operation (listing can imply read access).

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and front-loaded, starting with the core purpose. Each sentence adds value: the first states the action, the second explains ordering, and the subsequent ones detail parameter effects without redundancy. There's zero waste, making it efficient for an AI agent to parse.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations, no output schema, and 3 parameters with 0% schema coverage, the description provides a decent foundation by explaining purpose and parameter interactions. However, it lacks information on return values (e.g., message format), error cases, or authentication requirements, making it incomplete for full contextual understanding in a read operation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description must compensate. It adds significant meaning beyond the schema by explaining the semantics of 'unread' (filters to unread messages and excludes read ones) and 'limit' (applies to last messages, with interaction rules when combined with 'unread'). This covers key aspects of the 3 parameters, though it doesn't detail 'dialog_id' beyond context.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('List') and resource ('messages in a given dialog, chat or channel'), making the purpose immediately understandable. It distinguishes from the sibling tool 'ListDialogs' by specifying messages rather than dialogs. However, it doesn't explicitly contrast with potential alternatives beyond the sibling tool, keeping it from a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by explaining the effects of the 'unread' and 'limit' parameters, which suggests when to use them. However, it lacks explicit guidance on when to choose this tool over alternatives (e.g., vs. a search tool or the sibling 'ListDialogs'), and doesn't mention prerequisites like required permissions or context.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 2 tool updates
    • First observedListDialogs
    • First observedListMessages

TDQS

C2.9/5.0

Scored across 2 tools

Disambiguation5/5

The two tools have clearly distinct purposes: ListDialogs retrieves available dialogs/chats/channels, while ListMessages retrieves messages within a specific dialog/chat/channel. There is no overlap or ambiguity between them.

Naming Consistency5/5

Both tools follow a consistent verb_noun pattern with PascalCase naming (ListDialogs, ListMessages). The naming is predictable and readable throughout the set.

Tool Count2/5

With only 2 tools, this server feels severely under-scoped for a Telegram integration. While the tools are well-defined, there are obvious gaps in functionality (e.g., sending messages, managing channels, handling media) that limit its usefulness.

Completeness2/5

The tool surface is significantly incomplete for a Telegram server. It only provides read-only listing capabilities for dialogs and messages, missing essential operations like sending messages, creating/editing channels, handling files, or any write/update actions that would be expected in a messaging platform integration.

Maintenance

ActivityInactive
ResponsivenessUnresponsive

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    A read-only Telegram MCP server that retrieves messages from your DMs, groups, and channels, enabling Claude to generate executive briefings from Telegram conversations.
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    A Telegram integration for Claude, Cursor, and other MCP-compatible clients, exposing account, chat, message, contact, media, folder, and admin operations through the Model Context Protocol using Telethon.
    Apache 2.0
  • A
    license
    Not graded
    quality
    B
    maintenance
    A Telegram integration for Claude, Cursor, and other MCP-compatible clients. It exposes Telegram account, chat, message, contact, media, folder, and admin operations through the Model Context Protocol using Telethon.
    Apache 2.0