Skip to main content
Glama
es6kr

claude-session-manager

by es6kr

preview_cleanup

Preview empty and invalid API key sessions before cleanup in Claude Code Session Manager to maintain system efficiency.

Instructions

Preview sessions that would be cleaned (empty and invalid API key sessions)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
project_nameNoOptional: filter by project name

Implementation Reference

  • Main handler function implementing the preview_cleanup tool logic: scans Claude projects for empty or invalid API key sessions and compiles a preview list.
    def find_cleanable_sessions(project_name: str | None = None) -> dict:
        """Find sessions that can be cleaned."""
        base_path = get_base_path()
        result = {
            'empty_sessions': [],
            'invalid_api_key_sessions': [],
            'total_count': 0
        }
    
        if project_name:
            project_dirs = [base_path / project_name]
        else:
            project_dirs = [d for d in base_path.iterdir() if d.is_dir() and not d.name.startswith('.')]
    
        for project_path in project_dirs:
            if not project_path.exists():
                continue
    
            for jsonl_file in project_path.glob("*.jsonl"):
                if jsonl_file.name.startswith("agent-"):
                    continue
    
                session_id = jsonl_file.stem
                status = check_session_status(jsonl_file)
    
                session_info = {
                    'project_name': project_path.name,
                    'session_id': session_id,
                    'file_size': status['file_size']
                }
    
                if status['has_invalid_api_key'] and not status['has_messages']:
                    result['invalid_api_key_sessions'].append(session_info)
                elif status['is_empty'] or status['file_size'] == 0:
                    result['empty_sessions'].append(session_info)
    
        result['total_count'] = len(result['empty_sessions']) + len(result['invalid_api_key_sessions'])
        return result
  • Registers the 'preview_cleanup' tool with the MCP server inside the list_tools handler, including its schema.
    Tool(
        name="preview_cleanup",
        description="Preview sessions that would be cleaned (empty and invalid API key sessions)",
        inputSchema={
            "type": "object",
            "properties": {
                "project_name": {
                    "type": "string",
                    "description": "Optional: filter by project name"
                }
            },
            "required": []
        }
    ),
  • Input schema defining the optional 'project_name' parameter for the preview_cleanup tool.
    inputSchema={
        "type": "object",
        "properties": {
            "project_name": {
                "type": "string",
                "description": "Optional: filter by project name"
            }
        },
        "required": []
    }
  • Helper function called by the handler to analyze individual session files for emptiness, message presence, and invalid API key indicators.
    def check_session_status(file_path: Path) -> dict:
        """Check session file status."""
        status = {
            'is_empty': True,
            'has_invalid_api_key': False,
            'has_messages': False,
            'file_size': file_path.stat().st_size if file_path.exists() else 0
        }
    
        if not file_path.exists() or status['file_size'] == 0:
            return status
    
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if not line:
                        continue
                    try:
                        entry = json.loads(line)
                        entry_type = entry.get('type')
    
                        if entry_type == 'summary':
                            summary = entry.get('summary', '')
                            if 'Invalid API key' in summary:
                                status['has_invalid_api_key'] = True
                            else:
                                # Summary가 있다는 것은 요약된 메시지가 있다는 의미
                                status['is_empty'] = False
                                status['has_messages'] = True
    
                        if entry_type in ('user', 'assistant'):
                            status['is_empty'] = False
                            status['has_messages'] = True
    
                    except json.JSONDecodeError:
                        continue
        except Exception:
            pass
    
        return status
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 indicates this is a read-only preview operation (implied by 'preview'), but doesn't disclose critical details like whether it requires authentication, has rate limits, returns paginated results, or what the output format looks like. This is inadequate for a tool with zero annotation coverage.

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 a single, efficient sentence that directly states the tool's purpose with no wasted words. It's appropriately sized and front-loaded, making it easy for an agent to parse quickly.

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

Completeness2/5

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

Given the complexity of session management tools, no annotations, and no output schema, the description is incomplete. It doesn't explain what 'preview' entails (e.g., returns a list, counts, or details), how sessions are identified as 'empty' or 'invalid', or any error conditions. This leaves significant gaps for an agent to operate effectively.

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 schema description coverage is 100%, with the single parameter 'project_name' documented as 'Optional: filter by project name'. The description doesn't add any meaning beyond this, such as explaining how filtering works or providing examples. With high schema coverage, the baseline score of 3 is appropriate.

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 what the tool does ('Preview sessions that would be cleaned') with specific criteria ('empty and invalid API key sessions'), which is a specific verb+resource combination. However, it doesn't explicitly distinguish itself from sibling tools like 'clear_sessions' or 'list_sessions', which would require a 5.

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 like 'clear_sessions' or 'list_sessions'. It implies a preview function but doesn't specify prerequisites, timing, or exclusions, leaving the agent without clear usage context.

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/es6kr/claude-session-manager'

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