Skip to main content
Glama
melihbirim

PostgreSQL MCP Server

by melihbirim

list_tables

Retrieve all tables in the current PostgreSQL database with a read-only query, enabling quick schema overview and data structure analysis.

Instructions

List all tables in the current database

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The handler function for the 'list_tables' tool. It executes a SQL query to fetch table names and types from the 'information_schema.tables' where table_schema is 'public', formats the results as a list, and returns them in the MCP response format. Uses the shared 'executeQuery' helper and handles errors.
    async () => {
      try {
        const query = `
          SELECT table_name, table_type 
          FROM information_schema.tables 
          WHERE table_schema = 'public' 
          ORDER BY table_name;
        `;
        
        const tables = await executeQuery(query);
        
        if (tables.length === 0) {
          return {
            content: [
              {
                type: "text",
                text: "No tables found in the public schema.",
              },
            ],
          };
        }
    
        const tableList = tables
          .map(table => `- ${table.table_name} (${table.table_type})`)
          .join("\n");
    
        return {
          content: [
            {
              type: "text",
              text: `Tables in database:\n${tableList}`,
            },
          ],
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : "Unknown error";
        return {
          content: [
            {
              type: "text",
              text: `Error listing tables: ${errorMessage}`,
            },
          ],
        };
      }
    }
  • src/index.ts:118-168 (registration)
    Registers the 'list_tables' tool with the MCP server using server.tool(). The tool has no input parameters (empty schema), a description, and references the handler function.
    server.tool(
      "list_tables",
      "List all tables in the current database",
      {},
      async () => {
        try {
          const query = `
            SELECT table_name, table_type 
            FROM information_schema.tables 
            WHERE table_schema = 'public' 
            ORDER BY table_name;
          `;
          
          const tables = await executeQuery(query);
          
          if (tables.length === 0) {
            return {
              content: [
                {
                  type: "text",
                  text: "No tables found in the public schema.",
                },
              ],
            };
          }
    
          const tableList = tables
            .map(table => `- ${table.table_name} (${table.table_type})`)
            .join("\n");
    
          return {
            content: [
              {
                type: "text",
                text: `Tables in database:\n${tableList}`,
              },
            ],
          };
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : "Unknown error";
          return {
            content: [
              {
                type: "text",
                text: `Error listing tables: ${errorMessage}`,
              },
            ],
          };
        }
      }
    );
  • Input schema for the 'list_tables' tool, which is empty indicating no parameters are required.
    {},
  • Shared helper function used by 'list_tables' (and other tools) to safely execute read-only SQL queries after connection check and safety validation.
    async function executeQuery(query: string, params: any[] = []): Promise<any[]> {
      const client = await getDbConnection();
      
      // Basic safety checks for read-only operations
      const normalizedQuery = query.trim().toLowerCase();
      const readOnlyPrefixes = ['select', 'show', 'describe', 'explain', 'with'];
      const isReadOnly = readOnlyPrefixes.some(prefix => normalizedQuery.startsWith(prefix));
      
      if (!isReadOnly) {
        throw new Error("Only read-only queries (SELECT, SHOW, DESCRIBE, EXPLAIN, WITH) are allowed for security.");
      }
      
      try {
        const result = await client.query(query, params);
        return result.rows;
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
        throw new Error(`Query execution failed: ${errorMessage}`);
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden. It states the action but does not disclose behavioral traits such as whether this is a read-only operation, if it requires authentication, potential rate limits, or the format of the returned list. This leaves significant gaps in understanding how the tool behaves.

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 a single, clear sentence that directly states the tool's purpose without any unnecessary words. It is front-loaded and efficiently conveys the essential information, making it easy for an agent to parse quickly.

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

Completeness2/5

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

Given the lack of annotations and output schema, the description is incomplete. It does not explain what the output looks like (e.g., list format, pagination) or address behavioral aspects like error handling. For a tool with no structured metadata, more context is needed to fully guide the 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 tool has 0 parameters, and the input schema has 100% description coverage (though empty). The description does not need to add parameter details, so it appropriately avoids redundancy. A baseline score of 4 is given since no parameters are present, and the description does not mislead about inputs.

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 ('List') and resource ('tables in the current database'), making the purpose immediately understandable. However, it does not explicitly differentiate from sibling tools like 'get_schema' or 'describe_table', which might also provide table-related information, so it falls short of a perfect score.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives such as 'get_schema' or 'describe_table'. It lacks context about prerequisites (e.g., needing a database connection) or exclusions, leaving the agent to infer usage based on tool names alone.

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/melihbirim/pg-mcp'

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