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

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