Skip to main content
Glama
archetyx
by archetyx

telegram_get_context_info

Retrieve and send current session context information to Telegram, including token usage statistics, session details, and system configuration for remote AI assistant monitoring.

Instructions

        获取并发送当前会话的上下文信息到 Telegram

        ⚠️ 重要:调用此工具时,你应该:
        1. 检查系统提供的 token 使用量信息(<budget:token_budget> 标签)
        2. 将 token 使用情况包含在发送的信息中
        3. 发送完整的上下文信息(会话信息 + token 使用情况)

        返回信息应包括:
        - 会话 ID 和项目路径
        - Token 使用量(已使用 / 总量 / 剩余 / 使用率)
        - 会话运行时间
        - 系统信息
        - Telegram 配置

        示例输出格式:
        📊 会话上下文信息
        🆔 会话: testtg
        📁 项目: /path/to/project

        💾 Token 使用:
        - 已使用: 41,853 tokens
        - 总容量: 1,000,000 tokens
        - 剩余: 958,147 tokens
        - 使用率: 4.2%

        ⏱️ 运行时间: 15 分钟
        🖥️ 系统: Darwin 24.6.0
        🐍 Python: 3.14.0
        

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
token_totalNo总 token 容量(从系统预算信息中获取)
token_usedNo已使用的 token 数量(从系统预算信息中获取)

Implementation Reference

  • The handler function that implements the tool logic: gathers comprehensive session context (ID, paths, token usage if provided, timing, system info, Telegram config), formats it as a Markdown message, sends it to Telegram, and returns success/error feedback.
    async def handle_telegram_get_context_info(session, arguments: dict) -> list[TextContent]:
        """Handle telegram_get_context_info tool"""
        import platform
        from datetime import datetime
    
        token_used = arguments.get("token_used", 0)
        token_total = arguments.get("token_total", 1000000)
    
        # Gather context information
        info_parts = []
    
        info_parts.append("📊 会话上下文信息")
        info_parts.append("━━━━━━━━━━━━━━━━")
        info_parts.append(f"🆔 会话 ID: {session.session_id}")
        info_parts.append(f"📁 项目路径: {session.project_path}")
        info_parts.append(f"📂 当前目录: {os.getcwd()}")
    
        # Token usage (if provided)
        if token_used > 0:
            token_remaining = token_total - token_used
            usage_percent = (token_used / token_total) * 100
    
            info_parts.append("")
            info_parts.append("💾 Token 使用情况:")
            info_parts.append(f"- 已使用: {token_used:,} tokens")
            info_parts.append(f"- 总容量: {token_total:,} tokens")
            info_parts.append(f"- 剩余: {token_remaining:,} tokens")
            info_parts.append(f"- 使用率: {usage_percent:.1f}%")
    
        # Session timing
        created = datetime.fromisoformat(session.created_at)
        last_active = datetime.fromisoformat(session.last_active)
        uptime = (datetime.now() - created).total_seconds()
    
        info_parts.append("")
        info_parts.append("⏱️  会话时间:")
        info_parts.append(f"- 创建时间: {created.strftime('%Y-%m-%d %H:%M:%S')}")
    
        if uptime < 60:
            info_parts.append(f"- 运行时长: {int(uptime)} 秒")
        elif uptime < 3600:
            info_parts.append(f"- 运行时长: {int(uptime / 60)} 分钟")
        elif uptime < 86400:
            info_parts.append(f"- 运行时长: {int(uptime / 3600)} 小时")
        else:
            info_parts.append(f"- 运行时长: {int(uptime / 86400)} 天")
    
        # System info
        info_parts.append("")
        info_parts.append("🖥️  系统环境:")
        info_parts.append(f"- 操作系统: {platform.system()} {platform.release()}")
        info_parts.append(f"- Python: {platform.python_version()}")
        info_parts.append(f"- 状态: {session.status}")
    
        # Telegram config
        info_parts.append("")
        info_parts.append("📱 Telegram 配置:")
        info_parts.append(f"- 最长等待: {config.TELEGRAM_MAX_WAIT // 86400} 天")
        info_parts.append(f"- 轮询: {config.POLL_INTERVALS[0]}s → {config.POLL_INTERVALS[1]}s → {config.POLL_INTERVALS[2]}s")
    
        message = "\n".join(info_parts)
    
        # Update session
        session.update_activity()
    
        # Send to Telegram
        try:
            await send_telegram_message(session.chat_id, message)
            return [TextContent(
                type="text",
                text=f"✅ 上下文信息已发送到 Telegram (会话: {session.session_id})\n\n💡 提示:下次调用时传入 token_used 参数可显示 token 使用量"
            )]
        except Exception as e:
            return [TextContent(
                type="text",
                text=f"❌ 发送失败: {str(e)}"
            )]
  • Tool registration in the list_tools() handler, including name, detailed description of usage and expected output format, and inputSchema defining optional token_used and token_total parameters.
    Tool(
        name="telegram_get_context_info",
        description="""
        获取并发送当前会话的上下文信息到 Telegram
    
        ⚠️ 重要:调用此工具时,你应该:
        1. 检查系统提供的 token 使用量信息(<budget:token_budget> 标签)
        2. 将 token 使用情况包含在发送的信息中
        3. 发送完整的上下文信息(会话信息 + token 使用情况)
    
        返回信息应包括:
        - 会话 ID 和项目路径
        - Token 使用量(已使用 / 总量 / 剩余 / 使用率)
        - 会话运行时间
        - 系统信息
        - Telegram 配置
    
        示例输出格式:
        📊 会话上下文信息
        🆔 会话: testtg
        📁 项目: /path/to/project
    
        💾 Token 使用:
        - 已使用: 41,853 tokens
        - 总容量: 1,000,000 tokens
        - 剩余: 958,147 tokens
        - 使用率: 4.2%
    
        ⏱️ 运行时间: 15 分钟
        🖥️ 系统: Darwin 24.6.0
        🐍 Python: 3.14.0
        """,
        inputSchema={
            "type": "object",
            "properties": {
                "token_used": {
                    "type": "integer",
                    "description": "已使用的 token 数量(从系统预算信息中获取)"
                },
                "token_total": {
                    "type": "integer",
                    "description": "总 token 容量(从系统预算信息中获取)",
                    "default": 1000000
                }
            }
        }
    ),
  • Dispatch logic in the main @server.call_tool() function that routes calls to the specific handler.
    elif name == "telegram_get_context_info":
        return await handle_telegram_get_context_info(session, arguments)
  • Input schema defining the parameters for the tool: token_used (integer, required for usage display) and token_total (integer, default 1M).
    inputSchema={
        "type": "object",
        "properties": {
            "token_used": {
                "type": "integer",
                "description": "已使用的 token 数量(从系统预算信息中获取)"
            },
            "token_total": {
                "type": "integer",
                "description": "总 token 容量(从系统预算信息中获取)",
                "default": 1000000
            }
        }
    }
