export_csv
Export CSV data from editing sessions to files for sharing, analysis, or backup. Supports multiple formats and encodings to meet different workflow requirements.
Instructions
Export session data to various formats.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| session_id | Yes | ||
| file_path | No | ||
| format | No | csv | |
| encoding | No | utf-8 | |
| index | No |
Implementation Reference
- Core implementation of the export_csv tool handler. Retrieves dataframe from session, handles multiple export formats (CSV, TSV, JSON, Excel, Parquet, HTML, Markdown), writes to file (auto-generates path if not provided), and returns operation result with file details.async def export_csv( session_id: str, file_path: Optional[str] = None, format: ExportFormat = ExportFormat.CSV, encoding: str = "utf-8", index: bool = False, ctx: Context = None ) -> Dict[str, Any]: """Export session data to various formats. Args: session_id: Session ID to export file_path: Optional output file path (auto-generated if not provided) format: Export format (csv, tsv, json, excel, parquet, html, markdown) encoding: Output encoding index: Whether to include index in output ctx: FastMCP context Returns: Operation result with file path """ try: # Get session session_manager = get_session_manager() session = session_manager.get_session(session_id) if not session or session.df is None: return OperationResult( success=False, message="Session not found or no data loaded", error="Invalid session ID" ).model_dump() if ctx: await ctx.info(f"Exporting data in {format.value} format") await ctx.report_progress(0.1, "Preparing export...") # Generate file path if not provided if not file_path: timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"export_{session_id[:8]}_{timestamp}" # Determine extension based on format extensions = { ExportFormat.CSV: ".csv", ExportFormat.TSV: ".tsv", ExportFormat.JSON: ".json", ExportFormat.EXCEL: ".xlsx", ExportFormat.PARQUET: ".parquet", ExportFormat.HTML: ".html", ExportFormat.MARKDOWN: ".md" } file_path = tempfile.gettempdir() + "/" + filename + extensions[format] file_path = Path(file_path) df = session.df if ctx: await ctx.report_progress(0.5, f"Writing {format.value} file...") # Export based on format if format == ExportFormat.CSV: df.to_csv(file_path, encoding=encoding, index=index) elif format == ExportFormat.TSV: df.to_csv(file_path, sep='\t', encoding=encoding, index=index) elif format == ExportFormat.JSON: df.to_json(file_path, orient='records', indent=2) elif format == ExportFormat.EXCEL: df.to_excel(file_path, index=index, engine='openpyxl') elif format == ExportFormat.PARQUET: df.to_parquet(file_path, index=index) elif format == ExportFormat.HTML: df.to_html(file_path, index=index) elif format == ExportFormat.MARKDOWN: df.to_markdown(file_path, index=index) else: return OperationResult( success=False, message=f"Unsupported format: {format}", error="Invalid export format" ).model_dump() # Record operation session.record_operation( OperationType.EXPORT, {"format": format.value, "file_path": str(file_path)} ) if ctx: await ctx.report_progress(1.0, "Export complete!") await ctx.info(f"Exported to {file_path}") return OperationResult( success=True, message=f"Successfully exported data to {format.value}", session_id=session_id, data={ "file_path": str(file_path), "format": format.value, "rows_exported": len(df), "file_size_bytes": file_path.stat().st_size } ).model_dump() except Exception as e: if ctx: await ctx.error(f"Failed to export data: {str(e)}") return OperationResult( success=False, message="Failed to export data", error=str(e) ).model_dump()
- src/csv_editor/server.py:145-158 (registration)MCP tool registration for export_csv using @mcp.tool decorator. Converts string format to ExportFormat enum and delegates to the core handler in io_operations.@mcp.tool async def export_csv( session_id: str, file_path: Optional[str] = None, format: str = "csv", encoding: str = "utf-8", index: bool = False, ctx: Context = None ) -> Dict[str, Any]: """Export session data to various formats.""" from .models import ExportFormat format_enum = ExportFormat(format) return await _export_csv(session_id, file_path, format_enum, encoding, index, ctx)
- Pydantic Enum defining the supported export formats (CSV, TSV, JSON, Excel, Parquet, HTML, Markdown) used for input validation in export_csv tool.class ExportFormat(str, Enum): """Supported export formats.""" CSV = "csv" TSV = "tsv" JSON = "json" EXCEL = "excel" PARQUET = "parquet" HTML = "html" MARKDOWN = "markdown"