Skip to main content
Glama
bpamiri

SQL Server MCP

by bpamiri

delete_row

Remove specific database records by primary key value from SQL Server tables to maintain data integrity and manage storage.

Instructions

Delete a row by primary key.

Args:
    table: Table name (can include schema: 'dbo.Users' or 'Users')
    id: Primary key value of the row to delete

Returns:
    Dictionary with:
    - status: 'deleted' or error
    - table: Full table name
    - id: The deleted row's ID
    - rows_affected: Number of rows deleted (should be 1)

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
tableYes
idYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The main handler function for the 'delete_row' tool, decorated with @mcp.tool() for automatic registration with the MCP server. It deletes a specified row from a table using its primary key, handles errors, checks read-only mode, and returns a status dictionary.
    @mcp.tool()
    def delete_row(table: str, id: Any) -> dict[str, Any]:
        """Delete a row by primary key.
    
        Args:
            table: Table name (can include schema: 'dbo.Users' or 'Users')
            id: Primary key value of the row to delete
    
        Returns:
            Dictionary with:
            - status: 'deleted' or error
            - table: Full table name
            - id: The deleted row's ID
            - rows_affected: Number of rows deleted (should be 1)
        """
        try:
            manager = get_connection_manager()
            config = manager.config
    
            # Check read-only mode
            if config.read_only:
                return {"error": "Delete operations disabled in read-only mode"}
    
            schema, table_name = parse_table_name(table)
    
            # Get primary key column
            pk_cols = _get_primary_key_columns(schema, table_name)
            if not pk_cols:
                return {"error": f"No primary key found for table {schema}.{table_name}"}
    
            # Build DELETE statement
            query = f"DELETE FROM [{schema}].[{table_name}] WHERE [{pk_cols[0]}] = %s"
    
            affected = manager.execute_non_query(query, (id,))
    
            if affected == 0:
                return {
                    "error": f"No row found with {pk_cols[0]} = {id}",
                    "table": f"{schema}.{table_name}",
                }
    
            return {
                "status": "deleted",
                "table": f"{schema}.{table_name}",
                "id": id,
                "rows_affected": affected,
            }
    
        except QueryError as e:
            logger.error(f"Error deleting row from {table}: {e}")
            return {"error": str(e)}
        except Exception as e:
            logger.error(f"Unexpected error deleting row from {table}: {e}")
            return {"error": str(e)}
  • Helper function used by delete_row (and other CRUD tools) to retrieve the primary key column names for a given table, essential for constructing the WHERE clause in the DELETE statement.
    def _get_primary_key_columns(schema: str, table: str) -> list[str]:
        """Get primary key column(s) for a table.
    
        Args:
            schema: Schema name
            table: Table name
    
        Returns:
            List of primary key column names
        """
        manager = get_connection_manager()
    
        query = """
            SELECT c.COLUMN_NAME
            FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc
            JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
                ON tc.CONSTRAINT_NAME = c.CONSTRAINT_NAME
                AND tc.TABLE_SCHEMA = c.TABLE_SCHEMA
                AND tc.TABLE_NAME = c.TABLE_NAME
            WHERE tc.TABLE_SCHEMA = %s
                AND tc.TABLE_NAME = %s
                AND tc.CONSTRAINT_TYPE = 'PRIMARY KEY'
            ORDER BY c.ORDINAL_POSITION
        """
        rows = manager.execute_query(query, (schema, table))
        return [row["COLUMN_NAME"] for row in rows]
  • The __init__.py file imports the crud module, which triggers the execution of the @mcp.tool() decorators in crud.py, thereby registering the delete_row tool with the MCP server.
    from . import crud, databases, export, query, stored_procs, tables
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 ('Delete') and return values, including potential error status and rows affected, which adds context beyond basic functionality. However, it lacks details on permissions, side effects, or constraints like transaction handling or rate limits.

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, followed by clear sections for Args and Returns. Each sentence earns its place by providing necessary information 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.

Completeness4/5

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

Given the complexity of a deletion tool with no annotations, the description is mostly complete: it covers purpose, parameters, and return values (with an output schema present). However, it could improve by addressing potential risks or prerequisites, such as confirmation steps or dependencies, to fully compensate for the lack of annotations.

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% coverage. It explains that 'table' can include schema (e.g., 'dbo.Users' or 'Users') and clarifies that 'id' is the 'Primary key value of the row to delete,' providing essential context not present in the schema's bare titles.

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 ('Delete a row by primary key') and identifies the resource ('row'), distinguishing it from sibling tools like 'update_row' or 'insert_row' by focusing on deletion rather than modification or creation.

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 implies usage by specifying 'by primary key,' which suggests when to use this tool (for targeted deletion) versus alternatives like 'execute_query' for more complex operations. However, it does not explicitly state when not to use it or name specific alternatives, such as 'update_row' for modifications instead of deletions.

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/pymssql-mcp'

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