Skip to main content
Glama
KannaKim

PostgreSQL MCP Server

by KannaKim

run_query

Execute read-only SQL queries to retrieve data from PostgreSQL databases safely. Only SELECT statements are allowed for security.

Instructions

Run a read-only SQL query against the database. ONLY SELECT queries are allowed for safety.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesThe read-only SQL query to execute

Implementation Reference

  • main.py:39-52 (registration)
    Tool 'run_query' is registered in the list_tools() function with a schema requiring a 'query' string parameter.
    Tool(
        name="run_query",
        description="Run a read-only SQL query against the database. ONLY SELECT queries are allowed for safety.",
        inputSchema={
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "The read-only SQL query to execute"
                }
            },
            "required": ["query"]
        }
    )
  • main.py:40-52 (schema)
    The inputSchema for 'run_query' defines a 'query' string property as required input.
        name="run_query",
        description="Run a read-only SQL query against the database. ONLY SELECT queries are allowed for safety.",
        inputSchema={
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "The read-only SQL query to execute"
                }
            },
            "required": ["query"]
        }
    )
  • main.py:95-124 (handler)
    The handler for 'run_query' in call_tool() extracts the query, validates it's SELECT/WITH only, executes it in a read-only transaction via asyncpg, and formats the results as text.
    elif name == "run_query":
        query = arguments.get("query")
        if not query:
            return [TextContent(type="text", text="Error: query is required")]
            
        if not query.strip().upper().startswith("SELECT") and not query.strip().upper().startswith("WITH"):
             return [TextContent(type="text", text="Error: Only SELECT/WITH queries are permitted via this tool.")]
             
        try:
            async with pool.acquire() as conn:
                async with conn.transaction(readonly=True):
                    # Use direct fetch to avoid prepared statement argument issues for general queries
                    records = await conn.fetch(query)
                    
                    if not records:
                        return [TextContent(type="text", text="Query returned 0 rows.")]
                    
                    keys = list(records[0].keys())
                    header = " | ".join(keys)
                    separator = "-" * len(header)
                    
                    rows = []
                    for record in records:
                        rows.append(" | ".join(str(record[k]) for k in keys))
                        
                    result_text = f"{header}\n{separator}\n" + "\n".join(rows) + "\n\n(Limited to records fetched)"
                    return [TextContent(type="text", text=result_text)]
                
        except Exception as e:
             return [TextContent(type="text", text=f"Error executing query: {str(e)}")]
Behavior3/5

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

With no annotations, the description discloses the key read-only behavior. However, it lacks details on error handling, result format, or performance impacts, making it adequate but not rich.

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 two concise sentences, front-loaded with the core action, with no redundant information.

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 simplicity of the tool (single parameter, no output schema), the description is minimally complete. It could mention that it returns query results, but the lack is not critical.

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 coverage is 100% and the description reinforces the parameter's safety (read-only, SELECT-only). No additional meaning beyond the schema is provided, so baseline score applies.

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 runs a read-only SQL query, specifying 'SELECT queries only' which distinguishes it from sibling tools like get_schema and list_tables.

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?

It explicitly restricts usage to SELECT queries for safety, providing a clear when-to-use guideline. It could mention alternatives for non-SELECT queries, but the constraint is sufficient.

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/KannaKim/PostgresqlMCPServer'

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