Skip to main content
Glama
receptopalak

PostGIS MCP Server

by receptopalak

analyze-database

Analyze database schema and gather table information, with options to refresh cache for updated data, using the PostGIS MCP Server for spatial database functionality.

Instructions

Veritabanı şemasını analiz et ve tablo bilgilerini topla

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
force_refreshNoÖnbelleği yenileyip yeniden analiz et

Implementation Reference

  • Zod schema definition for the 'analyze-database' tool input, including optional 'force_refresh' boolean parameter.
    const AnalyzeDatabaseSchema = z.object({
      force_refresh: z.boolean().optional().default(false),
    });
  • server.ts:572-583 (registration)
    Tool registration in the ListToolsRequestSchema handler, defining name, description, and input schema matching AnalyzeDatabaseSchema.
      name: "analyze-database",
      description: "Veritabanı şemasını analiz et ve tablo bilgilerini topla",
      inputSchema: {
        type: "object",
        properties: {
          force_refresh: {
            type: "boolean",
            description: "Önbelleği yenileyip yeniden analiz et",
          },
        },
      },
    },
  • Handler implementation in CallToolRequestSchema switch statement. Parses input using AnalyzeDatabaseSchema, refreshes schema cache if needed by calling analyzeDatabaseSchema, generates and returns a JSON summary of the database structure.
    case "analyze-database": {
      const { force_refresh } = AnalyzeDatabaseSchema.parse(args);
    
      if (!databaseSchema || force_refresh) {
        databaseSchema = await analyzeDatabaseSchema(client);
      }
    
      const summary = {
        database: databaseSchema.connection_info.database,
        host: databaseSchema.connection_info.host,
        total_tables: Object.keys(databaseSchema.tables).length,
        spatial_tables: databaseSchema.spatial_tables.length,
        last_analyzed: databaseSchema.last_analyzed,
        table_summary: Object.entries(databaseSchema.tables).map(
          ([name, info]) => ({
            name,
            rows: info.row_count,
            columns: info.columns.length,
            spatial: info.geometry_columns.length > 0,
            description: info.table_comment || "Açıklama yok",
          })
        ),
      };
    
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(summary, null, 2),
          },
        ],
      };
    }
  • Main helper function that performs comprehensive database schema analysis. Queries PostgreSQL metadata tables to gather table info, column details (types, PK/FK, descriptions), geometry columns, indexes, row counts, sample data, and constructs a detailed DatabaseSchema object.
    async function analyzeDatabaseSchema(client: Client): Promise<DatabaseSchema> {
      const schema: DatabaseSchema = {
        tables: {},
        spatial_tables: [],
        last_analyzed: new Date(),
        connection_info: {
          database: process.env.DB_NAME || "unknown",
          host: process.env.DB_HOST || "localhost",
        },
      };
    
      // 1. Get all tables with basic info
      const tablesResult = await client.query(`
          SELECT 
            t.table_name,
            t.table_schema,
            t.table_type,
            obj_description(c.oid) as table_comment
          FROM information_schema.tables t
          LEFT JOIN pg_class c ON c.relname = t.table_name
          WHERE t.table_schema NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
          ORDER BY t.table_name;
        `);
    
      // 2. Get all columns with detailed info
      const columnsResult = await client.query(`
          SELECT 
            c.table_name,
            c.column_name,
            c.data_type,
            c.is_nullable::boolean,
            c.column_default,
            CASE WHEN pk.column_name IS NOT NULL THEN true ELSE false END as is_primary_key,
            CASE WHEN fk.column_name IS NOT NULL THEN true ELSE false END as is_foreign_key,
            fk.foreign_table_name,
            fk.foreign_column_name,
            col_description(pgc.oid, c.ordinal_position) as description
          FROM information_schema.columns c
          LEFT JOIN (
            SELECT ku.table_name, ku.column_name
            FROM information_schema.table_constraints tc
            JOIN information_schema.key_column_usage ku ON tc.constraint_name = ku.constraint_name
            WHERE tc.constraint_type = 'PRIMARY KEY'
          ) pk ON c.table_name = pk.table_name AND c.column_name = pk.column_name
          LEFT JOIN (
            SELECT 
              ku.table_name, 
              ku.column_name,
              ccu.table_name AS foreign_table_name,
              ccu.column_name AS foreign_column_name
            FROM information_schema.table_constraints tc
            JOIN information_schema.key_column_usage ku ON tc.constraint_name = ku.constraint_name
            JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name
            WHERE tc.constraint_type = 'FOREIGN KEY'
          ) fk ON c.table_name = fk.table_name AND c.column_name = fk.column_name
          LEFT JOIN pg_class pgc ON pgc.relname = c.table_name
          WHERE c.table_schema NOT IN ('information_schema', 'pg_catalog')
          ORDER BY c.table_name, c.ordinal_position;
        `);
    
      // 3. Get geometry columns
      let geometryColumns: any[] = [];
      try {
        const geometryResult = await client.query(`
            SELECT 
              f_table_name as table_name,
              f_geometry_column as column_name,
              type as geometry_type,
              srid
            FROM geometry_columns;
          `);
        geometryColumns = geometryResult.rows;
      } catch (error) {
        // PostGIS might not be installed
      }
    
      // 4. Get indexes
      const indexesResult = await client.query(`
          SELECT 
            schemaname,
            tablename,
            indexname,
            indexdef
          FROM pg_indexes 
          WHERE schemaname NOT IN ('information_schema', 'pg_catalog');
        `);
    
      // 5. Build table structures
      for (const table of tablesResult.rows) {
        const tableName = table.table_name;
    
        // Get columns for this table
        const tableColumns = columnsResult.rows
          .filter((col) => col.table_name === tableName)
          .map((col) => ({
            column_name: col.column_name,
            data_type: col.data_type,
            is_nullable: col.is_nullable,
            column_default: col.column_default,
            is_primary_key: col.is_primary_key,
            is_foreign_key: col.is_foreign_key,
            foreign_table: col.foreign_table_name,
            foreign_column: col.foreign_column_name,
            description: col.description,
          }));
    
        // Get geometry columns for this table
        const tableGeometryColumns = geometryColumns
          .filter((gc) => gc.table_name === tableName)
          .map((gc) => gc.column_name);
    
        // Get indexes for this table
        const tableIndexes = indexesResult.rows
          .filter((idx) => idx.tablename === tableName)
          .map((idx) => idx.indexname);
    
        // Get row count
        let rowCount = 0;
        try {
          const countResult = await client.query(
            `SELECT COUNT(*) as count FROM ${tableName}`
          );
          rowCount = parseInt(countResult.rows[0].count);
        } catch (error) {
          // Table might be inaccessible
        }
    
        // Get sample data (first 3 rows)
        let sampleData: any[] = [];
        try {
          const sampleResult = await client.query(
            `SELECT * FROM ${tableName} LIMIT 3`
          );
          sampleData = sampleResult.rows;
        } catch (error) {
          // Table might be inaccessible
        }
    
        schema.tables[tableName] = {
          table_name: tableName,
          table_schema: table.table_schema,
          table_type: table.table_type,
          columns: tableColumns,
          geometry_columns: tableGeometryColumns,
          row_count: rowCount,
          table_comment: table.table_comment,
          indexes: tableIndexes,
          sample_data: sampleData,
        };
    
        if (tableGeometryColumns.length > 0) {
          schema.spatial_tables.push(tableName);
        }
      }
    
      return schema;
    }
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 mentions analyzing and collecting information, which implies a read-only operation, but fails to detail aspects like performance impact, caching behavior (hinted by the 'force_refresh' parameter), error conditions, or output format. For a tool with no annotation coverage, this is a significant gap in transparency.

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, efficient sentence in Turkish that directly states the tool's purpose without unnecessary words. It is appropriately sized and front-loaded, making it easy for an agent to parse quickly. Every part of the sentence contributes to understanding the tool's function.

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 of database analysis and the lack of annotations and output schema, the description is incomplete. It does not explain what 'analyze' entails, what information is collected, the format of the results, or how it differs from similar tools like 'get-table-info.' This leaves the agent with insufficient context for effective use.

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 input schema has 100% description coverage, with the single parameter 'force_refresh' documented as 'Önbelleği yenileyip yeniden analiz et' (refresh cache and re-analyze). The description does not add any meaning beyond this, as it doesn't mention parameters at all. With high schema coverage, the baseline score of 3 is appropriate, as the schema adequately handles parameter semantics.

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: 'Veritabanı şemasını analiz et ve tablo bilgilerini topla' translates to 'Analyze the database schema and collect table information.' This specifies the verb (analyze/collect) and resource (database schema/table information). However, it doesn't explicitly distinguish this tool from its sibling 'get-table-info,' which appears to serve a similar purpose, preventing a score of 5.

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. There is no mention of prerequisites, context, or comparisons to sibling tools like 'get-table-info' or 'smart-query,' which might overlap in functionality. This lack of usage direction leaves the agent without clear decision-making criteria.

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/receptopalak/postgis-mcp'

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