@tejasanik/postgres-mcp-server 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -266,7 +266,7 @@ Switch to a different PostgreSQL server and optionally a specific database and s
266
266
 
267
267
  #### `get_current_connection`
268
268
 
269
- Returns details about the current database connection including server, database, schema, and access mode.
269
+ Returns details about the current database connection including server, database, schema, access mode, user, and AI context.
270
270
 
271
271
  **Parameters:** None
272
272
 
@@ -277,6 +277,8 @@ Returns details about the current database connection including server, database
277
277
  - `database`: Current database name
278
278
  - `schema`: Current schema name
279
279
  - `accessMode`: "readonly" or "full"
280
+ - `user`: Database username for the current connection
281
+ - `context`: (If configured) AI context/guidance for the current server
280
282
 
281
283
  ### Schema & Object Exploration
282
284
 
@@ -341,13 +343,16 @@ Executes SQL statements on the database. Supports pagination and parameterized q
341
343
 
342
344
  #### `execute_sql_file`
343
345
 
344
- Executes a `.sql` file from the filesystem. Useful for running migration scripts, schema changes, or data imports.
346
+ Executes a `.sql` file from the filesystem. Useful for running migration scripts, schema changes, or data imports. Supports SQL files from various tools like Liquibase, Flyway, and SQL Server migrations.
345
347
 
346
348
  **Parameters:**
347
349
 
348
350
  - `filePath` (required): Absolute or relative path to the `.sql` file to execute
349
351
  - `useTransaction` (optional): Wrap execution in a transaction (default: true). If any statement fails, all changes are rolled back.
350
352
  - `stopOnError` (optional): Stop execution on first error (default: true). If false, continues with remaining statements and collects all errors.
353
+ - `stripPatterns` (optional): Array of patterns to remove from SQL before execution. Useful for stripping tool-specific delimiters (e.g., Liquibase's `/`, SQL Server's `GO`).
354
+ - `stripAsRegex` (optional): If true, treat `stripPatterns` as regular expressions; if false, as literal strings (default: false).
355
+ - `validateOnly` (optional): If true, parse and validate the file without executing (default: false). Returns a preview of all statements.
351
356
 
352
357
  **Returns:**
353
358
 
@@ -364,9 +369,84 @@ Executes a `.sql` file from the filesystem. Useful for running migration scripts
364
369
  - `sql`: The failing SQL (truncated to 200 chars)
365
370
  - `error`: Error message
366
371
  - `rollback`: Whether a rollback was performed
372
+ - `validateOnly`: (When validateOnly=true) Set to true
373
+ - `preview`: (When validateOnly=true) Array of statement previews:
374
+ - `index`: Statement index (1-based)
375
+ - `lineNumber`: Line number in the file
376
+ - `sql`: The SQL statement (truncated to 200 chars)
377
+ - `type`: Detected statement type (SELECT, INSERT, UPDATE, DELETE, CREATE, etc.)
367
378
 
368
379
  **Limits:** Max file size: 50MB. Supports PostgreSQL-specific syntax including dollar-quoted strings and block comments.
369
380
 
