Skip to main content
Glama
bpamiri

SQL Server MCP

by bpamiri

export_to_csv

Execute SQL queries and export results directly to CSV files for data analysis, sharing, or backup purposes.

Instructions

Export query results to a CSV file.

Args:
    query: SQL SELECT query to execute
    filename: Output filename (relative or absolute path)
    delimiter: Field delimiter (default: comma)

Returns:
    Dictionary with:
    - status: 'success' or error
    - path: Absolute path to created file
    - row_count: Number of rows exported
    - file_size: Size of created file in bytes

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
filenameYes
delimiterNo,

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The @mcp.tool()-decorated export_to_csv function that executes the tool: validates the SQL SELECT query, executes it, writes results to CSV file with specified delimiter, handles empty results and errors.
    @mcp.tool()
    def export_to_csv(
        query: str,
        filename: str,
        delimiter: str = ",",
    ) -> dict[str, Any]:
        """Export query results to a CSV file.
    
        Args:
            query: SQL SELECT query to execute
            filename: Output filename (relative or absolute path)
            delimiter: Field delimiter (default: comma)
    
        Returns:
            Dictionary with:
            - status: 'success' or error
            - path: Absolute path to created file
            - row_count: Number of rows exported
            - file_size: Size of created file in bytes
        """
        try:
            manager = get_connection_manager()
            config = manager.config
    
            # Create validator
            validator = SQLValidator(
                blocked_commands=config.blocked_commands,
                read_only=True,
                allowed_schemas=config.allowed_schemas if config.allowed_schemas else None,
            )
    
            # Validate query is SELECT-only
            if not validator.is_select_only(query):
                return {
                    "error": "Only SELECT queries are allowed for export",
                    "query": query,
                }
    
            # Check blocked commands
            is_valid, error = validator.validate(query)
            if not is_valid:
                return {"error": error, "query": query}
    
            # Execute query (no row limit for export)
            rows = manager.execute_query(query)
    
            # Prepare output path
            path = Path(filename)
            if not path.is_absolute():
                path = Path.cwd() / path
    
            # Ensure parent directory exists
            path.parent.mkdir(parents=True, exist_ok=True)
    
            # Handle empty results
            if not rows:
                # Create empty file with just a newline
                path.write_text("")
                return {
                    "status": "success",
                    "path": str(path.absolute()),
                    "row_count": 0,
                    "file_size": 0,
                }
    
            # Write CSV file
            with open(path, "w", newline="", encoding="utf-8") as f:
                writer = csv.DictWriter(f, fieldnames=rows[0].keys(), delimiter=delimiter)
                writer.writeheader()
                writer.writerows(rows)
    
            return {
                "status": "success",
                "path": str(path.absolute()),
                "row_count": len(rows),
                "file_size": path.stat().st_size,
            }
    
        except Exception as e:
            logger.error(f"Error exporting to CSV: {e}")
            return {"error": str(e)}
  • Import statement that loads the tools modules (including export.py containing export_to_csv), registering all tools with the MCP server instance.
    from .tools import crud, databases, export, query, stored_procs, tables  # noqa: E402, F401
  • Import of export.py (and other tool modules) within tools package, facilitating registration when tools package is imported.
    from . import crud, databases, export, query, stored_procs, tables
  • Function signature with type annotations and docstring defining input parameters (query, filename, delimiter) and output format for the export_to_csv tool schema.
    def export_to_csv(
        query: str,
        filename: str,
        delimiter: str = ",",
    ) -> dict[str, Any]:
        """Export query results to a CSV file.
    
        Args:
            query: SQL SELECT query to execute
            filename: Output filename (relative or absolute path)
            delimiter: Field delimiter (default: comma)
    
        Returns:
            Dictionary with:
            - status: 'success' or error
            - path: Absolute path to created file
            - row_count: Number of rows exported
            - file_size: Size of created file in bytes
        """
Behavior3/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It describes the action ('Export query results to a CSV file') and return values, but lacks details on permissions, side effects, error handling, or performance implications. It adds basic context but doesn't fully compensate for the absence of annotations.

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 well-structured and front-loaded, starting with the core purpose followed by organized sections for arguments and returns. Each sentence adds value without redundancy, making it efficient and easy to parse. The bulleted lists enhance readability without unnecessary verbosity.

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

Completeness4/5

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

Given the tool's moderate complexity (3 parameters, no annotations, but with an output schema), the description is largely complete. It covers the purpose, parameters, and return values, with the output schema handling return details. However, it lacks behavioral context like error cases or constraints, leaving minor gaps in completeness.

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

Parameters5/5

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

The description adds significant meaning beyond the input schema, which has 0% description coverage. It explains each parameter's purpose: 'query' as an SQL SELECT query, 'filename' as the output path, and 'delimiter' as the field delimiter with a default. This compensates fully for the schema's lack of descriptions, providing clear semantics for all parameters.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with a specific verb ('Export') and resource ('query results to a CSV file'), distinguishing it from siblings like 'export_to_json' and 'execute_query' which handle different formats or operations. It precisely communicates what the tool does without ambiguity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage by specifying 'SQL SELECT query to execute', suggesting it's for exporting query results, but it doesn't explicitly state when to use this tool versus alternatives like 'export_to_json' or 'execute_query'. No guidance is provided on prerequisites, exclusions, or specific contexts, leaving usage somewhat open to interpretation.

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/bpamiri/mssql-mcp'

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