-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathserver.ts
665 lines (610 loc) · 22.1 KB
/
server.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import {
CallToolRequestSchema,
ListResourcesRequestSchema,
ListToolsRequestSchema,
ReadResourceRequestSchema,
Resource,
Tool,
ToolSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
import { DBTProjectContainer } from "../manifest/dbtProjectContainer";
import { Uri, Disposable } from "vscode";
import { provideSingleton } from "../utils";
import {
DBTProject,
DBTTerminal,
TelemetryEvents,
TelemetryService,
} from "@extension";
import { RunModelParams } from "../dbt_client/dbtIntegration";
import { CommandProcessResult } from "../commandProcessExecution";
import { existsSync, readFileSync } from "fs";
const ToolInputSchema = ToolSchema.shape.inputSchema;
type ToolInput = z.infer<typeof ToolInputSchema>;
const BaseSchema = z.object({});
const BaseProjectRootSchema = BaseSchema.extend({ projectRoot: z.string() });
const GetColumnsOfModelSchema = BaseProjectRootSchema.extend({
modelName: z.string(),
});
const GetColumnsOfSourceSchema = BaseProjectRootSchema.extend({
sourceName: z.string(),
tableName: z.string(),
});
const GetColumnValuesSchema = BaseProjectRootSchema.extend({
model: z.string(),
column: z.string(),
});
const CompileModelSchema = BaseProjectRootSchema.extend({
modelName: z.string(),
});
const CompileQuerySchema = BaseProjectRootSchema.extend({
query: z.string(),
originalModelName: z.string().optional(),
});
const ExecuteSQLWithLimitSchema = BaseProjectRootSchema.extend({
query: z.string(),
modelName: z.string(),
limit: z.number(),
});
const RunModelSchema = BaseProjectRootSchema.extend({
plusOperatorLeft: z.enum(["", "+"]),
modelName: z.string(),
plusOperatorRight: z.enum(["", "+"]),
});
const BuildModelSchema = BaseProjectRootSchema.extend({
plusOperatorLeft: z.enum(["", "+"]),
modelName: z.string(),
plusOperatorRight: z.enum(["", "+"]),
});
const BuildProjectSchema = BaseProjectRootSchema.extend({});
const RunTestSchema = BaseProjectRootSchema.extend({
testName: z.string(),
});
const RunModelTestSchema = BaseProjectRootSchema.extend({
modelName: z.string(),
});
const InstallDbtPackagesSchema = BaseProjectRootSchema.extend({
packages: z.array(z.string()),
});
const InstallDepsSchema = BaseProjectRootSchema.extend({});
const GetChildrenModelsSchema = BaseProjectRootSchema.extend({
table: z.string(),
});
const GetParentModelsSchema = BaseProjectRootSchema.extend({
table: z.string(),
});
enum ToolName {
GET_PROJECTS = "get_projects",
GET_CHILDREN_MODELS = "get_children_models",
GET_PARENT_MODELS = "get_parent_models",
GET_PROJECT_NAME = "get_project_name",
GET_SELECTED_TARGET = "get_selected_target",
GET_TARGET_NAMES = "get_target_names",
GET_TARGET_PATH = "get_target_path",
GET_PACKAGE_INSTALL_PATH = "get_package_install_path",
GET_MODEL_PATHS = "get_model_paths",
GET_SEED_PATHS = "get_seed_paths",
GET_MACRO_PATHS = "get_macro_paths",
GET_MANIFEST_PATH = "get_manifest_path",
GET_CATALOG_PATH = "get_catalog_path",
GET_DBT_VERSION = "get_dbt_version",
GET_ADAPTER_TYPE = "get_adapter_type",
GET_COLUMNS_OF_MODEL = "get_columns_of_model",
GET_COLUMNS_OF_SOURCE = "get_columns_of_source",
GET_COLUMN_VALUES = "get_column_values",
COMPILE_MODEL = "compile_model",
COMPILE_QUERY = "compile_query",
EXECUTE_SQL_WITH_LIMIT = "execute_sql_with_limit",
RUN_MODEL = "run_model",
BUILD_MODEL = "build_model",
BUILD_PROJECT = "build_project",
RUN_TEST = "run_test",
RUN_MODEL_TEST = "run_model_test",
INSTALL_DBT_PACKAGES = "install_dbt_packages",
INSTALL_DEPS = "install_deps",
}
@provideSingleton(DbtPowerUserMcpServerTools)
export class DbtPowerUserMcpServerTools implements Disposable {
constructor(
private dbtProjectContainer: DBTProjectContainer,
private dbtTerminal: DBTTerminal,
private telemetry: TelemetryService,
) {}
dispose() {}
private handleDbtCommandOutput = (result?: CommandProcessResult) => {
if (result?.stderr) {
throw new Error(result.stderr);
}
return {
content: [
{
type: "text",
text: result?.stdout,
},
],
};
};
public createServer = () => {
const server = new Server(
{
name: "DbtPowerUserMcpServerTools",
version: "1.0.0",
},
{
capabilities: {
prompts: {},
resources: { subscribe: true },
tools: {},
logging: {},
},
},
);
server.onerror = (error) => {
this.dbtTerminal.error("DbtPowerUserMcpServerTools", "Error", { error });
};
const getProjectResources = () => {
return this.dbtProjectContainer.getProjects().flatMap((project) => {
const projectRoot = project.projectRoot.fsPath;
const resources: Resource[] = [];
// Add manifest if exists
const manifestPath = project.getManifestPath();
if (manifestPath && existsSync(manifestPath)) {
resources.push({
uri: `file://${encodeURI(manifestPath)}`,
name: "manifest.json",
description: `dbt manifest for ${project.getProjectName()}`,
mimeType: "application/json",
});
}
// Add catalog if exists
const catalogPath = project.getCatalogPath();
if (catalogPath && existsSync(catalogPath)) {
resources.push({
uri: `file://${encodeURI(catalogPath)}`,
name: "catalog.json",
description: `dbt catalog for ${project.getProjectName()}`,
mimeType: "application/json",
});
}
return resources;
});
};
// List available resources
server.setRequestHandler(ListResourcesRequestSchema, async () => {
return { resources: getProjectResources() };
});
// Read resource contents
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
const decodedUri = decodeURIComponent(request.params.uri);
const filePath = Uri.parse(decodedUri).fsPath;
// Security: Validate path belongs to a known project
const isValid = this.dbtProjectContainer.getProjects().some((project) => {
return project.contains(Uri.file(filePath));
});
if (!existsSync(filePath) || !isValid) {
throw new Error("Resource not found or unauthorized");
}
return {
contents: [
{
uri: request.params.uri,
mimeType: "application/json",
text: readFileSync(filePath, "utf8"),
},
],
};
});
// Existing tools handler continues below
server.setRequestHandler(ListToolsRequestSchema, async () => {
this.dbtTerminal.debug("DbtPowerUserMcpServerTools", "Listing tools");
const tools: Tool[] = [
{
name: ToolName.GET_PROJECTS,
description:
"Returns a list of all available dbt project root paths. This must be called first to get the projectRoot parameter needed for all other tools.",
inputSchema: zodToJsonSchema(BaseSchema) as ToolInput,
},
{
name: ToolName.GET_PROJECT_NAME,
description: "Get project name",
inputSchema: zodToJsonSchema(BaseProjectRootSchema) as ToolInput,
},
{
name: ToolName.GET_SELECTED_TARGET,
description: "Get selected target",
inputSchema: zodToJsonSchema(BaseProjectRootSchema) as ToolInput,
},
{
name: ToolName.GET_TARGET_NAMES,
description: "Get target names",
inputSchema: zodToJsonSchema(BaseProjectRootSchema) as ToolInput,
},
{
name: ToolName.GET_TARGET_PATH,
description: "Get target path",
inputSchema: zodToJsonSchema(BaseProjectRootSchema) as ToolInput,
},
{
name: ToolName.GET_PACKAGE_INSTALL_PATH,
description: "Get package install path",
inputSchema: zodToJsonSchema(BaseProjectRootSchema) as ToolInput,
},
{
name: ToolName.GET_MODEL_PATHS,
description: "Get model paths",
inputSchema: zodToJsonSchema(BaseProjectRootSchema) as ToolInput,
},
{
name: ToolName.GET_SEED_PATHS,
description: "Get seed paths",
inputSchema: zodToJsonSchema(BaseProjectRootSchema) as ToolInput,
},
{
name: ToolName.GET_MACRO_PATHS,
description: "Get macro paths",
inputSchema: zodToJsonSchema(BaseProjectRootSchema) as ToolInput,
},
{
name: ToolName.GET_MANIFEST_PATH,
description: "Get manifest path",
inputSchema: zodToJsonSchema(BaseProjectRootSchema) as ToolInput,
},
{
name: ToolName.GET_CATALOG_PATH,
description: "Get catalog path",
inputSchema: zodToJsonSchema(BaseProjectRootSchema) as ToolInput,
},
{
name: ToolName.GET_DBT_VERSION,
description: "Get dbt version",
inputSchema: zodToJsonSchema(BaseProjectRootSchema) as ToolInput,
},
{
name: ToolName.GET_ADAPTER_TYPE,
description: "Get adapter type",
inputSchema: zodToJsonSchema(BaseProjectRootSchema) as ToolInput,
},
{
name: ToolName.GET_COLUMNS_OF_MODEL,
description:
"Returns the column names and data types for a specified dbt model. Use this to understand a model's schema before querying it.",
inputSchema: zodToJsonSchema(GetColumnsOfModelSchema) as ToolInput,
},
{
name: ToolName.GET_COLUMNS_OF_SOURCE,
description:
"Returns the column names and data types for a specified dbt source. Use this to understand a source's schema before querying it.",
inputSchema: zodToJsonSchema(GetColumnsOfSourceSchema) as ToolInput,
},
{
name: ToolName.GET_COLUMN_VALUES,
description:
"Returns the distinct values for a specified column in a model or source. Use this to understand the data distribution and possible values in a column.",
inputSchema: zodToJsonSchema(GetColumnValuesSchema) as ToolInput,
},
{
name: ToolName.COMPILE_MODEL,
description:
"Converts a dbt model's Jinja SQL into raw SQL. Use this to inspect the generated SQL before executing it. Note: This does not validate if the SQL will run successfully.",
inputSchema: zodToJsonSchema(CompileModelSchema) as ToolInput,
},
{
name: ToolName.COMPILE_QUERY,
description:
"Compile query, this will only convert the Jinja SQL to SQL, not determine if the SQL actually works. If the compilation succeeds, use the execute SQL and validate the data.",
inputSchema: zodToJsonSchema(CompileQuerySchema) as ToolInput,
},
{
name: ToolName.EXECUTE_SQL_WITH_LIMIT,
description:
"Executes a SQL query with a specified row limit and returns the results. Use this to test queries for newly created dbt models and retrieve sample data from the database.",
inputSchema: zodToJsonSchema(ExecuteSQLWithLimitSchema) as ToolInput,
},
{
name: ToolName.RUN_MODEL,
description:
"Executes a dbt model in the database. Use + for plusOperatorLeft to include parent models, and + for plusOperatorRight to include child models in the run.",
inputSchema: zodToJsonSchema(RunModelSchema) as ToolInput,
},
{
name: ToolName.BUILD_MODEL,
description:
"Builds a dbt model in the database. Use + for plusOperatorLeft to include parent models, and + for plusOperatorRight to include child models in the build.",
inputSchema: zodToJsonSchema(BuildModelSchema) as ToolInput,
},
{
name: ToolName.BUILD_PROJECT,
description:
"Builds the dbt project, this will run seeds, models and all related tests",
inputSchema: zodToJsonSchema(BuildProjectSchema) as ToolInput,
},
{
name: ToolName.RUN_TEST,
description:
"Run an indivdual test based on the test name in the dbt manifest.",
inputSchema: zodToJsonSchema(RunTestSchema) as ToolInput,
},
{
name: ToolName.RUN_MODEL_TEST,
description:
"Run model tests, use this tool to run the existing tests defined for the dbt model",
inputSchema: zodToJsonSchema(RunModelTestSchema) as ToolInput,
},
{
name: ToolName.INSTALL_DBT_PACKAGES,
description:
"Install dbt package(s), the dbt package string should be in the form of packageName@version",
inputSchema: zodToJsonSchema(InstallDbtPackagesSchema) as ToolInput,
},
{
name: ToolName.INSTALL_DEPS,
description:
"Install dbt package dependencies based on the dbt projects's packages.yml file",
inputSchema: zodToJsonSchema(InstallDepsSchema) as ToolInput,
},
{
name: ToolName.GET_CHILDREN_MODELS,
description:
"Returns the list of models that depend on the specified model (its children). Use this to understand a model's downstream impact and lineage.",
inputSchema: zodToJsonSchema(GetChildrenModelsSchema) as ToolInput,
},
{
name: ToolName.GET_PARENT_MODELS,
description:
"Returns the list of models that the specified model depends on (its parents). Use this to understand a model's upstream dependencies and lineage.",
inputSchema: zodToJsonSchema(GetParentModelsSchema) as ToolInput,
},
];
return { tools };
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args = {} } = request.params;
this.dbtTerminal.debug("DbtPowerUserMcpServerTools", "Calling tool", {
name,
args,
});
this.telemetry.sendTelemetryEvent(TelemetryEvents["MCP/ToolCall"], {
name,
...args,
});
try {
if (name === ToolName.GET_PROJECTS) {
const projects = this.dbtProjectContainer
.getProjects()
.map((project: DBTProject) => project.projectRoot.fsPath);
return {
content: [
{
type: "text",
text: JSON.stringify(projects),
},
],
};
}
if (!args || !args.projectRoot) {
throw new Error("projectRoot is required");
}
const projectRoot = decodeURIComponent(args.projectRoot as string);
const project = this.dbtProjectContainer.findDBTProject(
Uri.file(projectRoot),
);
if (!project) {
throw new Error(`Project not found for root: ${args.projectRoot}`);
}
switch (name) {
case ToolName.GET_PROJECT_NAME:
return {
content: [{ type: "text", text: project.getProjectName() }],
};
case ToolName.GET_SELECTED_TARGET:
return {
content: [{ type: "text", text: project.getSelectedTarget() }],
};
case ToolName.GET_TARGET_NAMES: {
const targetNames = await project.getTargetNames();
return {
content: [{ type: "text", text: targetNames.join(", ") }],
};
}
case ToolName.GET_TARGET_PATH:
return {
content: [{ type: "text", text: project.getTargetPath() || "" }],
};
case ToolName.GET_PACKAGE_INSTALL_PATH:
return {
content: [
{
type: "text",
text: project.getPackageInstallPath() || "",
},
],
};
case ToolName.GET_MODEL_PATHS:
return {
content: [
{
type: "text",
text: project.getModelPaths()?.join(", ") || "",
},
],
};
case ToolName.GET_SEED_PATHS:
return {
content: [
{
type: "text",
text: project.getSeedPaths()?.join(", ") || "",
},
],
};
case ToolName.GET_MACRO_PATHS:
return {
content: [
{
type: "text",
text: project.getMacroPaths()?.join(", ") || "",
},
],
};
case ToolName.GET_MANIFEST_PATH:
return {
content: [
{ type: "text", text: project.getManifestPath() || "" },
],
};
case ToolName.GET_CATALOG_PATH:
return {
content: [{ type: "text", text: project.getCatalogPath() || "" }],
};
case ToolName.GET_DBT_VERSION:
return {
content: [
{
type: "text",
text: project.getDBTVersion()?.join(".") || "",
},
],
};
case ToolName.GET_ADAPTER_TYPE:
return {
content: [{ type: "text", text: project.getAdapterType() }],
};
case ToolName.GET_COLUMNS_OF_MODEL: {
const result = await project.getColumnsOfModel(
args.modelName as string,
);
return {
content: [{ type: "text", text: JSON.stringify(result) }],
};
}
case ToolName.GET_COLUMNS_OF_SOURCE: {
const result = await project.getColumnsOfSource(
args.sourceName as string,
args.tableName as string,
);
return {
content: [{ type: "text", text: JSON.stringify(result) }],
};
}
case ToolName.GET_COLUMN_VALUES: {
const result = await project.getColumnValues(
args.model as string,
args.column as string,
);
return {
content: [{ type: "text", text: JSON.stringify(result) }],
};
}
case ToolName.COMPILE_MODEL: {
const result = await project.unsafeCompileNode(
args.modelName as string,
);
return { content: [{ type: "text", text: result || "" }] };
}
case ToolName.EXECUTE_SQL_WITH_LIMIT: {
const result = await project.executeSQLWithLimit(
args.query as string,
args.modelName as string,
args.limit as number,
true,
false,
);
return {
content: [{ type: "text", text: JSON.stringify(result) }],
};
}
case ToolName.RUN_MODEL: {
const runModelParams: RunModelParams = {
plusOperatorLeft: args.plusOperatorLeft as string,
modelName: args.modelName as string,
plusOperatorRight: args.plusOperatorRight as string,
};
const result = await project.runModel(runModelParams, true);
return this.handleDbtCommandOutput(result);
}
case ToolName.BUILD_MODEL: {
const runModelParams: RunModelParams = {
plusOperatorLeft: args.plusOperatorLeft as string,
modelName: args.modelName as string,
plusOperatorRight: args.plusOperatorRight as string,
};
const result = await project.buildModel(runModelParams, true);
return this.handleDbtCommandOutput(result);
}
case ToolName.BUILD_PROJECT: {
const result = await project.buildProject(true);
return this.handleDbtCommandOutput(result);
}
case ToolName.RUN_TEST: {
const result = await project.runTest(args.testName as string, true);
return this.handleDbtCommandOutput(result);
}
case ToolName.RUN_MODEL_TEST: {
const result = await project.runModelTest(
args.modelName as string,
true,
);
return this.handleDbtCommandOutput(result);
}
case ToolName.INSTALL_DBT_PACKAGES: {
const result = await project.installDbtPackages(
args.packages as string[],
);
return {
content: [{ type: "text", text: result }],
};
}
case ToolName.INSTALL_DEPS: {
const result = await project.installDeps();
return {
content: [{ type: "text", text: result }],
};
}
case ToolName.COMPILE_QUERY: {
const result = await project.unsafeCompileQuery(
args.query as string,
args.originalModelName as string,
);
return { content: [{ type: "text", text: result || "" }] };
}
case ToolName.GET_CHILDREN_MODELS: {
const result = project.getChildrenModels({
table: args.table as string,
});
return {
content: [{ type: "text", text: JSON.stringify(result) }],
};
}
case ToolName.GET_PARENT_MODELS: {
const result = project.getParentModels({
table: args.table as string,
});
return {
content: [{ type: "text", text: JSON.stringify(result) }],
};
}
default:
throw new Error(`Unknown tool: ${name}`);
}
} catch (error) {
this.dbtTerminal.error("DbtPowerUserMcpServerTools", "Error", {
error,
});
return {
content: [
{
type: "text",
text: `Unable to complete tool call. ${(error as Error).message}`,
},
],
isError: true,
error: error,
};
}
});
return { server, cleanup: async () => {} };
};
}