381
+ **Examples:**
382
+
383
+ ```
384
+ # Preview a file without executing
385
+ execute_sql_file({ filePath: "/path/to/migration.sql", validateOnly: true })
386
+
387
+ # Strip Liquibase delimiters (literal "/" on its own line)
388
+ execute_sql_file({ filePath: "/path/to/liquibase.sql", stripPatterns: ["/"] })
389
+
390
+ # Strip SQL Server GO statements (regex pattern)
391
+ execute_sql_file({
392
+ filePath: "/path/to/sqlserver.sql",
393
+ stripPatterns: ["^\\s*GO\\s*$"],
394
+ stripAsRegex: true
395
+ })
396
+
397
+ # Strip multiple patterns
398
+ execute_sql_file({
399
+ filePath: "/path/to/migration.sql",
400
+ stripPatterns: ["/", "GO", "\\"]
401
+ })
402
+ ```
403
+
404
+ #### `preview_sql_file`
405
+
406
+ Preview a SQL file without executing it. Similar to `mutation_preview` but for SQL files. Shows statement counts by type and warnings for potentially dangerous operations. Use this before `execute_sql_file` to understand what a migration will do.
407
+
408
+ **Parameters:**
409
+
410
+ - `filePath` (required): Absolute or relative path to the `.sql` file to preview
411
+ - `stripPatterns` (optional): Patterns to strip from SQL before parsing (same as execute_sql_file)
412
+ - `stripAsRegex` (optional): If true, treat patterns as regex (default: false)
413
+ - `maxStatements` (optional): Maximum statements to show in preview (default: 20, max: 100)
414
+
415
+ **Returns:**
416
+
417
+ - `filePath`: Resolved file path
418
+ - `fileSize`: File size in bytes
419
+ - `fileSizeFormatted`: Human-readable file size (e.g., "15.2 KB")
420
+ - `totalStatements`: Total executable statements in the file
421
+ - `statementsByType`: Breakdown by statement type (e.g., `{ "CREATE": 5, "INSERT": 10, "ALTER": 2 }`)
422
+ - `statements`: Array of statement previews (up to maxStatements):
423
+ - `index`: Statement number (1-based)
424
+ - `lineNumber`: Line number in file
425
+ - `sql`: Statement SQL (truncated to 300 chars)
426
+ - `type`: Statement type (SELECT, INSERT, CREATE, etc.)
427
+ - `warnings`: Array of warnings for dangerous operations:
428
+ - DROP statements
429
+ - TRUNCATE statements
430
+ - DELETE/UPDATE without WHERE clause
431
+ - `summary`: Human-readable summary (e.g., "File contains 17 statements: 10 INSERT, 5 CREATE, 2 ALTER")
432
+
433
+ **Example:**
434
+
435
+ ```
436
+ preview_sql_file({ filePath: "/path/to/migration.sql" })
437
+ // Returns:
438
+ // {
439
+ // "filePath": "/path/to/migration.sql",
440
+ // "fileSize": 15234,
441
+ // "fileSizeFormatted": "14.9 KB",
442
+ // "totalStatements": 17,
443
+ // "statementsByType": { "CREATE": 5, "INSERT": 10, "ALTER": 2 },
444
+ // "statements": [...],
445
+ // "warnings": ["Statement 15 (line 142): DROP statement detected - will permanently remove database object"],
446
+ // "summary": "File contains 17 statements: 10 INSERT, 5 CREATE, 2 ALTER"
447
+ // }
448
+ ```
449
+
370
450
  #### `mutation_preview`
371
451
 
372
452
  Preview the effect of INSERT, UPDATE, or DELETE statements without executing them. Shows estimated rows affected and a sample of rows that would be modified. Essential for verifying destructive queries before running them.
@@ -392,6 +472,151 @@ mutation_preview({ sql: "DELETE FROM orders WHERE status = 'cancelled'" })
392
472
  // Returns: { mutationType: "DELETE", estimatedRowsAffected: 150, sampleAffectedRows: [...5 rows...] }
