dbgraph 0.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 (116) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +347 -0
  3. package/dist/bin/dbgraph.d.ts +8 -0
  4. package/dist/bin/dbgraph.d.ts.map +1 -0
  5. package/dist/bin/dbgraph.js +382 -0
  6. package/dist/bin/dbgraph.js.map +1 -0
  7. package/dist/config.d.ts +25 -0
  8. package/dist/config.d.ts.map +1 -0
  9. package/dist/config.js +158 -0
  10. package/dist/config.js.map +1 -0
  11. package/dist/context/formatter.d.ts +94 -0
  12. package/dist/context/formatter.d.ts.map +1 -0
  13. package/dist/context/formatter.js +288 -0
  14. package/dist/context/formatter.js.map +1 -0
  15. package/dist/context/index.d.ts +77 -0
  16. package/dist/context/index.d.ts.map +1 -0
  17. package/dist/context/index.js +458 -0
  18. package/dist/context/index.js.map +1 -0
  19. package/dist/db/index.d.ts +26 -0
  20. package/dist/db/index.d.ts.map +1 -0
  21. package/dist/db/index.js +127 -0
  22. package/dist/db/index.js.map +1 -0
  23. package/dist/db/migrations.d.ts +8 -0
  24. package/dist/db/migrations.d.ts.map +1 -0
  25. package/dist/db/migrations.js +39 -0
  26. package/dist/db/migrations.js.map +1 -0
  27. package/dist/db/queries.d.ts +46 -0
  28. package/dist/db/queries.d.ts.map +1 -0
  29. package/dist/db/queries.js +436 -0
  30. package/dist/db/queries.js.map +1 -0
  31. package/dist/db/schema.sql +113 -0
  32. package/dist/db/sqlite-adapter.d.ts +30 -0
  33. package/dist/db/sqlite-adapter.d.ts.map +1 -0
  34. package/dist/db/sqlite-adapter.js +78 -0
  35. package/dist/db/sqlite-adapter.js.map +1 -0
  36. package/dist/directory.d.ts +37 -0
  37. package/dist/directory.d.ts.map +1 -0
  38. package/dist/directory.js +160 -0
  39. package/dist/directory.js.map +1 -0
  40. package/dist/errors.d.ts +46 -0
  41. package/dist/errors.d.ts.map +1 -0
  42. package/dist/errors.js +90 -0
  43. package/dist/errors.js.map +1 -0
  44. package/dist/graph/traversal.d.ts +157 -0
  45. package/dist/graph/traversal.d.ts.map +1 -0
  46. package/dist/graph/traversal.js +531 -0
  47. package/dist/graph/traversal.js.map +1 -0
  48. package/dist/index.d.ts +183 -0
  49. package/dist/index.d.ts.map +1 -0
  50. package/dist/index.js +435 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/introspect/base.d.ts +62 -0
  53. package/dist/introspect/base.d.ts.map +1 -0
  54. package/dist/introspect/base.js +107 -0
  55. package/dist/introspect/base.js.map +1 -0
  56. package/dist/introspect/connection.d.ts +30 -0
  57. package/dist/introspect/connection.d.ts.map +1 -0
  58. package/dist/introspect/connection.js +232 -0
  59. package/dist/introspect/connection.js.map +1 -0
  60. package/dist/introspect/index.d.ts +23 -0
  61. package/dist/introspect/index.d.ts.map +1 -0
  62. package/dist/introspect/index.js +46 -0
  63. package/dist/introspect/index.js.map +1 -0
  64. package/dist/introspect/mysql.d.ts +64 -0
  65. package/dist/introspect/mysql.d.ts.map +1 -0
  66. package/dist/introspect/mysql.js +360 -0
  67. package/dist/introspect/mysql.js.map +1 -0
  68. package/dist/introspect/postgres.d.ts +55 -0
  69. package/dist/introspect/postgres.d.ts.map +1 -0
  70. package/dist/introspect/postgres.js +372 -0
  71. package/dist/introspect/postgres.js.map +1 -0
  72. package/dist/introspect/sqlite.d.ts +33 -0
  73. package/dist/introspect/sqlite.d.ts.map +1 -0
  74. package/dist/introspect/sqlite.js +207 -0
  75. package/dist/introspect/sqlite.js.map +1 -0
  76. package/dist/mcp/engine.d.ts +92 -0
  77. package/dist/mcp/engine.d.ts.map +1 -0
  78. package/dist/mcp/engine.js +261 -0
  79. package/dist/mcp/engine.js.map +1 -0
  80. package/dist/mcp/index.d.ts +33 -0
  81. package/dist/mcp/index.d.ts.map +1 -0
  82. package/dist/mcp/index.js +119 -0
  83. package/dist/mcp/index.js.map +1 -0
  84. package/dist/mcp/server-instructions.d.ts +9 -0
  85. package/dist/mcp/server-instructions.d.ts.map +1 -0
  86. package/dist/mcp/server-instructions.js +71 -0
  87. package/dist/mcp/server-instructions.js.map +1 -0
  88. package/dist/mcp/session.d.ts +35 -0
  89. package/dist/mcp/session.d.ts.map +1 -0
  90. package/dist/mcp/session.js +140 -0
  91. package/dist/mcp/session.js.map +1 -0
  92. package/dist/mcp/tools.d.ts +99 -0
  93. package/dist/mcp/tools.d.ts.map +1 -0
  94. package/dist/mcp/tools.js +499 -0
  95. package/dist/mcp/tools.js.map +1 -0
  96. package/dist/mcp/transport.d.ts +78 -0
  97. package/dist/mcp/transport.d.ts.map +1 -0
  98. package/dist/mcp/transport.js +182 -0
  99. package/dist/mcp/transport.js.map +1 -0
  100. package/dist/search/query-parser.d.ts +66 -0
  101. package/dist/search/query-parser.d.ts.map +1 -0
  102. package/dist/search/query-parser.js +163 -0
  103. package/dist/search/query-parser.js.map +1 -0
  104. package/dist/search/query-utils.d.ts +78 -0
  105. package/dist/search/query-utils.d.ts.map +1 -0
  106. package/dist/search/query-utils.js +203 -0
  107. package/dist/search/query-utils.js.map +1 -0
  108. package/dist/types.d.ts +279 -0
  109. package/dist/types.d.ts.map +1 -0
  110. package/dist/types.js +47 -0
  111. package/dist/types.js.map +1 -0
  112. package/dist/utils.d.ts +40 -0
  113. package/dist/utils.d.ts.map +1 -0
  114. package/dist/utils.js +190 -0
  115. package/dist/utils.js.map +1 -0
  116. package/package.json +54 -0
