Skip to main content
Glama
sparfenyuk

Telegram MCP Server

ListMessages

Retrieve recent messages from Telegram chats, channels, or dialogs. Filter by unread messages or set a limit to view specific conversations.

Instructions

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.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
dialog_idYes
unreadNo
limitNo

Implementation Reference

  • The main handler function for executing the ListMessages tool. It fetches messages from the specified Telegram dialog_id, optionally filtering by unread status and limiting the number, and returns text contents of messages.
    @tool_runner.register
    async def list_messages(
        args: ListMessages,
    ) -> t.Sequence[TextContent | ImageContent | EmbeddedResource]:
        client: TelegramClient
        logger.info("method[ListMessages] args[%s]", args)
    
        response: list[TextContent] = []
        async with create_client() as client:
            result = await client(functions.messages.GetPeerDialogsRequest(peers=[args.dialog_id]))
            if not result:
                raise ValueError(f"Channel not found: {args.dialog_id}")
    
            if not isinstance(result, types.messages.PeerDialogs):
                raise TypeError(f"Unexpected result: {type(result)}")
    
            for dialog in result.dialogs:
                logger.debug("dialog: %s", dialog)
            for message in result.messages:
                logger.debug("message: %s", message)
    
            iter_messages_args: dict[str, t.Any] = {
                "entity": args.dialog_id,
                "reverse": False,
            }
            if args.unread:
                iter_messages_args["limit"] = min(dialog.unread_count, args.limit)
            else:
                iter_messages_args["limit"] = args.limit
    
            logger.debug("iter_messages_args: %s", iter_messages_args)
            async for message in client.iter_messages(**iter_messages_args):
                logger.debug("message: %s", type(message))
                if isinstance(message, custom.Message) and message.text:
                    logger.debug("message: %s", message.text)
                    response.append(TextContent(type="text", text=message.text))
    
        return response
  • Pydantic model defining the input parameters for the ListMessages tool: dialog_id (required int), unread (bool default False), limit (int default 100). The docstring provides the tool description.
    class ListMessages(ToolArgs):
        """
        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.
        """
    
        dialog_id: int
        unread: bool = False
        limit: int = 100
  • Dynamic registration of tools by inspecting subclasses of ToolArgs in the tools module, including ListMessages, and creating the tool mapping used by list_tools and call_tool.
    def enumerate_available_tools() -> t.Generator[tuple[str, Tool], t.Any, None]:
        for _, tool_args in inspect.getmembers(tools, inspect.isclass):
            if issubclass(tool_args, tools.ToolArgs) and tool_args != tools.ToolArgs:
                logger.debug("Found tool: %s", tool_args)
                description = tools.tool_description(tool_args)
                yield description.name, description
    
    
    mapping: dict[str, Tool] = dict(enumerate_available_tools())
  • Helper function that generates the Tool object from a ToolArgs class, used for registration of ListMessages.
    def tool_description(args: type[ToolArgs]) -> Tool:
        return Tool(
            name=args.__name__,
            description=args.__doc__,
            inputSchema=args.model_json_schema(),
        )
  • MCP server handler for tool calls that dispatches to the specific tool_runner for ListMessages via the dynamic mapping.
    async def call_tool(name: str, arguments: t.Any) -> Sequence[TextContent | ImageContent | EmbeddedResource]:  # noqa: ANN401
        """Handle tool calls for command line run."""
    
        if not isinstance(arguments, dict):
            raise TypeError("arguments must be dictionary")
    
        tool = mapping.get(name)
        if not tool:
            raise ValueError(f"Unknown tool: {name}")
    
        try:
            args = tools.tool_args(tool, **arguments)
            return await tools.tool_runner(args)
        except Exception as e:
            logger.exception("Error running tool: %s", name)
            raise RuntimeError(f"Caught Exception. Error: {e}") from e
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.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/sparfenyuk/mcp-telegram'

If you have feedback or need assistance with the MCP directory API, please join our Discord server