db-mcp 1.0.2 → 1.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.
Files changed (241) hide show
  1. package/.gitattributes +2 -0
  2. package/LICENSE +1 -1
  3. package/README.md +244 -518
  4. package/dist/chunk-4IA3DB5C.js +135 -0
  5. package/dist/chunk-AOUL5SHS.js +930 -0
  6. package/dist/chunk-DWJXQEFA.js +13759 -0
  7. package/dist/chunk-DZQLDEQS.js +879 -0
  8. package/dist/chunk-S5IDDSSB.js +74 -0
  9. package/dist/chunk-Z2GFQU3G.js +363 -0
  10. package/dist/cli.d.ts +0 -7
  11. package/dist/cli.js +227 -183
  12. package/dist/http-VSB7DBJR.js +1541 -0
  13. package/dist/index.d.ts +842 -10
  14. package/dist/index.js +5 -17
  15. package/dist/sqlite-VHBA4ABV.js +600 -0
  16. package/dist/sqlite-native-D2LH5ZT7.js +2498 -0
  17. package/dist/worker-script.d.ts +2 -0
  18. package/dist/worker-script.js +126 -0
  19. package/package.json +26 -16
  20. package/playwright.config.ts +101 -0
  21. package/scripts/generate-server-instructions.ts +111 -0
  22. package/server.json +5 -6
  23. package/test-server/README.md +118 -0
  24. package/test-server/code-map.md +409 -0
  25. package/test-server/fixtures/sample.csv +6 -0
  26. package/test-server/reset-database.ps1 +373 -0
  27. package/test-server/sample.csv +11 -0
  28. package/test-server/test-agent-experience.md +243 -0
  29. package/test-server/test-database.sql +388 -0
  30. package/test-server/test-group-tools.md +861 -0
  31. package/test-server/test-help-resources.mjs +238 -0
  32. package/test-server/test-preflight.md +53 -0
  33. package/test-server/test-prompts.md +354 -0
  34. package/test-server/test-resources.md +245 -0
  35. package/test-server/test-tool-annotations.mjs +157 -0
  36. package/test-server/test-tools-advanced-1.md +517 -0
  37. package/test-server/test-tools-advanced-2.md +487 -0
  38. package/test-server/test-tools-codemode.md +629 -0
  39. package/test-server/test-tools.md +176 -0
  40. package/test-server/tool-reference.md +236 -0
  41. package/tsconfig.test.json +9 -0
  42. package/dist/adapters/DatabaseAdapter.d.ts +0 -141
  43. package/dist/adapters/DatabaseAdapter.d.ts.map +0 -1
  44. package/dist/adapters/DatabaseAdapter.js +0 -131
  45. package/dist/adapters/DatabaseAdapter.js.map +0 -1
  46. package/dist/adapters/sqlite/SchemaManager.d.ts +0 -58
  47. package/dist/adapters/sqlite/SchemaManager.d.ts.map +0 -1
  48. package/dist/adapters/sqlite/SchemaManager.js +0 -187
  49. package/dist/adapters/sqlite/SchemaManager.js.map +0 -1
  50. package/dist/adapters/sqlite/SqliteAdapter.d.ts +0 -161
  51. package/dist/adapters/sqlite/SqliteAdapter.d.ts.map +0 -1
  52. package/dist/adapters/sqlite/SqliteAdapter.js +0 -741
  53. package/dist/adapters/sqlite/SqliteAdapter.js.map +0 -1
  54. package/dist/adapters/sqlite/index.d.ts +0 -9
  55. package/dist/adapters/sqlite/index.d.ts.map +0 -1
  56. package/dist/adapters/sqlite/index.js +0 -8
  57. package/dist/adapters/sqlite/index.js.map +0 -1
  58. package/dist/adapters/sqlite/json-utils.d.ts +0 -100
  59. package/dist/adapters/sqlite/json-utils.d.ts.map +0 -1
  60. package/dist/adapters/sqlite/json-utils.js +0 -274
  61. package/dist/adapters/sqlite/json-utils.js.map +0 -1
  62. package/dist/adapters/sqlite/output-schemas.d.ts +0 -1187
  63. package/dist/adapters/sqlite/output-schemas.d.ts.map +0 -1
  64. package/dist/adapters/sqlite/output-schemas.js +0 -1337
  65. package/dist/adapters/sqlite/output-schemas.js.map +0 -1
  66. package/dist/adapters/sqlite/prompts.d.ts +0 -13
  67. package/dist/adapters/sqlite/prompts.d.ts.map +0 -1
  68. package/dist/adapters/sqlite/prompts.js +0 -605
  69. package/dist/adapters/sqlite/prompts.js.map +0 -1
  70. package/dist/adapters/sqlite/resources.d.ts +0 -13
  71. package/dist/adapters/sqlite/resources.d.ts.map +0 -1
  72. package/dist/adapters/sqlite/resources.js +0 -251
  73. package/dist/adapters/sqlite/resources.js.map +0 -1
  74. package/dist/adapters/sqlite/tools/admin.d.ts +0 -14
  75. package/dist/adapters/sqlite/tools/admin.d.ts.map +0 -1
  76. package/dist/adapters/sqlite/tools/admin.js +0 -788
  77. package/dist/adapters/sqlite/tools/admin.js.map +0 -1
  78. package/dist/adapters/sqlite/tools/core.d.ts +0 -25
  79. package/dist/adapters/sqlite/tools/core.d.ts.map +0 -1
  80. package/dist/adapters/sqlite/tools/core.js +0 -359
  81. package/dist/adapters/sqlite/tools/core.js.map +0 -1
  82. package/dist/adapters/sqlite/tools/fts.d.ts +0 -13
  83. package/dist/adapters/sqlite/tools/fts.d.ts.map +0 -1
  84. package/dist/adapters/sqlite/tools/fts.js +0 -347
  85. package/dist/adapters/sqlite/tools/fts.js.map +0 -1
  86. package/dist/adapters/sqlite/tools/geo.d.ts +0 -14
  87. package/dist/adapters/sqlite/tools/geo.d.ts.map +0 -1
  88. package/dist/adapters/sqlite/tools/geo.js +0 -252
  89. package/dist/adapters/sqlite/tools/geo.js.map +0 -1
  90. package/dist/adapters/sqlite/tools/index.d.ts +0 -30
  91. package/dist/adapters/sqlite/tools/index.d.ts.map +0 -1
  92. package/dist/adapters/sqlite/tools/index.js +0 -61
  93. package/dist/adapters/sqlite/tools/index.js.map +0 -1
  94. package/dist/adapters/sqlite/tools/json-helpers.d.ts +0 -14
  95. package/dist/adapters/sqlite/tools/json-helpers.d.ts.map +0 -1
  96. package/dist/adapters/sqlite/tools/json-helpers.js +0 -477
  97. package/dist/adapters/sqlite/tools/json-helpers.js.map +0 -1
  98. package/dist/adapters/sqlite/tools/json-operations.d.ts +0 -14
  99. package/dist/adapters/sqlite/tools/json-operations.d.ts.map +0 -1
  100. package/dist/adapters/sqlite/tools/json-operations.js +0 -839
  101. package/dist/adapters/sqlite/tools/json-operations.js.map +0 -1
  102. package/dist/adapters/sqlite/tools/stats.d.ts +0 -15
  103. package/dist/adapters/sqlite/tools/stats.d.ts.map +0 -1
  104. package/dist/adapters/sqlite/tools/stats.js +0 -1219
  105. package/dist/adapters/sqlite/tools/stats.js.map +0 -1
  106. package/dist/adapters/sqlite/tools/text.d.ts +0 -14
  107. package/dist/adapters/sqlite/tools/text.d.ts.map +0 -1
  108. package/dist/adapters/sqlite/tools/text.js +0 -1141
  109. package/dist/adapters/sqlite/tools/text.js.map +0 -1
  110. package/dist/adapters/sqlite/tools/vector.d.ts +0 -14
  111. package/dist/adapters/sqlite/tools/vector.d.ts.map +0 -1
  112. package/dist/adapters/sqlite/tools/vector.js +0 -613
  113. package/dist/adapters/sqlite/tools/vector.js.map +0 -1
  114. package/dist/adapters/sqlite/tools/virtual.d.ts +0 -13
  115. package/dist/adapters/sqlite/tools/virtual.d.ts.map +0 -1
  116. package/dist/adapters/sqlite/tools/virtual.js +0 -930
  117. package/dist/adapters/sqlite/tools/virtual.js.map +0 -1
  118. package/dist/adapters/sqlite/types.d.ts +0 -207
  119. package/dist/adapters/sqlite/types.d.ts.map +0 -1
  120. package/dist/adapters/sqlite/types.js +0 -186
  121. package/dist/adapters/sqlite/types.js.map +0 -1
  122. package/dist/adapters/sqlite-native/NativeSqliteAdapter.d.ts +0 -163
  123. package/dist/adapters/sqlite-native/NativeSqliteAdapter.d.ts.map +0 -1
  124. package/dist/adapters/sqlite-native/NativeSqliteAdapter.js +0 -748
  125. package/dist/adapters/sqlite-native/NativeSqliteAdapter.js.map +0 -1
  126. package/dist/adapters/sqlite-native/index.d.ts +0 -11
  127. package/dist/adapters/sqlite-native/index.d.ts.map +0 -1
  128. package/dist/adapters/sqlite-native/index.js +0 -11
  129. package/dist/adapters/sqlite-native/index.js.map +0 -1
  130. package/dist/adapters/sqlite-native/tools/spatialite.d.ts +0 -19
  131. package/dist/adapters/sqlite-native/tools/spatialite.d.ts.map +0 -1
  132. package/dist/adapters/sqlite-native/tools/spatialite.js +0 -628
  133. package/dist/adapters/sqlite-native/tools/spatialite.js.map +0 -1
  134. package/dist/adapters/sqlite-native/tools/transactions.d.ts +0 -12
  135. package/dist/adapters/sqlite-native/tools/transactions.d.ts.map +0 -1
  136. package/dist/adapters/sqlite-native/tools/transactions.js +0 -255
  137. package/dist/adapters/sqlite-native/tools/transactions.js.map +0 -1
  138. package/dist/adapters/sqlite-native/tools/window.d.ts +0 -12
  139. package/dist/adapters/sqlite-native/tools/window.d.ts.map +0 -1
  140. package/dist/adapters/sqlite-native/tools/window.js +0 -370
  141. package/dist/adapters/sqlite-native/tools/window.js.map +0 -1
  142. package/dist/auth/AuthorizationServerDiscovery.d.ts +0 -90
  143. package/dist/auth/AuthorizationServerDiscovery.d.ts.map +0 -1
  144. package/dist/auth/AuthorizationServerDiscovery.js +0 -204
  145. package/dist/auth/AuthorizationServerDiscovery.js.map +0 -1
  146. package/dist/auth/OAuthResourceServer.d.ts +0 -65
  147. package/dist/auth/OAuthResourceServer.d.ts.map +0 -1
  148. package/dist/auth/OAuthResourceServer.js +0 -121
  149. package/dist/auth/OAuthResourceServer.js.map +0 -1
  150. package/dist/auth/TokenValidator.d.ts +0 -60
  151. package/dist/auth/TokenValidator.d.ts.map +0 -1
  152. package/dist/auth/TokenValidator.js +0 -235
  153. package/dist/auth/TokenValidator.js.map +0 -1
  154. package/dist/auth/errors.d.ts +0 -74
  155. package/dist/auth/errors.d.ts.map +0 -1
  156. package/dist/auth/errors.js +0 -133
  157. package/dist/auth/errors.js.map +0 -1
  158. package/dist/auth/index.d.ts +0 -13
  159. package/dist/auth/index.d.ts.map +0 -1
  160. package/dist/auth/index.js +0 -15
  161. package/dist/auth/index.js.map +0 -1
  162. package/dist/auth/middleware.d.ts +0 -81
  163. package/dist/auth/middleware.d.ts.map +0 -1
  164. package/dist/auth/middleware.js +0 -291
  165. package/dist/auth/middleware.js.map +0 -1
  166. package/dist/auth/scopes.d.ts +0 -136
  167. package/dist/auth/scopes.d.ts.map +0 -1
  168. package/dist/auth/scopes.js +0 -349
  169. package/dist/auth/scopes.js.map +0 -1
  170. package/dist/auth/types.d.ts +0 -257
  171. package/dist/auth/types.d.ts.map +0 -1
  172. package/dist/auth/types.js +0 -8
  173. package/dist/auth/types.js.map +0 -1
  174. package/dist/cli.d.ts.map +0 -1
  175. package/dist/cli.js.map +0 -1
  176. package/dist/constants/ServerInstructions.d.ts +0 -45
  177. package/dist/constants/ServerInstructions.d.ts.map +0 -1
  178. package/dist/constants/ServerInstructions.js +0 -356
  179. package/dist/constants/ServerInstructions.js.map +0 -1
  180. package/dist/filtering/ToolConstants.d.ts +0 -34
  181. package/dist/filtering/ToolConstants.d.ts.map +0 -1
  182. package/dist/filtering/ToolConstants.js +0 -174
  183. package/dist/filtering/ToolConstants.js.map +0 -1
  184. package/dist/filtering/ToolFilter.d.ts +0 -82
  185. package/dist/filtering/ToolFilter.d.ts.map +0 -1
  186. package/dist/filtering/ToolFilter.js +0 -296
  187. package/dist/filtering/ToolFilter.js.map +0 -1
  188. package/dist/index.d.ts.map +0 -1
  189. package/dist/index.js.map +0 -1
  190. package/dist/server/McpServer.d.ts +0 -61
  191. package/dist/server/McpServer.d.ts.map +0 -1
  192. package/dist/server/McpServer.js +0 -270
  193. package/dist/server/McpServer.js.map +0 -1
  194. package/dist/transports/http.d.ts +0 -134
  195. package/dist/transports/http.d.ts.map +0 -1
  196. package/dist/transports/http.js +0 -516
  197. package/dist/transports/http.js.map +0 -1
  198. package/dist/transports/index.d.ts +0 -5
  199. package/dist/transports/index.d.ts.map +0 -1
  200. package/dist/transports/index.js +0 -5
  201. package/dist/transports/index.js.map +0 -1
  202. package/dist/types/index.d.ts +0 -380
  203. package/dist/types/index.d.ts.map +0 -1
  204. package/dist/types/index.js +0 -68
  205. package/dist/types/index.js.map +0 -1
  206. package/dist/utils/annotations.d.ts +0 -44
  207. package/dist/utils/annotations.d.ts.map +0 -1
  208. package/dist/utils/annotations.js +0 -77
  209. package/dist/utils/annotations.js.map +0 -1
  210. package/dist/utils/errors.d.ts +0 -155
  211. package/dist/utils/errors.d.ts.map +0 -1
  212. package/dist/utils/errors.js +0 -329
  213. package/dist/utils/errors.js.map +0 -1
  214. package/dist/utils/identifiers.d.ts +0 -121
  215. package/dist/utils/identifiers.d.ts.map +0 -1
  216. package/dist/utils/identifiers.js +0 -319
  217. package/dist/utils/identifiers.js.map +0 -1
  218. package/dist/utils/index.d.ts +0 -7
  219. package/dist/utils/index.d.ts.map +0 -1
  220. package/dist/utils/index.js +0 -7
  221. package/dist/utils/index.js.map +0 -1
  222. package/dist/utils/insightsManager.d.ts +0 -39
  223. package/dist/utils/insightsManager.d.ts.map +0 -1
  224. package/dist/utils/insightsManager.js +0 -63
  225. package/dist/utils/insightsManager.js.map +0 -1
  226. package/dist/utils/logger.d.ts +0 -189
  227. package/dist/utils/logger.d.ts.map +0 -1
  228. package/dist/utils/logger.js +0 -394
  229. package/dist/utils/logger.js.map +0 -1
  230. package/dist/utils/progress-utils.d.ts +0 -54
  231. package/dist/utils/progress-utils.d.ts.map +0 -1
  232. package/dist/utils/progress-utils.js +0 -74
  233. package/dist/utils/progress-utils.js.map +0 -1
  234. package/dist/utils/resourceAnnotations.d.ts +0 -36
  235. package/dist/utils/resourceAnnotations.d.ts.map +0 -1
  236. package/dist/utils/resourceAnnotations.js +0 -57
  237. package/dist/utils/resourceAnnotations.js.map +0 -1
  238. package/dist/utils/where-clause.d.ts +0 -41
  239. package/dist/utils/where-clause.d.ts.map +0 -1
  240. package/dist/utils/where-clause.js +0 -116
  241. package/dist/utils/where-clause.js.map +0 -1
