Skip to main content
Glama
es6kr

claude-session-manager

by es6kr

clear_sessions

Delete empty sessions and invalid API key sessions from the Claude Code Session Manager to maintain system efficiency and security.

Instructions

Delete all empty sessions and invalid API key sessions

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
project_nameNoOptional: filter by project name
clear_emptyNoClear empty sessions (default: true)
clear_invalidNoClear invalid API key sessions (default: true)

Implementation Reference

  • The core handler function that implements the logic for the 'clear_sessions' tool. It identifies cleanable sessions (empty or invalid API key) and deletes them, returning a summary of actions taken.
    def clear_sessions(project_name: str | None = None, clear_empty: bool = True, clear_invalid: bool = True) -> dict:
        """Clear empty and invalid sessions."""
        cleanable = find_cleanable_sessions(project_name)
        deleted = {
            'empty_sessions': [],
            'invalid_api_key_sessions': [],
            'total_deleted': 0,
            'errors': []
        }
    
        sessions_to_delete = []
    
        if clear_empty:
            sessions_to_delete.extend([(s, 'empty') for s in cleanable['empty_sessions']])
        if clear_invalid:
            sessions_to_delete.extend([(s, 'invalid_api_key') for s in cleanable['invalid_api_key_sessions']])
    
        for session_info, reason in sessions_to_delete:
            try:
                success = delete_session(session_info['project_name'], session_info['session_id'])
                if success:
                    if reason == 'empty':
                        deleted['empty_sessions'].append(session_info)
                    else:
                        deleted['invalid_api_key_sessions'].append(session_info)
                    deleted['total_deleted'] += 1
            except Exception as e:
                deleted['errors'].append({
                    'session': session_info,
                    'error': str(e)
                })
    
        return deleted
  • Registration of the 'clear_sessions' tool in the MCP list_tools() function, including its name, description, and input schema.
    Tool(
        name="clear_sessions",
        description="Delete all empty sessions and invalid API key sessions",
        inputSchema={
            "type": "object",
            "properties": {
                "project_name": {
                    "type": "string",
                    "description": "Optional: filter by project name"
                },
                "clear_empty": {
                    "type": "boolean",
                    "description": "Clear empty sessions (default: true)"
                },
                "clear_invalid": {
                    "type": "boolean",
                    "description": "Clear invalid API key sessions (default: true)"
                }
            },
            "required": []
        }
    ),
  • Input schema defining the parameters for the clear_sessions tool: optional project_name (string), clear_empty (boolean, default true), clear_invalid (boolean, default true).
    inputSchema={
        "type": "object",
        "properties": {
            "project_name": {
                "type": "string",
                "description": "Optional: filter by project name"
            },
            "clear_empty": {
                "type": "boolean",
                "description": "Clear empty sessions (default: true)"
            },
            "clear_invalid": {
                "type": "boolean",
                "description": "Clear invalid API key sessions (default: true)"
            }
        },
        "required": []
    }
  • Tool dispatch handler in the MCP call_tool() function that extracts arguments and invokes the clear_sessions handler.
    elif name == "clear_sessions":
        project_name = arguments.get("project_name")
        clear_empty = arguments.get("clear_empty", True)
        clear_invalid = arguments.get("clear_invalid", True)
        result = clear_sessions(project_name, clear_empty, clear_invalid)
  • Helper function used by clear_sessions to identify empty and invalid API key sessions across projects.
    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
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations, the description carries full burden but only states what gets deleted without disclosing critical behavioral traits: whether deletion is permanent/reversible, permission requirements, side effects on related data, or confirmation prompts. 'Delete' implies mutation, but details are lacking.

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 with zero waste—every word contributes to understanding the tool's purpose. It's appropriately sized and front-loaded with the core action.

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?

For a destructive tool with no annotations and no output schema, the description is incomplete: it lacks information on return values, error conditions, safety warnings, or system impact. Given the complexity of deletion operations, more context is needed for safe use.

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?

Schema description coverage is 100%, so parameters are fully documented in the schema. The description doesn't add meaning beyond implying filtering by session types, which aligns with schema parameters. Baseline 3 is appropriate as the schema handles parameter 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 specific action ('Delete') and target resources ('all empty sessions and invalid API key sessions'), distinguishing it from siblings like 'delete_session' (singular) and 'preview_cleanup' (preview only). It precisely defines what gets deleted without ambiguity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for cleaning up specific session types but doesn't explicitly state when to use it versus alternatives like 'delete_session' (for individual sessions) or 'preview_cleanup' (for previewing cleanup). No guidance on prerequisites or exclusions is provided.

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