nexql-tools 0.4.1

MCP tool registry, JSON schemas, executors
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 NexQL-OSS Team

//! Tool descriptors for the active MCP surface (Phase 2–4).

use serde_json::{Value, json};

use crate::registry::{ToolName, ToolProfile};

#[derive(Debug, Clone)]
pub struct ToolSpec {
    pub name: ToolName,
    pub description: &'static str,
    pub input_schema: Value,
}

/// Tools filtered by the requested `ToolProfile`.
pub fn tools_for_profile(profile: ToolProfile) -> Vec<ToolSpec> {
    let names = ToolName::for_profile(profile);
    active_tools()
        .into_iter()
        .filter(|spec| names.contains(&spec.name))
        .collect()
}

/// Generate a formatted Mermaid ERD snippet for an object's column & key structure.
pub fn generate_mermaid_erd_for_object(obj: &serde_json::Map<String, Value>) -> Option<String> {
    let ref_name = obj.get("ref").and_then(|v| v.as_str()).unwrap_or("table");
    let safe_table_name = ref_name.replace(['.', '-'], "_");
    let mut diagram = String::from("erDiagram\n");
    diagram.push_str(&format!("    {safe_table_name} {{\n"));
    if let Some(columns) = obj.get("columns").and_then(|v| v.as_array()) {
        for col in columns {
            let name = col.get("name").and_then(|v| v.as_str()).unwrap_or("col");
            let data_type = col.get("type").and_then(|v| v.as_str()).unwrap_or("string");
            let pk = col.get("is_pk").and_then(|v| v.as_bool()).unwrap_or(false);
            let fk = col.get("is_fk").and_then(|v| v.as_bool()).unwrap_or(false);
            let key_str = match (pk, fk) {
                (true, true) => " PK,FK",
                (true, false) => " PK",
                (false, true) => " FK",
                _ => "",
            };
            diagram.push_str(&format!(
                "        {} {}{}\n",
                data_type.replace(' ', "_"),
                name,
                key_str
            ));
        }
    }
    diagram.push_str("    }\n");
    Some(diagram)
}

/// Generate a formatted Mermaid ERD diagram snippet for a FK join path.
pub fn generate_mermaid_diagram_for_path(path_val: &Value) -> Option<String> {
    let edges = path_val
        .as_array()
        .or_else(|| path_val.get("path").and_then(|v| v.as_array()))?;
    if edges.is_empty() {
        return None;
    }
    let mut diagram = String::from("erDiagram\n");
    for edge in edges {
        let from = edge
            .get("from")
            .and_then(|v| v.as_str())
            .unwrap_or("A")
            .replace(['.', '-'], "_");
        let to = edge
            .get("to")
            .and_then(|v| v.as_str())
            .unwrap_or("B")
            .replace(['.', '-'], "_");
        let from_col = edge.get("from_col").and_then(|v| v.as_str()).unwrap_or("");
        let to_col = edge.get("to_col").and_then(|v| v.as_str()).unwrap_or("");
        diagram.push_str(&format!(
            "    {from} }}|--|| {to} : \"{from_col} -> {to_col}\"\n"
        ));
    }
    Some(diagram)
}

