Skip to main content
Glama

summarize_chat

Transform chat conversations into structured markdown summaries and save them as organized files. Supports brief, detailed, or bullet-point styles while optionally including full history.

Instructions

Summarize chat history and save it as a markdown file.

Args: chat_history: The chat conversation text to summarize title: Optional title for the summary (will be used in filename) summary_style: Style of summary - 'brief', 'detailed', or 'bullet_points' include_full_history: Whether to include the full chat history in the summary file (default: True) create_separate_full_history: Whether to create a separate file with just the full history (default: False)

Returns: Path to the created summary file and preview of the summary

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
chat_historyYes
titleNo
summary_styleNodetailed
include_full_historyNo
create_separate_full_historyNo

Implementation Reference

  • main.py:127-325 (handler)
    The core handler function for the 'summarize_chat' tool. Decorated with @mcp.tool() for registration. Implements chat summarization logic: extracts code blocks and final solutions, generates structured markdown summaries, handles different styles and sizes, saves to notes directory, and returns file path with preview.
    @mcp.tool() def summarize_chat( chat_history: str, title: str = None, summary_style: str = "detailed", include_full_history: bool = True, create_separate_full_history: bool = False ) -> str: """ Summarize chat history and save it as a markdown file. Args: chat_history: The chat conversation text to summarize title: Optional title for the summary (will be used in filename) summary_style: Style of summary - 'brief', 'detailed', or 'bullet_points' include_full_history: Whether to include the full chat history in the summary file (default: True) create_separate_full_history: Whether to create a separate file with just the full history (default: False) Returns: Path to the created summary file and preview of the summary """ try: # Ensure notes directory exists if not ensure_notes_directory(): return "Error: Could not create or access notes directory" # Detect code sections and final solutions code_blocks = extract_code_blocks(chat_history) final_solutions = identify_final_solutions(chat_history, code_blocks) has_code = len(code_blocks) > 0 has_solutions = len(final_solutions) > 0 # Generate summary based on style with code awareness if summary_style == "brief": if has_code: summary_prompt = "Provide a brief 2-3 sentence summary of the key points from this conversation. Include any final code solutions or important code snippets that solve the main problem." else: summary_prompt = "Provide a brief 2-3 sentence summary of the key points from this conversation." elif summary_style == "bullet_points": if has_code: summary_prompt = "Create a bullet-point summary of the main topics and decisions from this conversation. Include a section for final code solutions and important code snippets." else: summary_prompt = "Create a bullet-point summary of the main topics and decisions from this conversation." else: # detailed if has_code: summary_prompt = "Provide a detailed summary including main topics discussed, key decisions made, and important insights from this conversation. Pay special attention to final code solutions, working code examples, and important code snippets that solve the main problems discussed." else: summary_prompt = "Provide a detailed summary including main topics discussed, key decisions made, and important insights from this conversation." # Create summary content (this would typically use an AI model) # For now, we'll create a structured summary lines = chat_history.split('\n') message_count = len([line for line in lines if line.strip()]) # Generate filename filename = generate_filename(title) filepath = NOTES_DIR / filename # Determine content organization based on size history_size_mb = len(chat_history) / (1024 * 1024) is_large_history = history_size_mb > 1 # Consider >1MB as large # Create code solutions section if found code_solutions_section = "" if has_solutions: code_solutions_section = "\n### 💻 Final Code Solutions\n\n" for i, solution in enumerate(final_solutions, 1): lang = solution.get("language", "text") code = solution["code"] solution_type = "Code Block" if solution["type"] == "block" else "Inline Code" code_solutions_section += f"**Solution {i} ({solution_type} - {lang}):**\n" code_solutions_section += f"```{lang}\n{code}\n```\n\n" elif has_code and not has_solutions: # Include all code blocks if no specific solutions were identified code_solutions_section = "\n### 📝 Code Snippets\n\n" for i, code_block in enumerate(code_blocks[:5], 1): # Limit to first 5 blocks lang = code_block.get("language", "text") code = code_block["code"] code_type = "Code Block" if code_block["type"] == "block" else "Inline Code" code_solutions_section += f"**Code {i} ({code_type} - {lang}):**\n" code_solutions_section += f"```{lang}\n{code}\n```\n\n" # Create summary section summary_section = f"""## Summary {summary_prompt} ### Key Points - Total messages in conversation: {message_count} - Conversation length: {len(chat_history):,} characters ({history_size_mb:.2f} MB) - Large history: {'Yes' if is_large_history else 'No'} - Code blocks found: {len(code_blocks)} - Final solutions identified: {len(final_solutions)} {code_solutions_section}""" # Create markdown content based on options if include_full_history: if is_large_history: # For large histories, put summary first, then full history in collapsible section markdown_content = f"""# Chat Summary: {title or 'Untitled'} **Date:** {datetime.now().strftime("%Y-%m-%d %H:%M:%S")} **Messages:** {message_count} **Summary Style:** {summary_style.replace('_', ' ').title()} {summary_section} ## Full Chat History <details> <summary>Click to expand full conversation ({history_size_mb:.2f} MB)</summary> ``` {chat_history} ``` </details> --- *Generated by Chat History Summarizer MCP Server* """ else: # For smaller histories, include everything normally markdown_content = f"""# Chat Summary: {title or 'Untitled'} **Date:** {datetime.now().strftime("%Y-%m-%d %H:%M:%S")} **Messages:** {message_count} **Summary Style:** {summary_style.replace('_', ' ').title()} {summary_section} ## Original Chat History ``` {chat_history} ``` --- *Generated by Chat History Summarizer MCP Server* """ else: # Summary only markdown_content = f"""# Chat Summary: {title or 'Untitled'} **Date:** {datetime.now().strftime("%Y-%m-%d %H:%M:%S")} **Messages:** {message_count} **Summary Style:** {summary_style.replace('_', ' ').title()} {summary_section} > **Note:** Full chat history not included in this summary file. > Original conversation length: {len(chat_history):,} characters ({history_size_mb:.2f} MB) --- *Generated by Chat History Summarizer MCP Server* """ # Save main summary file with open(filepath, 'w', encoding='utf-8') as f: f.write(markdown_content) result_message = f"Summary saved to: {filepath}" # Create separate full history file if requested if create_separate_full_history: history_filename = filepath.stem.replace("chat_summary_", "chat_full_") + ".md" history_filepath = NOTES_DIR / history_filename full_history_content = f"""# Full Chat History: {title or 'Untitled'} **Date:** {datetime.now().strftime("%Y-%m-%d %H:%M:%S")} **Messages:** {message_count} **Size:** {len(chat_history):,} characters ({history_size_mb:.2f} MB) ## Complete Conversation ``` {chat_history} ``` --- *Full chat history preserved by Chat History Summarizer MCP Server* """ with open(history_filepath, 'w', encoding='utf-8') as f: f.write(full_history_content) result_message += f"\nFull history saved separately to: {history_filepath}" preview = markdown_content[:500] + "..." if len(markdown_content) > 500 else markdown_content return f"{result_message}\n\nPreview:\n{preview}" except Exception as e: return f"Error creating summary: {str(e)}"
  • main.py:127-127 (registration)
    The @mcp.tool() decorator registers the summarize_chat function as an MCP tool, making it available under the name 'summarize_chat'.
    @mcp.tool()
  • Type hints and parameter definitions serve as the input schema for the tool, including docstring describing args and return.
    def summarize_chat( chat_history: str, title: str = None, summary_style: str = "detailed", include_full_history: bool = True, create_separate_full_history: bool = False ) -> str:
  • main.py:50-81 (helper)
    Helper function used by summarize_chat to extract code blocks from chat history.
    def extract_code_blocks(text: str) -> List[Dict[str, str]]: """Extract code blocks from chat text""" import re # Pattern to match code blocks (both ``` and single backticks) code_block_pattern = r'```(\w+)?\n(.*?)\n```|`([^`]+)`' code_blocks = [] # Find all code blocks matches = re.findall(code_block_pattern, text, re.DOTALL) for match in matches: if match[0] or match[1]: # Triple backtick code block language = match[0] if match[0] else "text" code = match[1].strip() if code: # Only include non-empty code blocks code_blocks.append({ "language": language, "code": code, "type": "block" }) elif match[2]: # Inline code code = match[2].strip() if code: code_blocks.append({ "language": "text", "code": code, "type": "inline" }) return code_blocks
  • Helper function used by summarize_chat to identify final code solutions in the chat.
    def identify_final_solutions(chat_history: str, code_blocks: List[Dict[str, str]]) -> List[Dict[str, str]]: """Identify code blocks that appear to be final solutions""" if not code_blocks: return [] final_solutions = [] # Keywords that suggest a final solution solution_keywords = [ "final", "solution", "working", "complete", "fixed", "resolved", "here's the", "this works", "final version", "complete code", "final implementation", "working example", "solved" ] # Look for code blocks that appear near solution keywords lines = chat_history.split('\n') for i, code_block in enumerate(code_blocks): # Check if this code block appears near solution keywords code_context = "" # Find the code block in the original text to get context code_start_idx = chat_history.find(code_block["code"]) if code_start_idx != -1: # Get 200 characters before and after the code block for context context_start = max(0, code_start_idx - 200) context_end = min(len(chat_history), code_start_idx + len(code_block["code"]) + 200) code_context = chat_history[context_start:context_end].lower() # Check if any solution keywords appear in the context is_solution = any(keyword in code_context for keyword in solution_keywords) # Also consider code blocks that appear later in the conversation as more likely to be solutions position_weight = (code_start_idx / len(chat_history)) * 100 # Percentage through conversation if is_solution or position_weight > 70: # If it's marked as solution or appears in last 30% of conversation final_solutions.append({ **code_block, "context": code_context[:100] + "..." if len(code_context) > 100 else code_context, "position_weight": position_weight }) return final_solutions

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/RalphLi213/ide-chat-summarizer-mcp'

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