Skip to main content
Glama
santoshray02

CSV Editor

by santoshray02

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
NameRequiredDescriptionDefault
session_idYes
file_pathNo
formatNocsv
encodingNoutf-8
indexNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

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()
  • 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"
Behavior2/5

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

With no annotations provided, the description carries full burden but only states the basic action without behavioral details. It doesn't mention whether this creates files, requires write permissions, has rate limits, or what happens on failure. For a tool with 5 parameters and file output, this is inadequate.

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, efficient sentence with no wasted words. It's appropriately sized and front-loaded, though its brevity contributes to gaps in other dimensions.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given 5 parameters with 0% schema coverage, no annotations, and sibling tools like 'export_history', the description is incomplete. It doesn't explain what 'various formats' means, how file_path interacts with output, or behavioral aspects. The output schema helps but doesn't fill these gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so parameters are undocumented in the schema. The description adds no parameter information beyond implying 'session_id' and 'format' from context, leaving 5 parameters largely unexplained. It fails to compensate for the schema gap.

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 ('Export') and resource ('session data'), making the purpose understandable. However, it doesn't distinguish this tool from sibling 'export_history' or specify that it exports to files (vs. returning data directly), which prevents a perfect score.

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?

No guidance is provided on when to use this tool versus alternatives like 'export_history' or other data export methods. The description lacks context about prerequisites, use cases, or exclusions, offering minimal usage direction.

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

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