Skip to main content
Glama
avantifellows

Avanti Fellows PostgreSQL MCP Server

Official

query

Execute read-only SELECT queries to explore, debug, or validate data in the Avanti Fellows PostgreSQL database.

Instructions

Execute a read-only SQL query against the database.

Only SELECT queries are allowed. Use this to explore data,
debug issues, or validate assumptions about the data.

Args:
    sql: A SELECT query to execute

Returns:
    JSON array of results, or error message

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sqlYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The primary handler function for the 'query' MCP tool. It validates the SQL as read-only, executes it using asyncpg, serializes results to JSON, and handles errors.
    @mcp.tool()
    async def query(sql: str) -> str:
        """Execute a read-only SQL query against the database.
    
        Only SELECT queries are allowed. Use this to explore data,
        debug issues, or validate assumptions about the data.
    
        Args:
            sql: A SELECT query to execute
    
        Returns:
            JSON array of results, or error message
        """
        if not is_read_only(sql):
            return json.dumps({"error": "Only SELECT queries are allowed"})
    
        try:
            async with get_connection() as conn:
                rows = await conn.fetch(sql)
                # Convert to list of dicts, handling special types
                results = []
                for row in rows:
                    results.append({k: _serialize_value(v) for k, v in dict(row).items()})
                return json.dumps(results, indent=2, default=str)
        except Exception as e:
            return json.dumps({"error": str(e)})
  • Helper function called by the query handler to ensure only safe, read-only SELECT queries are executed.
    def is_read_only(sql: str) -> bool:
        """Check if SQL is read-only (SELECT only)."""
        normalized = sql.strip().upper()
        # Must start with SELECT or WITH (for CTEs)
        if not (normalized.startswith("SELECT") or normalized.startswith("WITH")):
            return False
        # Block dangerous keywords even in subqueries
        dangerous = ["INSERT", "UPDATE", "DELETE", "DROP", "ALTER", "TRUNCATE", "CREATE", "GRANT", "REVOKE"]
        return not any(kw in normalized for kw in dangerous)
  • Async context manager for obtaining PostgreSQL connections, used by the query handler.
    @asynccontextmanager
    async def get_connection():
        """Get a database connection."""
        conn = await asyncpg.connect(**DB_CONFIG)
        try:
            yield conn
        finally:
            await conn.close()
  • Utility function used in query handler to serialize PostgreSQL values (e.g., dates, bytes) to JSON-compatible formats.
    def _serialize_value(value):
        """Serialize special PostgreSQL types to JSON-compatible values."""
        if value is None:
            return None
        if isinstance(value, (dict, list)):
            return value
        if hasattr(value, "isoformat"):  # datetime, date, time
            return value.isoformat()
        if isinstance(value, bytes):
            return value.decode("utf-8", errors="replace")
        return value
  • The @mcp.tool() decorator registers the query function as an MCP tool.
    @mcp.tool()
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 and does well by disclosing key behavioral traits: it's read-only, restricts to SELECT queries, and mentions error handling ('or error message'). It could improve by adding details like rate limits or result size 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 appropriately sized and front-loaded, with the core purpose in the first sentence, usage guidelines in the second, and clear sections for Args and Returns. Every sentence adds value without redundancy.

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

Completeness5/5

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

Given the tool's complexity (SQL execution), no annotations, and an output schema present, the description is complete enough: it covers purpose, usage, behavioral constraints, parameter meaning, and return values, making it self-sufficient for an AI agent.

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

Parameters4/5

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

The schema has 0% description coverage, but the description compensates by explaining the 'sql' parameter as 'A SELECT query to execute,' adding meaning beyond the bare schema. It doesn't provide syntax examples or constraints, but this is adequate given the single parameter.

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 a specific verb ('Execute') and resource ('read-only SQL query against the database'), distinguishing it from siblings like count_rows or describe_table by focusing on general query execution rather than specific operations.

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 explore data, debug issues, or validate assumptions') and explicitly states 'Only SELECT queries are allowed,' which helps differentiate it from potential write operations. However, it doesn't explicitly mention when to use alternatives like sample_data or search_columns.

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/avantifellows/mcp-postgres'

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