Skip to main content

glass_dev/
mcp.rs

1//! Full-product MCP tools contributed to the browser-owned transport.
2
3use crate::development::{Actor, ToolAuthorization, ToolCall};
4use crate::{DevelopmentToolContext, DevelopmentWorkspace};
5use glass_browser::mcp::server::{HostMcpTool, HostMcpToolBackend};
6use serde_json::{Value, json};
7use std::path::Path;
8use std::sync::Mutex;
9use std::sync::atomic::{AtomicU64, Ordering};
10
11const MAX_ARGUMENT_BYTES: usize = 256 * 1024;
12
13pub struct DevelopmentMcpBackend {
14    workspace: Mutex<DevelopmentWorkspace>,
15    unrestricted: bool,
16    next_call: AtomicU64,
17}
18
19impl DevelopmentMcpBackend {
20    pub fn open(root: impl AsRef<Path>, unrestricted: bool) -> Result<Self, String> {
21        Ok(Self {
22            workspace: Mutex::new(
23                DevelopmentWorkspace::open(root).map_err(|error| error.to_string())?,
24            ),
25            unrestricted,
26            next_call: AtomicU64::new(1),
27        })
28    }
29}
30
31impl HostMcpToolBackend for DevelopmentMcpBackend {
32    fn tools(&self) -> Vec<HostMcpTool> {
33        let workspace = self
34            .workspace
35            .lock()
36            .expect("development MCP workspace poisoned");
37        let mut tools = workspace
38            .tool_descriptors()
39            .into_iter()
40            .filter(|descriptor| descriptor.available)
41            .map(|descriptor| HostMcpTool {
42                name: descriptor.name,
43                description: descriptor.description,
44                input_schema: augment_schema(descriptor.input_schema, descriptor.mutating),
45            })
46            .collect::<Vec<_>>();
47        tools.extend(LEGACY_TOOLS.iter().map(|(name, mutating)| HostMcpTool {
48            name: (*name).into(),
49            description: format!(
50                "Trust-governed compatibility route for legacy development tool {name}"
51            ),
52            input_schema: augment_schema(json!({"type":"object"}), *mutating),
53        }));
54        tools
55    }
56
57    fn call(&self, name: &str, mut arguments: Value) -> Result<Value, String> {
58        if serde_json::to_vec(&arguments)
59            .map_err(|error| error.to_string())?
60            .len()
61            > MAX_ARGUMENT_BYTES
62        {
63            return Err(format!(
64                "development MCP arguments exceed {MAX_ARGUMENT_BYTES} bytes"
65            ));
66        }
67        let object = arguments
68            .as_object_mut()
69            .ok_or("development MCP arguments must be an object")?;
70        let metadata = object.remove("_glass").unwrap_or_else(|| json!({}));
71        let actor = metadata
72            .get("actor")
73            .and_then(Value::as_str)
74            .unwrap_or("mcp");
75        if actor.is_empty() || actor.len() > 128 || actor.chars().any(char::is_control) {
76            return Err("_glass.actor must contain 1..=128 non-control bytes".into());
77        }
78
79        let mut workspace = self
80            .workspace
81            .lock()
82            .map_err(|_| "development MCP workspace poisoned".to_string())?;
83        let legacy = LEGACY_TOOLS.iter().find(|(legacy, _)| *legacy == name);
84        let legacy_execution = legacy.is_some();
85        let descriptor = if legacy_execution {
86            crate::development::ToolDescriptor {
87                name: name.into(),
88                description: format!("Trust-governed compatibility route {name}"),
89                input_schema: json!({"type":"object"}),
90                mutating: legacy.expect("legacy tool checked above").1,
91                available: true,
92                unavailable_reason: None,
93            }
94        } else {
95            workspace
96                .tool_descriptors()
97                .into_iter()
98                .find(|descriptor| descriptor.name == name && descriptor.available)
99                .ok_or_else(|| format!("unknown development MCP tool {name}"))?
100        };
101        let authorized = self.unrestricted
102            || (metadata
103                .get("allowMutation")
104                .and_then(Value::as_bool)
105                .unwrap_or(false)
106                && metadata
107                    .get("confirmed")
108                    .and_then(Value::as_bool)
109                    .unwrap_or(false));
110        if descriptor.mutating && !authorized {
111            return Err(format!(
112                "{name} requires _glass.allowMutation=true and _glass.confirmed=true"
113            ));
114        }
115        let (name, arguments) = if legacy_execution {
116            if descriptor.mutating && !workspace.trust().permits_project_execution() {
117                return Err(format!(
118                    "{name} is blocked until the workspace is trusted by a local user"
119                ));
120            }
121            translate_legacy_execution(name, arguments, workspace.root())?
122        } else {
123            (name.to_string(), arguments)
124        };
125        let context = DevelopmentToolContext {
126            authorization: ToolAuthorization {
127                actor: Actor::external(actor),
128                allow_mutation: authorized,
129                confirmed: authorized,
130            },
131            initiator: None,
132            expected_generation: metadata
133                .get("expectedGeneration")
134                .and_then(Value::as_u64)
135                .unwrap_or_else(|| workspace.generation()),
136            expected_project_revision: metadata
137                .get("expectedProjectRevision")
138                .and_then(Value::as_u64)
139                .unwrap_or_else(|| workspace.project().revision()),
140        };
141        let call = ToolCall {
142            id: format!("mcp-{}", self.next_call.fetch_add(1, Ordering::Relaxed)),
143            name,
144            arguments,
145        };
146        workspace
147            .execute_tool(&call, &context)
148            .map_err(|error| error.to_string())
149    }
150}
151
152const LEGACY_TOOLS: &[(&str, bool)] = &[
153    ("project.read", false),
154    ("project.edit", true),
155    ("project.mkdir", true),
156    ("project.rename", true),
157    ("project.delete", true),
158    ("project.diagnostics", true),
159    ("project.run", true),
160    ("project.process.stop", true),
161    ("project.session.detach", true),
162    ("project.capsule.save", true),
163    ("project.capsule.clear", true),
164    ("project.neovim.probe", true),
165    ("project.experiment.create", true),
166    ("project.attach", true),
167    ("project.link", true),
168    ("agent.prompt", true),
169    ("agent.steer", true),
170];
171
172fn translate_legacy_execution(
173    name: &str,
174    mut arguments: Value,
175    workspace_root: &Path,
176) -> Result<(String, Value), String> {
177    let object = arguments
178        .as_object_mut()
179        .ok_or("legacy development arguments must be an object")?;
180    if let Some(root) = object.remove("root") {
181        let root = root
182            .as_str()
183            .ok_or("legacy project root must be a string")?;
184        let root = std::fs::canonicalize(root).map_err(|error| error.to_string())?;
185        if root != workspace_root {
186            return Err("legacy project tool root does not match the resident workspace".into());
187        }
188    }
189    let mapped = match name {
190        "project.read" => "glass.file.read",
191        "project.edit" => "glass.file.write",
192        "project.mkdir" => "glass.file.mkdir",
193        "project.rename" => "glass.file.rename",
194        "project.delete" => "glass.file.delete",
195        "project.diagnostics" => "glass.diagnostics.run",
196        "project.run" if object.remove("wait").and_then(|value| value.as_bool()) == Some(true) => {
197            "glass.command.run"
198        }
199        "project.run" => "glass.process.start",
200        "project.process.stop" => "glass.process.stop",
201        _ => {
202            return Err(format!(
203                "{name} is trust-gated and pending migration to the Glass Dev router"
204            ));
205        }
206    };
207    Ok((mapped.into(), arguments))
208}
209
210fn augment_schema(mut schema: Value, mutating: bool) -> Value {
211    if !schema.is_object() {
212        schema = json!({"type":"object"});
213    }
214    let object = schema
215        .as_object_mut()
216        .expect("tool schema must be an object");
217    let properties = object
218        .entry("properties")
219        .or_insert_with(|| json!({}))
220        .as_object_mut()
221        .expect("tool schema properties must be an object");
222    properties.insert(
223        "_glass".into(),
224        json!({
225            "type":"object",
226            "description":"Optional actor, authority, and stale-context guards.",
227            "properties":{
228                "actor":{"type":"string","maxLength":128},
229                "allowMutation":{"type":"boolean","default":false},
230                "confirmed":{"type":"boolean","default":false},
231                "expectedGeneration":{"type":"integer","minimum":1},
232                "expectedProjectRevision":{"type":"integer","minimum":0}
233            },
234            "additionalProperties":false,
235            "x-glass-mutating":mutating
236        }),
237    );
238    schema
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn backend_lists_and_executes_governed_resident_tools() {
247        let root = std::env::temp_dir().join(format!("glass-mcp-backend-{}", std::process::id()));
248        let _ = std::fs::remove_dir_all(&root);
249        std::fs::create_dir_all(&root).unwrap();
250        std::fs::write(root.join("note.txt"), "resident\n").unwrap();
251        let backend = DevelopmentMcpBackend::open(&root, false).unwrap();
252        assert!(
253            backend
254                .tools()
255                .iter()
256                .any(|tool| tool.name == "glass.file.read")
257        );
258        let read = backend
259            .call("glass.file.read", json!({"path":"note.txt"}))
260            .unwrap();
261        assert_eq!(read["content"], "resident\n");
262        assert!(
263            backend
264                .call(
265                    "glass.file.write",
266                    json!({"path":"denied.txt","content":"no"})
267                )
268                .is_err()
269        );
270        assert!(
271            backend
272                .call(
273                    "glass.file.write",
274                    json!({
275                        "path":"allowed.txt",
276                        "content":"yes",
277                        "_glass":{"allowMutation":true,"confirmed":true,"actor":"external-test"}
278                    }),
279                )
280                .unwrap_err()
281                .contains("trusted")
282        );
283        assert!(!root.join("allowed.txt").exists());
284        assert!(
285            backend
286                .call(
287                    "project.run",
288                    json!({
289                        "name":"blocked",
290                        "command":if cfg!(windows) { "echo no" } else { "printf no" },
291                        "wait":true,
292                        "_glass":{"allowMutation":true,"confirmed":true}
293                    }),
294                )
295                .unwrap_err()
296                .contains("trusted")
297        );
298        let status = backend
299            .call("glass.workspace.trust.status", json!({}))
300            .unwrap();
301        assert_eq!(status["trust"], "untrusted");
302        std::fs::remove_dir_all(root).unwrap();
303    }
304}