Skip to main content

glass_dev/
mcp.rs

1//! Full-product MCP tools contributed to the browser-owned transport.
2
3use crate::{DevelopmentToolContext, DevelopmentWorkspace};
4use glass_browser::development::{Actor, ToolAuthorization, ToolCall};
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        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()
47    }
48
49    fn call(&self, name: &str, mut arguments: Value) -> Result<Value, String> {
50        if serde_json::to_vec(&arguments)
51            .map_err(|error| error.to_string())?
52            .len()
53            > MAX_ARGUMENT_BYTES
54        {
55            return Err(format!(
56                "development MCP arguments exceed {MAX_ARGUMENT_BYTES} bytes"
57            ));
58        }
59        let object = arguments
60            .as_object_mut()
61            .ok_or("development MCP arguments must be an object")?;
62        let metadata = object.remove("_glass").unwrap_or_else(|| json!({}));
63        let actor = metadata
64            .get("actor")
65            .and_then(Value::as_str)
66            .unwrap_or("mcp");
67        if actor.is_empty() || actor.len() > 128 || actor.chars().any(char::is_control) {
68            return Err("_glass.actor must contain 1..=128 non-control bytes".into());
69        }
70
71        let mut workspace = self
72            .workspace
73            .lock()
74            .map_err(|_| "development MCP workspace poisoned".to_string())?;
75        let descriptor = workspace
76            .tool_descriptors()
77            .into_iter()
78            .find(|descriptor| descriptor.name == name && descriptor.available)
79            .ok_or_else(|| format!("unknown development MCP tool {name}"))?;
80        let authorized = self.unrestricted
81            || (metadata
82                .get("allowMutation")
83                .and_then(Value::as_bool)
84                .unwrap_or(false)
85                && metadata
86                    .get("confirmed")
87                    .and_then(Value::as_bool)
88                    .unwrap_or(false));
89        if descriptor.mutating && !authorized {
90            return Err(format!(
91                "{name} requires _glass.allowMutation=true and _glass.confirmed=true"
92            ));
93        }
94        let context = DevelopmentToolContext {
95            authorization: ToolAuthorization {
96                actor: Actor::external(actor),
97                allow_mutation: authorized,
98                confirmed: authorized,
99            },
100            expected_generation: metadata
101                .get("expectedGeneration")
102                .and_then(Value::as_u64)
103                .unwrap_or_else(|| workspace.generation()),
104            expected_project_revision: metadata
105                .get("expectedProjectRevision")
106                .and_then(Value::as_u64)
107                .unwrap_or_else(|| workspace.project().revision()),
108        };
109        let call = ToolCall {
110            id: format!("mcp-{}", self.next_call.fetch_add(1, Ordering::Relaxed)),
111            name: name.to_string(),
112            arguments,
113        };
114        workspace
115            .execute_tool(&call, &context)
116            .map_err(|error| error.to_string())
117    }
118}
119
120fn augment_schema(mut schema: Value, mutating: bool) -> Value {
121    if !schema.is_object() {
122        schema = json!({"type":"object"});
123    }
124    let object = schema
125        .as_object_mut()
126        .expect("tool schema must be an object");
127    let properties = object
128        .entry("properties")
129        .or_insert_with(|| json!({}))
130        .as_object_mut()
131        .expect("tool schema properties must be an object");
132    properties.insert(
133        "_glass".into(),
134        json!({
135            "type":"object",
136            "description":"Optional actor, authority, and stale-context guards.",
137            "properties":{
138                "actor":{"type":"string","maxLength":128},
139                "allowMutation":{"type":"boolean","default":false},
140                "confirmed":{"type":"boolean","default":false},
141                "expectedGeneration":{"type":"integer","minimum":1},
142                "expectedProjectRevision":{"type":"integer","minimum":0}
143            },
144            "additionalProperties":false,
145            "x-glass-mutating":mutating
146        }),
147    );
148    schema
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    #[test]
156    fn backend_lists_and_executes_governed_resident_tools() {
157        let root = std::env::temp_dir().join(format!("glass-mcp-backend-{}", std::process::id()));
158        let _ = std::fs::remove_dir_all(&root);
159        std::fs::create_dir_all(&root).unwrap();
160        std::fs::write(root.join("note.txt"), "resident\n").unwrap();
161        let backend = DevelopmentMcpBackend::open(&root, false).unwrap();
162        assert!(
163            backend
164                .tools()
165                .iter()
166                .any(|tool| tool.name == "glass.file.read")
167        );
168        let read = backend
169            .call("glass.file.read", json!({"path":"note.txt"}))
170            .unwrap();
171        assert_eq!(read["content"], "resident\n");
172        assert!(
173            backend
174                .call(
175                    "glass.file.write",
176                    json!({"path":"denied.txt","content":"no"})
177                )
178                .is_err()
179        );
180        backend
181            .call(
182                "glass.file.write",
183                json!({
184                    "path":"allowed.txt",
185                    "content":"yes",
186                    "_glass":{"allowMutation":true,"confirmed":true,"actor":"external-test"}
187                }),
188            )
189            .unwrap();
190        assert_eq!(
191            std::fs::read_to_string(root.join("allowed.txt")).unwrap(),
192            "yes"
193        );
194        std::fs::remove_dir_all(root).unwrap();
195    }
196}