Skip to main content
Glama
HenkDz

PostgreSQL MCP Server

pg_manage_schema

Manage PostgreSQL database schema operations including creating tables, altering structures, listing schema information, and handling ENUM types.

Instructions

Manage PostgreSQL schema - get schema info, create/alter tables, manage enums. Examples: operation="get_info" for table lists, operation="create_table" with tableName and columns, operation="get_enums" to list enums, operation="create_enum" with enumName and values

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
connectionStringNoPostgreSQL connection string (optional)
operationYesOperation: get_info (schema/table info), create_table (new table), alter_table (modify table), get_enums (list ENUMs), create_enum (new ENUM)
tableNameNoTable name (optional for get_info to get specific table info, required for create_table/alter_table)
schemaNoSchema name (defaults to public)
columnsNoColumn definitions (required for create_table)
operationsNoAlter operations (required for alter_table)
enumNameNoENUM name (optional for get_enums to filter, required for create_enum)
valuesNoENUM values (required for create_enum)
ifNotExistsNoInclude IF NOT EXISTS clause (for create_enum)

Implementation Reference

  • Full implementation of the 'pg_manage_schema' tool handler. Includes input schema definition, parameter extraction, operation dispatching (get_info, create_table, alter_table, get_enums, create_enum), calls to helper functions, error handling, and ToolOutput formatting.
    export const manageSchemaTools: PostgresTool = {
      name: 'pg_manage_schema',
      description: 'Manage PostgreSQL schema - get schema info, create/alter tables, manage enums. Examples: operation="get_info" for table lists, operation="create_table" with tableName and columns, operation="get_enums" to list enums, operation="create_enum" with enumName and values',
      inputSchema: z.object({
        connectionString: z.string().optional().describe('PostgreSQL connection string (optional)'),
        operation: z.enum(['get_info', 'create_table', 'alter_table', 'get_enums', 'create_enum']).describe('Operation: get_info (schema/table info), create_table (new table), alter_table (modify table), get_enums (list ENUMs), create_enum (new ENUM)'),
        
        // Common parameters
        tableName: z.string().optional().describe('Table name (optional for get_info to get specific table info, required for create_table/alter_table)'),
        schema: z.string().optional().describe('Schema name (defaults to public)'),
        
        // Create table parameters
        columns: z.array(z.object({
          name: z.string(),
          type: z.string().describe("PostgreSQL data type"),
          nullable: z.boolean().optional(),
          default: z.string().optional().describe("Default value expression"),
        })).optional().describe('Column definitions (required for create_table)'),
        
        // Alter table parameters
        operations: z.array(z.object({
          type: z.enum(['add', 'alter', 'drop']),
          columnName: z.string(),
          dataType: z.string().optional().describe("PostgreSQL data type (for add/alter)"),
          nullable: z.boolean().optional().describe("Whether the column can be NULL (for add/alter)"),
          default: z.string().optional().describe("Default value expression (for add/alter)"),
        })).optional().describe('Alter operations (required for alter_table)'),
        
        // Enum parameters
        enumName: z.string().optional().describe('ENUM name (optional for get_enums to filter, required for create_enum)'),
        values: z.array(z.string()).optional().describe('ENUM values (required for create_enum)'),
        ifNotExists: z.boolean().optional().describe('Include IF NOT EXISTS clause (for create_enum)')
      }),
      // biome-ignore lint/suspicious/noExplicitAny: <explanation>
      execute: async (args: any, getConnectionStringVal: GetConnectionStringFn): Promise<ToolOutput> => {
        const { 
          connectionString: connStringArg,
          operation,
          tableName,
          schema,
          columns,
          operations,
          enumName,
          values,
          ifNotExists
        } = args as {
          connectionString?: string;
          operation: 'get_info' | 'create_table' | 'alter_table' | 'get_enums' | 'create_enum';
          tableName?: string;
          schema?: string;
          columns?: Array<{
            name: string;
            type: string;
            nullable?: boolean;
            default?: string;
          }>;
          operations?: Array<{
            type: 'add' | 'alter' | 'drop';
            columnName: string;
            dataType?: string;
            nullable?: boolean;
            default?: string;
          }>;
          enumName?: string;
          values?: string[];
          ifNotExists?: boolean;
        };
    
        try {
          switch (operation) {
            case 'get_info': {
              const result = await executeGetSchemaInfo({
                connectionString: connStringArg,
                tableName
              }, getConnectionStringVal);
              const message = tableName 
                ? `Schema information for table ${tableName}` 
                : 'List of tables in database';
              return { content: [{ type: 'text', text: message }, { type: 'text', text: JSON.stringify(result, null, 2) }] };
            }
    
            case 'create_table': {
              if (!tableName || !columns || columns.length === 0) {
                return { 
                  content: [{ type: 'text', text: 'Error: tableName and columns are required for create_table operation' }], 
                  isError: true 
                };
              }
              const result = await executeCreateTable({
                connectionString: connStringArg,
                tableName,
                columns
              }, getConnectionStringVal);
              return { content: [{ type: 'text', text: `Table ${result.tableName} created successfully (if not exists).` }, { type: 'text', text: JSON.stringify(result, null, 2) }] };
            }
    
            case 'alter_table': {
              if (!tableName || !operations || operations.length === 0) {
                return { 
                  content: [{ type: 'text', text: 'Error: tableName and operations are required for alter_table operation' }], 
                  isError: true 
                };
              }
              const result = await executeAlterTable({
                connectionString: connStringArg,
                tableName,
                operations
              }, getConnectionStringVal);
              return { content: [{ type: 'text', text: `Table ${result.tableName} altered successfully.` }, { type: 'text', text: JSON.stringify(result, null, 2) }] };
            }
    
            case 'get_enums': {
              const result = await executeGetEnumsInSchema(
                connStringArg || '', 
                schema || 'public', 
                enumName, 
                getConnectionStringVal
              );
              return { content: [{ type: 'text', text: `Fetched ${result.length} ENUM(s).` }, { type: 'text', text: JSON.stringify(result, null, 2) }] };
            }
    
            case 'create_enum': {
              if (!enumName || !values || values.length === 0) {
                return { 
                  content: [{ type: 'text', text: 'Error: enumName and values are required for create_enum operation' }], 
                  isError: true 
                };
              }
              const result = await executeCreateEnumInSchema(
                connStringArg || '', 
                enumName, 
                values, 
                schema || 'public', 
                ifNotExists || false, 
                getConnectionStringVal
              );
              return { content: [{ type: 'text', text: `ENUM type ${result.schema ? `${result.schema}.` : ''}${result.enumName} created successfully.` }, { type: 'text', text: JSON.stringify(result, null, 2) }] };
            }
    
            default:
              return { 
                content: [{ type: 'text', text: `Error: Unknown operation "${operation}". Supported operations: get_info, create_table, alter_table, get_enums, create_enum` }], 
                isError: true 
              };
          }
    
        } catch (error) {
          const errorMessage = error instanceof McpError ? error.message : (error instanceof Error ? error.message : String(error));
          return { content: [{ type: 'text', text: `Error executing ${operation} operation: ${errorMessage}` }], isError: true };
        }
      }
    }; 
  • Zod input schema for the pg_manage_schema tool, defining parameters for connection, operation type, and operation-specific fields like tableName, columns, operations, enum details.
    inputSchema: z.object({
      connectionString: z.string().optional().describe('PostgreSQL connection string (optional)'),
      operation: z.enum(['get_info', 'create_table', 'alter_table', 'get_enums', 'create_enum']).describe('Operation: get_info (schema/table info), create_table (new table), alter_table (modify table), get_enums (list ENUMs), create_enum (new ENUM)'),
      
      // Common parameters
      tableName: z.string().optional().describe('Table name (optional for get_info to get specific table info, required for create_table/alter_table)'),
      schema: z.string().optional().describe('Schema name (defaults to public)'),
      
      // Create table parameters
      columns: z.array(z.object({
        name: z.string(),
        type: z.string().describe("PostgreSQL data type"),
        nullable: z.boolean().optional(),
        default: z.string().optional().describe("Default value expression"),
      })).optional().describe('Column definitions (required for create_table)'),
      
      // Alter table parameters
      operations: z.array(z.object({
        type: z.enum(['add', 'alter', 'drop']),
        columnName: z.string(),
        dataType: z.string().optional().describe("PostgreSQL data type (for add/alter)"),
        nullable: z.boolean().optional().describe("Whether the column can be NULL (for add/alter)"),
        default: z.string().optional().describe("Default value expression (for add/alter)"),
      })).optional().describe('Alter operations (required for alter_table)'),
      
      // Enum parameters
      enumName: z.string().optional().describe('ENUM name (optional for get_enums to filter, required for create_enum)'),
      values: z.array(z.string()).optional().describe('ENUM values (required for create_enum)'),
      ifNotExists: z.boolean().optional().describe('Include IF NOT EXISTS clause (for create_enum)')
    }),
  • src/index.ts:225-257 (registration)
    Registration of pg_manage_schema by including manageSchemaTools in the allTools array, which is passed to PostgreSQLServer constructor to populate availableToolsList and MCP capabilities.tools.
    const allTools: PostgresTool[] = [
      // Core Analysis & Debugging
      analyzeDatabaseTool,
      debugDatabaseTool,
      
      // Schema & Structure Management (Meta-Tools)
      manageSchemaTools,
      manageFunctionsTool,
      manageTriggersTools,
      manageIndexesTool,
      manageConstraintsTool,
      manageRLSTool,
      
      // User & Security Management
      manageUsersTool,
      
      // Query & Performance Management
      manageQueryTool,
      
      // Data Operations (Enhancement Tools)
      executeQueryTool,
      executeMutationTool,
      executeSqlTool,
      
      // Documentation & Metadata
      manageCommentsTool,
      
      // Data Migration & Monitoring
      exportTableDataTool,
      importTableDataTool,
      copyBetweenDatabasesTool,
      monitorDatabaseTool
    ];
  • src/index.ts:24-24 (registration)
    Import of the manageSchemaTools from src/tools/schema.ts for registration in the main server index.
    import { manageSchemaTools } from './tools/schema.js';
  • Helper function executeGetSchemaInfo used by pg_manage_schema for 'get_info' operation to retrieve schema or table information.
    async function executeGetSchemaInfo(
      input: GetSchemaInfoInput,
      getConnectionString: GetConnectionStringFn
    ): Promise<TableInfo | string[]> { // Return type depends on whether tableName is provided
      const resolvedConnectionString = getConnectionString(input.connectionString);
      const db = DatabaseConnection.getInstance();
      const { tableName } = input;
      
      try {
        await db.connect(resolvedConnectionString);
        
        if (tableName) {
          return await getTableInfo(db, tableName);
        }
        
        const tables = await db.query<{ table_name: string }>(
          `SELECT table_name 
           FROM information_schema.tables 
           WHERE table_schema = 'public' AND table_type = 'BASE TABLE' -- Ensure only base tables
           ORDER BY table_name`
        );
        return tables.map(t => t.table_name);
    
      } catch (error) {
        throw new McpError(ErrorCode.InternalError, `Failed to get schema information: ${error instanceof Error ? error.message : String(error)}`);
      } finally {
        await db.disconnect();
      }
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions operations but doesn't clarify critical traits: whether operations are read-only or destructive (e.g., create_table alters database state), authentication needs (connectionString is optional but implications unclear), error handling, or transaction behavior. The examples add some context but leave major gaps for a multi-operation tool with potential mutations.

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 efficiently structured in two sentences: a purpose statement followed by operation examples. Each example earns its place by illustrating parameter usage. However, the examples are somewhat terse and could be more clearly formatted, slightly reducing readability.

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 tool's complexity (9 parameters, multiple operations including mutations), no annotations, and no output schema, the description is incomplete. It doesn't address return values, error conditions, side effects, or prerequisites (e.g., database permissions). For a schema management tool with potential destructive operations, this leaves significant gaps for an AI agent.

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 description coverage is 100%, so the schema already documents all 9 parameters thoroughly. The description adds minimal value beyond the schema: it mentions operation examples and ties some parameters to operations (e.g., tableName for create_table), but doesn't explain semantics like column structure details or ifNotExists behavior. This meets the baseline for high schema 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 manages PostgreSQL schema with specific operations (get schema info, create/alter tables, manage enums). It distinguishes from siblings like pg_execute_query or pg_manage_indexes by focusing on schema operations rather than queries, indexes, or other database aspects. However, it doesn't explicitly contrast with all siblings like pg_manage_constraints or pg_manage_functions.

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 examples that imply when to use different operations (e.g., operation='get_info' for table lists), giving some contextual guidance. However, it lacks explicit when-not-to-use advice or clear alternatives among siblings (e.g., when to use pg_manage_constraints instead for constraint operations). The examples serve as usage hints but aren't comprehensive guidelines.

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/HenkDz/postgresql-mcp-server'

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