Skip to main content
Glama
bpamiri

SQL Server MCP

by bpamiri

export_to_json

Execute SQL SELECT queries and export the results directly to JSON files for data analysis, sharing, or integration with other applications.

Instructions

Export query results to a JSON file.

Args:
    query: SQL SELECT query to execute
    filename: Output filename (relative or absolute path)

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

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The export_to_json tool handler, including decorator for MCP registration, input validation, SQL execution, and JSON file export logic.
    @mcp.tool()
    def export_to_json(query: str, filename: str) -> dict[str, Any]:
        """Export query results to a JSON file.
    
        Args:
            query: SQL SELECT query to execute
            filename: Output filename (relative or absolute path)
    
        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)
    
            # Write JSON file
            with open(path, "w", encoding="utf-8") as f:
                json.dump(rows, f, indent=2, default=str)
    
            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 JSON: {e}")
            return {"error": str(e)}
Behavior4/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 effectively describes key behaviors: it creates a file (implied mutation/write operation), specifies the output format (JSON), and details the return structure. It doesn't mention permissions, rate limits, or error handling beyond status, but covers core functionality well.

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 with the core purpose in the first sentence, followed by organized sections for Args and Returns. Every sentence adds value without redundancy, making it efficient and easy to parse.

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

Completeness5/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 (2 parameters, no annotations, but with an output schema), the description is complete enough. It explains the purpose, parameters, and return values in detail. Since an output schema exists, the description doesn't need to redundantly explain return values, and it adequately covers the tool's scope and behavior.

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 schema description coverage is 0%, so the description must compensate fully. It adds significant meaning beyond the basic schema by explaining that 'query' is an 'SQL SELECT query to execute' and 'filename' is the 'Output filename (relative or absolute path)', clarifying usage and context that the schema alone lacks.

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 specific action ('Export query results to a JSON file') with the resource ('query results'), distinguishing it from siblings like export_to_csv (different format) and execute_query (no file output). It precisely defines the tool's function 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 through the mention of 'SQL SELECT query' and 'query results', suggesting it's for exporting data from database queries. However, it lacks explicit guidance on when to use this tool versus alternatives like export_to_csv or execute_query, nor does it mention prerequisites or exclusions.

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