Skip to main content
Glama
es6kr

claude-session-manager

by es6kr

rename_session

Change session titles by adding descriptive prefixes to organize Claude conversations within project folders.

Instructions

Rename a session by adding a title prefix to the first message

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
project_nameYesProject folder name
session_idYesSession ID (filename without .jsonl)
new_titleYesNew title to add as prefix

Implementation Reference

  • Core handler function that modifies the session's JSONL file by prefixing the new title to the first user message's text content, handling queue-operations and IDE tags appropriately.
    def rename_session(project_name: str, session_id: str, new_title: str) -> bool:
        """Rename a session by adding title prefix to first message."""
        base_path = get_base_path()
        project_path = base_path / project_name
        jsonl_file = project_path / f"{session_id}.jsonl"
    
        if not jsonl_file.exists():
            return False
    
        lines = []
        first_user_idx = -1
        original_message = None
    
        try:
            with open(jsonl_file, 'r', encoding='utf-8') as f:
                for i, line in enumerate(f):
                    lines.append(line)
                    line_stripped = line.strip()
                    if line_stripped:
                        try:
                            entry = json.loads(line_stripped)
                            entry_type = entry.get('type')
    
                            if entry_type == 'queue-operation' and original_message is None:
                                if entry.get('operation') == 'enqueue':
                                    content_arr = entry.get('content', [])
                                    for item in content_arr:
                                        if isinstance(item, dict) and item.get('type') == 'text':
                                            txt = item.get('text', '')
                                            if txt and not txt.strip().startswith('<ide_'):
                                                original_message = txt
                                                break
    
                            if entry_type == 'user' and first_user_idx == -1:
                                first_user_idx = i
    
                        except json.JSONDecodeError:
                            pass
    
            if first_user_idx == -1:
                return False
    
            entry = json.loads(lines[first_user_idx].strip())
            message = entry.get('message', {})
            content_list = message.get('content', [])
    
            if original_message is not None:
                text_idx = -1
                for idx, item in enumerate(content_list):
                    if isinstance(item, dict) and item.get('type') == 'text':
                        text_content = item.get('text', '')
                        if text_content.strip().startswith('<ide_'):
                            continue
                        text_idx = idx
                        break
    
                if text_idx >= 0:
                    content_list[text_idx]['text'] = f"{new_title}\n\n{original_message}"
                else:
                    insert_pos = 0
                    for idx, item in enumerate(content_list):
                        if isinstance(item, dict) and item.get('type') == 'text':
                            text_content = item.get('text', '')
                            if text_content.strip().startswith('<ide_'):
                                insert_pos = idx + 1
                    content_list.insert(insert_pos, {'type': 'text', 'text': f"{new_title}\n\n{original_message}"})
            else:
                for item in content_list:
                    if isinstance(item, dict) and item.get('type') == 'text':
                        old_text = item.get('text', '')
                        old_text = re.sub(r'^[^\n]+\n\n', '', old_text)
                        item['text'] = f"{new_title}\n\n{old_text}"
                        break
    
            entry['message']['content'] = content_list
            lines[first_user_idx] = json.dumps(entry, ensure_ascii=False) + '\n'
    
            with open(jsonl_file, 'w', encoding='utf-8') as f:
                f.writelines(lines)
    
            return True
    
        except Exception:
            return False
  • Registers the 'rename_session' tool with the MCP server, defining its name, description, and input schema.
    Tool(
        name="rename_session",
        description="Rename a session by adding a title prefix to the first message",
        inputSchema={
            "type": "object",
            "properties": {
                "project_name": {
                    "type": "string",
                    "description": "Project folder name"
                },
                "session_id": {
                    "type": "string",
                    "description": "Session ID (filename without .jsonl)"
                },
                "new_title": {
                    "type": "string",
                    "description": "New title to add as prefix"
                }
            },
            "required": ["project_name", "session_id", "new_title"]
        }
    ),
  • MCP tool dispatcher branch that extracts arguments and calls the rename_session handler function.
    elif name == "rename_session":
        project_name = arguments.get("project_name", "")
        session_id = arguments.get("session_id", "")
        new_title = arguments.get("new_title", "")
        success = rename_session(project_name, session_id, new_title)
        result = {"success": success, "message": "Session renamed" if success else "Failed to rename session"}
  • Helper function used in listing sessions to parse titles from session files, related to how titles are handled.
    def parse_session_summary(file_path: Path) -> dict | None:
        """Parse session file for summary info."""
        session_id = file_path.stem
        info = {
            "session_id": session_id,
            "title": f"Session {session_id[:8]}",
            "message_count": 0,
            "created_at": None,
            "updated_at": None,
        }
    
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                first_user_content = None
                for line in f:
                    line = line.strip()
                    if not line:
                        continue
                    try:
                        entry = json.loads(line)
                        entry_type = entry.get('type')
    
                        if entry_type in ('user', 'assistant'):
                            info["message_count"] += 1
                            timestamp = entry.get('timestamp', '')
                            if timestamp:
                                if not info["created_at"] or timestamp < info["created_at"]:
                                    info["created_at"] = timestamp
                                if not info["updated_at"] or timestamp > info["updated_at"]:
                                    info["updated_at"] = timestamp
    
                            if entry_type == 'user' and first_user_content is None:
                                message = entry.get('message', {})
                                content_list = message.get('content', [])
                                for item in content_list:
                                    if isinstance(item, dict) and item.get('type') == 'text':
                                        text = item.get('text', '').strip()
                                        text = re.sub(r'<ide_[^>]*>.*?</ide_[^>]*>', '', text, flags=re.DOTALL).strip()
                                        if text:
                                            first_user_content = text
                                            break
                    except json.JSONDecodeError:
                        continue
    
                if first_user_content:
                    if '\n\n' in first_user_content:
                        info["title"] = first_user_content.split('\n\n')[0][:100]
                    elif '\n' in first_user_content:
                        info["title"] = first_user_content.split('\n')[0][:100]
                    else:
                        info["title"] = first_user_content[:100]
    
        except Exception:
            return None
    
        return info if info["message_count"] > 0 else None
    
    
    def delete_session(project_name: str, session_id: str) -> bool:
        """Delete a session (move to .bak folder, or delete if empty)."""
        base_path = get_base_path()
        project_path = base_path / project_name
        jsonl_file = project_path / f"{session_id}.jsonl"
    
        if not jsonl_file.exists():
            return False
    
        # If file is empty (0 bytes), just delete it without backing up
        if jsonl_file.stat().st_size == 0:
            jsonl_file.unlink()
            return True
    
        backup_dir = base_path / ".bak"
        backup_dir.mkdir(exist_ok=True)
        backup_file = backup_dir / f"{project_name}_{session_id}.jsonl"
        jsonl_file.rename(backup_file)
        return True
    
    
    def rename_session(project_name: str, session_id: str, new_title: str) -> bool:
        """Rename a session by adding title prefix to first message."""
        base_path = get_base_path()
        project_path = base_path / project_name
        jsonl_file = project_path / f"{session_id}.jsonl"
    
        if not jsonl_file.exists():
            return False
    
        lines = []
        first_user_idx = -1
        original_message = None
    
        try:
            with open(jsonl_file, 'r', encoding='utf-8') as f:
                for i, line in enumerate(f):
                    lines.append(line)
                    line_stripped = line.strip()
                    if line_stripped:
                        try:
                            entry = json.loads(line_stripped)
                            entry_type = entry.get('type')
    
                            if entry_type == 'queue-operation' and original_message is None:
                                if entry.get('operation') == 'enqueue':
                                    content_arr = entry.get('content', [])
                                    for item in content_arr:
                                        if isinstance(item, dict) and item.get('type') == 'text':
                                            txt = item.get('text', '')
                                            if txt and not txt.strip().startswith('<ide_'):
                                                original_message = txt
                                                break
    
                            if entry_type == 'user' and first_user_idx == -1:
                                first_user_idx = i
    
                        except json.JSONDecodeError:
                            pass
    
            if first_user_idx == -1:
                return False
    
            entry = json.loads(lines[first_user_idx].strip())
            message = entry.get('message', {})
            content_list = message.get('content', [])
    
            if original_message is not None:
                text_idx = -1
                for idx, item in enumerate(content_list):
                    if isinstance(item, dict) and item.get('type') == 'text':
                        text_content = item.get('text', '')
                        if text_content.strip().startswith('<ide_'):
                            continue
                        text_idx = idx
                        break
    
                if text_idx >= 0:
                    content_list[text_idx]['text'] = f"{new_title}\n\n{original_message}"
                else:
                    insert_pos = 0
                    for idx, item in enumerate(content_list):
                        if isinstance(item, dict) and item.get('type') == 'text':
                            text_content = item.get('text', '')
                            if text_content.strip().startswith('<ide_'):
                                insert_pos = idx + 1
                    content_list.insert(insert_pos, {'type': 'text', 'text': f"{new_title}\n\n{original_message}"})
            else:
                for item in content_list:
                    if isinstance(item, dict) and item.get('type') == 'text':
                        old_text = item.get('text', '')
                        old_text = re.sub(r'^[^\n]+\n\n', '', old_text)
                        item['text'] = f"{new_title}\n\n{old_text}"
                        break
    
            entry['message']['content'] = content_list
            lines[first_user_idx] = json.dumps(entry, ensure_ascii=False) + '\n'
    
            with open(jsonl_file, 'w', encoding='utf-8') as f:
                f.writelines(lines)
    
            return True
    
        except Exception:
            return False
Behavior2/5

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

No annotations are provided, so the description carries full burden. It mentions 'adding a title prefix to the first message', which implies a mutation but doesn't disclose permissions needed, whether changes are reversible, or any side effects. For a mutation tool with zero 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.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, clear sentence with zero waste, front-loading the core action efficiently. It's appropriately sized for the tool's complexity.

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 no annotations and no output schema, the description is minimal but covers the basic purpose. It's adequate for a simple rename operation but lacks details on behavior, error cases, or output, leaving gaps in completeness for a mutation tool.

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 the schema already documents all three parameters. The description adds no additional meaning beyond what the schema provides, such as explaining how 'new_title' interacts with the first message. Baseline 3 is appropriate when schema does the heavy lifting.

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 verb 'rename' and resource 'session' with specific action 'adding a title prefix to the first message', which is specific and actionable. However, it doesn't explicitly distinguish from sibling tools like 'delete_session' or 'clear_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 'delete_session' or 'clear_sessions', nor does it mention prerequisites or context for renaming sessions. It's a basic statement of function without 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