Skip to main content
Glama
archetyx
by archetyx

telegram_notify

Send structured notifications to Telegram with event types including completed, error, question, and progress. Provide concise summaries and optional details for remote task monitoring and decision-making.

Instructions

        发送结构化通知到 Telegram

        参数:
        - event: 事件类型(completed/error/question/progress)
        - summary: 简短总结,必填,限制200字以内
        - details: 详细信息,可选

        最佳实践:
        1. summary 必须简洁明了(1-2句话),说明做了什么、结果如何
        2. 不要包含思考过程、不要包含代码片段
        3. 需要用户决策时,清晰说明选项

        示例:
        telegram_notify(
            event="completed",
            summary="修复了 auth.py:45 的空指针异常,所有测试通过",
            details="修改文件: auth.py, test_auth.py\n测试: 12/12 passed"
        )

        telegram_notify(
            event="question",
            summary="发现3种修复方案:1)添加空值检查 2)使用Optional类型 3)重构整个模块。推荐方案1,是否继续?"
        )
        

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
detailsNo详细信息(可选)
eventYes事件类型
summaryYes简短总结(必填,200字以内)

Implementation Reference

  • The core handler function for the 'telegram_notify' tool. It validates input, formats the notification message with event emoji and session ID, optionally includes details, updates the session state, sends the message to Telegram, and returns a success or error response.
    async def handle_telegram_notify(session, arguments: dict) -> list[TextContent]:
        """Handle telegram_notify tool"""
        event = arguments.get("event")
        summary = arguments.get("summary", "")
        details = arguments.get("details", "")
    
        # Validate summary length
        if len(summary) > 200:
            return [TextContent(
                type="text",
                text="错误: summary 过长,请精炼到200字以内"
            )]
    
        # Format message
        emoji = {
            "completed": "✅",
            "error": "❌",
            "question": "❓",
            "progress": "⏳"
        }
    
        message = f"{emoji.get(event, '🔔')} [`{session.session_id}`]\n{summary}"
    
        if details:
            message += f"\n\n━━━━━━━━━━━━\n📝 详情:\n{details}"
    
        # Update session
        session.last_message = summary
        session.update_activity()
        registry.update_session(session)  # Save to shared storage
    
        # Send to Telegram
        try:
            await send_telegram_message(session.chat_id, message)
            return [TextContent(
                type="text",
                text=f"✅ 已发送通知到 Telegram (会话: {session.session_id})"
            )]
        except Exception as e:
            return [TextContent(
                type="text",
                text=f"❌ 发送失败: {str(e)}"
            )]
  • Registration of the 'telegram_notify' tool in the MCP server's list_tools() method, defining the tool name, detailed description, and input schema with required event and summary parameters.
    Tool(
        name="telegram_notify",
        description="""
        ⚠️ 这是 Telegram MCP Server 的通知工具
        用于向用户的 Telegram Bot 发送任务进度通知
        
        ❌ 这不是通用的 Telegram 消息发送工具
        ❌ 不能发送消息到任意 Telegram 用户或群组
        ✅ 只能发送通知到配置的 Telegram Bot(用户会在 Telegram 中收到)
        
        💡 推荐使用 telegram_notify_with_actions 代替此工具
        telegram_notify_with_actions 提供动态按钮,用户体验更好
    
        此工具适用于:
        - 简单的状态更新(不需要用户交互)
        - 快速通知(无需提供下一步建议)
        - 向后兼容旧代码
    
        参数:
        - event: 事件类型(completed/error/question/progress)
        - summary: 简短总结(必填,200字以内)
        - details: 详细信息(可选)
    
        示例:
        telegram_notify(
            event="completed",
            summary="修复了 auth.py:45 的空指针异常,所有测试通过"
        )
    
        💡 更好的选择:使用 telegram_notify_with_actions 提供智能建议按钮
        """,
        inputSchema={
            "type": "object",
            "properties": {
                "event": {
                    "type": "string",
                    "enum": ["completed", "error", "question", "progress"],
                    "description": "事件类型"
                },
                "summary": {
                    "type": "string",
                    "description": "简短总结(必填,200字以内)",
                    "maxLength": 200
                },
                "details": {
                    "type": "string",
                    "description": "详细信息(可选)"
                }
            },
            "required": ["event", "summary"]
        }
    ),
  • Input schema definition for the 'telegram_notify' tool, specifying the object structure with event (enum), summary (required, max 200 chars), and optional details.
    inputSchema={
        "type": "object",
        "properties": {
            "event": {
                "type": "string",
                "enum": ["completed", "error", "question", "progress"],
                "description": "事件类型"
            },
            "summary": {
                "type": "string",
                "description": "简短总结(必填,200字以内)",
                "maxLength": 200
            },
            "details": {
                "type": "string",
                "description": "详细信息(可选)"
            }
        },
        "required": ["event", "summary"]
    }
  • Helper function to send messages to Telegram via HTTP API, with Markdown support, automatic retry on parse errors, and comprehensive error handling. Used by the telegram_notify handler.
    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
  • Dispatch logic in the main call_tool handler that routes 'telegram_notify' calls to the specific handle_telegram_notify function.
    if name == "telegram_notify":
        return await handle_telegram_notify(session, arguments)
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 behavioral traits such as the tool's function (sending notifications), parameter constraints (e.g., summary length limit), and best practices for content. However, it lacks details on potential side effects (e.g., rate limits, authentication needs), which would be helpful for a notification tool.

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 well-structured with clear sections (purpose, parameters, best practices, examples), front-loaded with the core purpose. Every sentence adds value, such as clarifying parameter roles and providing actionable guidance, with no wasted text.

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 moderate complexity (3 parameters, no output schema, no annotations), the description is mostly complete. It covers purpose, parameters, usage guidelines, and examples. However, it lacks details on behavioral aspects like error handling or response format, which would enhance completeness for a notification tool.

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 100%, so the baseline is 3. The description adds value by explaining parameter semantics in Chinese, providing best practices for 'summary' and 'details', and including examples that illustrate usage. This compensates for the schema's basic descriptions, though it doesn't add deep technical details beyond what's implied.

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

Purpose5/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 structured notifications to Telegram). It specifies the verb '发送' (send) and the resource 'Telegram', and distinguishes it from sibling tools like telegram_send, telegram_send_code, etc., by emphasizing structured notifications with specific event types rather than general messaging.

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 in the '最佳实践' (Best Practices) section, including when to use (e.g., for concise summaries without code snippets) and when not to use (e.g., avoid including thought processes). It also implicitly distinguishes from siblings by focusing on structured notifications, though it doesn't name alternatives directly.

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