Skip to main content
Glama

get_class_info

Retrieve Java class information from running JVM processes using jmap and javap commands to analyze class structures, memory usage, and implementation details for debugging and monitoring.

Instructions

获取类信息 - 使用jmap -histo和javap命令获取完整的类信息

        Args:
            pid (str): 进程ID,使用字符串形式(如:"12345")
            class_pattern (str): 类名表达式匹配
            show_detail (bool): 是否显示详细信息,默认false
            show_field (bool): 是否显示成员变量信息(需要show_detail=True),默认false
            use_regex (bool): 是否使用正则表达式匹配,默认false
            depth (str): 属性遍历深度(暂未使用)
            classloader_hash (Optional[str]): 指定class的ClassLoader的hashcode(暂未使用)
            classloader_class (Optional[str]): 指定执行表达式的ClassLoader的class name(暂未使用)
            max_matches (str): 匹配类的最大数量,使用字符串形式(如:"50")

        Returns:
            Dict: 包含类信息的字典
        

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pidNo
class_patternNo
show_detailNo
show_fieldNo
use_regexNo
depthNo
classloader_hashNo
classloader_classNo
max_matchesNo

Implementation Reference

  • The MCP tool handler for get_class_info. Validates inputs, imports and instantiates ClassInfoCoordinator, calls get_class_info_parallel to perform the core logic.
    @self.mcp.tool()
    def get_class_info(pid: str = "", 
                      class_pattern: str = "",
                      show_detail: bool = False,
                      show_field: bool = False,
                      use_regex: bool = False,
                      depth: str = "",
                      classloader_hash: Optional[str] = None,
                      classloader_class: Optional[str] = None,
                      max_matches: str = "") -> Dict:
        """获取类信息 - 使用jmap -histo和javap命令获取完整的类信息
        
        Args:
            pid (str): 进程ID,使用字符串形式(如:"12345")
            class_pattern (str): 类名表达式匹配
            show_detail (bool): 是否显示详细信息,默认false
            show_field (bool): 是否显示成员变量信息(需要show_detail=True),默认false
            use_regex (bool): 是否使用正则表达式匹配,默认false
            depth (str): 属性遍历深度(暂未使用)
            classloader_hash (Optional[str]): 指定class的ClassLoader的hashcode(暂未使用)
            classloader_class (Optional[str]): 指定执行表达式的ClassLoader的class name(暂未使用)
            max_matches (str): 匹配类的最大数量,使用字符串形式(如:"50")
    
        Returns:
            Dict: 包含类信息的字典
        """
        # 验证 pid 参数
        validated_pid = self._validate_and_convert_id(pid if pid else None, "Process ID")
        if validated_pid is None:
            return {"success": False, "error": "有效的进程ID是必须的"}
        
        # 验证 max_matches 参数
        validated_max_matches = None
        if max_matches:
            validated_max_matches = self._validate_and_convert_id(max_matches, "Max matches")
            if validated_max_matches is None or validated_max_matches <= 0:
                return {"success": False, "error": "max_matches必须是正整数"}
        
        try:
            # 创建 ClassInfoCoordinator 实例
            from .native.base import NativeCommandExecutor
            from .native.tools import ClassInfoCoordinator
            
            executor = NativeCommandExecutor()
            coordinator = ClassInfoCoordinator(executor)
            
            # 调用协调器获取类信息
            result = coordinator.get_class_info_parallel(
                pid=str(validated_pid),
                class_pattern=class_pattern,
                show_detail=show_detail,
                show_field=show_field,
                use_regex=use_regex,
                max_matches=validated_max_matches
            )
            
            return result
            
        except Exception as e:
            return {
                "success": False,
                "error": f"获取类信息时发生错误: {str(e)}",
                "classes": [],
                "total_matches": 0,
                "limited_by_max": False
            }
  • Core helper method implementing the class info retrieval: jmap histogram for stats, filtering, optional javap for structure.
    def get_class_info(self, pid: str, class_pattern: str = "", 
                      show_detail: bool = False, show_field: bool = False,
                      use_regex: bool = False, max_matches: Optional[int] = None,
                      **kwargs) -> Dict[str, Any]:
        """获取类信息
    
        Args:
            pid: 进程ID
            class_pattern: 类名模式匹配
            show_detail: 是否显示详细信息
            show_field: 是否显示字段信息
            use_regex: 是否使用正则表达式匹配
            max_matches: 最大匹配数量
    
        Returns:
            Dict[str, Any]: 包含类信息的字典
        """
        try:
            # 第一步:使用 jmap -histo 获取运行时统计信息
            jmap_result = self.jmap_histo_cmd.execute(
                pid=pid, 
                operation=JmapOperation.HISTO,
                live_only=kwargs.get('live_only', False)
            )
            
            if not jmap_result.get('success', False):
                return {
                    "success": False,
                    "error": f"Failed to get histogram data: {jmap_result.get('error', 'Unknown error')}",
                    "classes": [],
                    "total_matches": 0,
                    "limited_by_max": False
                }
    
            # 第二步:提取和过滤类信息
            histogram = jmap_result.get('histogram', [])
            filtered_classes = self._filter_classes(histogram, class_pattern, use_regex)
            
            # 第三步:应用最大匹配限制
            limited_by_max = False
            if max_matches and len(filtered_classes) > max_matches:
                filtered_classes = filtered_classes[:max_matches]
                limited_by_max = True
    
            # 第四步:构建基础结果
            classes_info = []
            for class_data in filtered_classes:
                class_info = {
                    "class_name": class_data["class_name"],
                    "runtime_info": {
                        "instances": class_data["instances"],
                        "bytes": class_data["bytes"],
                        "rank": len(classes_info) + 1  # 排名基于内存使用顺序
                    }
                }
                
                # 第五步:如果需要详细信息,获取结构信息
                if show_detail:
                    structure_info = self._get_structure_info(
                        class_data["class_name"], 
                        show_field,
                        **kwargs
                    )
                    if structure_info:
                        class_info["structure_info"] = structure_info
    
                classes_info.append(class_info)
    
            return {
                "success": True,
                "classes": classes_info,
                "total_matches": len(classes_info),
                "limited_by_max": limited_by_max,
                "error": None
            }
    
        except Exception as e:
            return {
                "success": False,
                "error": f"Coordinator error: {str(e)}",
                "classes": [],
                "total_matches": 0,
                "limited_by_max": False
            }
  • Parallel helper method for detailed class info: gets base stats then parallelizes javap calls for structure info across classes.
    def get_class_info_parallel(self, pid: str, class_pattern: str = "", 
                               show_detail: bool = False, show_field: bool = False,
                               use_regex: bool = False, max_matches: Optional[int] = None,
                               max_workers: int = 5, **kwargs) -> Dict[str, Any]:
        """并行获取类信息(优化版本)
    
        Args:
            pid: 进程ID
            class_pattern: 类名模式匹配
            show_detail: 是否显示详细信息
            show_field: 是否显示字段信息
            use_regex: 是否使用正则表达式匹配
            max_matches: 最大匹配数量
            max_workers: 最大工作线程数
    
        Returns:
            Dict[str, Any]: 包含类信息的字典
        """
        if not show_detail:
            # 如果不需要详细信息,使用普通版本
            return self.get_class_info(
                pid, class_pattern, show_detail, show_field, 
                use_regex, max_matches, **kwargs
            )
    
        try:
            # 第一步:获取基础信息
            base_result = self.get_class_info(
                pid, class_pattern, False, False, 
                use_regex, max_matches, **kwargs
            )
            
            if not base_result.get('success', False):
                return base_result
    
            classes_info = base_result["classes"]
            
            # 第二步:并行获取结构信息
            if classes_info:
                self._parallel_get_structure_info(
                    classes_info, show_field, max_workers, **kwargs
                )
    
            return {
                "success": True,
                "classes": classes_info,
                "total_matches": base_result["total_matches"],
                "limited_by_max": base_result["limited_by_max"],
                "error": None
            }
    
        except Exception as e:
            return {
                "success": False,
                "error": f"Parallel coordinator error: {str(e)}",
                "classes": [],
                "total_matches": 0,
                "limited_by_max": False
            }
  • Helper for filtering histogram classes by pattern, supporting regex or wildcard matching.
    def _filter_classes(self, histogram: List[Dict[str, Any]], 
                       pattern: str, use_regex: bool) -> List[Dict[str, Any]]:
        """过滤类列表
    
        Args:
            histogram: jmap 直方图数据
            pattern: 过滤模式
            use_regex: 是否使用正则表达式
    
        Returns:
            List[Dict[str, Any]]: 过滤后的类列表
        """
        if not pattern:
            return histogram
    
        filtered = []
        
        try:
            for class_data in histogram:
                class_name = class_data.get("class_name", "")
                
                if use_regex:
                    # 使用正则表达式匹配
                    if re.search(pattern, class_name, re.IGNORECASE):
                        filtered.append(class_data)
                else:
                    # 使用通配符匹配
                    if fnmatch.fnmatch(class_name.lower(), pattern.lower()):
                        filtered.append(class_data)
                        
        except re.error as e:
            # 正则表达式错误,返回原始列表
            return histogram
            
        return filtered
