1use super::config::McpConfig;
2use super::flight::{FlightBackend, describe_error};
3use super::provider::{CallContext, ToolProvider, error_result, input_schema, text_result};
4use super::read_only::check_read_only;
5use super::render::{RenderLimits, render_stream};
6use arrow::array::{Array, RecordBatch};
7use arrow::util::display::array_value_to_string;
8use async_trait::async_trait;
9use chrono::{DateTime, Duration, Utc};
10use futures::StreamExt;
11use micromegas_telemetry::time_range::TimeRange;
12use rmcp::model::{CallToolResult, JsonObject, Tool, ToolAnnotations};
13use serde::Deserialize;
14use std::sync::Arc;
15
16const QUERY_RULES: &str = "Rules: always pass begin (and end) to bound the time range, never filter \
17on time in the WHERE clause instead; always add a LIMIT unless the query is a small aggregate; \
18use view_instance() for single-process or single-stream queries; read describe_view for the \
19view's own rules before querying it. Only read-only SELECT queries are accepted.";
20
21const MAX_VIEW_NAME_LEN: usize = 128;
22
23#[derive(Debug, Deserialize)]
24struct QueryArgs {
25 sql: String,
26 begin: Option<String>,
27 end: Option<String>,
28 limit: Option<usize>,
29}
30
31#[derive(Debug, Deserialize)]
32struct DescribeViewArgs {
33 name: String,
34}
35
36pub fn parse_time(value: &str, now: DateTime<Utc>) -> Result<DateTime<Utc>, String> {
38 let value = value.trim();
39 if let Ok(t) = DateTime::parse_from_rfc3339(value) {
40 return Ok(t.with_timezone(&Utc));
41 }
42 let relative = value.char_indices().last().and_then(|(i, unit)| {
43 let n: i64 = value[..i].parse().ok()?;
44 let delta = match unit {
45 's' => Duration::try_seconds(n)?,
46 'm' => Duration::try_minutes(n)?,
47 'h' => Duration::try_hours(n)?,
48 'd' => Duration::try_days(n)?,
49 'w' => Duration::try_weeks(n)?,
50 _ => return None,
51 };
52 now.checked_sub_signed(delta)
53 });
54 relative.ok_or_else(|| {
55 format!("invalid time '{value}': use an RFC 3339 timestamp or a relative age like 1h, 7d")
56 })
57}
58
59pub fn parse_range(
61 begin: Option<&str>,
62 end: Option<&str>,
63 now: DateTime<Utc>,
64) -> Result<Option<TimeRange>, String> {
65 match (begin, end) {
66 (None, None) => Ok(None),
67 (None, Some(_)) => Err("end requires begin".to_string()),
68 (Some(begin), end) => {
69 let begin = parse_time(begin, now)?;
70 let end = match end {
71 Some(end) => parse_time(end, now)?,
72 None => now,
73 };
74 if begin > end {
75 return Err("begin must not be after end".to_string());
76 }
77 Ok(Some(TimeRange::new(begin, end)))
78 }
79 }
80}
81
82pub struct QueryToolProvider {
84 backend: Arc<dyn FlightBackend>,
85 config: McpConfig,
86}
87
88impl QueryToolProvider {
89 pub fn new(backend: Arc<dyn FlightBackend>, config: McpConfig) -> Self {
90 Self { backend, config }
91 }
92
93 fn query_properties() -> serde_json::Value {
94 serde_json::json!({
95 "sql": {"type": "string", "description": "A single read-only SELECT query."},
96 "begin": {"type": "string", "description": "Start of the time range: RFC 3339 or a relative age such as 1h or 7d."},
97 "end": {"type": "string", "description": "End of the time range (defaults to now when begin is set)."},
98 "limit": {"type": "integer", "minimum": 1, "description": "Maximum rows to return."}
99 })
100 }
101
102 async fn prepare_query(&self, ctx: &CallContext, args: JsonObject) -> CallToolResult {
103 let (args, range) = match self.parse_query_args(args) {
104 Ok(v) => v,
105 Err(e) => return error_result(e),
106 };
107 let estimate = match self.backend.prepare(ctx, &args.sql, range).await {
108 Ok(estimate) => estimate,
109 Err(e) => return error_result(describe_error(&e)),
110 };
111 let mut out = String::from("schema:\n");
112 for field in estimate.schema.fields() {
113 out.push_str(&format!("- {}: {}\n", field.name(), field.data_type()));
114 }
115 match estimate.total_bytes {
116 Some(bytes) => out.push_str(&format!("estimated_scan_bytes: {bytes}\n")),
117 None => out.push_str("estimated_scan_bytes: unknown\n"),
118 }
119 out.push_str(&format!(
120 "estimate_precision: {}\n",
121 estimate.estimate_precision.as_deref().unwrap_or("unknown")
122 ));
123 out.push_str(&format!(
124 "within_scan_cap: {}\n",
125 match estimate.within_scan_cap {
126 Some(true) => "true",
127 Some(false) => "false",
128 None => "unknown",
129 }
130 ));
131 if estimate.within_scan_cap == Some(false) {
132 out.push_str(
133 "hint: the estimated scan exceeds the cap; narrow begin/end or filter on the \
134 view's sort columns (see describe_view).\n",
135 );
136 } else if estimate.estimate_precision.as_deref() == Some("opaque") && range.is_none() {
137 out.push_str(
138 "hint: the scan cannot be estimated without a time range; pass begin/end or \
139 filter on the view's sort columns.\n",
140 );
141 }
142 text_result(out)
143 }
144
145 async fn execute_query(&self, ctx: &CallContext, args: JsonObject) -> CallToolResult {
146 let (args, range) = match self.parse_query_args(args) {
147 Ok(v) => v,
148 Err(e) => return error_result(e),
149 };
150 let limit = self.config.effective_limit(args.limit);
151 let stream = match self.backend.execute(ctx, &args.sql, range, limit + 1).await {
153 Ok(stream) => stream,
154 Err(e) => return error_result(describe_error(&e)),
155 };
156 let limits = RenderLimits {
157 max_rows: limit,
158 max_bytes: self.config.max_bytes,
159 };
160 match render_stream(stream, limits).await {
161 Ok(rendered) => text_result(rendered.text),
162 Err(e) => error_result(describe_error(&e)),
163 }
164 }
165
166 fn parse_query_args(&self, args: JsonObject) -> Result<(QueryArgs, Option<TimeRange>), String> {
167 let args: QueryArgs = serde_json::from_value(serde_json::Value::Object(args))
168 .map_err(|e| format!("invalid arguments: {e}"))?;
169 check_read_only(&args.sql)?;
170 let range = parse_range(args.begin.as_deref(), args.end.as_deref(), Utc::now())?;
171 Ok((args, range))
172 }
173
174 async fn fetch_rows(
175 &self,
176 ctx: &CallContext,
177 sql: &str,
178 limit: usize,
179 ) -> anyhow::Result<Vec<Vec<Option<String>>>> {
180 let mut stream = self.backend.execute(ctx, sql, None, limit).await?;
181 let mut rows = vec![];
182 while let Some(batch) = stream.next().await {
183 let batch: RecordBatch = batch?;
184 for row in 0..batch.num_rows() {
185 let mut cells = vec![];
186 for column in batch.columns() {
187 cells.push(if column.is_null(row) {
188 None
189 } else {
190 Some(array_value_to_string(column, row)?)
191 });
192 }
193 rows.push(cells);
194 }
195 }
196 Ok(rows)
197 }
198
199 async fn list_views(&self, ctx: &CallContext) -> CallToolResult {
200 let sql = "SELECT view_set_name, description FROM list_view_sets() \
201 ORDER BY view_set_name LIMIT 1000";
202 match self.fetch_rows(ctx, sql, 1000).await {
203 Ok(rows) => {
204 let mut out = String::new();
205 for row in rows {
206 let name = row.first().cloned().flatten().unwrap_or_default();
207 let summary = row
208 .get(1)
209 .cloned()
210 .flatten()
211 .and_then(|d| d.lines().find(|l| !l.trim().is_empty()).map(str::to_string))
212 .unwrap_or_default();
213 out.push_str(&format!("- {name}: {summary}\n"));
214 }
215 text_result(out)
216 }
217 Err(e) => error_result(describe_error(&e)),
218 }
219 }
220
221 async fn describe_view(&self, ctx: &CallContext, args: JsonObject) -> CallToolResult {
222 let args: DescribeViewArgs = match serde_json::from_value(serde_json::Value::Object(args)) {
223 Ok(a) => a,
224 Err(e) => return error_result(format!("invalid arguments: {e}")),
225 };
226 let name = args.name.trim();
227 if name.is_empty()
228 || name.len() > MAX_VIEW_NAME_LEN
229 || !name
230 .chars()
231 .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))
232 {
233 return error_result("invalid view name");
234 }
235 let sql = format!(
236 "SELECT view_set_name, description, columns, sort_order, has_view_maker, \
237 global_instance_available FROM list_view_sets() WHERE view_set_name = '{name}' LIMIT 1"
238 );
239 let rows = match self.fetch_rows(ctx, &sql, 1).await {
240 Ok(rows) => rows,
241 Err(e) => return error_result(describe_error(&e)),
242 };
243 let Some(row) = rows.first() else {
244 return error_result(format!("no view named '{name}'; use list_views"));
245 };
246 let cell = |i: usize| row.get(i).cloned().flatten();
247 let mut out = format!("# {name}\n\n");
248 out.push_str(&cell(1).unwrap_or_else(|| "(no description)".to_string()));
249 out.push_str("\n\n## columns\n");
250 out.push_str(&cell(2).unwrap_or_default());
251 out.push_str("\n\n## sort order\n");
252 out.push_str(&cell(3).unwrap_or_else(|| "unordered".to_string()));
253 out.push_str(&format!(
254 "\n\nglobal_view_available: {}\nview_instance_available: {}\n",
255 cell(5).as_deref().unwrap_or("false"),
256 cell(4).as_deref().unwrap_or("false"),
257 ));
258 if cell(5).as_deref() == Some("false") {
259 out.push_str("There is no global view: query it with view_instance().\n");
260 }
261 text_result(out)
262 }
263}
264
265#[async_trait]
266impl ToolProvider for QueryToolProvider {
267 fn tools(&self, _ctx: &CallContext) -> Vec<Tool> {
268 let read_only = || ToolAnnotations::new().read_only(true).open_world(false);
269 let prepare_desc = format!(
270 "Plan a query without running it: returns the result schema and, when the server \
271 reports one, the estimated scan size and whether it is within the scan cap. \
272 {QUERY_RULES}"
273 );
274 let execute_desc = format!(
275 "Run a read-only query and return a markdown table, cut at the row and byte caps. \
276 Takes the same arguments as prepare_query; re-send the full query. {QUERY_RULES}"
277 );
278 vec![
279 Tool::new(
280 "prepare_query",
281 prepare_desc,
282 input_schema(Self::query_properties(), &["sql"]),
283 )
284 .with_annotations(read_only()),
285 Tool::new(
286 "execute_query",
287 execute_desc,
288 input_schema(Self::query_properties(), &["sql"]),
289 )
290 .with_annotations(read_only()),
291 Tool::new(
292 "list_views",
293 "List the queryable views with the first line of their description.",
294 input_schema(serde_json::json!({}), &[]),
295 )
296 .with_annotations(read_only()),
297 Tool::new(
298 "describe_view",
299 "Describe a view: usage rules (binding), columns and sort order. Read this \
300 before querying a view.",
301 input_schema(
302 serde_json::json!({"name": {"type": "string", "description": "View name from list_views."}}),
303 &["name"],
304 ),
305 )
306 .with_annotations(read_only()),
307 ]
308 }
309
310 async fn call_tool(
311 &self,
312 ctx: &CallContext,
313 name: &str,
314 arguments: JsonObject,
315 ) -> Option<CallToolResult> {
316 Some(match name {
317 "prepare_query" => self.prepare_query(ctx, arguments).await,
318 "execute_query" => self.execute_query(ctx, arguments).await,
319 "list_views" => self.list_views(ctx).await,
320 "describe_view" => self.describe_view(ctx, arguments).await,
321 _ => return None,
322 })
323 }
324}