webmcp/lib.rs
1//! Browser-side [WebMCP](https://github.com/webmachinelearning/webmcp) for Rust.
2//!
3//! WebMCP lets a *page* hand tools to whatever agent is driving the browser.
4//! Unlike a hosted MCP server, the tools run inside the session the user is
5//! already logged into: no API key, no second copy of your authorization rules,
6//! and the agent sees exactly what the user can see.
7//!
8//! # What this crate adds over calling the API directly
9//!
10//! `js_sys::eval` can register a tool in five lines. What it cannot do is keep
11//! the JSON Schema the agent plans against in sync with the struct the handler
12//! destructures, or guarantee the tool disappears when the UI behind it does.
13//! Those are the two failure modes this crate exists to remove:
14//!
15//! * [`Tool::register_typed`] derives `inputSchema` from the argument type, so
16//! the schema and the deserialization target are one declaration.
17//! * [`ToolHandle`] unregisters on drop, which under the current spec means
18//! aborting the `AbortSignal` handed to `registerTool()`.
19//!
20//! # Targets
21//!
22//! Off wasm — SSR, native, tests — every registration returns
23//! [`Error::Unsupported`] instead of failing to compile, so the same component
24//! code builds for both halves of a fullstack app.
25//!
26//! # Spec drift
27//!
28//! The browser API is not stable yet. This crate targets the surface as of the
29//! April 2026 draft: `registerTool(tool, { signal })` on `document.modelContext`,
30//! falling back to the deprecated `navigator.modelContext` alias. The removed
31//! `provideContext()` / `clearContext()` / `unregisterTool()` methods are not
32//! implemented. See `wasm::model_context` for how the lookup degrades.
33//!
34//! # Example
35//!
36//! ```no_run
37//! # #[cfg(feature = "schema")] {
38//! use webmcp::{Tool, ToolResult};
39//!
40//! #[derive(serde::Deserialize, schemars::JsonSchema)]
41//! struct AddTodo {
42//! /// The text content of the todo item.
43//! text: String,
44//! }
45//!
46//! let handle = Tool::new("add_todo")
47//! .description("Add an item to the user's todo list")
48//! .register_typed(|args: AddTodo| async move {
49//! Ok::<_, std::convert::Infallible>(ToolResult::text(format!("Added {}", args.text)))
50//! })?;
51//! // `handle` keeps the tool alive; dropping it unregisters.
52//! # }
53//! # Ok::<(), webmcp::Error>(())
54//! ```
55
56mod error;
57mod result;
58mod tool;
59
60#[cfg(feature = "schema")]
61mod schema;
62
63#[cfg(target_family = "wasm")]
64pub mod wasm;
65#[cfg(target_family = "wasm")]
66use wasm as imp;
67
68#[cfg(not(target_family = "wasm"))]
69mod native;
70#[cfg(not(target_family = "wasm"))]
71use native as imp;
72
73// Public so both can coexist under `--all-features`; the root `use_tool` alias
74// below covers the ordinary case of a crate using exactly one framework.
75#[cfg(feature = "dioxus")]
76pub mod dioxus;
77#[cfg(feature = "leptos")]
78pub mod leptos;
79#[cfg(all(feature = "topcoat", not(target_family = "wasm")))]
80pub mod topcoat;
81
82pub use error::{Error, Result};
83pub use result::{Content, ToolResult};
84pub use tool::{Tool, ToolHandle};
85
86#[cfg(feature = "schema")]
87pub use schema::schema_for;
88
89#[cfg(feature = "dioxus")]
90pub use dioxus::use_tool;
91#[cfg(all(feature = "leptos", not(feature = "dioxus")))]
92pub use leptos::use_tool;
93
94/// Whether the current page exposes a model context to register tools on.
95///
96/// Useful for showing an "agent-ready" affordance, not for guarding
97/// registration — registering on an unsupported page is already a harmless
98/// [`Error::Unsupported`].
99pub fn is_supported() -> bool {
100 imp::is_supported()
101}
102
103/// Warn on the browser console; a no-op elsewhere.
104///
105/// The crate deliberately has no logging dependency: a UI crate should not
106/// force `tracing` or `log` on its dependents for three diagnostics.
107///
108/// Only wasm and the framework features call it; the plain host build would
109/// otherwise flag it as dead.
110#[cfg_attr(
111 not(any(target_family = "wasm", feature = "dioxus", feature = "leptos")),
112 allow(dead_code)
113)]
114pub(crate) fn warn(message: &str) {
115 #[cfg(target_family = "wasm")]
116 web_sys::console::warn_1(&wasm_bindgen::JsValue::from_str(message));
117 #[cfg(not(target_family = "wasm"))]
118 {
119 let _ = message;
120 }
121}