Skip to main content

openreadout_mcp/
lib.rs

1//! MCP (Model Context Protocol) server exposing the same operations as the CLI, over stdio.
2//! Tool inputs and outputs are the same `serde`/`schemars` types the CLI uses, so an agent
3//! sees one schema whichever way it calls us.
4//!
5//! MCP is the protocol AI assistants (Claude, Cursor, VS Code, ...) use to call local tools.
6//! The server offers one tool per operation (`openreadout_info`, `openreadout_stats`,
7//! `openreadout_peaks`, `openreadout_export`, ...), named like the CLI commands and taking the
8//! CLI flags' names as arguments, resources (`openreadout://formats`,
9//! `openreadout://file/{path}`) and prompts; `book/src/reference/mcp.md` in the repository lists them.
10//!
11//! # Cargo features
12//!
13//! | feature | default | what it adds |
14//! | --- | --- | --- |
15//! | `http` | no | `serve_http` and `HttpOptions`: MCP over Streamable HTTP on a loopback address (optional bearer token). Off by default so that the stdio server contains no networking code. |
16//!
17//! # Example
18//!
19//! ```no_run
20//! use openreadout_core::Registry;
21//!
22//! /// The readers the server may use; called once per request so that every call gets fresh
23//! /// readers. Real servers register the format crates' readers here.
24//! fn registry() -> Registry {
25//!     Registry::new()
26//! }
27//!
28//! // Serve on stdin/stdout until the client disconnects.
29//! openreadout_mcp::serve_stdio(registry)?;
30//! # Ok::<(), anyhow::Error>(())
31//! ```
32#![forbid(unsafe_code)]
33#![warn(missing_docs)]
34
35mod app;
36mod budget;
37mod coerce;
38#[cfg(feature = "http")]
39mod http;
40mod lean;
41mod progress;
42mod resources;
43mod schema_compact;
44mod tools;
45mod wording;
46
47#[cfg(feature = "http")]
48pub use http::{HttpOptions, serve_http};
49pub use resources::PREVIEW_BUDGET;
50
51use openreadout_core::{Error, Registry};
52use rmcp::handler::server::router::tool::ToolRouter;
53use rmcp::model::{
54    CallToolRequestParams, CallToolResponse, CallToolResult, GetPromptRequestParams,
55    GetPromptResponse, Implementation, ListPromptsResult, ListResourceTemplatesResult,
56    ListResourcesResult, ListToolsResult, PaginatedRequestParams, ReadResourceRequestParams,
57    ReadResourceResponse, ServerCapabilities, ServerConfig, Tool,
58};
59use rmcp::service::RequestContext;
60use rmcp::{ErrorData as McpError, RoleServer, ServerHandler, ServiceExt, tool_handler};
61use serde::Serialize;
62
63/// The server. Holds a registry factory so each call gets fresh readers.
64#[derive(Clone)]
65pub struct InstrumentServer {
66    registry: fn() -> Registry,
67    tool_router: ToolRouter<Self>,
68    watches: tools::watch::Watches,
69}
70
71impl std::fmt::Debug for InstrumentServer {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        f.write_str("InstrumentServer")
74    }
75}
76
77fn mcp_err(e: &Error) -> McpError {
78    let mut data = serde_json::json!({"code": e.code(), "exit_code": e.exit_code()});
79    if let Some(h) = e.hint() {
80        data["hint"] = serde_json::Value::String(wording::for_tools(&h));
81    }
82    McpError::new(
83        rmcp::model::ErrorCode::INTERNAL_ERROR,
84        wording::for_tools(&e.to_string()),
85        Some(data),
86    )
87}
88
89/// A failed tool call as a result with `isError`, its message and hint in the text (the model
90/// reads tool results; clients often pass on only the message of a protocol error), and
91/// `{code, exit_code, hint}` under `_meta["openreadout/error"]`.
92fn error_result(e: McpError) -> CallToolResult {
93    let mut text = e.message.to_string();
94    if let Some(h) = e
95        .data
96        .as_ref()
97        .and_then(|d| d.get("hint"))
98        .and_then(|h| h.as_str())
99    {
100        text.push_str("\nhint: ");
101        text.push_str(h);
102    }
103    let mut r = CallToolResult::error(vec![rmcp::model::ContentBlock::text(text)]);
104    // the code and exit code for clients that branch on them, as the CLI's JSON errors have
105    if let Some(d) = e.data {
106        r.meta
107            .get_or_insert_with(rmcp::model::MetaObject::default)
108            .insert(ERROR_META_KEY.into(), d);
109    }
110    r
111}
112
113/// Result `_meta` key of a failed call: `{code, exit_code, hint}`.
114pub const ERROR_META_KEY: &str = "openreadout/error";
115
116/// A tool's `strict` argument over the server's default (`OPENREADOUT_STRICT`, `--strict`).
117pub(crate) fn with_strict(reg: Registry, strict: Option<bool>) -> Registry {
118    match strict {
119        Some(on) => reg.strict(on),
120        None => reg,
121    }
122}
123
124fn to_value<T: Serialize>(v: &T) -> Result<serde_json::Value, McpError> {
125    serde_json::to_value(v).map_err(|e| McpError::internal_error(e.to_string(), None))
126}
127
128/// A successful result: the JSON as `structuredContent` and, for clients that only read
129/// `content`, the same JSON serialized as one text block.
130fn ok_json<T: Serialize>(v: &T) -> Result<CallToolResult, McpError> {
131    Ok(CallToolResult::structured(to_value(v)?))
132}
133
134impl InstrumentServer {
135    /// A fresh registry, strict when the call asks for it (`strict`) or the server runs strict.
136    fn reg_for(&self, strict: Option<bool>) -> Registry {
137        with_strict((self.registry)(), strict)
138    }
139
140    /// Names of the tools this server offers (for `openreadout self doctor`).
141    pub fn tool_names(&self) -> Vec<String> {
142        let mut names: Vec<String> = self
143            .tool_router
144            .list_all()
145            .into_iter()
146            .map(|t| t.name.to_string())
147            .collect();
148        names.sort();
149        names
150    }
151}
152
153impl InstrumentServer {
154    /// A server whose tools open files with readers from `registry` (called once per request).
155    pub fn new(registry: fn() -> Registry) -> Self {
156        let mut tool_router = tools::router();
157        for route in tool_router.map.values_mut() {
158            route.attr.input_schema =
159                std::sync::Arc::new(schema_compact::compact(&route.attr.input_schema));
160        }
161        Self {
162            registry,
163            tool_router,
164            watches: tools::watch::Watches::default(),
165        }
166    }
167}
168
169/// Server instructions sent at initialization.
170pub const INSTRUCTIONS: &str = "OpenReadout reads raw lab-instrument files and data-set directories without vendor software: microscopy, slides, screening plates, electron microscopy, flow cytometry, electrophysiology, NMR, spectroscopy, mass spectrometry, chromatography, plate readers, qPCR, DNA sequencers and bench instruments, in vendor binary formats and their text and XML exports. Its readers know each format's layout, units and conventions, so questions about these files need no hand-written parser. Each file reports an assurance level that says how far its variant was checked against an independent reader, and strict=true refuses values that are not validated. Indices are zero-based. Values are raw as stored unless a tool says it processed them. Only openreadout_export (data, and figures from openreadout_plot or openreadout_preview) and openreadout_extract write next to the data, to new files that are read back and verified. openreadout_index, openreadout_batch, openreadout_summarize and openreadout_report write only to paths you give them. Tools are the CLI's commands and arguments are its flags (analyze nmr-peaks --range-ppm is openreadout_nmr_peaks with range_ppm). Errors carry a code and a hint.";
171
172// The trait's methods are async; resources and prompts are answered without awaiting.
173#[allow(clippy::unused_async_trait_impl)]
174#[tool_handler(router = self.tool_router)]
175impl ServerHandler for InstrumentServer {
176    fn get_info(&self) -> ServerConfig {
177        let mut capabilities = ServerCapabilities::builder()
178            .enable_tools()
179            .enable_resources()
180            .enable_prompts()
181            .build();
182        capabilities.extensions = Some([app::server_extension()].into_iter().collect());
183        ServerConfig::new(capabilities)
184            .with_server_info(
185                Implementation::new("openreadout", env!("CARGO_PKG_VERSION"))
186                    .with_title("OpenReadout"),
187            )
188            .with_instructions(INSTRUCTIONS)
189    }
190
191    // The viewer app (`app`) hooks in here: tools/list, tools/call and the `ui://` resource.
192    async fn list_tools(
193        &self,
194        _request: Option<PaginatedRequestParams>,
195        context: RequestContext<RoleServer>,
196    ) -> Result<ListToolsResult, McpError> {
197        let mut tools = self.tool_router.list_all();
198        if app::ui_for(&context) {
199            app::decorate(&mut tools);
200        }
201        Ok(ListToolsResult::with_all_items(tools))
202    }
203
204    async fn call_tool(
205        &self,
206        mut request: CallToolRequestParams,
207        context: RequestContext<RoleServer>,
208    ) -> Result<CallToolResponse, McpError> {
209        if let (Some(tool), Some(args)) = (
210            self.tool_router.get(&request.name),
211            request.arguments.as_mut(),
212        ) {
213            coerce::args(&tool.input_schema, args);
214            for (key, inner_tool) in coerce::NESTED_TOOL_ARGS {
215                if let (Some(serde_json::Value::Object(inner)), Some(t)) =
216                    (args.get_mut(key), self.tool_router.get(inner_tool))
217                {
218                    coerce::args(&t.input_schema, inner);
219                }
220            }
221        }
222        if request.name == app::VIEW_TOOL {
223            return app::call_view(self.registry, request, &context)
224                .await
225                .map(Into::into);
226        }
227        let hint = app::ui_for(&context)
228            .then(|| app::view_hint(&request.name, request.arguments.as_ref()))
229            .flatten();
230        let name = request.name.clone();
231        let max_chars = budget::max_chars(&name, request.arguments.as_ref());
232        let tcc = rmcp::handler::server::tool::ToolCallContext::new(self, request, context);
233        let mut response = match coerce::with_argument_hint(
234            self.tool_router.call(tcc).await,
235            self.tool_router.get(&name),
236        ) {
237            Err(e) if self.tool_router.get(&name).is_some() => error_result(e).into(),
238            r => r?,
239        };
240        if let CallToolResponse::Complete(result) = &mut response {
241            wording::result_notes(result);
242            budget::fit(result, &name, max_chars);
243            if let Some(hint) = hint {
244                app::attach_hint(result, hint);
245            }
246        }
247        Ok(response)
248    }
249
250    fn get_tool(&self, name: &str) -> Option<Tool> {
251        if name == app::VIEW_TOOL {
252            return Some(app::view_tool());
253        }
254        self.tool_router.get(name).cloned()
255    }
256
257    async fn list_resources(
258        &self,
259        _request: Option<PaginatedRequestParams>,
260        context: RequestContext<RoleServer>,
261    ) -> Result<ListResourcesResult, McpError> {
262        let mut list = resources::list();
263        if app::ui_for(&context) {
264            list.push(app::resource());
265        }
266        Ok(ListResourcesResult::with_all_items(list))
267    }
268
269    async fn list_resource_templates(
270        &self,
271        _request: Option<PaginatedRequestParams>,
272        _context: RequestContext<RoleServer>,
273    ) -> Result<ListResourceTemplatesResult, McpError> {
274        Ok(ListResourceTemplatesResult::with_all_items(
275            resources::templates(),
276        ))
277    }
278
279    async fn read_resource(
280        &self,
281        request: ReadResourceRequestParams,
282        _context: RequestContext<RoleServer>,
283    ) -> Result<ReadResourceResponse, McpError> {
284        if let Some(r) = app::read(&request.uri) {
285            return Ok(r.into());
286        }
287        let registry = self.registry;
288        let uri = request.uri;
289        tokio::task::spawn_blocking(move || resources::read(registry, &uri))
290            .await
291            .map_err(|e| McpError::internal_error(format!("resource task failed: {e}"), None))?
292            .map(Into::into)
293    }
294
295    async fn list_prompts(
296        &self,
297        _request: Option<PaginatedRequestParams>,
298        _context: RequestContext<RoleServer>,
299    ) -> Result<ListPromptsResult, McpError> {
300        Ok(ListPromptsResult::with_all_items(resources::prompts()))
301    }
302
303    async fn get_prompt(
304        &self,
305        request: GetPromptRequestParams,
306        _context: RequestContext<RoleServer>,
307    ) -> Result<GetPromptResponse, McpError> {
308        resources::get_prompt(&request.name, request.arguments.as_ref()).map(Into::into)
309    }
310}
311
312/// Serve over stdio until the client disconnects.
313pub fn serve_stdio(registry: fn() -> Registry) -> anyhow::Result<()> {
314    let rt = tokio::runtime::Builder::new_multi_thread()
315        .enable_all()
316        .build()?;
317    rt.block_on(async {
318        let service = InstrumentServer::new(registry)
319            .serve(rmcp::transport::stdio())
320            .await?;
321        service.waiting().await?;
322        Ok(())
323    })
324}
325
326#[cfg(test)]
327mod tests {
328    use std::path::{Path, PathBuf};
329
330    use base64::Engine as _;
331    use openreadout_core::model::FileInfo;
332    use rmcp::handler::server::wrapper::Parameters;
333
334    use super::*;
335    use crate::tools::info::{InfoArgs, InfoView};
336    use crate::tools::preview::PreviewArgs;
337    use openreadout_core::reader::PlaneIndex;
338
339    #[test]
340    fn every_tool_is_annotated() {
341        let s = InstrumentServer::new(Registry::new);
342        let tools = s.tool_router.list_all();
343        let mut names: Vec<&str> = tools.iter().map(|t| t.name.as_ref()).collect();
344        names.sort_unstable();
345        assert_eq!(
346            names,
347            [
348                "openreadout_assay",
349                "openreadout_batch",
350                "openreadout_check",
351                "openreadout_chromatogram",
352                "openreadout_compare",
353                "openreadout_ephys_features",
354                "openreadout_export",
355                "openreadout_extract",
356                "openreadout_gate",
357                "openreadout_health",
358                "openreadout_index",
359                "openreadout_info",
360                "openreadout_link",
361                "openreadout_nmr_peaks",
362                "openreadout_peaks",
363                "openreadout_plot",
364                "openreadout_preview",
365                "openreadout_qpcr",
366                "openreadout_report",
367                "openreadout_scans",
368                "openreadout_search",
369                "openreadout_spectrum",
370                "openreadout_spikes",
371                "openreadout_stats",
372                "openreadout_summarize",
373                "openreadout_table",
374                "openreadout_trace",
375                "openreadout_watch",
376            ]
377        );
378        for t in &tools {
379            let a = t
380                .annotations
381                .as_ref()
382                .unwrap_or_else(|| panic!("{} has no annotations", t.name));
383            // `index` writes only its own index directory and `report` only its own new bundle
384            // file: not read-only, not destructive.
385            let overwrites = matches!(
386                t.name.as_ref(),
387                "openreadout_export"
388                    | "openreadout_extract"
389                    | "openreadout_batch"
390                    | "openreadout_summarize"
391            );
392            let writes =
393                overwrites || t.name == "openreadout_index" || t.name == "openreadout_report";
394            assert!(a.title.is_some(), "{}", t.name);
395            assert_eq!(a.read_only_hint, Some(!writes), "{}", t.name);
396            assert_eq!(a.destructive_hint, Some(overwrites), "{}", t.name);
397            // `watch` returns new events on every call.
398            let idempotent = t.name != "openreadout_watch";
399            assert_eq!(a.idempotent_hint, Some(idempotent), "{}", t.name);
400            assert_eq!(a.open_world_hint, Some(false), "{}", t.name);
401            if t.name != "openreadout_export" {
402                let o = t
403                    .output_schema
404                    .as_ref()
405                    .unwrap_or_else(|| panic!("{} has no outputSchema", t.name));
406                assert_eq!(
407                    o.get("type"),
408                    Some(&serde_json::json!("object")),
409                    "{}",
410                    t.name
411                );
412            }
413        }
414    }
415
416    /// A synthetic image format for tool tests: `SYNTHIMG`, then width and height (u32 LE);
417    /// the plane is a uint8 gradient generated on read.
418    #[derive(Debug)]
419    struct SynthReader;
420
421    #[derive(Debug)]
422    struct SynthImage {
423        path: String,
424        w: u32,
425        h: u32,
426    }
427
428    impl openreadout_core::FormatReader for SynthReader {
429        fn descriptor(&self) -> openreadout_core::FormatDescriptor {
430            openreadout_core::FormatDescriptor {
431                id: "synth".into(),
432                name: "Synthetic".into(),
433                vendor: "test".into(),
434                extensions: vec![],
435                family: "microscopy".into(),
436                can_read: true,
437                can_write: false,
438                confidence: openreadout_core::Confidence::High,
439                known_gaps: vec![],
440            }
441        }
442        fn sniff(&self, head: &[u8], _: &Path) -> Option<openreadout_core::Detection> {
443            head.starts_with(b"SYNTHIMG")
444                .then_some(openreadout_core::Detection {
445                    format_id: "synth",
446                    confidence: openreadout_core::DetectConfidence::Definite,
447                    note: None,
448                })
449        }
450        fn open(
451            &self,
452            path: &Path,
453        ) -> openreadout_core::Result<Box<dyn openreadout_core::Dataset>> {
454            let b = std::fs::read(path).map_err(|e| Error::io(path, e))?;
455            let u = |o: usize| u32::from_le_bytes([b[o], b[o + 1], b[o + 2], b[o + 3]]);
456            Ok(Box::new(SynthImage {
457                path: path.display().to_string(),
458                w: u(8),
459                h: u(12),
460            }))
461        }
462    }
463
464    impl openreadout_core::Dataset for SynthImage {
465        fn info(&self) -> openreadout_core::Result<FileInfo> {
466            let mut im = openreadout_core::ImageInfo::new(
467                0,
468                self.w,
469                self.h,
470                openreadout_core::PixelType::Uint8,
471            );
472            im.physical_size =
473                openreadout_core::PhysicalSize::micrometres(Some(0.5), Some(0.5), None);
474            let im = im.finish();
475            Ok(FileInfo {
476                path: self.path.clone(),
477                size_bytes: 16,
478                format: openreadout_core::FormatReader::descriptor(&SynthReader),
479                format_version: None,
480                plane_count: im.plane_count,
481                images: vec![im],
482                tables: vec![],
483                spectra: vec![],
484                traces: vec![],
485                notes: vec![],
486            })
487        }
488        fn vendor_metadata(&self) -> openreadout_core::Result<serde_json::Value> {
489            Ok(serde_json::Value::Null)
490        }
491        fn provenance(&self) -> openreadout_core::ProvenanceMap {
492            openreadout_core::ProvenanceMap::default()
493        }
494        fn entries(&self) -> openreadout_core::Result<Vec<openreadout_core::LsEntry>> {
495            Ok(vec![])
496        }
497        fn read_plane(
498            &mut self,
499            _: u32,
500            _: PlaneIndex,
501        ) -> openreadout_core::Result<openreadout_core::Plane> {
502            assert!(
503                u64::from(self.w) * u64::from(self.h) <= 1 << 24,
504                "the thumbnail budget must stop this read"
505            );
506            let data = (0..self.h)
507                .flat_map(|y| (0..self.w).map(move |x| ((x + y) % 256) as u8))
508                .collect();
509            Ok(openreadout_core::Plane {
510                width: self.w,
511                height: self.h,
512                pixel_type: openreadout_core::PixelType::Uint8,
513                samples_per_pixel: 1,
514                data,
515            })
516        }
517        fn check(&mut self) -> openreadout_core::Result<openreadout_core::CheckReport> {
518            Ok(openreadout_core::CheckReport::new(&self.path, "synth"))
519        }
520    }
521
522    fn synth_registry() -> Registry {
523        Registry::new().with(Box::new(SynthReader))
524    }
525
526    fn synth_file(name: &str, w: u32, h: u32) -> PathBuf {
527        let p = std::env::temp_dir().join(format!(
528            "openreadout-mcp-{}-{name}.synth",
529            std::process::id()
530        ));
531        let mut b = b"SYNTHIMG".to_vec();
532        b.extend_from_slice(&w.to_le_bytes());
533        b.extend_from_slice(&h.to_le_bytes());
534        std::fs::write(&p, b).unwrap();
535        p
536    }
537
538    fn info_args(file: &Path, thumbnail: Option<bool>) -> Parameters<InfoArgs> {
539        Parameters(InfoArgs {
540            file: file.display().to_string(),
541            view: InfoView::Summary,
542            ask: None,
543            max_images: None,
544            thumbnail,
545            vendor: false,
546            max_frames: None,
547            max_entries: None,
548            kind: None,
549            first_entry: None,
550            strict: None,
551        })
552    }
553
554    fn images(r: &CallToolResult) -> Vec<Vec<u8>> {
555        r.content
556            .iter()
557            .filter_map(|c| c.as_image())
558            .map(|i| {
559                base64::engine::general_purpose::STANDARD
560                    .decode(&i.data)
561                    .unwrap()
562            })
563            .collect()
564    }
565
566    fn texts(r: &CallToolResult) -> Vec<String> {
567        r.content
568            .iter()
569            .filter_map(|c| c.as_text())
570            .map(|t| t.text.clone())
571            .collect()
572    }
573
574    #[test]
575    fn info_attaches_a_bounded_thumbnail() {
576        let s = InstrumentServer::new(synth_registry);
577        let f = synth_file("small", 2000, 1000);
578        let with = s.info(info_args(&f, None)).unwrap();
579        let without = s.info(info_args(&f, Some(false))).unwrap();
580        assert_eq!(with.structured_content, without.structured_content);
581        assert!(images(&without).is_empty());
582        assert_eq!(without.content.len(), 1);
583        let img = images(&with);
584        assert_eq!(img.len(), 1);
585        let t = texts(&with);
586        assert!(
587            t.iter().any(|x| x.contains("rulers in full-res px")),
588            "{t:?}"
589        );
590        // PNG or JPEG, at most 384 px, identical across calls
591        let png = &img[0];
592        let (width, height) = if png.starts_with(b"\x89PNG") {
593            (
594                u32::from_be_bytes([png[16], png[17], png[18], png[19]]),
595                u32::from_be_bytes([png[20], png[21], png[22], png[23]]),
596            )
597        } else {
598            assert!(png.starts_with(&[0xFF, 0xD8]), "PNG or JPEG");
599            (0, 0)
600        };
601        assert!(
602            width.max(height) <= preview_size_limit(),
603            "{width}x{height}"
604        );
605        assert_eq!(images(&s.info(info_args(&f, None)).unwrap()), img);
606
607        // over the decoded-pixel budget: no picture, a note pointing to openreadout_preview
608        let big = synth_file("big", 40_000, 30_000);
609        let r = s.info(info_args(&big, None)).unwrap();
610        assert!(images(&r).is_empty());
611        let t = texts(&r);
612        assert!(
613            t.iter()
614                .any(|x| x.contains("no thumbnail") && x.contains("openreadout_preview")),
615            "{t:?}"
616        );
617        assert_eq!(
618            r.structured_content,
619            s.info(info_args(&big, Some(false)))
620                .unwrap()
621                .structured_content
622        );
623        let _ = std::fs::remove_file(f);
624        let _ = std::fs::remove_file(big);
625    }
626
627    /// A preview with annotations, as the agent saw it, saved by openreadout_export at twice
628    /// its size; the preview's result says how.
629    #[tokio::test]
630    async fn export_saves_an_annotated_preview() {
631        let server = InstrumentServer::new(synth_registry);
632        let file = synth_file("save", 3000, 2000);
633        let preview = serde_json::json!({
634            "file": file.display().to_string(),
635            "max_size": 400,
636            "dark": true,
637            "annotations": [{"type": "point", "x": 1500, "y": 1000, "label": "here"}],
638        });
639        let result = server
640            .preview(Parameters(serde_json::from_value(preview.clone()).unwrap()))
641            .await
642            .unwrap();
643        let seen = result.structured_content.unwrap();
644        let save = seen["save"].as_str().unwrap();
645        assert!(save.contains("preview = these arguments") && save.contains(".preview.png"));
646        let out = file.with_extension("annotated.png");
647        let args = serde_json::from_value(serde_json::json!({
648            "preview": preview, "output": out.display().to_string(), "dpi": 300,
649        }))
650        .unwrap();
651        let (written, shown) =
652            crate::tools::export::export_blocking(synth_registry, args, None).unwrap();
653        assert!(
654            shown.is_some_and(|(bytes, _)| !bytes.is_empty()),
655            "the saved picture comes back"
656        );
657        assert_eq!(written["drawn"], "image");
658        // the image is read again at twice max_size (whole downsampling steps, so about twice)
659        let saved_width = written["width"].as_u64().unwrap();
660        let seen_width = seen["width"].as_u64().unwrap();
661        assert!(
662            saved_width > seen_width * 3 / 2 && saved_width <= seen_width * 2 + 2,
663            "{saved_width} vs {seen_width}"
664        );
665        let png = std::fs::read(&out).unwrap();
666        assert!(png.starts_with(b"\x89PNG") && png.windows(4).any(|x| x == b"pHYs"));
667        // unknown preview arguments are refused, not ignored
668        let err =
669            serde_json::from_value::<PreviewArgs>(serde_json::json!({"file": "x", "zoom": 2}))
670                .unwrap_err();
671        assert!(err.to_string().contains("zoom"), "{err}");
672        let _ = std::fs::remove_file(out);
673        let _ = std::fs::remove_file(file);
674    }
675
676    fn preview_size_limit() -> u32 {
677        openreadout_preview::DEFAULT_THUMBNAIL_SIZE
678    }
679
680    #[tokio::test]
681    async fn preview_reports_the_ruler_mapping() {
682        let s = InstrumentServer::new(synth_registry);
683        let f = synth_file("preview", 3000, 2000);
684        let args = |axes: openreadout_preview::Axes, region: Option<openreadout_core::Region>| {
685            let v = serde_json::json!({"file": f.display().to_string(), "max_size": 400});
686            let mut a: PreviewArgs = serde_json::from_value(v).unwrap();
687            a.options.axes = Some(axes);
688            a.options.region = region;
689            Parameters(a)
690        };
691        let r = s
692            .preview(args(openreadout_preview::Axes::Rulers, None))
693            .await
694            .unwrap();
695        let v = r.structured_content.clone().unwrap();
696        let im = &v["image"];
697        assert_eq!(im["axes"], true);
698        assert_eq!(
699            im["full_res_region"],
700            serde_json::json!({"x": 0, "y": 0, "width": 3000, "height": 2000})
701        );
702        assert!(im["scale_bar"]["pixels"].as_u64().unwrap() > 0);
703        assert!(v["hint"].as_str().unwrap().contains("region"));
704        assert!(v["width"].as_u64().unwrap() <= 400);
705        // a zoom read off the rulers comes back with the same numbers
706        let zoom = openreadout_core::Region::new(1000, 500, 800, 600);
707        let r = s
708            .preview(args(openreadout_preview::Axes::Rulers, Some(zoom)))
709            .await
710            .unwrap();
711        let v = r.structured_content.unwrap();
712        assert_eq!(
713            v["image"]["full_res_region"],
714            serde_json::json!({"x": 1000, "y": 500, "width": 800, "height": 600})
715        );
716        assert_eq!(
717            v["image"]["source_origin"],
718            serde_json::json!({"x": 1000.0, "y": 500.0})
719        );
720        // axes=none: the bare plane fills the picture
721        let r = s
722            .preview(args(openreadout_preview::Axes::None, None))
723            .await
724            .unwrap();
725        let v = r.structured_content.unwrap();
726        assert_eq!(v["image"]["axes"], false);
727        assert_eq!(v["image"]["plot_area"]["width"], v["width"]);
728        let _ = std::fs::remove_file(f);
729    }
730
731    #[tokio::test]
732    async fn plot_returns_the_figure_and_what_it_drew() {
733        let s = InstrumentServer::new(Registry::new);
734        let args: crate::tools::plot::PlotArgs = serde_json::from_value(serde_json::json!({
735            "title": "per tube",
736            "data": {"values": {"x": ["E01", "E03"], "y": [0.004, 2.6]}},
737            "annotate": [{"type": "hline", "y": 1.0, "label": "threshold"}],
738        }))
739        .unwrap();
740        let r = s.plot(Parameters(args)).await.unwrap();
741        let first = serde_json::to_value(&r.content[0]).unwrap();
742        assert_eq!(first["type"], "image");
743        assert_eq!(first["mimeType"], "image/png");
744        let v = r.structured_content.clone().unwrap();
745        assert_eq!(v["inline_series"], 1);
746        assert_eq!(
747            v["panels"][0]["x"]["categories"],
748            serde_json::json!(["E01", "E03"])
749        );
750        let meta = r.meta.unwrap();
751        assert!(meta.get(crate::tools::plot::FIGURE_META_KEY).is_some());
752        // it says how to save it, and only openreadout_export writes
753        assert!(
754            v["save"]
755                .as_str()
756                .is_some_and(|s| s.starts_with("openreadout_export with plot")),
757            "{v}"
758        );
759        let e = serde_json::from_value::<crate::tools::plot::PlotArgs>(
760            serde_json::json!({"data": {"values": {"y": [1]}}, "output": "f.png"}),
761        )
762        .unwrap_err()
763        .to_string();
764        assert!(e.contains("openreadout_export"), "{e}");
765        // an unknown key names the known ones
766        let e =
767            serde_json::from_value::<crate::tools::plot::PlotArgs>(serde_json::json!({"dta": {}}))
768                .unwrap_err()
769                .to_string();
770        assert!(e.contains("unknown plot argument `dta`"), "{e}");
771    }
772
773    #[test]
774    fn capabilities_cover_tools_resources_prompts() {
775        let info = InstrumentServer::new(Registry::new).get_info();
776        assert!(info.capabilities.tools.is_some());
777        assert!(info.capabilities.resources.is_some());
778        assert!(info.capabilities.prompts.is_some());
779        assert!(INSTRUCTIONS.contains("openreadout_export"));
780        // A few sentences: the routing is in the tool names and descriptions.
781        assert!(INSTRUCTIONS.len() < 1200, "{}", INSTRUCTIONS.len());
782    }
783}