1use std::io::{BufRead, BufReader, Write};
10use std::net::{TcpListener, TcpStream};
11use std::sync::Arc;
12use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
13use std::time::Duration;
14
15use serde_json::{Value, json};
16
17const MAX_CONNECTIONS: usize = 16;
19const MAX_HEADERS: u64 = 64 * 1024;
21const MAX_HEADER_LINES: usize = 100;
22const MAX_BODY: usize = 16 * 1024 * 1024;
24
25pub type Handler = Arc<dyn Fn(Value) -> Option<Value> + Send + Sync>;
27
28pub struct HttpServer {
30 port: u16,
31 stop: Arc<AtomicBool>,
32}
33
34impl HttpServer {
35 pub fn port(&self) -> u16 {
36 self.port
37 }
38
39 pub fn url(&self) -> String {
41 format!("http://127.0.0.1:{}/mcp", self.port)
42 }
43
44 pub fn stop(&self) {
45 if !self.stop.swap(true, Ordering::Relaxed) {
46 let _ = TcpStream::connect(("127.0.0.1", self.port));
48 }
49 }
50}
51
52impl Drop for HttpServer {
53 fn drop(&mut self) {
54 self.stop();
55 }
56}
57
58pub fn start(port: u16, token: String, thread: &str, handler: Handler) -> Result<HttpServer, String> {
61 if token.len() < 16 {
62 return Err("MCP: o token precisa de pelo menos 16 caracteres".into());
63 }
64 let listener = TcpListener::bind(("127.0.0.1", port)).map_err(|e| format!("MCP: porta {port}: {e}"))?;
65 let port = listener.local_addr().map_err(|e| e.to_string())?.port();
66 let stop = Arc::new(AtomicBool::new(false));
67 let flag = stop.clone();
68 let token = Arc::new(token);
69 let open = Arc::new(AtomicUsize::new(0));
70 let name = thread.to_string();
71 std::thread::Builder::new()
72 .name(name.clone())
73 .spawn(move || {
74 for stream in listener.incoming() {
75 if flag.load(Ordering::Relaxed) {
76 break;
77 }
78 let Ok(stream) = stream else { continue };
79 if open.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS {
80 open.fetch_sub(1, Ordering::SeqCst);
81 continue;
82 }
83 let (token, open, handler) = (token.clone(), open.clone(), handler.clone());
84 let spawned = std::thread::Builder::new().name(format!("{name}-conexao")).spawn({
85 let open = open.clone();
86 move || {
87 serve(stream, &token, &*handler);
88 open.fetch_sub(1, Ordering::SeqCst);
89 }
90 });
91 if spawned.is_err() {
92 open.fetch_sub(1, Ordering::SeqCst);
94 }
95 }
96 })
97 .map_err(|e| e.to_string())?;
98 Ok(HttpServer { port, stop })
99}
100
101#[derive(Debug, Default)]
103pub struct Request {
104 pub method: String,
105 pub path: String,
106 pub headers: Vec<(String, String)>,
107 pub body: Vec<u8>,
108}
109
110impl Request {
111 pub fn header(&self, name: &str) -> Option<&str> {
112 self.headers.iter().find(|(k, _)| k == name).map(|(_, v)| v.as_str())
113 }
114}
115
116pub fn read_request(reader: &mut impl BufRead) -> Option<Request> {
119 let mut head = std::io::Read::take(&mut *reader, MAX_HEADERS);
120 let mut line = String::new();
121 head.read_line(&mut line).ok()?;
122 let mut parts = line.split_whitespace();
123 let mut req = Request { method: parts.next()?.to_string(), path: parts.next()?.to_string(), ..Default::default() };
124 loop {
125 let mut h = String::new();
126 if head.read_line(&mut h).ok()? == 0 {
127 if head.limit() == 0 {
129 return None;
130 }
131 break;
132 }
133 if req.headers.len() >= MAX_HEADER_LINES {
134 return None;
135 }
136 let h = h.trim_end();
137 if h.is_empty() {
138 break;
139 }
140 if let Some((k, v)) = h.split_once(':') {
141 req.headers.push((k.trim().to_ascii_lowercase(), v.trim().to_string()));
142 }
143 }
144 let len: usize = req.header("content-length").and_then(|v| v.parse().ok()).unwrap_or(0);
145 if len > MAX_BODY {
146 return None;
147 }
148 req.body = vec![0; len];
149 reader.read_exact(&mut req.body).ok()?;
150 Some(req)
151}
152
153pub fn local_origin(origin: Option<&str>) -> bool {
155 origin.is_none_or(|o| {
156 let host = o.trim_start_matches("http://").trim_start_matches("https://");
157 let host = if host.starts_with('[') { host.split(']').next().map(|h| &h[1..]).unwrap_or_default() } else { host.split(['/', ':']).next().unwrap_or_default() };
158 matches!(host, "127.0.0.1" | "localhost" | "::1")
159 })
160}
161
162pub fn authorized(header: Option<&str>, token: &str) -> bool {
164 let Some(given) = header.and_then(|h| h.strip_prefix("Bearer ")).map(str::trim) else { return false };
165 let (a, b) = (given.as_bytes(), token.as_bytes());
166 a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
167}
168
169pub fn rpc_error(id: Value, code: i64, message: &str) -> Value {
171 json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
172}
173
174fn respond(stream: &mut TcpStream, status: &str, body: Option<&Value>) {
175 let text = body.map(|b| b.to_string()).unwrap_or_default();
176 let head = if body.is_some() {
177 format!("HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", text.len())
178 } else {
179 format!("HTTP/1.1 {status}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
180 };
181 let _ = stream.write_all(head.as_bytes());
182 let _ = stream.write_all(text.as_bytes());
183}
184
185fn serve(mut stream: TcpStream, token: &str, handler: &(dyn Fn(Value) -> Option<Value> + Send + Sync)) {
186 let _ = stream.set_read_timeout(Some(Duration::from_secs(30)));
187 let Ok(clone) = stream.try_clone() else { return };
188 let Some(req) = read_request(&mut BufReader::new(clone)) else {
189 return respond(&mut stream, "431 Request Header Fields Too Large", None);
190 };
191 if !local_origin(req.header("origin")) {
192 return respond(&mut stream, "403 Forbidden", None);
193 }
194 if !authorized(req.header("authorization"), token) {
195 return respond(&mut stream, "401 Unauthorized", None);
196 }
197 if req.path.split('?').next() != Some("/mcp") {
198 return respond(&mut stream, "404 Not Found", None);
199 }
200 if req.method != "POST" {
202 return respond(&mut stream, "405 Method Not Allowed", None);
203 }
204 let Ok(message) = serde_json::from_slice::<Value>(&req.body) else {
205 return respond(&mut stream, "400 Bad Request", Some(&rpc_error(Value::Null, -32700, "JSON inválido")));
206 };
207 let reply = match message {
208 Value::Array(batch) => {
209 let replies: Vec<Value> = batch.into_iter().filter_map(handler).collect();
210 (!replies.is_empty()).then_some(Value::Array(replies))
211 }
212 single => handler(single),
213 };
214 match reply {
215 Some(r) => respond(&mut stream, "200 OK", Some(&r)),
216 None => respond(&mut stream, "202 Accepted", None),
218 }
219}