Skip to main content
Glama
marekrost

mcp-server-spreadsheet

sql_execute

Execute SQL statements to insert, update, or delete spreadsheet data directly within files. Automatically writes changes back to maintain data integrity.

Instructions

Execute a mutating SQL statement and write changes back to the file.

Supports INSERT INTO (adds rows), UPDATE (modifies cell values), and DELETE FROM (removes rows). The target sheet is determined from the SQL statement. After execution, the modified table is written back to the file atomically. Returns {"affected_rows": N}.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
fileYesPath to the spreadsheet file
sqlYesSQL mutation statement to execute: INSERT INTO, UPDATE, or DELETE FROM. Sheet names are table names. Example: UPDATE Sales SET status = 'Closed' WHERE quarter = 'Q1' AND revenue < 1000
header_rowNo1-based row number containing column headers. Defaults to 1.

Implementation Reference

  • The `sql_execute` function is decorated with `@mcp.tool()` and implements the logic for executing SQL mutations (INSERT, UPDATE, DELETE) on spreadsheet files by updating the underlying sheet and saving the file.
    @mcp.tool()
    def sql_execute(
        file: Annotated[str, Field(description="Path to the spreadsheet file")],
        sql: Annotated[str, Field(description=(
            "SQL mutation statement to execute: INSERT INTO, UPDATE, or "
            "DELETE FROM. Sheet names are table names. "
            "Example: UPDATE Sales SET status = 'Closed' "
            "WHERE quarter = 'Q1' AND revenue < 1000"
        ))],
        header_row: Annotated[int, Field(description="1-based row number containing column headers. Defaults to 1.")] = 1,
    ) -> dict:
        """Execute a mutating SQL statement and write changes back to the file.
    
        Supports INSERT INTO (adds rows), UPDATE (modifies cell values), and
        DELETE FROM (removes rows). The target sheet is determined from the
        SQL statement. After execution, the modified table is written back to
        the file atomically. Returns {"affected_rows": N}.
        """
        sql_stripped = sql.strip().rstrip(";")
        target_table = _extract_target_table(sql_stripped)
    
        wb = load_workbook(file)
        ws = _resolve_sheet(wb, target_table)
    
        headers, _ = _sheet_to_records(ws, header_row)
        if not headers:
            raise ValueError(f"Sheet {target_table!r} has no headers at row {header_row}")
        headers = _dedup_headers(headers)
        num_cols = len(headers)
    
        conn = _load_sheets_to_duckdb(wb, header_row)
    
        result = conn.execute(sql_stripped)
        affected = result.fetchone()[0]
    
        col_list = ", ".join(f'"{h}"' for h in headers)
        new_rows = conn.execute(f'SELECT {col_list} FROM "{target_table}"').fetchall()
    
        old_max_row = ws.max_row or header_row
        for r in range(header_row + 1, old_max_row + 1):
            for c in range(1, num_cols + 1):
                ws.set_cell(r, c, None)
    
        for r_idx, row in enumerate(new_rows):
            for c_idx, val in enumerate(row):
                ws.set_cell(header_row + 1 + r_idx, c_idx + 1, val)
    
        wb.save(file)
        return {"affected_rows": affected}
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 does well by specifying that changes are written back 'atomically,' describing the return format ('Returns {"affected_rows": N}'), and clarifying that sheet names serve as table names in SQL. It could improve by mentioning potential side effects or error conditions.

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 efficiently structured with four sentences that each add value: states purpose, lists supported operations, explains execution behavior, and specifies return format. It's front-loaded with the core functionality and avoids any redundant information.

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?

For a mutating tool with no annotations and no output schema, the description does well by explaining the atomic write-back and return format. However, it could provide more context about error handling, transaction behavior, or limitations (e.g., SQL dialect support). Given the complexity of SQL execution, there's room for slightly more completeness.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description doesn't add significant meaning beyond what's in the schema descriptions (e.g., the sql parameter example is already in the schema). It meets the baseline for high schema coverage but doesn't enhance parameter understanding.

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 mutating SQL statement and write changes back to the file') and distinguishes it from sibling tools like sql_query (which presumably doesn't mutate) and other spreadsheet manipulation tools. It explicitly mentions the supported SQL operations (INSERT, UPDATE, DELETE).

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 ('Execute a mutating SQL statement') and implicitly distinguishes it from sql_query (which is likely for read-only queries). However, it doesn't explicitly state when NOT to use it or mention specific alternatives among the many sibling tools beyond the general distinction.

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/marekrost/mcp-server-spreadsheet'

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