Skip to main content
Glama
KannaKim

PostgreSQL MCP Server

by KannaKim

get_schema

Retrieve the column names and data types of a specified table to understand its structure.

Instructions

Get the schema (columns, types) of a specific table

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
table_nameYesName of the table

Implementation Reference

  • main.py:25-38 (registration)
    Tool registration via Tool object with name='get_schema', including description and inputSchema requiring table_name
    Tool(
        name="get_schema",
        description="Get the schema (columns, types) of a specific table",
        inputSchema={
            "type": "object",
            "properties": {
                "table_name": {
                    "type": "string",
                    "description": "Name of the table"
                }
            },
            "required": ["table_name"]
        }
    ),
  • main.py:73-93 (handler)
    Handler implementation for get_schema: queries information_schema.columns for the given table_name and returns column names, data types, and nullability
    elif name == "get_schema":
        table_name = arguments.get("table_name")
        if not table_name:
            return [TextContent(type="text", text="Error: table_name is required")]
            
        async with pool.acquire() as conn:
            records = await conn.fetch("""
                SELECT column_name, data_type, is_nullable
                FROM information_schema.columns
                WHERE table_schema = 'public' AND table_name = $1
                ORDER BY ordinal_position
            """, table_name)
            
            if not records:
                return [TextContent(type="text", text=f"Table '{table_name}' not found or has no columns.")]
                
            schema_info = [f"Schema for {table_name}:"]
            for r in records:
                schema_info.append(f"- {r['column_name']} ({r['data_type']}, nullable: {r['is_nullable']})")
                
            return [TextContent(type="text", text="\n".join(schema_info))]
  • main.py:14-53 (registration)
    Full list_tools() function that registers all three tools including get_schema
    @app.list_tools()
    async def list_tools() -> list[Tool]:
        return [
            Tool(
                name="list_tables",
                description="List all tables in the current database schema",
                inputSchema={
                    "type": "object",
                    "properties": {},
                }
            ),
            Tool(
                name="get_schema",
                description="Get the schema (columns, types) of a specific table",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "table_name": {
                            "type": "string",
                            "description": "Name of the table"
                        }
                    },
                    "required": ["table_name"]
                }
            ),
            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:55-127 (handler)
    Full call_tool() handler dispatching function that routes to get_schema logic on line 73-93
    @app.call_tool()
    async def call_tool(name: str, arguments: dict) -> list[TextContent]:
        if not pool:
            return [TextContent(type="text", text="Error: Database connection pool not initialized. DATABASE_URL may be missing or invalid.")]
    
        if name == "list_tables":
            async with pool.acquire() as conn:
                records = await conn.fetch("""
                    SELECT table_name 
                    FROM information_schema.tables 
                    WHERE table_schema = 'public' 
                      AND table_type = 'BASE TABLE'
                """)
                tables = [record["table_name"] for record in records]
                if not tables:
                    return [TextContent(type="text", text="No tables found in public schema.")]
                return [TextContent(type="text", text=f"Tables in public schema:\n" + "\n".join(f"- {t}" for t in tables))]
    
        elif name == "get_schema":
            table_name = arguments.get("table_name")
            if not table_name:
                return [TextContent(type="text", text="Error: table_name is required")]
                
            async with pool.acquire() as conn:
                records = await conn.fetch("""
                    SELECT column_name, data_type, is_nullable
                    FROM information_schema.columns
                    WHERE table_schema = 'public' AND table_name = $1
                    ORDER BY ordinal_position
                """, table_name)
                
                if not records:
                    return [TextContent(type="text", text=f"Table '{table_name}' not found or has no columns.")]
                    
                schema_info = [f"Schema for {table_name}:"]
                for r in records:
                    schema_info.append(f"- {r['column_name']} ({r['data_type']}, nullable: {r['is_nullable']})")
                    
                return [TextContent(type="text", text="\n".join(schema_info))]
    
        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)}")]
    
        else:
            raise ValueError(f"Unknown tool: {name}")
Behavior3/5

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

With no annotations, the description must convey behavioral traits. It describes a read operation ('Get') but lacks details such as whether any side effects occur, authentication requirements, or rate limits. The description is adequate for a simple metadata retrieval but could be more explicit.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, front-loaded sentence that directly states the purpose. It is concise and efficient, though it could briefly mention the output to improve completeness without adding much length.

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 low complexity (one parameter, no output schema), the description covers the core functionality. It does not explain the return format, but the tool name and description imply a schema structure. For simple tools, this level of detail is sufficient.

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?

The schema provides 100% coverage with a clear description for table_name ('Name of the table'). The tool description does not add additional meaning beyond what the schema already conveys, 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 action ('Get') and the resource ('schema of a specific table'), making the purpose instantly understandable. It distinguishes itself from sibling tools: list_tables lists tables, run_query executes queries.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage when needing column names and types for a known table, but it does not provide explicit guidance on when to use this tool versus alternatives (e.g., run_query for more complex queries).

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