Skip to main content
Glama
apache

IoTDB MCP Server

Official
by apache

export_table_query

Execute SQL queries on IoTDB databases and export results to CSV or Excel files for data analysis and sharing.

Instructions

Execute a query and export the results to a CSV or Excel file.

Args: query_sql: The SQL query to execute (using TABLE dialect, time using ISO 8601 format, e.g. 2017-11-01T00:08:00.000) format: Export format, either "csv" or "excel" (default: "csv") filename: Optional filename for the exported file. If not provided, a unique filename will be generated.

SQL Syntax: SELECT ⟨select_list⟩ FROM ⟨tables⟩ [WHERE ⟨condition⟩] [GROUP BY ⟨groups⟩] [HAVING ⟨group_filter⟩] [FILL ⟨fill_methods⟩] [ORDER BY ⟨order_expression⟩] [OFFSET ⟨n⟩] [LIMIT ⟨n⟩];

Returns: Information about the exported file and a preview of the data (max 10 rows)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
query_sqlYes
formatNocsv
filenameNo

Implementation Reference

  • The handler function for the export_table_query tool, registered via @mcp.tool(). It handles queries in TABLE dialect, exports results to CSV/Excel using pandas, generates preview, and returns file information.
    @mcp.tool()
    async def export_table_query(query_sql: str, format: str = "csv", filename: str = None) -> list[TextContent]:
        """Execute a query and export the results to a CSV or Excel file.
        
        Args:
            query_sql: The SQL query to execute (using TABLE dialect, time using ISO 8601 format, e.g. 2017-11-01T00:08:00.000)
            format: Export format, either "csv" or "excel" (default: "csv")
            filename: Optional filename for the exported file. If not provided, a unique filename will be generated.
                    
        SQL Syntax:
            SELECT ⟨select_list⟩
              FROM ⟨tables⟩
              [WHERE ⟨condition⟩]
              [GROUP BY ⟨groups⟩]
              [HAVING ⟨group_filter⟩]
              [FILL ⟨fill_methods⟩]
              [ORDER BY ⟨order_expression⟩]
              [OFFSET ⟨n⟩]
              [LIMIT ⟨n⟩];
    
        Returns:
            Information about the exported file and a preview of the data (max 10 rows)
        """
        table_session = None
        try:
            table_session = session_pool.get_session()
            stmt = query_sql.strip().upper()
            
            if stmt.startswith("SELECT") or stmt.startswith("SHOW") or stmt.startswith("DESCRIBE") or stmt.startswith("DESC"):
                # Execute the query
                res = table_session.execute_query_statement(query_sql)
                
                # Create a pandas DataFrame
                df = res.todf()
                
                # Close the session
                table_session.close()
                
                # Generate unique filename with timestamp
                timestamp = int(datetime.datetime.now().timestamp())
                if filename is None:
                    filename = f"dump_{uuid.uuid4().hex[:4]}_{timestamp}"
                filepath = ""
                
                if format.lower() == "csv":
                    if(filename.lower().endswith(".csv")):
                        filename = filename[:-4]
                    filepath = f"{config.export_path}/{filename}.csv"
                    df.to_csv(filepath, index=False)
                elif format.lower() == "excel":
                    if(filename.lower().endswith(".xlsx")):
                        filename = filename[:-5]
                    filepath = f"{config.export_path}/{filename}.xlsx"
                    df.to_excel(filepath, index=False)
                else:
                    raise ValueError("Format must be either 'csv' or 'excel'")
                
                # Generate preview (first 10 rows)
                preview_rows = min(10, len(df))
                preview_data = []
                preview_data.append(",".join(df.columns))  # Header
    
                for i in range(preview_rows):
                    preview_data.append(",".join(map(str, df.iloc[i])))
    
                # Return information
                return [
                    TextContent(
                        type="text",
                        text=f"Query results exported to {filepath}\n\nPreview (first {preview_rows} rows):\n" + "\n".join(preview_data)
                    )
                ]
            else:
                raise ValueError("Only SELECT, SHOW or DESCRIBE queries are allowed for export")
        except Exception as e:
            if table_session:
                table_session.close()
            logger.error(f"Failed to export table query: {str(e)}")
            raise
  • The @mcp.tool() decorator registers the export_table_query function as an MCP tool.
    @mcp.tool()
  • Type hints and docstring define the input schema (query_sql: str, format: str='csv', filename: str=None) and output (list[TextContent]).
    async def export_table_query(query_sql: str, format: str = "csv", filename: str = None) -> list[TextContent]:
Behavior3/5

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

With no annotations provided, the description carries full burden and discloses key behavioral traits: it describes the export process, file format options, filename generation behavior, and preview limitations (max 10 rows). However, it doesn't mention potential side effects like file creation impacts, authentication needs, rate limits, or error handling for invalid SQL.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (Args, SQL Syntax, Returns) and front-loaded purpose statement. While comprehensive, some details like the full SQL syntax example might be excessive if the agent already understands SQL, but overall it's efficiently organized with minimal waste.

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 complexity (query execution + file export), no annotations, no output schema, and 3 parameters, the description provides good coverage: purpose, parameters, SQL syntax, and return information. However, it could better address behavioral aspects like error conditions or file system impacts to be fully complete for this mutation tool.

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?

With 0% schema description coverage, the description fully compensates by providing detailed semantic information for all 3 parameters: query_sql (SQL query with dialect and time format specifics), format (export format options with default), and filename (optional with auto-generation behavior). It adds substantial value beyond the bare schema.

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 specific verbs ('execute a query and export the results') and resources ('to a CSV or Excel file'), distinguishing it from sibling tools like describe_table, list_tables, and read_query which don't mention export functionality. It explicitly combines query execution with file export, making its unique role evident.

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

Usage Guidelines4/5

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

The description provides clear context for when to use this tool (to execute queries and export results to files), but doesn't explicitly state when not to use it or name alternatives among sibling tools. It implies usage for file exports but lacks explicit guidance on choosing between this and read_query for non-export scenarios.

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/apache/iotdb-mcp-server'

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