~ knotless Search/
↑↓ move↵ open⇧↵ all results

chadtmiller.com/knotless

git that lives in your Atmosphere account

knotless.dev
1 collaborator

knotless 0.17.0 Latest 2 packages, 1 image

1
10

serve: /mcp reads pulls and issues from its own index

Merged chadtmiller.com asked to merge into main from chadtmiller.com/knotless:serve/mcp-appview
crates/knotless-serve/src/lib.rs+61−15
@@ -46,6 +46,7 @@ use knotless::records::RepoRecord;
use knotless::remote::Remote;
use knotless::url::RepoUrl;
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
@@ -752,20 +753,12 @@ pub async fn run(opts: Options, ctx: Ctx) -> Result<()> {
Some(path) => Some(Arc::new(usage::Usage::open(path)?)),
None => None,
};
// MCP over HTTP, for the accounts KNOTLESS_MCP_DIDS names.
let mcp = match (&opts.public_url, ctx.env.mcp_dids.clone()) {
(_, dids) if dids.is_empty() => Router::new(),
(Some(url), dids) => {
let mcp = knotless_mcp::http::Mcp::new(&ctx, url, dids)?;
if let Some(usage) = usage.clone() {
mcp.observe(usage::mcp_events(usage));
}
knotless_mcp::http::router(mcp)
}
(None, _) => {
anyhow::bail!("KNOTLESS_MCP_DIDS takes --public-url, where assistants reach /mcp")
}
};
// MCP over HTTP, for the accounts KNOTLESS_MCP_DIDS names, made once
// the address it reads this server's index at is known.
let mcp_ctx = ctx.clone();
if opts.public_url.is_none() && !mcp_ctx.env.mcp_dids.is_empty() {
anyhow::bail!("KNOTLESS_MCP_DIDS takes --public-url, where assistants reach /mcp")
}
let mut app = App::build(ctx, opts.ttl, gateway, index, opts.private);
if let Some(app) = Arc::get_mut(&mut app) {
app.stale = opts.stale;
@@ -796,7 +789,8 @@ pub async fn run(opts: Options, ctx: Ctx) -> Result<()> {
tokio::spawn(spaces::follow(app.clone(), SPACES));
tokio::spawn(telemetry::summaries(app.clone(), SUMMARY));
let listener = tokio::net::TcpListener::bind(&opts.listen).await?;
let listening = format!("http://{}", listener.local_addr()?);
let addr = listener.local_addr()?;
let listening = format!("http://{addr}");
println!("listening on {listening}");
telemetry::said("listening", Some(&listening));
// The numbers and the log's level, on a port of their own, kept off
@@ -804,6 +798,13 @@ pub async fn run(opts: Options, ctx: Ctx) -> Result<()> {
telemetry::serve_admin(opts.metrics.as_deref(), app.clone()).await?;
// With no pages to hand on to, what this server does not answer is not found.
let pages = opts.web.map(web::pages).unwrap_or_default();
let indexed = app.index.is_some();
let url = opts
.public_url
.as_deref()
.filter(|_| !mcp_ctx.env.mcp_dids.is_empty());
let mcp = url.map(|url| mcp_routes(mcp_ctx, url, indexed, addr, usage.clone()));
let mcp = mcp.transpose()?.unwrap_or_default();
let releases = releases::routes(opts.releases, opts.public_url);
let mut routes = router(app).merge(releases).merge(mcp).merge(pages);
if let Some(usage) = usage.clone() {
@@ -828,10 +829,55 @@ pub async fn run(opts: Options, ctx: Ctx) -> Result<()> {
Ok(())
}
/// MCP over HTTP at `url`, for the accounts KNOTLESS_MCP_DIDS names.
fn mcp_routes(
mut ctx: Ctx,
url: &str,
indexed: bool,
addr: SocketAddr,
usage: Option<Arc<usage::Usage>>,
) -> Result<Router> {
let dids = ctx.env.mcp_dids.clone();
ctx.env.appview = mcp_appview(ctx.env.appview, indexed, addr);
let mcp = knotless_mcp::http::Mcp::new(&ctx, url, dids)?;
if let Some(usage) = usage {
mcp.observe(usage::mcp_events(usage));
}
Ok(knotless_mcp::http::router(mcp))
}
/// Where MCP over HTTP finds pulls and issues on public repositories: the
/// appview named, or else this server itself when it keeps the index, at
/// `addr` on this machine.
fn mcp_appview(named: Option<String>, indexed: bool, addr: SocketAddr) -> Option<String> {
named.or_else(|| {
indexed.then(|| {
let ip = match addr.ip() {
IpAddr::V4(ip) if ip.is_unspecified() => IpAddr::V4(Ipv4Addr::LOCALHOST),
IpAddr::V6(ip) if ip.is_unspecified() => IpAddr::V6(Ipv6Addr::LOCALHOST),
ip => ip,
};
format!("http://{}", SocketAddr::new(ip, addr.port()))
})
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn mcp_reads_its_own_index() {
let at = |s: &str| s.parse::<SocketAddr>().unwrap();
let named = Some("https://appview.example".to_string());
assert_eq!(mcp_appview(named.clone(), true, at("0.0.0.0:2590")), named);
assert_eq!(mcp_appview(None, false, at("0.0.0.0:2590")), None);
let own = |addr| mcp_appview(None, true, at(addr)).unwrap();
assert_eq!(own("0.0.0.0:2590"), "http://127.0.0.1:2590");
assert_eq!(own("[::]:2590"), "http://[::1]:2590");
assert_eq!(own("10.0.0.2:2590"), "http://10.0.0.2:2590");
}
#[test]
fn input_errors() {
let bad = AppError::input(knotless::read::BadInput("no".into()).into());
crates/knotless-serve/tests/serve.rs+14−0
@@ -327,8 +327,19 @@ fn binary_lifecycle() {
])
.env("KNOTLESS_MCP_DIDS", "did:plc:someone")
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
// The sweep at startup, told of on stderr, which is read to its end.
let (swept, sweeping) = std::sync::mpsc::channel();
let stderr = std::io::BufReader::new(child.stderr.take().unwrap());
std::thread::spawn(move || {
for line in std::io::BufRead::lines(stderr).map_while(Result::ok) {
if line.contains("index sweep ended") {
let _ = swept.send(());
}
}
});
let mut out = std::io::BufReader::new(child.stdout.take().unwrap());
let mut said = |prefix: &str| {
let mut line = String::new();
@@ -378,6 +389,9 @@ fn binary_lifecycle() {
);
// The pages are handed on, here to nothing.
assert_eq!(get(&format!("{base}/someone.test")).0, 502);
// Stopped only once the sweep has finished, which it may not have
// yet on a slow machine.
sweeping.recv_timeout(Duration::from_secs(30)).unwrap();
std::process::Command::new("kill")
.args(["-TERM", &child.id().to_string()])
.status()
docs/design/serve.md+4−2
@@ -345,8 +345,10 @@ user signs in with atproto OAuth, and only a listed account gets a token.
Registrations and tokens are signed rather than stored, so removing an account
stops its tokens at their next use. Each account's sessions and mirrors have
their own directory, so no one reads as anyone else. It needs `--public-url`,
the address assistants reach. [../reference/mcp.md](../reference/mcp.md) lists
the tools.
the address assistants reach. Pulls and issues on public repositories come from
`KNOTLESS_APPVIEW`, or, unset, from this server's own index when it keeps one
(`--index`), asked over this machine's address so the reads stay off the proxy.
[../reference/mcp.md](../reference/mcp.md) lists the tools.
## Private mode