1use axum::Router;
26use axum::extract::State;
27use axum::http::{StatusCode, header};
28use axum::response::{IntoResponse, Response};
29use axum::routing::post;
30use yaml_rust2::Yaml;
31
32use mira_core::json::Json;
33use mira_core::query::Search;
34use mira_core::series;
35
36use crate::api::{self, Api};
37
38const PROTOCOL: &str = "2025-06-18";
40
41pub fn router(api: Api) -> Router {
42 Router::new().route("/mcp", post(handler)).with_state(api)
43}
44
45const TOOLS: &str = r#"[
52{"name":"query_records",
53 "description":"Search logs or spans. Returns matching records newest-first with all attributes merged in, plus the blocks and rows the scan touched. Terms are AND-ed. Use `attr` for OpenTelemetry attributes (service.name, http.route, k8s.pod.name) and `field` for columns of the record itself (severity_text, severity_number, body, name, duration_nano, status_code, trace_id, span_id). Attributes are searched at all three levels - record, resource and scope - so you do not need to know where the SDK put them. Time bounds default to the last hour; widening them costs blocks scanned. `rows_matched` above `limit` means you are seeing a page: narrow the filter, or page with `after`.",
54 "inputSchema":{"type":"object","properties":{
55 "signal":{"type":"string","enum":["logs","traces"],"description":"default logs"},
56 "from":{"type":"string","description":"'-15m', 'now', or absolute nanoseconds. Default -1h."},
57 "to":{"type":"string","description":"same forms. Default now."},
58 "where":{"type":"array","description":"AND-ed terms, each {attr|field: <name>, <op>: <value>} where op is one of eq ne lt lte gt gte contains","items":{"type":"object"}},
59 "limit":{"type":"integer","description":"default 100, max 10000"},
60 "after":{"type":"string","description":"the `next` value from a previous response, verbatim, to continue where it stopped. Absent `next` means that was the last page. There is no offset: a store still being written to shifts under one."}}}},
61
62{"name":"get_trace",
63 "description":"Every span of one trace, by trace id, over all of retention. Prefer this to query_records with a trace_id filter: blocks carry a trace-id index, and this is the call that uses it. Returns spans newest-first; parent_span_id links them into the tree.",
64 "inputSchema":{"type":"object","required":["trace_id"],"properties":{
65 "trace_id":{"type":"string","description":"32 hex characters, as returned in any span or log record"},
66 "limit":{"type":"integer","description":"default 1000, max 10000"}}}},
67
68{"name":"query_metric",
69 "description":"One metric as time series, grouped by attribute set. Each series carries its identifying attributes, its `temporality` as the OTLP enum (0 unspecified, 1 delta, 2 cumulative), whether it is `monotonic`, and its points. Points are the values as stored: no step, no aggregation and no rate, so a cumulative sum is the running counter and a per-second rate is yours to derive by subtracting consecutive points and dividing by the gap between their timestamps. Omit `name` at your peril - it scans every metric in the window.",
70 "inputSchema":{"type":"object","properties":{
71 "name":{"type":"string","description":"exact metric name, from list_metrics"},
72 "from":{"type":"string"},"to":{"type":"string"},
73 "where":{"type":"array","description":"same term grammar as query_records","items":{"type":"object"}},
74 "max_series":{"type":"integer","description":"default 200"},
75 "max_points":{"type":"integer","description":"default 5000"}}}},
76
77{"name":"list_metrics",
78 "description":"Metric names present in a time window, with unit and kind. Call this before query_metric rather than guessing a name.",
79 "inputSchema":{"type":"object","properties":{
80 "from":{"type":"string"},"to":{"type":"string"}}}},
81
82{"name":"correlate",
83 "description":"The frame around what a search matched: the time window, the traces those records belong to, and the services that took part. This is the tool for 'what else was happening', and it replaces the usual three round trips of query, read a trace id, query again. `expand` is an ordered walk, and the order matters: 'traces' widens the window to the real start and end of the traces found, which you almost always want first because a log line is written after the request it describes; 'peers' then adds every service that appears in those traces; 'around:<duration>' pads the window by hand. Every field of the answer is an input to another call - feed a trace to get_trace, a service name to query_records as {attr: service.name, eq: <name>}, and from/to to anything. `truncated` true means the frame hit its cap and is a sample, so narrow the search before drawing conclusions.",
84 "inputSchema":{"type":"object","properties":{
85 "signal":{"type":"string","enum":["logs","traces"],"description":"what to anchor on, default logs"},
86 "from":{"type":"string"},"to":{"type":"string"},
87 "where":{"type":"array","description":"same term grammar as query_records","items":{"type":"object"}},
88 "expand":{"type":"array","description":"ordered steps, each one of: traces, peers, around:<duration> such as around:30s","items":{"type":"string"}}}}},
89
90{"name":"service_map",
91 "description":"Who calls whom in a time window, computed from parent_span_id at read time. Nodes are services with their span and error counts; edges carry calls, errors, average and max duration in nanoseconds. The edge from \"entry\" is traffic arriving from outside the traced system. `unresolved` counts spans whose parent was not in the sample - if it is a large fraction of the spans, raise max_spans or narrow the window before trusting a thin edge. Use this to find the failing dependency before querying its records.",
92 "inputSchema":{"type":"object","properties":{
93 "from":{"type":"string"},"to":{"type":"string"},
94 "max_spans":{"type":"integer","description":"span budget, default 1000000. Newest blocks are read first, so a small budget is a recent sample, not a truncated one."}}}},
95
96{"name":"list_services",
97 "description":"Every service that emitted anything in a time window, with the stable entity key Mira identifies it by. Call this before filtering on service.name rather than guessing at the spelling. Two entries with the same name and different keys are two distinct instances or deployments.",
98 "inputSchema":{"type":"object","properties":{
99 "from":{"type":"string"},"to":{"type":"string"}}}},
100
101{"name":"list_alerts",
102 "description":"Every alerting rule this node evaluates and what it is currently doing: state is one of ok, pending (breaching but has not held for `for_nano` yet) and firing. `value` is the last evaluation, `threshold` and `op` are what it is compared against, and `matched`/`total` are the record counts behind it - a ratio rule counts `matched` of `total`, a count rule counts `matched`. `link` opens the same records in Mira's UI. An empty list means this node has no rules file, not that everything is healthy. `error` non-null means the rule could not be evaluated, which is not the same as not firing. Rules are static KYAML in a file, so this tool reads and never writes.",
103 "inputSchema":{"type":"object","properties":{}}},
104
105{"name":"render_rca",
106 "description":"Turn an investigation into a root-cause analysis in markdown. You supply the findings as fields; Mira renders the document, and before it does it re-runs every citation in `evidence` against the store. A citation that matches no records fails the whole call and the reason names the claim - so cite something you actually found with query_records, get_trace or correlate, and if a citation fails, widen its window or drop the claim rather than rewording it. Each evidence item gives exactly one of `trace_id` or `query`; a query with no from/to inherits the incident window, which is what you want. `prevention` is an alerts.kyaml rule and is parsed by the same loader the alerting engine uses, so a rule that would not start is an error here rather than a surprise later. Mira has no tool that changes a cluster and this is not one: `remediation` is text for whoever is on call, and the rendered document says so. With `emit` the write-up is also stored as a log record, searchable afterwards as {field: body, contains: ...} or {attr: rca.title, ...}.",
107 "inputSchema":{"type":"object","required":["title","summary","root_cause"],"properties":{
108 "title":{"type":"string","description":"one line, as a ticket title"},
109 "from":{"type":"string","description":"start of the incident; same forms as query_records. Default -1h."},
110 "to":{"type":"string"},
111 "summary":{"type":"string","description":"what broke, for whom, for how long - the paragraph someone reads first"},
112 "impact":{"type":"array","description":"quantified: request counts, error rates, affected services. Numbers you read out of a tool, not adjectives.","items":{"type":"string"}},
113 "timeline":{"type":"array","description":"ordered automatically, so give entries in any order","items":{"type":"object","required":["at","what"],"properties":{"at":{"type":"string","description":"'-42m' or absolute nanoseconds"},"what":{"type":"string"}}}},
114 "root_cause":{"type":"string","description":"the mechanism, not the symptom: what made the failure inevitable"},
115 "evidence":{"type":"array","description":"cited claims. Every one is re-run before the document is rendered.","items":{"type":"object","required":["claim"],"properties":{
116 "claim":{"type":"string"},
117 "trace_id":{"type":"string","description":"32 hex characters"},
118 "query":{"type":"object","description":"a query_records document: signal, where, and optionally from/to"}}}},
119 "ruled_out":{"type":"array","description":"hypotheses you tested and eliminated, each with how. The section that stops the next person repeating the investigation.","items":{"type":"string"}},
120 "contributing":{"type":"array","items":{"type":"string"}},
121 "remediation":{"type":"array","description":"what a human or an agent with cluster access should do. Mira does none of it.","items":{"type":"string"}},
122 "verification":{"type":"array","description":"how to tell the fix worked, as things to look at in Mira","items":{"type":"string"}},
123 "prevention":{"type":"object","description":"an alerting rule that would have caught this: {name, query, when, over, for, severity}. `when` is like 'count > 20' or 'ratio > 5%'; the query may not carry its own window. No `notify` - the operator's file names the targets."},
124 "emit":{"type":"boolean","description":"also store the document in Mira as a log record. Default false."}}}}
125]"#;
126
127async fn handler(State(api): State<Api>, body: String) -> Response {
133 let doc = match api::parse(&body) {
134 Ok(d) => d,
135 Err(e) => return rpc_error(&Yaml::Null, -32700, &e),
136 };
137 let id = doc["id"].clone();
138 let method = doc["method"].as_str().unwrap_or_default();
139 let params = &doc["params"];
140
141 match method {
142 "initialize" => result(
143 &id,
144 &format!(
145 "{{\"protocolVersion\":\"{PROTOCOL}\",\"capabilities\":{{\"tools\":{{}}}},\
146 \"serverInfo\":{{\"name\":\"mira\",\"version\":\"{}\"}}}}",
147 env!("CARGO_PKG_VERSION")
148 ),
149 ),
150 "tools/list" => result(&id, &format!("{{\"tools\":{TOOLS}}}")),
151 "tools/call" => call(api, &id, params).await,
152 "ping" => result(&id, "{}"),
153 _ if id.is_badvalue() || id.is_null() => StatusCode::ACCEPTED.into_response(),
157 other => rpc_error(&id, -32601, &format!("unknown method {other:?}")),
158 }
159}
160
161async fn call(api: Api, id: &Yaml, params: &Yaml) -> Response {
162 let name = params["name"].as_str().unwrap_or_default();
163 let args = ¶ms["arguments"];
164 let now = api::now_nanos();
165 let dir = api.data_dir.clone();
166
167 let out = match name {
171 "query_records" => match api::search_doc(args, now) {
172 Ok(q) => {
173 let open = api.open(q.signal.dir()).await;
174 blocking("rows", move || {
175 mira_core::query::search_open(&dir, &q, &open)
176 })
177 .await
178 }
179 Err(e) => Err(e),
180 },
181 "get_trace" => match trace_search(args) {
182 Ok(q) => {
183 let open = api.open(q.signal.dir()).await;
184 blocking("rows", move || {
185 mira_core::query::search_open(&dir, &q, &open)
186 })
187 .await
188 }
189 Err(e) => Err(e),
190 },
191 "query_metric" => match api::series_doc(args, now) {
192 Ok(q) => {
193 let open = api.open("metrics").await;
194 blocking("series", move || series::series_open(&dir, &q, &open)).await
195 }
196 Err(e) => Err(e),
197 },
198 "list_metrics" => match api::window_doc(args, now) {
199 Ok((from, to)) => {
200 let open = api.open("metrics").await;
201 blocking("names", move || series::names_open(&dir, from, to, &open)).await
202 }
203 Err(e) => Err(e),
204 },
205 "correlate" => match api::correlate_doc(args, now) {
206 Ok((q, ops)) => {
207 let anchored = api.open(q.signal.dir()).await;
208 let all = api.open_all().await;
209 blocking("frame", move || {
210 api::correlate(&dir, &q, &ops, &anchored, &all)
211 })
212 .await
213 }
214 Err(e) => Err(e),
215 },
216 "service_map" => match api::map_doc(args, now) {
217 Ok((from, to, max_spans)) => {
218 let open = api.open("traces").await;
219 blocking("map", move || {
220 mira_core::frame::map(&dir, from, to, max_spans, &open)
221 })
222 .await
223 }
224 Err(e) => Err(e),
225 },
226 "list_services" => match api::window_doc(args, now) {
227 Ok((from, to)) => {
228 let open = api.open_all().await;
229 blocking("entities", move || {
230 mira_core::frame::entities(&dir, from, to, &open)
231 })
232 .await
233 }
234 Err(e) => Err(e),
235 },
236 "list_alerts" => match api::known(args, &[]) {
239 Ok(()) => Ok(api.alerts.json()),
240 Err(e) => Err(e),
241 },
242 "render_rca" => render_rca(&api, args, now).await,
243 other => Err(format!("unknown tool {other:?}")),
244 };
245
246 let mut j = Json::new();
247 j.obj(|j| {
248 j.key("content");
249 j.arr(|j| {
250 j.obj(|j| {
251 j.key("type");
252 j.str("text");
253 j.key("text");
254 match &out {
255 Ok(text) => j.str(text),
256 Err(e) => j.str(e),
257 }
258 });
259 });
260 j.key("isError");
261 j.bool(out.is_err());
262 });
263 result(id, &j.into_string())
264}
265
266async fn render_rca(api: &Api, args: &Yaml, now: i64) -> Result<String, String> {
278 let mut doc = crate::rca::doc(args, now)?;
279 for f in &mut doc.evidence {
280 let q = f.cite.clone();
281 let dir = api.data_dir.clone();
282 let open = api.open(q.signal.dir()).await;
283 let rows = api::scan(move || mira_core::query::search_open(&dir, &q, &open))
288 .await
289 .ok()
290 .and_then(Result::ok)
291 .map(|r| r.stats.rows_matched);
292 f.seen(rows);
293 }
294 if let Some(dead) = doc.dead() {
295 return Err(dead);
296 }
297 let md = doc.render();
298 if doc.emit {
299 let logs = api.logs.as_ref().ok_or(
304 "the document was rendered but `emit` could not store it: this process \
305 has no ingest pipeline. Take the markdown from a call without `emit`.",
306 )?;
307 logs.submit(doc.export(&md, now)).await.map_err(|_| {
313 "the document was rendered but the ingest pipeline refused to store it. \
314 Take the markdown from a call without `emit`."
315 .to_owned()
316 })?;
317 }
318 Ok(md)
319}
320
321fn trace_search(args: &Yaml) -> Result<Search, String> {
326 api::known(args, &["trace_id", "limit"])?;
330 let id = args["trace_id"]
331 .as_str()
332 .ok_or("trace_id is required, as 32 hex characters")?;
333 let limit = match &args["limit"] {
334 Yaml::Integer(n) if *n > 0 => (*n as usize).min(10_000),
338 _ => 1_000,
339 };
340 crate::rca::trace_query(id, limit)
341}
342
343async fn blocking(
348 field: &'static str,
349 f: impl FnOnce() -> mira_core::error::Result<mira_core::query::Results> + Send + 'static,
350) -> Result<String, String> {
351 let t = std::time::Instant::now();
352 match api::scan(f).await {
353 Ok(Ok(r)) => Ok(api::envelope(field, &r, t.elapsed())),
354 Ok(Err(e)) => Err(e.to_string()),
355 Err(e) => Err(format!("query task panicked: {e}")),
356 }
357}
358
359fn result(id: &Yaml, payload: &str) -> Response {
360 json(format!(
361 "{{\"jsonrpc\":\"2.0\",\"id\":{},\"result\":{payload}}}",
362 rpc_id(id)
363 ))
364}
365
366fn rpc_error(id: &Yaml, code: i32, message: &str) -> Response {
367 let mut j = Json::new();
368 j.str(message);
369 json(format!(
370 "{{\"jsonrpc\":\"2.0\",\"id\":{},\"error\":{{\"code\":{code},\"message\":{}}}}}",
371 rpc_id(id),
372 j.into_string()
373 ))
374}
375
376fn rpc_id(id: &Yaml) -> String {
379 match id {
380 Yaml::Integer(n) => n.to_string(),
381 Yaml::String(s) => {
382 let mut j = Json::new();
383 j.str(s);
384 j.into_string()
385 }
386 _ => "null".into(),
387 }
388}
389
390fn json(body: String) -> Response {
394 (
395 StatusCode::OK,
396 [(header::CONTENT_TYPE, "application/json")],
397 body,
398 )
399 .into_response()
400}
401
402#[cfg(test)]
403mod tests {
404 use super::*;
405 use std::path::PathBuf;
406 use std::sync::Arc;
407
408 fn api(name: &str) -> (Api, PathBuf) {
411 let dir = std::env::temp_dir().join(format!("mira-mcp-{name}-{}", std::process::id()));
412 let _ = std::fs::remove_dir_all(&dir);
413 std::fs::create_dir_all(&dir).unwrap();
414 let mut b = mira_core::logs::LogsBuilder::new();
415 b.append_request(&crate::e2e::logs_export(
416 "checkout",
417 api::now_nanos() as u64,
418 4,
419 ))
420 .unwrap();
421 let sealed = b.finish().unwrap();
422 mira_core::block::publish(&dir, "logs", mira_core::block::node_id("a"), 0, 0, &sealed)
423 .unwrap();
424 (
425 Api {
426 data_dir: Arc::new(dir.clone()),
427 ..Default::default()
428 },
429 dir,
430 )
431 }
432
433 async fn rpc(api: &Api, body: &str) -> (StatusCode, String) {
434 let res = handler(State(api.clone()), body.to_owned()).await;
435 let status = res.status();
436 let bytes = axum::body::to_bytes(res.into_body(), usize::MAX)
437 .await
438 .unwrap();
439 (status, String::from_utf8(bytes.to_vec()).unwrap())
440 }
441
442 #[tokio::test]
447 async fn a_tool_that_cannot_answer_says_so_in_its_result_not_in_the_protocol() {
448 let (api, _dir) = api("tools");
449 let call = |name: &str, args: &str| {
450 format!(
451 r#"{{"jsonrpc":"2.0","id":1,"method":"tools/call",
452 "params":{{"name":"{name}","arguments":{args}}}}}"#
453 )
454 };
455 let ok = [
456 ("query_records", r#"{"limit":2}"#),
457 (
458 "get_trace",
459 r#"{"trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","limit":5}"#,
460 ),
461 ("query_metric", r#"{"name":"http.server.duration"}"#),
462 ("list_metrics", "{}"),
463 (
464 "correlate",
465 r#"{"expand":["traces","around:30s","peers"],"limit":2}"#,
466 ),
467 ("service_map", r#"{"max_spans":100}"#),
468 ("list_services", "{}"),
469 ("list_alerts", "{}"),
470 (
473 "render_rca",
474 r#"{"title":"t","summary":"s","root_cause":"r","evidence":[
475 {"claim":"checkout was logging","query":{"where":[
476 {"attr":"service.name","eq":"checkout"}]}}]}"#,
477 ),
478 ];
479 for (name, args) in ok {
480 let (s, body) = rpc(&api, &call(name, args)).await;
481 assert_eq!(s, StatusCode::OK, "{name}");
482 assert!(body.contains(r#""isError":false"#), "{name}: {body}");
483 }
484
485 let (_, body) = rpc(
488 &api,
489 r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_metrics"}}"#,
490 )
491 .await;
492 assert!(body.contains(r#""isError":false"#), "{body}");
493
494 let bad = [
497 ("query_records", r#"{"signal":"metrics"}"#, "unknown signal"),
498 ("get_trace", r#"{"trace_id":"nope"}"#, "hex trace id"),
499 ("query_metric", r#"{"where":"errors"}"#, "list of terms"),
500 ("list_metrics", r#"{"from":"yesterday"}"#, "yesterday"),
501 ("teleport", "{}", "unknown tool"),
502 ("query_records", r#"{"filters":[]}"#, "unknown query key"),
505 ("query_metric", r#"{"step":"1m"}"#, "unknown query key"),
506 ("list_metrics", r#"{"name":"http"}"#, "unknown query key"),
507 ("correlate", r#"{"expand":["sideways"]}"#, "sideways"),
508 ("correlate", r#"{"expand":"traces"}"#, "list of steps"),
509 ("correlate", r#"{"signal":"metrics"}"#, "unknown signal"),
510 ("service_map", r#"{"max_spans":0}"#, "max_spans"),
511 ("service_map", r#"{"limit":5}"#, "unknown query key"),
512 ("list_services", r#"{"to":"soon"}"#, "soon"),
513 ("list_alerts", r#"{"from":"-1h"}"#, "unknown query key"),
517 (
518 "get_trace",
519 r#"{"trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","limitt":5}"#,
520 "unknown query key",
521 ),
522 (
526 "render_rca",
527 r#"{"title":"t","root_cause":"r"}"#,
528 "`summary`",
529 ),
530 (
531 "render_rca",
532 r#"{"title":"t","summary":"s","root_cause":"r","evidence":[
533 {"claim":"ghosts","query":{"where":[
534 {"attr":"service.name","eq":"nobody"}]}}]}"#,
535 "matches no records",
536 ),
537 (
538 "render_rca",
539 r#"{"title":"t","summary":"s","root_cause":"r","emit":true}"#,
540 "no ingest pipeline",
541 ),
542 ];
543 for (name, args, want) in bad {
544 let (s, body) = rpc(&api, &call(name, args)).await;
545 assert_eq!(s, StatusCode::OK, "{name}");
546 assert!(body.contains(r#""isError":true"#), "{name}: {body}");
547 assert!(body.contains(want), "{name}: {body}");
548 }
549 }
550
551 #[tokio::test]
560 async fn a_broken_store_is_reported_to_the_model_rather_than_thrown() {
561 let panicked = blocking("rows", || panic!("a page fault, say"))
562 .await
563 .unwrap_err();
564 assert!(panicked.contains("query task panicked"), "{panicked}");
565
566 let dir = std::env::temp_dir().join(format!("mira-mcp-broken-{}", std::process::id()));
567 let _ = std::fs::remove_dir_all(&dir);
568 std::fs::create_dir_all(&dir).unwrap();
569 std::fs::write(dir.join("logs"), b"not a directory").unwrap();
570 let api = Api {
571 data_dir: Arc::new(dir),
572 ..Default::default()
573 };
574 let (s, body) = rpc(
575 &api,
576 r#"{"jsonrpc":"2.0","id":1,"method":"tools/call",
577 "params":{"name":"query_records","arguments":{}}}"#,
578 )
579 .await;
580 assert_eq!(s, StatusCode::OK);
581 assert!(body.contains(r#""isError":true"#), "{body}");
582 }
583
584 #[tokio::test]
589 async fn the_protocol_surface_echoes_ids_and_stays_quiet_when_there_is_none() {
590 let (api, _dir) = api("proto");
591 let (_, body) = rpc(
592 &api,
593 r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}"#,
594 )
595 .await;
596 assert!(body.contains(PROTOCOL), "{body}");
597 assert!(body.contains(env!("CARGO_PKG_VERSION")), "{body}");
598
599 let (_, body) = rpc(&api, r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#).await;
600 for tool in [
601 "query_records",
602 "get_trace",
603 "query_metric",
604 "list_metrics",
605 "correlate",
606 "service_map",
607 "list_services",
608 "render_rca",
609 ] {
610 assert!(body.contains(tool), "{tool} missing from tools/list");
611 }
612 assert!(!body.contains("as rates"), "{body}");
617 assert!(body.contains("2 cumulative"), "{body}");
618
619 let (_, body) = rpc(&api, r#"{"jsonrpc":"2.0","id":"a\"b","method":"ping"}"#).await;
622 assert!(
623 body.starts_with(r#"{"jsonrpc":"2.0","id":"a\"b","result":{}}"#),
624 "{body}"
625 );
626
627 let (s, body) = rpc(
628 &api,
629 r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
630 )
631 .await;
632 assert_eq!(s, StatusCode::ACCEPTED);
633 assert!(body.is_empty(), "{body}");
634
635 let (_, body) = rpc(&api, r#"{"jsonrpc":"2.0","id":true,"method":"levitate"}"#).await;
638 assert!(body.contains(r#""id":null"#), "{body}");
639 assert!(
640 body.contains("-32601") && body.contains("levitate"),
641 "{body}"
642 );
643
644 let (_, body) = rpc(&api, "{not: [kyaml").await;
645 assert!(body.contains("-32700"), "{body}");
646 }
647
648 #[test]
652 fn a_trace_lookup_insists_on_a_whole_trace_id() {
653 let doc = |s: &str| api::parse(s).unwrap();
654 let q = trace_search(&doc(r#"{"trace_id":" 4BF92F3577B34DA6A3CE929D0E0E4736 "}"#)).unwrap();
655 assert_eq!(q.signal, mira_core::query::Signal::Traces);
656 assert_eq!((q.from, q.to), (0, i64::MAX));
657 assert_eq!(q.limit, 1_000);
658 assert!(q.after.is_none());
659 assert_eq!(q.terms.len(), 1);
660
661 let short = trace_search(&doc(r#"{"trace_id":"ab","limit":7}"#)).unwrap_err();
662 assert!(short.contains("16-byte"), "{short}");
663 assert!(trace_search(&doc(r#"{"trace_id":"0102030405060708"}"#)).is_err());
665 assert!(trace_search(&doc("{}")).unwrap_err().contains("required"));
666 let typo = trace_search(&doc(
669 r#"{"trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","limitt":5}"#,
670 ))
671 .unwrap_err();
672 assert!(
673 typo.contains("unknown query key") && typo.contains("limitt"),
674 "{typo}"
675 );
676
677 let limit = |s: &str| {
678 trace_search(&doc(&format!(
679 r#"{{"trace_id":"4bf92f3577b34da6a3ce929d0e0e4736","limit":{s}}}"#
680 )))
681 .unwrap()
682 .limit
683 };
684 assert_eq!(limit("7"), 7);
685 assert_eq!(limit("99999"), 10_000);
686 assert_eq!(limit("0"), 1_000);
688 assert_eq!(limit(r#""lots""#), 1_000);
689 }
690}