Skip to main content
Glama

get_stack_trace

Retrieve and analyze thread stack traces from Java processes to diagnose performance issues, identify blocking threads, and monitor JVM application behavior.

Instructions

获取线程堆栈信息

        Args:
            pid (str): 进程ID,使用字符串形式(如:"12345")
            thread_id (str): 线程ID,使用字符串形式。支持十六进制(如:"0x2c03")
            top_n (str): 显示前N个线程,使用字符串形式(如:"5"),默认值为"5"
            find_blocking (bool): 是否只查找阻塞线程(BLOCKED状态或等待锁的线程)
            interval (str): 采样间隔,使用字符串形式(如:"1000"表示1秒)
            show_all (bool): 是否显示所有信息

        Returns:
            Dict: 包含线程堆栈信息的字典,包含以下字段:
                - threads (List[Dict]): 线程信息列表
                - thread_count (int): 线程数量
                - raw_output (str): 原始输出
                - timestamp (float): 时间戳
                - success (bool): 是否成功
                - error (Optional[str]): 错误信息
        

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pidNo
thread_idNo
top_nNo5
find_blockingNo
intervalNo
show_allNo

Implementation Reference

  • Primary handler implementation for the 'get_stack_trace' tool. Validates PID and parameters, executes JstackCommand to dump threads, filters by blocking status, specific thread ID, or top N threads, and returns structured thread information.
    @self.mcp.tool()
    def get_stack_trace(pid: str = "", 
                        thread_id: str = "", 
                        top_n: str = "5", 
                        find_blocking: bool = False, 
                        interval: str = "", 
                        show_all: bool = False) -> Dict:
        """获取线程堆栈信息
        
        Args:
            pid (str): 进程ID,使用字符串形式(如:"12345")
            thread_id (str): 线程ID,使用字符串形式。支持十六进制(如:"0x2c03")
            top_n (str): 显示前N个线程,使用字符串形式(如:"5"),默认值为"5"
            find_blocking (bool): 是否只查找阻塞线程(BLOCKED状态或等待锁的线程)
            interval (str): 采样间隔,使用字符串形式(如:"1000"表示1秒)
            show_all (bool): 是否显示所有信息
    
        Returns:
            Dict: 包含线程堆栈信息的字典,包含以下字段:
                - threads (List[Dict]): 线程信息列表
                - thread_count (int): 线程数量
                - raw_output (str): 原始输出
                - timestamp (float): 时间戳
                - success (bool): 是否成功
                - error (Optional[str]): 错误信息
        """
        
        try:
            validated_pid = self._validate_and_convert_id(pid if pid else None, "process ID")
            if validated_pid is None:
                return {
                    "raw_output": "",
                    "timestamp": time.time(),
                    "success": False,
                    "error": "Invalid process ID"
                }
            
            validated_thread_id = self._validate_and_convert_id(thread_id if thread_id else None, "thread ID")
            validated_top_n = self._validate_and_convert_id(top_n if top_n else None, "top_n")
            # 设置默认值
            if validated_top_n is None:
                validated_top_n = 5
                
        except ValueError as e:
            return {
                "raw_output": "",
                "timestamp": time.time(),
                "success": False,
                "error": str(e)
            }
        
        cmd = JstackCommand(self.executor, JstackFormatter())
        result = cmd.execute(str(validated_pid))
        
        if not result.get('success', False):
            return {
                "threads": [],
                "thread_count": 0,
                "raw_output": result.get('output', ''),
                "timestamp": time.time(),
                "success": False,
                "error": result.get('error', 'Failed to execute jstack command')
            }
        
        threads = result.get('threads', [])
        
        # 处理 find_blocking:筛选阻塞线程
        if find_blocking:
            blocking_threads = []
            for thread in threads:
                state = thread.get('state', '').upper()
                locks = thread.get('locks', [])
                
                # 检查是否为阻塞状态
                is_blocked = (
                    'BLOCKED' in state or
                    any('waiting to lock' in lock.lower() for lock in locks) or
                    any('parking to wait' in lock.lower() for lock in locks)
                )
                
                if is_blocked:
                    blocking_threads.append(thread)
            
            threads = blocking_threads
        
        # 处理 thread_id:筛选指定线程
        if validated_thread_id is not None:
            target_threads = []
            # 支持十进制和十六进制
            target_nid_hex = hex(validated_thread_id) if isinstance(validated_thread_id, int) else str(validated_thread_id)
            target_nid_dec = str(validated_thread_id)
            
            for thread in threads:
                thread_nid = thread.get('nid', '')
                thread_tid = thread.get('thread_id')
                
                # 匹配nid(十六进制)或thread_id(十进制)
                if (thread_nid == target_nid_hex or 
                    thread_nid == target_nid_dec or
                    thread_tid == validated_thread_id):
                    target_threads.append(thread)
            
            threads = target_threads
        
        # 处理 top_n:取前N个线程
        if validated_top_n is not None and validated_top_n > 0:
            threads = threads[:validated_top_n]
        
        # 返回格式化后的结果,包含 threads 字段
        return {
            "threads": threads,
            "thread_count": len(threads),
            "raw_output": result.get('output', ''),
            "timestamp": time.time(),
            "success": True,
            "error": None
        }
  • Helper method used by get_stack_trace to validate and convert string PIDs, thread_ids, top_n to integers, supporting hexadecimal format.
    def _validate_and_convert_id(self, value: Union[int, str, None], param_name: str = "ID") -> Optional[int]:
        """
        验证并转换ID参数,支持int和str类型的数字参数
        
        Args:
            value: 要转换的值,可以是int、str或None
            param_name: 参数名称,用于错误信息
            
        Returns:
            转换后的整数值,如果输入为None则返回None
            
        Raises:
            ValueError: 如果无法转换为有效的整数
        """
        if value is None:
            return None
            
        if isinstance(value, int):
            return value
            
        if isinstance(value, str):
            # 去除前后空白字符
            value = value.strip()
            if not value:
                return None
                
            try:
                # 支持十六进制格式(如0x2c03)和十进制格式
                if value.lower().startswith('0x'):
                    return int(value, 16)
                else:
                    return int(value)
            except ValueError:
                raise ValueError(f"Invalid {param_name}: '{value}' cannot be converted to integer")
        
        raise ValueError(f"Invalid {param_name} type: expected int, str or None, got {type(value)}")
  • Registration of the get_stack_trace tool using the FastMCP decorator.
    @self.mcp.tool()
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 of behavioral disclosure. It does describe the return format in detail (threads list, thread count, raw output, etc.), which is valuable behavioral information. However, it doesn't mention performance characteristics, rate limits, authentication requirements, or potential side effects of the sampling interval parameter.

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 well-structured with clear sections for Args and Returns, making it easy to parse. While comprehensive, it's appropriately sized for a tool with 6 parameters and detailed return information. The Chinese text at the beginning could be more concise, but overall the structure is efficient.

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 complexity (6 parameters, no annotations, no output schema), the description provides substantial context including detailed parameter explanations and a comprehensive return format specification. The main gap is the lack of usage guidance relative to sibling tools, but otherwise it's quite complete for helping an agent understand and invoke the tool correctly.

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

Parameters5/5

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

The description provides excellent parameter semantics beyond the input schema, which has 0% description coverage. Each parameter is clearly explained with examples (e.g., '12345' for pid, '0x2c03' for thread_id, '1000' for interval), default values are specified, and boolean parameters have clear explanations of what they control. This fully compensates for the lack of schema descriptions.

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 '获取线程堆栈信息' (get thread stack information), which is a specific verb+resource combination. However, it doesn't explicitly differentiate from sibling tools like 'get_thread_info' or 'get_stack_trace_by_method', which likely provide related but different functionality.

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. With multiple sibling tools related to threads and stack traces (get_thread_info, get_stack_trace_by_method, get_jcmd_output), there's no indication of when this specific stack trace retrieval tool is appropriate versus other thread-related tools.

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/xzq-xu/jvm-mcp-server'

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