save_chat_history
Converts chat conversations into organized Markdown files, capturing messages with timestamps and optional session IDs for easy reference.
Instructions
Save chat history as a Markdown file
Args:
messages: List of chat messages, each containing role and content
conversation_id: Optional conversation ID for file naming
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| conversation_id | No | ||
| messages | Yes |
Implementation Reference
- chat_logger.py:28-55 (handler)The core handler function for the 'save_chat_history' tool. It is decorated with @mcp.tool() which handles registration. Formats chat messages into Markdown and saves them to a file in the 'chat_logs' directory.@mcp.tool() async def save_chat_history(messages: List[Dict[str, Any]], conversation_id: str = None) -> str: """ Save chat history as a Markdown file Args: messages: List of chat messages, each containing role and content conversation_id: Optional conversation ID for file naming """ ensure_logs_directory() # Generate filename timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"chat_logs/chat_{conversation_id}_{timestamp}.md" if conversation_id else f"chat_logs/chat_{timestamp}.md" # Format all messages formatted_content = "# Chat History\n\n" formatted_content += f"Conversation ID: {conversation_id}\n" if conversation_id else "" formatted_content += f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n" for message in messages: formatted_content += format_message(message) # Save file with open(filename, "w", encoding="utf-8") as f: f.write(formatted_content) return f"Chat history has been saved to file: {filename}"
- chat_logger.py:14-26 (helper)Helper function to format individual chat messages into Markdown sections, used within save_chat_history.def format_message(message: Dict[str, Any]) -> str: """Format message into Markdown format""" role = message.get("role", "unknown") content = message.get("content", "") timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") return f""" ### {role.capitalize()} - {timestamp} {content} --- """
- chat_logger.py:9-12 (helper)Helper function to create the 'chat_logs' directory if it doesn't exist, called at the start of save_chat_history.def ensure_logs_directory(): """Ensure the logs directory exists""" if not os.path.exists("chat_logs"): os.makedirs("chat_logs")
- chat_logger.py:28-28 (registration)The @mcp.tool() decorator on the save_chat_history function, which registers the tool with the FastMCP server.@mcp.tool()