Behavior2/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 mentions the tool uses jmap and javap commands but doesn't describe what happens during execution (e.g., whether it pauses the JVM, requires specific permissions, has performance implications, or returns structured vs unstructured data). The description states it returns a 'Dict' but provides no details about the structure or content of that dictionary. For a tool with 9 parameters and no annotation coverage, this is insufficient.

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 front-loaded with the core purpose, but the parameter documentation section is quite lengthy (9 parameters with detailed explanations). While all parameter information is valuable given the 0% schema coverage, the structure could be more efficient. The description earns its length but isn't optimally concise.

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 the complexity (9 parameters, no annotations, no output schema), the description does a good job explaining parameters but falls short on other aspects. It doesn't explain the tool's behavior during execution, doesn't describe the return value structure despite mentioning a 'Dict', and provides no usage context. The parameter documentation is comprehensive, but other critical context is missing for a tool of this complexity.

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?

The description provides excellent parameter documentation with clear explanations for each of the 9 parameters, including default values, dependencies (show_field requires show_detail=True), and implementation notes about parameters that are '暂未使用' (not yet used). With 0% schema description coverage, the description fully compensates by explaining what each parameter means, how they interact, and their expected formats. The only minor gap is not explaining the format of the returned dictionary.

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 class information) and specifies it uses 'jmap -histo and javap commands' to obtain complete class information. This provides a specific verb ('获取' - get) and resource ('类信息' - class information) with implementation details. However, it doesn't explicitly differentiate from sibling tools like 'decompile_class' or 'search_method', which reduces 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 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. While it mentions using jmap and javap commands, it doesn't explain when this tool is preferred over sibling tools like 'decompile_class', 'search_method', or 'get_jvm_info'. There's no mention of prerequisites, typical use cases, or limitations that would help an agent choose appropriately.

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