From 4c67d79d80ffe518940c039719c481e0568e9060 Mon Sep 17 00:00:00 2001 From: Worker-OCS-OPS Date: Sat, 21 Nov 2026 15:07:06 +0100 Subject: [PATCH 1/2] Civil read ops: civil_station_offset and civil_surface_stats MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two read-only query ops over the decoded civil records, in the same op/query family the MCP ocs_read facade and the headless automation server serve: - civil_station_offset: the point at an alignment's station, offset perpendicular across it (positive right of travel, the way Civil 3D offsets run). The station is the one Civil 3D shows — past a station equation it runs on from the station ahead. Curves read along their arcs at the curvature the codec solved; spirals read from the codec's solved points. - civil_surface_stats: a TIN surface's elevation bounds and triangulation counts, over the vertices its visible triangles draw. Both answer from already-decoded data; nothing writes, selects or rebuilds. --- src/app/automation.rs | 18 +- src/app/civil_query.rs | 378 +++++++++++++++++++++++++++++++++++++++++ src/app/control/mod.rs | 2 + src/app/mod.rs | 1 + src/mcp.rs | 4 +- 5 files changed, 401 insertions(+), 2 deletions(-) create mode 100644 src/app/civil_query.rs diff --git a/src/app/automation.rs b/src/app/automation.rs index 1894ec0e70..b3b8224f0b 100644 --- a/src/app/automation.rs +++ b/src/app/automation.rs @@ -13,6 +13,10 @@ //! - `{"op":"entities"}` — summary count by entity type //! - `{"op":"save","path":"out.dwg"}` — write the document (path optional //! once opened/saved) +//! - `{"op":"civil_station_offset",...}` — the point at an alignment's +//! station, offset across it (read) +//! - `{"op":"civil_surface_stats",...}` — a TIN surface's elevation +//! bounds and counts (read) #[cfg(not(target_arch = "wasm32"))] use crate::io::line_read::{lines_capped, MAX_LINE_BYTES}; @@ -583,7 +587,7 @@ fn request_point(req: &Value, key: &str) -> Option<[f64; 2]> { (x.is_finite() && y.is_finite()).then_some([x, y]) } -fn request_handle(value: &Value) -> Option { +pub(super) fn request_handle(value: &Value) -> Option { value .as_str() .and_then(|value| { @@ -1127,6 +1131,18 @@ impl OpenCADStudio { "entities" => self.entity_summary(), "audit" => self.document_audit(&req), "query" => self.entity_query(self.active_tab, &req), + "civil_station_offset" => { + crate::app::civil_query::civil_station_offset( + &self.tabs[self.active_tab].scene.document, + &req, + ) + } + "civil_surface_stats" => { + crate::app::civil_query::civil_surface_stats( + &self.tabs[self.active_tab].scene.document, + &req, + ) + } "text_search" => self.automation_text_search(&req), "text_audit" => self.automation_text_audit(&req), "text_replace" => self.automation_text_replace(&req), diff --git a/src/app/civil_query.rs b/src/app/civil_query.rs new file mode 100644 index 0000000000..c700f8429e --- /dev/null +++ b/src/app/civil_query.rs @@ -0,0 +1,378 @@ +//! Read-only civil query ops: station-offset points on alignments and TIN +//! surface statistics. +//! +//! Both ops answer from the already-decoded civil records (`ArchEntityData`) +//! without touching the document: a station-offset read solves the alignment's +//! stored design elements into a point the way Civil 3D's `GetPointAtStation` +//! does, and a surface read tallies the triangulation the record keeps. No op +//! here writes, selects, or rebuilds anything. + +use document::classes::arch::ArchEntityData; +use document::classes::civil::{AlignmentPiece, StationEquation, TinSurface}; +use document::entities::{EntityType, ExtendedEntityData}; +use document::types::Vector2; +use document::Handle; +use serde_json::{json, Value}; + +/// Chords shorter than this carry no geometry (the solver's dedup epsilon). +const EPS: f64 = 1e-9; + +/// The station length one chord of a solved piece spans: a curve's chord is +/// measured along the arc it cuts off its piece's solved curvature. +fn span_length(kind: &AlignmentPiece, curvature: &f64, a: Vector2, b: Vector2) -> f64 { + let c = a.distance(&b); + if *kind == AlignmentPiece::Curve && curvature.abs() > EPS { + let radius = 1.0 / curvature.abs(); + 2.0 * radius * (c / (2.0 * radius)).min(1.0).asin() + } else { + c + } +} + +/// The station length of a whole solved piece. +fn piece_length(piece: &(AlignmentPiece, f64, Vec)) -> f64 { + let (kind, curvature, points) = piece; + points.windows(2).map(|w| span_length(kind, curvature, w[0], w[1])).sum() +} + +fn err(msg: impl std::fmt::Display) -> Value { + json!({ "ok": false, "error": msg.to_string() }) +} + +/// The civil record of `handle`, when it is an Extended entity of `dxf_name`. +fn arch_named<'a>( + document: &'a document::Document, + handle: Handle, + dxf_name: &str, +) -> Option<&'a ArchEntityData> { + let EntityType::Extended(entity) = document.get_entity(handle)? else { + return None; + }; + let ExtendedEntityData::Arch(data) = &entity.data else { + return None; + }; + (data.dxf_name == dxf_name).then_some(data) +} + +/// The raw (geometry) distance a displayed station names. `display_station` +/// runs stations past an equation on from its station ahead; this inverts it: +/// the equation whose ahead station the shown station has passed converts +/// back to its raw anchor, the same way the drawing's station labels do. +fn raw_station(equations: &[StationEquation], shown: f64) -> f64 { + let mut raw = shown; + for equation in equations { + let passed = if equation.increasing { + shown >= equation.ahead + } else { + shown <= equation.ahead + }; + if passed { + raw = if equation.increasing { + equation.raw + (shown - equation.ahead) + } else { + equation.raw + (equation.ahead - shown) + }; + } + } + raw +} + +/// Where `distance` from the first solved run's start sits: the point and its +/// unit direction of travel. +/// +/// A curve's chords are measured along its arc at the curvature the codec +/// solved the element with (the way the codec's own station runs do), so a +/// station picks the same point whether it names a line, curve or spiral run. +pub(crate) fn point_at_distance( + pieces: &[(AlignmentPiece, f64, Vec)], + distance: f64, +) -> Option<(Vector2, [f64; 2])> { + let mut start = 0.0; + for (kind, curvature, points) in pieces { + let lengths: Vec = points + .windows(2) + .map(|w| span_length(kind, curvature, w[0], w[1])) + .collect(); + let total: f64 = lengths.iter().sum(); + // A hair past the end (rounding) still reads as the piece's end. + if distance > start + total + EPS { + start += total; + continue; + } + let local = (distance - start).clamp(0.0, total); + let mut walked = 0.0; + for (index, length) in lengths.iter().enumerate() { + if local > walked + *length + EPS { + walked += *length; + continue; + } + let (a, b) = (points[index], points[index + 1]); + let c = a.distance(&b); + if c < EPS || *length < EPS { + continue; + } + let f = ((local - walked) / *length).clamp(0.0, 1.0); + let ex = [(b.x - a.x) / c, (b.y - a.y) / c]; + if *kind == AlignmentPiece::Curve && curvature.abs() > EPS { + // The arc through the chord at the piece's solved curvature: + // its centre hangs off the chord's midpoint (left for a + // counter-clockwise piece, right for a clockwise one), and + // the chord's central angle is 2·asin(chord / 2r) — the + // same accounting that measured the piece's station length. + let radius = 1.0 / curvature.abs(); + let turn = f64::from(curvature.signum() > 0.0) * 2.0 - 1.0; + let theta = 2.0 * (c / (2.0 * radius)).min(1.0).asin(); + let mid = [(a.x + b.x) / 2.0, (a.y + b.y) / 2.0]; + let sagitta = (radius * radius - c * c / 4.0).max(0.0).sqrt(); + let center = [ + mid[0] - ex[1] * turn * sagitta, + mid[1] + ex[0] * turn * sagitta, + ]; + let (sin, cos) = (turn * f * theta).sin_cos(); + let from = [a.x - center[0], a.y - center[1]]; + let point = [ + center[0] + from[0] * cos - from[1] * sin, + center[1] + from[0] * sin + from[1] * cos, + ]; + // The chord aims at the arc's middle: the travel direction + // at fraction f turns (f - ½)·θ from it. + let (sin, cos) = (turn * (f - 0.5) * theta).sin_cos(); + let direction = [ex[0] * cos - ex[1] * sin, ex[0] * sin + ex[1] * cos]; + return Some((Vector2::new(point[0], point[1]), direction)); + } + // A line runs straight; a spiral reads from its solved points + // (the integration's sampling is the codec's spiral truth). + let point = [a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f]; + return Some((Vector2::new(point[0], point[1]), ex)); + } + return None; + } + None +} + +/// `{"op":"civil_station_offset","handle":"…","station":…,"offset":…}` — the +/// point at a station of an alignment, offset perpendicular to it. +/// +/// The station is the one Civil 3D shows (past a station equation it runs on +/// from the station ahead); the offset is signed across the alignment, +/// positive to the right of the direction of travel. Pure read: nothing in +/// the document changes. +pub(crate) fn civil_station_offset(document: &document::Document, req: &Value) -> Value { + let Some(handle) = super::automation::request_handle(&req["handle"]) else { + return err("civil_station_offset: missing or invalid \"handle\""); + }; + let Some(data) = arch_named(document, handle, "AECC_ALIGNMENT") else { + return err(format!( + "civil_station_offset: handle {:?} is not an AECC_ALIGNMENT", + req["handle"].as_str().unwrap_or_default() + )); + }; + let Some(station) = req["station"].as_f64() else { + return err("civil_station_offset: missing \"station\""); + }; + let offset = req["offset"].as_f64().unwrap_or(0.0); + let start = data.alignment_start_station().unwrap_or(0.0); + let pieces = data.alignment_pieces_with_curvature(); + let length: f64 = pieces.iter().map(piece_length).sum(); + let distance = raw_station(&data.alignment_station_equations(), station) - start; + // The solved run's length can fall a hair short of the stationing the + // record reports (integrated spirals); a station that names the end + // still reads as the end. + const END_TOLERANCE: f64 = 1e-3; + if !(-END_TOLERANCE..=length + END_TOLERANCE).contains(&distance) { + return err(format!( + "civil_station_offset: station {station:.4} is outside the alignment's stations {:.4} to {:.4}", + start, + start + length + )); + } + let distance = distance.clamp(0.0, length); + let Some((point, direction)) = point_at_distance(&pieces, distance) else { + return err("civil_station_offset: the alignment's geometry is not solved that far"); + }; + // Positive offset to the right of the direction of travel. + let at = [ + point.x + offset * direction[1], + point.y - offset * direction[0], + ]; + json!({ + "ok": true, + "handle": format!("{:X}", handle.value()), + "station": station, + "offset": offset, + "raw_station": start + distance, + "point": [at[0], at[1]], + }) +} + +/// Elevation bounds and counts of a TIN surface's drawn triangulation: the +/// vertices a visible triangle uses (a surface point outside the boundary or +/// dropped by an edit draws no triangle and carries no elevation). +pub(crate) fn surface_stats(surface: &TinSurface) -> Option<(f64, f64, usize, usize, usize)> { + let mut drawn = vec![false; surface.vertices.len()]; + let mut visible = 0usize; + for triangle in &surface.triangles { + if !triangle.is_visible() { + continue; + } + visible += 1; + for index in triangle.vertices { + if let Some(slot) = drawn.get_mut(index as usize) { + *slot = true; + } + } + } + let mut bounds: Option<(f64, f64)> = None; + for (index, used) in drawn.iter().enumerate() { + if !used { + continue; + } + let z = surface.vertices[index].position.z; + bounds = Some(match bounds { + Some((min, max)) => (min.min(z), max.max(z)), + None => (z, z), + }); + } + bounds.map(|(min, max)| (min, max, surface.vertices.len(), surface.triangles.len(), visible)) +} + +/// `{"op":"civil_surface_stats","handle":"…"}` — a TIN surface's elevation +/// bounds and triangulation counts. Pure read over the decoded record. +pub(crate) fn civil_surface_stats(document: &document::Document, req: &Value) -> Value { + let Some(handle) = super::automation::request_handle(&req["handle"]) else { + return err("civil_surface_stats: missing or invalid \"handle\""); + }; + let Some(data) = arch_named(document, handle, "AECC_TIN_SURFACE") else { + return err(format!( + "civil_surface_stats: handle {:?} is not an AECC_TIN_SURFACE", + req["handle"].as_str().unwrap_or_default() + )); + }; + // The built triangulation, falling back to the stored snapshot a surface + // keeps from its last build. + let surface = data.tin_surface().or_else(|| data.tin_snapshot()); + let Some(surface) = surface else { + return err(format!( + "civil_surface_stats: handle {:X} keeps no readable triangulation", + handle.value() + )); + }; + let Some((min, max, vertices, triangles, visible)) = surface_stats(&surface) else { + return err(format!( + "civil_surface_stats: handle {:X} draws no triangles", + handle.value() + )); + }; + json!({ + "ok": true, + "handle": format!("{:X}", handle.value()), + "min_elevation": min, + "max_elevation": max, + "vertices": vertices, + "triangles": triangles, + "visible_triangles": visible, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn line_points(points: &[(f64, f64)]) -> Vec { + points.iter().map(|(x, y)| Vector2::new(*x, *y)).collect() + } + + #[test] + fn a_station_names_its_point_on_a_line() { + let pieces = vec![(AlignmentPiece::Line, 0.0, line_points(&[(0.0, 0.0), (100.0, 0.0)]))]; + let (point, direction) = point_at_distance(&pieces, 40.0).expect("point"); + assert!((point.x - 40.0).abs() < 1e-12 && point.y.abs() < 1e-12, "{point:?}"); + assert!((direction[0] - 1.0).abs() < 1e-12 && direction[1].abs() < 1e-12); + } + + #[test] + fn a_curve_station_measures_along_the_arc() { + // A 90-degree left arc of radius 50 centred at (0, 50): from (0,0) + // to (50, 50). Its arc length is 25π, far past the 50√2 chord. + let arc = 25.0 * std::f64::consts::PI; + let pieces = vec![( + AlignmentPiece::Curve, + 1.0 / 50.0, + line_points(&[(0.0, 0.0), (50.0, 50.0)]), + )]; + let (point, _) = point_at_distance(&pieces, arc).expect("point at the arc's end"); + assert!((point.x - 50.0).abs() < 1e-9, "{point:?}"); + assert!((point.y - 50.0).abs() < 1e-9, "{point:?}"); + // Halfway along the arc the walk sits on its 45-degree mid point. + let (point, direction) = point_at_distance(&pieces, arc / 2.0) + .expect("point at the arc's mid"); + assert!((point.x - 50.0 / std::f64::consts::SQRT_2).abs() < 1e-9, "{point:?}"); + assert!((point.y - (50.0 - 50.0 / std::f64::consts::SQRT_2)).abs() < 1e-9, "{point:?}"); + // The tangent there points 45 degrees up. + assert!((direction[0] - direction[1]).abs() < 1e-9, "{direction:?}"); + } + + #[test] + fn a_clockwise_curve_bends_the_other_way() { + // A 90-degree right arc of radius 50 centred at (0, -50): from + // (0,0) heading +x it ends at (50, -50). + let arc = 25.0 * std::f64::consts::PI; + let pieces = vec![( + AlignmentPiece::Curve, + -1.0 / 50.0, + line_points(&[(0.0, 0.0), (50.0, -50.0)]), + )]; + let (point, _) = point_at_distance(&pieces, arc).expect("point at the arc's end"); + assert!((point.x - 50.0).abs() < 1e-9, "{point:?}"); + assert!((point.y + 50.0).abs() < 1e-9, "{point:?}"); + } + + #[test] + fn pieces_hand_over_at_their_joins() { + let pieces = vec![ + (AlignmentPiece::Line, 0.0, line_points(&[(0.0, 0.0), (10.0, 0.0)])), + (AlignmentPiece::Line, 0.0, line_points(&[(10.0, 0.0), (10.0, 10.0)])), + ]; + let (point, direction) = point_at_distance(&pieces, 15.0).expect("past the join"); + assert!((point.x - 10.0).abs() < 1e-12 && (point.y - 5.0).abs() < 1e-12, "{point:?}"); + assert!(direction[0].abs() < 1e-12 && (direction[1] - 1.0).abs() < 1e-12); + assert!(point_at_distance(&pieces, 20.0 + 1.0).is_none(), "past the end"); + } + + #[test] + fn a_station_equation_shifts_the_raw_distance() { + let equation = StationEquation { raw: 100.0, back: 120.0, ahead: 120.0, increasing: true }; + assert!((raw_station(&[equation], 150.0) - 130.0).abs() < 1e-12); + let decreasing = StationEquation { raw: 100.0, back: 120.0, ahead: 120.0, increasing: false }; + assert!((raw_station(&[decreasing], 90.0) - 130.0).abs() < 1e-12); + // Without an equation the shown station is the raw one. + assert!((raw_station(&[], 42.0) - 42.0).abs() < 1e-12); + // The last equation the shown station has passed wins. + let later = StationEquation { raw: 200.0, back: 210.0, ahead: 210.0, increasing: true }; + assert!((raw_station(&[equation, later], 215.0) - 205.0).abs() < 1e-12); + } + + #[test] + fn the_surface_bounds_come_from_the_drawn_triangles() { + use document::classes::civil::{TinTriangle, TinVertex}; + use document::types::Vector3; + let vertex = |x: f64, y: f64, z: f64| TinVertex { + position: Vector3::new(x, y, z), + flags: 0x80, + triangle: 0, + }; + let surface = TinSurface { + // The drawn surface spans 10..20; the fourth vertex is a corner + // whose triangles are hidden — it carries no drawn elevation. + vertices: vec![vertex(0.0, 0.0, 10.0), vertex(1.0, 0.0, 20.0), vertex(0.0, 1.0, 15.0), vertex(5.0, 5.0, 99.0)], + triangles: vec![ + TinTriangle { vertices: [0, 1, 2], neighbors: [-1, -1, -1], flags: 0 }, + TinTriangle { vertices: [0, 1, 3], neighbors: [-1, -1, -1], flags: 1 }, + ], + corners: [0, 1, 2, 3], + }; + let (min, max, vertices, triangles, visible) = surface_stats(&surface).expect("bounds"); + assert_eq!((min, max), (10.0, 20.0)); + assert_eq!((vertices, triangles, visible), (4, 2, 1)); + } +} diff --git a/src/app/control/mod.rs b/src/app/control/mod.rs index 1ff1be524b..b151cb1356 100644 --- a/src/app/control/mod.rs +++ b/src/app/control/mod.rs @@ -715,6 +715,8 @@ impl OpenCADStudio { | "snap" | "grips" | "query" + | "civil_station_offset" + | "civil_surface_stats" | "records" | "record_schema" | "capabilities" diff --git a/src/app/mod.rs b/src/app/mod.rs index bc048b8660..17a5f444bb 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -85,6 +85,7 @@ mod measurement; mod model_ops; mod civil; mod civil_packages; +mod civil_query; mod surfacing; mod solid_edit_ops; mod mtext_editor; diff --git a/src/mcp.rs b/src/mcp.rs index 044aee0de2..5ac92004d2 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -78,6 +78,8 @@ const READ_OPS: &[&str] = &[ "state", "hello", "query", + "civil_station_offset", + "civil_surface_stats", "records", "record_schema", "capabilities", @@ -2562,7 +2564,7 @@ pub(crate) fn tool_definitions() -> Value { { "name":"ocs_read", "description":"Use entity_schema with parameters.type for creation fields/examples; omit type to list. Use validate with parameters.request to check an execute request without running it (no live document checks). Use guide with parameters.name to read workflow, architecture, capture or batch-bindings guidance (omit name to list). Discover capabilities and record schemas, or read state, complete database records, command manifests, entities, blocks (semantic block instances with attributes, definition tags and dynamic properties), properties, kernel measurements and spatial relationships, history, events or operation status from a live OCS session. Use batch_result with parameters.request_id to retrieve retained batch details without executing steps; available only in the originating MCP connection, for up to 64 retained batches per session.", - "inputSchema":{"type":"object","properties":{"ocs_session_id":{"type":"string","minLength":1,"description":"Value of session_id returned by ocs_sessions."},"op":{"type":"string","enum":READ_OPS,"default":"state"},"parameters":{"type":"object","description":"Operation-specific filters.","properties":{"layout":{"type":"string","minLength":1,"description":"Layout name for op: page_setup_get."},"request":{"type":"object","description":"Execute request to preflight without dispatch. request_id may be omitted. Batch bindings are checked structurally; result-dependent values require execution."},"name":{"type":"string","description":"Command name, block name/glob, or record name."},"names":{"type":"array","items":{"type":"string"},"description":"Block name or wildcard glob filters (e.g. ['*'], ['DOOR*']) for op: blocks."},"extract_attributes":{"type":"boolean","default":true,"description":"Extract ATTRIB values, ATTDEF defaults, and visible definition text tags (e.g. TAG, DIMS) for op: blocks."},"extract_dynamic_properties":{"type":"boolean","default":true,"description":"Extract dynamic block parameters, visibility states, and lookup values for op: blocks."},"include_anonymous":{"type":"boolean","default":false,"description":"Include unlinked internal anonymous blocks (*U..., *D..., *T...) in op: blocks."},"search":{"type":"string","description":"Case-insensitive command or record-type search."},"find":{"type":"string","description":"Text query string for text_search."},"match_case":{"type":"boolean","default":false,"description":"Case-sensitive text search."},"whole_word":{"type":"boolean","default":false,"description":"Match only whole words."},"ignore_accents":{"type":"boolean","description":"Ignore accents/diacritics in text (defaults to true when match_case is false)."},"scope":{"type":"string","enum":["all","active_space","blocks"],"default":"all","description":"Text search scope."},"system_spellcheck":{"type":"boolean","default":false,"description":"Use native OS spell-checker (Windows, macOS, Linux)."},"language":{"type":"string","description":"Language tag for spell-checker (e.g. 'fr-FR', 'en-US', 'de-DE', 'es-ES')."},"suggest":{"type":"boolean","default":true,"description":"Include suggested corrections for misspelled words."},"check_terms":{"type":"array","items":{"type":"string"},"description":"List of terms or suspect misspellings to flag in text_audit."},"dictionary":{"type":"array","items":{"type":"string"},"description":"Known valid words for text_audit dictionary check."},"pairs":{"type":"array","description":"Find/replace pairs for dry-run simulation in text_audit.","items":{"type":"object","properties":{"find":{"type":"string"},"replace":{"type":"string"}},"required":["find","replace"]}},"dry_run_pairs":{"type":"array","description":"Alias for pairs in text_audit.","items":{"type":"object","properties":{"find":{"type":"string"},"replace":{"type":"string"}},"required":["find","replace"]}},"document_id":{"type":"integer","minimum":0},"path":{"type":"string","description":"Optional intended output path for audit; extension determines target format."},"target_format":{"type":"string","enum":["dwg","dxf"],"description":"Intended output format for audit."},"target_version":{"type":"string","enum":["R14","2000","2004","2007","2010","2013","2018","AC1014","AC1015","AC1018","AC1021","AC1024","AC1027","AC1032"],"description":"Intended CAD output version for audit."},"collection":{"type":"string","description":"Record collection, all for records, or omit to discover collections and schema types."},"handle":{"type":"string"},"handles":{"type":"array","items":{"type":"string"},"description":"Exact entity or record handles."},"type":{"type":"string","description":"Entity or record type filter; for record_schema, returns its complete type graph and writable field paths."},"layer":{"type":"string","description":"Layer name filter for query; * and ? are wildcards."},"xdata_app":{"type":"string","description":"Only entities carrying XDATA of this application (query)."},"detail":{"type":"string","enum":["summary","geometry","full"],"default":"geometry","description":"Entity detail returned by query."},"fields":{"type":"array","items":{"type":"string"},"description":"Return only these entity fields plus handle."},"paths":{"type":"array","items":{"type":"string"},"description":"Project RFC 6901 JSON Pointer paths relative to record.properties."},"where":{"type":"array","description":"All property filters must match.","items":{"type":"object","properties":{"path":{"type":"string"},"op":{"type":"string","enum":["eq","ne","lt","lte","gt","gte","contains","starts_with","ends_with","in","exists","not_exists"],"default":"eq"},"value":{}},"required":["path"],"additionalProperties":false}},"near":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Rank planar curves by exact kernel distance to this world XY point."},"point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"World point whose object snap the snap op reports."},"from":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Base point for perpendicular and tangent snaps (snap op)."},"contains_point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Return closed planar curves containing this world XY point."},"bounds":{"type":"array","items":{"type":"number"},"minItems":4,"maxItems":4,"description":"Filter entities whose world XY bounds overlap [min_x,min_y,max_x,max_y]."},"intersections":{"type":"array","items":{"type":"string"},"minItems":2,"maxItems":2,"description":"Return exact kernel intersections between two planar curve handles."},"after":{"type":"integer","minimum":0,"description":"Event cursor."},"request_id":{"type":"string","description":"Operation id to query."},"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":10000}},"additionalProperties":false}},"anyOf":[{"required":["ocs_session_id"]},{"required":["op"],"properties":{"op":{"enum":["guide","entity_schema","validate"]}}}],"additionalProperties":false}, + "inputSchema":{"type":"object","properties":{"ocs_session_id":{"type":"string","minLength":1,"description":"Value of session_id returned by ocs_sessions."},"op":{"type":"string","enum":READ_OPS,"default":"state"},"parameters":{"type":"object","description":"Operation-specific filters.","properties":{"layout":{"type":"string","minLength":1,"description":"Layout name for op: page_setup_get."},"request":{"type":"object","description":"Execute request to preflight without dispatch. request_id may be omitted. Batch bindings are checked structurally; result-dependent values require execution."},"name":{"type":"string","description":"Command name, block name/glob, or record name."},"names":{"type":"array","items":{"type":"string"},"description":"Block name or wildcard glob filters (e.g. ['*'], ['DOOR*']) for op: blocks."},"extract_attributes":{"type":"boolean","default":true,"description":"Extract ATTRIB values, ATTDEF defaults, and visible definition text tags (e.g. TAG, DIMS) for op: blocks."},"extract_dynamic_properties":{"type":"boolean","default":true,"description":"Extract dynamic block parameters, visibility states, and lookup values for op: blocks."},"include_anonymous":{"type":"boolean","default":false,"description":"Include unlinked internal anonymous blocks (*U..., *D..., *T...) in op: blocks."},"search":{"type":"string","description":"Case-insensitive command or record-type search."},"find":{"type":"string","description":"Text query string for text_search."},"match_case":{"type":"boolean","default":false,"description":"Case-sensitive text search."},"whole_word":{"type":"boolean","default":false,"description":"Match only whole words."},"ignore_accents":{"type":"boolean","description":"Ignore accents/diacritics in text (defaults to true when match_case is false)."},"scope":{"type":"string","enum":["all","active_space","blocks"],"default":"all","description":"Text search scope."},"system_spellcheck":{"type":"boolean","default":false,"description":"Use native OS spell-checker (Windows, macOS, Linux)."},"language":{"type":"string","description":"Language tag for spell-checker (e.g. 'fr-FR', 'en-US', 'de-DE', 'es-ES')."},"suggest":{"type":"boolean","default":true,"description":"Include suggested corrections for misspelled words."},"check_terms":{"type":"array","items":{"type":"string"},"description":"List of terms or suspect misspellings to flag in text_audit."},"dictionary":{"type":"array","items":{"type":"string"},"description":"Known valid words for text_audit dictionary check."},"pairs":{"type":"array","description":"Find/replace pairs for dry-run simulation in text_audit.","items":{"type":"object","properties":{"find":{"type":"string"},"replace":{"type":"string"}},"required":["find","replace"]}},"dry_run_pairs":{"type":"array","description":"Alias for pairs in text_audit.","items":{"type":"object","properties":{"find":{"type":"string"},"replace":{"type":"string"}},"required":["find","replace"]}},"document_id":{"type":"integer","minimum":0},"path":{"type":"string","description":"Optional intended output path for audit; extension determines target format."},"target_format":{"type":"string","enum":["dwg","dxf"],"description":"Intended output format for audit."},"target_version":{"type":"string","enum":["R14","2000","2004","2007","2010","2013","2018","AC1014","AC1015","AC1018","AC1021","AC1024","AC1027","AC1032"],"description":"Intended CAD output version for audit."},"collection":{"type":"string","description":"Record collection, all for records, or omit to discover collections and schema types."},"handle":{"type":"string"},"handles":{"type":"array","items":{"type":"string"},"description":"Exact entity or record handles."},"type":{"type":"string","description":"Entity or record type filter; for record_schema, returns its complete type graph and writable field paths."},"layer":{"type":"string","description":"Layer name filter for query; * and ? are wildcards."},"xdata_app":{"type":"string","description":"Only entities carrying XDATA of this application (query)."},"detail":{"type":"string","enum":["summary","geometry","full"],"default":"geometry","description":"Entity detail returned by query."},"fields":{"type":"array","items":{"type":"string"},"description":"Return only these entity fields plus handle."},"paths":{"type":"array","items":{"type":"string"},"description":"Project RFC 6901 JSON Pointer paths relative to record.properties."},"where":{"type":"array","description":"All property filters must match.","items":{"type":"object","properties":{"path":{"type":"string"},"op":{"type":"string","enum":["eq","ne","lt","lte","gt","gte","contains","starts_with","ends_with","in","exists","not_exists"],"default":"eq"},"value":{}},"required":["path"],"additionalProperties":false}},"near":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Rank planar curves by exact kernel distance to this world XY point."},"point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"World point whose object snap the snap op reports."},"from":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Base point for perpendicular and tangent snaps (snap op)."},"contains_point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Return closed planar curves containing this world XY point."},"bounds":{"type":"array","items":{"type":"number"},"minItems":4,"maxItems":4,"description":"Filter entities whose world XY bounds overlap [min_x,min_y,max_x,max_y]."},"intersections":{"type":"array","items":{"type":"string"},"minItems":2,"maxItems":2,"description":"Return exact kernel intersections between two planar curve handles."},"after":{"type":"integer","minimum":0,"description":"Event cursor."},"request_id":{"type":"string","description":"Operation id to query."},"offset":{"type":"number","description":"Number of matching entities to skip (query); signed perpendicular distance from the alignment, positive right of travel (civil_station_offset)."},"limit":{"type":"integer","minimum":1,"maximum":10000},"station":{"type":"number","description":"Alignment station for op: civil_station_offset."},"handle":{"type":"string"},"handles":{"type":"array","items":{"type":"string"},"description":"Exact entity or record handles."}},"additionalProperties":false}},"anyOf":[{"required":["ocs_session_id"]},{"required":["op"],"properties":{"op":{"enum":["guide","entity_schema","validate"]}}}],"additionalProperties":false}, "outputSchema":read_output_schema(), "title":"Read OCS state","annotations":{"readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false} }, From 0a0a8649aeb82435d693030a5750d8ab67b576b3 Mon Sep 17 00:00:00 2001 From: Worker-OCS-OPS Date: Sat, 21 Nov 2026 15:31:38 +0100 Subject: [PATCH 2/2] civil_station_offset: name the perpendicular distance offset_distance "offset" is a pagination keyword across the read surface; the civil op takes its own "offset_distance" so the two never share a key. Also pin the tool-schema digest for the two new read ops. --- src/app/automation.rs | 3 ++- src/app/civil_query.rs | 10 +++++----- src/mcp.rs | 4 ++-- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/app/automation.rs b/src/app/automation.rs index b3b8224f0b..0c915be661 100644 --- a/src/app/automation.rs +++ b/src/app/automation.rs @@ -14,7 +14,8 @@ //! - `{"op":"save","path":"out.dwg"}` — write the document (path optional //! once opened/saved) //! - `{"op":"civil_station_offset",...}` — the point at an alignment's -//! station, offset across it (read) +//! station, offset_distance across +//! it (read) //! - `{"op":"civil_surface_stats",...}` — a TIN surface's elevation //! bounds and counts (read) diff --git a/src/app/civil_query.rs b/src/app/civil_query.rs index c700f8429e..e1ba421f27 100644 --- a/src/app/civil_query.rs +++ b/src/app/civil_query.rs @@ -150,13 +150,13 @@ pub(crate) fn point_at_distance( None } -/// `{"op":"civil_station_offset","handle":"…","station":…,"offset":…}` — the +/// `{"op":"civil_station_offset","handle":"…","station":…,"offset_distance":…}` — the /// point at a station of an alignment, offset perpendicular to it. /// /// The station is the one Civil 3D shows (past a station equation it runs on -/// from the station ahead); the offset is signed across the alignment, -/// positive to the right of the direction of travel. Pure read: nothing in -/// the document changes. +/// from the station ahead); the `offset_distance` is signed across the +/// alignment, positive to the right of the direction of travel. Pure read: +/// nothing in the document changes. pub(crate) fn civil_station_offset(document: &document::Document, req: &Value) -> Value { let Some(handle) = super::automation::request_handle(&req["handle"]) else { return err("civil_station_offset: missing or invalid \"handle\""); @@ -170,7 +170,7 @@ pub(crate) fn civil_station_offset(document: &document::Document, req: &Value) - let Some(station) = req["station"].as_f64() else { return err("civil_station_offset: missing \"station\""); }; - let offset = req["offset"].as_f64().unwrap_or(0.0); + let offset = req["offset_distance"].as_f64().unwrap_or(0.0); let start = data.alignment_start_station().unwrap_or(0.0); let pieces = data.alignment_pieces_with_curvature(); let length: f64 = pieces.iter().map(piece_length).sum(); diff --git a/src/mcp.rs b/src/mcp.rs index 5ac92004d2..d4392174a3 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -65,7 +65,7 @@ const MODERN_PROTOCOL_VERSION: &str = "2026-07-28"; /// Find and Replace is driveable from a script: `find_replace_dialog`. /// `save` describes its `target_version` as the DWG version. #[cfg(test)] -const TOOL_SCHEMA_DIGEST: &str = "f3d8f6b3e67c70f28172dee418959de6985dd7a0ea628a4c1e09463ea6e74149"; +const TOOL_SCHEMA_DIGEST: &str = "849f9f47d34f5aa257361135967914deb9b890da9d083c22de780fe1466c66fa"; const MAX_REQUEST: usize = 1_048_576; const MAX_RESPONSE: u64 = 16 * 1024 * 1024; const CACHE_TTL_MS: u64 = 3_600_000; @@ -2564,7 +2564,7 @@ pub(crate) fn tool_definitions() -> Value { { "name":"ocs_read", "description":"Use entity_schema with parameters.type for creation fields/examples; omit type to list. Use validate with parameters.request to check an execute request without running it (no live document checks). Use guide with parameters.name to read workflow, architecture, capture or batch-bindings guidance (omit name to list). Discover capabilities and record schemas, or read state, complete database records, command manifests, entities, blocks (semantic block instances with attributes, definition tags and dynamic properties), properties, kernel measurements and spatial relationships, history, events or operation status from a live OCS session. Use batch_result with parameters.request_id to retrieve retained batch details without executing steps; available only in the originating MCP connection, for up to 64 retained batches per session.", - "inputSchema":{"type":"object","properties":{"ocs_session_id":{"type":"string","minLength":1,"description":"Value of session_id returned by ocs_sessions."},"op":{"type":"string","enum":READ_OPS,"default":"state"},"parameters":{"type":"object","description":"Operation-specific filters.","properties":{"layout":{"type":"string","minLength":1,"description":"Layout name for op: page_setup_get."},"request":{"type":"object","description":"Execute request to preflight without dispatch. request_id may be omitted. Batch bindings are checked structurally; result-dependent values require execution."},"name":{"type":"string","description":"Command name, block name/glob, or record name."},"names":{"type":"array","items":{"type":"string"},"description":"Block name or wildcard glob filters (e.g. ['*'], ['DOOR*']) for op: blocks."},"extract_attributes":{"type":"boolean","default":true,"description":"Extract ATTRIB values, ATTDEF defaults, and visible definition text tags (e.g. TAG, DIMS) for op: blocks."},"extract_dynamic_properties":{"type":"boolean","default":true,"description":"Extract dynamic block parameters, visibility states, and lookup values for op: blocks."},"include_anonymous":{"type":"boolean","default":false,"description":"Include unlinked internal anonymous blocks (*U..., *D..., *T...) in op: blocks."},"search":{"type":"string","description":"Case-insensitive command or record-type search."},"find":{"type":"string","description":"Text query string for text_search."},"match_case":{"type":"boolean","default":false,"description":"Case-sensitive text search."},"whole_word":{"type":"boolean","default":false,"description":"Match only whole words."},"ignore_accents":{"type":"boolean","description":"Ignore accents/diacritics in text (defaults to true when match_case is false)."},"scope":{"type":"string","enum":["all","active_space","blocks"],"default":"all","description":"Text search scope."},"system_spellcheck":{"type":"boolean","default":false,"description":"Use native OS spell-checker (Windows, macOS, Linux)."},"language":{"type":"string","description":"Language tag for spell-checker (e.g. 'fr-FR', 'en-US', 'de-DE', 'es-ES')."},"suggest":{"type":"boolean","default":true,"description":"Include suggested corrections for misspelled words."},"check_terms":{"type":"array","items":{"type":"string"},"description":"List of terms or suspect misspellings to flag in text_audit."},"dictionary":{"type":"array","items":{"type":"string"},"description":"Known valid words for text_audit dictionary check."},"pairs":{"type":"array","description":"Find/replace pairs for dry-run simulation in text_audit.","items":{"type":"object","properties":{"find":{"type":"string"},"replace":{"type":"string"}},"required":["find","replace"]}},"dry_run_pairs":{"type":"array","description":"Alias for pairs in text_audit.","items":{"type":"object","properties":{"find":{"type":"string"},"replace":{"type":"string"}},"required":["find","replace"]}},"document_id":{"type":"integer","minimum":0},"path":{"type":"string","description":"Optional intended output path for audit; extension determines target format."},"target_format":{"type":"string","enum":["dwg","dxf"],"description":"Intended output format for audit."},"target_version":{"type":"string","enum":["R14","2000","2004","2007","2010","2013","2018","AC1014","AC1015","AC1018","AC1021","AC1024","AC1027","AC1032"],"description":"Intended CAD output version for audit."},"collection":{"type":"string","description":"Record collection, all for records, or omit to discover collections and schema types."},"handle":{"type":"string"},"handles":{"type":"array","items":{"type":"string"},"description":"Exact entity or record handles."},"type":{"type":"string","description":"Entity or record type filter; for record_schema, returns its complete type graph and writable field paths."},"layer":{"type":"string","description":"Layer name filter for query; * and ? are wildcards."},"xdata_app":{"type":"string","description":"Only entities carrying XDATA of this application (query)."},"detail":{"type":"string","enum":["summary","geometry","full"],"default":"geometry","description":"Entity detail returned by query."},"fields":{"type":"array","items":{"type":"string"},"description":"Return only these entity fields plus handle."},"paths":{"type":"array","items":{"type":"string"},"description":"Project RFC 6901 JSON Pointer paths relative to record.properties."},"where":{"type":"array","description":"All property filters must match.","items":{"type":"object","properties":{"path":{"type":"string"},"op":{"type":"string","enum":["eq","ne","lt","lte","gt","gte","contains","starts_with","ends_with","in","exists","not_exists"],"default":"eq"},"value":{}},"required":["path"],"additionalProperties":false}},"near":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Rank planar curves by exact kernel distance to this world XY point."},"point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"World point whose object snap the snap op reports."},"from":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Base point for perpendicular and tangent snaps (snap op)."},"contains_point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Return closed planar curves containing this world XY point."},"bounds":{"type":"array","items":{"type":"number"},"minItems":4,"maxItems":4,"description":"Filter entities whose world XY bounds overlap [min_x,min_y,max_x,max_y]."},"intersections":{"type":"array","items":{"type":"string"},"minItems":2,"maxItems":2,"description":"Return exact kernel intersections between two planar curve handles."},"after":{"type":"integer","minimum":0,"description":"Event cursor."},"request_id":{"type":"string","description":"Operation id to query."},"offset":{"type":"number","description":"Number of matching entities to skip (query); signed perpendicular distance from the alignment, positive right of travel (civil_station_offset)."},"limit":{"type":"integer","minimum":1,"maximum":10000},"station":{"type":"number","description":"Alignment station for op: civil_station_offset."},"handle":{"type":"string"},"handles":{"type":"array","items":{"type":"string"},"description":"Exact entity or record handles."}},"additionalProperties":false}},"anyOf":[{"required":["ocs_session_id"]},{"required":["op"],"properties":{"op":{"enum":["guide","entity_schema","validate"]}}}],"additionalProperties":false}, + "inputSchema":{"type":"object","properties":{"ocs_session_id":{"type":"string","minLength":1,"description":"Value of session_id returned by ocs_sessions."},"op":{"type":"string","enum":READ_OPS,"default":"state"},"parameters":{"type":"object","description":"Operation-specific filters.","properties":{"layout":{"type":"string","minLength":1,"description":"Layout name for op: page_setup_get."},"request":{"type":"object","description":"Execute request to preflight without dispatch. request_id may be omitted. Batch bindings are checked structurally; result-dependent values require execution."},"name":{"type":"string","description":"Command name, block name/glob, or record name."},"names":{"type":"array","items":{"type":"string"},"description":"Block name or wildcard glob filters (e.g. ['*'], ['DOOR*']) for op: blocks."},"extract_attributes":{"type":"boolean","default":true,"description":"Extract ATTRIB values, ATTDEF defaults, and visible definition text tags (e.g. TAG, DIMS) for op: blocks."},"extract_dynamic_properties":{"type":"boolean","default":true,"description":"Extract dynamic block parameters, visibility states, and lookup values for op: blocks."},"include_anonymous":{"type":"boolean","default":false,"description":"Include unlinked internal anonymous blocks (*U..., *D..., *T...) in op: blocks."},"search":{"type":"string","description":"Case-insensitive command or record-type search."},"find":{"type":"string","description":"Text query string for text_search."},"match_case":{"type":"boolean","default":false,"description":"Case-sensitive text search."},"whole_word":{"type":"boolean","default":false,"description":"Match only whole words."},"ignore_accents":{"type":"boolean","description":"Ignore accents/diacritics in text (defaults to true when match_case is false)."},"scope":{"type":"string","enum":["all","active_space","blocks"],"default":"all","description":"Text search scope."},"system_spellcheck":{"type":"boolean","default":false,"description":"Use native OS spell-checker (Windows, macOS, Linux)."},"language":{"type":"string","description":"Language tag for spell-checker (e.g. 'fr-FR', 'en-US', 'de-DE', 'es-ES')."},"suggest":{"type":"boolean","default":true,"description":"Include suggested corrections for misspelled words."},"check_terms":{"type":"array","items":{"type":"string"},"description":"List of terms or suspect misspellings to flag in text_audit."},"dictionary":{"type":"array","items":{"type":"string"},"description":"Known valid words for text_audit dictionary check."},"pairs":{"type":"array","description":"Find/replace pairs for dry-run simulation in text_audit.","items":{"type":"object","properties":{"find":{"type":"string"},"replace":{"type":"string"}},"required":["find","replace"]}},"dry_run_pairs":{"type":"array","description":"Alias for pairs in text_audit.","items":{"type":"object","properties":{"find":{"type":"string"},"replace":{"type":"string"}},"required":["find","replace"]}},"document_id":{"type":"integer","minimum":0},"path":{"type":"string","description":"Optional intended output path for audit; extension determines target format."},"target_format":{"type":"string","enum":["dwg","dxf"],"description":"Intended output format for audit."},"target_version":{"type":"string","enum":["R14","2000","2004","2007","2010","2013","2018","AC1014","AC1015","AC1018","AC1021","AC1024","AC1027","AC1032"],"description":"Intended CAD output version for audit."},"collection":{"type":"string","description":"Record collection, all for records, or omit to discover collections and schema types."},"handle":{"type":"string"},"handles":{"type":"array","items":{"type":"string"},"description":"Exact entity or record handles."},"type":{"type":"string","description":"Entity or record type filter; for record_schema, returns its complete type graph and writable field paths."},"layer":{"type":"string","description":"Layer name filter for query; * and ? are wildcards."},"xdata_app":{"type":"string","description":"Only entities carrying XDATA of this application (query)."},"detail":{"type":"string","enum":["summary","geometry","full"],"default":"geometry","description":"Entity detail returned by query."},"fields":{"type":"array","items":{"type":"string"},"description":"Return only these entity fields plus handle."},"paths":{"type":"array","items":{"type":"string"},"description":"Project RFC 6901 JSON Pointer paths relative to record.properties."},"where":{"type":"array","description":"All property filters must match.","items":{"type":"object","properties":{"path":{"type":"string"},"op":{"type":"string","enum":["eq","ne","lt","lte","gt","gte","contains","starts_with","ends_with","in","exists","not_exists"],"default":"eq"},"value":{}},"required":["path"],"additionalProperties":false}},"near":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Rank planar curves by exact kernel distance to this world XY point."},"point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"World point whose object snap the snap op reports."},"from":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Base point for perpendicular and tangent snaps (snap op)."},"contains_point":{"type":"array","items":{"type":"number"},"minItems":2,"maxItems":3,"description":"Return closed planar curves containing this world XY point."},"bounds":{"type":"array","items":{"type":"number"},"minItems":4,"maxItems":4,"description":"Filter entities whose world XY bounds overlap [min_x,min_y,max_x,max_y]."},"intersections":{"type":"array","items":{"type":"string"},"minItems":2,"maxItems":2,"description":"Return exact kernel intersections between two planar curve handles."},"after":{"type":"integer","minimum":0,"description":"Event cursor."},"request_id":{"type":"string","description":"Operation id to query."},"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":1,"maximum":10000},"station":{"type":"number","description":"Alignment station for op: civil_station_offset."},"offset_distance":{"type":"number","description":"Signed perpendicular distance from the alignment, positive right of travel, for op: civil_station_offset."},"handle":{"type":"string"},"handles":{"type":"array","items":{"type":"string"},"description":"Exact entity or record handles."}},"additionalProperties":false}},"anyOf":[{"required":["ocs_session_id"]},{"required":["op"],"properties":{"op":{"enum":["guide","entity_schema","validate"]}}}],"additionalProperties":false}, "outputSchema":read_output_schema(), "title":"Read OCS state","annotations":{"readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false} },