Skip to main content

prometheus_mcp/mcp/
tools.rs

1use crate::mcp::metrics;
2use crate::mcp::repository::get_repository;
3use crate::mcp::types::*;
4use maplit::hashmap;
5use rpc_router::{Handler, HandlerResult, RouterBuilder, RpcParams};
6use serde::{Deserialize, Serialize};
7
8/// register all tools to the router
9pub fn register_tools(router_builder: RouterBuilder) -> RouterBuilder {
10    router_builder
11        .append_dyn("tools/list", tools_list.into_dyn())
12        .append_dyn("prometheus_query", prometheus_query.into_dyn())
13        .append_dyn("prometheus_query_range", prometheus_query_range.into_dyn())
14        .append_dyn(
15            "prometheus_list_metrics",
16            prometheus_list_metrics.into_dyn(),
17        )
18        .append_dyn(
19            "prometheus_get_metadata",
20            prometheus_get_metadata.into_dyn(),
21        )
22        .append_dyn("prometheus_get_series", prometheus_get_series.into_dyn())
23        .append_dyn(
24            "prometheus_get_label_values",
25            prometheus_get_label_values.into_dyn(),
26        )
27}
28
29pub async fn tools_list(_request: Option<ListToolsRequest>) -> HandlerResult<ListToolsResult> {
30    // Build schemas with additionalProperties=false. Also mirror input_schema to `parameters` for compatibility.
31    let query_schema = ToolInputSchema {
32        type_name: "object".to_string(),
33        properties: hashmap! {
34            "query".to_string() => ToolInputSchemaProperty {
35                type_name: Some("string".to_owned()),
36                description: Some("Prometheus query string".to_owned()),
37                enum_values: None,
38                items: None,
39                min_items: None,
40            },
41            "time".to_string() => ToolInputSchemaProperty {
42                type_name: Some("string".to_owned()),
43                description: Some("Evaluation timestamp (RFC3339 or Unix timestamp)".to_owned()),
44                enum_values: None,
45                items: None,
46                min_items: None,
47            }
48        },
49        required: vec!["query".to_string()],
50        additional_properties: Some(false),
51    };
52
53    let range_schema = ToolInputSchema {
54        type_name: "object".to_string(),
55        properties: hashmap! {
56            "query".to_string() => ToolInputSchemaProperty {
57                type_name: Some("string".to_owned()),
58                description: Some("Prometheus query string".to_owned()),
59                enum_values: None,
60                items: None,
61                min_items: None,
62            },
63            "start".to_string() => ToolInputSchemaProperty {
64                type_name: Some("string".to_owned()),
65                description: Some("Start timestamp (RFC3339 or Unix timestamp)".to_owned()),
66                enum_values: None,
67                items: None,
68                min_items: None,
69            },
70            "end".to_string() => ToolInputSchemaProperty {
71                type_name: Some("string".to_owned()),
72                description: Some("End timestamp (RFC3339 or Unix timestamp)".to_owned()),
73                enum_values: None,
74                items: None,
75                min_items: None,
76            },
77            "step".to_string() => ToolInputSchemaProperty {
78                type_name: Some("string".to_owned()),
79                description: Some("Query resolution step width (e.g. 30s, 1m, 1h)".to_owned()),
80                enum_values: None,
81                items: None,
82                min_items: None,
83            }
84        },
85        required: vec![
86            "query".to_string(),
87            "start".to_string(),
88            "end".to_string(),
89            "step".to_string(),
90        ],
91        additional_properties: Some(false),
92    };
93
94    let list_metrics_schema = ToolInputSchema {
95        type_name: "object".to_string(),
96        properties: hashmap! {},
97        required: vec![],
98        additional_properties: Some(false),
99    };
100
101    let metadata_schema = ToolInputSchema {
102        type_name: "object".to_string(),
103        properties: hashmap! {
104            "metric".to_string() => ToolInputSchemaProperty {
105                type_name: Some("string".to_owned()),
106                description: Some("Metric name".to_owned()),
107                enum_values: None,
108                items: None,
109                min_items: None,
110            }
111        },
112        required: vec!["metric".to_string()],
113        additional_properties: Some(false),
114    };
115
116    let series_schema = ToolInputSchema {
117        type_name: "object".to_string(),
118        properties: hashmap! {
119            "match_strings".to_string() => ToolInputSchemaProperty {
120                type_name: Some("array".to_owned()),
121                description: Some("Array of Prometheus series selectors (e.g. ['up', 'node_cpu_seconds_total{mode=\"idle\"}'])".to_owned()),
122                enum_values: None,
123                items: Some(Box::new(ToolInputSchemaProperty {
124                    type_name: Some("string".to_owned()),
125                    enum_values: None,
126                    description: None,
127                    items: None,
128                    min_items: None,
129                })),
130                min_items: Some(1),
131            }
132        },
133        required: vec!["match_strings".to_string()],
134        additional_properties: Some(false),
135    };
136
137    let label_values_schema = ToolInputSchema {
138        type_name: "object".to_string(),
139        properties: hashmap! {
140            "label_name".to_string() => ToolInputSchemaProperty {
141                type_name: Some("string".to_owned()),
142                description: Some("Label name".to_owned()),
143                enum_values: None,
144                items: None,
145                min_items: None,
146            }
147        },
148        required: vec!["label_name".to_string()],
149        additional_properties: Some(false),
150    };
151
152    let response = ListToolsResult {
153        tools: vec![
154            Tool {
155                name: "prometheus_query".to_string(),
156                description: Some("Execute a Prometheus instant query".to_string()),
157                parameters: Some(query_schema.clone()),
158                input_schema: query_schema,
159            },
160            Tool {
161                name: "prometheus_query_range".to_string(),
162                description: Some("Execute a Prometheus range query".to_string()),
163                parameters: Some(range_schema.clone()),
164                input_schema: range_schema,
165            },
166            Tool {
167                name: "prometheus_list_metrics".to_string(),
168                description: Some(
169                    "List all metric names that can be queried from Prometheus".to_string(),
170                ),
171                parameters: Some(list_metrics_schema.clone()),
172                input_schema: list_metrics_schema,
173            },
174            Tool {
175                name: "prometheus_get_metadata".to_string(),
176                description: Some("Get metadata about a specific metric".to_string()),
177                parameters: Some(metadata_schema.clone()),
178                input_schema: metadata_schema,
179            },
180            Tool {
181                name: "prometheus_get_series".to_string(),
182                description: Some(
183                    "Get time series data for a specific metric with optional label matchers"
184                        .to_string(),
185                ),
186                parameters: Some(series_schema.clone()),
187                input_schema: series_schema,
188            },
189            Tool {
190                name: "prometheus_get_label_values".to_string(),
191                description: Some("Get all label values for a specific label name".to_string()),
192                parameters: Some(label_values_schema.clone()),
193                input_schema: label_values_schema,
194            },
195        ],
196        next_cursor: None,
197    };
198    Ok(response)
199}
200
201#[derive(Deserialize, Serialize, RpcParams)]
202pub struct PrometheusQueryRequest {
203    pub query: String,
204    pub time: Option<String>,
205}
206
207pub async fn prometheus_query(request: PrometheusQueryRequest) -> HandlerResult<CallToolResult> {
208    metrics::record_tool_call("prometheus_query");
209
210    let repo = get_repository();
211    match repo.query(&request.query, request.time.as_deref()).await {
212        Ok(result) => {
213            let result_json =
214                serde_json::to_string_pretty(&result).unwrap_or_else(|_| "{}".to_string());
215            Ok(CallToolResult {
216                content: vec![CallToolResultContent::Text { text: result_json }],
217                is_error: false,
218            })
219        }
220        Err(err) => Ok(CallToolResult {
221            content: vec![CallToolResultContent::Text {
222                text: err_string(&err),
223            }],
224            is_error: true,
225        }),
226    }
227}
228
229#[derive(Deserialize, Serialize, RpcParams)]
230pub struct PrometheusQueryRangeRequest {
231    pub query: String,
232    pub start: String,
233    pub end: String,
234    pub step: String,
235}
236
237pub async fn prometheus_query_range(
238    request: PrometheusQueryRangeRequest,
239) -> HandlerResult<CallToolResult> {
240    metrics::record_tool_call("prometheus_query_range");
241
242    let repo = get_repository();
243    match repo
244        .query_range(&request.query, &request.start, &request.end, &request.step)
245        .await
246    {
247        Ok(result) => {
248            let result_json =
249                serde_json::to_string_pretty(&result).unwrap_or_else(|_| "{}".to_string());
250            Ok(CallToolResult {
251                content: vec![CallToolResultContent::Text { text: result_json }],
252                is_error: false,
253            })
254        }
255        Err(err) => Ok(CallToolResult {
256            content: vec![CallToolResultContent::Text {
257                text: err_string(&err),
258            }],
259            is_error: true,
260        }),
261    }
262}
263
264#[derive(Deserialize, Serialize, RpcParams)]
265pub struct PrometheusListMetricsRequest {}
266
267pub async fn prometheus_list_metrics(
268    _request: PrometheusListMetricsRequest,
269) -> HandlerResult<CallToolResult> {
270    metrics::record_tool_call("prometheus_list_metrics");
271
272    let repo = get_repository();
273    match repo.list_metrics().await {
274        Ok(metrics) => {
275            let result_json =
276                serde_json::to_string_pretty(&metrics).unwrap_or_else(|_| "[]".to_string());
277            Ok(CallToolResult {
278                content: vec![CallToolResultContent::Text { text: result_json }],
279                is_error: false,
280            })
281        }
282        Err(err) => Ok(CallToolResult {
283            content: vec![CallToolResultContent::Text {
284                text: err_string(&err),
285            }],
286            is_error: true,
287        }),
288    }
289}
290
291#[derive(Deserialize, Serialize, RpcParams)]
292pub struct PrometheusGetMetadataRequest {
293    pub metric: String,
294}
295
296pub async fn prometheus_get_metadata(
297    request: PrometheusGetMetadataRequest,
298) -> HandlerResult<CallToolResult> {
299    metrics::record_tool_call("prometheus_get_metadata");
300
301    let repo = get_repository();
302    match repo.get_metadata(&request.metric).await {
303        Ok(metadata) => {
304            let result_json =
305                serde_json::to_string_pretty(&metadata).unwrap_or_else(|_| "[]".to_string());
306            Ok(CallToolResult {
307                content: vec![CallToolResultContent::Text { text: result_json }],
308                is_error: false,
309            })
310        }
311        Err(err) => Ok(CallToolResult {
312            content: vec![CallToolResultContent::Text {
313                text: err_string(&err),
314            }],
315            is_error: true,
316        }),
317    }
318}
319
320#[derive(Deserialize, Serialize, RpcParams)]
321pub struct PrometheusGetSeriesRequest {
322    pub match_strings: Vec<String>,
323}
324
325pub async fn prometheus_get_series(
326    request: PrometheusGetSeriesRequest,
327) -> HandlerResult<CallToolResult> {
328    metrics::record_tool_call("prometheus_get_series");
329
330    let repo = get_repository();
331
332    // Convert Vec<String> to Vec<&str>
333    let match_strings: Vec<&str> = request.match_strings.iter().map(|s| s.as_str()).collect();
334
335    match repo.get_series(match_strings).await {
336        Ok(series) => {
337            let result_json =
338                serde_json::to_string_pretty(&series).unwrap_or_else(|_| "[]".to_string());
339            Ok(CallToolResult {
340                content: vec![CallToolResultContent::Text { text: result_json }],
341                is_error: false,
342            })
343        }
344        Err(err) => Ok(CallToolResult {
345            content: vec![CallToolResultContent::Text {
346                text: err_string(&err),
347            }],
348            is_error: true,
349        }),
350    }
351}
352
353#[derive(Deserialize, Serialize, RpcParams)]
354pub struct PrometheusGetLabelValuesRequest {
355    pub label_name: String,
356}
357
358pub async fn prometheus_get_label_values(
359    request: PrometheusGetLabelValuesRequest,
360) -> HandlerResult<CallToolResult> {
361    metrics::record_tool_call("prometheus_get_label_values");
362
363    let repo = get_repository();
364    match repo.get_label_values(&request.label_name).await {
365        Ok(values) => {
366            let result_json =
367                serde_json::to_string_pretty(&values).unwrap_or_else(|_| "[]".to_string());
368            Ok(CallToolResult {
369                content: vec![CallToolResultContent::Text { text: result_json }],
370                is_error: false,
371            })
372        }
373        Err(err) => Ok(CallToolResult {
374            content: vec![CallToolResultContent::Text {
375                text: err_string(&err),
376            }],
377            is_error: true,
378        }),
379    }
380}
381
382fn err_string(err: &dyn std::fmt::Debug) -> String {
383    format!("{:?}", err)
384}