Skip to main content
Glama
cesarvarela

PostgreSQL MCP Server

by cesarvarela

get-schema

Retrieve PostgreSQL database schema details like tables, columns, data types, and constraints to understand database structure.

Instructions

Get database schema information including tables, columns, data types, and optionally constraints. Useful for understanding database structure.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
schema_nameNopublic
table_patternNo
include_columnsNo
include_constraintsNo

Implementation Reference

  • The main handler function `getSchema` that executes the tool logic: validates input, checks connection, queries information_schema.tables for tables (optionally filtered), fetches columns and constraints if requested, groups them by table, and returns structured schema information.
    export async function getSchema(
      rawParams: any
    ): McpToolResponse {
      try {
        // Validate and parse parameters
        const params = getSchemaSchema.parse(rawParams);
        
        // Check database connection status
        const connectionStatus = getConnectionStatus();
        if (connectionStatus.status !== 'connected') {
          return createDatabaseUnavailableResponse("get database schema");
        }
        
        const { schema_name, table_pattern, include_columns, include_constraints } = params;
    
        // Base query for tables
        let tablesQuery = `
          SELECT 
            table_name,
            table_schema,
            table_type
          FROM information_schema.tables
          WHERE table_schema = $1
        `;
        
        const queryParams: any[] = [schema_name];
        let paramIndex = 2;
    
        // Add table pattern filter if provided
        if (table_pattern) {
          tablesQuery += ` AND table_name LIKE $${paramIndex}`;
          queryParams.push(table_pattern);
          paramIndex++;
        }
    
        tablesQuery += ` ORDER BY table_name`;
    
        debug("Fetching schema information for schema: %s", schema_name);
        const tables = await executePostgresQuery<TableInfo>(tablesQuery, queryParams);
    
        // Initialize columns and constraints properties for all tables
        tables.forEach(table => {
          table.columns = [];
          table.constraints = [];
        });
    
        // Enhance tables with column information if requested
        if (include_columns && tables.length > 0) {
          const columnsQuery = `
            SELECT 
              table_name,
              column_name,
              data_type,
              is_nullable,
              column_default,
              character_maximum_length,
              numeric_precision,
              numeric_scale,
              ordinal_position
            FROM information_schema.columns
            WHERE table_schema = $1
            ORDER BY table_name, ordinal_position
          `;
    
          const columns = await executePostgresQuery<ColumnInfo & { table_name: string; ordinal_position: number }>(
            columnsQuery, 
            [schema_name]
          );
    
          // Group columns by table
          const columnsByTable = new Map<string, ColumnInfo[]>();
          columns.forEach(col => {
            if (!columnsByTable.has(col.table_name)) {
              columnsByTable.set(col.table_name, []);
            }
            const { table_name, ordinal_position, ...columnInfo } = col;
            columnsByTable.get(col.table_name)!.push(columnInfo);
          });
    
          // Add columns to tables
          tables.forEach(table => {
            table.columns = columnsByTable.get(table.table_name) || [];
          });
        }
    
        // Enhance tables with constraint information if requested
        if (include_constraints && tables.length > 0) {
          const constraintsQuery = `
            SELECT 
              tc.table_name,
              tc.constraint_name,
              tc.constraint_type,
              kcu.column_name,
              ccu.table_name AS foreign_table_name,
              ccu.column_name AS foreign_column_name
            FROM information_schema.table_constraints tc
            LEFT JOIN information_schema.key_column_usage kcu
              ON tc.constraint_name = kcu.constraint_name
              AND tc.table_schema = kcu.table_schema
            LEFT JOIN information_schema.constraint_column_usage ccu
              ON tc.constraint_name = ccu.constraint_name
              AND tc.table_schema = ccu.table_schema
            WHERE tc.table_schema = $1
            ORDER BY tc.table_name, tc.constraint_name
          `;
    
          const constraints = await executePostgresQuery<ConstraintInfo & { table_name: string }>(
            constraintsQuery, 
            [schema_name]
          );
    
          // Group constraints by table
          const constraintsByTable = new Map<string, ConstraintInfo[]>();
          constraints.forEach(constraint => {
            if (!constraintsByTable.has(constraint.table_name)) {
              constraintsByTable.set(constraint.table_name, []);
            }
            const { table_name, ...constraintInfo } = constraint;
            constraintsByTable.get(constraint.table_name)!.push(constraintInfo);
          });
    
          // Add constraints to tables
          tables.forEach(table => {
            table.constraints = constraintsByTable.get(table.table_name) || [];
          });
        }
    
        const response = {
          schema: schema_name,
          table_count: tables.length,
          tables: tables,
          generated_at: new Date().toISOString(),
        };
    
        return createMcpSuccessResponse(response);
    
      } catch (error) {
        return createMcpErrorResponse("get schema", error);
      }
    }
  • Zod schema definition for the `get-schema` tool inputs: schema_name (default 'public'), optional table_pattern filter, flags for including columns and constraints.
    // Zod schema for input validation
    export const getSchemaShape: ZodRawShape = {
      schema_name: z.string().optional().default("public"),
      table_pattern: z.string().optional(),
      include_columns: z.boolean().optional().default(true),
      include_constraints: z.boolean().optional().default(false),
    };
    
    export const getSchemaSchema = z.object(getSchemaShape);
  • index.ts:34-39 (registration)
    Registration of the `get-schema` tool on the MCP server, providing name, description, input schema, and handler function.
    server.tool(
      "get-schema",
      "Get database schema information including tables, columns, data types, and optionally constraints. Useful for understanding database structure.",
      getSchemaShape,
      getSchema
    );
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 of behavioral disclosure. It describes what information is retrieved but lacks details on behavioral traits such as whether this is a read-only operation (implied by 'Get' but not stated), potential performance impacts, error conditions, or the format of the returned data. The description is minimal and doesn't compensate for the absence of annotations.

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 concise and well-structured with two sentences: the first states the purpose and key parameters, and the second provides usage context. Every sentence adds value without redundancy, making it efficient and easy to parse.

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 complexity (4 parameters with 0% schema coverage, no annotations, no output schema), the description is incomplete. It doesn't explain parameter meanings, behavioral aspects like safety or output format, or how it relates to sibling tools. For a tool that retrieves database schema—a potentially complex operation—this leaves significant gaps for an AI agent to understand and use it correctly.

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?

Schema description coverage is 0%, meaning none of the 4 parameters are documented in the schema. The description mentions 'optionally constraints' which hints at the 'include_constraints' parameter, but it doesn't explain the other parameters (schema_name, table_pattern, include_columns) or their purposes. This adds minimal value beyond the schema, failing to compensate for the low coverage.

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 tool's purpose: 'Get database schema information including tables, columns, data types, and optionally constraints.' It specifies the verb ('Get') and resource ('database schema information') with concrete examples of what information is retrieved. However, it doesn't explicitly differentiate from sibling tools like 'get-table-info' or 'query-table', which might also provide schema-related information.

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 provides some usage context: 'Useful for understanding database structure.' This implies when to use it (for structural understanding) but doesn't explicitly state when not to use it or mention alternatives among the sibling tools. For example, it doesn't clarify how this differs from 'get-table-info' or when to prefer one over the other.

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

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