@@ -0,0 +1,92 @@
1
+ /**
2
+ * MCP Engine
3
+ *
4
+ * Manages the DBGraph instance lifecycle and dispatches to the tool handler.
5
+ *
6
+ * One engine serves many sessions (direct stdio mode or daemon socket mode).
7
+ * Initialization is lazy — started in the background on MCP initialize and
8
+ * retried synchronously before the first tool call. This lets the MCP server
9
+ * respond to initialize immediately without blocking on schema introspection.
10
+ */
11
+ import { DBGraphToolHandler } from './tools';
12
+ import type { ToolDefinition, ToolResult } from './tools';
13
+ /**
14
+ * MCP Engine — shared state for one or more MCP sessions.
15
+ */
16
+ export declare class MCPEngine {
17
+ private dbgraph;
18
+ private toolHandler;
19
+ private initPromise;
20
+ private projectPath;
21
+ private closed;
22
+ constructor();
23
+ /** Whether the default project's DBGraph is open and ready. */
24
+ isReady(): boolean;
25
+ /** Get tool definitions. */
26
+ getTools(): ToolDefinition[];
27
+ /** Get server instructions for the MCP initialize response. */
28
+ getServerInstructions(): string;
29
+ /** Get the underlying tool handler (for direct dispatch in server mode). */
30
+ getToolHandler(): DBGraphToolHandler;
31
+ /** The project root that was resolved on init (null if none). */
32
+ getProjectPath(): string | null;
33
+ /**
34
+ * Start initialization in the background (called from MCP initialize).
35
+ *
36
+ * Non-blocking — the engine will be ready by the time the first tool call
37
+ * arrives thanks to ensureInitialized / retry logic in the session layer.
38
+ * Multiple calls are idempotent; only the first starts the init flow.
39
+ */
40
+ startBackgroundInit(projectPath?: string): void;
41
+ /**
42
+ * Ensure the DBGraph instance is initialized — called before every tool call.
43
+ *
44
+ * If background init already succeeded (or is in-flight), this returns
45
+ * immediately (awaiting the in-flight promise if needed). If no background
46
+ * init was started, it runs synchronously.
47
+ *
48
+ * Throws if initialization fails, which the session layer catches and
49
+ * surfaces as an MCP error response.
50
+ */
51
+ ensureInitialized(projectPath?: string): Promise<void>;
52
+ /**
53
+ * Execute a tool by name.
54
+ */
55
+ executeTool(name: string, args: Record<string, unknown>): Promise<ToolResult>;
56
+ /**
57
+ * Full re-index of all configured databases.
58
+ * Optionally store a schema fingerprint after success (for watch mode).
59
+ */
60
+ executeReindex(fingerprint?: string): Promise<{
61
+ sourcesIndexed: number;
62
+ nodesCreated: number;
63
+ edgesCreated: number;
64
+ errors: string[];
65
+ }>;
66
+ /**
67
+ * Check if the database schema changed by comparing a lightweight
68
+ * fingerprint (column list hash) against the last known value.
69
+ * Only supports MySQL/MariaDB for now.
70
+ */
71
+ checkSchemaChanged(): Promise<{
72
+ changed: boolean;
73
+ detail: string;
74
+ currentFingerprint?: string;
75
+ }>;
76
+ /**
77
+ * Close the DBGraph instance and release resources.
78
+ * Idempotent — safe to call multiple times.
79
+ */
80
+ stop(): void;
81
+ /**
82
+ * Background initialization — walks up from searchFrom to find .dbgraph/,
83
+ * opens the database, and sets up the DBGraph instance.
84
+ */
85
+ private doInitialize;
86
+ /**
87
+ * Synchronous open used as a fallback retry when background init missed
88
+ * a newly-created .dbgraph/ directory.
89
+ */
90
+ private tryOpenSync;
91
+ }
92
+ //# sourceMappingURL=engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../../src/mcp/engine.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAG7C,OAAO,KAAK,EAAE,cAAc,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAE1D;;GAEG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,OAAO,CAAwB;IACvC,OAAO,CAAC,WAAW,CAAqB;IACxC,OAAO,CAAC,WAAW,CAA8B;IACjD,OAAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,MAAM,CAAS;;IAavB,+DAA+D;IAC/D,OAAO,IAAI,OAAO;IAIlB,4BAA4B;IAC5B,QAAQ,IAAI,cAAc,EAAE;IAI5B,+DAA+D;IAC/D,qBAAqB,IAAI,MAAM;IAI/B,4EAA4E;IAC5E,cAAc,IAAI,kBAAkB;IAIpC,iEAAiE;IACjE,cAAc,IAAI,MAAM,GAAG,IAAI;IAI/B;;;;;;OAMG;IACH,mBAAmB,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI;IAa/C;;;;;;;;;OASG;IACG,iBAAiB,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAoC5D;;OAEG;IACG,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,UAAU,CAAC;IAInF;;;OAGG;IACG,cAAc,CAAC,WAAW,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;QAClD,cAAc,EAAE,MAAM,CAAC;QACvB,YAAY,EAAE,MAAM,CAAC;QACrB,YAAY,EAAE,MAAM,CAAC;QACrB,MAAM,EAAE,MAAM,EAAE,CAAC;KAClB,CAAC;IAuBF;;;;OAIG;IACG,kBAAkB,IAAI,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,kBAAkB,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IA+CtG;;;OAGG;IACH,IAAI,IAAI,IAAI;IAkBZ;;;OAGG;YACW,YAAY;IAwB1B;;;OAGG;IACH,OAAO,CAAC,WAAW;CAgBpB"}
@@ -0,0 +1,261 @@
1
+ "use strict";
2
+ /**
3
+ * MCP Engine
4
+ *
5
+ * Manages the DBGraph instance lifecycle and dispatches to the tool handler.
6
+ *
7
+ * One engine serves many sessions (direct stdio mode or daemon socket mode).
8
+ * Initialization is lazy — started in the background on MCP initialize and
9
+ * retried synchronously before the first tool call. This lets the MCP server
10
+ * respond to initialize immediately without blocking on schema introspection.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.MCPEngine = void 0;
14
+ const index_1 = require("../index");
15
+ const directory_1 = require("../directory");
16
+ const tools_1 = require("./tools");
17
+ const server_instructions_1 = require("./server-instructions");
18
+ const connection_1 = require("../introspect/connection");
19
+ /**
20
+ * MCP Engine — shared state for one or more MCP sessions.
21
+ */
22
+ class MCPEngine {
23
+ dbgraph = null;
24
+ toolHandler;
25
+ initPromise = null;
26
+ projectPath = null;
27
+ closed = false;
28
+ constructor() {
29
+ // Pass a getter so the handler always reads the live instance.
30
+ // The `!` assert is safe because the handler is only called after
31
+ // ensureInitialized succeeds.
32
+ this.toolHandler = new tools_1.DBGraphToolHandler(() => this.dbgraph);
33
+ }
34
+ // ---------------------------------------------------------------------------
35
+ // Public API
36
+ // ---------------------------------------------------------------------------
37
+ /** Whether the default project's DBGraph is open and ready. */
38
+ isReady() {
39
+ return this.dbgraph !== null;
40
+ }
41
+ /** Get tool definitions. */
42
+ getTools() {
43
+ return this.toolHandler.getTools();
44
+ }
45
+ /** Get server instructions for the MCP initialize response. */
46
+ getServerInstructions() {
47
+ return server_instructions_1.SERVER_INSTRUCTIONS;
48
+ }
49
+ /** Get the underlying tool handler (for direct dispatch in server mode). */
50
+ getToolHandler() {
51
+ return this.toolHandler;
52
+ }
53
+ /** The project root that was resolved on init (null if none). */
54
+ getProjectPath() {
55
+ return this.projectPath;
56
+ }
57
+ /**
58
+ * Start initialization in the background (called from MCP initialize).
59
+ *
60
+ * Non-blocking — the engine will be ready by the time the first tool call
61
+ * arrives thanks to ensureInitialized / retry logic in the session layer.
62
+ * Multiple calls are idempotent; only the first starts the init flow.
63
+ */
64
+ startBackgroundInit(projectPath) {
65
+ if (this.closed)
66
+ return;
67
+ if (this.dbgraph)
68
+ return; // already initialized
69
+ if (this.initPromise)
70
+ return; // already in-flight
71
+ const searchFrom = projectPath ?? process.cwd();
72
+ this.projectPath = searchFrom;
73
+ this.initPromise = this.doInitialize(searchFrom).catch((err) => {
74
+ const msg = err instanceof Error ? err.message : String(err);
75
+ process.stderr.write(`[DBGraph MCP] Background init failed: ${msg}\n`);
76
+ });
77
+ }
78
+ /**
79
+ * Ensure the DBGraph instance is initialized — called before every tool call.
80
+ *
81
+ * If background init already succeeded (or is in-flight), this returns
82
+ * immediately (awaiting the in-flight promise if needed). If no background
83
+ * init was started, it runs synchronously.
84
+ *
85
+ * Throws if initialization fails, which the session layer catches and
86
+ * surfaces as an MCP error response.
87
+ */
88
+ async ensureInitialized(projectPath) {
89
+ if (this.closed)
90
+ return;
91
+ if (this.dbgraph)
92
+ return;
93
+ // If background init is running, await it
94
+ if (this.initPromise) {
95
+ await this.initPromise;
96
+ // Retry once more if background init failed — the .dbgraph/ directory
97
+ // may have appeared after the background attempt (user ran `dbgraph init`
98
+ // in another terminal between listTools and tools/call).
99
+ if (!this.dbgraph) {
100
+ const searchFrom = projectPath ?? this.projectPath ?? process.cwd();
101
+ this.projectPath = searchFrom;
102
+ this.tryOpenSync(searchFrom);
103
+ }
104
+ if (this.dbgraph)
105
+ return;
106
+ throw new Error(`DBGraph not initialized. Searched from: ${projectPath ?? this.projectPath ?? process.cwd()}\n` +
107
+ 'Run `dbgraph init` in your project directory first, then point your ' +
108
+ 'MCP client to the project path.');
109
+ }
110
+ // No background init was started — run synchronously now
111
+ const searchFrom = projectPath ?? process.cwd();
112
+ this.projectPath = searchFrom;
113
+ this.tryOpenSync(searchFrom);
114
+ if (!this.dbgraph) {
115
+ throw new Error(`DBGraph not initialized. Searched from: ${searchFrom}\n` +
116
+ 'Run `dbgraph init` in your project directory to create the .dbgraph/ index.');
117
+ }
118
+ }
119
+ /**
120
+ * Execute a tool by name.
121
+ */
122
+ async executeTool(name, args) {
123
+ return this.toolHandler.execute(name, args);
124
+ }
125
+ /**
126
+ * Full re-index of all configured databases.
127
+ * Optionally store a schema fingerprint after success (for watch mode).
128
+ */
129
+ async executeReindex(fingerprint) {
130
+ if (!this.dbgraph) {
131
+ throw new Error('DBGraph not initialized. Cannot re-index.');
132
+ }
133
+ const config = this.dbgraph.getConfig();
134
+ if (!config || config.databases.length === 0) {
135
+ throw new Error('No databases configured. Create a dbgraph-db.json file.');
136
+ }
137
+ const result = await this.dbgraph.indexAll();
138
+ // Store fingerprint after successful re-index so next poll can compare
139
+ if (fingerprint) {
140
+ this.dbgraph.getQueryBuilder().setMetadata('schema_fingerprint', fingerprint);
141
+ }
142
+ return {
143
+ sourcesIndexed: result.sourcesIndexed,
144
+ nodesCreated: result.nodesCreated,
145
+ edgesCreated: result.edgesCreated,
146
+ errors: result.errors,
147
+ };
148
+ }
149
+ /**
150
+ * Check if the database schema changed by comparing a lightweight
151
+ * fingerprint (column list hash) against the last known value.
152
+ * Only supports MySQL/MariaDB for now.
153
+ */
154
+ async checkSchemaChanged() {
155
+ if (!this.dbgraph)
156
+ return { changed: false, detail: 'No graph loaded' };
157
+ const config = this.dbgraph.getConfig();
158
+ if (!config || config.databases.length === 0)
159
+ return { changed: false, detail: 'No databases configured' };
160
+ const dbConfigs = config.databases.filter(d => d.engine === 'mysql' || d.engine === 'mariadb');
161
+ if (dbConfigs.length === 0)
162
+ return { changed: false, detail: 'No MySQL/MariaDB databases' };
163
+ // Compute current fingerprint: for each DB, MD5 of all (table.column, type, nullable)
164
+ const currentParts = [];
165
+ for (const db of dbConfigs) {
166
+ let conn;
167
+ try {
168
+ conn = await (0, connection_1.createConnection)(db);
169
+ const rows = await conn.query(`SELECT MD5(GROUP_CONCAT(
170
+ CONCAT_WS('.', TABLE_NAME, COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE)
171
+ ORDER BY TABLE_NAME, ORDINAL_POSITION
172
+ )) AS fingerprint
173
+ FROM information_schema.COLUMNS
174
+ WHERE TABLE_SCHEMA = ?`, [db.database]);
175
+ const fp = rows[0]?.fingerprint ?? '';
176
+ currentParts.push(`${db.alias}=${fp}`);
177
+ }
178
+ catch (err) {
179
+ const msg = err instanceof Error ? err.message : String(err);
180
+ currentParts.push(`${db.alias}=ERROR:${msg}`);
181
+ }
182
+ finally {
183
+ if (conn)
184
+ await conn.close().catch(() => { });
185
+ }
186
+ }
187
+ const currentFingerprint = currentParts.join('|');
188
+ // Load last fingerprint from project metadata
189
+ const lastFingerprint = this.dbgraph.getQueryBuilder().getMetadata('schema_fingerprint') ?? '';
190
+ if (currentFingerprint === lastFingerprint) {
191
+ return { changed: false, detail: 'Schema unchanged', currentFingerprint };
192
+ }
193
+ return { changed: true, detail: 'Schema changed: re-index required', currentFingerprint };
194
+ }
195
+ /**
196
+ * Close the DBGraph instance and release resources.
197
+ * Idempotent — safe to call multiple times.
198
+ */
199
+ stop() {
200
+ if (this.closed)
201
+ return;
202
+ this.closed = true;
203
+ if (this.dbgraph) {
204
+ try {
205
+ this.dbgraph.close();
206
+ }
207
+ catch {
208
+ // Ignore close errors — resources may already be freed
209
+ }
210
+ this.dbgraph = null;
211
+ }
212
+ this.initPromise = null;
213
+ }
214
+ // ---------------------------------------------------------------------------
215
+ // Private
216
+ // ---------------------------------------------------------------------------
217
+ /**
218
+ * Background initialization — walks up from searchFrom to find .dbgraph/,
219
+ * opens the database, and sets up the DBGraph instance.
220
+ */
221
+ async doInitialize(searchFrom) {
222
+ const resolvedRoot = (0, directory_1.findNearestDBGraphRoot)(searchFrom);
223
+ if (!resolvedRoot) {
224
+ // No .dbgraph/ found — that's normal. The session layer will retry
225
+ // on the first tool call, at which point the user may have run init.
226
+ this.projectPath = searchFrom;
227
+ return;
228
+ }
229
+ this.projectPath = resolvedRoot;
230
+ try {
231
+ this.dbgraph = await index_1.DBGraph.open(resolvedRoot);
232
+ process.stderr.write(`[DBGraph MCP] Opened schema graph at ${resolvedRoot}\n`);
233
+ }
234
+ catch (err) {
235
+ const msg = err instanceof Error ? err.message : String(err);
236
+ process.stderr.write(`[DBGraph MCP] Failed to open schema graph at ${resolvedRoot}: ${msg}\n`);
237
+ throw err;
238
+ }
239
+ }
240
+ /**
241
+ * Synchronous open used as a fallback retry when background init missed
242
+ * a newly-created .dbgraph/ directory.
243
+ */
244
+ tryOpenSync(searchFrom) {
245
+ try {
246
+ const resolvedRoot = (0, directory_1.findNearestDBGraphRoot)(searchFrom);
247
+ if (!resolvedRoot)
248
+ return;
249
+ this.dbgraph = index_1.DBGraph.openSync(resolvedRoot);
250
+ this.projectPath = resolvedRoot;
251
+ process.stderr.write(`[DBGraph MCP] Opened schema graph at ${resolvedRoot}\n`);
252
+ }
253
+ catch (err) {
254
+ const msg = err instanceof Error ? err.message : String(err);
255
+ process.stderr.write(`[DBGraph MCP] Sync open failed: ${msg}\n`);
256
+ this.dbgraph = null;
257
+ }
258
+ }
259
+ }
260
+ exports.MCPEngine = MCPEngine;
261
+ //# sourceMappingURL=engine.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine.js","sourceRoot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BA8QC"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * MCP Server
3
+ *
4
+ * Entry point for the MCP server. Wires transport, session, and engine.
5
+ */
6
+ export { MCPEngine } from './engine';
7
+ export interface MCPServerOptions {
8
+ projectPath?: string;
9
+ autoRefresh?: boolean;
10
+ }
11
+ /**
12
+ * MCPServer — manages MCP lifecycle (stdio or daemon mode)
13
+ */
14
+ export declare class MCPServer {
15
+ private engine;
16
+ private session;
17
+ private projectPath?;
18
+ private autoRefresh;
19
+ constructor(options?: MCPServerOptions);
20
+ /**
21
+ * Start MCP server in stdio mode (used by AI agents directly)
22
+ */
23
+ start(): void;
24
+ /**
25
+ * Start MCP server as a daemon listening on a Unix socket / named pipe
26
+ */
27
+ startDaemon(projectRoot: string): Promise<void>;
28
+ /**
29
+ * Stop the MCP server
30
+ */
31
+ stop(): void;
32
+ }
33
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/mcp/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAUH,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAErC,MAAM,WAAW,gBAAgB;IAC/B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED;;GAEG;AACH,qBAAa,SAAS;IACpB,OAAO,CAAC,MAAM,CAAY;IAC1B,OAAO,CAAC,OAAO,CAA2B;IAC1C,OAAO,CAAC,WAAW,CAAC,CAAS;IAC7B,OAAO,CAAC,WAAW,CAAU;gBAEjB,OAAO,GAAE,gBAAqB;IAM1C;;OAEG;IACH,KAAK,IAAI,IAAI;IASb;;OAEG;IACG,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAqCrD;;OAEG;IACH,IAAI,IAAI,IAAI;CAIb"}
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ /**
3
+ * MCP Server
4
+ *
5
+ * Entry point for the MCP server. Wires transport, session, and engine.
6
+ */
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __importStar = (this && this.__importStar) || (function () {
24
+ var ownKeys = function(o) {
25
+ ownKeys = Object.getOwnPropertyNames || function (o) {
26
+ var ar = [];
27
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
28
+ return ar;
29
+ };
30
+ return ownKeys(o);
31
+ };
32
+ return function (mod) {
33
+ if (mod && mod.__esModule) return mod;
34
+ var result = {};
35
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
36
+ __setModuleDefault(result, mod);
37
+ return result;
38
+ };
39
+ })();
40
+ Object.defineProperty(exports, "__esModule", { value: true });
41
+ exports.MCPServer = exports.MCPEngine = void 0;
42
+ const transport_1 = require("./transport");
43
+ const session_1 = require("./session");
44
+ const engine_1 = require("./engine");
45
+ const net = __importStar(require("net"));
46
+ const path = __importStar(require("path"));
47
+ const fs = __importStar(require("fs"));
48
+ const transport_2 = require("./transport");
49
+ var engine_2 = require("./engine");
50
+ Object.defineProperty(exports, "MCPEngine", { enumerable: true, get: function () { return engine_2.MCPEngine; } });
51
+ /**
52
+ * MCPServer — manages MCP lifecycle (stdio or daemon mode)
53
+ */
54
+ class MCPServer {
55
+ engine;
56
+ session = null;
57
+ projectPath;
58
+ autoRefresh;
59
+ constructor(options = {}) {
60
+ this.engine = new engine_1.MCPEngine();
61
+ this.projectPath = options.projectPath;
62
+ this.autoRefresh = options.autoRefresh ?? false;
63
+ }
64
+ /**
65
+ * Start MCP server in stdio mode (used by AI agents directly)
66
+ */
67
+ start() {
68
+ const transport = new transport_1.StdioTransport();
69
+ this.session = new session_1.MCPSession(transport, this.engine, {
70
+ explicitProjectPath: this.projectPath,
71
+ autoRefresh: this.autoRefresh,
72
+ });
73
+ this.session.start();
74
+ }
75
+ /**
76
+ * Start MCP server as a daemon listening on a Unix socket / named pipe
77
+ */
78
+ async startDaemon(projectRoot) {
79
+ const socketPath = (0, transport_2.getDaemonSocketPath)(projectRoot);
80
+ const pidPath = (0, transport_2.getDaemonPidPath)(projectRoot);
81
+ // Ensure .dbgraph dir exists
82
+ const dbgraphDir = path.join(projectRoot, '.dbgraph');
83
+ if (!fs.existsSync(dbgraphDir)) {
84
+ fs.mkdirSync(dbgraphDir, { recursive: true });
85
+ }
86
+ // Clean up stale socket
87
+ try {
88
+ if (fs.existsSync(socketPath)) {
89
+ fs.unlinkSync(socketPath);
90
+ }
91
+ }
92
+ catch { /* ignore */ }
93
+ // Write PID file
94
+ fs.writeFileSync(pidPath, String(process.pid), 'utf-8');
95
+ return new Promise((resolve) => {
96
+ const server = net.createServer((socket) => {
97
+ const transport = new transport_1.SocketTransport(socket);
98
+ const session = new session_1.MCPSession(transport, this.engine, {
99
+ explicitProjectPath: this.projectPath ?? projectRoot,
100
+ autoRefresh: this.autoRefresh,
101
+ });
102
+ session.start();
103
+ });
104
+ server.listen(socketPath, () => {
105
+ console.error(`DBGraph daemon listening on ${socketPath}`);
106
+ resolve();
107
+ });
108
+ });
109
+ }
110
+ /**
111
+ * Stop the MCP server
112
+ */
113
+ stop() {
114
+ this.session?.stop();
115
+ this.engine.stop();
116
+ }
117
+ }
118
+ exports.MCPServer = MCPServer;
119
+ //#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C;IACrB,CAAC;CACF;AAvED,8BAuEC"}
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Server-level instructions emitted in the MCP `initialize` response.
3
+ *
4
+ * MCP clients surface this text in the agent's system prompt automatically,
5
+ * giving the agent a high-level playbook for the dbgraph toolset before it
6
+ * sees individual tool descriptions.
7
+ */
8
+ export declare const SERVER_INSTRUCTIONS = "# DBGraph \u2014 database knowledge graph for schema-aware SQL generation\n\nDBGraph is a SQLite knowledge graph of every database schema object (tables,\ncolumns, views, indexes, foreign keys) in your project. The schema is\nintrospected ahead of time \u2014 reads are sub-millisecond and require no live\ndatabase connection.\n\n**Always consult dbgraph BEFORE writing SQL.** Understanding the schema first\nis the single largest quality lever for generated queries. A minute of\nschema exploration saves many rounds of \"fix the column name\" corrections.\n\n## Recommended workflow\n\n1. **`dbgraph_search`** \u2014 Find tables, columns, or views by name. Start here\n when you know roughly what you're looking for.\n\n2. **`dbgraph_context`** (PRIMARY) \u2014 Get the full schema of a table or view:\n columns, types, primary keys, foreign keys, indexes, and what references it.\n This is the main tool for understanding a schema object.\n\n3. **`dbgraph_trace`** \u2014 Trace foreign key join paths between two tables.\n Use this to discover how tables relate before writing JOIN clauses.\n\n4. **`dbgraph_explore`** \u2014 Fetch schemas for several related tables at once\n (fewer round-trips than calling `dbgraph_context` repeatedly).\n\n5. **`dbgraph_sources`** \u2014 List all configured databases and their engines.\n Useful when you don't know which database alias contains the table you need.\n\n6. **`dbgraph_status`** \u2014 See overall graph statistics: node/edge counts,\n breakdown by kind, and last index time. Quick health check.\n\n## When to use each tool\n\n| You want to... | Use this tool |\n|---|---|\n| Find a table or column by name | `dbgraph_search` |\n| See a table's full schema (columns, PKs, FKs, indexes) | `dbgraph_context` |\n| Discover how two tables join (FK path) | `dbgraph_trace` |\n| Explore several related tables at once | `dbgraph_explore` |\n| List available databases | `dbgraph_sources` |\n| Check if the schema index is healthy | `dbgraph_status` |\n\n## Common chains\n\n- **Write a correct JOIN**: `dbgraph_context` on each table \u2192 `dbgraph_trace`\n to confirm the FK path \u2192 then write SQL.\n- **Understand an unfamiliar schema**: `dbgraph_search` for key terms \u2192\n `dbgraph_context` on the main tables \u2192 `dbgraph_explore` on related ones.\n- **Debug a broken query**: `dbgraph_context` on each referenced table \u2192\n check column names and types \u2192 `dbgraph_trace` to verify join columns.\n\n## Anti-patterns\n\n- **Don't guess column names** \u2014 use `dbgraph_context` to see them.\n- **Don't chain many `dbgraph_context` calls** \u2014 use `dbgraph_explore` with\n space-separated table names for a batch view.\n- **Don't write JOINs without tracing** \u2014 `dbgraph_trace` reveals the FK path\n and often shows intermediate tables you didn't know existed.\n";
9
+ //# sourceMappingURL=server-instructions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-instructions.d.ts","sourceRoot":"","sources":["../../src/mcp/server-instructions.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,eAAO,MAAM,mBAAmB,ozFA2D/B,CAAC"}
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ /**
3
+ * Server-level instructions emitted in the MCP `initialize` response.
4
+ *
5
+ * MCP clients surface this text in the agent's system prompt automatically,
6
+ * giving the agent a high-level playbook for the dbgraph toolset before it
7
+ * sees individual tool descriptions.
8
+ */
9
+ Object.defineProperty(exports, "__esModule", { value: true });
10
+ exports.SERVER_INSTRUCTIONS = void 0;
11
+ exports.SERVER_INSTRUCTIONS = `# DBGraph — database knowledge graph for schema-aware SQL generation
12
+
13
+ DBGraph is a SQLite knowledge graph of every database schema object (tables,
14
+ columns, views, indexes, foreign keys) in your project. The schema is
15
+ introspected ahead of time — reads are sub-millisecond and require no live
16
+ database connection.
17
+
18
+ **Always consult dbgraph BEFORE writing SQL.** Understanding the schema first
19
+ is the single largest quality lever for generated queries. A minute of
20
+ schema exploration saves many rounds of "fix the column name" corrections.
21
+
22
+ ## Recommended workflow
23
+
24
+ 1. **\`dbgraph_search\`** — Find tables, columns, or views by name. Start here
25
+ when you know roughly what you're looking for.
26
+
27
+ 2. **\`dbgraph_context\`** (PRIMARY) — Get the full schema of a table or view:
28
+ columns, types, primary keys, foreign keys, indexes, and what references it.
29
+ This is the main tool for understanding a schema object.
30
+
31
+ 3. **\`dbgraph_trace\`** — Trace foreign key join paths between two tables.
32
+ Use this to discover how tables relate before writing JOIN clauses.
33
+
34
+ 4. **\`dbgraph_explore\`** — Fetch schemas for several related tables at once
35
+ (fewer round-trips than calling \`dbgraph_context\` repeatedly).
36
+
37
+ 5. **\`dbgraph_sources\`** — List all configured databases and their engines.
38
+ Useful when you don't know which database alias contains the table you need.
39
+
40
+ 6. **\`dbgraph_status\`** — See overall graph statistics: node/edge counts,
41
+ breakdown by kind, and last index time. Quick health check.
42
+
43
+ ## When to use each tool
44
+
45
+ | You want to... | Use this tool |
46
+ |---|---|
47
+ | Find a table or column by name | \`dbgraph_search\` |
48
+ | See a table's full schema (columns, PKs, FKs, indexes) | \`dbgraph_context\` |
49
+ | Discover how two tables join (FK path) | \`dbgraph_trace\` |
50
+ | Explore several related tables at once | \`dbgraph_explore\` |
51
+ | List available databases | \`dbgraph_sources\` |
52
+ | Check if the schema index is healthy | \`dbgraph_status\` |
53
+
54
+ ## Common chains
55
+
56
+ - **Write a correct JOIN**: \`dbgraph_context\` on each table → \`dbgraph_trace\`
57
+ to confirm the FK path → then write SQL.
58
+ - **Understand an unfamiliar schema**: \`dbgraph_search\` for key terms →
59
+ \`dbgraph_context\` on the main tables → \`dbgraph_explore\` on related ones.
60
+ - **Debug a broken query**: \`dbgraph_context\` on each referenced table →
61
+ check column names and types → \`dbgraph_trace\` to verify join columns.
62
+
63
+ ## Anti-patterns
64
+
65
+ - **Don't guess column names** — use \`dbgraph_context\` to see them.
66
+ - **Don't chain many \`dbgraph_context\` calls** — use \`dbgraph_explore\` with
67
+ space-separated table names for a batch view.
68
+ - **Don't write JOINs without tracing** — \`dbgraph_trace\` reveals the FK path
69
+ and often shows intermediate tables you didn't know existed.
70
+ `;
71
+ //# sourceMappingURL=server-instructions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-instructions.js","sourceRoot":"","sources":["../../src/mcp/server-instructions.ts"],"names":[],"mappings":";AAAA;;;;;;GAMG;;;AAEU,QAAA,mBAAmB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2DlC,CAAC"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * MCP Session
3
+ *
4
+ * Manages a single MCP session — handles initialization, tool listing,
5
+ * and tool call dispatching.
6
+ */
7
+ import { JsonRpcTransport } from './transport';
8
+ import { MCPEngine } from './engine';
9
+ export interface MCPSessionOptions {
10
+ explicitProjectPath?: string;
11
+ autoRefresh?: boolean;
12
+ }
13
+ export declare class MCPSession {
14
+ private transport;
15
+ private engine;
16
+ private clientSupportsRoots;
17
+ private rootsAttempted;
18
+ private explicitProjectPath;
19
+ private watchConfig;
20
+ constructor(transport: JsonRpcTransport, engine: MCPEngine, opts?: MCPSessionOptions);
21
+ start(): void;
22
+ stop(): void;
23
+ getTransport(): JsonRpcTransport;
24
+ private handleMessage;
25
+ private retryInitIfNeeded;
26
+ /**
27
+ * Before each tool call, lazily check if the database schema changed
28
+ * and re-index if needed. Zero overhead when idle.
29
+ */
30
+ private refreshIfSchemaChanged;
31
+ private handleInitialize;
32
+ private handleToolsList;
33
+ private handleToolsCall;
34
+ }
35
+ //# sourceMappingURL=session.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session.d.ts","sourceRoot":"","sources":["../../src/mcp/session.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EACL,gBAAgB,EAEjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAErC,MAAM,WAAW,iBAAiB;IAChC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED,qBAAa,UAAU;IAOnB,OAAO,CAAC,SAAS;IACjB,OAAO,CAAC,MAAM;IAPhB,OAAO,CAAC,mBAAmB,CAAS;IACpC,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,mBAAmB,CAAgB;IAC3C,OAAO,CAAC,WAAW,CAAU;gBAGnB,SAAS,EAAE,gBAAgB,EAC3B,MAAM,EAAE,SAAS,EACzB,IAAI,GAAE,iBAAsB;IAM9B,KAAK,IAAI,IAAI;IAIb,IAAI,IAAI,IAAI;IAIZ,YAAY,IAAI,gBAAgB;YAIlB,aAAa;YA4Bb,iBAAiB;IAM/B;;;OAGG;YACW,sBAAsB;YAkBtB,gBAAgB;YA4BhB,eAAe;YAMf,eAAe;CA+B9B"}