Behavior4/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 effectively discloses key behavioral traits: it's a read-only operation (获取并发送 implies retrieval and transmission, not mutation), requires specific data inputs (token usage from system budget), and specifies the output format and content. However, it doesn't mention potential side effects like rate limits or authentication needs, though these might be less critical for this tool.

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

Conciseness3/5

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

The description is appropriately sized but not optimally structured. It front-loads the purpose clearly, but the detailed instructions and example output format (while helpful) make it somewhat verbose. Every sentence earns its place by providing necessary guidance, but it could be more streamlined for quick scanning.

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 complexity (2 parameters, no output schema, no annotations), the description is quite complete. It covers purpose, usage steps, output content, and example format. The main gap is the lack of an output schema, but the description compensates by detailing the return information and providing an example. For a context-reporting tool, this is sufficient though not exhaustive.

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 significant value beyond the schema: it explains that token_total and token_used should be derived from system budget information (<budget:token_budget>), provides context for why these parameters are needed (to include token usage in the output), and shows how they're used in the example output format. This compensates well for the schema-only documentation.

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' (get and send current session context information to Telegram). It specifies the exact action (get and send), resource (context information), and destination (Telegram), distinguishing it from sibling tools like telegram_send or telegram_notify which appear to send generic messages or notifications.

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 instructs when to use this tool (to send context information including token usage), specifies prerequisites (checking system token usage via <budget:token_budget>), and outlines required steps (include token usage, send complete context). It implicitly distinguishes from siblings by focusing on context info rather than general messaging or file sending.

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