Open an aindrive drive as a read-only folder in Memona
The plugin reaches a drive through aindrive's remote MCP endpoint with the drive's access token. Opening a connection asks which tools the token may call, so it works while the drive's machine sleeps. Listing, stat and reading map to list_files, stat and read_file; a read is statted first, and a file whose length changed in between is refused as a conflict. Reads decode only the window asked for, straight from the reply pieces, so any 1 MiB slice of a file up to aindrive's 8 MiB limit fits Memona's per-call fuel. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,258 @@
|
||||
//! An in-memory aindrive behind the generated synchronous `Guest` API. It
|
||||
//! answers tool calls the way the drive's MCP endpoint does, as one
|
||||
//! server-sent event; live QA covers Memona's real HTTP host and the service.
|
||||
|
||||
pub use crate::sdk::host::{Header, HostError, Method, Request, Response};
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use serde_json::{Value, json};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::BTreeMap;
|
||||
use std::rc::Rc;
|
||||
|
||||
pub struct File {
|
||||
pub bytes: Vec<u8>,
|
||||
/// Written into replies verbatim, the way the device's float prints.
|
||||
pub mtime: &'static str,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Drive {
|
||||
/// Drive-relative paths. A folder is any prefix of a file, or listed here.
|
||||
pub files: BTreeMap<String, File>,
|
||||
pub folders: Vec<String>,
|
||||
/// The tools `tools/list` offers; every tool by default.
|
||||
pub tools: Option<Vec<&'static str>>,
|
||||
/// The status every request answers with, when not 200.
|
||||
pub status: Option<u16>,
|
||||
/// Replaces a file between a stat and the read that follows it.
|
||||
pub change_on_read: Option<File>,
|
||||
pub seen: Vec<Seen>,
|
||||
}
|
||||
|
||||
pub struct Seen {
|
||||
pub url: String,
|
||||
pub authorization: Option<String>,
|
||||
pub method: String,
|
||||
pub tool: Option<String>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static ACTIVE: RefCell<Option<Rc<RefCell<Drive>>>> =
|
||||
const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
pub fn install(drive: Drive) -> Rc<RefCell<Drive>> {
|
||||
let drive = Rc::new(RefCell::new(drive));
|
||||
ACTIVE.set(Some(drive.clone()));
|
||||
drive
|
||||
}
|
||||
|
||||
pub fn file(bytes: &[u8], mtime: &'static str) -> File {
|
||||
File {
|
||||
bytes: bytes.to_vec(),
|
||||
mtime,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn http(request: &Request) -> Result<Exchange, HostError> {
|
||||
if !matches!(request.method, Method::Post) {
|
||||
return Err(HostError::InvalidInput);
|
||||
}
|
||||
let drive = ACTIVE
|
||||
.with_borrow(Clone::clone)
|
||||
.ok_or(HostError::Internal)?;
|
||||
Ok(Exchange {
|
||||
drive,
|
||||
request: request.clone(),
|
||||
body: RefCell::new(Vec::new()),
|
||||
reply: RefCell::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
pub struct Exchange {
|
||||
drive: Rc<RefCell<Drive>>,
|
||||
request: Request,
|
||||
body: RefCell<Vec<u8>>,
|
||||
reply: RefCell<Option<Vec<u8>>>,
|
||||
}
|
||||
|
||||
impl Exchange {
|
||||
pub fn push(&self, data: &[u8]) -> Result<(), HostError> {
|
||||
if data.len() > 1024 * 1024 || self.reply.borrow().is_some() {
|
||||
return Err(HostError::InvalidInput);
|
||||
}
|
||||
self.body.borrow_mut().extend_from_slice(data);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn respond(&self) -> Result<Response, HostError> {
|
||||
let call: Value = serde_json::from_slice(&self.body.borrow())
|
||||
.map_err(|_| HostError::InvalidInput)?;
|
||||
let mut drive = self.drive.borrow_mut();
|
||||
let authorization = self
|
||||
.request
|
||||
.headers
|
||||
.iter()
|
||||
.find(|header| header.name == "authorization")
|
||||
.map(|header| header.value.clone());
|
||||
drive.seen.push(Seen {
|
||||
url: self.request.url.clone(),
|
||||
authorization,
|
||||
method: call["method"].as_str().unwrap_or_default().to_owned(),
|
||||
tool: call["params"]["name"].as_str().map(str::to_owned),
|
||||
});
|
||||
let (status, reply) = match drive.status {
|
||||
Some(status) => (status, b"{\"error\":\"refused\"}".to_vec()),
|
||||
None => (200, event(&drive.answer(&call))),
|
||||
};
|
||||
*self.reply.borrow_mut() = Some(reply);
|
||||
Ok(Response {
|
||||
status,
|
||||
headers: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Hands the reply over in pieces smaller than asked for, so a caller
|
||||
/// that stops at the first short piece loses the rest.
|
||||
pub fn pull(&self, limit: u32) -> Result<Vec<u8>, HostError> {
|
||||
let mut reply = self.reply.borrow_mut();
|
||||
let reply = reply.as_mut().ok_or(HostError::InvalidInput)?;
|
||||
let count = reply.len().min(limit as usize).min(4096);
|
||||
Ok(reply.drain(..count).collect())
|
||||
}
|
||||
}
|
||||
|
||||
fn event(message: &Value) -> Vec<u8> {
|
||||
format!("event: message\ndata: {message}\n\n").into_bytes()
|
||||
}
|
||||
|
||||
fn success(structured: Value) -> Value {
|
||||
json!({
|
||||
"result": {
|
||||
"_meta": { "ai.aindrive/a2ui": [] },
|
||||
"content": [{ "type": "text", "text": "ok" }],
|
||||
"structuredContent": structured,
|
||||
},
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
})
|
||||
}
|
||||
|
||||
fn failure(text: &str) -> Value {
|
||||
json!({
|
||||
"result": {
|
||||
"_meta": {},
|
||||
"content": [{ "type": "text", "text": text }],
|
||||
"isError": true,
|
||||
},
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
})
|
||||
}
|
||||
|
||||
impl Drive {
|
||||
fn answer(&mut self, call: &Value) -> Value {
|
||||
if call["method"] == "tools/list" {
|
||||
let tools = self.tools.clone().unwrap_or_else(|| {
|
||||
vec![
|
||||
"list_files",
|
||||
"read_file",
|
||||
"write_file",
|
||||
"delete_path",
|
||||
"stat",
|
||||
]
|
||||
});
|
||||
let tools: Vec<Value> =
|
||||
tools.iter().map(|name| json!({ "name": name })).collect();
|
||||
return json!({ "result": { "tools": tools }, "jsonrpc": "2.0", "id": 1 });
|
||||
}
|
||||
let arguments = &call["params"]["arguments"];
|
||||
let path = arguments["path"].as_str().unwrap_or_default().to_owned();
|
||||
match call["params"]["name"].as_str().unwrap_or_default() {
|
||||
"list_files" => match self.children(&path) {
|
||||
Some(entries) => success(json!({ "entries": entries })),
|
||||
None if self.files.contains_key(&path) => {
|
||||
failure("[internal] ENOTDIR: not a directory, scandir '/Users/me'")
|
||||
}
|
||||
None => failure("[internal] ENOENT: no such file or directory"),
|
||||
},
|
||||
"stat" if path.is_empty() => failure("[invalid_params] path required"),
|
||||
"stat" => match self.entry(&path) {
|
||||
Some(entry) => success(entry),
|
||||
None => failure(&format!("[not_found] no entry at {path}")),
|
||||
},
|
||||
"read_file" => {
|
||||
if let Some(changed) = self.change_on_read.take() {
|
||||
self.files.insert(path.clone(), changed);
|
||||
}
|
||||
match self.files.get(&path) {
|
||||
Some(file) => success(json!({
|
||||
"method": "read",
|
||||
"content": STANDARD.encode(&file.bytes),
|
||||
"encoding": "base64",
|
||||
"truncated": false,
|
||||
})),
|
||||
None if self.is_folder(&path) => failure("[internal] is a directory"),
|
||||
None => failure("[internal] ENOENT: no such file or directory"),
|
||||
}
|
||||
}
|
||||
_ => failure("[internal] unknown tool"),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_folder(&self, path: &str) -> bool {
|
||||
path.is_empty()
|
||||
|| self.folders.iter().any(|folder| folder == path)
|
||||
|| self
|
||||
.files
|
||||
.keys()
|
||||
.any(|file| file.starts_with(&format!("{path}/")))
|
||||
}
|
||||
|
||||
fn entry(&self, path: &str) -> Option<Value> {
|
||||
let name = path.rsplit('/').next().unwrap_or(path);
|
||||
if let Some(file) = self.files.get(path) {
|
||||
let entry = format!(
|
||||
r#"{{"name":{},"path":{},"isDir":false,"size":{},"mtimeMs":{}}}"#,
|
||||
json!(name),
|
||||
json!(path),
|
||||
file.bytes.len(),
|
||||
file.mtime,
|
||||
);
|
||||
return serde_json::from_str(&entry).ok();
|
||||
}
|
||||
self.is_folder(path).then(|| {
|
||||
json!({ "name": name, "path": path, "isDir": true, "size": 96,
|
||||
"mtimeMs": 1_791_726_544_422.142_f64 })
|
||||
})
|
||||
}
|
||||
|
||||
fn children(&self, path: &str) -> Option<Vec<Value>> {
|
||||
if !self.is_folder(path) {
|
||||
return None;
|
||||
}
|
||||
let prefix = if path.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!("{path}/")
|
||||
};
|
||||
let mut names: Vec<&str> = self
|
||||
.files
|
||||
.keys()
|
||||
.chain(self.folders.iter())
|
||||
.filter_map(|item| item.strip_prefix(&prefix))
|
||||
.filter_map(|rest| rest.split('/').next())
|
||||
.filter(|name| !name.is_empty())
|
||||
.collect();
|
||||
names.dedup();
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
Some(
|
||||
names
|
||||
.into_iter()
|
||||
.filter_map(|name| self.entry(&format!("{prefix}{name}")))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user