Skip to main content

mira/
mcp.rs

1//! MCP, on the same port as everything else.
2//!
3//! The agentic principle's first reading: a model should be able to point at
4//! Mira and ask, without a translation layer in between. That is one endpoint,
5//! `POST /mcp`, speaking JSON-RPC 2.0 over Streamable HTTP.
6//!
7//! Eight of the nine tools are the same eight questions the UI asks —
8//! deliberately. An agent and a human looking at the same incident should be
9//! reading the same numbers out of the same code path; a separate "agent API"
10//! is a second read path to keep correct, and the first thing it does is
11//! drift. The ninth, `render_rca`, is the one question a UI cannot ask: it
12//! turns the eight answers into the write-up, and re-runs every citation in it
13//! before handing it back (see [`crate::rca`]).
14//!
15//! Stateless, and not by accident. Streamable HTTP lets a server hand out an
16//! `Mcp-Session-Id` and then requires every later request to carry it, which
17//! makes the server a thing with memory that a load balancer has to route back
18//! to the same replica. We issue none: every request carries everything it
19//! needs, any replica can answer it, and killing one loses nothing. That is
20//! principle 4 applied to the agent surface.
21//!
22//! No SSE either. The responses here are single JSON documents that arrive when
23//! the scan finishes, so a stream would be one event and a teardown.
24
25use 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
38/// The revision of the MCP spec these messages conform to.
39const PROTOCOL: &str = "2025-06-18";
40
41pub fn router(api: Api) -> Router {
42    Router::new().route("/mcp", post(handler)).with_state(api)
43}
44
45/// Tool definitions, verbatim.
46///
47/// Written by hand rather than generated, because this text is the prompt. A
48/// model chooses a tool and fills its arguments from these descriptions alone,
49/// so what belongs here is the shape of the data and the mistake to avoid —
50/// not a restatement of the parameter names.
51const 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
127/// The MCP endpoint: JSON-RPC in, one of the nine tools in [`TOOLS`] out.
128///
129/// Streamable HTTP with no session and no SSE, because every tool here is a
130/// single request and a single response. An agent points at this URL and has
131/// the same reads the UI does.
132async 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        // A notification has no id and takes no reply. `notifications/initialized`
154        // is the one every client sends, and answering it with an error is how a
155        // session fails on its second message.
156        _ 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 = &params["arguments"];
164    let now = api::now_nanos();
165    let dir = api.data_dir.clone();
166
167    // Tool failures are results, not protocol errors: a model that asked for a
168    // metric that does not exist needs to read the reason and try again, and a
169    // JSON-RPC error is something its client may swallow before it ever sees it.
170    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        // No window and no scan: this is in-memory state, so it does not go
237        // through `blocking` and has nothing to report as blocks scanned.
238        "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
266/// The one tool that reads in order to write.
267///
268/// The loop is the point: parse, re-run every citation, and only render if all
269/// of them still hold. A model that has been reasoning for twenty minutes has
270/// usually accumulated one claim it can no longer support, and this is the pass
271/// that finds it — before the document is pasted into a ticket rather than
272/// after.
273///
274/// The scans go through `api::scan` like every other read here, so an RCA's
275/// citations queue behind the same permit as a browser's queries rather than
276/// getting a pool of their own.
277async 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        // A read that failed and a read that matched nothing are the same
284        // answer to the only question being asked — "can this document stand
285        // up?" — so both collapse to `None` here, and `Rca::dead` tells them
286        // apart in the message.
287        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        // `Api::logs` is `None` on a node with no pipeline behind it, which in
300        // practice is a unit test. The document is still the answer; it just
301        // did not get stored, and saying which of those happened is the whole
302        // reason this is not a silent success.
303        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        // One message for all four refusals. They differ in whether a retry
308        // would work, which is a distinction the OTLP receivers turn into
309        // distinct status codes because an exporter acts on it — but the agent
310        // holding this document does the same thing either way, and it is the
311        // thing the sentence says.
312        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
321/// "Every span of this trace", which is the one query with no useful time
322/// bound: you look a trace up because you do not know when it happened. The
323/// window is therefore all of it, and the block-level trace-id filter is what
324/// makes that affordable.
325fn trace_search(args: &Yaml) -> Result<Search, String> {
326    // The other three tools get this from `search_doc`/`series_doc`/`window_doc`;
327    // this one builds its query by hand, so it has to ask. A misspelled `limit`
328    // is a page size the model believes it set.
329    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        // A trace is one page or it is a broken trace. 10,000 spans is already
335        // past what any waterfall can show, and an agent handed "here is a
336        // third of a trace, ask again" will reason about the third.
337        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
343/// Same rule as the HTTP API, through the same door: a cold mmap fault stalls
344/// the OS thread it lands on, and tokio has no way to see that happen. Sharing
345/// `api::scan` also shares its permit, so an agent's reads and a browser's are
346/// bounded together rather than each getting the whole pool.
347async 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
376/// JSON-RPC ids are a number, a string, or absent. Echoed back exactly, because
377/// that is how the client matches the reply to the call.
378fn 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
390/// Always 200 with a JSON body, even for an error object: in JSON-RPC the
391/// failure is in the payload, and a client that sees a 4xx may never parse far
392/// enough to find out what went wrong.
393fn 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    /// A data directory with one logs block in it, so the tools that succeed
409    /// have something to have succeeded on.
410    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    /// A tool call answers with `isError` inside a 200, never a JSON-RPC error.
443    /// This is the distinction the module header makes and the one a client is
444    /// most likely to get wrong, so every tool is driven through both sides of
445    /// it: the argument document that parses, and the one that does not.
446    #[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            // The fixture block is `service.name: checkout`, so this citation
471            // is one that holds — which is the only way the document renders.
472            (
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        // A tool that needs no arguments may be called with no `arguments`
486        // member at all, and that is a request, not a malformed document.
487        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        // Each tool parses its arguments with a different function, so each one
495        // needs its own way of being wrong.
496        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            // A misspelled key is a filter that was silently dropped, which the
503            // model cannot see in a page of unfiltered rows.
504            ("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` takes no arguments at all, so every key is a
514            // misspelling — including a window, which it does not honour and
515            // must not appear to.
516            ("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            // The write-up's own failure modes, through the same door as every
523            // other tool's: a missing section, a citation that does not hold,
524            // and a store this process cannot write to.
525            (
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    /// A read that fails — or panics — underneath the tool is still the tool's
552    /// answer, not a dead connection: the model is the one that has to decide
553    /// what to do next.
554    ///
555    /// `spawn_blocking` catches the unwind and hands it back as a `JoinError`.
556    /// Dropping it would leave the request hanging with the server otherwise
557    /// healthy, and a hung tool call is the one failure an agent cannot reason
558    /// about at all.
559    #[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    /// The handshake, and the three ways a request can not be a tool call. The
585    /// notification case is the one that breaks sessions: every client sends
586    /// `notifications/initialized` immediately after `initialize`, and a reply
587    /// to it — even a correct-looking error — ends the session on message two.
588    #[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        // These descriptions are the model's only documentation of the data, so
613        // they may not promise arithmetic the engine does not do: points come
614        // back as stored, and the temporality legend is what lets the model do
615        // the subtraction itself.
616        assert!(!body.contains("as rates"), "{body}");
617        assert!(body.contains("2 cumulative"), "{body}");
618
619        // A string id comes back quoted and escaped, because the client matches
620        // on it byte for byte.
621        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        // A method nobody knows, with an id, is a real JSON-RPC error — and a
636        // null id there is still a reply, since the client is waiting for one.
637        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    /// `get_trace` is the one tool with no time bound, so the id is the only
649    /// thing narrowing it. A malformed id has to be refused before the scan,
650    /// not turned into a filter that matches nothing after reading retention.
651    #[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        // A span id is 8 bytes and looks like a trace id to anyone not counting.
664        assert!(trace_search(&doc(r#"{"trace_id":"0102030405060708"}"#)).is_err());
665        assert!(trace_search(&doc("{}")).unwrap_err().contains("required"));
666        // The key check the other three tools get from their `*_doc` parser: a
667        // dropped `limit` is a page size the model thinks it set.
668        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        // Zero and "all of them" both mean the default rather than an empty page.
687        assert_eq!(limit("0"), 1_000);
688        assert_eq!(limit(r#""lots""#), 1_000);
689    }
690}