1use std::io::{BufRead, Read, Write};
17use std::net::TcpStream;
18use std::path::{Path, PathBuf};
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::sync::mpsc;
21use std::sync::{Arc, Mutex, RwLock};
22use std::time::Duration;
23
24use serde_json::{Value, json};
25
26static ENABLED: AtomicBool = AtomicBool::new(false);
27static BRIDGING: AtomicBool = AtomicBool::new(false);
29static APP_VERSION: RwLock<String> = RwLock::new(String::new());
30
31pub fn set_enabled(on: bool) {
33 ENABLED.store(on, Ordering::Relaxed);
34}
35
36pub fn enabled() -> bool {
38 ENABLED.load(Ordering::Relaxed)
39}
40
41pub fn set_app_version(version: &str) {
43 if let Ok(mut v) = APP_VERSION.write() {
44 *v = version.to_string();
45 }
46}
47
48pub(super) fn app_version() -> String {
49 APP_VERSION.read().map(|v| v.clone()).unwrap_or_default()
50}
51
52pub fn dir() -> Option<PathBuf> {
55 if let Some(d) = std::env::var_os("AYLIS_MCP_APPS_DIR") {
56 return Some(PathBuf::from(d));
57 }
58 if cfg!(windows) {
59 std::env::var_os("LOCALAPPDATA")
60 .map(PathBuf::from)
61 .or_else(|| std::env::var_os("USERPROFILE").map(|h| PathBuf::from(h).join("AppData").join("Local")))
62 .map(|d| d.join("aylis").join("mcp-apps"))
63 } else if cfg!(target_os = "macos") {
64 std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Library/Application Support/aylis/mcp-apps"))
65 } else {
66 std::env::var_os("XDG_DATA_HOME")
67 .map(PathBuf::from)
68 .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local/share")))
69 .map(|d| d.join("aylis").join("mcp-apps"))
70 }
71}
72
73fn exe_prefix() -> Option<String> {
75 let exe = std::env::current_exe().ok()?;
76 let exe = std::fs::canonicalize(&exe).unwrap_or(exe);
77 let text = exe.to_string_lossy().to_lowercase();
78 let hash = text.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3));
79 let stem = exe.file_stem().map(|s| sanitize(&s.to_string_lossy())).unwrap_or_default();
80 Some(format!("{stem}-{hash:016x}-"))
81}
82
83fn sanitize(text: &str) -> String {
84 text.chars().map(|c| if c.is_ascii_alphanumeric() || c == '-' || c == '_' { c } else { '_' }).collect()
85}
86
87pub(super) struct Discovery {
89 path: PathBuf,
90}
91
92impl Drop for Discovery {
93 fn drop(&mut self) {
94 let _ = std::fs::remove_file(&self.path);
95 }
96}
97
98pub(super) fn publish(name: &str, port: u16, token: &str) -> Result<Discovery, String> {
100 if BRIDGING.load(Ordering::Relaxed) {
101 return Err("MCP: este processo é a ponte stdio".into());
102 }
103 let dir = dir().ok_or("MCP: sem pasta de dados do usuário")?;
104 create_private_dir(&dir)?;
105 let prefix = exe_prefix().ok_or("MCP: não achei o executável")?;
106 let path = dir.join(format!("{prefix}{}.json", sanitize(name)));
107 let text = json!({ "name": name, "port": port, "token": token, "pid": std::process::id() }).to_string();
108 write_private(&path, text.as_bytes())?;
109 Ok(Discovery { path })
110}
111
112#[cfg(unix)]
113fn create_private_dir(dir: &Path) -> Result<(), String> {
114 use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
115 std::fs::DirBuilder::new().recursive(true).mode(0o700).create(dir).map_err(|e| format!("{}: {e}", dir.display()))?;
116 std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700)).map_err(|e| format!("{}: {e}", dir.display()))
117}
118
119#[cfg(not(unix))]
120fn create_private_dir(dir: &Path) -> Result<(), String> {
121 std::fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))
123}
124
125#[cfg(unix)]
126fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
127 use std::os::unix::fs::OpenOptionsExt;
128 let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(path).map_err(|e| format!("{}: {e}", path.display()))?;
129 f.write_all(bytes).map_err(|e| format!("{}: {e}", path.display()))
130}
131
132#[cfg(not(unix))]
133fn write_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
134 std::fs::write(path, bytes).map_err(|e| format!("{}: {e}", path.display()))
135}
136
137#[derive(Clone, Debug)]
139struct Target {
140 name: String,
141 port: u16,
142 token: String,
143}
144
145fn find(name: Option<&str>) -> Result<Option<Target>, String> {
147 let (Some(dir), Some(prefix)) = (dir(), exe_prefix()) else { return Ok(None) };
148 let Ok(entries) = std::fs::read_dir(&dir) else { return Ok(None) };
149 let mut found: Vec<Target> = entries
150 .flatten()
151 .filter(|e| e.file_name().to_string_lossy().starts_with(&prefix))
152 .filter_map(|e| serde_json::from_str::<Value>(&std::fs::read_to_string(e.path()).ok()?).ok())
153 .filter_map(|v| Some(Target { name: v["name"].as_str()?.to_string(), port: u16::try_from(v["port"].as_u64()?).ok()?, token: v["token"].as_str()?.to_string() }))
154 .collect();
155 if let Some(name) = name {
156 found.retain(|t| t.name.eq_ignore_ascii_case(name));
157 }
158 match found.len() {
159 0 => Ok(None),
160 1 => Ok(found.pop()),
161 _ => Err(format!("o app tem mais de um servidor MCP aberto ({}): passe o nome depois de --mcp-stdio", found.iter().map(|t| t.name.as_str()).collect::<Vec<_>>().join(", "))),
162 }
163}
164
165fn post(target: &Target, body: &str) -> Result<Option<String>, String> {
167 let addr = std::net::SocketAddr::from(([127, 0, 0, 1], target.port));
168 let mut s = TcpStream::connect_timeout(&addr, Duration::from_secs(3)).map_err(|e| format!("o app não respondeu ({e})"))?;
169 let _ = s.set_read_timeout(Some(Duration::from_secs(600)));
171 write!(s, "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nContent-Type: application/json\r\nAccept: application/json\r\nAuthorization: Bearer {}\r\nContent-Length: {}\r\n\r\n{body}", target.port, target.token, body.len()).map_err(|e| e.to_string())?;
172 let mut raw = Vec::new();
173 s.read_to_end(&mut raw).map_err(|e| e.to_string())?;
174 let raw = String::from_utf8_lossy(&raw);
175 let status: u16 = raw.split_whitespace().nth(1).and_then(|s| s.parse().ok()).unwrap_or(0);
176 let reply = raw.split_once("\r\n\r\n").map(|(_, b)| b.trim().to_string()).unwrap_or_default();
177 match status {
178 200 => Ok(Some(reply)),
179 202 => Ok(None),
180 _ if !reply.is_empty() => Ok(Some(reply)),
181 other => Err(format!("o app recusou o pedido (HTTP {other})")),
182 }
183}
184
185fn listen(target: &Target, out: &Output) {
187 let addr = std::net::SocketAddr::from(([127, 0, 0, 1], target.port));
188 let Ok(mut s) = TcpStream::connect_timeout(&addr, Duration::from_secs(3)) else { return };
189 if write!(s, "GET /mcp HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nAccept: text/event-stream\r\nAuthorization: Bearer {}\r\n\r\n", target.port, target.token).is_err() {
190 return;
191 }
192 let mut reader = std::io::BufReader::new(s);
193 let mut line = String::new();
194 loop {
196 line.clear();
197 match reader.read_line(&mut line) {
198 Ok(0) | Err(_) => return,
199 Ok(_) if line.trim().is_empty() => break,
200 Ok(_) if line.starts_with("HTTP/") && !line.contains(" 200 ") => return,
201 Ok(_) => {}
202 }
203 }
204 loop {
205 line.clear();
206 match reader.read_line(&mut line) {
207 Ok(0) | Err(_) => return,
208 Ok(_) => {
209 if let Some(data) = line.trim_end().strip_prefix("data:") {
210 emit(out, data.trim());
211 }
212 }
213 }
214 }
215}
216
217fn emit(out: &Output, line: &str) {
218 if let Ok(mut o) = out.lock() {
219 let _ = writeln!(o, "{line}");
220 let _ = o.flush();
221 }
222}
223
224fn rpc_error(id: Value, message: &str) -> String {
225 json!({ "jsonrpc": "2.0", "id": id, "error": { "code": -32000, "message": message } }).to_string()
226}
227
228pub fn run_bridge(server: Option<&str>) -> Result<(), String> {
232 BRIDGING.store(true, Ordering::Relaxed);
235 let out: Output = Arc::new(Mutex::new(Box::new(std::io::stdout())));
236 bridge(server, std::io::stdin().lock(), out)
237}
238
239pub type Output = Arc<Mutex<Box<dyn Write + Send>>>;
241
242pub fn bridge(server: Option<&str>, input: impl BufRead, out: Output) -> Result<(), String> {
244 let (tx, rx) = mpsc::channel::<Target>();
246 let listener_out = out.clone();
247 let _ = std::thread::Builder::new().name("aylis-mcp-avisos".into()).spawn(move || {
248 while let Ok(mut target) = rx.recv() {
249 while let Ok(t) = rx.try_recv() {
251 target = t;
252 }
253 listen(&target, &listener_out);
254 }
255 });
256 for line in input.lines() {
257 let Ok(line) = line else { break };
258 let line = line.trim();
259 if line.is_empty() {
260 continue;
261 }
262 let message: Value = match serde_json::from_str(line) {
263 Ok(v) => v,
264 Err(e) => {
265 emit(&out, &json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32700, "message": format!("JSON inválido: {e}") } }).to_string());
266 continue;
267 }
268 };
269 let id = message.get("id").cloned();
270 let answer = |text: &str| {
271 if let Some(id) = &id {
272 emit(&out, &rpc_error(id.clone(), text));
273 }
274 };
275 let target = match find(server) {
276 Ok(Some(t)) => t,
277 Ok(None) => {
278 answer("o app não está aberto (ou o servidor MCP dele está desligado): abra o app e tente de novo");
279 continue;
280 }
281 Err(e) => {
282 answer(&e);
283 continue;
284 }
285 };
286 match post(&target, line) {
287 Ok(Some(reply)) => emit(&out, &reply),
288 Ok(None) => {}
289 Err(e) => {
290 answer(&e);
291 continue;
292 }
293 }
294 let _ = tx.send(target);
296 }
297 Ok(())
298}