Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

feat(webmcp): add native form schemas, fill intents, and activity states

ldm0ca0a4c81a27a
diff --git a/Cargo.lock b/Cargo.lock
index f4af77f47..b20b90f81 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3468,6 +3468,17 @@ dependencies = [
"syn 3.0.3",
]
+[[package]]
+name = "moli-webmcp"
+version = "0.1.0"
+dependencies = [
+ "indexmap",
+ "moli-dom",
+ "num-bigint",
+ "serde",
+ "serde_json",
+]
+
[[package]]
name = "moli-websocket"
version = "0.1.0"
@@ -4629,7 +4640,7 @@ dependencies = [
[[package]]
name = "selectors"
version = "0.40.0"
-source = "git+https://github.com/lexmount/stylo?branch=moli#3c8bbb450a52f9a4dcb2de51061216a1d2727def"
+source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27"
dependencies = [
"bitflags",
"cssparser",
@@ -4761,7 +4772,7 @@ dependencies = [
[[package]]
name = "servo_arc"
version = "0.4.3"
-source = "git+https://github.com/lexmount/stylo?branch=moli#3c8bbb450a52f9a4dcb2de51061216a1d2727def"
+source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27"
dependencies = [
"serde",
"stable_deref_trait",
@@ -5014,7 +5025,7 @@ dependencies = [
[[package]]
name = "stylo"
version = "0.20.0"
-source = "git+https://github.com/lexmount/stylo?branch=moli#3c8bbb450a52f9a4dcb2de51061216a1d2727def"
+source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27"
dependencies = [
"app_units",
"arrayvec",
@@ -5070,7 +5081,7 @@ dependencies = [
[[package]]
name = "stylo_atoms"
version = "0.20.0"
-source = "git+https://github.com/lexmount/stylo?branch=moli#3c8bbb450a52f9a4dcb2de51061216a1d2727def"
+source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27"
dependencies = [
"string_cache",
"string_cache_codegen",
@@ -5079,7 +5090,7 @@ dependencies = [
[[package]]
name = "stylo_derive"
version = "0.20.0"
-source = "git+https://github.com/lexmount/stylo?branch=moli#3c8bbb450a52f9a4dcb2de51061216a1d2727def"
+source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27"
dependencies = [
"darling",
"proc-macro2",
@@ -5091,7 +5102,7 @@ dependencies = [
[[package]]
name = "stylo_dom"
version = "0.20.0"
-source = "git+https://github.com/lexmount/stylo?branch=moli#3c8bbb450a52f9a4dcb2de51061216a1d2727def"
+source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27"
dependencies = [
"bitflags",
"stylo_malloc_size_of",
@@ -5100,7 +5111,7 @@ dependencies = [
[[package]]
name = "stylo_malloc_size_of"
version = "0.20.0"
-source = "git+https://github.com/lexmount/stylo?branch=moli#3c8bbb450a52f9a4dcb2de51061216a1d2727def"
+source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27"
dependencies = [
"app_units",
"cssparser",
@@ -5117,7 +5128,7 @@ dependencies = [
[[package]]
name = "stylo_static_prefs"
version = "0.20.0"
-source = "git+https://github.com/lexmount/stylo?branch=moli#3c8bbb450a52f9a4dcb2de51061216a1d2727def"
+source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27"
dependencies = [
"toml",
]
@@ -5135,7 +5146,7 @@ dependencies = [
[[package]]
name = "stylo_traits"
version = "0.20.0"
-source = "git+https://github.com/lexmount/stylo?branch=moli#3c8bbb450a52f9a4dcb2de51061216a1d2727def"
+source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27"
dependencies = [
"app_units",
"bitflags",
@@ -5434,7 +5445,7 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "to_shmem"
version = "0.5.0"
-source = "git+https://github.com/lexmount/stylo?branch=moli#3c8bbb450a52f9a4dcb2de51061216a1d2727def"
+source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27"
dependencies = [
"cssparser",
"servo_arc",
@@ -5447,7 +5458,7 @@ dependencies = [
[[package]]
name = "to_shmem_derive"
version = "0.1.0"
-source = "git+https://github.com/lexmount/stylo?branch=moli#3c8bbb450a52f9a4dcb2de51061216a1d2727def"
+source = "git+https://github.com/lexmount/stylo?rev=0c7e8baf63b6714e7614834fadbc09710f3c3d27#0c7e8baf63b6714e7614834fadbc09710f3c3d27"
dependencies = [
"darling",
"proc-macro2",
diff --git a/Cargo.toml b/Cargo.toml
index f4d2f0ae8..f2de4738f 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -75,6 +75,7 @@ members = [
"moli-webidl",
"moli-webidl-callback",
"moli-webidl-derive",
+ "moli-webmcp",
"moli-cookie-jar",
"moli-websocket",
"moli-fetch",
@@ -103,13 +104,13 @@ curl-sys = { git = "https://github.com/lexmount/curl-rust", rev = "a0ea59f5ca1b1
cookie = { git = "https://github.com/ldm0/cookie-rs", branch = "priority" }
v8 = { path = "vendor/v8-152.2.0" }
deno_v8 = { path = "vendor/deno_v8-0.3.0" }
-selectors = { git = "https://github.com/lexmount/stylo", branch = "moli" }
-servo_arc = { git = "https://github.com/lexmount/stylo", branch = "moli" }
-stylo = { git = "https://github.com/lexmount/stylo", branch = "moli" }
-stylo_atoms = { git = "https://github.com/lexmount/stylo", branch = "moli" }
-stylo_dom = { git = "https://github.com/lexmount/stylo", branch = "moli" }
-stylo_static_prefs = { git = "https://github.com/lexmount/stylo", branch = "moli" }
-stylo_traits = { git = "https://github.com/lexmount/stylo", branch = "moli" }
+selectors = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" }
+servo_arc = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" }
+stylo = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" }
+stylo_atoms = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" }
+stylo_dom = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" }
+stylo_static_prefs = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" }
+stylo_traits = { git = "https://github.com/lexmount/stylo", rev = "0c7e8baf63b6714e7614834fadbc09710f3c3d27" }
svgtypes = { git = "https://github.com/lexmount/svgtypes", branch = "feat/strict-path-numbers" }
taffy = { git = "https://github.com/ldm0/taffy", rev = "645bf5a49df607a8bff34ec90c5343901d04f10e" }
diff --git a/moli-dom/src/native/element/control_state.rs b/moli-dom/src/native/element/control_state.rs
index 2c5429fea..7eb75e8fd 100644
--- a/moli-dom/src/native/element/control_state.rs
+++ b/moli-dom/src/native/element/control_state.rs
@@ -172,6 +172,8 @@ pub struct ElementControlState {
scroll_left: Option<f64>,
custom_validation_message: String,
popover_open: bool,
+ web_mcp_form_active: bool,
+ web_mcp_submit_active: bool,
dialog_modal: bool,
dialog_return_value: String,
custom_states: IndexSet<String>,
@@ -179,6 +181,20 @@ pub struct ElementControlState {
}
impl ElementControlState {
+ pub fn web_mcp_form_active(&self) -> bool {
+ self.web_mcp_form_active
+ }
+
+ pub fn web_mcp_submit_active(&self) -> bool {
+ self.web_mcp_submit_active
+ }
+
+ pub fn set_web_mcp_activity(&mut self, form: bool, submit: bool) -> bool {
+ let changed = self.web_mcp_form_active != form || self.web_mcp_submit_active != submit;
+ self.web_mcp_form_active = form;
+ self.web_mcp_submit_active = submit;
+ changed
+ }
pub fn explicit_element_references(&self, attribute: &str) -> Option<&[NativeNodeId]> {
self.explicit_element_references
.as_deref()?
diff --git a/moli-dom/src/native/element/mod.rs b/moli-dom/src/native/element/mod.rs
index 0de3f42eb..443f518d9 100644
--- a/moli-dom/src/native/element/mod.rs
+++ b/moli-dom/src/native/element/mod.rs
@@ -1068,6 +1068,18 @@ impl Element {
self.control_state().popover_open()
}
+ pub fn web_mcp_form_active(&self) -> bool {
+ self.control_state().web_mcp_form_active()
+ }
+
+ pub fn web_mcp_submit_active(&self) -> bool {
+ self.control_state().web_mcp_submit_active()
+ }
+
+ pub fn set_web_mcp_activity(&mut self, form: bool, submit: bool) -> bool {
+ self.control_state_mut().set_web_mcp_activity(form, submit)
+ }
+
pub fn dialog_modal(&self) -> bool {
self.control_state().dialog_modal()
}
diff --git a/moli-dom/src/native/element/tests.rs b/moli-dom/src/native/element/tests.rs
index 1407dc087..18334fa9f 100644
--- a/moli-dom/src/native/element/tests.rs
+++ b/moli-dom/src/native/element/tests.rs
@@ -475,3 +475,29 @@ fn range_input_value_uses_live_min_max_and_step_attributes() {
assert_eq!(defaulted.input_value(), "4");
assert!(!defaulted.input_value_dirty());
}
+
+#[test]
+fn range_value_setters_use_element_bounds_and_step_authority() {
+ let mut input = Element::new_html("input");
+ for (name, value) in [
+ ("type", "range"),
+ ("min", "100"),
+ ("max", "200"),
+ ("step", "10"),
+ ] {
+ input.set_attribute(name.into(), String::new(), None, value.into());
+ }
+ for (value, expected) in [
+ ("180", "180"),
+ ("185", "190"),
+ ("250", "200"),
+ ("90", "100"),
+ ("invalid", "150"),
+ ] {
+ input.set_input_value(value);
+ assert_eq!(input.input_value(), expected);
+ }
+ input.set_attribute("step".into(), String::new(), None, "any".into());
+ input.set_input_value("180.25");
+ assert_eq!(input.input_value(), "180.25");
+}
diff --git a/moli-dom/src/native/host/mutation/state.rs b/moli-dom/src/native/host/mutation/state.rs
index 4aca93b3c..35212b5f1 100644
--- a/moli-dom/src/native/host/mutation/state.rs
+++ b/moli-dom/src/native/host/mutation/state.rs
@@ -345,6 +345,17 @@ impl DomHost {
did_change
}
+ pub fn set_web_mcp_activity(&mut self, handle: DomHandle, form: bool, submit: bool) -> bool {
+ let changed = self
+ .node_mut(handle)
+ .and_then(|node| node.data_mut().as_element_mut())
+ .is_some_and(|element| element.set_web_mcp_activity(form, submit));
+ if changed {
+ self.record_mutation(MutationScope::QueryState);
+ }
+ changed
+ }
+
pub fn set_dialog_modal(&mut self, handle: DomHandle, modal: bool) -> bool {
let did_change = {
let Some(element) = self
diff --git a/moli-dom/src/native/host/query_index.rs b/moli-dom/src/native/host/query_index.rs
index f51479d0d..e7452c07a 100644
--- a/moli-dom/src/native/host/query_index.rs
+++ b/moli-dom/src/native/host/query_index.rs
@@ -260,6 +260,28 @@ impl DomHost {
self.elements_by_tag_name_ns(document, Some(HTML_NAMESPACE_URI), local_name, true)
}
+ /// Indexed candidates in a subtree, including descendants of shadow roots.
+ /// The result has no tree-order guarantee. Empty tag indexes do not traverse
+ /// the subtree, including when the root contains many unrelated elements.
+ pub fn html_elements_by_local_name_in_shadow_including_subtree(
+ &self,
+ root: DomHandle,
+ local_name: &str,
+ ) -> Vec<DomHandle> {
+ self.ensure_namespace_local_name_element_index();
+ let index = self.element_query_index.borrow();
+ let Some(candidates) =
+ index.namespace_local_name_candidates(HTML_NAMESPACE_URI, local_name)
+ else {
+ return Vec::new();
+ };
+ candidates
+ .iter()
+ .copied()
+ .filter(|handle| self.is_host_including_inclusive_ancestor(root, *handle))
+ .collect()
+ }
+
fn ensure_qualified_name_element_index(&self) {
if self
.element_query_index
@@ -843,6 +865,50 @@ mod tests {
);
}
+ #[test]
+ fn shadow_including_tag_query_tracks_new_detached_and_moved_candidates() {
+ let mut host = test_host();
+ let document = host.document_handle();
+ let root = host.create_element("section");
+ assert!(host.append_child(document, root));
+ assert!(
+ host.html_elements_by_local_name_in_shadow_including_subtree(root, "form")
+ .is_empty()
+ );
+ let light_form = host.create_element("form");
+ let shadow_root = host.attach_shadow_root(root, "closed").unwrap();
+ let shadow_form = host.create_element("form");
+ let detached_form = host.create_element("form");
+ let foreign_form = host
+ .create_element_ns(Some("http://www.w3.org/2000/svg"), "form")
+ .unwrap();
+ assert!(host.append_child(root, light_form));
+ assert!(host.append_child(root, foreign_form));
+ assert!(host.append_child(shadow_root, shadow_form));
+ let forms = host.html_elements_by_local_name_in_shadow_including_subtree(document, "form");
+ assert_eq!(forms.len(), 2);
+ assert!(forms.contains(&light_form) && forms.contains(&shadow_form));
+ assert_eq!(
+ host.html_elements_by_local_name_in_shadow_including_subtree(detached_form, "form"),
+ vec![detached_form]
+ );
+ assert!(host.remove_child(document, root));
+ assert!(
+ host.html_elements_by_local_name_in_shadow_including_subtree(document, "form")
+ .is_empty()
+ );
+ assert_eq!(
+ host.html_elements_by_local_name_in_shadow_including_subtree(root, "form")
+ .len(),
+ 2
+ );
+ assert!(host.append_child(document, shadow_form));
+ assert_eq!(
+ host.html_elements_by_local_name_in_shadow_including_subtree(document, "form"),
+ vec![shadow_form]
+ );
+ }
+
#[test]
fn tag_queries_keep_subtree_boundaries_with_unrelated_index_candidates() {
fn assert_query(
diff --git a/moli-selector/src/detached_stylo.rs b/moli-selector/src/detached_stylo.rs
index 93844383f..98e001d55 100644
--- a/moli-selector/src/detached_stylo.rs
+++ b/moli-selector/src/detached_stylo.rs
@@ -500,6 +500,8 @@ where
| NonTSPseudoClass::ReadOnly
| NonTSPseudoClass::ReadWrite
| NonTSPseudoClass::PlaceholderShown
+ | NonTSPseudoClass::ToolFormActive
+ | NonTSPseudoClass::ToolSubmitActive
| NonTSPseudoClass::InRange
| NonTSPseudoClass::OutOfRange
| NonTSPseudoClass::Valid
diff --git a/moli-selector/src/stylo/invalidation.rs b/moli-selector/src/stylo/invalidation.rs
index f4e1cb42f..29aba64cc 100644
--- a/moli-selector/src/stylo/invalidation.rs
+++ b/moli-selector/src/stylo/invalidation.rs
@@ -1566,6 +1566,12 @@ fn ascii_whitespace_tokens(value: &str) -> Vec<String> {
fn stylo_retained_dependency_state_for_element(element: &Element) -> ElementState {
let mut state = ElementState::empty();
+ if element.web_mcp_form_active() {
+ state |= ElementState::TOOL_FORM_ACTIVE;
+ }
+ if element.web_mcp_submit_active() {
+ state |= ElementState::TOOL_SUBMIT_ACTIVE;
+ }
const HEADING_NAMES: [(&str, u64); 6] = [
("h1", 1),
("h2", 2),
diff --git a/moli-selector/src/stylo/query/element.rs b/moli-selector/src/stylo/query/element.rs
index 72afb044f..0d8500e4c 100644
--- a/moli-selector/src/stylo/query/element.rs
+++ b/moli-selector/src/stylo/query/element.rs
@@ -643,6 +643,8 @@ impl SelectorsElement for QueryElement<'_> {
NonTSPseudoClass::ReadOnly => self.matches_read_only_pseudo(),
NonTSPseudoClass::ReadWrite => self.matches_read_write_pseudo(),
NonTSPseudoClass::PlaceholderShown => self.matches_placeholder_shown_pseudo(),
+ NonTSPseudoClass::ToolFormActive => self.element().web_mcp_form_active(),
+ NonTSPseudoClass::ToolSubmitActive => self.element().web_mcp_submit_active(),
NonTSPseudoClass::InRange => self.matches_in_range_pseudo(),
NonTSPseudoClass::OutOfRange => self.matches_out_of_range_pseudo(),
NonTSPseudoClass::Valid => {
diff --git a/moli-selector/src/stylo/query/pseudo.rs b/moli-selector/src/stylo/query/pseudo.rs
index 9dd9fe46c..cb7f5ab00 100644
--- a/moli-selector/src/stylo/query/pseudo.rs
+++ b/moli-selector/src/stylo/query/pseudo.rs
@@ -52,6 +52,12 @@ impl<'a> QueryElement<'a> {
if element.autofilled() {
state |= ElementState::AUTOFILL;
}
+ if element.web_mcp_form_active() {
+ state |= ElementState::TOOL_FORM_ACTIVE;
+ }
+ if element.web_mcp_submit_active() {
+ state |= ElementState::TOOL_SUBMIT_ACTIVE;
+ }
if self.matches_validity_pseudo() {
if self.is_invalid() {
state |= ElementState::INVALID;
diff --git a/moli-webmcp/Cargo.toml b/moli-webmcp/Cargo.toml
new file mode 100644
index 000000000..28281e25d
--- /dev/null
+++ b/moli-webmcp/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+license.workspace = true
+name = "moli-webmcp"
+version = "0.1.0"
+edition = "2024"
+
+[dependencies]
+indexmap = { version = "2.6", features = ["serde"] }
+moli-dom = { path = "../moli-dom" }
+num-bigint = "0.4.6"
+serde = { version = "1.0.228", features = ["derive"] }
+serde_json = { version = "1.0.145", features = ["raw_value"] }
+
+[lints]
+workspace = true
diff --git a/moli-webmcp/src/lib.rs b/moli-webmcp/src/lib.rs
new file mode 100644
index 000000000..9774a6eef
--- /dev/null
+++ b/moli-webmcp/src/lib.rs
@@ -0,0 +1,23 @@
+//! WebMCP algorithms over the native DOM, independent of JavaScript bindings.
+//!
+//! The browser owns form discovery, label ownership, HTML pattern validation,
+//! invocation lifetimes and applying updates. This crate describes controls,
+//! validates complete fill plans and extracts navigation results.
+
+mod number;
+mod plan;
+mod result;
+mod schema;
+
+pub use plan::{Fill, prepare_fill};
+pub use result::navigation_result;
+pub use schema::{ParameterControls, input_schema};
+
+/// Chromium's shared name restriction for imperative and declarative tools.
+pub fn is_valid_tool_name(name: &str) -> bool {
+ !name.is_empty()
+ && name.len() <= 128
+ && name
+ .bytes()
+ .all(|byte| byte.is_ascii_alphanumeric() || b"_-.".contains(&byte))
+}
diff --git a/moli-webmcp/src/number.rs b/moli-webmcp/src/number.rs
new file mode 100644
index 000000000..8b56f7133
--- /dev/null
+++ b/moli-webmcp/src/number.rs
@@ -0,0 +1,71 @@
+//! Blink JSONValue's int32 and six-significant-digit double conversions.
+
+use num_bigint::BigUint;
+use serde_json::Number;
+
+pub(crate) fn integer(number: &Number) -> Option<i32> {
+ let value = number.as_f64()?;
+ (value >= f64::from(i32::MIN) && value <= f64::from(i32::MAX) && value.fract() == 0.0)
+ .then_some(value as i32)
+}
+
+pub(crate) fn stringify(number: &Number) -> String {
+ if let Some(integer) = integer(number) {
+ return integer.to_string();
+ }
+ let value = number.as_f64().expect("finite JSON number");
+ let bits = value.abs().to_bits();
+ let encoded_exponent = ((bits >> 52) & 0x7ff) as i32;
+ let significand = bits & ((1_u64 << 52) - 1);
+ let (significand, binary_exponent) = if encoded_exponent == 0 {
+ (significand, -1074)
+ } else {
+ (significand | (1_u64 << 52), encoded_exponent - 1023 - 52)
+ };
+ let mut numerator = BigUint::from(significand);
+ let mut denominator = BigUint::from(1_u8);
+ if binary_exponent >= 0 {
+ numerator <<= binary_exponent as usize;
+ } else {
+ denominator <<= binary_exponent.unsigned_abs() as usize;
+ }
+ let mut exponent = value.abs().log10().floor() as i32;
+ let scale = 5 - exponent;
+ let power = BigUint::from(10_u8).pow(scale.unsigned_abs());
+ if scale >= 0 {
+ numerator *= power;
+ } else {
+ denominator *= power;
+ }
+ // Round the exact binary value, including halfway cases, without a
+ // second floating-point rounding when multiplying by a decimal scale.
+ let mut coefficient = &numerator / &denominator;
+ if ((&numerator % &denominator) << 1_usize) >= denominator {
+ coefficient += BigUint::from(1_u8);
+ }
+ let mut digits = coefficient.to_string();
+ if digits.len() == 7 {
+ digits.pop();
+ exponent += 1;
+ }
+ let sign = if value.is_sign_negative() { "-" } else { "" };
+ if !(-6..6).contains(&exponent) {
+ // Blink retains trailing mantissa zeros in exponential notation.
+ return format!("{sign}{}.{}e{exponent:+}", &digits[..1], &digits[1..]);
+ }
+ let fixed = if exponent < 0 {
+ format!("0.{}{digits}", "0".repeat((-exponent - 1) as usize))
+ } else {
+ let point = (exponent + 1) as usize;
+ if point < digits.len() {
+ digits.insert(point, '.');
+ }
+ digits
+ };
+ let fixed = if fixed.contains('.') {
+ fixed.trim_end_matches('0').trim_end_matches('.')
+ } else {
+ &fixed
+ };
+ format!("{sign}{fixed}")
+}
diff --git a/moli-webmcp/src/plan.rs b/moli-webmcp/src/plan.rs
new file mode 100644
index 000000000..1fb2f93b4
--- /dev/null
+++ b/moli-webmcp/src/plan.rs
@@ -0,0 +1,145 @@
+//! Validate all input and prepare native control updates before applying any.
+
+use std::collections::HashSet;
+use std::sync::Arc;
+
+use moli_dom::{
+ forms::{InputType, sanitize_input_value_for_type_with_multiple},
+ native::{DomHost, NativeNodeId, Node},
+};
+use serde_json::Value;
+
+use crate::{ParameterControls, number, schema};
+
+/// Native updates to apply in order after the complete input has been validated.
+pub enum Fill {
+ Value(NativeNodeId, String),
+ Checked(NativeNodeId, bool),
+ Select(NativeNodeId, Vec<String>),
+ Checkable {
+ handle: NativeNodeId,
+ selected: Arc<HashSet<String>>,
+ radio: bool,
+ },
+}
+
+fn scalar(value: &Value) -> Option<String> {
+ match value {
+ Value::String(value) => Some(value.clone()),
+ Value::Number(value) => Some(number::stringify(value)),
+ Value::Bool(value) => Some(value.to_string()),
+ _ => None,
+ }
+}
+
+fn boolean(value: &Value) -> Option<bool> {
+ match value {
+ Value::Bool(value) => Some(*value),
+ Value::Number(value) => Some(number::integer(value)? != 0),
+ Value::String(value) if value.eq_ignore_ascii_case("true") || value == "1" => Some(true),
+ Value::String(value) if value.eq_ignore_ascii_case("false") || value == "0" => Some(false),
+ _ => None,
+ }
+}
+
+fn values(value: &Value) -> Option<Vec<String>> {
+ let values = value
+ .as_array()?
+ .iter()
+ .map(scalar)
+ .collect::<Option<Vec<_>>>()?;
+ let unique = values.iter().collect::<HashSet<_>>();
+ (unique.len() == values.len()).then_some(values)
+}
+
+/// Validate all arguments without mutating the DOM.
+///
+/// Unknown parameters and invalid choices reject the entire fill plan.
+pub fn prepare_fill(
+ dom: &DomHost,
+ parameters: ParameterControls,
+ input: &str,
+) -> Option<Vec<Fill>> {
+ let input: indexmap::IndexMap<String, Value> = serde_json::from_str(input).ok()?;
+ let mut plan = Vec::new();
+ for (name, value) in &input {
+ let group = parameters.get(name)?;
+ let element = schema::parameter_element(dom, group)?;
+ let first = group[0];
+ if element.is_html_element("select") {
+ let multiple = element.has_attribute("multiple");
+ let selected = if multiple {
+ values(value)?
+ } else {
+ vec![scalar(value)?]
+ };
+ let options = dom.select_option_elements(first);
+ let choices = options
+ .iter()
+ .map(|option| dom.option_value(*option).expect("select option"))
+ .collect::<Vec<_>>();
+ if selected.iter().any(|value| !choices.contains(value)) {
+ return None;
+ }
+ // Earlier fields dispatch author events before this field is filled.
+ // Retain values, rather than option nodes that those events can replace.
+ plan.push(Fill::Select(first, selected));
+ } else if element.is_html_input()
+ && element.input_type() == InputType::Checkbox
+ && group.len() == 1
+ {
+ plan.push(Fill::Checked(first, boolean(value)?));
+ } else if element.is_html_input()
+ && matches!(element.input_type(), InputType::Checkbox | InputType::Radio)
+ {
+ let selected = if element.input_type() == InputType::Checkbox {
+ values(value)?
+ } else {
+ vec![scalar(value)?]
+ };
+ let choices = group
+ .iter()
+ .map(|handle| {
+ dom.node(*handle)
+ .and_then(Node::as_element)
+ .expect("parameter control")
+ .attribute("value")
+ .unwrap_or("on")
+ .to_owned()
+ })
+ .collect::<Vec<_>>();
+ if selected.iter().any(|value| !choices.contains(value)) {
+ return None;
+ }
+ let selected = Arc::new(selected.into_iter().collect::<HashSet<_>>());
+ plan.extend(group.iter().copied().map(|handle| Fill::Checkable {
+ handle,
+ selected: selected.clone(),
+ radio: element.input_type() == InputType::Radio,
+ }));
+ } else {
+ let value = scalar(value)?;
+ if element.is_html_input() {
+ let numeric = matches!(element.input_type(), InputType::Number | InputType::Range);
+ if (numeric && value.is_empty())
+ || (!value.is_empty()
+ && sanitize_input_value_for_type_with_multiple(
+ element.input_type(),
+ &value,
+ element.has_attribute("multiple"),
+ )
+ .is_empty())
+ {
+ return None;
+ }
+ }
+ let value = if element.is_html_element("textarea") {
+ value.replace("\r\n", "\n").replace('\r', "\n")
+ } else {
+ value
+ };
+ plan.push(Fill::Value(first, value));
+ }
+ }
+ Some(plan)
+}
diff --git a/moli-webmcp/src/result.rs b/moli-webmcp/src/result.rs
new file mode 100644
index 000000000..eab622761
--- /dev/null
+++ b/moli-webmcp/src/result.rs
@@ -0,0 +1,68 @@
+//! Read JSON-LD responses from a completed destination Document.
+
+use moli_dom::native::{DomHost, NativeNodeId};
+
+/// Collect parseable JSON-LD scripts in document order.
+///
+/// Legacy JSON comments are accepted for Chromium compatibility.
+pub fn navigation_result(dom: &DomHost, document: NativeNodeId) -> String {
+ let mut results = Vec::<serde_json::Value>::new();
+ for handle in dom.script_handles_in_light_subtree(document) {
+ if dom.is_html_element_named(handle, "script")
+ && dom
+ .node(handle)
+ .and_then(|node| node.as_element())
+ .and_then(|element| element.attribute("type"))
+ == Some("application/ld+json")
+ && let Some(text) = dom.text_content(handle)
+ && let Ok(value) = serde_json::from_str(&strip_json_comments(&text))
+ {
+ results.push(value);
+ }
+ }
+ serde_json::to_string(&results).expect("JSON-LD result")
+}
+
+// Chromium's legacy JSON-LD parser accepts comments, but JSON strings must
+// retain literal comment markers and escaped quotes.
+fn strip_json_comments(text: &str) -> String {
+ let mut bytes = text.as_bytes().to_vec();
+ let mut index = 0;
+ let mut quoted = false;
+ while index < bytes.len() {
+ match bytes[index] {
+ b'\\' if quoted => {
+ index += 2;
+ continue;
+ }
+ b'"' => quoted = !quoted,
+ b'/' if !quoted && bytes.get(index + 1) == Some(&b'/') => {
+ while index < bytes.len() && bytes[index] != b'\n' {
+ bytes[index] = b' ';
+ index += 1;
+ }
+ continue;
+ }
+ b'/' if !quoted && bytes.get(index + 1) == Some(&b'*') => {
+ bytes[index] = b' ';
+ bytes[index + 1] = b' ';
+ index += 2;
+ while index + 1 < bytes.len() && !(bytes[index] == b'*' && bytes[index + 1] == b'/')
+ {
+ bytes[index] = b' ';
+ index += 1;
+ }
+ if index + 1 >= bytes.len() {
+ return String::new();
+ }
+ bytes[index] = b' ';
+ bytes[index + 1] = b' ';
+ index += 2;
+ continue;
+ }
+ _ => {}
+ }
+ index += 1;
+ }
+ String::from_utf8(bytes).expect("comment replacement preserves UTF-8")
+}
diff --git a/moli-webmcp/src/schema.rs b/moli-webmcp/src/schema.rs
new file mode 100644
index 000000000..b2e757c6a
--- /dev/null
+++ b/moli-webmcp/src/schema.rs
@@ -0,0 +1,418 @@
+//! Form controls retain DOM order in their JSON schema.
+
+use moli_dom::{
+ forms::{InputType, input_step, number_step_mismatch},
+ native::{DomHost, Element, NativeNodeId, Node},
+};
+use serde::Serialize;
+use serde_json::value::{RawValue, to_raw_value};
+
+/// Eligible controls grouped by trimmed parameter names in DOM order.
+///
+/// The browser discovers form ownership and omits disabled and readonly controls.
+pub type ParameterControls = indexmap::IndexMap<String, Vec<NativeNodeId>>;
+
+#[derive(Serialize)]
+struct OrderedObject<T>(indexmap::IndexMap<String, T>);
+
+impl OrderedObject<Box<RawValue>> {
+ fn put(&mut self, key: &str, value: impl Serialize) {
+ self.0.insert(
+ key.into(),
+ to_raw_value(&value).expect("native schema value"),
+ );
+ }
+}
+
+#[derive(Serialize)]
+struct FormSchema {
+ r#type: &'static str,
+ properties: OrderedObject<OrderedObject<Box<RawValue>>>,
+ required: Vec<String>,
+}
+
+#[derive(Serialize)]
+struct Alternative<'a> {
+ r#type: &'static str,
+ r#const: &'a str,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ title: Option<String>,
+}
+
+/// Describe eligible form controls in parameter and DOM order.
+///
+/// Label ownership and HTML pattern validation remain browser responsibilities.
+pub fn input_schema(
+ dom: &DomHost,
+ parameters: ParameterControls,
+ label_handles: impl Fn(NativeNodeId) -> Vec<NativeNodeId>,
+ mut pattern_is_usable: impl FnMut(&str) -> bool,
+) -> String {
+ let mut properties = indexmap::IndexMap::new();
+ let mut required = Vec::new();
+ for (name, controls) in parameters {
+ if let Some(property) =
+ parameter_schema(dom, &controls, &label_handles, &mut pattern_is_usable)
+ {
+ if controls.iter().any(|control| {
+ dom.node(*control)
+ .and_then(Node::as_element)
+ .is_some_and(|element| element.has_attribute("required"))
+ }) {
+ required.push(name.clone());
+ }
+ properties.insert(name, property);
+ }
+ }
+ serde_json::to_string(&FormSchema {
+ r#type: "object",
+ properties: OrderedObject(properties),
+ required,
+ })
+ .expect("native WebMCP form schema")
+}
+
+// Check only the control shape. Executing a tool does not need to serialize
+// a schema or traverse labels to establish which parameters it accepts.
+pub(crate) fn parameter_element<'a>(
+ dom: &'a DomHost,
+ controls: &[NativeNodeId],
+) -> Option<&'a Element> {
+ let element = dom.node(*controls.first()?)?.as_element()?;
+ if element.is_html_element("select") || element.is_html_textarea() {
+ return (controls.len() == 1).then_some(element);
+ }
+ if !element.is_html_input() {
+ return None;
+ }
+ let kind = element.input_type();
+ if controls.iter().any(|handle| {
+ dom.node(*handle)
+ .and_then(Node::as_element)
+ .is_none_or(|input| !input.is_html_input() || input.input_type() != kind)
+ }) {
+ return None;
+ }
+ let supported = match kind {
+ InputType::Checkbox | InputType::Radio => true,
+ InputType::Hidden => {
+ controls.len() == 1
+ && element
+ .attribute("toolparamdescription")
+ .is_some_and(|value| !value.is_empty())
+ }
+ InputType::Number
+ | InputType::Range
+ | InputType::Text
+ | InputType::Search
+ | InputType::Password
+ | InputType::Tel
+ | InputType::Url
+ | InputType::Email
+ | InputType::Color
+ | InputType::Date
+ | InputType::DatetimeLocal
+ | InputType::Month
+ | InputType::Week
+ | InputType::Time => controls.len() == 1,
+ _ => false,
+ };
+ supported.then_some(element)
+}
+
+fn parameter_schema(
+ dom: &DomHost,
+ controls: &[NativeNodeId],
+ label_handles: &impl Fn(NativeNodeId) -> Vec<NativeNodeId>,
+ pattern_is_usable: &mut impl FnMut(&str) -> bool,
+) -> Option<OrderedObject<Box<RawValue>>> {
+ let element = parameter_element(dom, controls)?;
+ let mut fields = OrderedObject(indexmap::IndexMap::new());
+ if element.is_html_element("select") {
+ let options = dom.select_option_elements(controls[0]);
+ let values = options
+ .iter()
+ .map(|option| dom.option_value(*option).expect("select option"))
+ .collect::<Vec<_>>();
+ let alternatives = options
+ .iter()
+ .zip(&values)
+ .map(|(option, value)| alternative(value, Some(text_content(dom, *option))))
+ .collect::<Vec<_>>();
+ fields = choices_schema(alternatives, &values, element.has_attribute("multiple"));
+ } else if element.is_html_textarea() {
+ fields.put("type", "string");
+ } else if element.is_html_input() {
+ let kind = element.input_type();
+ match kind {
+ InputType::Checkbox if controls.len() == 1 => fields.put("type", "boolean"),
+ InputType::Checkbox | InputType::Radio => {
+ let values = controls
+ .iter()
+ .map(|control| {
+ dom.node(*control)
+ .and_then(Node::as_element)
+ .expect("input control")
+ .attribute("value")
+ .unwrap_or("on")
+ .to_owned()
+ })
+ .collect::<Vec<_>>();
+ let alternatives = values
+ .iter()
+ .zip(controls)
+ .map(|(value, control)| {
+ let title = label_text(dom, *control, label_handles);
+ alternative(value, (!title.is_empty()).then_some(title))
+ })
+ .collect::<Vec<_>>();
+ fields = choices_schema(alternatives, &values, kind == InputType::Checkbox);
+ }
+ InputType::Number | InputType::Range => {
+ fields.put("type", "number");
+ let minimum = number_attribute(element, "min")
+ .or_else(|| (kind == InputType::Range).then_some(0.0));
+ let maximum = number_attribute(element, "max")
+ .or_else(|| (kind == InputType::Range).then_some(100.0))
+ .map(|maximum| {
+ if kind == InputType::Range {
+ maximum.max(minimum.unwrap_or(0.0))
+ } else {
+ maximum
+ }
+ });
+ if let Some(value) = minimum {
+ fields.put("minimum", value);
+ }
+ if let Some(value) = maximum {
+ fields.put("maximum", value);
+ }
+ if element
+ .attribute("step")
+ .is_none_or(|step| !step.eq_ignore_ascii_case("any"))
+ {
+ let step = number_attribute(element, "step")
+ .filter(|step| *step > 0.0)
+ .unwrap_or(1.0);
+ let attribute = |name| {
+ element
+ .attribute(name)
+ .filter(|_| number_attribute(element, name).is_some())
+ };
+ if number_step_mismatch(
+ "0",
+ attribute("step"),
+ attribute("min"),
+ attribute("value"),
+ ) == Some(false)
+ {
+ fields.put("multipleOf", step);
+ }
+ }
+ }
+ InputType::Text
+ | InputType::Search
+ | InputType::Password
+ | InputType::Tel
+ | InputType::Url
+ | InputType::Email
+ | InputType::Hidden => fields.put("type", "string"),
+ InputType::Color => {
+ fields.put("type", "string");
+ fields.put("format", "^#[0-9a-zA-Z]{6}$");
+ }
+ InputType::Date
+ | InputType::DatetimeLocal
+ | InputType::Month
+ | InputType::Week
+ | InputType::Time => {
+ fields.put("type", "string");
+ fields.put("format", temporal_format(element));
+ }
+ _ => return None,
+ }
+ if matches!(
+ kind,
+ InputType::Text
+ | InputType::Search
+ | InputType::Password
+ | InputType::Tel
+ | InputType::Url
+ | InputType::Email
+ | InputType::Hidden
+ | InputType::Number
+ ) && let Some(pattern) = element.attribute("pattern")
+ && pattern_is_usable(pattern)
+ {
+ fields.put("pattern", pattern);
+ }
+ } else {
+ return None;
+ }
+ let mut description = description(dom, controls, label_handles);
+ if element.is_html_input() && element.input_type() == InputType::Date {
+ const DATE_CONTEXT: &str = "Dates MUST be provided in 'YYYY-MM-DD' format.";
+ description = if description.is_empty() {
+ DATE_CONTEXT.into()
+ } else {
+ format!("{description} ({DATE_CONTEXT})")
+ };
+ }
+ if !description.is_empty() {
+ fields.put("description", description);
+ }
+ Some(fields)
+}
+
+fn number_attribute(element: &Element, name: &str) -> Option<f64> {
+ let value = element.attribute(name)?;
+ if !matches!(*value.as_bytes().first()?, b'-' | b'.' | b'0'..=b'9') {
+ return None;
+ }
+ value.parse::<f64>().ok().filter(|value| value.is_finite())
+}
+
+fn text_content(dom: &DomHost, handle: NativeNodeId) -> String {
+ dom.text_content(handle).unwrap_or_default()
+}
+
+fn alternative(value: &str, title: Option<String>) -> Alternative<'_> {
+ Alternative {
+ r#type: "string",
+ r#const: value,
+ title,
+ }
+}
+
+fn choices_schema(
+ alternatives: Vec<Alternative<'_>>,
+ values: &[String],
+ multiple: bool,
+) -> OrderedObject<Box<RawValue>> {
+ let mut choices = OrderedObject(indexmap::IndexMap::new());
+ choices.put("type", "string");
+ choices.put("anyOf", alternatives);
+ choices.put("enum", values);
+ if multiple {
+ let mut fields = OrderedObject(indexmap::IndexMap::new());
+ fields.put("type", "array");
+ fields.put("items", choices);
+ fields.put("uniqueItems", true);
+ fields
+ } else {
+ choices
+ }
+}
+
+fn temporal_format(element: &Element) -> String {
+ match element.input_type() {
+ InputType::Date => "date".into(),
+ InputType::Month => "^[0-9]{4}-(0[1-9]|1[0-2])$".into(),
+ InputType::Week => "^[0-9]{4}-W(0[1-9]|[1-4][0-9]|5[0-3])$".into(),
+ _ => {
+ let step = input_step(
+ element.input_type(),
+ element
+ .attribute("step")
+ .filter(|_| number_attribute(element, "step").is_some()),
+ )
+ .unwrap_or(60000.0);
+ let prefix = if element.input_type() == InputType::DatetimeLocal {
+ "[0-9]{4}-(0[1-9]|1[0-2])-[0-9]{2}T"
+ } else {
+ ""
+ };
+ let seconds = if step < 1000.0 {
+ r"(:[0-5][0-9](\.[0-9]{1,3})?)?"
+ } else if step < 60000.0 {
+ "(:[0-5][0-9])?"
+ } else {
+ ""
+ };
+ format!("^{prefix}([01][0-9]|2[0-3]):[0-5][0-9]{seconds}$")
+ }
+ }
+}
+
+fn label_text(
+ dom: &DomHost,
+ control: NativeNodeId,
+ label_handles: &impl Fn(NativeNodeId) -> Vec<NativeNodeId>,
+) -> String {
+ label_handles(control)
+ .into_iter()
+ .map(|label| {
+ let mut stack = vec![label];
+ let mut text = String::new();
+ while let Some(handle) = stack.pop() {
+ let node = dom.node(handle).expect("label node");
+ if node.as_element().is_some_and(|element| {
+ matches!(
+ element.local_name(),
+ "button"
+ | "input"
+ | "meter"
+ | "output"
+ | "progress"
+ | "select"
+ | "textarea"
+ )
+ }) {
+ continue;
+ }
+ if let Some(value) = node.as_text() {
+ text.push_str(value.data());
+ }
+ stack.extend(dom.child_handles_reversed(handle));
+ }
+ text.trim().to_owned()
+ })
+ .collect::<Vec<_>>()
+ .join("; ")
+}
+
+fn description(
+ dom: &DomHost,
+ controls: &[NativeNodeId],
+ label_handles: &impl Fn(NativeNodeId) -> Vec<NativeNodeId>,
+) -> String {
+ let element = dom
+ .node(controls[0])
+ .and_then(Node::as_element)
+ .expect("parameter element");
+ if controls.len() == 1 {
+ if let Some(value) = element
+ .attribute("toolparamdescription")
+ .filter(|value| !value.is_empty())
+ {
+ return value.into();
+ }
+ let text = label_text(dom, controls[0], label_handles);
+ return if !text.is_empty() {
+ text
+ } else {
+ element
+ .attribute("aria-description")
+ .unwrap_or_default()
+ .into()
+ };
+ }
+ let mut parent = dom.parent_node(controls[0]);
+ while let Some(handle) = parent {
+ if let Some(fieldset) = dom
+ .node(handle)
+ .and_then(Node::as_element)
+ .filter(|element| element.is_html_fieldset())
+ && controls
+ .iter()
+ .all(|control| dom.contains(handle, *control))
+ {
+ return fieldset
+ .attribute("toolparamdescription")
+ .unwrap_or_default()
+ .into();
+ }
+ parent = dom.parent_node(handle);
+ }
+ String::new()
+}