@@ -0,0 +1,176 @@
1
+ # db-mcp (SQLite) Tool Testing
2
+
3
+ **Ignore WASM content. Test Native Mode Only**
4
+
5
+ **Step 1:** Confirm you read the server help content sourced from `C:\Users\chris\Desktop\db-mcp\src\constants\server-instructions\gotchas.md` using `view_file` (not grep or search) — to understand documented behaviors, edge cases, and response structures for this tool group.
6
+
7
+ **Step 2:** Please conduct an exhaustive test of the tool group specified in the group-specific checklist (pasted after this document) using live MCP server tool calls directly — not scripts/terminal.
8
+
9
+ **Note** If temp tables are present from a previous test pass, it's because the database is locked. Ignore them.
10
+
11
+ ## Test Database Schema
12
+
13
+ The test database (test-server/test.db) contains these tables with JSON-relevant columns:
14
+
15
+ | Table | Rows | Columns | JSON Columns |
16
+ | ----------------- | ---- | ----------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |
17
+ | test_products | 16 | id, name, description, price, category, created_at | — |
18
+ | test_orders | 20 | id, product_id (FK), customer_name, quantity, total_price, order_date, status | — |
19
+ | test_jsonb_docs | 6 | id, doc, metadata, tags, created_at | **doc**, **metadata** (nested), **tags** (array) |
20
+ | test_articles | 8 | id, title, body, author, category, published_at | — |
21
+ | test_users | 9 | id, username, email, phone, bio, created_at | — |
22
+ | test_measurements | 200 | id, sensor_id, temperature, humidity, pressure, measured_at | — |
23
+ | test_embeddings | 20 | id, content, category, embedding | **embedding** (8-dim float array); category values: database, fitness, food, tech, travel |
24
+ | test_locations | 15 | id, name, city, latitude, longitude, type | — |
25
+ | test_categories | 17 | id, name, path, level | — |
26
+ | test_events | 100 | id, event_type, user_id (INT, 8 values), payload, event_date | **payload** (JSON) |
27
+
28
+ **Primary JSON test tables:**
29
+
30
+ - `test_jsonb_docs.doc` — Row 1: `{"type":"article","title":"Getting Started with SQLite","author":"Alice","views":1250,"rating":4.5}`, Row 3: `{"type":"video",...,"duration":3600}`, Row 4 has `nested.level1.level2 = "deep value"`
31
+ - `test_jsonb_docs.metadata` — Object with keys: source, language, version, quality, subscribers
32
+ - `test_jsonb_docs.tags` — Array of strings like `["database","tutorial","beginner"]`
33
+ - `test_events.payload` — Object with keys: page (values: home, products, cart, checkout), session (values: sess_1000+)
34
+
35
+ > **Note:** String values in test data use **lowercase** (e.g., `category = 'electronics'`, not `'Electronics'`). Use case-sensitive matching in queries.
36
+
37
+ > **Note:** `test_measurements.sensor_id` is an **INTEGER** column (values 1-5), not a string. Use `sensor_id = 1`, not `sensor_id = 'S001'`.
38
+
39
+ > **Note:** When testing `sqlite_execute_code`, do **not** pass `readonly: true` unless specifically testing read-only filtering. The `readonly` flag makes write methods return structured errors (`{success: false, code: "CODEMODE_READONLY_VIOLATION"}`). Methods remain callable but reject write operations. Use `readonly: false` (or omit it) to get the full API surface.
40
+
41
+ ## Testing Requirements
42
+
43
+ > [!CAUTION]
44
+ > **Zero tolerance for raw MCP errors.** ANY response that is a raw MCP error (e.g., `-32602`, `isError: true`, no `success` field) is a **bug that must be reported and fixed** — never an acceptable design choice, SDK limitation, or expected behavior. If you see one, report it as ❌ immediately. Do not rationalize it as "the SDK rejecting at the boundary" or "by design for range-constrained params." The handler MUST catch it.
45
+
46
+ 1. Use existing `test_*` tables for read operations (SELECT, COUNT, queries)
47
+ 2. Create temporary tables with `temp_*` prefix for write operations
48
+ 3. Test each tool with realistic inputs based on the schema above
49
+ 4. Report all failures, unexpected behaviors, improvement opportunities, or unnecessarily large payloads
50
+ 5. Do not mention what already works well or issues well documented in help resources and runtime hints which are already optimal
51
+ 6. **Error path testing**: For **every** tool, test at least **two** invalid inputs: (a) a domain error (nonexistent table, invalid column, missing required parameter) and (b) a **Zod validation error** (call the tool with `{}` empty params if it has required parameters, or pass the wrong type). Both must return a **structured handler error** (`{success: false, error: "..."}`) — NOT a raw MCP error frame. See the "Structured Error Response Pattern" section below for how to distinguish the two. This is the most common deficiency found across tool groups.
52
+ 7. **Output schema testing**: For **every** tool that has an `outputSchema`, confirm that at least one valid happy-path call returns a structured JSON response — NOT a raw MCP `-32602` "output schema" error. Output schema mismatches (handler returns fields not declared in the schema) produce the same `-32602` code as input errors but are only caught with valid inputs. See "Output Schema Validation Errors" below. Also check for the inverse: if a schema is **defined** in `src/adapters/sqlite/output-schemas/` but **not wired** to the tool definition, report as ⚠️ — the schema exists but provides no enforcement.
53
+ 8. **Deterministic checklist first**: Complete ALL items in the group-specific checklist before moving to freeform exploration. The checklist uses exact inputs and expected outputs to ensure reproducible coverage every run.
54
+
55
+ ## Structured Error Response Pattern
56
+
57
+ All tools should return errors as structured objects instead of throwing. A thrown error propagates as a raw MCP error, which is unhelpful to clients. The expected pattern:
58
+
59
+ ```json
60
+ { "success": false, "error": "Human-readable error message" }
61
+ ```
62
+
63
+ ### Handler Error vs MCP Error — How to Distinguish
64
+
65
+ There are two kinds of error responses. Only one is correct:
66
+
67
+ | Type | Source | What you see | Verdict |
68
+ | -------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- | ------------------ |
69
+ | **Handler error** ✅ | Handler catches error and returns `{success: false, error: "..."}` | Parseable JSON object with `success` and `error` fields | Correct |
70
+ | **MCP error** ❌ | Uncaught throw propagates to MCP framework | Raw text error string, often prefixed with `Error:`, wrapped in an `isError: true` content block — no `success` field | Bug — report as ❌ |
71
+
72
+ **Concrete examples:**
73
+
74
+ ```
75
+ ✅ Handler error (correct):
76
+ {"success": false, "error": "Table 'nonexistent_xyz' does not exist"}
77
+
78
+ ❌ MCP error (bug — handler threw instead of catching):
79
+ content: [{type: "text", text: "Error: SQLITE_ERROR: no such table: nonexistent_xyz"}]
80
+ isError: true
81
+ ```
82
+
83
+ The MCP error case means the handler is missing a `try/catch` block. When testing, if you see a raw error string (especially one containing `SQLITE_ERROR` without a `success` field), report it as ❌.
84
+
85
+ ### Zod Validation Errors
86
+
87
+ Calling a tool with wrong parameter types or missing required fields triggers a Zod validation error. If the handler has no outer `try/catch`, this surfaces as a raw MCP error (often `-32602`). Test every tool with `{}` (empty params) if it has required parameters — the response must be a handler error, not an MCP error.
88
+
89
+ **Zod refinement leak pattern:** `DatabaseAdapter.registerTool()` uses `.partial()` on input schemas so the SDK accepts `{}`. But `.partial()` only makes keys **optional** — it does NOT strip refinements like `.min(1)`, `.max(90)`, or `.min(-90).max(90)`. This applies to **ALL types** — strings, arrays, AND numbers:
90
+
91
+ - `z.string().min(1)` + empty `""` → SDK rejects with raw MCP `-32602`
92
+ - `z.array().min(1)` + empty `[]` → SDK rejects with raw MCP `-32602`
93
+ - `z.number().min(-90).max(90)` + value `91` → SDK rejects with raw MCP `-32602`
94
+
95
+ **Fix:** Remove ALL `.min(N)` / `.max(N)` refinements from the schema and validate inside the handler instead (see `sqlite_query_plan` in `diagnostics.ts`, `sqlite_append_insight` in `pragma.ts`, and `validateCoordinates()` in `geo.ts` for examples). Optional fields with `.default()` are safe because the default satisfies the constraint.
96
+
97
+ **Required enum coercion pattern:** For **optional** enum params with defaults, `z.preprocess(coercer, z.enum([...]).optional().default(...))` works — the coercer returns `undefined` for invalid values → the `.default()` kicks in. For **required** enum params (no `.optional().default(...)`), this pattern **fails**: the SDK's `.partial()` wraps the preprocess in `.optional()`, but the inner `z.enum()` still rejects `undefined` → raw MCP `-32602`. **Fix:** Use `z.string()` in the schema and validate the enum inside the handler's `try/catch`, returning a structured error (see `VALID_ANALYSIS_TYPES` / `VALID_OPERATIONS` / `VALID_FORMATS` in SpatiaLite `analysis.ts` for examples).
98
+
99
+ **What to report:**
100
+
101
+ - If a tool call returns a raw MCP error (no JSON body with `success` field), report it as ❌ with the tool name and the raw error message
102
+ - If a tool returns `{success: false, error: "..."}`, that is the correct behavior — do not report it as a failure
103
+ - If a tool returns a successful response for an obviously invalid input (e.g., nonexistent table returns `{success: true}`), report it as ⚠️
104
+
105
+ ### Wrong-Type Numeric Parameter Coercion
106
+
107
+ For every tool with optional numeric parameters (e.g., `limit`, `buckets`, `windowSize`, `radius`, `sampleSize`), call the tool with `param: "abc"` (string instead of number). The tool must NOT return a raw MCP `-32602` error. Acceptable behaviors:
108
+
109
+ - Handler returns `{success: false, error: "..."}` with a validation message
110
+ - Handler silently applies the default value
111
+ - Handler coerces to NaN and returns a descriptive error
112
+
113
+ Unacceptable: Raw MCP error frame with `-32602` code.
114
+
115
+ ### Output Schema Validation Errors
116
+
117
+ The MCP SDK enforces `additionalProperties: false` on **output** schemas. If a handler returns fields not declared in its output schema, the SDK rejects the response with a raw `-32602` error — even though the handler logic succeeded. This is a different failure mode from input validation:
118
+
119
+ - **Input `-32602`**: Triggered by sending unrecognized/invalid parameters → caught by the Zod sweep (call with `{}` or `extraParam`)
120
+ - **Output `-32602`**: Triggered by the handler **returning** undeclared fields → caught by a valid happy-path call that still produces a raw MCP error
121
+
122
+ **How to detect:** If a tool call with **correct, valid inputs** returns a raw MCP `-32602` mentioning "does not match the tool's output schema" or "additional properties", the output schema in `src/adapters/sqlite/output-schemas/` is missing fields that the handler returns. Report as ❌ with both the tool name and the missing field(s).
123
+
124
+ **Fix pattern:** Add the missing fields to the output schema (e.g., `durationMs: z.number().optional()`, `message: z.string().optional()`). Do NOT remove fields from the handler response — the schema must match reality.
125
+
126
+ **Systematic check:** For every tool that has an `outputSchema`, make at least one valid happy-path call and confirm it returns a parseable JSON object with a `success` field — not a raw MCP error. This is separate from (and complementary to) the Zod validation sweep, which tests invalid inputs.
127
+
128
+ ### Error Consistency Audit
129
+
130
+ During testing, check for these inconsistencies across tool groups:
131
+
132
+ 1. **Throw-vs-return**: If a tool throws a raw error instead of returning `{success: false}`, report as ❌. Document which tool groups have raw-error leakage.
133
+ 2. **Error field name**: All `{success: false}` responses should use `error` as the field name. The `reason` field is reserved for `{success: true, skipped: true}` informational responses.
134
+ 3. **Zod validation leaks**: If calling a tool with an invalid enum value or missing required field produces a raw MCP `-32602` error instead of a structured response, report as ❌.
135
+ 4. **Output schema leaks**: If calling a tool with valid inputs produces a raw MCP `-32602` mentioning "output schema" or "additional properties", report as ❌ (see "Output Schema Validation Errors" above).
136
+ 5. **Centralized error formatting**: db-mcp uses `DbMcpError`. If any tool group catches errors but formats them inconsistently (e.g., different message patterns for the same error type), report as ⚠️.
137
+ 6. **Orphaned output schemas**: If a schema is exported from `src/adapters/sqlite/output-schemas/` (e.g., `TransactionBeginOutputSchema`) but the corresponding tool definition does not reference it via `outputSchema`, report as ⚠️. Use `grep_search` to check whether the schema name appears in any tool file under `src/adapters/`. Defined-but-unwired schemas provide zero enforcement.
138
+ 7. **Inline output schemas**: If any tool defines `outputSchema: z.object({...})` inline in the handler file instead of importing a named schema from `output-schemas/`, report as ⚠️. All output schemas must live in `src/adapters/sqlite/output-schemas/` with named exports. Use `grep_search` with pattern `outputSchema: z.object` across `src/adapters/` to detect violations.
139
+
140
+ ### Split Schema Pattern Verification
141
+
142
+ All tools use the Split Schema pattern: a plain `z.object()` Base schema for MCP parameter visibility, and a `z.preprocess()` wrapper for handler parsing. Verify:
143
+
144
+ 1. **Parameter visibility**: For tools with optional parameters (e.g., `limit`, `readonly`), make a direct MCP call using those parameters. If the tool ignores or rejects documented parameters, report as a Split Schema violation.
145
+ 2. **Alias acceptance**: For tools with documented parameter aliases (e.g., `table`/`tableName`, `query`/`sql`, `indexName`/`name`), verify that direct MCP tool calls correctly accept the aliases.
146
+
147
+ ## Reporting Format
148
+
149
+ - ❌ Fail: Tool errors or produces incorrect results (include error message)
150
+ - ⚠️ Issue: Unexpected behavior or improvement opportunity
151
+ - 📦 Payload: Unnecessarily large response that should be optimized — **blocking, equally important as ❌ bugs**. Oversized payloads waste LLM context window tokens and degrade downstream tool-calling quality. Report the response size in KB and suggest a concrete optimization (e.g., filter system tables, add `compact` option, omit empty arrays).
152
+
153
+ ## Post-Test Procedures
154
+
155
+ ### Reporting Rules
156
+
157
+ - Use ✅ only in inline notes during testing; omit from Final Summary
158
+ - Do not mention what already works well or issues already documented in help resources and runtime hints
159
+
160
+ ### After Testing
161
+
162
+ 1. **Triage findings**: If issues were found, create an implementation plan, making sure they are consistent with working patterns in other tools/tool groups. If the plan requires no user decisions, proceed directly to implementation
163
+ 2. **Scope of fixes** includes corrections to any of:
164
+ - Handler code
165
+ - `src/constants/server-instructions/*.md` (per-group help files) — run `npm run generate:instructions` after editing to regenerate `server-instructions.ts`
166
+ - Test database (`test-server/test.db`)
167
+ - This prompt (`test-tools.md`) and group file (`test-group-tools.md`)
168
+
169
+ ### After Implementation
170
+
171
+ 3. **Validate**: Run test suite and fix broken tests, run lint + typecheck and fix issues, update changelog (no duplicate headers)
172
+ 4. **Commit**: Stage and commit all changes — do NOT push
173
+ 5. **Live re-test**: Test fixes with direct MCP tool calls. I will have already rebuilt and restarted the server.
174
+ 6. **Final summary**: If no issues found, provide the final summary after testing. If issues were fixed, provide the summary after live MCP re-testing confirms fixes are working. If the test prompt/database can be improved, make the improvements.
175
+
176
+ ---
@@ -0,0 +1,236 @@
1
+ # Tool Reference
2
+
3
+ Complete reference of all **139 Native / 115 WASM tools** organized by 9 tool groups + codemode. Each group automatically includes Code Mode (`sqlite_execute_code`) for token-efficient operations.
4
+
5
+ > **3 built-in tools** (`server_info`, `server_health`, `list_adapters`) are always available regardless of filter settings.
6
+ >
7
+ > Use [Tool Filtering](#️-tool-filtering) to select the groups you need. See [Code Mode](#-recommended-code-mode-maximum-token-savings) for the `sqlite.*` API that exposes every tool below through sandboxed JavaScript.
8
+
9
+ ---
10
+
11
+ ## codemode (1 tool)
12
+
13
+ Sandboxed JavaScript execution that exposes all 9 tool groups through the `sqlite.*` API.
14
+
15
+ | Tool | Description |
16
+ | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
17
+ | `sqlite_execute_code` | Execute JavaScript in a sandboxed environment with access to all SQLite tools via the `sqlite.*` API. Enables complex multi-step operations in a single call with 70–90% token savings. |
18
+
19
+ ---
20
+
21
+ ## core (9 tools + Code Mode)
22
+
23
+ Read/write queries, table and index management, and schema discovery.
24
+
25
+ | Tool | Description |
26
+ | ----------------------- | --------------------------------------------------------------------------------------------------------- |
27
+ | `sqlite_read_query` | Execute a SELECT query on the SQLite database. Returns rows as JSON. Use parameter binding for safety. |
28
+ | `sqlite_write_query` | Execute an INSERT, UPDATE, or DELETE query. Returns affected row count. Use parameter binding for safety. |
29
+ | `sqlite_list_tables` | List all tables and views in the database with their column counts. |
30
+ | `sqlite_describe_table` | Get detailed schema information for a table including columns, types, and constraints. |
31
+ | `sqlite_create_table` | Create a new table in the database with specified columns and constraints. |
32
+ | `sqlite_drop_table` | Drop (delete) a table from the database. This is irreversible! |
33
+ | `sqlite_get_indexes` | List all indexes in the database, optionally filtered by table. |
34
+ | `sqlite_create_index` | Create an index on one or more columns to improve query performance. |
35
+ | `sqlite_drop_index` | Drop (delete) an index from the database. |
36
+
37
+ ---
38
+
39
+ ## json (23 tools + Code Mode)
40
+
41
+ Comprehensive JSON manipulation — read, write, transform, validate, and analyze JSON documents stored in SQLite.
42
+
43
+ | Tool | Description |
44
+ | ------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
45
+ | `sqlite_json_insert` | Insert a row with JSON data. Automatically normalizes JSON for consistent storage. |
46
+ | `sqlite_json_update` | Update a value at a specific JSON path using `json_set()`. |
47
+ | `sqlite_json_select` | Select rows and optionally extract specific JSON paths. |
48
+ | `sqlite_json_query` | Query JSON data with path-based filters and projections. |
49
+ | `sqlite_json_validate_path` | Validate a JSON path syntax without executing a query. |
50
+ | `sqlite_json_merge` | Merge JSON object into existing JSON column using `json_patch()`. |
51
+ | `sqlite_json_analyze_schema` | Analyze JSON data in a column to infer its schema (types, nullability, counts). |
52
+ | `sqlite_create_json_collection` | Create an optimized JSON document collection table with ID, data column, optional timestamps, and JSON path indexes. |
53
+ | `sqlite_json_valid` | Check if a string is valid JSON. |
54
+ | `sqlite_json_extract` | Extract a value from a JSON column at the specified path using `json_extract()`. |
55
+ | `sqlite_json_set` | Set a value at a JSON path using `json_set()`. Creates path if it does not exist. |
56
+ | `sqlite_json_remove` | Remove a value at a JSON path using `json_remove()`. |
57
+ | `sqlite_json_type` | Get the JSON type (null, true, false, integer, real, text, array, object) at a path. |
58
+ | `sqlite_json_array_length` | Get the length of a JSON array at the specified path. |
59
+ | `sqlite_json_array_append` | Append a value to a JSON array using `json_insert()`. |
60
+ | `sqlite_json_keys` | Get the distinct keys of JSON objects at the specified path (returns unique keys across all matching rows). |
61
+ | `sqlite_json_each` | Expand a JSON array or object into rows using `json_each()`. |
62
+ | `sqlite_json_group_array` | Aggregate column values into a JSON array using `json_group_array()`. |
63
+ | `sqlite_json_group_object` | Aggregate key-value pairs into a JSON object using `json_group_object()`. |
64
+ | `sqlite_json_pretty` | Format JSON string with indentation for readability. |
65
+ | `sqlite_jsonb_convert` | Convert a text JSON column to JSONB binary format for faster processing. Requires SQLite 3.45+. |
66
+ | `sqlite_json_storage_info` | Analyze storage format of a JSON column (text vs JSONB) and report statistics. |
67
+ | `sqlite_json_normalize_column` | Normalize JSON data in a column (sort keys, compact format) for consistent storage and comparison. |
68
+
69
+ ---
70
+
71
+ ## text (17 Native / 13 WASM tools + Code Mode)
72
+
73
+ Text processing, regex, fuzzy matching, phonetic search, and FTS5 full-text search.
74
+
75
+ | Tool | Description |
76
+ | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
77
+ | `sqlite_regex_extract` | Extract text matching a regex pattern. Processed in JavaScript after fetching data. |
78
+ | `sqlite_regex_match` | Find rows where column matches a regex pattern. Processed in JavaScript. |
79
+ | `sqlite_text_split` | Split a text column by delimiter into array results. |
80
+ | `sqlite_text_concat` | Concatenate multiple columns with optional separator. |
81
+ | `sqlite_text_replace` | Replace text in a column using SQLite `replace()` function. |
82
+ | `sqlite_text_trim` | Trim whitespace from text column values. |
83
+ | `sqlite_text_case` | Convert text to uppercase or lowercase. |
84
+ | `sqlite_text_substring` | Extract a substring from text column using `substr()`. |
85
+ | `sqlite_fuzzy_match` | Find fuzzy matches using Levenshtein distance. Splits values into tokens by default (`tokenize: false` to match entire value). Use `maxDistance` 1–3 for similar-length strings. |
86
+ | `sqlite_phonetic_match` | Find phonetically similar values using Soundex (SQLite native) or Metaphone algorithm. |
87
+ | `sqlite_text_normalize` | Normalize text using Unicode normalization (NFC, NFD, NFKC, NFKD) or strip accents. |
88
+ | `sqlite_text_validate` | Validate text values against patterns: email, phone, URL, UUID, IPv4, or custom regex. |
89
+ | `sqlite_advanced_search` | Advanced search combining exact, fuzzy (Levenshtein), and phonetic (Soundex) matching. |
90
+ | `sqlite_fts_create` | Create an FTS5 full-text search virtual table. `[NATIVE ONLY]` |
91
+ | `sqlite_fts_search` | Search an FTS5 table using full-text query syntax. `[NATIVE ONLY]` |
92
+ | `sqlite_fts_rebuild` | Rebuild an FTS5 index to optimize search performance. `[NATIVE ONLY]` |
93
+ | `sqlite_fts_match_info` | Get FTS5 match ranking information using bm25. `[NATIVE ONLY]` |
94
+
95
+ ---
96
+
97
+ ## stats (19 Native / 13 WASM tools + Code Mode)
98
+
99
+ Statistical analysis — descriptive stats, percentiles, correlation, regression, distributions, and window functions.
100
+
101
+ | Tool | Description |
102
+ | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
103
+ | `sqlite_stats_basic` | Get basic statistics (count, sum, avg, min, max) for a numeric column. |
104
+ | `sqlite_stats_count` | Count rows, optionally distinct values in a column. |
105
+ | `sqlite_stats_group_by` | Aggregate statistics grouped by a column. |
106
+ | `sqlite_stats_histogram` | Create a histogram with specified number of buckets. |
107
+ | `sqlite_stats_percentile` | Calculate percentiles (median, quartiles, etc.) for a column. |
108
+ | `sqlite_stats_correlation` | Calculate Pearson correlation coefficient between two numeric columns. |
109
+ | `sqlite_stats_top_n` | Get top N values from a column. |
110
+ | `sqlite_stats_distinct` | Get distinct values from a column. |
111
+ | `sqlite_stats_summary` | Get summary statistics for multiple columns at once. |
112
+ | `sqlite_stats_frequency` | Get frequency distribution of values in a column. |
113
+ | `sqlite_stats_outliers` | Detect outliers using IQR (Interquartile Range) or Z-score method. |
114
+ | `sqlite_stats_regression` | Perform linear or polynomial regression analysis between two columns. |
115
+ | `sqlite_stats_hypothesis` | Perform statistical hypothesis tests: one-sample t-test, two-sample t-test, or chi-square test. |
116
+ | `sqlite_window_row_number` | Assign sequential row numbers based on ordering. Useful for pagination and ranking. `[NATIVE ONLY]` |
117
+ | `sqlite_window_rank` | Calculate rank of rows. RANK leaves gaps after ties, DENSE_RANK does not, PERCENT_RANK gives 0–1 range. `[NATIVE ONLY]` |
118
+ | `sqlite_window_lag_lead` | Access previous (LAG) or next (LEAD) row values. Useful for comparing consecutive rows. `[NATIVE ONLY]` |
119
+ | `sqlite_window_running_total` | Calculate running (cumulative) total. Useful for balance tracking, cumulative metrics. `[NATIVE ONLY]` |
120
+ | `sqlite_window_moving_avg` | Calculate moving (rolling) average. Useful for smoothing time series data. `[NATIVE ONLY]` |
121
+ | `sqlite_window_ntile` | Divide rows into N buckets. E.g., 4 buckets = quartiles, 10 = deciles, 100 = percentiles. `[NATIVE ONLY]` |
122
+
123
+ ---
124
+
125
+ ## vector (11 tools + Code Mode)
126
+
127
+ Vector storage, similarity search, and distance calculations for embeddings and AI/ML operations.
128
+
129
+ | Tool | Description |
130
+ | ---------------------------- | ------------------------------------------------------------------------ |
131
+ | `sqlite_vector_create_table` | Create a table optimized for vector storage with JSON vector column. |
132
+ | `sqlite_vector_store` | Store or update a vector in the database. |
133
+ | `sqlite_vector_batch_store` | Store multiple vectors in a batch operation. |
134
+ | `sqlite_vector_search` | Find similar vectors using cosine, euclidean, or dot product similarity. |
135
+ | `sqlite_vector_get` | Retrieve a vector by its ID. |
136
+ | `sqlite_vector_delete` | Delete vectors by their IDs. |
137
+ | `sqlite_vector_count` | Count vectors in a table. |
138
+ | `sqlite_vector_stats` | Get statistics about vectors in a table. |
139
+ | `sqlite_vector_dimensions` | Get the dimensions of vectors in a table. |
140
+ | `sqlite_vector_normalize` | Normalize a vector to unit length. |
141
+ | `sqlite_vector_distance` | Calculate distance or similarity between two vectors. |
142
+
143
+ ---
144
+
145
+ ## admin (33 Native / 26 WASM tools + Code Mode)
146
+
147
+ Database maintenance — backup/restore, PRAGMA, views, virtual tables, and transaction control.
148
+
149
+ | Tool | Description |
150
+ | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
151
+ | `sqlite_backup` | Create a backup of the database to a file. |
152
+ | `sqlite_analyze` | Analyze table statistics to improve query performance. |
153
+ | `sqlite_integrity_check` | Check database integrity for corruption or errors. |
154
+ | `sqlite_optimize` | Optimize database by reindexing and/or analyzing. |
155
+ | `sqlite_restore` | Restore database from a backup file. WARNING: This replaces the current database. |
156
+ | `sqlite_verify_backup` | Verify a backup file's integrity without restoring it. |
157
+ | `sqlite_index_stats` | Get detailed statistics for database indexes. |
158
+ | `sqlite_pragma_compile_options` | Get the compile-time options used to build SQLite. Use the `filter` parameter to reduce output (~50+ options by default). |
159
+ | `sqlite_pragma_database_list` | List all attached databases. |
160
+ | `sqlite_pragma_optimize` | Run `PRAGMA optimize` to improve query performance based on usage patterns. |
161
+ | `sqlite_pragma_settings` | Get or set a PRAGMA value. |
162
+ | `sqlite_pragma_table_info` | Get detailed column information for a table. |
163
+ | `sqlite_append_insight` | Add a business insight to the `memo://insights` resource. Use this to capture key findings during data analysis. |
164
+ | `sqlite_generate_series` | Generate a series of numbers using `generate_series()` virtual table. |
165
+ | `sqlite_create_view` | Create a view based on a SELECT query. |
166
+ | `sqlite_list_views` | List all views in the database. |
167
+ | `sqlite_drop_view` | Drop (delete) a view from the database. |
168
+ | `sqlite_dbstat` | Get database storage statistics using dbstat virtual table. |
169
+ | `sqlite_vacuum` | Rebuild the database to reclaim space and optimize structure. |
170
+ | `sqlite_list_virtual_tables` | List all virtual tables in the database. |
171
+ | `sqlite_virtual_table_info` | Get metadata about a specific virtual table. |
172
+ | `sqlite_drop_virtual_table` | Drop a virtual table. |
173
+ | `sqlite_create_csv_table` | Create a virtual table from a CSV file. Requires the csv extension. |
174
+ | `sqlite_analyze_csv_schema` | Analyze a CSV file structure and infer column types. Uses a temporary virtual table. |
175
+ | `sqlite_create_rtree_table` | Create an R-Tree virtual table for spatial indexing. Supports 2–5 dimensions. |
176
+ | `sqlite_create_series_table` | Create a table populated with a series of numbers. Unlike `generate_series`, this creates a persistent table. |
177
+ | `sqlite_transaction_begin` | Begin a new transaction. Use immediate or exclusive mode for write-heavy operations. `[NATIVE ONLY]` |
178
+ | `sqlite_transaction_commit` | Commit the current transaction, making all changes permanent. `[NATIVE ONLY]` |
179
+ | `sqlite_transaction_rollback` | Rollback the current transaction, discarding all changes. `[NATIVE ONLY]` |
180
+ | `sqlite_transaction_savepoint` | Create a savepoint within the current transaction for partial rollback. `[NATIVE ONLY]` |
181
+ | `sqlite_transaction_release` | Release a savepoint, keeping the changes made since it was created. `[NATIVE ONLY]` |
182
+ | `sqlite_transaction_rollback_to` | Rollback to a savepoint, discarding changes made after it was created. `[NATIVE ONLY]` |
183
+ | `sqlite_transaction_execute` | Execute multiple SQL statements in a single transaction. Automatically commits on success or rolls back on error. `[NATIVE ONLY]` |
184
+
185
+ ---
186
+
187
+ ## geo (11 Native / 4 WASM tools + Code Mode)
188
+
189
+ Geospatial operations — Haversine distance/radius queries and SpatiaLite advanced GIS.
190
+
191
+ | Tool | Description |
192
+ | -------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
193
+ | `sqlite_geo_distance` | Calculate the distance between two geographic points using Haversine formula. |
194
+ | `sqlite_geo_nearby` | Find points within a radius of a center point. |
195
+ | `sqlite_geo_bounding_box` | Find points within a rectangular bounding box. |
196
+ | `sqlite_geo_cluster` | Cluster geographic points into grid cells. |
197
+ | `sqlite_spatialite_load` | Load SpatiaLite extension for geospatial capabilities. Required before using other spatial tools. `[NATIVE ONLY]` |
198
+ | `sqlite_spatialite_create_table` | Create a spatial table with geometry column using SpatiaLite. `[NATIVE ONLY]` |
199
+ | `sqlite_spatialite_query` | Execute spatial SQL queries using SpatiaLite functions (`ST_Distance`, `ST_Within`, etc.). `[NATIVE ONLY]` |
200
+ | `sqlite_spatialite_analyze` | Perform spatial analysis: nearest neighbor, point in polygon, distance matrix. `[NATIVE ONLY]` |
201
+ | `sqlite_spatialite_index` | Create, drop, or check spatial R-Tree index on geometry column. `[NATIVE ONLY]` |
202
+ | `sqlite_spatialite_transform` | Perform geometry operations: buffer, intersection, union, centroid, simplify. `[NATIVE ONLY]` |
203
+ | `sqlite_spatialite_import` | Import geometry data from WKT or GeoJSON into a spatial table. `[NATIVE ONLY]` |
204
+
205
+ ---
206
+
207
+ ## introspection (9 tools + Code Mode)
208
+
209
+ Read-only schema analysis — dependency graphs, cascade simulation, diagnostics, and migration risk assessment.
210
+
211
+ | Tool | Description |
212
+ | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
213
+ | `sqlite_dependency_graph` | Build a foreign key dependency graph showing relationships between all tables. Returns nodes (tables), edges (FK references), circular dependency detection, and root/leaf table identification. |
214
+ | `sqlite_topological_sort` | Generate a safe DDL execution order for tables based on foreign key dependencies. `create` direction lists parent tables first; `drop` direction lists child tables first. |
215
+ | `sqlite_cascade_simulator` | Simulate the impact of a DELETE, DROP, or TRUNCATE on a table. Shows which tables would be affected through cascading foreign key actions, with severity scoring. |
216
+ | `sqlite_schema_snapshot` | Generate a comprehensive snapshot of the database schema — tables, views, indexes, and triggers — in a single call. |
217
+ | `sqlite_constraint_analysis` | Analyze database schema for constraint health issues: missing primary keys, columns that should be NOT NULL, foreign keys without indexes, and tables that could benefit from FK relationships. |
218
+ | `sqlite_migration_risks` | Analyze DDL statements for SQLite-specific migration risks. Detects ALTER TABLE limitations, large table operations, column type changes, destructive operations, and FTS5 rebuild requirements. |
219
+ | `sqlite_storage_analysis` | Analyze database storage health: fragmentation, size breakdown per table, and optimization recommendations. |
220
+ | `sqlite_index_audit` | Audit index effectiveness: find redundant indexes (prefix duplicates), missing foreign key indexes, and large tables without secondary indexes. Returns actionable suggestions. |
221
+ | `sqlite_query_plan` | Analyze a SQL query's execution plan. Returns structured EXPLAIN QUERY PLAN output with scan-type classification and optimization suggestions. |
222
+
223
+ ---
224
+
225
+ ## migration (6 tools + Code Mode)
226
+
227
+ Schema migration tracking — initialize, record, apply, rollback, and audit migrations with SHA-256 deduplication.
228
+
229
+ | Tool | Description |
230
+ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
231
+ | `sqlite_migration_init` | Initialize the migration tracking system by creating the `_mcp_migrations` table. Safe to call multiple times — idempotent. |
232
+ | `sqlite_migration_record` | Record a migration that was applied externally (not executed by this tool). Uses SHA-256 hashing for dedup — duplicate SQL blocks are rejected. |
233
+ | `sqlite_migration_apply` | Execute migration SQL and record it atomically. If the SQL fails, no record is created. Uses SHA-256 hashing for dedup. |
234
+ | `sqlite_migration_rollback` | Roll back a migration by ID or version. Requires that rollback SQL was recorded with the migration. Supports dry-run mode to preview the rollback SQL without executing. |
235
+ | `sqlite_migration_history` | Query migration history with optional filters by status and source system. Supports pagination. |
236
+ | `sqlite_migration_status` | Get a summary of migration tracking state — latest version, counts by status, and unique source systems. |
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "compilerOptions": {
4
+ "noEmit": true,
5
+ "rootDir": "."
6
+ },
7
+ "include": ["src/**/*.ts", "src/**/*.test.ts"],
8
+ "exclude": ["node_modules", "dist"]
9
+ }
@@ -1,141 +0,0 @@
1
- /**
2
- * db-mcp - Database Adapter Interface
3
- *
4
- * Abstract base class for SQLite database adapters.
5
- * Provides a consistent interface for SQLite database operations
6
- * across WASM and native backend variants.
7
- */
8
- import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
9
- import type { DatabaseConfig, DatabaseType, HealthStatus, QueryResult, SchemaInfo, TableInfo, AdapterCapabilities, ToolDefinition, ResourceDefinition, PromptDefinition, RequestContext, ToolGroup, ToolFilterConfig } from "../types/index.js";
10
- /**
11
- * Abstract base class for database adapters
12
- */
13
- export declare abstract class DatabaseAdapter {
14
- /** Database type identifier */
15
- abstract readonly type: DatabaseType;
16
- /** Human-readable adapter name */
17
- abstract readonly name: string;
18
- /** Adapter version */
19
- abstract readonly version: string;
20
- /** Connection status */
21
- protected connected: boolean;
22
- /** Database configuration */
23
- protected config: DatabaseConfig | null;
24
- /**
25
- * Connect to the database
26
- * @param config - Database connection configuration
27
- */
28
- abstract connect(config: DatabaseConfig): Promise<void>;
29
- /**
30
- * Disconnect from the database
31
- */
32
- abstract disconnect(): Promise<void>;
33
- /**
34
- * Check if connected to the database
35
- */
36
- isConnected(): boolean;
37
- /**
38
- * Get health status of the database connection
39
- */
40
- abstract getHealth(): Promise<HealthStatus>;
41
- /**
42
- * Execute a read-only query (SELECT)
43
- * @param sql - SQL query string
44
- * @param params - Query parameters for prepared statements
45
- */
46
- abstract executeReadQuery(sql: string, params?: unknown[]): Promise<QueryResult>;
47
- /**
48
- * Execute a write query (INSERT, UPDATE, DELETE)
49
- * @param sql - SQL query string
50
- * @param params - Query parameters for prepared statements
51
- * @param skipValidation - Skip security validation (for trusted internal operations)
52
- */
53
- abstract executeWriteQuery(sql: string, params?: unknown[], skipValidation?: boolean): Promise<QueryResult>;
54
- /**
55
- * Execute any query (for admin operations)
56
- * @param sql - SQL query string
57
- * @param params - Query parameters for prepared statements
58
- */
59
- abstract executeQuery(sql: string, params?: unknown[]): Promise<QueryResult>;
60
- /**
61
- * Get full database schema information
62
- */
63
- abstract getSchema(): Promise<SchemaInfo>;
64
- /**
65
- * List all tables in the database
66
- */
67
- abstract listTables(): Promise<TableInfo[]>;
68
- /**
69
- * Describe a specific table's structure
70
- * @param tableName - Name of the table
71
- */
72
- abstract describeTable(tableName: string): Promise<TableInfo>;
73
- /**
74
- * List available schemas/databases
75
- */
76
- abstract listSchemas(): Promise<string[]>;
77
- /**
78
- * Get adapter capabilities
79
- */
80
- abstract getCapabilities(): AdapterCapabilities;
81
- /**
82
- * Get supported tool groups for this adapter
83
- */
84
- abstract getSupportedToolGroups(): ToolGroup[];
85
- /**
86
- * Get all tool definitions for this adapter
87
- */
88
- abstract getToolDefinitions(): ToolDefinition[];
89
- /**
90
- * Get all resource definitions for this adapter
91
- */
92
- abstract getResourceDefinitions(): ResourceDefinition[];
93
- /**
94
- * Get all prompt definitions for this adapter
95
- */
96
- abstract getPromptDefinitions(): PromptDefinition[];
97
- /**
98
- * Register tools with the MCP server
99
- * @param server - MCP server instance
100
- * @param filterConfig - Tool filter configuration
101
- */
102
- registerTools(server: McpServer, filterConfig: ToolFilterConfig): void;
103
- /**
104
- * Register a single tool with the MCP server
105
- */
106
- protected abstract registerTool(server: McpServer, tool: ToolDefinition): void;
107
- /**
108
- * Register resources with the MCP server
109
- */
110
- registerResources(server: McpServer): void;
111
- /**
112
- * Register a single resource with the MCP server
113
- */
114
- protected abstract registerResource(server: McpServer, resource: ResourceDefinition): void;
115
- /**
116
- * Register prompts with the MCP server
117
- */
118
- registerPrompts(server: McpServer): void;
119
- /**
120
- * Register a single prompt with the MCP server
121
- */
122
- protected abstract registerPrompt(server: McpServer, prompt: PromptDefinition): void;
123
- /**
124
- * Validate query for safety (SQL injection prevention)
125
- * @param sql - SQL query to validate
126
- * @param isReadOnly - Whether to enforce read-only restrictions
127
- */
128
- protected validateQuery(sql: string, isReadOnly: boolean): void;
129
- /**
130
- * Create a request context for tool execution
131
- * @param requestId Optional request ID for tracing
132
- * @param server Optional MCP Server instance for progress notifications
133
- * @param progressToken Optional progress token from client request _meta
134
- */
135
- protected createContext(requestId?: string, server?: unknown, progressToken?: string | number): RequestContext;
136
- /**
137
- * Get adapter info for logging/debugging
138
- */
139
- getInfo(): Record<string, unknown>;
140
- }
141
- //# sourceMappingURL=DatabaseAdapter.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"DatabaseAdapter.d.ts","sourceRoot":"","sources":["../../src/adapters/DatabaseAdapter.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACzE,OAAO,KAAK,EACV,cAAc,EACd,YAAY,EACZ,YAAY,EACZ,WAAW,EACX,UAAU,EACV,SAAS,EACT,mBAAmB,EACnB,cAAc,EACd,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACd,SAAS,EACT,gBAAgB,EACjB,MAAM,mBAAmB,CAAC;AAG3B;;GAEG;AACH,8BAAsB,eAAe;IACnC,+BAA+B;IAC/B,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC;IAErC,kCAAkC;IAClC,QAAQ,CAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAE/B,sBAAsB;IACtB,QAAQ,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAElC,wBAAwB;IACxB,SAAS,CAAC,SAAS,UAAS;IAE5B,6BAA6B;IAC7B,SAAS,CAAC,MAAM,EAAE,cAAc,GAAG,IAAI,CAAQ;IAM/C;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC;IAEvD;;OAEG;IACH,QAAQ,CAAC,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAEpC;;OAEG;IACH,WAAW,IAAI,OAAO;IAItB;;OAEG;IACH,QAAQ,CAAC,SAAS,IAAI,OAAO,CAAC,YAAY,CAAC;IAM3C;;;;OAIG;IACH,QAAQ,CAAC,gBAAgB,CACvB,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,OAAO,EAAE,GACjB,OAAO,CAAC,WAAW,CAAC;IAEvB;;;;;OAKG;IACH,QAAQ,CAAC,iBAAiB,CACxB,GAAG,EAAE,MAAM,EACX,MAAM,CAAC,EAAE,OAAO,EAAE,EAClB,cAAc,CAAC,EAAE,OAAO,GACvB,OAAO,CAAC,WAAW,CAAC;IAEvB;;;;OAIG;IACH,QAAQ,CAAC,YAAY,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,WAAW,CAAC;IAM5E;;OAEG;IACH,QAAQ,CAAC,SAAS,IAAI,OAAO,CAAC,UAAU,CAAC;IAEzC;;OAEG;IACH,QAAQ,CAAC,UAAU,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;IAE3C;;;OAGG;IACH,QAAQ,CAAC,aAAa,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC;IAE7D;;OAEG;IACH,QAAQ,CAAC,WAAW,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IAMzC;;OAEG;IACH,QAAQ,CAAC,eAAe,IAAI,mBAAmB;IAE/C;;OAEG;IACH,QAAQ,CAAC,sBAAsB,IAAI,SAAS,EAAE;IAM9C;;OAEG;IACH,QAAQ,CAAC,kBAAkB,IAAI,cAAc,EAAE;IAE/C;;OAEG;IACH,QAAQ,CAAC,sBAAsB,IAAI,kBAAkB,EAAE;IAEvD;;OAEG;IACH,QAAQ,CAAC,oBAAoB,IAAI,gBAAgB,EAAE;IAEnD;;;;OAIG;IACH,aAAa,CAAC,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,gBAAgB,GAAG,IAAI;IAatE;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,YAAY,CAC7B,MAAM,EAAE,SAAS,EACjB,IAAI,EAAE,cAAc,GACnB,IAAI;IAEP;;OAEG;IACH,iBAAiB,CAAC,MAAM,EAAE,SAAS,GAAG,IAAI;IAQ1C;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,gBAAgB,CACjC,MAAM,EAAE,SAAS,EACjB,QAAQ,EAAE,kBAAkB,GAC3B,IAAI;IAEP;;OAEG;IACH,eAAe,CAAC,MAAM,EAAE,SAAS,GAAG,IAAI;IAQxC;;OAEG;IACH,SAAS,CAAC,QAAQ,CAAC,cAAc,CAC/B,MAAM,EAAE,SAAS,EACjB,MAAM,EAAE,gBAAgB,GACvB,IAAI;IAMP;;;;OAIG;IACH,SAAS,CAAC,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,GAAG,IAAI;IAwC/D;;;;;OAKG;IACH,SAAS,CAAC,aAAa,CACrB,SAAS,CAAC,EAAE,MAAM,EAClB,MAAM,CAAC,EAAE,OAAO,EAChB,aAAa,CAAC,EAAE,MAAM,GAAG,MAAM,GAC9B,cAAc;IAcjB;;OAEG;IACH,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;CAUnC"}