Skip to main content
Glama
HenkDz

PostgreSQL MCP Server

pg_copy_between_databases

Copy data between two PostgreSQL databases by specifying source and target connection strings and table name. Supports conditional filtering and target table truncation options.

Instructions

Copy data between two databases

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
sourceConnectionStringYes
targetConnectionStringYes
tableNameYes
whereNo
truncateTargetNo

Implementation Reference

  • The core handler function that implements the logic to copy table data from a source PostgreSQL database to a target database. It connects to the source DB, queries the data (with optional WHERE clause), disconnects, connects to the target DB, optionally truncates the table, and inserts the data in a transaction.
    async function executeCopyBetweenDatabases(
      input: CopyBetweenDatabasesInput,
      getConnectionString: GetConnectionStringFn
    ): Promise<{ tableName: string; rowCount: number }> {
      const { sourceConnectionString, targetConnectionString, tableName, where, truncateTarget } = input;
      
      const db = DatabaseConnection.getInstance(); // Use the singleton for both connections sequentially
    
      try {
        // --- Source Operations ---
        await db.connect(sourceConnectionString);
        
        let query = `SELECT * FROM "${tableName}"`;
        if (where) {
          query += ` WHERE ${where}`;
        }
        
        const data = await db.query<Record<string, unknown>[]>(query);
        
        if (data.length === 0) {
          await db.disconnect(); // Disconnect source if no data
          return { tableName, rowCount: 0 };
        }
        
        await db.disconnect(); // Disconnect source before connecting to target
        
        // --- Target Operations ---
        await db.connect(targetConnectionString);
        
        if (truncateTarget) {
          await db.query(`TRUNCATE TABLE "${tableName}"`);
        }
        
        let importedCount = 0;
        await db.transaction(async (client: import('pg').PoolClient) => {
          for (const record of data) {
            const columns = Object.keys(record);
            if (columns.length === 0) continue;
            const values = Object.values(record);
            const placeholders = values.map((_, i) => `$${i + 1}`).join(', ');
            
            const insertQuery = `
              INSERT INTO "${tableName}" (${columns.map(c => `"${c}"`).join(', ')})
              VALUES (${placeholders})
            `;
            await client.query(insertQuery, values);
            importedCount++;
          }
        });
        
        return { tableName, rowCount: importedCount };
      } catch (error) {
        throw new McpError(ErrorCode.InternalError, `Failed to copy data: ${error instanceof Error ? error.message : String(error)}`);
      } finally {
        // Ensure disconnection in normal flow; connect() handles prior disconnects if needed.
        // The connect method in DatabaseConnection already handles disconnecting if connected to a different DB.
        // So, a single disconnect here should be fine, assuming the last active connection was target.
        // If an error occurred mid-operation (e.g., after source connect, before target connect),
        // connect() for target would handle disconnecting from source.
        // If an error occurs after target connect, this disconnect handles target.
        await db.disconnect(); 
      }
    }
  • Zod schema defining the input parameters for the pg_copy_between_databases tool: source and target connection strings, table name, optional WHERE clause, and optional truncate flag.
    const CopyBetweenDatabasesInputSchema = z.object({
      sourceConnectionString: z.string(),
      targetConnectionString: z.string(),
      tableName: z.string(),
      where: z.string().optional(),
      truncateTarget: z.boolean().optional().default(false),
    });
  • The PostgresTool object definition that registers the tool with its name, description, input schema, and execute wrapper that validates input and calls the main handler.
    export const copyBetweenDatabasesTool: PostgresTool = {
      name: 'pg_copy_between_databases',
      description: 'Copy data between two databases',
      inputSchema: CopyBetweenDatabasesInputSchema,
      async execute(params: unknown, getConnectionString: GetConnectionStringFn): Promise<ToolOutput> {
        const validationResult = CopyBetweenDatabasesInputSchema.safeParse(params);
        if (!validationResult.success) {
          return { content: [{ type: 'text', text: `Invalid input: ${validationResult.error.format()}` }], isError: true };
        }
        try {
          const result = await executeCopyBetweenDatabases(validationResult.data, getConnectionString);
          return { content: [{ type: 'text', text: `Successfully copied ${result.rowCount} rows to ${result.tableName}` }] };
        } catch (error) {
          const errorMessage = error instanceof McpError ? error.message : (error instanceof Error ? error.message : String(error));
          return { content: [{ type: 'text', text: `Error copying data: ${errorMessage}` }], isError: true };
        }
      }
    };
  • src/index.ts:225-257 (registration)
    The allTools array where the copyBetweenDatabasesTool is included among all available tools, which is then passed to the PostgreSQLServer constructor to register tools with the MCP server.
    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:22-22 (registration)
    Import statement that brings the copyBetweenDatabasesTool into the main index file for inclusion in the tools list.
    import { exportTableDataTool, importTableDataTool, copyBetweenDatabasesTool } from './tools/migration.js';
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. 'Copy data between two databases' implies a write operation to the target database, but it doesn't disclose critical traits like whether this requires specific permissions, if it's a bulk operation, what happens on failure, or if there are rate limits. For a tool with 5 parameters and 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 with zero waste. It's appropriately sized for the tool's name and gets straight to the point without unnecessary elaboration. Every word earns its place in conveying the core functionality.

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 (5 parameters, no annotations, no output schema, and 0% schema coverage), the description is inadequate. It doesn't explain what the tool returns, how parameters interact, or the operational context. For a data copying tool with multiple configuration options, more completeness is needed to guide effective use.

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 5 parameters have descriptions in the schema. The tool description doesn't mention any parameters or provide meaning beyond the basic action. It fails to compensate for the lack of schema documentation, leaving parameters like 'where' and 'truncateTarget' completely unexplained in context.

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 'Copy data between two databases' clearly states the verb (copy) and resource (data between databases). It's specific about the action but doesn't differentiate from sibling tools like pg_export_table_data or pg_import_table_data, which might handle similar data movement operations. The purpose is unambiguous but lacks sibling distinction.

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. With siblings like pg_export_table_data and pg_import_table_data that might handle similar data transfer tasks, there's no indication of when this tool is preferred or what specific scenarios it addresses. No exclusions or prerequisites are mentioned.

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