use std::path::PathBuf;
use anyhow::{Context as _, Result, bail};
use openmoat_proxy::{Endpoint, Scheme};
use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;
use crate::home::Home;
pub mod discovery;
pub mod sse;
pub mod transport;
#[cfg(test)]
mod tests;
#[derive(Serialize, Deserialize)]
pub struct Record {
pub url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
}
impl Drop for Record {
fn drop(&mut self) {
if let Some(token) = &mut self.token {
zeroize::Zeroize::zeroize(token);
}
}
}
impl std::fmt::Debug for Record {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Record")
.field("url", &self.url)
.field("token", &self.token.as_ref().map(|_| "…"))
.finish()
}
}
pub fn path(home: &Home, name: &str) -> PathBuf {
let pins = super::tools::path(home, name);
let file = pins.file_name().map_or_else(
|| std::ffi::OsString::from("server.json"),
ToOwned::to_owned,
);
home.root().join("mcp-remote").join(file)
}
impl Record {
pub fn load(home: &Home, name: &str) -> Result<Option<Self>> {
let path = path(home, name);
let text = match std::fs::read(&path) {
Ok(text) => Zeroizing::new(text),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
};
let record =
serde_json::from_slice(&text).with_context(|| format!("reading {}", path.display()))?;
Ok(Some(record))
}
pub fn save(&self, home: &Home, name: &str) -> Result<()> {
let text = Zeroizing::new(serde_json::to_vec_pretty(self)?);
crate::home::write_private(&path(home, name), &text)
}
}
pub fn endpoint(url: &str) -> Result<Endpoint> {
let endpoint = Endpoint::parse(url).map_err(|e| anyhow::Error::msg(e.to_string()))?;
if endpoint.host.parse::<std::net::IpAddr>().is_err() {
let last = endpoint.host.rsplit('.').next().unwrap_or("");
if last.bytes().all(|b| b.is_ascii_digit()) || last.starts_with("0x") {
bail!("`{url}` names an address in an unusual notation");
}
}
if endpoint.scheme == Scheme::Http && endpoint.host.eq_ignore_ascii_case("localhost") {
bail!("`{url}`: plain http goes to 127.0.0.1 or [::1], not to a name");
}
Ok(endpoint)
}
pub fn origin(endpoint: &Endpoint) -> String {
let scheme = match endpoint.scheme {
Scheme::Http => "http",
Scheme::Https => "https",
};
let host = if endpoint.host.contains(':') {
format!("[{}]", endpoint.host)
} else {
endpoint.host.clone()
};
format!("{scheme}://{host}:{}", endpoint.port)
}
pub fn failed_answer(message: &str, why: &str) -> Option<String> {
let request: serde_json::Value = serde_json::from_str(message).ok()?;
request.get("method")?;
let id = request.get("id").filter(|id| !id.is_null())?;
let answer = serde_json::json!({
"jsonrpc": "2.0",
"id": id,
"error": {
"code": -32603,
"message": format!("OpenMoat could not reach the remote MCP server: {why}"),
},
});
Some(answer.to_string())
}
pub fn admitted(home: &Home, server: &str, url: &str) -> Result<Record> {
let wanted = endpoint(url)?;
let Some(record) = Record::load(home, server)? else {
bail!(
"no person has named remote MCP server `{server}`; run `openmoat mcp login {server} \
--url {}` in a terminal (docs/USAGE.md \"Remote MCP servers\")",
origin(&wanted)
);
};
let pinned = endpoint(&record.url)?;
if pinned != wanted {
bail!(
"remote MCP server `{server}` was named with {}, not {}; if the server moved, run \
`openmoat mcp login {server} --url <new url>` in a terminal",
origin(&pinned),
origin(&wanted)
);
}
Ok(record)
}