misp-mcp 1.2.0 → 1.3.4

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.
@@ -0,0 +1,2468 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/config.ts
4
+ function getConfig() {
5
+ const url = process.env.MISP_URL;
6
+ if (!url) {
7
+ throw new Error("MISP_URL environment variable is required");
8
+ }
9
+ const apiKey = process.env.MISP_API_KEY;
10
+ if (!apiKey) {
11
+ throw new Error("MISP_API_KEY environment variable is required");
12
+ }
13
+ const verifySsl = process.env.MISP_VERIFY_SSL !== "false";
14
+ const timeout = parseInt(process.env.MISP_TIMEOUT ?? "30", 10) * 1e3;
15
+ return {
16
+ url: url.replace(/\/+$/, ""),
17
+ apiKey,
18
+ verifySsl,
19
+ timeout
20
+ };
21
+ }
22
+
23
+ // src/client.ts
24
+ import { Agent } from "undici";
25
+ var ID_PATTERN = /^[A-Za-z0-9_-]+$/;
26
+ function encodeId(id, kind = "id") {
27
+ if (!ID_PATTERN.test(id)) {
28
+ throw new Error(`Invalid ${kind}: ${JSON.stringify(id)}`);
29
+ }
30
+ return encodeURIComponent(id);
31
+ }
32
+ var MispClient = class {
33
+ baseUrl;
34
+ apiKey;
35
+ timeout;
36
+ dispatcher;
37
+ constructor(config) {
38
+ this.baseUrl = config.url;
39
+ this.apiKey = config.apiKey;
40
+ this.timeout = config.timeout;
41
+ this.dispatcher = new Agent({
42
+ connect: { rejectUnauthorized: config.verifySsl }
43
+ });
44
+ }
45
+ async request(method, path, body, rawResponse = false) {
46
+ const url = `${this.baseUrl}${path}`;
47
+ const headers = {
48
+ Authorization: this.apiKey,
49
+ Accept: "application/json",
50
+ "Content-Type": "application/json"
51
+ };
52
+ const controller = new AbortController();
53
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
54
+ const options = {
55
+ method,
56
+ headers,
57
+ body: body ? JSON.stringify(body) : void 0,
58
+ signal: controller.signal,
59
+ dispatcher: this.dispatcher
60
+ };
61
+ let response;
62
+ try {
63
+ response = await fetch(url, options);
64
+ } catch (err) {
65
+ if (err instanceof Error && err.name === "AbortError") {
66
+ throw new Error(`MISP API timeout after ${this.timeout}ms`);
67
+ }
68
+ const message = err instanceof Error ? err.message : String(err);
69
+ throw new Error(`MISP API request failed: ${message}`);
70
+ } finally {
71
+ clearTimeout(timeoutId);
72
+ }
73
+ const text = await response.text();
74
+ if (!response.ok) {
75
+ const statusMessages = {
76
+ 401: "Invalid API key or unauthorized",
77
+ 403: "Insufficient permissions",
78
+ 404: "Resource not found",
79
+ 405: "Method not allowed"
80
+ };
81
+ const prefix = statusMessages[response.status] || `HTTP ${response.status}`;
82
+ let detail = "";
83
+ try {
84
+ const parsed = JSON.parse(text);
85
+ detail = parsed.message || parsed.errors || text;
86
+ } catch {
87
+ detail = text;
88
+ }
89
+ throw new Error(`${prefix}: ${detail}`);
90
+ }
91
+ if (rawResponse) {
92
+ return text;
93
+ }
94
+ try {
95
+ return JSON.parse(text);
96
+ } catch {
97
+ throw new Error(`Failed to parse MISP response as JSON: ${text.slice(0, 200)}`);
98
+ }
99
+ }
100
+ // --- Event methods ---
101
+ async searchEvents(params) {
102
+ const body = {
103
+ returnFormat: "json",
104
+ limit: params.limit ?? 50
105
+ };
106
+ if (params.value) body.value = params.value;
107
+ if (params.type) body.type = params.type;
108
+ if (params.category) body.category = params.category;
109
+ if (params.tags) body.tags = params.tags;
110
+ if (params.eventid) body.eventid = params.eventid;
111
+ if (params.org) body.org = params.org;
112
+ if (params.dateFrom) body.from = params.dateFrom;
113
+ if (params.dateTo) body.to = params.dateTo;
114
+ if (params.last) body.last = params.last;
115
+ if (params.published !== void 0) body.published = params.published ? 1 : 0;
116
+ if (params.page) body.page = params.page;
117
+ const data = await this.request(
118
+ "POST",
119
+ "/events/restSearch",
120
+ body
121
+ );
122
+ return (data.response || []).map((r) => r.Event);
123
+ }
124
+ async getEvent(eventId) {
125
+ const data = await this.request(
126
+ "GET",
127
+ `/events/view/${encodeId(eventId, "eventId")}`
128
+ );
129
+ return data.Event;
130
+ }
131
+ async createEvent(params) {
132
+ const eventData = {
133
+ info: params.info,
134
+ distribution: params.distribution,
135
+ threat_level_id: params.threat_level_id,
136
+ analysis: params.analysis
137
+ };
138
+ if (params.date) eventData.date = params.date;
139
+ const data = await this.request("POST", "/events/add", {
140
+ Event: eventData
141
+ });
142
+ if (params.tags && params.tags.length > 0 && data.Event.id) {
143
+ for (const tag of params.tags) {
144
+ await this.tagEvent(data.Event.id, tag);
145
+ }
146
+ return this.getEvent(data.Event.id);
147
+ }
148
+ return data.Event;
149
+ }
150
+ async updateEvent(eventId, params) {
151
+ const eventData = {};
152
+ if (params.info !== void 0) eventData.info = params.info;
153
+ if (params.threat_level_id !== void 0)
154
+ eventData.threat_level_id = params.threat_level_id;
155
+ if (params.analysis !== void 0) eventData.analysis = params.analysis;
156
+ const data = await this.request(
157
+ "POST",
158
+ `/events/edit/${encodeId(eventId, "eventId")}`,
159
+ { Event: eventData }
160
+ );
161
+ return data.Event;
162
+ }
163
+ async publishEvent(eventId) {
164
+ return this.request(
165
+ "POST",
166
+ `/events/publish/${encodeId(eventId, "eventId")}`
167
+ );
168
+ }
169
+ async tagEvent(eventId, tag) {
170
+ return this.request("POST", "/events/addTag", {
171
+ event: eventId,
172
+ tag
173
+ });
174
+ }
175
+ async untagEvent(eventId, tag) {
176
+ return this.request("POST", "/events/removeTag", {
177
+ event: eventId,
178
+ tag
179
+ });
180
+ }
181
+ // --- Attribute methods ---
182
+ async searchAttributes(params) {
183
+ const body = {
184
+ returnFormat: "json",
185
+ limit: params.limit ?? 50
186
+ };
187
+ if (params.value) body.value = params.value;
188
+ if (params.type) body.type = params.type;
189
+ if (params.category) body.category = params.category;
190
+ if (params.tags) body.tags = params.tags;
191
+ if (params.to_ids !== void 0) body.to_ids = params.to_ids ? 1 : 0;
192
+ if (params.includeCorrelations)
193
+ body.includeCorrelations = 1;
194
+ if (params.last) body.last = params.last;
195
+ const data = await this.request(
196
+ "POST",
197
+ "/attributes/restSearch",
198
+ body
199
+ );
200
+ return data.response?.Attribute || [];
201
+ }
202
+ async addAttribute(eventId, params) {
203
+ const attrData = {
204
+ type: params.type,
205
+ value: params.value
206
+ };
207
+ if (params.category) attrData.category = params.category;
208
+ if (params.to_ids !== void 0) attrData.to_ids = params.to_ids;
209
+ if (params.comment) attrData.comment = params.comment;
210
+ if (params.distribution !== void 0)
211
+ attrData.distribution = params.distribution;
212
+ const data = await this.request(
213
+ "POST",
214
+ `/attributes/add/${encodeId(eventId, "eventId")}`,
215
+ attrData
216
+ );
217
+ if (params.tags && params.tags.length > 0 && data.Attribute?.id) {
218
+ for (const tag of params.tags) {
219
+ await this.request("POST", "/attributes/addTag", {
220
+ attribute: data.Attribute.id,
221
+ tag
222
+ });
223
+ }
224
+ }
225
+ return data.Attribute;
226
+ }
227
+ async deleteAttribute(attributeId, hard = false) {
228
+ const body = hard ? { hard: 1 } : {};
229
+ return this.request(
230
+ "POST",
231
+ `/attributes/delete/${encodeId(attributeId, "attributeId")}`,
232
+ body
233
+ );
234
+ }
235
+ // --- Describe types ---
236
+ async describeTypes() {
237
+ const data = await this.request(
238
+ "GET",
239
+ "/attributes/describeTypes"
240
+ );
241
+ return data.result;
242
+ }
243
+ // --- Tags ---
244
+ async listTags(search) {
245
+ const path = search ? `/tags/search/${encodeURIComponent(search)}` : "/tags";
246
+ const data = await this.request("GET", path);
247
+ return data.Tag || [];
248
+ }
249
+ // --- Sightings ---
250
+ async addSighting(params) {
251
+ const body = {
252
+ type: params.type
253
+ };
254
+ if (params.value) body.value = params.value;
255
+ if (params.source) body.source = params.source;
256
+ if (params.timestamp) body.timestamp = params.timestamp;
257
+ const path = params.attributeId ? `/sightings/add/${encodeId(params.attributeId, "attributeId")}` : "/sightings/add";
258
+ const data = await this.request("POST", path, body);
259
+ return data.Sighting;
260
+ }
261
+ // --- Warninglists ---
262
+ async checkWarninglists(value) {
263
+ return this.request(
264
+ "POST",
265
+ "/warninglists/checkValue",
266
+ [value]
267
+ );
268
+ }
269
+ // --- Statistics ---
270
+ async getStatistics() {
271
+ return this.request("GET", "/events/index");
272
+ }
273
+ // --- Taxonomies ---
274
+ async listTaxonomies() {
275
+ const data = await this.request("GET", "/taxonomies");
276
+ return (data || []).map((t) => t.Taxonomy);
277
+ }
278
+ // --- Exports ---
279
+ async exportEvents(params) {
280
+ const formatEndpoints = {
281
+ csv: "/events/csv/download",
282
+ stix: "/events/stix/download",
283
+ suricata: "/events/nids/suricata/download",
284
+ snort: "/events/nids/snort/download",
285
+ text: "/attributes/text/download",
286
+ rpz: "/attributes/rpz/download"
287
+ };
288
+ const endpoint = formatEndpoints[params.format];
289
+ if (!endpoint) {
290
+ throw new Error(
291
+ `Unsupported export format: ${params.format}. Supported: ${Object.keys(formatEndpoints).join(", ")}`
292
+ );
293
+ }
294
+ const body = {};
295
+ if (params.eventId) body.eventid = params.eventId;
296
+ if (params.type) body.type = params.type;
297
+ if (params.tags) body.tags = params.tags;
298
+ if (params.last) body.last = params.last;
299
+ return this.request("POST", endpoint, body, true);
300
+ }
301
+ async exportHashes(params) {
302
+ const validFormats = ["md5", "sha1", "sha256"];
303
+ if (!validFormats.includes(params.format)) {
304
+ throw new Error(
305
+ `Unsupported hash format: ${params.format}. Supported: ${validFormats.join(", ")}`
306
+ );
307
+ }
308
+ let path = `/events/hids/${params.format}/download`;
309
+ const queryParts = [];
310
+ if (params.last) queryParts.push(`last=${encodeURIComponent(params.last)}`);
311
+ if (params.tags) queryParts.push(`tags=${encodeURIComponent(params.tags.join(","))}`);
312
+ if (queryParts.length > 0) path += `?${queryParts.join("&")}`;
313
+ return this.request("GET", path, void 0, true);
314
+ }
315
+ // --- Objects ---
316
+ async listObjectTemplates() {
317
+ const data = await this.request("GET", "/objectTemplates");
318
+ return (data || []).map((t) => t.ObjectTemplate);
319
+ }
320
+ async getObjectTemplate(templateId) {
321
+ const data = await this.request(
322
+ "GET",
323
+ `/objectTemplates/view/${encodeId(templateId, "templateId")}`
324
+ );
325
+ return data.ObjectTemplate;
326
+ }
327
+ async addObject(eventId, params) {
328
+ const body = {
329
+ name: params.name,
330
+ Attribute: params.attributes.map((a) => ({
331
+ object_relation: a.object_relation,
332
+ type: a.type,
333
+ value: a.value,
334
+ to_ids: a.to_ids ?? false,
335
+ comment: a.comment
336
+ }))
337
+ };
338
+ if (params.comment) body.comment = params.comment;
339
+ if (params.distribution !== void 0)
340
+ body.distribution = params.distribution;
341
+ const data = await this.request(
342
+ "POST",
343
+ `/objects/add/${encodeId(eventId, "eventId")}`,
344
+ body
345
+ );
346
+ return data.Object;
347
+ }
348
+ async deleteObject(objectId, hard = false) {
349
+ const body = hard ? { hard: 1 } : {};
350
+ return this.request(
351
+ "POST",
352
+ `/objects/delete/${encodeId(objectId, "objectId")}`,
353
+ body
354
+ );
355
+ }
356
+ // --- Galaxies ---
357
+ async listGalaxies() {
358
+ const data = await this.request("GET", "/galaxies");
359
+ return (data || []).map((g) => g.Galaxy);
360
+ }
361
+ async getGalaxy(galaxyId) {
362
+ const data = await this.request("GET", `/galaxies/view/${encodeId(galaxyId, "galaxyId")}`);
363
+ return {
364
+ ...data.Galaxy,
365
+ GalaxyCluster: data.GalaxyCluster
366
+ };
367
+ }
368
+ async searchGalaxyClusters(search, galaxyType) {
369
+ const body = {
370
+ searchall: search
371
+ };
372
+ if (galaxyType) body.context = galaxyType;
373
+ const data = await this.request("POST", "/galaxy_clusters/restSearch", body);
374
+ return (data || []).map((c) => c.GalaxyCluster);
375
+ }
376
+ async attachGalaxyCluster(targetType, targetId, galaxyClusterId) {
377
+ if (!ID_PATTERN.test(galaxyClusterId)) {
378
+ throw new Error(`Invalid galaxyClusterId: ${JSON.stringify(galaxyClusterId)}`);
379
+ }
380
+ return this.request(
381
+ "POST",
382
+ `/galaxies/attachCluster/${encodeId(targetId, "targetId")}/${targetType}`,
383
+ { Galaxy: { target_id: galaxyClusterId } }
384
+ );
385
+ }
386
+ // --- Feeds ---
387
+ async listFeeds() {
388
+ const data = await this.request(
389
+ "GET",
390
+ "/feeds"
391
+ );
392
+ return (data || []).map((f) => f.Feed);
393
+ }
394
+ async toggleFeed(feedId, enable) {
395
+ return this.request(
396
+ "POST",
397
+ `/feeds/${enable ? "enable" : "disable"}/${encodeId(feedId, "feedId")}`
398
+ );
399
+ }
400
+ async fetchFeed(feedId) {
401
+ return this.request(
402
+ "GET",
403
+ `/feeds/fetchFromFeed/${encodeId(feedId, "feedId")}`
404
+ );
405
+ }
406
+ async cacheFeed(feedId) {
407
+ return this.request(
408
+ "GET",
409
+ `/feeds/cacheFeeds/${encodeId(feedId, "feedId")}`
410
+ );
411
+ }
412
+ // --- Organisations ---
413
+ async listOrganisations(scope = "all") {
414
+ const data = await this.request("GET", `/organisations/index/scope:${scope}`);
415
+ return (data || []).map((o) => o.Organisation);
416
+ }
417
+ async getOrganisation(orgId) {
418
+ const data = await this.request(
419
+ "GET",
420
+ `/organisations/view/${encodeId(orgId, "orgId")}`
421
+ );
422
+ return data.Organisation;
423
+ }
424
+ // --- Server ---
425
+ async getVersion() {
426
+ return this.request("GET", "/servers/getVersion");
427
+ }
428
+ async getServerSettings() {
429
+ try {
430
+ return await this.request(
431
+ "GET",
432
+ "/servers/serverSettings"
433
+ );
434
+ } catch (err) {
435
+ const msg = err instanceof Error ? err.message : String(err);
436
+ if (msg.startsWith("Insufficient permissions") || msg.startsWith("HTTP 403")) {
437
+ return {};
438
+ }
439
+ throw err;
440
+ }
441
+ }
442
+ async listSharingGroups() {
443
+ const data = await this.request("GET", "/sharing_groups");
444
+ return (data.response || []).map((g) => g.SharingGroup);
445
+ }
446
+ async deleteEvent(eventId) {
447
+ return this.request(
448
+ "POST",
449
+ `/events/delete/${encodeId(eventId, "eventId")}`
450
+ );
451
+ }
452
+ };
453
+
454
+ // src/mcp-server.ts
455
+ import { readFileSync } from "fs";
456
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
457
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
458
+
459
+ // src/tools/events.ts
460
+ import { z } from "zod";
461
+
462
+ // src/guards.ts
463
+ function destructiveEnvOptIn() {
464
+ return process.env.MISP_ALLOW_DESTRUCTIVE === "true";
465
+ }
466
+ function blocked(text) {
467
+ return {
468
+ content: [{ type: "text", text }],
469
+ isError: true
470
+ };
471
+ }
472
+ function requireConfirmation(confirm, action) {
473
+ if (confirm === true || destructiveEnvOptIn()) {
474
+ return null;
475
+ }
476
+ return blocked(
477
+ `Refused: ${action} is a destructive action. Pass "confirm": true to proceed, or set MISP_ALLOW_DESTRUCTIVE=true to pre-authorize destructive operations.`
478
+ );
479
+ }
480
+ function requireHardConfirmation(confirmHard, action) {
481
+ if (confirmHard === true) {
482
+ return null;
483
+ }
484
+ return blocked(
485
+ `Refused: ${action} is a PERMANENT, irreversible delete. Pass "confirmHard": true (in addition to "confirm": true) to proceed.`
486
+ );
487
+ }
488
+
489
+ // src/tools/events.ts
490
+ function registerEventTools(server, client) {
491
+ server.tool(
492
+ "misp_search_events",
493
+ "Search MISP events by IOC value, type, tags, date range, or organization",
494
+ {
495
+ value: z.string().optional().describe("IOC value to search across all attributes"),
496
+ type: z.string().optional().describe("Attribute type filter (ip-src, ip-dst, domain, md5, sha256, url, email-src, etc.)"),
497
+ category: z.string().optional().describe("Category filter (Network activity, Payload delivery, External analysis, etc.)"),
498
+ tags: z.array(z.string()).optional().describe("Tag filters (e.g., tlp:white, misp-galaxy:mitre-attack-pattern)"),
499
+ eventId: z.string().optional().describe("Specific event ID"),
500
+ org: z.string().optional().describe("Organization filter"),
501
+ dateFrom: z.string().optional().describe("Start date (YYYY-MM-DD)"),
502
+ dateTo: z.string().optional().describe("End date (YYYY-MM-DD)"),
503
+ last: z.string().optional().describe("Relative time (e.g., 1d, 7d, 30d, 6m)"),
504
+ published: z.boolean().optional().describe("Only published events"),
505
+ limit: z.number().optional().describe("Max results (default 50)"),
506
+ page: z.number().optional().describe("Page number for pagination")
507
+ },
508
+ async (params) => {
509
+ try {
510
+ const events = await client.searchEvents({
511
+ value: params.value,
512
+ type: params.type,
513
+ category: params.category,
514
+ tags: params.tags,
515
+ eventid: params.eventId,
516
+ org: params.org,
517
+ dateFrom: params.dateFrom,
518
+ dateTo: params.dateTo,
519
+ last: params.last,
520
+ published: params.published,
521
+ limit: params.limit,
522
+ page: params.page
523
+ });
524
+ if (events.length === 0) {
525
+ return {
526
+ content: [{ type: "text", text: "No events found matching the search criteria." }]
527
+ };
528
+ }
529
+ const summary = events.map((e) => ({
530
+ id: e.id,
531
+ info: e.info,
532
+ date: e.date,
533
+ threat_level: ["", "High", "Medium", "Low", "Undefined"][parseInt(e.threat_level_id) || 0],
534
+ analysis: ["Initial", "Ongoing", "Complete"][parseInt(e.analysis) || 0],
535
+ published: e.published,
536
+ org: e.Orgc?.name || "Unknown",
537
+ attribute_count: e.attribute_count,
538
+ tags: (e.Tag || []).map((t) => t.name)
539
+ }));
540
+ return {
541
+ content: [
542
+ {
543
+ type: "text",
544
+ text: JSON.stringify(summary, null, 2)
545
+ }
546
+ ]
547
+ };
548
+ } catch (err) {
549
+ return {
550
+ content: [
551
+ { type: "text", text: `Error searching events: ${err instanceof Error ? err.message : String(err)}` }
552
+ ],
553
+ isError: true
554
+ };
555
+ }
556
+ }
557
+ );
558
+ server.tool(
559
+ "misp_get_event",
560
+ "Get full details of a specific MISP event including all attributes, objects, tags, and related events",
561
+ {
562
+ eventId: z.string().describe("Event ID to retrieve")
563
+ },
564
+ async ({ eventId }) => {
565
+ try {
566
+ const event = await client.getEvent(eventId);
567
+ const result = {
568
+ id: event.id,
569
+ uuid: event.uuid,
570
+ info: event.info,
571
+ date: event.date,
572
+ threat_level: ["", "High", "Medium", "Low", "Undefined"][parseInt(event.threat_level_id) || 0],
573
+ analysis: ["Initial", "Ongoing", "Complete"][parseInt(event.analysis) || 0],
574
+ distribution: ["Organization", "Community", "Connected communities", "All communities", "Sharing group"][parseInt(event.distribution) || 0],
575
+ published: event.published,
576
+ org: event.Orgc?.name || "Unknown",
577
+ tags: (event.Tag || []).map((t) => t.name),
578
+ attribute_count: event.attribute_count,
579
+ attributes: (event.Attribute || []).map((a) => ({
580
+ id: a.id,
581
+ type: a.type,
582
+ category: a.category,
583
+ value: a.value,
584
+ to_ids: a.to_ids,
585
+ comment: a.comment
586
+ })),
587
+ objects: (event.Object || []).map((o) => ({
588
+ id: o.id,
589
+ name: o.name,
590
+ meta_category: o.meta_category,
591
+ attributes: (o.Attribute || []).map((a) => ({
592
+ type: a.type,
593
+ value: a.value
594
+ }))
595
+ })),
596
+ galaxies: (event.Galaxy || []).map((g) => ({
597
+ name: g.name,
598
+ type: g.type,
599
+ clusters: (g.GalaxyCluster || []).map((c) => c.value)
600
+ })),
601
+ related_events: (event.RelatedEvent || []).map((r) => ({
602
+ id: r.Event.id,
603
+ info: r.Event.info,
604
+ date: r.Event.date
605
+ }))
606
+ };
607
+ return {
608
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
609
+ };
610
+ } catch (err) {
611
+ return {
612
+ content: [
613
+ { type: "text", text: `Error getting event: ${err instanceof Error ? err.message : String(err)}` }
614
+ ],
615
+ isError: true
616
+ };
617
+ }
618
+ }
619
+ );
620
+ server.tool(
621
+ "misp_create_event",
622
+ "Create a new MISP event for documenting incidents or threat intelligence. Does not publish - use misp_publish_event separately.",
623
+ {
624
+ info: z.string().describe("Event description/title"),
625
+ distribution: z.union([z.literal(0), z.literal(1), z.literal(2), z.literal(3), z.literal(4)]).describe("0=Organization only, 1=Community, 2=Connected communities, 3=All communities, 4=Sharing group"),
626
+ threatLevel: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)]).describe("1=High, 2=Medium, 3=Low, 4=Undefined"),
627
+ analysis: z.union([z.literal(0), z.literal(1), z.literal(2)]).describe("0=Initial, 1=Ongoing, 2=Complete"),
628
+ date: z.string().optional().describe("Event date (YYYY-MM-DD)"),
629
+ tags: z.array(z.string()).optional().describe("Tags to apply")
630
+ },
631
+ async (params) => {
632
+ try {
633
+ const event = await client.createEvent({
634
+ info: params.info,
635
+ distribution: params.distribution,
636
+ threat_level_id: params.threatLevel,
637
+ analysis: params.analysis,
638
+ date: params.date,
639
+ tags: params.tags
640
+ });
641
+ return {
642
+ content: [
643
+ {
644
+ type: "text",
645
+ text: JSON.stringify(
646
+ {
647
+ id: event.id,
648
+ uuid: event.uuid,
649
+ info: event.info,
650
+ date: event.date,
651
+ published: event.published,
652
+ tags: (event.Tag || []).map((t) => t.name)
653
+ },
654
+ null,
655
+ 2
656
+ )
657
+ }
658
+ ]
659
+ };
660
+ } catch (err) {
661
+ return {
662
+ content: [
663
+ { type: "text", text: `Error creating event: ${err instanceof Error ? err.message : String(err)}` }
664
+ ],
665
+ isError: true
666
+ };
667
+ }
668
+ }
669
+ );
670
+ server.tool(
671
+ "misp_update_event",
672
+ "Update an existing MISP event's metadata (info, threat level, analysis status). Publishing is separate - use misp_publish_event.",
673
+ {
674
+ eventId: z.string().describe("Event ID to update"),
675
+ info: z.string().optional().describe("New event description"),
676
+ threatLevel: z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4)]).optional().describe("1=High, 2=Medium, 3=Low, 4=Undefined"),
677
+ analysis: z.union([z.literal(0), z.literal(1), z.literal(2)]).optional().describe("0=Initial, 1=Ongoing, 2=Complete")
678
+ },
679
+ async ({ eventId, info, threatLevel, analysis }) => {
680
+ try {
681
+ const event = await client.updateEvent(eventId, {
682
+ info,
683
+ threat_level_id: threatLevel,
684
+ analysis
685
+ });
686
+ return {
687
+ content: [
688
+ {
689
+ type: "text",
690
+ text: JSON.stringify(
691
+ {
692
+ id: event.id,
693
+ info: event.info,
694
+ threat_level_id: event.threat_level_id,
695
+ analysis: event.analysis,
696
+ published: event.published
697
+ },
698
+ null,
699
+ 2
700
+ )
701
+ }
702
+ ]
703
+ };
704
+ } catch (err) {
705
+ return {
706
+ content: [
707
+ { type: "text", text: `Error updating event: ${err instanceof Error ? err.message : String(err)}` }
708
+ ],
709
+ isError: true
710
+ };
711
+ }
712
+ }
713
+ );
714
+ server.tool(
715
+ "misp_publish_event",
716
+ "Publish a MISP event, triggering alerts and notifications to sharing partners. State-changing: requires confirm:true (or MISP_ALLOW_DESTRUCTIVE=true).",
717
+ {
718
+ eventId: z.string().describe("Event ID to publish"),
719
+ confirm: z.boolean().optional().describe("Must be true to publish (triggers alerts to sharing partners) unless MISP_ALLOW_DESTRUCTIVE=true")
720
+ },
721
+ async ({ eventId, confirm }) => {
722
+ try {
723
+ const guard = requireConfirmation(confirm, `publishing event ${eventId}`);
724
+ if (guard) return guard;
725
+ const result = await client.publishEvent(eventId);
726
+ return {
727
+ content: [
728
+ { type: "text", text: result.message || `Event ${eventId} published successfully.` }
729
+ ]
730
+ };
731
+ } catch (err) {
732
+ return {
733
+ content: [
734
+ { type: "text", text: `Error publishing event: ${err instanceof Error ? err.message : String(err)}` }
735
+ ],
736
+ isError: true
737
+ };
738
+ }
739
+ }
740
+ );
741
+ server.tool(
742
+ "misp_tag_event",
743
+ "Add or remove a tag from a MISP event (TLP, MITRE ATT&CK, custom tags). Removing a tag is destructive and requires confirm:true (or MISP_ALLOW_DESTRUCTIVE=true).",
744
+ {
745
+ eventId: z.string().describe("Event ID to tag"),
746
+ tag: z.string().describe("Tag name (e.g., tlp:white, misp-galaxy:mitre-attack-pattern)"),
747
+ remove: z.boolean().optional().describe("Set to true to remove the tag instead of adding"),
748
+ confirm: z.boolean().optional().describe("Required (true) when remove is true, unless MISP_ALLOW_DESTRUCTIVE=true. Ignored when adding a tag.")
749
+ },
750
+ async ({ eventId, tag, remove, confirm }) => {
751
+ try {
752
+ if (remove) {
753
+ const guard = requireConfirmation(confirm, `removing tag "${tag}" from event ${eventId}`);
754
+ if (guard) return guard;
755
+ await client.untagEvent(eventId, tag);
756
+ return {
757
+ content: [
758
+ { type: "text", text: `Tag "${tag}" removed from event ${eventId}.` }
759
+ ]
760
+ };
761
+ } else {
762
+ await client.tagEvent(eventId, tag);
763
+ return {
764
+ content: [
765
+ { type: "text", text: `Tag "${tag}" added to event ${eventId}.` }
766
+ ]
767
+ };
768
+ }
769
+ } catch (err) {
770
+ return {
771
+ content: [
772
+ { type: "text", text: `Error tagging event: ${err instanceof Error ? err.message : String(err)}` }
773
+ ],
774
+ isError: true
775
+ };
776
+ }
777
+ }
778
+ );
779
+ }
780
+
781
+ // src/tools/attributes.ts
782
+ import { z as z2 } from "zod";
783
+ function registerAttributeTools(server, client) {
784
+ server.tool(
785
+ "misp_search_attributes",
786
+ "Search for specific attributes (IOCs) across all MISP events",
787
+ {
788
+ value: z2.string().optional().describe("IOC value to search"),
789
+ type: z2.string().optional().describe("Attribute type (ip-src, ip-dst, domain, md5, sha256, url, email-src, hostname, etc.)"),
790
+ category: z2.string().optional().describe("Category filter"),
791
+ tags: z2.array(z2.string()).optional().describe("Tag filters"),
792
+ toIds: z2.boolean().optional().describe("Only IDS-flagged attributes"),
793
+ includeCorrelations: z2.boolean().optional().describe("Include correlation data"),
794
+ last: z2.string().optional().describe("Relative time filter (e.g., 1d, 7d, 30d)"),
795
+ limit: z2.number().optional().describe("Max results (default 50)")
796
+ },
797
+ async (params) => {
798
+ try {
799
+ const attributes = await client.searchAttributes({
800
+ value: params.value,
801
+ type: params.type,
802
+ category: params.category,
803
+ tags: params.tags,
804
+ to_ids: params.toIds,
805
+ includeCorrelations: params.includeCorrelations,
806
+ last: params.last,
807
+ limit: params.limit
808
+ });
809
+ if (attributes.length === 0) {
810
+ return {
811
+ content: [{ type: "text", text: "No attributes found matching the search criteria." }]
812
+ };
813
+ }
814
+ const summary = attributes.map((a) => ({
815
+ id: a.id,
816
+ event_id: a.event_id,
817
+ type: a.type,
818
+ category: a.category,
819
+ value: a.value,
820
+ to_ids: a.to_ids,
821
+ comment: a.comment || void 0,
822
+ tags: (a.Tag || []).map((t) => t.name),
823
+ event_info: a.Event?.info,
824
+ correlations: a.RelatedAttribute ? a.RelatedAttribute.map((r) => ({
825
+ value: r.value,
826
+ type: r.type,
827
+ event_id: r.event_id
828
+ })) : void 0
829
+ }));
830
+ return {
831
+ content: [{ type: "text", text: JSON.stringify(summary, null, 2) }]
832
+ };
833
+ } catch (err) {
834
+ return {
835
+ content: [
836
+ { type: "text", text: `Error searching attributes: ${err instanceof Error ? err.message : String(err)}` }
837
+ ],
838
+ isError: true
839
+ };
840
+ }
841
+ }
842
+ );
843
+ server.tool(
844
+ "misp_add_attribute",
845
+ "Add an IOC/attribute to a MISP event",
846
+ {
847
+ eventId: z2.string().describe("Event ID to add the attribute to"),
848
+ type: z2.string().describe("Attribute type (ip-src, ip-dst, domain, md5, sha256, sha1, url, email-src, hostname, filename, etc.)"),
849
+ value: z2.string().describe("The IOC value"),
850
+ category: z2.string().optional().describe("Category (auto-determined from type if omitted)"),
851
+ toIds: z2.boolean().optional().describe("Flag for IDS export (default true for applicable types)"),
852
+ comment: z2.string().optional().describe("Context/notes about this IOC"),
853
+ distribution: z2.number().optional().describe("Distribution level (0-4)"),
854
+ tags: z2.array(z2.string()).optional().describe("Tags to apply to the attribute")
855
+ },
856
+ async (params) => {
857
+ try {
858
+ const attribute = await client.addAttribute(params.eventId, {
859
+ type: params.type,
860
+ value: params.value,
861
+ category: params.category,
862
+ to_ids: params.toIds,
863
+ comment: params.comment,
864
+ distribution: params.distribution,
865
+ tags: params.tags
866
+ });
867
+ return {
868
+ content: [
869
+ {
870
+ type: "text",
871
+ text: JSON.stringify(
872
+ {
873
+ id: attribute.id,
874
+ event_id: attribute.event_id,
875
+ type: attribute.type,
876
+ category: attribute.category,
877
+ value: attribute.value,
878
+ to_ids: attribute.to_ids
879
+ },
880
+ null,
881
+ 2
882
+ )
883
+ }
884
+ ]
885
+ };
886
+ } catch (err) {
887
+ return {
888
+ content: [
889
+ { type: "text", text: `Error adding attribute: ${err instanceof Error ? err.message : String(err)}` }
890
+ ],
891
+ isError: true
892
+ };
893
+ }
894
+ }
895
+ );
896
+ server.tool(
897
+ "misp_add_attributes_bulk",
898
+ "Add multiple attributes (IOCs) to a MISP event at once",
899
+ {
900
+ eventId: z2.string().describe("Event ID to add attributes to"),
901
+ attributes: z2.array(
902
+ z2.object({
903
+ type: z2.string().describe("Attribute type"),
904
+ value: z2.string().describe("IOC value"),
905
+ category: z2.string().optional().describe("Category"),
906
+ toIds: z2.boolean().optional().describe("IDS flag"),
907
+ comment: z2.string().optional().describe("Comment")
908
+ })
909
+ ).describe("Array of attributes to add")
910
+ },
911
+ async ({ eventId, attributes }) => {
912
+ try {
913
+ const results = [];
914
+ for (const attr of attributes) {
915
+ try {
916
+ const created = await client.addAttribute(eventId, {
917
+ type: attr.type,
918
+ value: attr.value,
919
+ category: attr.category,
920
+ to_ids: attr.toIds,
921
+ comment: attr.comment
922
+ });
923
+ results.push({
924
+ value: attr.value,
925
+ type: attr.type,
926
+ id: created.id
927
+ });
928
+ } catch (err) {
929
+ results.push({
930
+ value: attr.value,
931
+ type: attr.type,
932
+ error: err instanceof Error ? err.message : String(err)
933
+ });
934
+ }
935
+ }
936
+ const succeeded = results.filter((r) => r.id);
937
+ const failed = results.filter((r) => r.error);
938
+ return {
939
+ content: [
940
+ {
941
+ type: "text",
942
+ text: JSON.stringify(
943
+ {
944
+ total: attributes.length,
945
+ succeeded: succeeded.length,
946
+ failed: failed.length,
947
+ results
948
+ },
949
+ null,
950
+ 2
951
+ )
952
+ }
953
+ ]
954
+ };
955
+ } catch (err) {
956
+ return {
957
+ content: [
958
+ { type: "text", text: `Error adding attributes: ${err instanceof Error ? err.message : String(err)}` }
959
+ ],
960
+ isError: true
961
+ };
962
+ }
963
+ }
964
+ );
965
+ server.tool(
966
+ "misp_delete_attribute",
967
+ "Delete (soft or hard) an attribute from MISP. Destructive: requires confirm:true (or MISP_ALLOW_DESTRUCTIVE=true); hard delete also requires confirmHard:true.",
968
+ {
969
+ attributeId: z2.string().describe("Attribute ID to delete"),
970
+ hard: z2.boolean().optional().describe("Hard delete (permanent) instead of soft delete"),
971
+ confirm: z2.boolean().optional().describe("Must be true to perform this destructive deletion (unless MISP_ALLOW_DESTRUCTIVE=true)"),
972
+ confirmHard: z2.boolean().optional().describe("Must be true (in addition to confirm) to perform a permanent hard delete")
973
+ },
974
+ async ({ attributeId, hard, confirm, confirmHard }) => {
975
+ try {
976
+ const guard = requireConfirmation(confirm, `deleting attribute ${attributeId}`);
977
+ if (guard) return guard;
978
+ if (hard) {
979
+ const hardGuard = requireHardConfirmation(
980
+ confirmHard,
981
+ `hard-deleting attribute ${attributeId}`
982
+ );
983
+ if (hardGuard) return hardGuard;
984
+ }
985
+ const result = await client.deleteAttribute(attributeId, hard);
986
+ return {
987
+ content: [
988
+ { type: "text", text: result.message || `Attribute ${attributeId} deleted successfully.` }
989
+ ]
990
+ };
991
+ } catch (err) {
992
+ return {
993
+ content: [
994
+ { type: "text", text: `Error deleting attribute: ${err instanceof Error ? err.message : String(err)}` }
995
+ ],
996
+ isError: true
997
+ };
998
+ }
999
+ }
1000
+ );
1001
+ }
1002
+
1003
+ // src/tools/correlation.ts
1004
+ import { z as z3 } from "zod";
1005
+ function registerCorrelationTools(server, client) {
1006
+ server.tool(
1007
+ "misp_correlate",
1008
+ "Find correlations for a specific observable value across all MISP events",
1009
+ {
1010
+ value: z3.string().describe("Observable value to correlate (IP, domain, hash, etc.)")
1011
+ },
1012
+ async ({ value }) => {
1013
+ try {
1014
+ const attributes = await client.searchAttributes({
1015
+ value,
1016
+ includeCorrelations: true
1017
+ });
1018
+ if (attributes.length === 0) {
1019
+ return {
1020
+ content: [{ type: "text", text: `No results found for "${value}" in MISP.` }]
1021
+ };
1022
+ }
1023
+ const eventMap = /* @__PURE__ */ new Map();
1024
+ for (const attr of attributes) {
1025
+ const eid = attr.event_id;
1026
+ if (!eventMap.has(eid)) {
1027
+ eventMap.set(eid, {
1028
+ event_id: eid,
1029
+ event_info: attr.Event?.info || "Unknown",
1030
+ attributes: []
1031
+ });
1032
+ }
1033
+ eventMap.get(eid).attributes.push({
1034
+ id: attr.id,
1035
+ type: attr.type,
1036
+ category: attr.category,
1037
+ value: attr.value
1038
+ });
1039
+ }
1040
+ const correlations = [];
1041
+ for (const attr of attributes) {
1042
+ if (attr.RelatedAttribute) {
1043
+ for (const rel of attr.RelatedAttribute) {
1044
+ correlations.push({
1045
+ value: rel.value,
1046
+ type: rel.type,
1047
+ event_id: rel.event_id
1048
+ });
1049
+ }
1050
+ }
1051
+ }
1052
+ const result = {
1053
+ searched_value: value,
1054
+ found_in_events: Array.from(eventMap.values()),
1055
+ total_events: eventMap.size,
1056
+ total_attributes: attributes.length,
1057
+ correlations: correlations.length > 0 ? correlations : void 0
1058
+ };
1059
+ return {
1060
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1061
+ };
1062
+ } catch (err) {
1063
+ return {
1064
+ content: [
1065
+ { type: "text", text: `Error correlating value: ${err instanceof Error ? err.message : String(err)}` }
1066
+ ],
1067
+ isError: true
1068
+ };
1069
+ }
1070
+ }
1071
+ );
1072
+ server.tool(
1073
+ "misp_get_related_events",
1074
+ "Get events related to a specific event through shared attributes and correlations",
1075
+ {
1076
+ eventId: z3.string().describe("Event ID to find related events for"),
1077
+ maxAttributes: z3.number().int().positive().optional().describe("Max number of to_ids attributes to correlate across (default 20). Higher values hit the MISP API more."),
1078
+ perAttributeLimit: z3.number().int().positive().optional().describe("Max matches to fetch per attribute value (default 100).")
1079
+ },
1080
+ async ({ eventId, maxAttributes, perAttributeLimit }) => {
1081
+ try {
1082
+ const attrCap = maxAttributes ?? 20;
1083
+ const matchLimit = perAttributeLimit ?? 100;
1084
+ const event = await client.getEvent(eventId);
1085
+ const eventAttributes = event.Attribute || [];
1086
+ if (eventAttributes.length === 0) {
1087
+ return {
1088
+ content: [{ type: "text", text: `Event ${eventId} has no attributes to correlate.` }]
1089
+ };
1090
+ }
1091
+ const relatedMap = /* @__PURE__ */ new Map();
1092
+ if (event.RelatedEvent && event.RelatedEvent.length > 0) {
1093
+ for (const rel of event.RelatedEvent) {
1094
+ relatedMap.set(rel.Event.id, {
1095
+ event_id: rel.Event.id,
1096
+ event_info: rel.Event.info,
1097
+ overlapping_iocs: [],
1098
+ correlation_count: 0
1099
+ });
1100
+ }
1101
+ }
1102
+ const toIdsAttrs = eventAttributes.filter((a) => a.to_ids);
1103
+ const truncatedAttributes = toIdsAttrs.length > attrCap;
1104
+ const valuesToSearch = toIdsAttrs.slice(0, attrCap).map((a) => a.value);
1105
+ let truncatedMatches = false;
1106
+ for (const value of valuesToSearch) {
1107
+ const matches = await client.searchAttributes({
1108
+ value,
1109
+ includeCorrelations: true,
1110
+ limit: matchLimit
1111
+ });
1112
+ if (matches.length >= matchLimit) {
1113
+ truncatedMatches = true;
1114
+ }
1115
+ for (const match of matches) {
1116
+ if (match.event_id !== eventId) {
1117
+ if (!relatedMap.has(match.event_id)) {
1118
+ relatedMap.set(match.event_id, {
1119
+ event_id: match.event_id,
1120
+ event_info: match.Event?.info || "Unknown",
1121
+ overlapping_iocs: [],
1122
+ correlation_count: 0
1123
+ });
1124
+ }
1125
+ const entry = relatedMap.get(match.event_id);
1126
+ if (!entry.overlapping_iocs.includes(value)) {
1127
+ entry.overlapping_iocs.push(value);
1128
+ }
1129
+ entry.correlation_count++;
1130
+ }
1131
+ }
1132
+ }
1133
+ const related = Array.from(relatedMap.values()).sort(
1134
+ (a, b) => b.correlation_count - a.correlation_count
1135
+ );
1136
+ return {
1137
+ content: [
1138
+ {
1139
+ type: "text",
1140
+ text: JSON.stringify(
1141
+ {
1142
+ event_id: eventId,
1143
+ event_info: event.info,
1144
+ related_events: related,
1145
+ total_related: related.length,
1146
+ truncated: truncatedAttributes || truncatedMatches,
1147
+ truncation_reason: truncatedAttributes ? `Only the first ${attrCap} of ${toIdsAttrs.length} to_ids attributes were correlated. Raise maxAttributes to scan more.` : truncatedMatches ? `At least one attribute hit the per-attribute match limit of ${matchLimit}. Raise perAttributeLimit to see more correlations.` : void 0
1148
+ },
1149
+ null,
1150
+ 2
1151
+ )
1152
+ }
1153
+ ]
1154
+ };
1155
+ } catch (err) {
1156
+ return {
1157
+ content: [
1158
+ { type: "text", text: `Error finding related events: ${err instanceof Error ? err.message : String(err)}` }
1159
+ ],
1160
+ isError: true
1161
+ };
1162
+ }
1163
+ }
1164
+ );
1165
+ server.tool(
1166
+ "misp_describe_types",
1167
+ "Get all available MISP attribute types and categories with their mappings",
1168
+ {},
1169
+ async () => {
1170
+ try {
1171
+ const types = await client.describeTypes();
1172
+ return {
1173
+ content: [{ type: "text", text: JSON.stringify(types, null, 2) }]
1174
+ };
1175
+ } catch (err) {
1176
+ return {
1177
+ content: [
1178
+ { type: "text", text: `Error getting types: ${err instanceof Error ? err.message : String(err)}` }
1179
+ ],
1180
+ isError: true
1181
+ };
1182
+ }
1183
+ }
1184
+ );
1185
+ }
1186
+
1187
+ // src/tools/tags.ts
1188
+ import { z as z4 } from "zod";
1189
+ function registerTagTools(server, client) {
1190
+ server.tool(
1191
+ "misp_list_tags",
1192
+ "List available MISP tags with usage statistics",
1193
+ {
1194
+ search: z4.string().optional().describe("Search filter for tag names"),
1195
+ limit: z4.number().optional().describe("Max results to return")
1196
+ },
1197
+ async ({ search, limit }) => {
1198
+ try {
1199
+ let tags = await client.listTags(search);
1200
+ if (limit && limit > 0) {
1201
+ tags = tags.slice(0, limit);
1202
+ }
1203
+ if (tags.length === 0) {
1204
+ return {
1205
+ content: [{ type: "text", text: "No tags found." }]
1206
+ };
1207
+ }
1208
+ const summary = tags.map((t) => ({
1209
+ id: t.id,
1210
+ name: t.name,
1211
+ colour: t.colour,
1212
+ event_count: t.event_count,
1213
+ attribute_count: t.attribute_count
1214
+ }));
1215
+ return {
1216
+ content: [{ type: "text", text: JSON.stringify(summary, null, 2) }]
1217
+ };
1218
+ } catch (err) {
1219
+ return {
1220
+ content: [
1221
+ { type: "text", text: `Error listing tags: ${err instanceof Error ? err.message : String(err)}` }
1222
+ ],
1223
+ isError: true
1224
+ };
1225
+ }
1226
+ }
1227
+ );
1228
+ server.tool(
1229
+ "misp_search_by_tag",
1230
+ "Search MISP events or attributes by tag (MITRE ATT&CK, TLP, custom tags)",
1231
+ {
1232
+ tag: z4.string().describe("Tag name to search for (e.g., tlp:white, mitre-attack:T1059)"),
1233
+ type: z4.enum(["event", "attribute"]).optional().describe("Search events or attributes (default: event)")
1234
+ },
1235
+ async ({ tag, type: searchType }) => {
1236
+ try {
1237
+ if (searchType === "attribute") {
1238
+ const attributes = await client.searchAttributes({ tags: [tag] });
1239
+ if (attributes.length === 0) {
1240
+ return {
1241
+ content: [{ type: "text", text: `No attributes found with tag "${tag}".` }]
1242
+ };
1243
+ }
1244
+ const summary2 = attributes.map((a) => ({
1245
+ id: a.id,
1246
+ event_id: a.event_id,
1247
+ type: a.type,
1248
+ value: a.value,
1249
+ category: a.category,
1250
+ event_info: a.Event?.info
1251
+ }));
1252
+ return {
1253
+ content: [{ type: "text", text: JSON.stringify(summary2, null, 2) }]
1254
+ };
1255
+ }
1256
+ const events = await client.searchEvents({ tags: [tag] });
1257
+ if (events.length === 0) {
1258
+ return {
1259
+ content: [{ type: "text", text: `No events found with tag "${tag}".` }]
1260
+ };
1261
+ }
1262
+ const summary = events.map((e) => ({
1263
+ id: e.id,
1264
+ info: e.info,
1265
+ date: e.date,
1266
+ threat_level: ["", "High", "Medium", "Low", "Undefined"][parseInt(e.threat_level_id) || 0],
1267
+ org: e.Orgc?.name || "Unknown",
1268
+ tags: (e.Tag || []).map((t) => t.name)
1269
+ }));
1270
+ return {
1271
+ content: [{ type: "text", text: JSON.stringify(summary, null, 2) }]
1272
+ };
1273
+ } catch (err) {
1274
+ return {
1275
+ content: [
1276
+ { type: "text", text: `Error searching by tag: ${err instanceof Error ? err.message : String(err)}` }
1277
+ ],
1278
+ isError: true
1279
+ };
1280
+ }
1281
+ }
1282
+ );
1283
+ }
1284
+
1285
+ // src/tools/exports.ts
1286
+ import { z as z5 } from "zod";
1287
+ function registerExportTools(server, client) {
1288
+ server.tool(
1289
+ "misp_export_iocs",
1290
+ "Export IOCs from MISP in various formats (CSV, STIX, Suricata, Snort, text, RPZ)",
1291
+ {
1292
+ format: z5.enum(["csv", "stix", "suricata", "snort", "text", "rpz"]).describe("Export format"),
1293
+ eventId: z5.string().optional().describe("Specific event ID (or all events if omitted)"),
1294
+ type: z5.string().optional().describe("Filter by attribute type"),
1295
+ tags: z5.array(z5.string()).optional().describe("Filter by tags"),
1296
+ last: z5.string().optional().describe("Relative time filter (e.g., 1d, 7d)")
1297
+ },
1298
+ async (params) => {
1299
+ try {
1300
+ const output = await client.exportEvents({
1301
+ format: params.format,
1302
+ eventId: params.eventId,
1303
+ type: params.type,
1304
+ tags: params.tags,
1305
+ last: params.last
1306
+ });
1307
+ if (!output || output.trim().length === 0) {
1308
+ return {
1309
+ content: [
1310
+ { type: "text", text: `No IOCs found for the specified criteria in ${params.format} format.` }
1311
+ ]
1312
+ };
1313
+ }
1314
+ return {
1315
+ content: [{ type: "text", text: output }]
1316
+ };
1317
+ } catch (err) {
1318
+ return {
1319
+ content: [
1320
+ { type: "text", text: `Error exporting IOCs: ${err instanceof Error ? err.message : String(err)}` }
1321
+ ],
1322
+ isError: true
1323
+ };
1324
+ }
1325
+ }
1326
+ );
1327
+ server.tool(
1328
+ "misp_export_hashes",
1329
+ "Export file hashes from MISP for HIDS integration",
1330
+ {
1331
+ format: z5.enum(["md5", "sha1", "sha256"]).describe("Hash format to export"),
1332
+ last: z5.string().optional().describe("Relative time filter (e.g., 1d, 7d)"),
1333
+ tags: z5.array(z5.string()).optional().describe("Filter by tags")
1334
+ },
1335
+ async (params) => {
1336
+ try {
1337
+ const output = await client.exportHashes({
1338
+ format: params.format,
1339
+ last: params.last,
1340
+ tags: params.tags
1341
+ });
1342
+ if (!output || output.trim().length === 0) {
1343
+ return {
1344
+ content: [
1345
+ { type: "text", text: `No ${params.format} hashes found for the specified criteria.` }
1346
+ ]
1347
+ };
1348
+ }
1349
+ return {
1350
+ content: [{ type: "text", text: output }]
1351
+ };
1352
+ } catch (err) {
1353
+ return {
1354
+ content: [
1355
+ { type: "text", text: `Error exporting hashes: ${err instanceof Error ? err.message : String(err)}` }
1356
+ ],
1357
+ isError: true
1358
+ };
1359
+ }
1360
+ }
1361
+ );
1362
+ }
1363
+
1364
+ // src/tools/sightings.ts
1365
+ import { z as z6 } from "zod";
1366
+ function registerSightingTools(server, client) {
1367
+ server.tool(
1368
+ "misp_add_sighting",
1369
+ "Report a sighting of an IOC (confirms it was observed in the wild, marks as false positive, or sets expiration)",
1370
+ {
1371
+ attributeId: z6.string().optional().describe("Attribute ID to sight (use this or value)"),
1372
+ value: z6.string().optional().describe("Attribute value to sight (use this or attributeId)"),
1373
+ type: z6.union([z6.literal(0), z6.literal(1), z6.literal(2)]).describe("0=Sighting (seen in the wild), 1=False positive, 2=Expiration"),
1374
+ source: z6.string().optional().describe("Source of the sighting (e.g., organization name, sensor ID)"),
1375
+ timestamp: z6.string().optional().describe("Timestamp of the sighting (Unix timestamp)")
1376
+ },
1377
+ async (params) => {
1378
+ try {
1379
+ if (!params.attributeId && !params.value) {
1380
+ return {
1381
+ content: [
1382
+ { type: "text", text: "Either attributeId or value must be provided." }
1383
+ ],
1384
+ isError: true
1385
+ };
1386
+ }
1387
+ const sighting = await client.addSighting({
1388
+ attributeId: params.attributeId,
1389
+ value: params.value,
1390
+ type: params.type,
1391
+ source: params.source,
1392
+ timestamp: params.timestamp
1393
+ });
1394
+ const typeLabels = ["Sighting", "False positive", "Expiration"];
1395
+ return {
1396
+ content: [
1397
+ {
1398
+ type: "text",
1399
+ text: JSON.stringify(
1400
+ {
1401
+ id: sighting.id,
1402
+ type: typeLabels[params.type],
1403
+ attribute_id: sighting.attribute_id,
1404
+ event_id: sighting.event_id,
1405
+ source: sighting.source,
1406
+ date_sighting: sighting.date_sighting
1407
+ },
1408
+ null,
1409
+ 2
1410
+ )
1411
+ }
1412
+ ]
1413
+ };
1414
+ } catch (err) {
1415
+ return {
1416
+ content: [
1417
+ { type: "text", text: `Error adding sighting: ${err instanceof Error ? err.message : String(err)}` }
1418
+ ],
1419
+ isError: true
1420
+ };
1421
+ }
1422
+ }
1423
+ );
1424
+ }
1425
+
1426
+ // src/tools/warninglists.ts
1427
+ import { z as z7 } from "zod";
1428
+ function registerWarninglistTools(server, client) {
1429
+ server.tool(
1430
+ "misp_check_warninglists",
1431
+ "Check if an observable value appears on any MISP warninglists (known benign/false positive lists)",
1432
+ {
1433
+ value: z7.string().describe("Value to check against warninglists (IP, domain, hash, etc.)")
1434
+ },
1435
+ async ({ value }) => {
1436
+ try {
1437
+ const results = await client.checkWarninglists(value);
1438
+ const matches = results[value] || [];
1439
+ if (matches.length === 0) {
1440
+ return {
1441
+ content: [
1442
+ {
1443
+ type: "text",
1444
+ text: `"${value}" does not appear on any warninglists. This does not confirm it is malicious, but it is not a known benign indicator.`
1445
+ }
1446
+ ]
1447
+ };
1448
+ }
1449
+ const summary = matches.map((w) => ({
1450
+ name: w.name,
1451
+ category: w.category,
1452
+ description: w.description,
1453
+ type: w.type
1454
+ }));
1455
+ return {
1456
+ content: [
1457
+ {
1458
+ type: "text",
1459
+ text: JSON.stringify(
1460
+ {
1461
+ value,
1462
+ on_warninglists: true,
1463
+ match_count: matches.length,
1464
+ warninglists: summary,
1465
+ note: "This value appears on known benign/false positive lists. Exercise caution before treating it as malicious."
1466
+ },
1467
+ null,
1468
+ 2
1469
+ )
1470
+ }
1471
+ ]
1472
+ };
1473
+ } catch (err) {
1474
+ return {
1475
+ content: [
1476
+ { type: "text", text: `Error checking warninglists: ${err instanceof Error ? err.message : String(err)}` }
1477
+ ],
1478
+ isError: true
1479
+ };
1480
+ }
1481
+ }
1482
+ );
1483
+ }
1484
+
1485
+ // src/tools/objects.ts
1486
+ import { z as z8 } from "zod";
1487
+ function registerObjectTools(server, client) {
1488
+ server.tool(
1489
+ "misp_list_object_templates",
1490
+ "List available MISP object templates (file, domain-ip, email, network-connection, etc.)",
1491
+ {
1492
+ search: z8.string().optional().describe("Filter templates by name"),
1493
+ limit: z8.number().optional().describe("Max results (default 50)")
1494
+ },
1495
+ async ({ search, limit }) => {
1496
+ try {
1497
+ const templates = await client.listObjectTemplates();
1498
+ let filtered = templates;
1499
+ if (search) {
1500
+ const q = search.toLowerCase();
1501
+ filtered = templates.filter(
1502
+ (t) => t.name.toLowerCase().includes(q) || t.description.toLowerCase().includes(q)
1503
+ );
1504
+ }
1505
+ if (limit && limit > 0) {
1506
+ filtered = filtered.slice(0, limit);
1507
+ }
1508
+ if (filtered.length === 0) {
1509
+ return {
1510
+ content: [{ type: "text", text: "No object templates found." }]
1511
+ };
1512
+ }
1513
+ const summary = filtered.map((t) => ({
1514
+ id: t.id,
1515
+ uuid: t.uuid,
1516
+ name: t.name,
1517
+ description: t.description,
1518
+ version: t.version,
1519
+ meta_category: t.meta_category
1520
+ }));
1521
+ return {
1522
+ content: [{ type: "text", text: JSON.stringify(summary, null, 2) }]
1523
+ };
1524
+ } catch (err) {
1525
+ return {
1526
+ content: [
1527
+ {
1528
+ type: "text",
1529
+ text: `Error listing object templates: ${err instanceof Error ? err.message : String(err)}`
1530
+ }
1531
+ ],
1532
+ isError: true
1533
+ };
1534
+ }
1535
+ }
1536
+ );
1537
+ server.tool(
1538
+ "misp_get_object_template",
1539
+ "Get details of a specific MISP object template including required and optional attributes",
1540
+ {
1541
+ templateId: z8.string().describe("Object template ID or UUID")
1542
+ },
1543
+ async ({ templateId }) => {
1544
+ try {
1545
+ const template = await client.getObjectTemplate(templateId);
1546
+ return {
1547
+ content: [{ type: "text", text: JSON.stringify(template, null, 2) }]
1548
+ };
1549
+ } catch (err) {
1550
+ return {
1551
+ content: [
1552
+ {
1553
+ type: "text",
1554
+ text: `Error getting object template: ${err instanceof Error ? err.message : String(err)}`
1555
+ }
1556
+ ],
1557
+ isError: true
1558
+ };
1559
+ }
1560
+ }
1561
+ );
1562
+ server.tool(
1563
+ "misp_add_object",
1564
+ "Add a MISP object (structured group of attributes) to an event",
1565
+ {
1566
+ eventId: z8.string().describe("Event ID to add the object to"),
1567
+ templateName: z8.string().describe(
1568
+ "Object template name (e.g., file, domain-ip, email, network-connection, url)"
1569
+ ),
1570
+ attributes: z8.array(
1571
+ z8.object({
1572
+ object_relation: z8.string().describe(
1573
+ "Attribute relation within the object (e.g., filename, md5, ip, domain)"
1574
+ ),
1575
+ type: z8.string().describe("Attribute type (ip-dst, domain, md5, filename, etc.)"),
1576
+ value: z8.string().describe("Attribute value"),
1577
+ to_ids: z8.boolean().optional().describe("Flag for IDS export"),
1578
+ comment: z8.string().optional().describe("Comment")
1579
+ })
1580
+ ).describe("Attributes to include in the object"),
1581
+ comment: z8.string().optional().describe("Object-level comment"),
1582
+ distribution: z8.number().optional().describe("Distribution level (0-4)")
1583
+ },
1584
+ async ({ eventId, templateName, attributes, comment, distribution }) => {
1585
+ try {
1586
+ const result = await client.addObject(eventId, {
1587
+ name: templateName,
1588
+ attributes,
1589
+ comment,
1590
+ distribution
1591
+ });
1592
+ return {
1593
+ content: [
1594
+ {
1595
+ type: "text",
1596
+ text: JSON.stringify(
1597
+ {
1598
+ id: result.id,
1599
+ name: result.name,
1600
+ event_id: result.event_id,
1601
+ meta_category: result.meta_category,
1602
+ description: result.description,
1603
+ attributes: (result.Attribute || []).map((a) => ({
1604
+ type: a.type,
1605
+ object_relation: a.object_relation,
1606
+ value: a.value
1607
+ }))
1608
+ },
1609
+ null,
1610
+ 2
1611
+ )
1612
+ }
1613
+ ]
1614
+ };
1615
+ } catch (err) {
1616
+ return {
1617
+ content: [
1618
+ {
1619
+ type: "text",
1620
+ text: `Error adding object: ${err instanceof Error ? err.message : String(err)}`
1621
+ }
1622
+ ],
1623
+ isError: true
1624
+ };
1625
+ }
1626
+ }
1627
+ );
1628
+ server.tool(
1629
+ "misp_delete_object",
1630
+ "Delete a MISP object from an event. Destructive: requires confirm:true (or MISP_ALLOW_DESTRUCTIVE=true); hard delete also requires confirmHard:true.",
1631
+ {
1632
+ objectId: z8.string().describe("Object ID to delete"),
1633
+ hard: z8.boolean().optional().describe("Hard delete (permanent) instead of soft delete"),
1634
+ confirm: z8.boolean().optional().describe("Must be true to perform this destructive deletion (unless MISP_ALLOW_DESTRUCTIVE=true)"),
1635
+ confirmHard: z8.boolean().optional().describe("Must be true (in addition to confirm) to perform a permanent hard delete")
1636
+ },
1637
+ async ({ objectId, hard, confirm, confirmHard }) => {
1638
+ try {
1639
+ const guard = requireConfirmation(confirm, `deleting object ${objectId}`);
1640
+ if (guard) return guard;
1641
+ if (hard) {
1642
+ const hardGuard = requireHardConfirmation(
1643
+ confirmHard,
1644
+ `hard-deleting object ${objectId}`
1645
+ );
1646
+ if (hardGuard) return hardGuard;
1647
+ }
1648
+ const result = await client.deleteObject(objectId, hard);
1649
+ return {
1650
+ content: [
1651
+ {
1652
+ type: "text",
1653
+ text: result.message || `Object ${objectId} deleted successfully.`
1654
+ }
1655
+ ]
1656
+ };
1657
+ } catch (err) {
1658
+ return {
1659
+ content: [
1660
+ {
1661
+ type: "text",
1662
+ text: `Error deleting object: ${err instanceof Error ? err.message : String(err)}`
1663
+ }
1664
+ ],
1665
+ isError: true
1666
+ };
1667
+ }
1668
+ }
1669
+ );
1670
+ }
1671
+
1672
+ // src/tools/galaxies.ts
1673
+ import { z as z9 } from "zod";
1674
+ function registerGalaxyTools(server, client) {
1675
+ server.tool(
1676
+ "misp_list_galaxies",
1677
+ "List available MISP galaxies (MITRE ATT&CK, threat actors, malware families, tools, etc.)",
1678
+ {
1679
+ search: z9.string().optional().describe("Filter galaxies by name or type"),
1680
+ namespace: z9.string().optional().describe(
1681
+ "Filter by namespace (e.g., mitre-attack-pattern, mitre-intrusion-set, mitre-malware)"
1682
+ )
1683
+ },
1684
+ async ({ search, namespace }) => {
1685
+ try {
1686
+ const galaxies = await client.listGalaxies();
1687
+ let filtered = galaxies;
1688
+ if (search) {
1689
+ const q = search.toLowerCase();
1690
+ filtered = filtered.filter(
1691
+ (g) => g.name.toLowerCase().includes(q) || g.type.toLowerCase().includes(q) || g.description.toLowerCase().includes(q)
1692
+ );
1693
+ }
1694
+ if (namespace) {
1695
+ const ns = namespace.toLowerCase();
1696
+ filtered = filtered.filter(
1697
+ (g) => g.type.toLowerCase().includes(ns)
1698
+ );
1699
+ }
1700
+ if (filtered.length === 0) {
1701
+ return {
1702
+ content: [{ type: "text", text: "No galaxies found matching the criteria." }]
1703
+ };
1704
+ }
1705
+ const summary = filtered.map((g) => ({
1706
+ id: g.id,
1707
+ name: g.name,
1708
+ type: g.type,
1709
+ description: g.description.length > 150 ? g.description.slice(0, 150) + "..." : g.description
1710
+ }));
1711
+ return {
1712
+ content: [{ type: "text", text: JSON.stringify(summary, null, 2) }]
1713
+ };
1714
+ } catch (err) {
1715
+ return {
1716
+ content: [
1717
+ {
1718
+ type: "text",
1719
+ text: `Error listing galaxies: ${err instanceof Error ? err.message : String(err)}`
1720
+ }
1721
+ ],
1722
+ isError: true
1723
+ };
1724
+ }
1725
+ }
1726
+ );
1727
+ server.tool(
1728
+ "misp_get_galaxy",
1729
+ "Get a specific galaxy with its clusters (e.g., MITRE ATT&CK techniques, threat actor profiles)",
1730
+ {
1731
+ galaxyId: z9.string().describe("Galaxy ID to retrieve")
1732
+ },
1733
+ async ({ galaxyId }) => {
1734
+ try {
1735
+ const galaxy = await client.getGalaxy(galaxyId);
1736
+ const result = {
1737
+ id: galaxy.id,
1738
+ uuid: galaxy.uuid,
1739
+ name: galaxy.name,
1740
+ type: galaxy.type,
1741
+ description: galaxy.description,
1742
+ clusters: (galaxy.GalaxyCluster || []).map((c) => ({
1743
+ id: c.id,
1744
+ value: c.value,
1745
+ description: c.description && c.description.length > 200 ? c.description.slice(0, 200) + "..." : c.description,
1746
+ tag_name: c.tag_name
1747
+ })),
1748
+ cluster_count: (galaxy.GalaxyCluster || []).length
1749
+ };
1750
+ return {
1751
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }]
1752
+ };
1753
+ } catch (err) {
1754
+ return {
1755
+ content: [
1756
+ {
1757
+ type: "text",
1758
+ text: `Error getting galaxy: ${err instanceof Error ? err.message : String(err)}`
1759
+ }
1760
+ ],
1761
+ isError: true
1762
+ };
1763
+ }
1764
+ }
1765
+ );
1766
+ server.tool(
1767
+ "misp_search_galaxy_clusters",
1768
+ "Search galaxy clusters by keyword (find specific MITRE ATT&CK techniques, threat actors, malware, etc.)",
1769
+ {
1770
+ search: z9.string().describe(
1771
+ "Search term (e.g., 'phishing', 'APT28', 'ransomware', 'T1566')"
1772
+ ),
1773
+ galaxyType: z9.string().optional().describe(
1774
+ "Limit to a specific galaxy type (e.g., mitre-attack-pattern, mitre-intrusion-set)"
1775
+ )
1776
+ },
1777
+ async ({ search, galaxyType }) => {
1778
+ try {
1779
+ const results = await client.searchGalaxyClusters(search, galaxyType);
1780
+ if (results.length === 0) {
1781
+ return {
1782
+ content: [
1783
+ {
1784
+ type: "text",
1785
+ text: `No galaxy clusters found matching "${search}".`
1786
+ }
1787
+ ]
1788
+ };
1789
+ }
1790
+ const summary = results.map((c) => ({
1791
+ id: c.id,
1792
+ galaxy_id: c.galaxy_id,
1793
+ value: c.value,
1794
+ description: c.description && c.description.length > 200 ? c.description.slice(0, 200) + "..." : c.description,
1795
+ tag_name: c.tag_name,
1796
+ type: c.type
1797
+ }));
1798
+ return {
1799
+ content: [{ type: "text", text: JSON.stringify(summary, null, 2) }]
1800
+ };
1801
+ } catch (err) {
1802
+ return {
1803
+ content: [
1804
+ {
1805
+ type: "text",
1806
+ text: `Error searching galaxy clusters: ${err instanceof Error ? err.message : String(err)}`
1807
+ }
1808
+ ],
1809
+ isError: true
1810
+ };
1811
+ }
1812
+ }
1813
+ );
1814
+ server.tool(
1815
+ "misp_attach_galaxy_cluster",
1816
+ "Attach a galaxy cluster (MITRE ATT&CK technique, threat actor, etc.) to an event or attribute",
1817
+ {
1818
+ targetType: z9.enum(["event", "attribute"]).describe("Attach to an event or attribute"),
1819
+ targetId: z9.string().describe("Event ID or attribute ID"),
1820
+ galaxyClusterId: z9.string().describe("Galaxy cluster ID to attach")
1821
+ },
1822
+ async ({ targetType, targetId, galaxyClusterId }) => {
1823
+ try {
1824
+ await client.attachGalaxyCluster(targetType, targetId, galaxyClusterId);
1825
+ return {
1826
+ content: [
1827
+ {
1828
+ type: "text",
1829
+ text: `Galaxy cluster ${galaxyClusterId} attached to ${targetType} ${targetId}.`
1830
+ }
1831
+ ]
1832
+ };
1833
+ } catch (err) {
1834
+ return {
1835
+ content: [
1836
+ {
1837
+ type: "text",
1838
+ text: `Error attaching galaxy cluster: ${err instanceof Error ? err.message : String(err)}`
1839
+ }
1840
+ ],
1841
+ isError: true
1842
+ };
1843
+ }
1844
+ }
1845
+ );
1846
+ }
1847
+
1848
+ // src/tools/feeds.ts
1849
+ import { z as z10 } from "zod";
1850
+ function registerFeedTools(server, client) {
1851
+ server.tool(
1852
+ "misp_list_feeds",
1853
+ "List configured MISP feeds (threat intel sources, IOC feeds, etc.)",
1854
+ {
1855
+ enabled: z10.boolean().optional().describe("Filter by enabled/disabled status")
1856
+ },
1857
+ async ({ enabled }) => {
1858
+ try {
1859
+ let feeds = await client.listFeeds();
1860
+ if (enabled !== void 0) {
1861
+ feeds = feeds.filter((f) => f.enabled === enabled);
1862
+ }
1863
+ if (feeds.length === 0) {
1864
+ return {
1865
+ content: [{ type: "text", text: "No feeds found." }]
1866
+ };
1867
+ }
1868
+ const summary = feeds.map((f) => ({
1869
+ id: f.id,
1870
+ name: f.name,
1871
+ provider: f.provider,
1872
+ url: f.url,
1873
+ enabled: f.enabled,
1874
+ source_format: f.source_format,
1875
+ distribution: f.distribution,
1876
+ event_id: f.event_id,
1877
+ caching_enabled: f.caching_enabled
1878
+ }));
1879
+ return {
1880
+ content: [{ type: "text", text: JSON.stringify(summary, null, 2) }]
1881
+ };
1882
+ } catch (err) {
1883
+ return {
1884
+ content: [
1885
+ {
1886
+ type: "text",
1887
+ text: `Error listing feeds: ${err instanceof Error ? err.message : String(err)}`
1888
+ }
1889
+ ],
1890
+ isError: true
1891
+ };
1892
+ }
1893
+ }
1894
+ );
1895
+ server.tool(
1896
+ "misp_toggle_feed",
1897
+ "Enable or disable a MISP feed",
1898
+ {
1899
+ feedId: z10.string().describe("Feed ID"),
1900
+ enable: z10.boolean().describe("true to enable, false to disable")
1901
+ },
1902
+ async ({ feedId, enable }) => {
1903
+ try {
1904
+ await client.toggleFeed(feedId, enable);
1905
+ return {
1906
+ content: [
1907
+ {
1908
+ type: "text",
1909
+ text: `Feed ${feedId} ${enable ? "enabled" : "disabled"} successfully.`
1910
+ }
1911
+ ]
1912
+ };
1913
+ } catch (err) {
1914
+ return {
1915
+ content: [
1916
+ {
1917
+ type: "text",
1918
+ text: `Error toggling feed: ${err instanceof Error ? err.message : String(err)}`
1919
+ }
1920
+ ],
1921
+ isError: true
1922
+ };
1923
+ }
1924
+ }
1925
+ );
1926
+ server.tool(
1927
+ "misp_fetch_feed",
1928
+ "Trigger a fetch/pull of data from a specific MISP feed",
1929
+ {
1930
+ feedId: z10.string().describe("Feed ID to fetch")
1931
+ },
1932
+ async ({ feedId }) => {
1933
+ try {
1934
+ const result = await client.fetchFeed(feedId);
1935
+ return {
1936
+ content: [
1937
+ {
1938
+ type: "text",
1939
+ text: result.message || `Feed ${feedId} fetch initiated.`
1940
+ }
1941
+ ]
1942
+ };
1943
+ } catch (err) {
1944
+ return {
1945
+ content: [
1946
+ {
1947
+ type: "text",
1948
+ text: `Error fetching feed: ${err instanceof Error ? err.message : String(err)}`
1949
+ }
1950
+ ],
1951
+ isError: true
1952
+ };
1953
+ }
1954
+ }
1955
+ );
1956
+ server.tool(
1957
+ "misp_cache_feed",
1958
+ "Cache feed data locally for correlation without creating events",
1959
+ {
1960
+ feedId: z10.string().describe("Feed ID to cache")
1961
+ },
1962
+ async ({ feedId }) => {
1963
+ try {
1964
+ const result = await client.cacheFeed(feedId);
1965
+ return {
1966
+ content: [
1967
+ {
1968
+ type: "text",
1969
+ text: result.message || `Feed ${feedId} cache initiated.`
1970
+ }
1971
+ ]
1972
+ };
1973
+ } catch (err) {
1974
+ return {
1975
+ content: [
1976
+ {
1977
+ type: "text",
1978
+ text: `Error caching feed: ${err instanceof Error ? err.message : String(err)}`
1979
+ }
1980
+ ],
1981
+ isError: true
1982
+ };
1983
+ }
1984
+ }
1985
+ );
1986
+ }
1987
+
1988
+ // src/tools/organisations.ts
1989
+ import { z as z11 } from "zod";
1990
+ function registerOrganisationTools(server, client) {
1991
+ server.tool(
1992
+ "misp_list_organisations",
1993
+ "List MISP organisations (local and remote sharing partners)",
1994
+ {
1995
+ scope: z11.enum(["local", "external", "all"]).optional().describe("Filter by local, external, or all organisations")
1996
+ },
1997
+ async ({ scope }) => {
1998
+ try {
1999
+ const orgs = await client.listOrganisations(scope || "all");
2000
+ if (orgs.length === 0) {
2001
+ return {
2002
+ content: [{ type: "text", text: "No organisations found." }]
2003
+ };
2004
+ }
2005
+ const summary = orgs.map((o) => ({
2006
+ id: o.id,
2007
+ name: o.name,
2008
+ uuid: o.uuid,
2009
+ description: o.description,
2010
+ nationality: o.nationality,
2011
+ sector: o.sector,
2012
+ type: o.type,
2013
+ local: o.local
2014
+ }));
2015
+ return {
2016
+ content: [{ type: "text", text: JSON.stringify(summary, null, 2) }]
2017
+ };
2018
+ } catch (err) {
2019
+ return {
2020
+ content: [
2021
+ {
2022
+ type: "text",
2023
+ text: `Error listing organisations: ${err instanceof Error ? err.message : String(err)}`
2024
+ }
2025
+ ],
2026
+ isError: true
2027
+ };
2028
+ }
2029
+ }
2030
+ );
2031
+ server.tool(
2032
+ "misp_get_organisation",
2033
+ "Get details of a specific MISP organisation",
2034
+ {
2035
+ orgId: z11.string().describe("Organisation ID")
2036
+ },
2037
+ async ({ orgId }) => {
2038
+ try {
2039
+ const org = await client.getOrganisation(orgId);
2040
+ return {
2041
+ content: [{ type: "text", text: JSON.stringify(org, null, 2) }]
2042
+ };
2043
+ } catch (err) {
2044
+ return {
2045
+ content: [
2046
+ {
2047
+ type: "text",
2048
+ text: `Error getting organisation: ${err instanceof Error ? err.message : String(err)}`
2049
+ }
2050
+ ],
2051
+ isError: true
2052
+ };
2053
+ }
2054
+ }
2055
+ );
2056
+ }
2057
+
2058
+ // src/tools/servers.ts
2059
+ import { z as z12 } from "zod";
2060
+ function registerServerTools(server, client) {
2061
+ server.tool(
2062
+ "misp_server_status",
2063
+ "Get MISP server version, status, and diagnostic information",
2064
+ {},
2065
+ async () => {
2066
+ try {
2067
+ const version = await client.getVersion();
2068
+ const settings = await client.getServerSettings();
2069
+ return {
2070
+ content: [
2071
+ {
2072
+ type: "text",
2073
+ text: JSON.stringify(
2074
+ {
2075
+ version: version.version,
2076
+ pymisp_recommended: version.pymisp_recommended_version,
2077
+ permissions: {
2078
+ sync: version.perm_sync,
2079
+ sighting: version.perm_sighting,
2080
+ galaxy_editor: version.perm_galaxy_editor,
2081
+ analyst_data: version.perm_analyst_data
2082
+ },
2083
+ diagnostics: settings.diagnostics
2084
+ },
2085
+ null,
2086
+ 2
2087
+ )
2088
+ }
2089
+ ]
2090
+ };
2091
+ } catch (err) {
2092
+ return {
2093
+ content: [
2094
+ {
2095
+ type: "text",
2096
+ text: `Error getting server status: ${err instanceof Error ? err.message : String(err)}`
2097
+ }
2098
+ ],
2099
+ isError: true
2100
+ };
2101
+ }
2102
+ }
2103
+ );
2104
+ server.tool(
2105
+ "misp_list_sharing_groups",
2106
+ "List MISP sharing groups for controlled event distribution",
2107
+ {},
2108
+ async () => {
2109
+ try {
2110
+ const groups = await client.listSharingGroups();
2111
+ if (groups.length === 0) {
2112
+ return {
2113
+ content: [
2114
+ {
2115
+ type: "text",
2116
+ text: "No sharing groups configured."
2117
+ }
2118
+ ]
2119
+ };
2120
+ }
2121
+ const summary = groups.map((g) => ({
2122
+ id: g.id,
2123
+ name: g.name,
2124
+ description: g.description,
2125
+ uuid: g.uuid,
2126
+ releasability: g.releasability,
2127
+ active: g.active,
2128
+ org_count: g.org_count
2129
+ }));
2130
+ return {
2131
+ content: [{ type: "text", text: JSON.stringify(summary, null, 2) }]
2132
+ };
2133
+ } catch (err) {
2134
+ return {
2135
+ content: [
2136
+ {
2137
+ type: "text",
2138
+ text: `Error listing sharing groups: ${err instanceof Error ? err.message : String(err)}`
2139
+ }
2140
+ ],
2141
+ isError: true
2142
+ };
2143
+ }
2144
+ }
2145
+ );
2146
+ server.tool(
2147
+ "misp_delete_event",
2148
+ "Delete a MISP event (requires appropriate permissions). Destructive: requires confirm:true (or MISP_ALLOW_DESTRUCTIVE=true).",
2149
+ {
2150
+ eventId: z12.string().describe("Event ID to delete"),
2151
+ confirm: z12.boolean().optional().describe("Must be true to perform this destructive deletion (unless MISP_ALLOW_DESTRUCTIVE=true)")
2152
+ },
2153
+ async ({ eventId, confirm }) => {
2154
+ try {
2155
+ const guard = requireConfirmation(confirm, `deleting event ${eventId}`);
2156
+ if (guard) return guard;
2157
+ const result = await client.deleteEvent(eventId);
2158
+ return {
2159
+ content: [
2160
+ {
2161
+ type: "text",
2162
+ text: result.message || `Event ${eventId} deleted.`
2163
+ }
2164
+ ]
2165
+ };
2166
+ } catch (err) {
2167
+ return {
2168
+ content: [
2169
+ {
2170
+ type: "text",
2171
+ text: `Error deleting event: ${err instanceof Error ? err.message : String(err)}`
2172
+ }
2173
+ ],
2174
+ isError: true
2175
+ };
2176
+ }
2177
+ }
2178
+ );
2179
+ }
2180
+
2181
+ // src/resources.ts
2182
+ function registerResources(server, client) {
2183
+ server.resource(
2184
+ "types",
2185
+ "misp://types",
2186
+ {
2187
+ description: "All supported MISP attribute types and categories with their mappings",
2188
+ mimeType: "application/json"
2189
+ },
2190
+ async () => {
2191
+ const types = await client.describeTypes();
2192
+ const summary = {
2193
+ types: types.types,
2194
+ categories: types.categories,
2195
+ category_type_mappings: types.category_type_mappings,
2196
+ type_defaults: Object.entries(types.sane_defaults).map(([type, info]) => ({
2197
+ type,
2198
+ default_category: info.default_category,
2199
+ to_ids: info.to_ids === 1
2200
+ }))
2201
+ };
2202
+ return {
2203
+ contents: [
2204
+ {
2205
+ uri: "misp://types",
2206
+ mimeType: "application/json",
2207
+ text: JSON.stringify(summary, null, 2)
2208
+ }
2209
+ ]
2210
+ };
2211
+ }
2212
+ );
2213
+ server.resource(
2214
+ "statistics",
2215
+ "misp://statistics",
2216
+ {
2217
+ description: "MISP instance capability summary (supported attribute types and categories). Use misp_search_events for actual counts.",
2218
+ mimeType: "application/json"
2219
+ },
2220
+ async () => {
2221
+ const types = await client.describeTypes();
2222
+ const stats = {
2223
+ available_types: types.types.length,
2224
+ available_categories: types.categories.length,
2225
+ note: "This resource reports capability metadata, not event totals. Use misp_search_events with date/tag filters to count events."
2226
+ };
2227
+ return {
2228
+ contents: [
2229
+ {
2230
+ uri: "misp://statistics",
2231
+ mimeType: "application/json",
2232
+ text: JSON.stringify(stats, null, 2)
2233
+ }
2234
+ ]
2235
+ };
2236
+ }
2237
+ );
2238
+ server.resource(
2239
+ "taxonomies",
2240
+ "misp://taxonomies",
2241
+ {
2242
+ description: "Available MISP taxonomies (TLP, MITRE ATT&CK, etc.)",
2243
+ mimeType: "application/json"
2244
+ },
2245
+ async () => {
2246
+ const taxonomies = await client.listTaxonomies();
2247
+ const summary = taxonomies.map((t) => ({
2248
+ namespace: t.namespace,
2249
+ description: t.description,
2250
+ version: t.version,
2251
+ enabled: t.enabled
2252
+ }));
2253
+ return {
2254
+ contents: [
2255
+ {
2256
+ uri: "misp://taxonomies",
2257
+ mimeType: "application/json",
2258
+ text: JSON.stringify(summary, null, 2)
2259
+ }
2260
+ ]
2261
+ };
2262
+ }
2263
+ );
2264
+ }
2265
+
2266
+ // src/prompts.ts
2267
+ import { z as z13 } from "zod";
2268
+ function registerPrompts(server) {
2269
+ server.prompt(
2270
+ "investigate-ioc",
2271
+ "Deep investigation of an IOC across MISP - searches for the indicator, finds correlations, checks warninglists, and summarizes threat context",
2272
+ {
2273
+ ioc: z13.string().describe("The IOC value to investigate (IP, domain, hash, URL, email, etc.)"),
2274
+ iocType: z13.string().optional().describe("IOC type hint (ip-src, domain, md5, sha256, url, etc.)")
2275
+ },
2276
+ ({ ioc, iocType }) => {
2277
+ const typeHint = iocType ? `The IOC type is "${iocType}".` : "Determine the IOC type from the value format.";
2278
+ return {
2279
+ messages: [
2280
+ {
2281
+ role: "user",
2282
+ content: {
2283
+ type: "text",
2284
+ text: `Investigate the following IOC in MISP: "${ioc}"
2285
+
2286
+ ${typeHint}
2287
+
2288
+ Follow these steps:
2289
+ 1. Use misp_search_attributes to search for this IOC value across all events. If you know the type, filter by it.
2290
+ 2. Use misp_correlate to find all correlations for this value across events.
2291
+ 3. Use misp_check_warninglists to check if this value appears on any known benign/false positive lists.
2292
+ 4. For each event found, note the threat level, tags (especially TLP and MITRE ATT&CK), and related IOCs.
2293
+ 5. If the IOC appears in multiple events, use misp_get_related_events on the most relevant event to discover additional related intelligence.
2294
+
2295
+ Provide a structured summary including:
2296
+ - Whether the IOC was found in MISP and in how many events
2297
+ - Threat level assessment based on event metadata
2298
+ - Related IOCs and correlations discovered
2299
+ - Whether it appears on any warninglists (potential false positive)
2300
+ - MITRE ATT&CK techniques associated with this IOC
2301
+ - Recommended next steps for the analyst`
2302
+ }
2303
+ }
2304
+ ]
2305
+ };
2306
+ }
2307
+ );
2308
+ server.prompt(
2309
+ "create-incident-event",
2310
+ "Guided workflow for creating a MISP event from an incident, including adding attributes, tagging, and publishing",
2311
+ {
2312
+ description: z13.string().describe("Description of the incident"),
2313
+ iocs: z13.string().optional().describe("Comma-separated list of IOCs to add (e.g., '192.168.1.1,evil.com,abc123hash')")
2314
+ },
2315
+ ({ description, iocs }) => {
2316
+ const iocList = iocs ? `
2317
+ The following IOCs should be added: ${iocs}` : "\nAsk the analyst for any IOCs (IP addresses, domains, file hashes, URLs) associated with this incident.";
2318
+ return {
2319
+ messages: [
2320
+ {
2321
+ role: "user",
2322
+ content: {
2323
+ type: "text",
2324
+ text: `Create a MISP event for the following incident:
2325
+
2326
+ "${description}"
2327
+ ${iocList}
2328
+
2329
+ Follow these steps:
2330
+ 1. Use misp_create_event with:
2331
+ - An informative title based on the incident description
2332
+ - Appropriate threat level (1=High for active compromise, 2=Medium for suspicious activity, 3=Low for informational)
2333
+ - Analysis status: 0 (Initial)
2334
+ - Distribution: 0 (Organization only) to start - can be broadened later
2335
+
2336
+ 2. For each IOC:
2337
+ - Determine the correct attribute type (ip-src, ip-dst, domain, md5, sha256, url, etc.)
2338
+ - Use misp_add_attribute (or misp_add_attributes_bulk for multiple) to add them
2339
+ - Use misp_check_warninglists to verify none are known false positives
2340
+
2341
+ 3. Add appropriate tags using misp_tag_event:
2342
+ - TLP tag (tlp:white, tlp:green, tlp:amber, tlp:red)
2343
+ - Relevant MITRE ATT&CK technique tags if applicable
2344
+ - Any organization-specific tags
2345
+
2346
+ 4. Summarize what was created:
2347
+ - Event ID and title
2348
+ - Number of attributes added
2349
+ - Tags applied
2350
+ - Ask if the analyst wants to publish (misp_publish_event) or keep as draft`
2351
+ }
2352
+ }
2353
+ ]
2354
+ };
2355
+ }
2356
+ );
2357
+ server.prompt(
2358
+ "threat-report",
2359
+ "Generate a threat intelligence report from MISP data by aggregating events, extracting IOC patterns, and summarizing the threat landscape",
2360
+ {
2361
+ eventId: z13.string().optional().describe("Specific event ID to report on"),
2362
+ tag: z13.string().optional().describe("Filter by tag (e.g., mitre-attack:T1059, tlp:amber)"),
2363
+ dateRange: z13.string().optional().describe("Date range or relative time (e.g., '7d', '30d', '2024-01-01 to 2024-01-31')")
2364
+ },
2365
+ ({ eventId, tag, dateRange }) => {
2366
+ let scopeInstructions;
2367
+ if (eventId) {
2368
+ scopeInstructions = `Focus on event ID ${eventId}. Use misp_get_event to get full details, then misp_get_related_events for context.`;
2369
+ } else if (tag) {
2370
+ scopeInstructions = `Focus on events tagged with "${tag}". Use misp_search_by_tag to find matching events.`;
2371
+ } else if (dateRange) {
2372
+ const isRelative = /^\d+[dmhwy]$/.test(dateRange);
2373
+ if (isRelative) {
2374
+ scopeInstructions = `Focus on events from the last ${dateRange}. Use misp_search_events with last="${dateRange}".`;
2375
+ } else {
2376
+ scopeInstructions = `Focus on events in the date range: ${dateRange}. Use misp_search_events with appropriate dateFrom/dateTo.`;
2377
+ }
2378
+ } else {
2379
+ scopeInstructions = `Generate a report on recent threat activity. Use misp_search_events with last="7d" to get the latest events.`;
2380
+ }
2381
+ return {
2382
+ messages: [
2383
+ {
2384
+ role: "user",
2385
+ content: {
2386
+ type: "text",
2387
+ text: `Generate a threat intelligence report from MISP data.
2388
+
2389
+ ${scopeInstructions}
2390
+
2391
+ Report structure:
2392
+ 1. **Executive Summary**: Brief overview of the threat landscape for the specified scope
2393
+ 2. **Key Events**: List the most significant events with threat levels and descriptions
2394
+ 3. **IOC Summary**:
2395
+ - Use misp_search_attributes to aggregate IOC types and counts
2396
+ - List the most significant indicators by type (IPs, domains, hashes, URLs)
2397
+ 4. **MITRE ATT&CK Coverage**: List any ATT&CK techniques observed across the events
2398
+ 5. **Correlations**: Use misp_correlate on high-value IOCs to discover cross-event links
2399
+ 6. **Recommendations**:
2400
+ - Immediate blocking actions (IPs, domains to block)
2401
+ - Detection rules needed
2402
+ - Areas requiring further investigation
2403
+
2404
+ Format the report in clear markdown with headers and tables where appropriate.`
2405
+ }
2406
+ }
2407
+ ]
2408
+ };
2409
+ }
2410
+ );
2411
+ }
2412
+
2413
+ // src/mcp-server.ts
2414
+ var packageJson = JSON.parse(
2415
+ readFileSync(new URL("../package.json", import.meta.url), "utf8")
2416
+ );
2417
+ function createMispMcpServer(deps = {}) {
2418
+ const config = deps.config ?? getConfig();
2419
+ const client = deps.client ?? new MispClient(config);
2420
+ const server = new McpServer({
2421
+ name: "misp-mcp",
2422
+ version: packageJson.version ?? "0.0.0",
2423
+ description: "MCP server for MISP threat intelligence platform - IOC lookups, event management, correlation discovery, and intelligence enrichment"
2424
+ });
2425
+ registerEventTools(server, client);
2426
+ registerAttributeTools(server, client);
2427
+ registerCorrelationTools(server, client);
2428
+ registerTagTools(server, client);
2429
+ registerExportTools(server, client);
2430
+ registerSightingTools(server, client);
2431
+ registerWarninglistTools(server, client);
2432
+ registerObjectTools(server, client);
2433
+ registerGalaxyTools(server, client);
2434
+ registerFeedTools(server, client);
2435
+ registerOrganisationTools(server, client);
2436
+ registerServerTools(server, client);
2437
+ registerResources(server, client);
2438
+ registerPrompts(server);
2439
+ return server;
2440
+ }
2441
+ function stripSchemaFromToolList(transport) {
2442
+ const send = transport.send.bind(transport);
2443
+ transport.send = (message) => {
2444
+ const tools = message?.result?.tools;
2445
+ if (Array.isArray(tools)) {
2446
+ for (const tool of tools) {
2447
+ if (tool?.inputSchema) delete tool.inputSchema.$schema;
2448
+ if (tool?.outputSchema) delete tool.outputSchema.$schema;
2449
+ }
2450
+ }
2451
+ return send(message);
2452
+ };
2453
+ }
2454
+ async function serveMcp() {
2455
+ const config = getConfig();
2456
+ const server = createMispMcpServer({ config });
2457
+ const transport = new StdioServerTransport();
2458
+ stripSchemaFromToolList(transport);
2459
+ await server.connect(transport);
2460
+ }
2461
+
2462
+ export {
2463
+ getConfig,
2464
+ MispClient,
2465
+ createMispMcpServer,
2466
+ serveMcp
2467
+ };
2468
+ //# sourceMappingURL=chunk-X4LNYJKC.js.map