forked from elastic/mcp-server-elasticsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
2441 lines (2211 loc) · 72.9 KB
/
index.ts
File metadata and controls
2441 lines (2211 loc) · 72.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/*
* Copyright Elasticsearch B.V. and contributors
* SPDX-License-Identifier: Apache-2.0
*/
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { Client, estypes, ClientOptions } from "@elastic/elasticsearch";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import fs from "fs";
// Configuration schema with auth options
const ConfigSchema = z
.object({
url: z
.string()
.trim()
.min(1, "Elasticsearch URL cannot be empty")
.url("Invalid Elasticsearch URL format")
.describe("Elasticsearch server URL"),
apiKey: z
.string()
.optional()
.describe("API key for Elasticsearch authentication"),
username: z
.string()
.optional()
.describe("Username for Elasticsearch authentication"),
password: z
.string()
.optional()
.describe("Password for Elasticsearch authentication"),
caCert: z
.string()
.optional()
.describe("Path to custom CA certificate for Elasticsearch"),
})
.refine(
(data) => {
// If username is provided, password must be provided
if (data.username) {
return !!data.password;
}
// If password is provided, username must be provided
if (data.password) {
return !!data.username;
}
// If apiKey is provided, it's valid
if (data.apiKey) {
return true;
}
// No auth is also valid (for local development)
return true;
},
{
message:
"Either ES_API_KEY or both ES_USERNAME and ES_PASSWORD must be provided, or no auth for local development",
path: ["username", "password"],
}
);
type ElasticsearchConfig = z.infer<typeof ConfigSchema>;
export async function createElasticsearchMcpServer(
config: ElasticsearchConfig
) {
const validatedConfig = ConfigSchema.parse(config);
const { url, apiKey, username, password, caCert } = validatedConfig;
const clientOptions: ClientOptions = {
node: url,
};
// Set up authentication
if (apiKey) {
clientOptions.auth = { apiKey };
} else if (username && password) {
clientOptions.auth = { username, password };
}
// Set up SSL/TLS certificate if provided
if (caCert) {
try {
const ca = fs.readFileSync(caCert);
clientOptions.tls = { ca };
} catch (error) {
console.error(
`Failed to read certificate file: ${
error instanceof Error ? error.message : String(error)
}`
);
}
}
const esClient = new Client(clientOptions);
const server = new McpServer({
name: "elasticsearch-mcp-server",
version: "0.1.1",
});
// Tool 1: List indices
server.tool(
"list_indices",
"List all available Elasticsearch indices",
{},
async () => {
try {
const response = await esClient.cat.indices({ format: "json" });
const indicesInfo = response.map((index) => ({
index: index.index,
health: index.health,
status: index.status,
docsCount: index.docsCount,
}));
return {
content: [
{
type: "text" as const,
text: `Found ${indicesInfo.length} indices`,
},
{
type: "text" as const,
text: JSON.stringify(indicesInfo, null, 2),
},
],
};
} catch (error) {
console.error(
`Failed to list indices: ${
error instanceof Error ? error.message : String(error)
}`
);
return {
content: [
{
type: "text" as const,
text: `Error: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
}
);
// Tool 2: Get mappings for an index
server.tool(
"get_mappings",
"Get field mappings for a specific Elasticsearch index",
{
index: z
.string()
.trim()
.min(1, "Index name is required")
.describe("Name of the Elasticsearch index to get mappings for"),
},
async ({ index }) => {
try {
const mappingResponse = await esClient.indices.getMapping({
index,
});
return {
content: [
{
type: "text" as const,
text: `Mappings for index: ${index}`,
},
{
type: "text" as const,
text: `Mappings for index ${index}: ${JSON.stringify(
mappingResponse[index]?.mappings || {},
null,
2
)}`,
},
],
};
} catch (error) {
console.error(
`Failed to get mappings: ${
error instanceof Error ? error.message : String(error)
}`
);
return {
content: [
{
type: "text" as const,
text: `Error: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
}
);
// Tool 3: Search an index with simplified parameters
server.tool(
"search",
"Perform an Elasticsearch search with the provided query DSL. Highlights are always enabled.",
{
index: z
.string()
.trim()
.min(1, "Index name is required")
.describe("Name of the Elasticsearch index to search"),
queryBody: z
.record(z.any())
.refine(
(val) => {
try {
JSON.parse(JSON.stringify(val));
return true;
} catch (e) {
return false;
}
},
{
message: "queryBody must be a valid Elasticsearch query DSL object",
}
)
.describe(
"Complete Elasticsearch query DSL object that can include query, size, from, sort, etc."
),
},
async ({ index, queryBody }) => {
try {
// Get mappings to identify text fields for highlighting
const mappingResponse = await esClient.indices.getMapping({
index,
});
const indexMappings = mappingResponse[index]?.mappings || {};
const searchRequest: estypes.SearchRequest = {
index,
...queryBody,
};
// Always do highlighting
if (indexMappings.properties) {
const textFields: Record<string, estypes.SearchHighlightField> = {};
for (const [fieldName, fieldData] of Object.entries(
indexMappings.properties
)) {
if (fieldData.type === "text" || "dense_vector" in fieldData) {
textFields[fieldName] = {};
}
}
searchRequest.highlight = {
fields: textFields,
pre_tags: ["<em>"],
post_tags: ["</em>"],
};
}
const result = await esClient.search(searchRequest);
// Extract the 'from' parameter from queryBody, defaulting to 0 if not provided
const from = queryBody.from || 0;
const contentFragments = result.hits.hits.map((hit) => {
const highlightedFields = hit.highlight || {};
const sourceData = hit._source || {};
let content = "";
for (const [field, highlights] of Object.entries(highlightedFields)) {
if (highlights && highlights.length > 0) {
content += `${field} (highlighted): ${highlights.join(
" ... "
)}\n`;
}
}
for (const [field, value] of Object.entries(sourceData)) {
if (!(field in highlightedFields)) {
content += `${field}: ${JSON.stringify(value)}\n`;
}
}
return {
type: "text" as const,
text: content.trim(),
};
});
const metadataFragment = {
type: "text" as const,
text: `Total results: ${
typeof result.hits.total === "number"
? result.hits.total
: result.hits.total?.value || 0
}, showing ${result.hits.hits.length} from position ${from}`,
};
return {
content: [metadataFragment, ...contentFragments],
};
} catch (error) {
console.error(
`Search failed: ${
error instanceof Error ? error.message : String(error)
}`
);
return {
content: [
{
type: "text" as const,
text: `Error: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
}
);
// Tool 4: Get shard information
server.tool(
"get_shards",
"Get shard information for all or specific indices",
{
index: z
.string()
.optional()
.describe("Optional index name to get shard information for"),
},
async ({ index }) => {
try {
const response = await esClient.cat.shards({
index,
format: "json",
});
const shardsInfo = response.map((shard) => ({
index: shard.index,
shard: shard.shard,
prirep: shard.prirep,
state: shard.state,
docs: shard.docs,
store: shard.store,
ip: shard.ip,
node: shard.node,
}));
const metadataFragment = {
type: "text" as const,
text: `Found ${shardsInfo.length} shards${
index ? ` for index ${index}` : ""
}`,
};
return {
content: [
metadataFragment,
{
type: "text" as const,
text: JSON.stringify(shardsInfo, null, 2),
},
],
};
} catch (error) {
console.error(
`Failed to get shard information: ${
error instanceof Error ? error.message : String(error)
}`
);
return {
content: [
{
type: "text" as const,
text: `Error: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
}
);
// Tool 5: Ingest document
server.tool(
"ingest_document",
"Insert a document into an Elasticsearch index",
{
index: z
.string()
.trim()
.min(1, "Index name is required")
.describe("Name of the Elasticsearch index to insert into"),
document: z
.record(z.any())
.refine(
(val) => {
try {
JSON.parse(JSON.stringify(val));
return true;
} catch (e) {
return false;
}
},
{
message: "document must be a valid JSON object"
}
)
.describe("Document data to insert into the index"),
id: z
.string()
.optional()
.describe("Optional document ID. If not provided, Elasticsearch will generate one")
},
async ({ index, document, id }) => {
try {
const indexParams: estypes.IndexRequest = {
index,
body: document
};
if (id) {
indexParams.id = id;
}
const result = await esClient.index(indexParams);
return {
content: [
{
type: "text" as const,
text: `Successfully inserted document with ID: ${result._id}`,
},
{
type: "text" as const,
text: `Result: ${JSON.stringify({
index: result._index,
id: result._id,
version: result._version,
result: result.result
}, null, 2)}`,
},
],
};
} catch (error) {
console.error(
`Failed to insert document: ${
error instanceof Error ? error.message : String(error)
}`
);
return {
content: [
{
type: "text" as const,
text: `Error: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
}
);
// Tool 6: Bulk ingest documents
server.tool(
"bulk_ingest",
"Insert multiple documents into an Elasticsearch index in a single request",
{
index: z
.string()
.trim()
.min(1, "Index name is required")
.describe("Name of the Elasticsearch index to insert into"),
documents: z
.array(z.record(z.any()))
.min(1, "At least one document is required")
.refine(
(val) => {
try {
JSON.parse(JSON.stringify(val));
return true;
} catch (e) {
return false;
}
},
{
message: "documents must be an array of valid JSON objects"
}
)
.describe("Array of document data to insert into the index"),
idField: z
.string()
.optional()
.describe("Optional field name to use for document IDs. If provided, this field from each document will be used as its ID")
},
async ({ index, documents, idField }) => {
try {
// Prepare bulk operations
const operations = [];
for (const doc of documents) {
// Add index action
operations.push({
index: {
_index: index,
...(idField && doc[idField] ? { _id: doc[idField].toString() } : {})
}
});
// Add document
operations.push(doc);
}
const result = await esClient.bulk({
operations
});
const successCount = result.items.filter(item => !item.index?.error).length;
const errorCount = result.items.filter(item => item.index?.error).length;
return {
content: [
{
type: "text" as const,
text: `Bulk operation completed with ${successCount} successful and ${errorCount} failed operations`,
},
{
type: "text" as const,
text: `Took: ${result.took}ms, Errors: ${result.errors}`,
},
...(errorCount > 0 ? [{
type: "text" as const,
text: `Errors: ${JSON.stringify(
result.items
.filter(item => item.index?.error)
.map(item => ({
id: item.index?._id,
error: item.index?.error
})),
null,
2
)}`
}] : [])
],
};
} catch (error) {
console.error(
`Failed to perform bulk operation: ${
error instanceof Error ? error.message : String(error)
}`
);
return {
content: [
{
type: "text" as const,
text: `Error: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
}
);
// Tool 7: Create index
server.tool(
"create_index",
"Create a new Elasticsearch index with optional mappings and settings",
{
index: z
.string()
.trim()
.min(1, "Index name is required")
.describe("Name of the new Elasticsearch index to create"),
mappings: z
.record(z.any())
.optional()
.describe("Optional mappings configuration for the index fields"),
settings: z
.record(z.any())
.optional()
.describe("Optional index settings like number of shards, replicas, etc.")
},
async ({ index, mappings, settings }) => {
try {
// Check if index already exists
const indexExists = await esClient.indices.exists({ index });
if (indexExists) {
return {
content: [
{
type: "text" as const,
text: `Error: Index '${index}' already exists. Choose a different name or delete the existing index first.`,
},
],
};
}
// Prepare create index request
const createIndexRequest: any = {
index
};
// Add mappings and settings if provided
if (mappings || settings) {
createIndexRequest.mappings = mappings;
createIndexRequest.settings = settings;
}
const result = await esClient.indices.create(createIndexRequest);
return {
content: [
{
type: "text" as const,
text: `Successfully created index '${index}'`,
},
{
type: "text" as const,
text: `Result: ${JSON.stringify({
acknowledged: result.acknowledged,
shards_acknowledged: result.shards_acknowledged,
index: result.index
}, null, 2)}`,
},
],
};
} catch (error) {
console.error(
`Failed to create index: ${
error instanceof Error ? error.message : String(error)
}`
);
return {
content: [
{
type: "text" as const,
text: `Error: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
}
);
// Tool 8: Create alert
server.tool(
"create_alert",
"Create an Elasticsearch watcher alert based on query conditions",
{
name: z
.string()
.trim()
.min(1, "Alert name is required")
.describe("Name for this alert"),
index: z
.string()
.trim()
.min(1, "Index name is required")
.describe("Name of the Elasticsearch index to monitor"),
query: z
.record(z.any())
.describe("Elasticsearch query to determine when the alert should trigger"),
schedule: z
.string()
.describe("Alert check schedule in cron format (e.g. '0 */1 * * * ?' for every minute)"),
actionType: z
.enum(["log", "index", "email", "webhook"])
.describe("Type of action to perform when alert triggers"),
actionDetails: z
.record(z.any())
.describe("Configuration details for the selected action type")
},
async ({ name, index, query, schedule, actionType, actionDetails }) => {
try {
// Check if watcher API is available
try {
await esClient.watcher.stats();
} catch (error) {
return {
content: [
{
type: "text" as const,
text: "Error: Watcher API is not available in your Elasticsearch installation or you don't have sufficient permissions.",
},
],
};
}
// Prepare the watcher definition
const watchId = `mcp_alert_${name.toLowerCase().replace(/\s+/g, '_')}`;
// Build the action based on actionType
const action: Record<string, any> = {};
switch (actionType) {
case "log":
action.logging = {
text: actionDetails.message || `Alert triggered for ${name}`
};
break;
case "index":
action.index = {
index: actionDetails.index || "alerts",
doc_type: actionDetails.doc_type || "_doc"
};
break;
case "email":
action.email = {
to: actionDetails.to || "alerts@example.com",
subject: actionDetails.subject || `Alert: ${name} triggered`,
body: {
html: actionDetails.body || `Alert <b>${name}</b> was triggered`
}
};
break;
case "webhook":
action.webhook = {
method: actionDetails.method || "POST",
host: actionDetails.host || "localhost",
port: actionDetails.port || 8080,
path: actionDetails.path || "/alert",
body: actionDetails.body || `Alert ${name} triggered`
};
break;
}
// Create the watcher
const watch = {
trigger: {
schedule: {
cron: schedule
}
},
input: {
search: {
request: {
search_type: "query_then_fetch",
indices: [index],
body: {
query: query
}
}
}
},
condition: {
compare: {
"ctx.payload.hits.total": {
gt: 0
}
}
},
actions: {
[`${actionType}_action`]: action
}
};
// Put the watch
const response = await esClient.watcher.putWatch({
id: watchId,
body: watch as any
});
return {
content: [
{
type: "text" as const,
text: `Successfully created alert "${name}" with ID: ${watchId}`,
},
{
type: "text" as const,
text: `Result: ${JSON.stringify({
created: response.created,
id: response._id,
version: response._version
}, null, 2)}`,
},
],
};
} catch (error) {
console.error(
`Failed to create alert: ${
error instanceof Error ? error.message : String(error)
}`
);
return {
content: [
{
type: "text" as const,
text: `Error: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
}
);
// Tool 9: Get alerts
server.tool(
"get_alerts",
"List all existing alerts (watches) in Elasticsearch",
{},
async () => {
try {
// Check if watcher API is available
try {
await esClient.watcher.stats();
} catch (error) {
return {
content: [
{
type: "text" as const,
text: "Error: Watcher API is not available in your Elasticsearch installation or you don't have sufficient permissions.",
},
],
};
}
// Get all watches with prefix mcp_alert_
const response = await esClient.search({
index: ".watches",
body: {
query: {
prefix: {
_id: "mcp_alert_"
}
}
} as any
});
const alerts = response.hits.hits.map((hit) => ({
id: hit._id || "",
name: (hit._id || "").replace("mcp_alert_", "").replace(/_/g, " "),
status: (hit._source as any)?.status?.state || "unknown",
lastExecuted: (hit._source as any)?.status?.last_execution?.time || "never"
}));
return {
content: [
{
type: "text" as const,
text: `Found ${alerts.length} alerts`,
},
{
type: "text" as const,
text: JSON.stringify(alerts, null, 2),
},
],
};
} catch (error) {
console.error(
`Failed to get alerts: ${
error instanceof Error ? error.message : String(error)
}`
);
return {
content: [
{
type: "text" as const,
text: `Error: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
}
);
// Tool 10: Delete alert
server.tool(
"delete_alert",
"Delete an existing alert (watch) in Elasticsearch",
{
name: z
.string()
.trim()
.min(1, "Alert name is required")
.describe("Name of the alert to delete")
},
async ({ name }) => {
try {
// Check if watcher API is available
try {
await esClient.watcher.stats();
} catch (error) {
return {
content: [
{
type: "text" as const,
text: "Error: Watcher API is not available in your Elasticsearch installation or you don't have sufficient permissions.",
},
],
};
}
const watchId = `mcp_alert_${name.toLowerCase().replace(/\s+/g, '_')}`;
// Check if watch exists first
const exists = await esClient.watcher.getWatch({
id: watchId
}).catch(() => null);
if (!exists) {
return {
content: [
{
type: "text" as const,
text: `Alert "${name}" not found.`,
},
],
};
}
// Delete the watch
const response = await esClient.watcher.deleteWatch({
id: watchId
});
return {
content: [
{
type: "text" as const,
text: `Successfully deleted alert "${name}"`,
},
{
type: "text" as const,
text: `Result: ${JSON.stringify({
found: response.found,
version: response._version
}, null, 2)}`,
},
],
};
} catch (error) {
console.error(
`Failed to delete alert: ${
error instanceof Error ? error.message : String(error)
}`
);
return {
content: [
{
type: "text" as const,
text: `Error: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
}
);
// Tool 11: Query builder
server.tool(
"build_query",
"Build an Elasticsearch query without writing raw JSON",
{
index: z
.string()
.trim()
.min(1, "Index name is required")
.describe("Name of the Elasticsearch index to query"),