Skip to main content
Glama
archetyx
by archetyx

telegram_send

Send free-form messages to Telegram with automatic handling of long content by truncating messages over 300 characters. Use for direct communication through the Telegram MCP Server.

Instructions

        发送自由格式消息到 Telegram(不推荐,请优先使用 telegram_notify)

        自动处理:
        - 超过300字自动截断
        - 会提示使用 telegram_notify 发送结构化消息
        

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
messageYes消息内容

Implementation Reference

  • Main handler function that executes the 'telegram_send' tool logic: extracts message, truncates if >300 chars, formats with session ID, updates session state, sends to Telegram via send_telegram_message, returns success/error content.
    async def handle_telegram_send(session, arguments: dict) -> list[TextContent]:
        """Handle telegram_send tool"""
        message = arguments.get("message", "")
    
        # Auto-truncate if too long
        if len(message) > 300:
            message = message[:280] + "\n\n... [消息过长已截断,建议使用 telegram_notify]"
    
        # Format message
        formatted = f"🤖 [`{session.session_id}`]\n{message}"
    
        # Update session
        session.last_message = message
        session.update_activity()
        registry.update_session(session)  # Save to shared storage
    
        # Send to Telegram
        try:
            await send_telegram_message(session.chat_id, formatted)
            return [TextContent(
                type="text",
                text=f"✅ 已发送消息到 Telegram (会话: {session.session_id})"
            )]
        except Exception as e:
            return [TextContent(
                type="text",
                text=f"❌ 发送失败: {str(e)}"
            )]
  • Tool registration in list_tools(): defines name 'telegram_send', description, and inputSchema requiring 'message' string.
    Tool(
        name="telegram_send",
        description="""
        发送自由格式消息到 Telegram(不推荐,请优先使用 telegram_notify)
    
        自动处理:
        - 超过300字自动截断
        - 会提示使用 telegram_notify 发送结构化消息
        """,
        inputSchema={
            "type": "object",
            "properties": {
                "message": {
                    "type": "string",
                    "description": "消息内容"
                }
            },
            "required": ["message"]
        }
    ),
  • Input schema for 'telegram_send' tool: object with required 'message' property (string).
    inputSchema={
        "type": "object",
        "properties": {
            "message": {
                "type": "string",
                "description": "消息内容"
            }
        },
        "required": ["message"]
    }
  • Dispatch logic in call_tool() that routes 'telegram_send' calls to the handle_telegram_send function.
    elif name == "telegram_send":
        return await handle_telegram_send(session, arguments)
  • Helper function used by telegram_send to actually send the HTTP request to Telegram API, with Markdown fallback.
    async def send_telegram_message(chat_id: str, message: str, parse_mode: str = "Markdown") -> None:
        """Send message to Telegram (async) using HTTP API"""
        import httpx
    
        url = f"https://api.telegram.org/bot{config.TELEGRAM_BOT_TOKEN}/sendMessage"
    
        payload = {
            "chat_id": chat_id,
            "text": message
        }
    
        # Only add parse_mode if it's not None
        if parse_mode:
            payload["parse_mode"] = parse_mode
    
        try:
            async with httpx.AsyncClient() as client:
                response = await client.post(url, json=payload, timeout=10.0)
                response.raise_for_status()
        except httpx.HTTPStatusError as e:
            if e.response.status_code == 400 and parse_mode:
                # Markdown parsing failed, retry without parse_mode
                logger.warning(f"Markdown parsing failed (400 Bad Request), retrying as plain text")
                payload.pop("parse_mode", None)
                async with httpx.AsyncClient() as client:
                    response = await client.post(url, json=payload, timeout=10.0)
                    response.raise_for_status()
            else:
                logger.error(f"Failed to send Telegram message: {e}")
                raise
        except Exception as e:
            logger.error(f"Failed to send Telegram message: {e}")
            raise
Behavior4/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. It discloses key behavioral traits: automatic truncation for messages over 300 characters and a prompt to use 'telegram_notify' for structured messages. However, it doesn't cover other potential behaviors like error handling, rate limits, or authentication needs, leaving some gaps for a tool with no annotation support.

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 concise and well-structured into three brief points: purpose, automatic handling, and recommendation. Each sentence adds value without redundancy. However, the formatting includes extra whitespace and quotes, slightly detracting from cleanliness, but the content itself is efficiently presented.

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

Completeness4/5

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

Given the tool's low complexity (1 parameter, no output schema, no annotations), the description is fairly complete. It covers purpose, usage guidelines, and key behaviors like truncation. However, it lacks details on return values or error cases, which could be useful despite no output schema. For a simple tool, this is adequate but not exhaustive.

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

Parameters3/5

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

The input schema has 100% description coverage, with the 'message' parameter documented as '消息内容' (message content). The description doesn't add any parameter-specific semantics beyond what the schema provides, such as format constraints or examples. With high schema coverage, the baseline score of 3 is appropriate, as the description doesn't compensate but doesn't need to heavily.

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 tool's purpose: '发送自由格式消息到 Telegram' (send free-form messages to Telegram). It specifies the verb ('发送' - send) and resource ('Telegram'), and distinguishes it from the sibling 'telegram_notify' by mentioning it's for free-form messages. However, it doesn't fully differentiate from other siblings like 'telegram_send_code', 'telegram_send_file', or 'telegram_send_image', which also send content to Telegram.

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

Usage Guidelines5/5

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

The description provides explicit usage guidelines: it states '不推荐,请优先使用 telegram_notify' (not recommended, please prioritize using telegram_notify) and explains that 'telegram_notify' is for structured messages, while this tool is for free-form messages. This clearly defines when to use this tool versus alternatives, including exclusions and recommendations.

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/archetyx/telegram-mcp-server'

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