Skip to main content
Glama
sharansahu

MCP SQL Agent

by sharansahu

query_data

Execute SQL queries safely with full schema awareness to interact with databases. Use get_schema() to analyze the database structure before querying.

Instructions

Execute SQL queries safely. Use get_schema() first to understand the database structure.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • Handler implementation for query_data tool in SQLite server. Executes arbitrary SQL queries using sqlite3 and formats results.
    @mcp.tool()
    def query_data(sql: str) -> str:
        """Execute SQL queries safely. Use get_schema() first to understand the database structure."""
        logger.info(f"Executing SQL query: {sql}")
        conn = sqlite3.connect(db_path)
        try:
            result = conn.execute(sql).fetchall()
            conn.commit()
            
            if not result:
                return "Query executed successfully but returned no results."
            
            # Format results nicely
            output = f"Query returned {len(result)} row(s):\n\n"
            for i, row in enumerate(result, 1):
                output += f"Row {i}: {row}\n"
            
            return output
        except Exception as e:
            return f"Error: {str(e)}"
        finally:
            conn.close()
  • Handler implementation for query_data tool in MySQL server. Executes SQL queries using mysql.connector, handles SELECT vs mutations differently.
    @mcp.tool()
    def query_data(sql: str) -> str:
        """Execute SQL queries safely. Use get_schema() first to understand the database structure."""
        logger.info(f"Executing SQL query: {sql}")
        try:
            conn = mysql.connector.connect(**db_config)
            cursor = conn.cursor()
            
            cursor.execute(sql)
            
            # Handle different types of queries
            if sql.strip().upper().startswith(('SELECT', 'SHOW', 'DESCRIBE', 'EXPLAIN')):
                result = cursor.fetchall()
                if not result:
                    return "Query executed successfully but returned no results."
                
                # Format results nicely
                output = f"Query returned {len(result)} row(s):\n\n"
                for i, row in enumerate(result, 1):
                    output += f"Row {i}: {row}\n"
            else:
                # For INSERT, UPDATE, DELETE, etc.
                conn.commit()
                output = f"Query executed successfully. Affected rows: {cursor.rowcount}"
            
            return output
        except Exception as e:
            return f"Error: {str(e)}"
        finally:
            if 'cursor' in locals():
                cursor.close()
            if 'conn' in locals():
                conn.close()
  • Handler implementation for query_data tool in Oracle server. Executes SQL queries using cx_Oracle, distinguishes SELECT/WITH queries.
    @mcp.tool()
    def query_data(sql: str) -> str:
        """Execute SQL queries safely. Use get_schema() first to understand the database structure."""
        logger.info(f"Executing SQL query: {sql}")
        try:
            conn = cx_Oracle.connect(**db_config)
            cursor = conn.cursor()
            
            cursor.execute(sql)
            
            # Handle different types of queries
            if sql.strip().upper().startswith(('SELECT', 'WITH')):
                result = cursor.fetchall()
                if not result:
                    return "Query executed successfully but returned no results."
                
                # Format results nicely
                output = f"Query returned {len(result)} row(s):\n\n"
                for i, row in enumerate(result, 1):
                    output += f"Row {i}: {row}\n"
            else:
                # For INSERT, UPDATE, DELETE, etc.
                conn.commit()
                output = f"Query executed successfully. Affected rows: {cursor.rowcount}"
            
            return output
        except Exception as e:
            return f"Error: {str(e)}"
        finally:
            if 'cursor' in locals():
                cursor.close()
            if 'conn' in locals():
Behavior2/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 mentions 'safely' but doesn't explain what that entails (e.g., read-only vs. write operations, error handling, or performance limits). This leaves significant gaps in understanding how the tool behaves beyond basic execution.

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 highly concise with two sentences that are front-loaded and waste no words. Each sentence serves a clear purpose: stating the tool's function and providing a usage guideline.

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

Completeness3/5

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

Given the tool's complexity (executing arbitrary SQL queries) and the presence of an output schema (which handles return values), the description is minimally adequate. However, with no annotations and low parameter coverage, it lacks details on safety, constraints, and error handling that would be helpful for an AI agent.

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

Parameters2/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. It only implies that the 'sql' parameter is for SQL queries without adding details like supported syntax, constraints, or examples. This fails to adequately clarify the parameter's meaning beyond the basic schema.

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

Purpose4/5

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

The description clearly states the action ('Execute SQL queries') and resource ('database'), making the purpose understandable. However, it doesn't explicitly differentiate this tool from its siblings like 'describe_table' or 'search_tables', which also interact with database structures.

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 guidance to 'Use get_schema() first to understand the database structure,' which helps the agent know when to use this tool in relation to a sibling. However, it doesn't specify when NOT to use it or mention alternatives like 'list_tables' for other purposes.

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

Related 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/sharansahu/mcp-sql'

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