1use 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 unrestricted: false,
131 },
132 initiator: None,
133 expected_generation: metadata
134 .get("expectedGeneration")
135 .and_then(Value::as_u64)
136 .unwrap_or_else(|| workspace.generation()),
137 expected_project_revision: metadata
138 .get("expectedProjectRevision")
139 .and_then(Value::as_u64)
140 .unwrap_or_else(|| workspace.project().revision()),
141 };
142 let call = ToolCall {
143 id: format!("mcp-{}", self.next_call.fetch_add(1, Ordering::Relaxed)),
144 name,
145 arguments,
146 };
147 workspace
148 .execute_tool(&call, &context)
149 .map_err(|error| error.to_string())
150 }
151}
152
153const LEGACY_TOOLS: &[(&str, bool)] = &[
154 ("project.read", false),
155 ("project.edit", true),
156 ("project.mkdir", true),
157 ("project.rename", true),
158 ("project.delete", true),
159 ("project.diagnostics", true),
160 ("project.run", true),
161 ("project.process.stop", true),
162 ("project.session.detach", true),
163 ("project.capsule.save", true),
164 ("project.capsule.clear", true),
165 ("project.neovim.probe", true),
166 ("project.experiment.create", true),
167 ("project.attach", true),
168 ("project.link", true),
169 ("agent.prompt", true),
170 ("agent.steer", true),
171];
172
173fn translate_legacy_execution(
174 name: &str,
175 mut arguments: Value,
176 workspace_root: &Path,
177) -> Result<(String, Value), String> {
178 let object = arguments
179 .as_object_mut()
180 .ok_or("legacy development arguments must be an object")?;
181 if let Some(root) = object.remove("root") {
182 let root = root
183 .as_str()
184 .ok_or("legacy project root must be a string")?;
185 let root = std::fs::canonicalize(root).map_err(|error| error.to_string())?;
186 if root != workspace_root {
187 return Err("legacy project tool root does not match the resident workspace".into());
188 }
189 }
190 let mapped = match name {
191 "project.read" => "glass.file.read",
192 "project.edit" => "glass.file.write",
193 "project.mkdir" => "glass.file.mkdir",
194 "project.rename" => "glass.file.rename",
195 "project.delete" => "glass.file.delete",
196 "project.diagnostics" => "glass.diagnostics.run",
197 "project.run" if object.remove("wait").and_then(|value| value.as_bool()) == Some(true) => {
198 "glass.command.run"
199 }
200 "project.run" => "glass.process.start",
201 "project.process.stop" => "glass.process.stop",
202 _ => {
203 return Err(format!(
204 "{name} is trust-gated and pending migration to the Glass Dev router"
205 ));
206 }
207 };
208 Ok((mapped.into(), arguments))
209}
210
211fn augment_schema(mut schema: Value, mutating: bool) -> Value {
212 if !schema.is_object() {
213 schema = json!({"type":"object"});
214 }
215 let object = schema
216 .as_object_mut()
217 .expect("tool schema must be an object");
218 let properties = object
219 .entry("properties")
220 .or_insert_with(|| json!({}))
221 .as_object_mut()
222 .expect("tool schema properties must be an object");
223 properties.insert(
224 "_glass".into(),
225 json!({
226 "type":"object",
227 "description":"Optional actor, authority, and stale-context guards.",
228 "properties":{
229 "actor":{"type":"string","maxLength":128},
230 "allowMutation":{"type":"boolean","default":false},
231 "confirmed":{"type":"boolean","default":false},
232 "expectedGeneration":{"type":"integer","minimum":1},
233 "expectedProjectRevision":{"type":"integer","minimum":0}
234 },
235 "additionalProperties":false,
236 "x-glass-mutating":mutating
237 }),
238 );
239 schema
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 #[test]
247 fn backend_lists_and_executes_governed_resident_tools() {
248 let root = std::env::temp_dir().join(format!("glass-mcp-backend-{}", std::process::id()));
249 let _ = std::fs::remove_dir_all(&root);
250 std::fs::create_dir_all(&root).unwrap();
251 std::fs::write(root.join("note.txt"), "resident\n").unwrap();
252 let backend = DevelopmentMcpBackend::open(&root, false).unwrap();
253 assert!(
254 backend
255 .tools()
256 .iter()
257 .any(|tool| tool.name == "glass.file.read")
258 );
259 let read = backend
260 .call("glass.file.read", json!({"path":"note.txt"}))
261 .unwrap();
262 assert_eq!(read["content"], "resident\n");
263 assert!(
264 backend
265 .call(
266 "glass.file.write",
267 json!({"path":"denied.txt","content":"no"})
268 )
269 .is_err()
270 );
271 assert!(
272 backend
273 .call(
274 "glass.file.write",
275 json!({
276 "path":"allowed.txt",
277 "content":"yes",
278 "_glass":{"allowMutation":true,"confirmed":true,"actor":"external-test"}
279 }),
280 )
281 .unwrap_err()
282 .contains("trusted")
283 );
284 assert!(!root.join("allowed.txt").exists());
285 assert!(
286 backend
287 .call(
288 "project.run",
289 json!({
290 "name":"blocked",
291 "command":if cfg!(windows) { "echo no" } else { "printf no" },
292 "wait":true,
293 "_glass":{"allowMutation":true,"confirmed":true}
294 }),
295 )
296 .unwrap_err()
297 .contains("trusted")
298 );
299 let status = backend
300 .call("glass.workspace.trust.status", json!({}))
301 .unwrap();
302 assert_eq!(status["trust"], "untrusted");
303 std::fs::remove_dir_all(root).unwrap();
304 }
305}