393
473
  ```
394
474
 
475
+ #### `mutation_dry_run`
476
+
477
+ **Transaction-based dry-run for mutations.** Actually executes the INSERT/UPDATE/DELETE within a transaction, captures **REAL** results, then ROLLBACK so nothing persists. More accurate than `mutation_preview` because it catches actual constraint violations, trigger effects, and exact row counts.
478
+
479
+ **Non-Rollbackable Operations:** Statements containing explicit `NEXTVAL()` or `SETVAL()` are **skipped** to prevent sequence values from being permanently consumed. For skipped statements, an `EXPLAIN` query plan is provided instead.
480
+
481
+ **Parameters:**
482
+
483
+ - `sql` (required): The INSERT, UPDATE, or DELETE statement to dry-run
484
+ - `sampleSize` (optional): Number of sample rows to return (default: 10, max: 20)
485
+
486
+ **Returns:**
487
+
488
+ - `mutationType`: Type of mutation (INSERT, UPDATE, DELETE)
489
+ - `success`: Whether the dry-run executed successfully
490
+ - `skipped`: If `true`, statement was skipped (contains non-rollbackable operation)
491
+ - `skipReason`: Why the statement was skipped
492
+ - `rowsAffected`: **Actual** number of rows that would be affected
493
+ - `beforeRows`: Sample of rows before the change (for UPDATE/DELETE)
494
+ - `affectedRows`: Sample of rows after the change (for INSERT/UPDATE) or deleted rows
495
+ - `targetTable`: The table being modified
496
+ - `whereClause`: The WHERE clause (if present)
497
+ - `executionTimeMs`: Execution time in milliseconds
498
+ - `error`: Detailed PostgreSQL error information if failed:
499
+ - `message`: Error message
500
+ - `code`: PostgreSQL error code (e.g., '23505' for unique violation)
501
+ - `detail`: Detailed error description
502
+ - `hint`: Hint for fixing the error
503
+ - `constraint`: Constraint name that caused the error
504
+ - `table`, `column`, `schema`: Related database objects
505
+ - `nonRollbackableWarnings`: Warnings about side effects:
506
+ - `operation`: Type of operation (SEQUENCE, VACUUM, etc.)
507
+ - `message`: Warning message
508
+ - `mustSkip`: If `true`, operation was skipped; if `false`, just a warning
509
+ - `warnings`: General warnings (e.g., no WHERE clause)
510
+ - `explainPlan`: Query plan from EXPLAIN (for skipped DML statements with NEXTVAL/SETVAL)
511
+
512
+ **Example:**
513
+
514
+ ```
515
+ mutation_dry_run({ sql: "INSERT INTO users (email) VALUES ('test@test.com')" })
516
+ // On success: { success: true, mutationType: "INSERT", rowsAffected: 1, affectedRows: [{id: 5, email: "test@test.com"}] }
517
+ // On failure: { success: false, error: { code: "23505", constraint: "users_email_key", detail: "Key already exists" } }
518
+
519
+ // With explicit NEXTVAL (skipped):
520
+ mutation_dry_run({ sql: "INSERT INTO users (id) VALUES (nextval('users_id_seq'))" })
521
+ // Returns: { success: true, skipped: true, skipReason: "NEXTVAL increments sequence...", explainPlan: [...] }
522
+ ```
523
+
524
+ #### `dry_run_sql_file`
525
+
526
+ **Transaction-based dry-run for SQL files.** Actually executes ALL statements within a transaction, captures **REAL** results for each statement (row counts, errors with line numbers, constraint violations), then ROLLBACK so nothing persists. Perfect for testing migrations before deploying.
527
+
528
+ **Non-Rollbackable Operations:** The following operations are automatically **skipped** (not executed):
529
+ - **VACUUM, CLUSTER, REINDEX CONCURRENTLY**: Cannot run inside a transaction
530
+ - **CREATE INDEX CONCURRENTLY**: Cannot run inside a transaction
531
+ - **CREATE/DROP DATABASE**: Cannot run inside a transaction
532
+ - **NEXTVAL(), SETVAL()**: Would permanently consume sequence values
533
+
534
+ For skipped DML statements (INSERT/UPDATE/DELETE/SELECT with NEXTVAL/SETVAL), an `EXPLAIN` query plan is provided so you can still see what the query would do.
535
+
536
+ **Parameters:**
537
+
538
+ - `filePath` (required): Absolute or relative path to the `.sql` file
539
+ - `stripPatterns` (optional): Patterns to strip from SQL before execution (e.g., `["/"]` for Liquibase)
540
+ - `stripAsRegex` (optional): If true, treat patterns as regex (default: false)
541
+ - `maxStatements` (optional): Maximum statements to include in results (default: 50, max: 200)
542
+ - `stopOnError` (optional): Stop on first error (default: false - continues to show ALL errors)
543
+
544
+ **Returns:**
545
+
546
+ - `success`: Whether all statements executed successfully (skipped statements don't count as failures)
547
+ - `filePath`: Resolved file path
548
+ - `fileSize`: File size in bytes
549
+ - `fileSizeFormatted`: Human-readable file size
550
+ - `totalStatements`: Total statements in file
551
+ - `successCount`: Number of successful statements
552
+ - `failureCount`: Number of failed statements
553
+ - `skippedCount`: Number of skipped statements (non-rollbackable operations)
554
+ - `totalRowsAffected`: Total rows affected across all statements
555
+ - `statementsByType`: Breakdown by statement type (e.g., `{"CREATE": 5, "INSERT": 10}`)
556
+ - `executionTimeMs`: Total execution time
557
+ - `statementResults`: Array of results for each statement:
558
+ - `index`: Statement number (1-based)
559
+ - `lineNumber`: Line number in file
560
+ - `sql`: The SQL statement (truncated)
561
+ - `type`: Statement type (SELECT, INSERT, CREATE, etc.)
562
+ - `success`: Whether statement succeeded
563
+ - `skipped`: If `true`, statement was skipped (non-rollbackable operation)
564
+ - `skipReason`: Why the statement was skipped
565
+ - `rowCount`: Rows affected/returned
566
+ - `rows`: Sample rows (for SELECT or RETURNING)
567
+ - `executionTimeMs`: Statement execution time
568
+ - `error`: Detailed PostgreSQL error if failed (same fields as `mutation_dry_run`)
569
+ - `warnings`: Warnings for this statement
570
+ - `explainPlan`: Query plan from EXPLAIN (for skipped DML statements)
571
+ - `nonRollbackableWarnings`: Warnings about operations that can't be fully rolled back:
572
+ - `operation`: Type (SEQUENCE, VACUUM, CLUSTER, etc.)
573
+ - `message`: Warning message
574
+ - `mustSkip`: If `true`, operation was skipped; if `false`, just a warning
575
+ - `statementIndex`, `lineNumber`: Location in file
576
+ - `summary`: Human-readable summary
577
+ - `rolledBack`: Always `true` - confirms changes were rolled back
578
+
579
+ **Example:**
580
+
581
+ ```
582
+ dry_run_sql_file({ filePath: "/path/to/migration.sql", stripPatterns: ["/"] })
583
+ // Returns:
584
+ // {
585
+ // "success": false,
586
+ // "totalStatements": 15,
587
+ // "successCount": 12,
588
+ // "failureCount": 2,
589
+ // "skippedCount": 1,
590
+ // "statementResults": [
591
+ // { "index": 1, "lineNumber": 1, "type": "CREATE", "success": true },
592
+ // { "index": 5, "lineNumber": 23, "type": "INSERT", "success": false,
593
+ // "error": { "code": "23505", "constraint": "users_pkey", "detail": "Key already exists" } },
594
+ // { "index": 8, "lineNumber": 45, "type": "SELECT", "success": true, "skipped": true,
595
+ // "skipReason": "NEXTVAL increments sequence...", "explainPlan": [...] },
596
+ // ...
597
+ // ],
598
+ // "nonRollbackableWarnings": [
599
+ // { "operation": "SEQUENCE", "message": "INSERT may consume sequence values...", "mustSkip": false },
600
+ // { "operation": "SEQUENCE", "message": "NEXTVAL increments sequence...", "mustSkip": true }
601
+ // ],
602
+ // "summary": "Dry-run of 15 statements: 12 succeeded, 2 failed, 1 skipped (non-rollbackable). All changes rolled back.",
603
+ // "rolledBack": true
604
+ // }
605
+ ```
606
+
607
+ **When to use `dry_run_sql_file` vs `preview_sql_file`:**
608
+
609
+ | Feature | `preview_sql_file` | `dry_run_sql_file` |
610
+ |---------|-------------------|-------------------|
611
+ | Speed | Fast (just parsing) | Slower (actual execution) |
612
+ | Detects syntax errors | Basic | **Actual PostgreSQL errors** |
613
+ | Detects constraint violations | No | **Yes** |
614
+ | Detects trigger effects | No | **Yes** |
615
+ | Accurate row counts | No (estimates) | **Yes (actual)** |
616
+ | Shows error details | No | **Yes (code, constraint, hint)** |
617
+ | Consumes sequences | No | **No (NEXTVAL/SETVAL skipped)** |
618
+ | Shows query plan for skipped ops | N/A | **Yes (EXPLAIN)** |
619
+
395
620
  #### `batch_execute`
396
621
 
397
622
  Execute multiple SQL queries in parallel. Returns all results keyed by query name. Efficient for fetching multiple independent pieces of data in a single call.