/// Phase 2 catalog tools (live Postgres; no index required).
pub fn phase2_catalog_tools() -> Vec<ToolSpec> {
    vec![
        ToolSpec {
            name: ToolName::ListConnections,
            description: "List configured connection profiles (never includes passwords).",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::ListDatabases,
            description: "List databases available for a connection profile.",
            input_schema: object_schema(&[(
                "connectionId",
                "string",
                true,
                "Name of a configured connection profile, as returned by list_connections.",
            )]),
        },
        ToolSpec {
            name: ToolName::ListSchemas,
            description: "List non-system schemas in the currently selected database.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::ListObjects,
            description: "List objects (tables, views, …) in a schema.",
            input_schema: object_schema(&[
                (
                    "schema",
                    "string",
                    false,
                    "Schema name to list, e.g. \"public\". Defaults to all non-system schemas.",
                ),
                (
                    "kind",
                    "string",
                    false,
                    "Filter by object kind: \"table\", \"view\", or \"materialized_view\".",
                ),
                (
                    "include_partitions",
                    "boolean",
                    false,
                    "When true, list child partition tables individually. Default false groups partitioned parents.",
                ),
                (
                    "connectionId",
                    "string",
                    false,
                    "Optional connection profile override — does not change session context.",
                ),
                (
                    "database",
                    "string",
                    false,
                    "Database on connectionId. Requires connectionId when set.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::GetCurrentContext,
            description: "Return the active profile, database, and access mode.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::SwitchConnection,
            description: "Switch the session to another connection profile / database.",
            input_schema: object_schema(&[
                (
                    "connectionId",
                    "string",
                    true,
                    "Name of a configured connection profile, as returned by list_connections.",
                ),
                (
                    "database",
                    "string",
                    false,
                    "Database name on that connection. Defaults to the profile's configured database.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::RunSelect,
            description: "Run a read-only SELECT or WITH query. DML/DDL are rejected. Supports parameterized execution via `params` ($1, $2, …). Results default to 50 rows with total_count and has_more pagination metadata.",
            input_schema: object_schema(&[
                (
                    "sql",
                    "string",
                    true,
                    "A single SELECT or WITH statement, schema-qualify table names where possible.",
                ),
                (
                    "params",
                    "array",
                    false,
                    "Bound parameters for $1, $2, … in `sql`. JSON values: string, number, boolean, or null.",
                ),
                (
                    "limit",
                    "number",
                    false,
                    "Maximum rows to return. Defaults to 50; capped by profile max_rows.",
                ),
                (
                    "format",
                    "string",
                    false,
                    "Output format: \"compact\" (default columnar), \"json\", \"markdown\", or \"csv\".",
                ),
                (
                    "connectionId",
                    "string",
                    false,
                    "Optional connection profile override — does not change session context.",
                ),
                (
                    "database",
                    "string",
                    false,
                    "Database on connectionId. Requires connectionId when set.",
                ),
                (
                    "resolve_fks",
                    "boolean",
                    false,
                    "When true, add __resolved suffix columns for foreign-key IDs in the result.",
                ),
                (
                    "timeout_ms",
                    "number",
                    false,
                    "Per-query statement timeout in milliseconds; capped by profile statement_timeout_ms.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::ExplainQuery,
            description: "Run EXPLAIN (no ANALYZE execute) for a SELECT/WITH query.",
            input_schema: object_schema(&[
                (
                    "sql",
                    "string",
                    true,
                    "A single SELECT or WITH statement to explain (not executed).",
                ),
                (
                    "connectionId",
                    "string",
                    false,
                    "Optional connection profile override — does not change session context.",
                ),
                (
                    "database",
                    "string",
                    false,
                    "Database on connectionId. Requires connectionId when set.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::DiscoverTools,
            description: "Dynamically discover and inspect specialized MCP database tools by keyword query (e.g., 'locks', 'bloat', 'index') or category ('query', 'dba', 'write'). Use this when you need specialized tools beyond the core surface.",
            input_schema: object_schema(&[
                (
                    "query",
                    "string",
                    false,
                    "Free-text keyword to search tool names/descriptions, e.g. \"locks\" or \"bloat\".",
                ),
                (
                    "category",
                    "string",
                    false,
                    "Restrict to a tool category: \"query\", \"dba\", \"meta\", or \"write\".",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::RunDoctor,
            description: "Run diagnostic health checks on active database connection, permissions, session guards, and index status.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::SetupConnection,
            description: "Automatically detect or configure a database connection. Scans environment variables, workspace files, and local settings, eliciting missing credentials when supported.",
            input_schema: object_schema(&[
                ("name", "string", false, "Profile name to assign/detect."),
                (
                    "url",
                    "string",
                    false,
                    "Full postgres:// connection URL; if given, host/port/dbname/user/password are ignored.",
                ),
                ("host", "string", false, "Database server hostname."),
                (
                    "port",
                    "number",
                    false,
                    "Database server port (default 5432).",
                ),
                ("dbname", "string", false, "Database name to connect to."),
                ("user", "string", false, "Database role/username."),
                (
                    "password",
                    "string",
                    false,
                    "Database role password. Never written to disk in plaintext — stored in the OS keyring, or the call fails with the password_command/password_file alternative.",
                ),
                (
                    "sslmode",
                    "string",
                    false,
                    "libpq sslmode value, e.g. \"disable\", \"require\", \"verify-full\".",
                ),
                (
                    "interactive",
                    "boolean",
                    false,
                    "Prompt (elicit) for missing credentials instead of failing. Default false.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::SaveProfile,
            description: "Save or update a database connection profile in user configuration with atomic backup and dynamic session reload.",
            input_schema: object_schema(&[
                ("name", "string", true, "Profile name to save under."),
                (
                    "url",
                    "string",
                    false,
                    "Full postgres:// connection URL; if given, host/port/dbname/user/password are ignored.",
                ),
                ("host", "string", false, "Database server hostname."),
                (
                    "port",
                    "number",
                    false,
                    "Database server port (default 5432).",
                ),
                ("dbname", "string", false, "Database name to connect to."),
                ("user", "string", false, "Database role/username."),
                (
                    "password",
                    "string",
                    false,
                    "Database role password. Never written to disk in plaintext — stored in the OS keyring, or the call fails with the password_command/password_file alternative.",
                ),
                (
                    "sslmode",
                    "string",
                    false,
                    "libpq sslmode value, e.g. \"disable\", \"require\", \"verify-full\".",
                ),
                (
                    "access_mode",
                    "string",
                    false,
                    "Session access mode: \"read\", \"write\", or \"admin\". Setting \"write\" or \"admin\" requires confirm_elevated_access: true, or the call is rejected.",
                ),
                (
                    "confirm_elevated_access",
                    "boolean",
                    false,
                    "Required (must be true) when access_mode is \"write\" or \"admin\" — explicit opt-in for a privilege escalation. No effect when access_mode is omitted or \"read\".",
                ),
                (
                    "max_rows",
                    "number",
                    false,
                    "Row cap applied to run_select/export_query for this profile.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::TestProfile,
            description: "Test a database connection profile or inline parameters and return server version, superuser status, and round-trip latency.",
            input_schema: object_schema(&[
                (
                    "name",
                    "string",
                    false,
                    "Existing profile name to test. Omit to test inline parameters instead.",
                ),
                (
                    "url",
                    "string",
                    false,
                    "Full postgres:// connection URL to test inline (alternative to name).",
                ),
                (
                    "host",
                    "string",
                    false,
                    "Database server hostname (inline test).",
                ),
                (
                    "port",
                    "number",
                    false,
                    "Database server port (inline test).",
                ),
                ("dbname", "string", false, "Database name (inline test)."),
                (
                    "user",
                    "string",
                    false,
                    "Database role/username (inline test).",
                ),
                (
                    "password",
                    "string",
                    false,
                    "Database role password (inline test).",
                ),
                (
                    "sslmode",
                    "string",
                    false,
                    "libpq sslmode value (inline test), e.g. \"require\".",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::ExportProfile,
            description: "Export a secret-sanitized TOML configuration for team sharing (.nexql/config.toml) with all passwords and credentials stripped.",
            input_schema: object_schema(&[(
                "format",
                "string",
                false,
                "Output format, currently only \"toml\" is supported (default).",
            )]),
        },
        ToolSpec {
            name: ToolName::ImportProfile,
            description: "Import a team configuration file (.nexql/config.toml) or TOML content into local user configuration.",
            input_schema: object_schema(&[
                (
                    "content",
                    "string",
                    false,
                    "Raw TOML content to import. Provide this or `path`, not both.",
                ),
                (
                    "path",
                    "string",
                    false,
                    "Filesystem path to a .nexql/config.toml file to import.",
                ),
            ]),
        },
    ]
}

/// Phase 3 index tools (require `nexql-mcp index build`).
pub fn phase3_index_tools() -> Vec<ToolSpec> {
    vec![
        ToolSpec {
            name: ToolName::ResolveTarget,
            description: "Autonomously find which connection/database matches a user's hint (a database name, environment, host fragment) and/or an object hint (a table/view name), searching across ALL configured connections and their indexed schemas. Call this FIRST whenever the request references a database, environment, or object that is not the current session context — before search_schema, before list_connections. When the match is unambiguous it switches the session context automatically and returns the resolved connection/database; only returns `ambiguous: true` with a candidate list when multiple equally-plausible matches exist, in which case surface those candidates to the user rather than guessing.",
            input_schema: object_schema(&[
                (
                    "hint",
                    "string",
                    false,
                    "Free-text hint about the target connection: database name, environment, or host fragment.",
                ),
                (
                    "objectHint",
                    "string",
                    false,
                    "Free-text hint about a table/view name expected to live in the target database.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::Orient,
            description: "One-call schema bootstrap digest: tables (columns, PK, row estimate), FK join edges (declared vs inferred), enum-like low-cardinality text columns, and degradation notes. Call this FIRST on an unfamiliar database — before search_schema, describe_object, or get_join_path — to build context in a single low-token round trip instead of many.",
            input_schema: object_schema(&[(
                "focus",
                "string",
                false,
                "Substring to filter tables/joins by ref (e.g. \"orders\"). Omit to summarize the whole indexed schema.",
            )]),
        },
        ToolSpec {
            name: ToolName::InspectOrSearch,
            description: "Composite schema discovery: search by keywords and return matching objects with columns, keys, and row estimates in one call — replaces search_schema → describe_object chains.",
            input_schema: object_schema(&[
                (
                    "query",
                    "string",
                    true,
                    "Natural-language or keyword search, e.g. \"cash card\".",
                ),
                (
                    "include_columns",
                    "boolean",
                    false,
                    "Include per-column definitions in each match. Default true.",
                ),
                (
                    "limit_objects",
                    "number",
                    false,
                    "Maximum matching objects to return. Default 3.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::SearchAllDatabases,
            description: "Cross-database schema search: find which connection/database owns an entity across all configured profiles and indexed databases.",
            input_schema: object_schema(&[
                (
                    "query",
                    "string",
                    true,
                    "Table/view name or keyword to search across all connections and databases.",
                ),
                (
                    "limit_per_database",
                    "number",
                    false,
                    "Max hits per connection/database pair. Default 3.",
                ),
                (
                    "limit_connections",
                    "number",
                    false,
                    "Max connection/database pairs to search. Default 20.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::SearchSchema,
            description: "Search the live, auto-indexed database schema using natural language or keywords to find tables, views, materialized views, and functions matching the query. Call this FIRST before writing any SQL — do not assume a table exists without finding it here.",
            input_schema: object_schema(&[(
                "query",
                "string",
                true,
                "Natural-language or keyword search, e.g. \"customer email\".",
            )]),
        },
        ToolSpec {
            name: ToolName::DescribeObject,
            description: "Get structural details of a specific database object (table, view, or materialized view) including columns, data types, constraints, and indexes.",
            input_schema: object_schema(&[
                (
                    "ref",
                    "string",
                    true,
                    "Object reference. Prefer schema-qualified form \"schema.name\" (e.g. \"public.customers\"); a bare name is resolved if unambiguous.",
                ),
                (
                    "resolve_refs",
                    "boolean",
                    false,
                    "When true, attach enum values and resolved FK label samples on columns.",
                ),
                (
                    "resolve_refs_limit",
                    "number",
                    false,
                    "Max distinct FK values to resolve per column when resolve_refs is true. Default 20.",
                ),
                (
                    "connectionId",
                    "string",
                    false,
                    "Optional connection profile override — does not change session context.",
                ),
                (
                    "database",
                    "string",
                    false,
                    "Database on connectionId. Requires connectionId when set.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::GetJoinPath,
            description: "Find the shortest path of join relationships and foreign keys between two database tables.",
            input_schema: object_schema(&[
                (
                    "a",
                    "string",
                    true,
                    "Source table reference. Prefer schema-qualified form \"schema.name\" (e.g. \"public.orders\"); a bare name is resolved if unambiguous.",
                ),
                (
                    "b",
                    "string",
                    true,
                    "Target table reference. Prefer schema-qualified form \"schema.name\" (e.g. \"public.customers\"); a bare name is resolved if unambiguous.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::SampleValues,
            description: "Retrieve a list of sample values from a specific table column to inspect its contents. Only works on read-only SELECT queries.",
            input_schema: object_schema(&[
                (
                    "ref",
                    "string",
                    true,
                    "Table/view reference. Prefer schema-qualified form \"schema.name\" (e.g. \"public.orders\"); a bare name is resolved if unambiguous.",
                ),
                (
                    "col",
                    "string",
                    true,
                    "Column name within `ref` to sample values from.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::RebuildIndex,
            description: "Rebuild the schema index for the active database connection.",
            input_schema: object_schema(&[(
                "depth",
                "string",
                false,
                "Index scope: \"shallow\" (structure only) or \"full\" (structure + sample values). Default \"full\".",
            )]),
        },
        ToolSpec {
            name: ToolName::RefreshIndex,
            description: "Refresh the schema index for the active database connection using previous build scope.",
            input_schema: object_schema(&[]),
        },
    ]
}

/// Phase 4 monitoring / DDL tools (descriptions from ToolSpec.ts where available).
pub fn phase4_tools() -> Vec<ToolSpec> {
    vec![
        ToolSpec {
            name: ToolName::GetDdl,
            description: "Get the DDL / definition of a database object. Views, materialized views, functions, and indexes return their CREATE statement; tables return structured DDL (columns, constraints, indexes).",
            input_schema: object_schema(&[
                (
                    "ref",
                    "string",
                    true,
                    "Object reference. Prefer schema-qualified form \"schema.name\" (e.g. \"public.orders\"); a bare name is resolved if unambiguous.",
                ),
                (
                    "kind",
                    "string",
                    false,
                    "Object kind hint: \"table\", \"view\", \"materialized_view\", \"function\", or \"index\". Auto-detected if omitted.",
                ),
                (
                    "connectionId",
                    "string",
                    false,
                    "Optional connection profile override — does not change session context.",
                ),
                (
                    "database",
                    "string",
                    false,
                    "Database on connectionId. Requires connectionId when set.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::TableStats,
            description: "Get size, row-count, activity (scans, inserts/updates/deletes, dead tuples, vacuum/analyze times) and per-column statistics for a specific table.",
            input_schema: object_schema(&[
                (
                    "ref",
                    "string",
                    true,
                    "Table reference. Prefer schema-qualified form \"schema.name\" (e.g. \"public.orders\"); a bare name is resolved if unambiguous.",
                ),
                (
                    "connectionId",
                    "string",
                    false,
                    "Optional connection profile override — does not change session context.",
                ),
                (
                    "database",
                    "string",
                    false,
                    "Database on connectionId. Requires connectionId when set.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::IndexUsage,
            description: "Get index usage statistics (scan counts, size, definition, type) for a specific table's indexes. Useful for finding unused or missing indexes.",
            input_schema: object_schema(&[(
                "ref",
                "string",
                true,
                "Table reference. Prefer schema-qualified form \"schema.name\" (e.g. \"public.orders\"); a bare name is resolved if unambiguous.",
            )]),
        },
        ToolSpec {
            name: ToolName::ListRunningQueries,
            description: "List currently executing (non-idle) queries in the connected database with pid, user, state, wait events, and duration.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::FindBlockingLocks,
            description: "Find lock contention: which queries are blocked waiting on locks and which pids/queries are blocking them.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::SlowQueries,
            description: "List the slowest statements by mean execution time from pg_stat_statements (requires the extension; returns a hint if not installed).",
            input_schema: object_schema(&[(
                "limit",
                "number",
                false,
                "Maximum number of statements to return. Default 10.",
            )]),
        },
        ToolSpec {
            name: ToolName::DbHealthCheck,
            description: "Run a database health overview: size/connection stats, cache hit ratio, tables with dead tuples needing vacuum, active connections, and blocking-lock count. Sections that fail are reported individually; partial results are still returned.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::GetIndexStatus,
            description: "Return schema-index status for the active connection/database: indexed_at, fingerprint, object counts, and optional live fingerprint drift. Returns status:\"missing\" (not an error) if no index has been built yet.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::ListExtensions,
            description: "List installed PostgreSQL extensions (name, version, schema).",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::ServerSettings,
            description: "Return key PostgreSQL server settings from pg_settings (memory, connections, timeouts, autovacuum, version).",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::SuggestIndexes,
            description: "Suggest indexes from high sequential-scan tables, unindexed FK columns, and optional pg_stat_statements / EXPLAIN plan heuristics. Pass sql to analyze a specific query plan.",
            input_schema: object_schema(&[
                (
                    "limit",
                    "number",
                    false,
                    "Maximum number of suggestions to return. Default 10.",
                ),
                (
                    "sql",
                    "string",
                    false,
                    "Optional SELECT/WITH statement whose plan should inform the suggestions.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::FindUnusedIndexes,
            description: "List indexes with idx_scan = 0 (never used since stats reset), excluding primary keys, unique indexes, and constraint-backed indexes.",
            input_schema: object_schema(&[(
                "limit",
                "number",
                false,
                "Maximum number of indexes to return. Default 10.",
            )]),
        },
        ToolSpec {
            name: ToolName::BloatReport,
            description: "Approximate table bloat via dead-tuple ratio from pg_stat_user_tables (simplified estimate — not physical page bloat). Tables with >1000 dead tuples, ordered by bloat %.",
            input_schema: object_schema(&[(
                "limit",
                "number",
                false,
                "Maximum number of tables to return. Default 10.",
            )]),
        },
        ToolSpec {
            name: ToolName::FindMissingFks,
            description: "Find likely missing foreign keys: prefers schema-index join-graph inferred edges; falls back to catalog naming (*_id columns without an FK matching a PK).",
            input_schema: object_schema(&[(
                "limit",
                "number",
                false,
                "Maximum number of candidates to return. Default 20.",
            )]),
        },
    ]
}

/// Phase 4b read-only breadth (export / role introspection).
pub fn phase4b_tools() -> Vec<ToolSpec> {
    vec![
        ToolSpec {
            name: ToolName::ExportQuery,
            description: "Run a read-only SELECT/WITH and format results as CSV, JSON, or SQL INSERT statements. Honors max-row / max-char caps. For sqlinsert, pass table as schema.name.",
            input_schema: object_schema(&[
                (
                    "sql",
                    "string",
                    true,
                    "A single SELECT or WITH statement to run and export.",
                ),
                (
                    "format",
                    "string",
                    false,
                    "Output format: \"csv\", \"json\", or \"sqlinsert\". Default \"csv\".",
                ),
                (
                    "table",
                    "string",
                    false,
                    "Target table as \"schema.name\", required when format=\"sqlinsert\".",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::ListRoles,
            description: "List PostgreSQL roles (attributes). Pass role to get memberships and table privileges for one role.",
            input_schema: object_schema(&[(
                "role",
                "string",
                false,
                "Specific role name to inspect memberships/privileges for. Omit to list all roles.",
            )]),
        },
        ToolSpec {
            name: ToolName::DbDashboard,
            description: "One-shot live metrics bundle: DB size/owner, connection-state breakdown, top tables by size, object counts, active queries, and blocking locks. Soft-fails per section.",
            input_schema: object_schema(&[]),
        },
        ToolSpec {
            name: ToolName::DeepPlanAnalysis,
            description: "Run EXPLAIN (ANALYZE by default) and return parsed plan metrics (scan counts, bottlenecks, buffer stats) plus severity-graded findings: estimate skew, expensive function/CTE/subquery nodes, and recommendations. Set analyze=false for plan-only (no execution). The single query-plan-analysis tool — covers what separate explain_analyze/analyze_query_plan tools used to.",
            input_schema: object_schema(&[
                (
                    "sql",
                    "string",
                    true,
                    "A single SELECT or WITH statement to analyze.",
                ),
                (
                    "analyze",
                    "boolean",
                    false,
                    "If false, use plan-only estimates without executing the query. Default true.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::SchemaDiff,
            description: "Compare two schemas in the current database (or sourceSchema vs targetSchema). Returns structured table/column/constraint/index diffs. Read-only — does not apply changes.",
            input_schema: object_schema(&[
                (
                    "sourceSchema",
                    "string",
                    true,
                    "Name of the schema to treat as the baseline, e.g. \"public\".",
                ),
                (
                    "targetSchema",
                    "string",
                    true,
                    "Name of the schema to diff against the baseline, e.g. \"staging\".",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::GenerateMigration,
            description: "Emit migration SQL to evolve sourceSchema toward targetSchema (from a live schema_diff). Read-only — returns SQL text, never executes it. Destructive drops are commented out.",
            input_schema: object_schema(&[
                (
                    "sourceSchema",
                    "string",
                    true,
                    "Name of the schema to migrate from, e.g. \"public\".",
                ),
                (
                    "targetSchema",
                    "string",
                    true,
                    "Name of the schema to migrate towards, e.g. \"staging\".",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::AutoTuneQuery,
            description: "Autonomous query tuner: executes EXPLAIN ANALYZE, checks table statistics, evaluates missing indexes, and outputs step-by-step performance tuning recommendations.",
            input_schema: object_schema(&[(
                "sql",
                "string",
                true,
                "A single SELECT or WITH statement to tune. It executes for real.",
            )]),
        },
        ToolSpec {
            name: ToolName::CheckDdlSafety,
            description: "Safety guard for migration DDL: inspects SQL for dangerous exclusive locks (e.g. non-concurrent index builds, column drops, table rewrites) and outputs risk scores and safe zero-downtime alternatives.",
            input_schema: object_schema(&[(
                "ddl",
                "string",
                true,
                "One or more DDL statements to inspect for locking risk. Not executed.",
            )]),
        },
    ]
}

/// Phase 9 write/admin tools (always listed; access-gated at dispatch).
pub fn phase9_write_tools() -> Vec<ToolSpec> {
    vec![
        ToolSpec {
            name: ToolName::ExecuteSql,
            description: "Execute DML (and DDL in admin mode) inside an explicit transaction. Set dry_run=true to roll back after execution. Errors always roll back.",
            input_schema: object_schema(&[
                (
                    "sql",
                    "string",
                    true,
                    "A single DML statement (INSERT/UPDATE/DELETE), or DDL if the session is in admin mode.",
                ),
                (
                    "dry_run",
                    "boolean",
                    false,
                    "If true, execute then roll back so no change persists. Default false.",
                ),
                (
                    "include_diff",
                    "boolean",
                    false,
                    "When true (default when dry_run), capture before/after row snapshots for UPDATE/DELETE.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::EditRow,
            description: "Structured insert, update, or delete by primary key. The server builds parameterized SQL — pass table (schema.name), action, values, and pk for update/delete.",
            input_schema: object_schema(&[
                ("table", "string", true, "Target table as \"schema.name\"."),
                (
                    "action",
                    "string",
                    true,
                    "Operation to perform: \"insert\", \"update\", or \"delete\".",
                ),
                (
                    "values",
                    "object",
                    false,
                    "Column name/value pairs to insert or update. Required for insert/update.",
                ),
                (
                    "pk",
                    "object",
                    false,
                    "Primary-key column name/value pairs identifying the row. Required for update/delete.",
                ),
                (
                    "dry_run",
                    "boolean",
                    false,
                    "If true, execute then roll back so no change persists. Default false.",
                ),
                (
                    "include_diff",
                    "boolean",
                    false,
                    "When true (default when dry_run), capture before/after row snapshots for update/delete.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::ImportData,
            description: "Batch INSERT rows from a JSON array of objects into a table. Optional columns array fixes column order; otherwise keys from the first row are used.",
            input_schema: object_schema(&[
                ("table", "string", true, "Target table as \"schema.name\"."),
                (
                    "rows",
                    "array",
                    true,
                    "Array of row objects, each mapping column name to value.",
                ),
                (
                    "columns",
                    "array",
                    false,
                    "Explicit column order to insert with. Defaults to the keys of the first row.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::ApplyDdl,
            description: "Apply a DDL statement (CREATE, ALTER, DROP, TRUNCATE, …) in admin mode inside a transaction. Set dry_run=true to roll back.",
            input_schema: object_schema(&[
                ("sql", "string", true, "A single DDL statement to apply."),
                (
                    "dry_run",
                    "boolean",
                    false,
                    "If true, execute then roll back so no change persists. Default false.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::CreateIndexConcurrently,
            description: "Run CREATE INDEX CONCURRENTLY outside a transaction (non-blocking index build). Admin mode only.",
            input_schema: object_schema(&[(
                "sql",
                "string",
                true,
                "A single CREATE INDEX CONCURRENTLY statement.",
            )]),
        },
        ToolSpec {
            name: ToolName::RunMaintenance,
            description: "Run VACUUM, ANALYZE, or REINDEX outside a transaction. Admin mode only. Optional table (schema.name); vacuum supports full=true.",
            input_schema: object_schema(&[
                (
                    "action",
                    "string",
                    true,
                    "Maintenance action: \"vacuum\", \"analyze\", or \"reindex\".",
                ),
                (
                    "table",
                    "string",
                    false,
                    "Target table as \"schema.name\". Omit to run against the whole database where supported.",
                ),
                (
                    "full",
                    "boolean",
                    false,
                    "For action=\"vacuum\", run VACUUM FULL (rewrites the table, takes an exclusive lock). Default false.",
                ),
            ]),
        },
        ToolSpec {
            name: ToolName::TerminateQuery,
            description: "Cancel (pg_cancel_backend) or force-terminate (pg_terminate_backend) a backend by pid. Admin mode only. Refuses superuser targets and the current session.",
            input_schema: object_schema(&[
                (
                    "pid",
                    "number",
                    true,
                    "Backend process id to cancel/terminate.",
                ),
                (
                    "force",
                    "boolean",
                    false,
                    "If true, force-terminate the backend (pg_terminate_backend) instead of a soft cancel. Default false.",
                ),
            ]),
        },
    ]
}

/// Full tools/list surface for the current phase (catalog + index + Phase 4 + 4b + 9).
pub fn active_tools() -> Vec<ToolSpec> {
    let mut specs = phase2_catalog_tools();
    specs.extend(phase3_index_tools());
    specs.extend(phase4_tools());
    specs.extend(phase4b_tools());
    specs.extend(phase9_write_tools());
    specs
}

/// JSON Schema fragment for array-typed tool parameters.
/// Strict MCP clients (Cursor, Copilot, Gemini) reject `"type": "array"` without `items`.
fn array_items_schema(prop_name: &str) -> Value {
    match prop_name {
        "columns" => json!({ "type": "string" }),
        "rows" => json!({
            "type": "object",
            "additionalProperties": true
        }),
        "params" => json!({
            "oneOf": [
                { "type": "string" },
                { "type": "number" },
                { "type": "boolean" },
                { "type": "null" }
            ]
        }),
        // Safe default for any future array param — never emit bare `{}`.
        _ => json!({ "type": "string" }),
    }
}

/// Build a JSON Schema object for a tool's input, from `(name, type, required, description)`
/// tuples. Every property carries a non-empty description (see `all_tools_have_descriptions`
/// test) and the object forbids unknown properties so a typo'd/hallucinated argument fails
/// loudly instead of silently vanishing.
fn object_schema(props: &[(&str, &str, bool, &str)]) -> Value {
    let mut properties = serde_json::Map::new();
    let mut required = Vec::new();
    for (name, ty, req, description) in props {
        let mut prop_val = match *ty {
            "array" => json!({
                "type": "array",
                "items": array_items_schema(name),
            }),
            _ => json!({ "type": *ty }),
        };
        prop_val["description"] = json!(*description);
        properties.insert((*name).into(), prop_val);
        if *req {
            required.push(json!(*name));
        }
    }
    json!({
        "type": "object",
        "properties": properties,
        "required": required,
        "additionalProperties": false
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::registry::ToolName;

    #[test]
    fn active_tools_lists_fifty_four() {
        let specs = active_tools();
        assert_eq!(specs.len(), 54);
        assert_eq!(specs.len(), ToolName::ACTIVE.len());
        for (spec, name) in specs.iter().zip(ToolName::ACTIVE.iter()) {
            assert_eq!(spec.name, *name);
        }
    }

    #[test]
    fn phase9_write_tools_count() {
        assert_eq!(phase9_write_tools().len(), ToolName::PHASE9.len());
    }

    #[test]
    fn array_properties_have_items() {
        fn items_schema_is_valid(items: &Value) -> bool {
            items.get("type").is_some()
                || items.get("oneOf").is_some()
                || items.get("anyOf").is_some()
                || items.get("allOf").is_some()
        }

        for tool in active_tools() {
            if let Some(props) = tool
                .input_schema
                .get("properties")
                .and_then(|p| p.as_object())
            {
                for (prop_name, prop_val) in props {
                    if prop_val.get("type").and_then(|t| t.as_str()) == Some("array") {
                        let items = prop_val.get("items").unwrap_or_else(|| {
                            panic!(
                                "Tool '{}' parameter '{}' is array type but missing 'items'",
                                tool.name.as_str(),
                                prop_name
                            )
                        });
                        assert!(
                            items_schema_is_valid(items),
                            "Tool '{}' parameter '{}' has array items without a concrete schema",
                            tool.name.as_str(),
                            prop_name
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn import_data_rows_and_columns_have_typed_items() {
        let spec = active_tools()
            .into_iter()
            .find(|t| t.name == ToolName::ImportData)
            .expect("import_data tool");
        let props = spec
            .input_schema
            .get("properties")
            .and_then(|p| p.as_object())
            .expect("import_data properties");
        let rows = &props["rows"];
        assert_eq!(rows["type"], "array");
        assert_eq!(rows["items"]["type"], "object");
        assert_eq!(rows["items"]["additionalProperties"], true);
        let columns = &props["columns"];
        assert_eq!(columns["type"], "array");
        assert_eq!(columns["items"]["type"], "string");
    }

    #[test]
    fn profile_tools_filtering() {
        let query_specs = tools_for_profile(ToolProfile::Query);
        assert_eq!(query_specs.len(), 21);

        let dba_specs = tools_for_profile(ToolProfile::Dba);
        assert_eq!(dba_specs.len(), 26);

        let meta_specs = tools_for_profile(ToolProfile::Meta);
        assert_eq!(meta_specs.len(), 13);

        let full_specs = tools_for_profile(ToolProfile::Full);
        assert_eq!(full_specs.len(), 54);
    }

    /// Regression guard for Issue 1: every tool parameter must carry a non-empty
    /// `description`, and every input schema must forbid unknown properties.
    #[test]
    fn all_tools_have_descriptions_and_reject_unknown_properties() {
        for tool in active_tools() {
            assert_eq!(
                tool.input_schema.get("additionalProperties"),
                Some(&json!(false)),
                "Tool '{}' input_schema must set additionalProperties: false",
                tool.name.as_str()
            );
            if let Some(props) = tool
                .input_schema
                .get("properties")
                .and_then(|p| p.as_object())
            {
                for (prop_name, prop_val) in props {
                    let desc = prop_val.get("description").and_then(|d| d.as_str());
                    assert!(
                        desc.is_some_and(|d| !d.is_empty()),
                        "Tool '{}' parameter '{}' is missing a non-empty description",
                        tool.name.as_str(),
                        prop_name
                    );
                }
            }
        }
    }

    #[test]
    fn generate_mermaid_erd_test() {
        let obj = json!({
            "ref": "public.users",
            "columns": [
                { "name": "id", "type": "uuid", "is_pk": true, "is_fk": false },
                { "name": "email", "type": "varchar", "is_pk": false, "is_fk": false },
                { "name": "org_id", "type": "uuid", "is_pk": false, "is_fk": true }
            ]
        });
        let diagram = generate_mermaid_erd_for_object(obj.as_object().unwrap()).unwrap();
        assert!(diagram.contains("erDiagram"));
        assert!(diagram.contains("public_users"));
        assert!(diagram.contains("uuid id PK"));
        assert!(diagram.contains("uuid org_id FK"));
    }

    #[test]
    fn generate_mermaid_diagram_for_path_test() {
        let path = json!([
            { "from": "public.orders", "to": "public.users", "from_col": "user_id", "to_col": "id" }
        ]);
        let diagram = generate_mermaid_diagram_for_path(&path).unwrap();
        assert!(diagram.contains("erDiagram"));
        assert!(diagram.contains("public_orders }|--|| public_users : \"user_id -> id\""));
    }
}