Skip to main content
Glama

export_csv

Export session data from the CSV editor into CSV or other formats by specifying session ID, file path, encoding, and indexing preferences for streamlined data sharing and storage.

Instructions

Export session data to various formats.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
encodingNoutf-8
file_pathNo
formatNocsv
indexNo
session_idYes

Implementation Reference

  • Core handler function that implements the export_csv tool logic. Retrieves session data, generates output path if needed, exports using pandas to various formats (CSV, TSV, JSON, Excel, Parquet, HTML, Markdown), records the operation, and returns result.
    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()
  • Registers the export_csv tool with the FastMCP server using the @mcp.tool decorator. This is the entry point called by MCP clients, which delegates to the core implementation.
    @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)
  • Enum defining the supported export formats used by the export_csv tool for input validation and format selection.
    class ExportFormat(str, Enum): """Supported export formats.""" CSV = "csv" TSV = "tsv" JSON = "json" EXCEL = "excel" PARQUET = "parquet" HTML = "html" MARKDOWN = "markdown"

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/santoshray02/csv-editor'

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