chadtmiller.com/group-host
atmosphere group host
0
0
Assistants act as a member in one group, over MCP
crates/group-host/src/assistants.rsnew+798−0
798 lines changed: not loaded until asked for.
crates/group-host/src/authorization.rs+19−4
| @@ -8,6 +8,7 @@ | ||
| ||
use crate::Host; | ||
use crate::api::{Params, invalid, param}; | ||
use crate::assistants; | ||
use crate::group::meta_space; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::oauth_scope::{concrete, configure}; | ||
| @@ -80,7 +81,7 @@ impl Host { | ||
| ||
/// A group as the approval page shows it to `member`: what of its | ||
/// profile they may read, their roles, and what the app would get. | ||
fn offered(&self, group: &str, member: &str, requested: &[String]) -> Answer { | ||
pub(crate) fn offered(&self, group: &str, member: &str, requested: &[String]) -> Answer { | ||
let handle = group_of(self, group)?; | ||
let roles = self.roles(group, member).map_err(XrpcError::internal)?; | ||
let granted = match roles.is_empty() { | ||
| @@ -146,7 +147,11 @@ pub async fn get_authorization( | ||
headers: HeaderMap, | ||
) -> Answer { | ||
let me = signed_in(&host, &headers, &format!("{NS}.getAuthorization")).await?; | ||
let request = pending(&host, param(&p, "requestUri")?)?; | ||
let uri = param(&p, "requestUri")?; | ||
if uri.starts_with(assistants::PREFIX) { | ||
return Ok(Json(assistants::assistant_view(&host, uri, &me)?)); | ||
} | ||
let request = pending(&host, uri)?; | ||
let requested = requested(&request); | ||
let metadata = host.client(&request.client_id, now_millis()).await; | ||
let metadata = metadata.map(|c| c.metadata).unwrap_or_default(); | ||
| @@ -189,9 +194,14 @@ pub async fn approve_authorization( | ||
) -> Answer { | ||
let me = signed_in(&host, &headers, &format!("{NS}.approveAuthorization")).await?; | ||
let uri = body["requestUri"].as_str(); | ||
let request = pending(&host, uri.ok_or_else(|| invalid("requestUri is required"))?)?; | ||
let uri = uri.ok_or_else(|| invalid("requestUri is required"))?; | ||
let group = body["group"].as_str(); | ||
let group = group.ok_or_else(|| invalid("group is required"))?; | ||
if uri.starts_with(assistants::PREFIX) { | ||
let redirect = assistants::approve(&host, uri, &me, group)?; | ||
return Ok(Json(json!({ "redirectUrl": redirect }))); | ||
} | ||
let request = pending(&host, uri)?; | ||
group_of(&host, group)?; | ||
host.active(group)?; | ||
let named = host.named_group(&request)?; | ||
| @@ -226,7 +236,12 @@ pub async fn decline_authorization( | ||
) -> Answer { | ||
signed_in(&host, &headers, &format!("{NS}.declineAuthorization")).await?; | ||
let uri = body["requestUri"].as_str(); | ||
let request = pending(&host, uri.ok_or_else(|| invalid("requestUri is required"))?)?; | ||
let uri = uri.ok_or_else(|| invalid("requestUri is required"))?; | ||
if uri.starts_with(assistants::PREFIX) { | ||
let redirect = assistants::decline(&host, uri)?; | ||
return Ok(Json(json!({ "redirectUrl": redirect }))); | ||
} | ||
let request = pending(&host, uri)?; | ||
let declined = host.decline_request(&request); | ||
let redirect = declined.map_err(XrpcError::internal)?.ok_or_else(expired)?; | ||
Ok(Json(json!({ "redirectUrl": redirect }))) | ||
crates/group-host/src/console_login.rs+1−1
| @@ -187,7 +187,7 @@ impl Host { | ||
} | ||
| ||
/// A session cookie's value, naming `did`, signed `now`. | ||
fn session_cookie(&self, did: &str, now: i64) -> String { | ||
pub(crate) fn session_cookie(&self, did: &str, now: i64) -> String { | ||
let claims = jose::b64(json!({"did": did, "iat": now, "exp": now + LASTS}).to_string()); | ||
format!( | ||
"{claims}.{}", | ||
crates/group-host/src/lib.rs+21−0
| @@ -6,6 +6,7 @@ | ||
pub mod actors; | ||
pub mod api; | ||
pub mod app_passwords; | ||
pub mod assistants; | ||
pub mod authority; | ||
pub mod authority_api; | ||
pub mod authorization; | ||
| @@ -459,6 +460,26 @@ fn oauth_routes() -> Router<Arc<Host>> { | ||
.route("/oauth/par", post(oauth::par)) | ||
.route("/oauth/token", post(oauth::token)) | ||
.route("/oauth/revoke", post(oauth::revoke)) | ||
.route( | ||
"/.well-known/oauth-protected-resource/mcp", | ||
get(assistants::resource_metadata), | ||
) | ||
.route( | ||
"/.well-known/oauth-authorization-server/mcp", | ||
get(assistants::server_metadata), | ||
) | ||
.route("/mcp", post(assistants::mcp)) | ||
.route("/mcp/register", post(assistants::register)) | ||
.route("/mcp/authorize", get(assistants::authorize)) | ||
.route("/mcp/token", post(assistants::token)) | ||
.route( | ||
"/xrpc/fyi.opensocial.listConnectedApps", | ||
get(assistants::list_connected_apps), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.revokeConnectedApp", | ||
post(assistants::revoke_connected_app), | ||
) | ||
.layer(axum::middleware::from_fn(oauth::cors)) | ||
} | ||
| ||
crates/group-host/src/oauth_store.rs+3−0
| @@ -399,6 +399,9 @@ impl Store { | ||
/// no more once they are out of it. | ||
pub fn revoke_member_grants(&self, group: &str, member: &str) -> Result<usize> { | ||
let conn = self.conn(); | ||
// Their assistants, too, act as them no more. | ||
let sql = "DELETE FROM assistant_grant WHERE grp = ?1 AND member = ?2"; | ||
conn.execute(sql, [group, member])?; | ||
Ok(conn.execute(REVOKE_MEMBER, [group, member])?) | ||
} | ||
} | ||
crates/group-host/src/store.rs+36−0
| @@ -343,6 +343,40 @@ pub const MIGRATIONS: &[&str] = &[ | ||
description TEXT, | ||
created_at INTEGER NOT NULL | ||
); | ||
", | ||
" | ||
CREATE TABLE assistant_client ( | ||
id TEXT PRIMARY KEY, | ||
name TEXT NOT NULL, | ||
redirect_uris TEXT NOT NULL, | ||
created_at INTEGER NOT NULL | ||
); | ||
CREATE TABLE assistant_request ( | ||
id TEXT PRIMARY KEY, | ||
client_id TEXT NOT NULL, | ||
client_name TEXT NOT NULL, | ||
redirect_uri TEXT NOT NULL, | ||
state TEXT, | ||
code_challenge TEXT NOT NULL, | ||
expires_at INTEGER NOT NULL, | ||
grp TEXT REFERENCES account (did), | ||
member TEXT, | ||
code_hash TEXT UNIQUE | ||
); | ||
CREATE TABLE assistant_grant ( | ||
id TEXT PRIMARY KEY, | ||
grp TEXT NOT NULL REFERENCES account (did), | ||
member TEXT NOT NULL, | ||
client_id TEXT NOT NULL, | ||
client_name TEXT NOT NULL, | ||
access_hash TEXT NOT NULL UNIQUE, | ||
access_expires INTEGER NOT NULL, | ||
refresh_hash TEXT NOT NULL UNIQUE, | ||
expires_at INTEGER NOT NULL, | ||
created_at INTEGER NOT NULL, | ||
used_at INTEGER NOT NULL | ||
); | ||
CREATE INDEX assistant_grant_member ON assistant_grant (grp, member); | ||
", | ||
]; | ||
| ||
| @@ -461,6 +495,8 @@ const DEACTIVATION: &str = "SELECT at, by, stewards FROM deactivation WHERE did | ||
const ACTIVATE: &str = "DELETE FROM deactivation WHERE did = ?1"; | ||
/// What goes with an account, in an order its references allow. | ||
const FORGET_ACCOUNT: &[&str] = &[ | ||
"DELETE FROM assistant_grant WHERE grp = ?1", | ||
"DELETE FROM assistant_request WHERE grp = ?1", | ||
"DELETE FROM account_import WHERE did = ?1", | ||
"DELETE FROM migration_export WHERE did = ?1", | ||
"DELETE FROM recovery_key WHERE grp = ?1", | ||
crates/group-host/tests/assistants.rsnew+717−0
717 lines changed: not loaded until asked for.
crates/group-host/Cargo.toml+2−0
| @@ -11,6 +11,7 @@ atproto.workspace = true | ||
anyhow.workspace = true | ||
axum.workspace = true | ||
futures.workspace = true | ||
group-host-mcp.workspace = true | ||
hmac.workspace = true | ||
rand_core.workspace = true | ||
reqwest.workspace = true | ||
| @@ -19,6 +20,7 @@ serde.workspace = true | ||
serde_json.workspace = true | ||
sha2.workspace = true | ||
tokio.workspace = true | ||
tower.workspace = true | ||
tracing.workspace = true | ||
tracing-subscriber.workspace = true | ||
| ||
crates/group-host-mcp/src/lib.rs+315−1
| @@ -3,4 +3,318 @@ | ||
//! may do only what that member's roles allow: read the group, and run its | ||
//! members, roles, invites and moderation. | ||
//! | ||
//! The tools arrive with the methods they call; see `docs/design/README.md`. | ||
//! This crate is the protocol and the tools: what an assistant may call, | ||
//! made from the methods' lexicons, and the answer to each message it | ||
//! sends (JSON-RPC, over MCP's Streamable HTTP, each answered on its own). | ||
//! The host serves it at `/mcp`, signs assistants in, and makes each call: | ||
//! as the member, in the one group they connected the assistant to, which | ||
//! is why no tool asks which group. | ||
| ||
use serde_json::{Map, Value, json}; | ||
use std::collections::HashMap; | ||
| ||
/// The versions of MCP this server speaks, the latest first. | ||
pub const PROTOCOL_VERSIONS: [&str; 3] = ["2025-06-18", "2025-03-26", "2024-11-05"]; | ||
| ||
/// What the server tells an assistant of itself as it connects. | ||
const INSTRUCTIONS: &str = "The tools act as the person who connected you, in the one group \ | ||
they chose, with what their roles there allow: read the group, and run its members, roles, \ | ||
rules, invites, spaces and moderation. Anything their roles do not allow is refused."; | ||
| ||
macro_rules! lexicon { | ||
($name:literal) => { | ||
( | ||
concat!("fyi.opensocial.", $name), | ||
include_str!(concat!("../../../lexicons/fyi/opensocial/", $name, ".json")), | ||
) | ||
}; | ||
} | ||
| ||
/// The methods an assistant may call, by their lexicons. | ||
const METHODS: &[(&str, &str)] = &[ | ||
lexicon!("getGroup"), | ||
lexicon!("updateProfile"), | ||
lexicon!("putRule"), | ||
lexicon!("deleteRule"), | ||
lexicon!("putRole"), | ||
lexicon!("deleteRole"), | ||
lexicon!("assignRoles"), | ||
lexicon!("listJoinRequests"), | ||
lexicon!("admitMember"), | ||
lexicon!("denyJoinRequest"), | ||
lexicon!("listInvites"), | ||
lexicon!("createInvite"), | ||
lexicon!("revokeInvite"), | ||
lexicon!("ejectMember"), | ||
lexicon!("createSpace"), | ||
lexicon!("listSpaceRecords"), | ||
lexicon!("listSubjects"), | ||
lexicon!("getSubjectHistory"), | ||
lexicon!("applyLabel"), | ||
lexicon!("negateLabel"), | ||
lexicon!("resolveSubject"), | ||
]; | ||
| ||
/// What the methods refer to: ours, and atproto's. | ||
const REFERRED: &[(&str, &str)] = &[ | ||
lexicon!("defs"), | ||
lexicon!("access"), | ||
( | ||
"com.atproto.admin.defs", | ||
include_str!("../../../lexicons/upstream/com/atproto/admin/defs.json"), | ||
), | ||
( | ||
"com.atproto.repo.strongRef", | ||
include_str!("../../../lexicons/upstream/com/atproto/repo/strongRef.json"), | ||
), | ||
]; | ||
| ||
/// A tool: a method of the host's, asked in the group the assistant was | ||
/// connected to. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Tool { | ||
/// Its name, the method's: `getGroup`. | ||
pub name: String, | ||
/// The method, `fyi.opensocial.getGroup`. | ||
pub nsid: String, | ||
/// Whether it is a procedure (a POST of JSON), not a query. | ||
pub procedure: bool, | ||
pub description: String, | ||
/// What it takes, as JSON Schema: the method's parameters or input, | ||
/// but the group. | ||
pub input_schema: Value, | ||
} | ||
| ||
/// The lexicons by NSID, to resolve references in. | ||
struct Docs(HashMap<String, Value>); | ||
| ||
/// `from`'s fields, as `(theirs, ours)`, into `to`. | ||
fn copy(from: &Value, to: &mut Value, fields: &[(&str, &str)]) { | ||
for (theirs, ours) in fields { | ||
if let Some(v) = from.get(*theirs) { | ||
to[*ours] = v.clone(); | ||
} | ||
} | ||
} | ||
| ||
impl Docs { | ||
fn load() -> Docs { | ||
let all = METHODS.iter().chain(REFERRED); | ||
let parsed = all.map(|(nsid, text)| { | ||
let doc = serde_json::from_str(text).expect("a lexicon is JSON"); | ||
(nsid.to_string(), doc) | ||
}); | ||
Docs(parsed.collect()) | ||
} | ||
| ||
/// The def `reference` names, from within `doc`: `#name`, `nsid#name`, | ||
/// or `nsid` for its main; with the NSID of the document it is in. | ||
fn resolve(&self, doc: &str, reference: &str) -> Option<(String, &Value)> { | ||
let (nsid, name) = match reference.split_once('#') { | ||
Some(("", name)) => (doc, name), | ||
Some((nsid, name)) => (nsid, name), | ||
None => (reference, "main"), | ||
}; | ||
let def = self.0.get(nsid)?.get("defs")?.get(name)?; | ||
Some((nsid.to_string(), def)) | ||
} | ||
| ||
/// `def`, a lexicon type in `doc`, as JSON Schema; references followed | ||
/// `depth` deep, and one past that, or not among these lexicons, left | ||
/// open. | ||
fn schema(&self, doc: &str, def: &Value, depth: u8) -> Value { | ||
let mut out = match def["type"].as_str().unwrap_or_default() { | ||
"string" => { | ||
let mut s = json!({"type": "string"}); | ||
copy( | ||
def, | ||
&mut s, | ||
&[("maxLength", "maxLength"), ("format", "format")], | ||
); | ||
if let Some(known) = def["knownValues"].as_array() { | ||
let known: Vec<&str> = known.iter().filter_map(Value::as_str).collect(); | ||
s["description"] = json!(format!("One of: {}.", known.join(", "))); | ||
} | ||
s | ||
} | ||
"integer" => { | ||
let mut s = json!({"type": "integer"}); | ||
copy( | ||
def, | ||
&mut s, | ||
&[("minimum", "minimum"), ("maximum", "maximum")], | ||
); | ||
s | ||
} | ||
"boolean" => json!({"type": "boolean"}), | ||
"array" => { | ||
let items = self.schema(doc, &def["items"], depth); | ||
let mut s = json!({"type": "array", "items": items}); | ||
copy( | ||
def, | ||
&mut s, | ||
&[("maxLength", "maxItems"), ("minLength", "minItems")], | ||
); | ||
s | ||
} | ||
"object" | "params" => self.object(doc, def, depth), | ||
"ref" if depth > 0 => { | ||
let reference = def["ref"].as_str().unwrap_or_default(); | ||
match self.resolve(doc, reference) { | ||
Some((at, found)) => self.schema(&at, found, depth - 1), | ||
None => json!({}), | ||
} | ||
} | ||
"union" if depth > 0 => { | ||
let refs = def["refs"].as_array().cloned().unwrap_or_default(); | ||
let any: Vec<Value> = refs.iter().map(|r| self.member(doc, r, depth)).collect(); | ||
json!({ "anyOf": any }) | ||
} | ||
_ => json!({}), | ||
}; | ||
if let Some(d) = def["description"].as_str() { | ||
let known = out["description"].as_str().map(|k| format!(" {k}")); | ||
out["description"] = json!(format!("{d}{}", known.unwrap_or_default())); | ||
} | ||
out | ||
} | ||
| ||
/// A member of a union, `reference`, which says which it is by its | ||
/// `$type`, as atproto has it. | ||
fn member(&self, doc: &str, reference: &Value, depth: u8) -> Value { | ||
let one = json!({"type": "ref", "ref": reference}); | ||
let mut s = self.schema(doc, &one, depth); | ||
let name = reference.as_str().unwrap_or_default(); | ||
// A local reference, `#name`, is named in full: `<doc>#name`. | ||
let local = if name.starts_with('#') { doc } else { "" }; | ||
let name = format!("{local}{name}"); | ||
if let Some(props) = s.get_mut("properties").and_then(Value::as_object_mut) { | ||
props.insert("$type".into(), json!({ "const": name })); | ||
} | ||
s | ||
} | ||
| ||
fn object(&self, doc: &str, def: &Value, depth: u8) -> Value { | ||
let properties: Map<String, Value> = def["properties"] | ||
.as_object() | ||
.into_iter() | ||
.flatten() | ||
.map(|(k, v)| (k.clone(), self.schema(doc, v, depth))) | ||
.collect(); | ||
let required = def["required"].as_array().cloned().unwrap_or_default(); | ||
json!({"type": "object", "properties": properties, "required": required}) | ||
} | ||
} | ||
| ||
/// How deep the tools' schemas follow references. | ||
const DEPTH: u8 = 6; | ||
| ||
/// The tools, each a method, its schema without the group. | ||
pub fn tools() -> Vec<Tool> { | ||
let docs = Docs::load(); | ||
let tool = |nsid: &str| { | ||
let main = &docs.0[nsid]["defs"]["main"]; | ||
let procedure = main["type"] == "procedure"; | ||
let taken = match procedure { | ||
true => &main["input"]["schema"], | ||
false => &main["parameters"], | ||
}; | ||
let mut input = docs.object(nsid, taken, DEPTH); | ||
let properties = input["properties"].as_object_mut(); | ||
properties | ||
.expect("an object's schema has properties") | ||
.remove("group"); | ||
let required = input["required"].as_array_mut(); | ||
let required = required.expect("an object's schema says what it requires"); | ||
required.retain(|r| r != "group"); | ||
Tool { | ||
name: nsid.rsplit('.').next().unwrap_or(nsid).to_string(), | ||
nsid: nsid.to_string(), | ||
procedure, | ||
description: main["description"].as_str().unwrap_or_default().into(), | ||
input_schema: input, | ||
} | ||
}; | ||
METHODS.iter().map(|(nsid, _)| tool(nsid)).collect() | ||
} | ||
| ||
fn error(id: &Value, code: i64, message: &str) -> Value { | ||
json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}}) | ||
} | ||
| ||
/// The answer to `message`, an assistant's JSON-RPC message, or none for | ||
/// a notification: each tool called through `call`, with its arguments, | ||
/// which answers what the method did, or why it did not. | ||
pub async fn answer<F, Fut>(message: &Value, tools: &[Tool], call: F) -> Option<Value> | ||
where | ||
F: FnOnce(Tool, Value) -> Fut, | ||
Fut: Future<Output = Result<Value, String>>, | ||
{ | ||
if !message.is_object() || message["jsonrpc"] != "2.0" { | ||
let said = "a JSON-RPC 2.0 message is an object"; | ||
return Some(error(&Value::Null, -32600, said)); | ||
} | ||
// A notification, with no id, is answered by nothing. | ||
let id = message.get("id")?; | ||
let params = &message["params"]; | ||
let answered = match message["method"].as_str().unwrap_or_default() { | ||
"initialize" => { | ||
let asked = params["protocolVersion"].as_str().unwrap_or_default(); | ||
let known = PROTOCOL_VERSIONS.into_iter().find(|v| *v == asked); | ||
json!({ | ||
"protocolVersion": known.unwrap_or(PROTOCOL_VERSIONS[0]), | ||
"capabilities": {"tools": {"listChanged": false}}, | ||
"serverInfo": {"name": "group-host", "version": env!("CARGO_PKG_VERSION")}, | ||
"instructions": INSTRUCTIONS, | ||
}) | ||
} | ||
"ping" => json!({}), | ||
"tools/list" => { | ||
let listed = tools.iter().map(|t| { | ||
json!({"name": t.name, "description": t.description, "inputSchema": t.input_schema}) | ||
}); | ||
json!({ "tools": listed.collect::<Vec<_>>() }) | ||
} | ||
"tools/call" => { | ||
let name = params["name"].as_str().unwrap_or_default(); | ||
let Some(tool) = tools.iter().find(|t| t.name == name) else { | ||
return Some(error(id, -32602, &format!("no tool {name}"))); | ||
}; | ||
let arguments = match ¶ms["arguments"] { | ||
Value::Null => json!({}), | ||
given @ Value::Object(_) => given.clone(), | ||
_ => return Some(error(id, -32602, "a tool's arguments are an object")), | ||
}; | ||
match call(tool.clone(), arguments).await { | ||
Ok(done) => { | ||
let text = done.to_string(); | ||
let mut out = json!({"content": [{"type": "text", "text": text}]}); | ||
if done.is_object() { | ||
out["structuredContent"] = done; | ||
} | ||
out | ||
} | ||
Err(why) => json!({"content": [{"type": "text", "text": why}], "isError": true}), | ||
} | ||
} | ||
other => return Some(error(id, -32601, &format!("no method {other}"))), | ||
}; | ||
Some(json!({"jsonrpc": "2.0", "id": id, "result": answered})) | ||
} | ||
| ||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
| ||
/// A union of a lexicon's own defs: each member names itself in full. | ||
#[test] | ||
fn names_a_local_member_of_a_union_in_full() { | ||
let doc = | ||
json!({"defs": {"a": {"type": "object", "properties": {"x": {"type": "string"}}}}}); | ||
let docs = Docs(HashMap::from([("com.example.thing".to_string(), doc)])); | ||
let union = json!({"type": "union", "refs": ["#a"]}); | ||
let schema = docs.schema("com.example.thing", &union, DEPTH); | ||
let member = &schema["anyOf"][0]["properties"]["$type"]["const"]; | ||
assert_eq!(member, "com.example.thing#a"); | ||
} | ||
} | ||
crates/group-host-mcp/tests/protocol.rsnew+214−0
| @@ -0,0 +1,214 @@ | ||
//! The tools, as an assistant lists them, and what the server answers | ||
//! each message it sends. | ||
| ||
use group_host_mcp::{PROTOCOL_VERSIONS, Tool, answer, tools}; | ||
use serde_json::{Value, json}; | ||
| ||
/// What the server answers `message`, each tool answering as `said` says. | ||
async fn ask(message: Value, said: Result<Value, String>) -> Option<Value> { | ||
let tools = tools(); | ||
answer(&message, &tools, |_: Tool, _: Value| async move { said }).await | ||
} | ||
| ||
fn tool(name: &str) -> Tool { | ||
tools().into_iter().find(|t| t.name == name).unwrap() | ||
} | ||
| ||
#[test] | ||
fn makes_a_tool_of_each_method_without_its_group() { | ||
let all = tools(); | ||
assert!(all.len() > 15); | ||
for t in &all { | ||
assert!(t.nsid.ends_with(&t.name), "{t:?}"); | ||
assert!( | ||
t.input_schema["properties"].get("group").is_none(), | ||
"{}", | ||
t.name | ||
); | ||
let required = t.input_schema["required"].as_array(); | ||
assert!( | ||
!required.into_iter().flatten().any(|r| r == "group"), | ||
"{}", | ||
t.name | ||
); | ||
assert!(!t.description.is_empty(), "{}", t.name); | ||
} | ||
let get = tool("getGroup"); | ||
assert!(!get.procedure); | ||
assert_eq!( | ||
get.input_schema, | ||
json!({"type": "object", "properties": {}, "required": []}) | ||
); | ||
| ||
let admit = tool("admitMember"); | ||
assert!(admit.procedure); | ||
assert_eq!(admit.input_schema["properties"]["did"]["format"], "did"); | ||
// A reference followed: each role an object naming it. | ||
let role = &admit.input_schema["properties"]["roles"]["items"]; | ||
assert_eq!(role["type"], "object"); | ||
assert_eq!(role["properties"]["role"]["type"], "string"); | ||
| ||
// Known values said in words, beside what the lexicon says. | ||
let status = &tool("listSubjects").input_schema["properties"]["status"]; | ||
let said = status["description"].as_str().unwrap(); | ||
assert!(said.contains("One of: open"), "{said}"); | ||
let limit = &tool("listSubjects").input_schema["properties"]["limit"]; | ||
assert_eq!(limit["type"], "integer"); | ||
assert!(limit.get("maximum").is_some()); | ||
| ||
// A union, each member saying which it is. | ||
let subject = &tool("applyLabel").input_schema["properties"]["subject"]; | ||
let members = subject["anyOf"].as_array().unwrap(); | ||
assert!(members.len() >= 2, "{subject}"); | ||
assert!( | ||
members | ||
.iter() | ||
.filter_map(|m| m["properties"]["$type"]["const"].as_str()) | ||
.count() | ||
>= 1, | ||
"{subject}" | ||
); | ||
let online = &tool("updateProfile").input_schema["properties"]["online"]; | ||
assert_eq!(online["type"], "boolean"); | ||
} | ||
| ||
#[tokio::test] | ||
async fn answers_initialize_ping_and_the_list() { | ||
let said = ask( | ||
json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-03-26"}}), | ||
Ok(json!({})), | ||
) | ||
.await | ||
.unwrap(); | ||
assert_eq!(said["id"], 1); | ||
assert_eq!(said["result"]["protocolVersion"], "2025-03-26"); | ||
assert_eq!( | ||
said["result"]["capabilities"]["tools"]["listChanged"], | ||
false | ||
); | ||
assert!(said["result"]["instructions"].is_string()); | ||
// One it does not speak: the latest it does. | ||
let said = ask( | ||
json!({"jsonrpc": "2.0", "id": "a", "method": "initialize", "params": {"protocolVersion": "1999-01-01"}}), | ||
Ok(json!({})), | ||
) | ||
.await | ||
.unwrap(); | ||
assert_eq!(said["result"]["protocolVersion"], PROTOCOL_VERSIONS[0]); | ||
| ||
let said = ask( | ||
json!({"jsonrpc": "2.0", "id": 2, "method": "ping"}), | ||
Ok(json!({})), | ||
) | ||
.await; | ||
assert_eq!(said.unwrap()["result"], json!({})); | ||
let said = ask( | ||
json!({"jsonrpc": "2.0", "id": 3, "method": "tools/list"}), | ||
Ok(json!({})), | ||
) | ||
.await; | ||
let listed = said.unwrap()["result"]["tools"].clone(); | ||
assert_eq!(listed.as_array().unwrap().len(), tools().len()); | ||
assert!(listed[0]["inputSchema"]["type"] == "object"); | ||
| ||
// A notification is answered by nothing. | ||
let said = ask( | ||
json!({"jsonrpc": "2.0", "method": "notifications/initialized"}), | ||
Ok(json!({})), | ||
) | ||
.await; | ||
assert!(said.is_none()); | ||
} | ||
| ||
#[tokio::test] | ||
async fn calls_a_tool_and_says_what_it_did_or_why_not() { | ||
let call = |args: Value| json!({"jsonrpc": "2.0", "id": 7, "method": "tools/call", "params": {"name": "getGroup", "arguments": args}}); | ||
let said = ask( | ||
call(Value::Null), | ||
Ok(json!({"group": {"did": "did:plc:x"}})), | ||
) | ||
.await | ||
.unwrap(); | ||
assert_eq!( | ||
said["result"]["structuredContent"]["group"]["did"], | ||
"did:plc:x" | ||
); | ||
let text = said["result"]["content"][0]["text"].as_str().unwrap(); | ||
assert_eq!( | ||
serde_json::from_str::<Value>(text).unwrap()["group"]["did"], | ||
"did:plc:x" | ||
); | ||
assert!(said["result"].get("isError").is_none()); | ||
| ||
let said = ask(call(json!({})), Ok(json!([1, 2]))).await.unwrap(); | ||
assert!(said["result"].get("structuredContent").is_none()); | ||
assert_eq!(said["result"]["content"][0]["text"], "[1,2]"); | ||
| ||
let said = ask(call(json!({})), Err("Forbidden: missing invite".into())) | ||
.await | ||
.unwrap(); | ||
assert_eq!(said["result"]["isError"], true); | ||
assert_eq!( | ||
said["result"]["content"][0]["text"], | ||
"Forbidden: missing invite" | ||
); | ||
| ||
// The arguments it was given, to the call. | ||
let tools = tools(); | ||
let message = call(json!({"x": 1})); | ||
let said = answer(&message, &tools, |t: Tool, args: Value| async move { | ||
Ok(json!({"tool": t.nsid, "args": args})) | ||
}) | ||
.await | ||
.unwrap(); | ||
assert_eq!( | ||
said["result"]["structuredContent"], | ||
json!({"tool": "fyi.opensocial.getGroup", "args": {"x": 1}}) | ||
); | ||
} | ||
| ||
#[tokio::test] | ||
async fn refuses_what_is_not_a_request_it_knows() { | ||
let error = |said: Option<Value>| said.unwrap()["error"]["code"].as_i64().unwrap(); | ||
assert_eq!(error(ask(json!([1]), Ok(json!({}))).await), -32600); | ||
assert_eq!( | ||
error( | ||
ask( | ||
json!({"jsonrpc": "1.0", "id": 1, "method": "ping"}), | ||
Ok(json!({})) | ||
) | ||
.await | ||
), | ||
-32600 | ||
); | ||
assert_eq!( | ||
error( | ||
ask( | ||
json!({"jsonrpc": "2.0", "id": 1, "method": "resources/list"}), | ||
Ok(json!({})) | ||
) | ||
.await | ||
), | ||
-32601 | ||
); | ||
assert_eq!( | ||
error( | ||
ask( | ||
json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "nothing"}}), | ||
Ok(json!({})) | ||
) | ||
.await | ||
), | ||
-32602 | ||
); | ||
assert_eq!( | ||
error( | ||
ask( | ||
json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "getGroup", "arguments": [1]}}), | ||
Ok(json!({})) | ||
) | ||
.await | ||
), | ||
-32602 | ||
); | ||
} | ||
crates/group-host-mcp/Cargo.toml+4−1
| @@ -7,4 +7,7 @@ license.workspace = true | ||
rust-version.workspace = true | ||
| ||
[dependencies] | ||
opensocial.workspace = true | ||
serde_json.workspace = true | ||
| ||
[dev-dependencies] | ||
tokio.workspace = true | ||
docs/design/assistants.mdnew+54−0
| @@ -0,0 +1,54 @@ | ||
# Assistants | ||
| ||
An assistant, an AI app that is an MCP client, connects to a group to act | ||
there as the member who connected it, with what their roles allow and | ||
nothing more (`assistants.rs`, and `crates/group-host-mcp` for the | ||
protocol and the tools). | ||
| ||
## Connecting | ||
| ||
The host is the assistant's MCP server, at `<PUBLIC_URL>/mcp`, and the | ||
OAuth server it signs in at, as MCP's authorization spec has it: | ||
| ||
- `/.well-known/oauth-protected-resource/mcp` names the resource and its | ||
authorization server, whose issuer is `<PUBLIC_URL>/mcp`, and whose | ||
metadata is at `/.well-known/oauth-authorization-server/mcp`. | ||
- An assistant names itself by a client ID metadata document, its client | ||
ID that document's https URL, or registers at `/mcp/register` (RFC 7591) | ||
as a public client. Either way it names at most ten redirect URIs, each | ||
one it may be sent back to: over https, to a loopback address over | ||
http, or to an app's own scheme, never a script's. A client registered | ||
and never connected is forgotten after a day. Its name is its own word | ||
for itself, and the approval page says so, with where it came from. | ||
- `/mcp/authorize` takes a code request with PKCE (S256) for that | ||
resource, and sends the browser to the console's approval page, where | ||
the member, signed in as themselves, reads it with `getAuthorization` | ||
(`assistant: true`), and picks the group to connect it to. | ||
- `/mcp/token` exchanges the code, once, for its client, redirect URI and | ||
verifier, for a Bearer access token (an hour) and a refresh token (thirty | ||
days unused), each kept by its hash; a refresh token is used once. | ||
| ||
This is not the host's atproto OAuth server, where apps sign in *as* a | ||
group (see [signing in](signing-in.md)). An assistant's tokens are kept | ||
apart from a group's, and neither is taken for the other. | ||
| ||
## Acting | ||
| ||
Each message an assistant sends to `/mcp` (JSON-RPC, each answered on its | ||
own, as JSON) is answered as the member, in the group they chose. Its | ||
tools are the core's methods, each by its lexicon (`getGroup`, | ||
`createInvite`, `putRule`, `applyLabel`, …), their input schemas made from | ||
the lexicons, without the group, which is always the one chosen. A call is | ||
the host asking itself as the member, as the console does: the host's | ||
methods decide, by the member's roles as they are now, and a refusal is | ||
the tool's error, in the method's words. | ||
| ||
Each member sees, on the group's page, the assistants they connected, and | ||
disconnects one there (`listConnectedApps`, `revokeConnectedApp`). Put out | ||
of the group, the member's assistants are disconnected with them. | ||
| ||
## From the prototype | ||
| ||
- The prototype's assistant was its sites module's, at each group's own | ||
address, and made pages; this one is the core's methods alone, at the | ||
host's address, and the member chooses the group as they connect it. | ||