chadtmiller.com/group-host
atmosphere group host
0
0
Commands are grouped, and each MCP tool is its command's twin
.claude/skills/docs/context.md+3−3
| @@ -11,7 +11,7 @@ protocol instead of the page. | ||
spaces, and its OAuth server. | ||
- Members keep their own accounts on their own PDSes, anywhere. What a | ||
member may do in a group is what their roles there grant, and an app or | ||
assistant a member signs in gets what those roles allow and nothing more. | ||
MCP client a member signs in gets what those roles allow and nothing more. | ||
- The host is one Rust server over SQLite, with a console (a SvelteKit | ||
app) where people start and run groups and approve apps, and a command, | ||
`opensocial`, that does the same from a terminal. | ||
| @@ -48,12 +48,12 @@ for more. | ||
client holds. | ||
- **lexicon**: the schema for a record or method (`lexicons/fyi/opensocial/`). | ||
- **label**: a moderation tag on a record or account. | ||
- **MCP**: the protocol an AI assistant uses to call tools on a server. | ||
- **MCP**: the protocol an AI app uses to call tools on a server. | ||
| ||
## Pages to link | ||
| ||
Design: `README.md` (overview), `spaces.md`, `groups.md`, | ||
`membership.md`, `signing-in.md`, `moderation.md`, `assistants.md`, | ||
`membership.md`, `signing-in.md`, `moderation.md`, `mcp.md`, | ||
`recovery.md`, `moving.md`. Reference: `../reference/api.md`, `mcp.md`, | ||
`cli.md`, `config.md`. `../development.md`. Link to them rather than | ||
restating them. | ||
.claude/skills/docs/questions.md+7−6
| @@ -66,7 +66,7 @@ one question per mechanism. | ||
6. Where is membership recorded (the members space: membership, role and | ||
permissions records), and what does each hold? | ||
7. What does putting someone out take with them: credentials, the OAuth | ||
grants they approved, their assistants, their app passwords and | ||
grants they approved, their MCP clients, their app passwords and | ||
sessions? | ||
8. How long does the host keep trying to deliver an invite to someone's | ||
inbox? | ||
| @@ -75,7 +75,7 @@ one question per mechanism. | ||
## signing-in.md | ||
| ||
1. Who signs in to what: a person to the console, an app as a group, an | ||
assistant as a member? | ||
MCP client as a member? | ||
2. How does the console sign people in, and what does it keep? | ||
3. How does an app sign in as a group, when a group has no password? | ||
4. Who approves, and what does the app then get? | ||
| @@ -95,7 +95,7 @@ one question per mechanism. | ||
12. What happens to an app's tokens when the group is switched off | ||
(tokens still refresh; writes refused; getSession says | ||
`deactivated`)? | ||
13. How do assistant grants relate to group grants: separate server, | ||
13. How do MCP grants relate to group grants: separate server, | ||
separate table, not in `listGroupTokens` — where does the reader go | ||
to see them? | ||
14. What may a confidential client vs a public client do differently | ||
| @@ -118,14 +118,15 @@ one question per mechanism. | ||
group starts with hold? | ||
7. What happens to the queue when a group is deleted? | ||
| ||
## assistants.md | ||
## mcp.md | ||
| ||
1. What is an assistant, and what may it do in a group? | ||
1. What is an MCP client, and what may it do in a group? Which | ||
command is each tool the twin of? | ||
2. How does it connect and sign in, and how is that kept apart from apps | ||
signing in as a group? | ||
3. What are its tools, and how is each call decided? | ||
4. How does a member see and disconnect one? | ||
5. How long do an assistant's tokens last, and what ends a connection? | ||
5. How long do an MCP client's tokens last, and what ends a connection? | ||
| ||
## recovery.md | ||
| ||
crates/group-host/src/authorization.rs+7−7
| @@ -6,9 +6,9 @@ | ||
| ||
use crate::Host; | ||
use crate::api::{Params, param}; | ||
use crate::assistants; | ||
use crate::group::meta_space; | ||
use crate::group_api::{group_of, signed_in}; | ||
use crate::mcp; | ||
use crate::oauth_scope::{concrete, set_of}; | ||
use crate::oauth_store::Request; | ||
use crate::rbac::{Access, NS}; | ||
| @@ -142,8 +142,8 @@ pub async fn get_authorization( | ||
) -> Answer { | ||
let me = signed_in(&host, &headers, &format!("{NS}.getAuthorization")).await?; | ||
let uri = param(&p, "requestUri")?; | ||
if uri.starts_with(assistants::PREFIX) { | ||
return Ok(Json(assistants::assistant_view(&host, uri, &me)?)); | ||
if uri.starts_with(mcp::PREFIX) { | ||
return Ok(Json(mcp::mcp_view(&host, uri, &me)?)); | ||
} | ||
let request = pending(&host, uri)?; | ||
let requested = requested(&request); | ||
| @@ -191,8 +191,8 @@ pub async fn approve_authorization( | ||
let uri = uri.expect("its lexicon requires it"); | ||
let group = body["group"].as_str(); | ||
let group = group.expect("its lexicon requires it"); | ||
if uri.starts_with(assistants::PREFIX) { | ||
let redirect = assistants::approve(&host, uri, &me, group)?; | ||
if uri.starts_with(mcp::PREFIX) { | ||
let redirect = mcp::approve(&host, uri, &me, group)?; | ||
return Ok(Json(json!({ "redirectUrl": redirect }))); | ||
} | ||
let request = pending(&host, uri)?; | ||
| @@ -231,8 +231,8 @@ pub async fn decline_authorization( | ||
signed_in(&host, &headers, &format!("{NS}.declineAuthorization")).await?; | ||
let uri = body["requestUri"].as_str(); | ||
let uri = uri.expect("its lexicon requires it"); | ||
if uri.starts_with(assistants::PREFIX) { | ||
let redirect = assistants::decline(&host, uri)?; | ||
if uri.starts_with(mcp::PREFIX) { | ||
let redirect = mcp::decline(&host, uri)?; | ||
return Ok(Json(json!({ "redirectUrl": redirect }))); | ||
} | ||
let request = pending(&host, uri)?; | ||
crates/group-host/src/group_invites.rs+20−29
| @@ -12,11 +12,11 @@ | ||
| ||
use crate::Host; | ||
use crate::api::{Params, invalid, page, param}; | ||
use crate::assistants::Connected; | ||
use crate::group::meta_space; | ||
use crate::group_api::{caller, group_of, signed_in}; | ||
use crate::group_members::{Members, acting}; | ||
use crate::lexicons::check_record; | ||
use crate::mcp::McpGrant; | ||
use crate::oauth_resource::Acting; | ||
use crate::oauth_store::Grant; | ||
use crate::rbac::NS; | ||
| @@ -319,21 +319,21 @@ impl Host { | ||
Ok(made) | ||
} | ||
| ||
/// What an assistant's invite tool does, as the member who connected | ||
/// What an MCP client's `invite_send` does, as the member who connected | ||
/// it, in their group: the write the member's own group session for | ||
/// the invitee's inbox would make (`sendInvite`, or `takeBackInvite` | ||
/// for the one waiting), logged as the assistant's. The invite's URI. | ||
/// `person`'s inbox would make, `record` written there, or with none | ||
/// the invite waiting taken back, logged as the MCP client's. The invite's | ||
/// URI. | ||
pub(crate) async fn invite_as( | ||
&self, | ||
who: &Connected, | ||
tool: &str, | ||
args: &Value, | ||
who: &McpGrant, | ||
person: &str, | ||
record: Option<Value>, | ||
) -> Result<Value, XrpcError> { | ||
let invitee = args["invitee"].as_str().unwrap_or_default(); | ||
let inbox = SpaceRef::parse(&inbox_of(invitee)).map_err(|e| invalid(e.to_string()))?; | ||
let inbox = SpaceRef::parse(&inbox_of(person)).map_err(|e| invalid(e.to_string()))?; | ||
let now = now_millis(); | ||
let grant = Grant { | ||
id: format!("assistant-{}", who.id), | ||
id: who.id.clone(), | ||
group: who.group.clone(), | ||
member: who.member.clone(), | ||
client_id: who.client_id.clone(), | ||
| @@ -343,29 +343,20 @@ impl Host { | ||
access_expires: now, | ||
expires_at: now, | ||
created_at: now, | ||
source: "assistant".into(), | ||
source: "mcp".into(), | ||
used_at: None, | ||
}; | ||
let permissions = Permissions::new(&grant.scope, &grant.group); | ||
let acting = Acting { grant, permissions }; | ||
let collection = format!("{NS}.invite"); | ||
let write = match tool { | ||
"sendInvite" => { | ||
let mut value = json!({"$type": collection, "createdAt": iso(now)}); | ||
for field in ["message", "expiresAt"] { | ||
if let Some(given) = args.get(field) { | ||
value[field] = given.clone(); | ||
} | ||
} | ||
let rkey = self.clock.next(); | ||
Write::Create { | ||
collection, | ||
rkey, | ||
value, | ||
} | ||
} | ||
_ => { | ||
let waiting = self.store.invited(&who.group, invitee); | ||
let write = match record { | ||
Some(value) => Write::Create { | ||
collection, | ||
rkey: self.clock.next(), | ||
value, | ||
}, | ||
None => { | ||
let waiting = self.store.invited(&who.group, person); | ||
let waiting = waiting.map_err(XrpcError::internal)?; | ||
let rkey = waiting.map(|w| w.rkey).unwrap_or_default(); | ||
Write::Delete { collection, rkey } | ||
| @@ -473,7 +464,7 @@ pub async fn decline_invite( | ||
| ||
/// Whether a user may read or write a space this host manages for its | ||
/// authority: someone's inbox, which its owner reads and groups here | ||
/// write their invites in. Asked by the space's authority, with service | ||
/// write their invites in. McpRequest by the space's authority, with service | ||
/// auth for this host. | ||
pub async fn check_user_access( | ||
State(host): State<Arc<Host>>, | ||
crates/group-host/src/lib.rs+9−9
| @@ -7,7 +7,6 @@ pub mod account_move; | ||
pub mod actors; | ||
pub mod api; | ||
pub mod app_passwords; | ||
pub mod assistants; | ||
pub mod authority; | ||
pub mod authority_api; | ||
pub mod authorization; | ||
| @@ -32,6 +31,7 @@ pub mod index; | ||
pub mod index_api; | ||
pub mod lexicons; | ||
pub mod lifecycle; | ||
pub mod mcp; | ||
pub mod member_writes; | ||
pub mod migration; | ||
pub mod moderation; | ||
| @@ -458,23 +458,23 @@ fn oauth_routes() -> Router<Arc<Host>> { | ||
.route("/oauth/revoke", post(oauth::revoke)) | ||
.route( | ||
"/.well-known/oauth-protected-resource/mcp", | ||
get(assistants::resource_metadata), | ||
get(mcp::resource_metadata), | ||
) | ||
.route( | ||
"/.well-known/oauth-authorization-server/mcp", | ||
get(assistants::server_metadata), | ||
get(mcp::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("/mcp", post(mcp::mcp)) | ||
.route("/mcp/register", post(mcp::register)) | ||
.route("/mcp/authorize", get(mcp::authorize)) | ||
.route("/mcp/token", post(mcp::token)) | ||
.route( | ||
"/xrpc/fyi.opensocial.listConnectedApps", | ||
get(assistants::list_connected_apps), | ||
get(mcp::list_connected_apps), | ||
) | ||
.route( | ||
"/xrpc/fyi.opensocial.revokeConnectedApp", | ||
post(assistants::revoke_connected_app), | ||
post(mcp::revoke_connected_app), | ||
) | ||
.layer(axum::middleware::from_fn(oauth::cors)) | ||
} | ||
crates/group-host/src/assistants.rs → crates/group-host/src/mcp.rsrenamed+175−161
| @@ -1,21 +1,22 @@ | ||
//! Assistants: an AI app, as an MCP client, acting as a member in one of | ||
//! their groups, with what the member's roles there allow and nothing | ||
//! more. | ||
//! The MCP server: an MCP client, as an AI app is, acting as a member in | ||
//! one of their groups, with what the member's roles there allow and | ||
//! nothing more. Its tools are `group_host_mcp`'s, each carried out here | ||
//! as the member. | ||
//! | ||
//! The host is the assistant's MCP server, at `/mcp`, and the OAuth server | ||
//! The host is the client's MCP server, at `/mcp`, and the OAuth server | ||
//! it signs in at, as MCP's authorization spec has it: OAuth 2.1 with PKCE, | ||
//! Bearer tokens for that one resource, the server found from the | ||
//! resource's metadata (RFC 9728) and named by its own (RFC 8414, at the | ||
//! issuer `<PUBLIC_URL>/mcp`). An assistant names itself by a client ID | ||
//! issuer `<PUBLIC_URL>/mcp`). An MCP client names itself by a client ID | ||
//! metadata document, its client ID the URL of one, or registers itself | ||
//! (RFC 7591). This is not the host's atproto OAuth server, where apps | ||
//! sign in *as* a group, and their tokens are not each other's. | ||
//! | ||
//! Where the member says yes is the console's approval page, signed in as | ||
//! themselves: the assistant's request is one more the page reads with | ||
//! themselves: the MCP client's request is one more the page reads with | ||
//! `getAuthorization`, and the member picks the group. Each tool call is | ||
//! then the member's own, in that group, as the console's are: the host | ||
//! asks itself, as them. Put out of the group, they and their assistants | ||
//! asks itself, as them. Put out of the group, they and their MCP clients | ||
//! can do nothing there, and its grants end. | ||
| ||
use crate::Host; | ||
| @@ -37,16 +38,16 @@ use axum::extract::{Query, State}; | ||
use axum::http::{HeaderMap, Request, StatusCode, header}; | ||
use axum::response::{IntoResponse, Redirect, Response}; | ||
use axum::{Form, Json}; | ||
use group_host_mcp::{Kind, Tool}; | ||
use group_host_mcp::{Plan, Tool}; | ||
use rusqlite::{OptionalExtension, Row, params}; | ||
use serde_json::{Value, json}; | ||
use std::collections::HashMap; | ||
use std::sync::{Arc, LazyLock}; | ||
use tower::ServiceExt; | ||
| ||
/// What a request an assistant made is named by, on the approval page. | ||
pub const PREFIX: &str = "urn:group-host:assistant:"; | ||
/// How long an assistant's request waits to be approved, and its code to | ||
/// What a request an MCP client made is named by, on the approval page. | ||
pub const PREFIX: &str = "urn:group-host:mcp:"; | ||
/// How long an MCP client's request waits to be approved, and its code to | ||
/// be exchanged. | ||
const REQUEST_FOR: i64 = 10 * 60_000; | ||
/// How long its access token lasts, and its refresh token unused. | ||
| @@ -58,10 +59,10 @@ const UNUSED_FOR: i64 = 24 * 60 * 60_000; | ||
/// The tools, made once. | ||
static TOOLS: LazyLock<Vec<Tool>> = LazyLock::new(group_host_mcp::tools); | ||
| ||
/// An assistant's request to act as a member: who it is, where to send | ||
/// An MCP client's request to act as a member: who it is, where to send | ||
/// the browser back to, and once approved, the group and member. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Asked { | ||
pub struct McpRequest { | ||
pub id: String, | ||
pub client_id: String, | ||
pub client_name: String, | ||
| @@ -73,9 +74,9 @@ pub struct Asked { | ||
pub member: Option<String>, | ||
} | ||
| ||
/// An assistant connected: the member it acts as, in the group, and when. | ||
/// An MCP client connected: the member it acts as, in the group, and when. | ||
#[derive(Debug, Clone, PartialEq)] | ||
pub struct Connected { | ||
pub struct McpGrant { | ||
pub id: String, | ||
pub group: String, | ||
pub member: String, | ||
| @@ -85,8 +86,8 @@ pub struct Connected { | ||
pub used_at: i64, | ||
} | ||
| ||
fn asked(r: &Row) -> rusqlite::Result<Asked> { | ||
Ok(Asked { | ||
fn asked(r: &Row) -> rusqlite::Result<McpRequest> { | ||
Ok(McpRequest { | ||
id: r.get(0)?, | ||
client_id: r.get(1)?, | ||
client_name: r.get(2)?, | ||
| @@ -99,8 +100,8 @@ fn asked(r: &Row) -> rusqlite::Result<Asked> { | ||
}) | ||
} | ||
| ||
fn connected(r: &Row) -> rusqlite::Result<Connected> { | ||
Ok(Connected { | ||
fn connected(r: &Row) -> rusqlite::Result<McpGrant> { | ||
Ok(McpGrant { | ||
id: r.get(0)?, | ||
group: r.get(1)?, | ||
member: r.get(2)?, | ||
| @@ -111,14 +112,14 @@ fn connected(r: &Row) -> rusqlite::Result<Connected> { | ||
}) | ||
} | ||
| ||
const ASKED: &str = "SELECT id, client_id, client_name, redirect_uri, state, code_challenge, expires_at, grp, member FROM assistant_request"; | ||
const ASKED: &str = "SELECT id, client_id, client_name, redirect_uri, state, code_challenge, expires_at, grp, member FROM mcp_request"; | ||
const CONNECTED: &str = | ||
"SELECT id, grp, member, client_id, client_name, created_at, used_at FROM assistant_grant"; | ||
"SELECT id, grp, member, client_id, client_name, created_at, used_at FROM mcp_grant"; | ||
| ||
impl Store { | ||
/// Keeps a client an assistant registered: its name, and where it | ||
/// Keeps a client that registered itself: its name, and where it | ||
/// may be sent back to. | ||
pub fn register_assistant( | ||
pub fn register_mcp_client( | ||
&self, | ||
id: &str, | ||
name: &str, | ||
| @@ -128,11 +129,12 @@ impl Store { | ||
// Registering is anyone's: one never connected goes after a day. | ||
// One a member connected stays, to connect again; its connections | ||
// go once their refresh tokens lapse. | ||
let stale = "DELETE FROM assistant_client WHERE created_at < ?1 AND connected = 0"; | ||
let stale = "DELETE FROM mcp_client WHERE created_at < ?1 AND connected = 0"; | ||
self.conn().execute(stale, [now - UNUSED_FOR])?; | ||
let lapsed = "DELETE FROM assistant_grant WHERE expires_at <= ?1"; | ||
let lapsed = "DELETE FROM mcp_grant WHERE expires_at <= ?1"; | ||
self.conn().execute(lapsed, [now])?; | ||
let sql = "INSERT INTO assistant_client (id, name, redirect_uris, created_at) VALUES (?1, ?2, ?3, ?4)"; | ||
let sql = | ||
"INSERT INTO mcp_client (id, name, redirect_uris, created_at) VALUES (?1, ?2, ?3, ?4)"; | ||
let redirects = serde_json::to_string(redirects)?; | ||
self.conn() | ||
.execute(sql, params![id, name, redirects, now])?; | ||
| @@ -140,8 +142,8 @@ impl Store { | ||
} | ||
| ||
/// A registered client's name and redirect URIs. | ||
pub fn registered_assistant(&self, id: &str) -> Result<Option<(String, Vec<String>)>> { | ||
let sql = "SELECT name, redirect_uris FROM assistant_client WHERE id = ?1"; | ||
pub fn registered_mcp_client(&self, id: &str) -> Result<Option<(String, Vec<String>)>> { | ||
let sql = "SELECT name, redirect_uris FROM mcp_client WHERE id = ?1"; | ||
let found = self.conn().query_row(sql, [id], |r| { | ||
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)) | ||
}); | ||
| @@ -149,9 +151,9 @@ impl Store { | ||
Ok(found.map(|(name, uris)| (name, serde_json::from_str(&uris).unwrap_or_default()))) | ||
} | ||
| ||
/// Keeps an assistant's request, until it is answered or lapses. | ||
pub fn ask_for_assistant(&self, a: &Asked) -> Result<()> { | ||
let sql = "INSERT INTO assistant_request (id, client_id, client_name, redirect_uri, state, code_challenge, expires_at) | ||
/// Keeps an MCP client's request, until it is answered or lapses. | ||
pub fn keep_mcp_request(&self, a: &McpRequest) -> Result<()> { | ||
let sql = "INSERT INTO mcp_request (id, client_id, client_name, redirect_uri, state, code_challenge, expires_at) | ||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)"; | ||
let row = params![ | ||
a.id, | ||
| @@ -166,57 +168,57 @@ impl Store { | ||
Ok(()) | ||
} | ||
| ||
/// An assistant's request, unanswered and unlapsed at `now`. | ||
pub fn assistant_request(&self, id: &str, now: i64) -> Result<Option<Asked>> { | ||
/// An MCP client's request, unanswered and unlapsed at `now`. | ||
pub fn mcp_request(&self, id: &str, now: i64) -> Result<Option<McpRequest>> { | ||
let sql = format!("{ASKED} WHERE id = ?1 AND expires_at > ?2 AND grp IS NULL"); | ||
let found = self.conn().query_row(&sql, params![id, now], asked); | ||
Ok(found.optional()?) | ||
} | ||
| ||
/// Approves an assistant's request for `member` in `group`, its code | ||
/// Approves an MCP client's request for `member` in `group`, its code | ||
/// kept by its hash: the request, if it was there to approve. | ||
pub fn approve_assistant( | ||
pub fn approve_mcp_request( | ||
&self, | ||
id: &str, | ||
group: &str, | ||
member: &str, | ||
code: &str, | ||
now: i64, | ||
) -> Result<Option<Asked>> { | ||
let sql = "UPDATE assistant_request SET grp = ?2, member = ?3, code_hash = ?4 | ||
) -> Result<Option<McpRequest>> { | ||
let sql = "UPDATE mcp_request SET grp = ?2, member = ?3, code_hash = ?4 | ||
WHERE id = ?1 AND grp IS NULL AND expires_at > ?5 | ||
RETURNING id, client_id, client_name, redirect_uri, state, code_challenge, expires_at, grp, member"; | ||
let row = params![id, group, member, code, now]; | ||
Ok(self.conn().query_row(sql, row, asked).optional()?) | ||
} | ||
| ||
/// An assistant's request, gone: whether it was there. | ||
pub fn drop_assistant_request(&self, id: &str) -> Result<bool> { | ||
let sql = "DELETE FROM assistant_request WHERE id = ?1"; | ||
/// An MCP client's request, gone: whether it was there. | ||
pub fn drop_mcp_request(&self, id: &str) -> Result<bool> { | ||
let sql = "DELETE FROM mcp_request WHERE id = ?1"; | ||
Ok(self.conn().execute(sql, [id])? == 1) | ||
} | ||
| ||
/// The approved request whose code hashes to `code`, once: it is gone | ||
/// as it is taken. | ||
pub fn redeem_assistant_code(&self, code: &str, now: i64) -> Result<Option<Asked>> { | ||
pub fn redeem_mcp_code(&self, code: &str, now: i64) -> Result<Option<McpRequest>> { | ||
let mut conn = self.conn(); | ||
let tx = conn.transaction()?; | ||
let sql = format!("{ASKED} WHERE code_hash = ?1 AND expires_at > ?2 AND grp IS NOT NULL"); | ||
let found = tx.query_row(&sql, params![code, now], asked).optional()?; | ||
tx.execute("DELETE FROM assistant_request WHERE code_hash = ?1", [code])?; | ||
tx.execute("DELETE FROM mcp_request WHERE code_hash = ?1", [code])?; | ||
tx.commit()?; | ||
Ok(found) | ||
} | ||
| ||
/// Keeps an assistant connected, its tokens by their hashes. | ||
pub fn connect_assistant( | ||
/// Keeps an MCP client connected, its tokens by their hashes. | ||
pub fn connect_mcp_client( | ||
&self, | ||
c: &Connected, | ||
c: &McpGrant, | ||
access: &str, | ||
refresh: &str, | ||
now: i64, | ||
) -> Result<()> { | ||
let sql = "INSERT INTO assistant_grant (id, grp, member, client_id, client_name, access_hash, access_expires, refresh_hash, expires_at, created_at, used_at) | ||
let sql = "INSERT INTO mcp_grant (id, grp, member, client_id, client_name, access_hash, access_expires, refresh_hash, expires_at, created_at, used_at) | ||
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?10)"; | ||
let row = params![ | ||
c.id, | ||
| @@ -231,21 +233,21 @@ impl Store { | ||
now | ||
]; | ||
self.conn().execute(sql, row)?; | ||
let connected = "UPDATE assistant_client SET connected = 1 WHERE id = ?1"; | ||
let connected = "UPDATE mcp_client SET connected = 1 WHERE id = ?1"; | ||
self.conn().execute(connected, [&c.client_id])?; | ||
Ok(()) | ||
} | ||
| ||
/// The connection whose access token hashes to `access`, unlapsed, | ||
/// marked as used `now`. | ||
pub fn assistant_by_access(&self, access: &str, now: i64) -> Result<Option<Connected>> { | ||
pub fn mcp_grant_by_access(&self, access: &str, now: i64) -> Result<Option<McpGrant>> { | ||
let sql = format!("{CONNECTED} WHERE access_hash = ?1 AND access_expires > ?2"); | ||
let found = self | ||
.conn() | ||
.query_row(&sql, params![access, now], connected) | ||
.optional()?; | ||
if let Some(c) = &found { | ||
let sql = "UPDATE assistant_grant SET used_at = ?2 WHERE id = ?1"; | ||
let sql = "UPDATE mcp_grant SET used_at = ?2 WHERE id = ?1"; | ||
self.conn().execute(sql, params![c.id, now])?; | ||
} | ||
Ok(found) | ||
| @@ -254,15 +256,15 @@ impl Store { | ||
/// `client`'s connection whose refresh token hashes to `refresh`, its | ||
/// tokens changed to `access` and `next`: none if there is none, or it | ||
/// lapsed. | ||
pub fn refresh_assistant( | ||
pub fn refresh_mcp_grant( | ||
&self, | ||
client: &str, | ||
refresh: &str, | ||
access: &str, | ||
next: &str, | ||
now: i64, | ||
) -> Result<Option<Connected>> { | ||
let sql = "UPDATE assistant_grant SET access_hash = ?3, access_expires = ?4, refresh_hash = ?5, expires_at = ?6 | ||
) -> Result<Option<McpGrant>> { | ||
let sql = "UPDATE mcp_grant SET access_hash = ?3, access_expires = ?4, refresh_hash = ?5, expires_at = ?6 | ||
WHERE refresh_hash = ?1 AND client_id = ?2 AND expires_at > ?7"; | ||
let row = params![ | ||
refresh, | ||
| @@ -280,9 +282,9 @@ impl Store { | ||
Ok(self.conn().query_row(&sql, [next], connected).optional()?) | ||
} | ||
| ||
/// The assistants `member` connected to `group`, the most lately used | ||
/// The MCP clients `member` connected to `group`, the most lately used | ||
/// first. | ||
pub fn assistants_of(&self, group: &str, member: &str, now: i64) -> Result<Vec<Connected>> { | ||
pub fn mcp_clients_of(&self, group: &str, member: &str, now: i64) -> Result<Vec<McpGrant>> { | ||
let sql = format!( | ||
"{CONNECTED} WHERE grp = ?1 AND member = ?2 AND expires_at > ?3 ORDER BY used_at DESC, id" | ||
); | ||
| @@ -293,8 +295,8 @@ impl Store { | ||
} | ||
| ||
/// `member`'s connections of `client` in `group`, ended: how many. | ||
pub fn disconnect_assistant(&self, group: &str, member: &str, client: &str) -> Result<usize> { | ||
let sql = "DELETE FROM assistant_grant WHERE grp = ?1 AND member = ?2 AND client_id = ?3"; | ||
pub fn disconnect_mcp_client(&self, group: &str, member: &str, client: &str) -> Result<usize> { | ||
let sql = "DELETE FROM mcp_grant WHERE grp = ?1 AND member = ?2 AND client_id = ?3"; | ||
Ok(self.conn().execute(sql, params![group, member, client])?) | ||
} | ||
} | ||
| @@ -315,7 +317,7 @@ impl Host { | ||
format!("{}/mcp", self.config.public_url) | ||
} | ||
| ||
/// Where an assistant finds out how to sign in. | ||
/// Where an MCP client finds out how to sign in. | ||
fn resource_metadata_url(&self) -> String { | ||
format!( | ||
"{}/.well-known/oauth-protected-resource/mcp", | ||
| @@ -325,7 +327,7 @@ impl Host { | ||
| ||
/// A client's name, and the redirect URIs it may use: by its metadata | ||
/// document if its ID is the URL of one, or as it registered. | ||
async fn assistant_client(&self, client_id: &str) -> Option<(String, Vec<String>)> { | ||
async fn mcp_client(&self, client_id: &str) -> Option<(String, Vec<String>)> { | ||
// Over https, or http for a host on http, as on a dev network. | ||
let on_http = self.config.public_url.starts_with("http://"); | ||
if client_id.starts_with("https://") || (on_http && client_id.starts_with("http://")) { | ||
| @@ -346,7 +348,7 @@ impl Host { | ||
// sent back to, and it is no client. | ||
return redirects_ok(&uris).then_some((name, uris)); | ||
} | ||
self.store.registered_assistant(client_id).ok().flatten() | ||
self.store.registered_mcp_client(client_id).ok().flatten() | ||
} | ||
} | ||
| ||
| @@ -377,7 +379,7 @@ pub async fn server_metadata(State(host): State<Arc<Host>>) -> Json<Value> { | ||
})) | ||
} | ||
| ||
/// Whether an assistant may be sent back to `uri`: over https, to a | ||
/// Whether an MCP client may be sent back to `uri`: over https, to a | ||
/// loopback address over http, or to an app's own scheme; never with a | ||
/// fragment (RFC 6749 §3.1.2). | ||
fn may_return_to(uri: &str) -> bool { | ||
| @@ -409,7 +411,7 @@ fn redirects_ok(uris: &[String]) -> bool { | ||
.all(|u| u.len() <= REDIRECT_MAX && may_return_to(u)) | ||
} | ||
| ||
/// Registers an assistant (RFC 7591): a public client, by its name and | ||
/// Registers an MCP client (RFC 7591): a public client, by its name and | ||
/// where it may be sent back to. | ||
pub async fn register( | ||
State(host): State<Arc<Host>>, | ||
| @@ -425,12 +427,12 @@ pub async fn register( | ||
let said = "redirect_uris are https, http to a loopback address, or an app's own scheme"; | ||
return Ok(bad("invalid_redirect_uri", said)); | ||
} | ||
let name = body["client_name"].as_str().unwrap_or("An assistant"); | ||
let name = body["client_name"].as_str().unwrap_or("An AI app"); | ||
let name: String = name.chars().take(100).collect(); | ||
let id = jose::random(16); | ||
let kept = host | ||
.store | ||
.register_assistant(&id, &name, &uris, now_millis()); | ||
.register_mcp_client(&id, &name, &uris, now_millis()); | ||
kept.map_err(XrpcError::internal)?; | ||
let out = json!({ | ||
"client_id": id, | ||
| @@ -450,7 +452,7 @@ fn with_query(uri: &str, query: &[(&str, &str)]) -> String { | ||
url.to_string() | ||
} | ||
| ||
/// An assistant's authorization request: checked, kept, and the browser | ||
/// An MCP client's authorization request: checked, kept, and the browser | ||
/// sent to the console to say yes to it. | ||
pub async fn authorize( | ||
State(host): State<Arc<Host>>, | ||
| @@ -460,7 +462,7 @@ pub async fn authorize( | ||
let (Some(client_id), Some(redirect_uri)) = (p.get("client_id"), p.get("redirect_uri")) else { | ||
return refused("client_id and redirect_uri are required"); | ||
}; | ||
let Some((name, uris)) = host.assistant_client(client_id).await else { | ||
let Some((name, uris)) = host.mcp_client(client_id).await else { | ||
return refused("no client by that client_id"); | ||
}; | ||
if !uris.contains(redirect_uri) { | ||
| @@ -486,7 +488,7 @@ pub async fn authorize( | ||
if !s256 || !(43..=128).contains(&challenge.len()) || !resource { | ||
return back("invalid_request"); | ||
} | ||
let request = Asked { | ||
let request = McpRequest { | ||
id: format!("{PREFIX}{}", jose::random(24)), | ||
client_id: client_id.clone(), | ||
client_name: name, | ||
| @@ -497,7 +499,7 @@ pub async fn authorize( | ||
group: None, | ||
member: None, | ||
}; | ||
let kept = host.store.ask_for_assistant(&request); | ||
let kept = host.store.keep_mcp_request(&request); | ||
kept.map_err(XrpcError::internal)?; | ||
let console = &host.config.console_url; | ||
let approve = with_query( | ||
| @@ -509,8 +511,8 @@ pub async fn authorize( | ||
| ||
/// The pending request `uri` names, for the console: the client, and the | ||
/// groups the member could connect it to. | ||
pub(crate) fn assistant_view(host: &Host, uri: &str, me: &str) -> Result<Value, XrpcError> { | ||
let request = host.store.assistant_request(uri, now_millis()); | ||
pub(crate) fn mcp_view(host: &Host, uri: &str, me: &str) -> Result<Value, XrpcError> { | ||
let request = host.store.mcp_request(uri, now_millis()); | ||
let request = request.map_err(XrpcError::internal)?.ok_or_else(expired)?; | ||
let mut groups = Vec::new(); | ||
// It asks for no scope: it does what the member's roles allow. | ||
| @@ -522,7 +524,7 @@ pub(crate) fn assistant_view(host: &Host, uri: &str, me: &str) -> Result<Value, | ||
"requested": [], | ||
"labels": [], | ||
"groups": groups, | ||
"assistant": true, | ||
"mcp": true, | ||
})) | ||
} | ||
| ||
| @@ -534,7 +536,7 @@ pub(crate) fn expired() -> XrpcError { | ||
) | ||
} | ||
| ||
/// Approves an assistant's request for `me` in `group`: where to send the | ||
/// Approves an MCP client's request for `me` in `group`: where to send the | ||
/// browser back to, with its code. | ||
pub(crate) fn approve(host: &Host, uri: &str, me: &str, group: &str) -> Result<String, XrpcError> { | ||
group_of(host, group)?; | ||
| @@ -548,13 +550,13 @@ pub(crate) fn approve(host: &Host, uri: &str, me: &str, group: &str) -> Result<S | ||
let hash = jose::sha256(&code); | ||
let approved = host | ||
.store | ||
.approve_assistant(uri, group, me, &hash, now_millis()); | ||
.approve_mcp_request(uri, group, me, &hash, now_millis()); | ||
let request = approved.map_err(XrpcError::internal)?.ok_or_else(expired)?; | ||
tracing::info!( | ||
member = me, | ||
client = request.client_id, | ||
group, | ||
"an assistant connected" | ||
"an MCP client connected" | ||
); | ||
let iss = host.mcp_url(); | ||
let mut query = vec![("code", code.as_str()), ("iss", iss.as_str())]; | ||
| @@ -564,12 +566,12 @@ pub(crate) fn approve(host: &Host, uri: &str, me: &str, group: &str) -> Result<S | ||
Ok(with_query(&request.redirect_uri, &query)) | ||
} | ||
| ||
/// Declines an assistant's request: where to send the browser back to. | ||
/// Declines an MCP client's request: where to send the browser back to. | ||
pub(crate) fn decline(host: &Host, uri: &str) -> Result<String, XrpcError> { | ||
let request = host.store.assistant_request(uri, now_millis()); | ||
let request = host.store.mcp_request(uri, now_millis()); | ||
let request = request.map_err(XrpcError::internal)?.ok_or_else(expired)?; | ||
host.store | ||
.drop_assistant_request(uri) | ||
.drop_mcp_request(uri) | ||
.map_err(XrpcError::internal)?; | ||
let iss = host.mcp_url(); | ||
let mut query = vec![("error", "access_denied"), ("iss", iss.as_str())]; | ||
| @@ -609,7 +611,7 @@ pub async fn token( | ||
"authorization_code" => { | ||
let redeemed = host | ||
.store | ||
.redeem_assistant_code(&jose::sha256(field("code")), now); | ||
.redeem_mcp_code(&jose::sha256(field("code")), now); | ||
let Some(request) = redeemed.map_err(XrpcError::internal)? else { | ||
return Ok(bad("invalid_grant", "an unknown or used code")); | ||
}; | ||
| @@ -623,7 +625,7 @@ pub async fn token( | ||
let said = "the code is not this client's, or not for this verifier"; | ||
return Ok(bad("invalid_grant", said)); | ||
} | ||
let connection = Connected { | ||
let connection = McpGrant { | ||
id: jose::random(16), | ||
group: request.group.unwrap_or_default(), | ||
member: request.member.unwrap_or_default(), | ||
| @@ -634,7 +636,7 @@ pub async fn token( | ||
}; | ||
let kept = host | ||
.store | ||
.connect_assistant(&connection, &access_hash, &refresh_hash, now); | ||
.connect_mcp_client(&connection, &access_hash, &refresh_hash, now); | ||
kept.map_err(XrpcError::internal)?; | ||
Ok(issued(&access, &refresh)) | ||
} | ||
| @@ -643,7 +645,7 @@ pub async fn token( | ||
let client = field("client_id"); | ||
let rotated = | ||
host.store | ||
.refresh_assistant(client, &old, &access_hash, &refresh_hash, now); | ||
.refresh_mcp_grant(client, &old, &access_hash, &refresh_hash, now); | ||
match rotated.map_err(XrpcError::internal)? { | ||
Some(_) => Ok(issued(&access, &refresh)), | ||
None => Ok(bad( | ||
| @@ -659,7 +661,7 @@ pub async fn token( | ||
} | ||
} | ||
| ||
/// The challenge an assistant without a current token is answered with. | ||
/// The challenge an MCP client without a current token is answered with. | ||
fn challenge(host: &Host, error: Option<&str>) -> Response { | ||
let meta = host.resource_metadata_url(); | ||
let said = match error { | ||
| @@ -670,7 +672,7 @@ fn challenge(host: &Host, error: Option<&str>) -> Response { | ||
( | ||
StatusCode::UNAUTHORIZED, | ||
headers, | ||
"an assistant's token is required", | ||
"an MCP client's token is required", | ||
) | ||
.into_response() | ||
} | ||
| @@ -695,29 +697,22 @@ fn query_of(args: &Value) -> Vec<(String, String)> { | ||
out | ||
} | ||
| ||
/// A record tool's write: the record's kind, the type of the group's | ||
/// space it is kept in, the one key it is kept at if one, and whether it | ||
/// goes. | ||
struct RecordAsked<'a> { | ||
collection: &'a str, | ||
space: &'a str, | ||
literal: Option<&'a str>, | ||
delete: bool, | ||
} | ||
| ||
impl Host { | ||
/// Writes the record `asked` names, its key and value `args`, as the | ||
/// group, in `who`'s group: what a group session `who`'s member | ||
/// approved for that space would write, its scope what their roles | ||
/// there grant now, kept to the same rules. | ||
/// Writes a record of `who`'s group as the group, as `Plan::Write` | ||
/// says: `record` at `rkey`, or at a new key, or with none deletes the | ||
/// one at `rkey`, in its space of the type `space`. What a group | ||
/// session `who`'s member approved for that space would write, its | ||
/// scope what their roles there grant now, kept to the same rules. | ||
async fn record_as( | ||
&self, | ||
who: &Connected, | ||
asked: &RecordAsked<'_>, | ||
mut args: Value, | ||
who: &McpGrant, | ||
space: &str, | ||
collection: String, | ||
rkey: Option<String>, | ||
record: Option<Value>, | ||
) -> Result<Value, XrpcError> { | ||
let group = &who.group; | ||
let uri = format!("at://{group}/space/{}/self", asked.space); | ||
let uri = format!("at://{group}/space/{space}/self"); | ||
let space = SpaceRef::parse(&uri).expect("a group's own space is a space"); | ||
let (_, _, scope) = self.group_scope(group, &who.member, &uri, &space)?; | ||
let now = now_millis(); | ||
| @@ -739,78 +734,85 @@ impl Host { | ||
permissions: Permissions::new(&scope, group), | ||
grant, | ||
}; | ||
let fields = args | ||
.as_object_mut() | ||
.expect("a tool's arguments are an object"); | ||
let named = fields.remove("rkey"); | ||
let rkey = match (asked.literal, named.as_ref().and_then(Value::as_str)) { | ||
(Some(key), _) => key.to_string(), | ||
(None, Some(key)) => key.to_string(), | ||
(None, None) => self.clock.next(), | ||
}; | ||
let collection = asked.collection.to_string(); | ||
let write = match asked.delete { | ||
true => Write::Delete { collection, rkey }, | ||
false => { | ||
fields.insert("$type".into(), json!(collection)); | ||
Write::Update { | ||
collection, | ||
rkey, | ||
value: args.clone(), | ||
} | ||
} | ||
let rkey = rkey.unwrap_or_else(|| self.clock.next()); | ||
let write = match &record { | ||
None => Write::Delete { collection, rkey }, | ||
Some(value) => Write::Update { | ||
collection, | ||
rkey, | ||
value: value.clone(), | ||
}, | ||
}; | ||
let writes = std::slice::from_ref(&write); | ||
let written = self.write_as(&acting, &uri, &space, writes, true); | ||
written.await?; | ||
let (collection, rkey) = write.path(); | ||
let mut out = json!({"uri": format!("{uri}/{group}/{collection}/{rkey}")}); | ||
if !asked.delete { | ||
out["cid"] = json!(record_cid(collection, &args)?.to_string()); | ||
if let Some(value) = &record { | ||
out["cid"] = json!(record_cid(collection, value)?.to_string()); | ||
} | ||
Ok(out) | ||
} | ||
| ||
/// Calls `tool` with `args` as `who`, in their group: as the console | ||
/// does, the host asking itself as them. A tool that writes an invite | ||
/// makes the write their own session for the group would. | ||
async fn call_as( | ||
self: &Arc<Self>, | ||
who: &Connected, | ||
tool: Tool, | ||
mut args: Value, | ||
) -> Result<Value, String> { | ||
if let Kind::Record { | ||
space, | ||
literal, | ||
delete, | ||
} = &tool.kind | ||
{ | ||
let asked = RecordAsked { | ||
collection: &tool.nsid, | ||
/// Carries out `plan` as `who`, in their group: a method asked as the | ||
/// console asks it, a record written as their own session for the | ||
/// group would. | ||
async fn carry_out(self: &Arc<Self>, who: &McpGrant, plan: Plan) -> Result<Value, String> { | ||
let said = |e: XrpcError| format!("{}: {}", e.error, e.message); | ||
match plan { | ||
Plan::Call { | ||
nsid, | ||
procedure, | ||
mut input, | ||
} => { | ||
input["group"] = json!(who.group); | ||
self.ask_as(who, &nsid, procedure, &input).await | ||
} | ||
Plan::Write { | ||
space, | ||
literal: literal.as_deref(), | ||
delete: *delete, | ||
}; | ||
let written = self.record_as(who, &asked, args).await; | ||
return written.map_err(|e| format!("{}: {}", e.error, e.message)); | ||
} | ||
if tool.nsid.starts_with("com.atproto.space.") { | ||
let made = self.invite_as(who, &tool.name, &args).await; | ||
return made.map_err(|e| format!("{}: {}", e.error, e.message)); | ||
collection, | ||
rkey, | ||
record, | ||
} => { | ||
let written = self.record_as(who, &space, collection, rkey, record); | ||
written.await.map_err(said) | ||
} | ||
Plan::Invite { person, record } => { | ||
let written = self.invite_as(who, &person, record).await; | ||
written.map_err(said) | ||
} | ||
Plan::Grant { role, grant } => { | ||
let members = crate::group::members_space(&who.group); | ||
let collection = format!("{NS}.permissions"); | ||
let kept = self.group_record(&who.group, &members, &collection, "self"); | ||
let kept = kept.map_err(XrpcError::internal).map_err(said)?; | ||
let kept = kept.unwrap_or_default(); | ||
let write = group_host_mcp::regrant(&kept, &role, grant); | ||
Box::pin(self.carry_out(who, write)).await | ||
} | ||
} | ||
args["group"] = json!(who.group); | ||
} | ||
| ||
/// Asks the method `nsid` with `input` as `who`'s member, as the | ||
/// console does: the host asking itself as them. | ||
async fn ask_as( | ||
self: &Arc<Self>, | ||
who: &McpGrant, | ||
nsid: &str, | ||
procedure: bool, | ||
input: &Value, | ||
) -> Result<Value, String> { | ||
let cookie = self.session_cookie(&who.member, now_millis()); | ||
let cookie = format!("{}={cookie}", crate::console_login::COOKIE); | ||
let path = format!("/xrpc/{}", tool.nsid); | ||
let request = match tool.kind == Kind::Procedure { | ||
let path = format!("/xrpc/{nsid}"); | ||
let request = match procedure { | ||
true => Request::post(path) | ||
.header(header::CONTENT_TYPE, "application/json") | ||
.body(Body::from(args.to_string())), | ||
.body(Body::from(input.to_string())), | ||
false => { | ||
let mut url = reqwest::Url::parse("http://host/").expect("a URL"); | ||
url.set_path(&path); | ||
url.query_pairs_mut().extend_pairs(query_of(&args)); | ||
url.query_pairs_mut().extend_pairs(query_of(input)); | ||
let at = format!("{}?{}", url.path(), url.query().unwrap_or_default()); | ||
Request::get(at).body(Body::empty()) | ||
} | ||
| @@ -820,22 +822,34 @@ impl Host { | ||
request.headers_mut().insert(header::COOKIE, value); | ||
let res = crate::router(self.clone()).oneshot(request).await; | ||
let res = res.expect("the router answers every request"); | ||
let ok = res.status().is_success(); | ||
let status = res.status(); | ||
let bytes = axum::body::to_bytes(res.into_body(), usize::MAX).await; | ||
let body: Value = bytes | ||
.ok() | ||
.and_then(|b| serde_json::from_slice(&b).ok()) | ||
.unwrap_or_default(); | ||
if !ok { | ||
if !status.is_success() { | ||
let error = body["error"].as_str().unwrap_or("Error"); | ||
let message = body["message"].as_str().unwrap_or_default(); | ||
return Err(format!("{error}: {message}")); | ||
} | ||
Ok(body) | ||
} | ||
| ||
/// Calls `tool` with `args` as `who`, in their group: what it comes | ||
/// to, carried out; or why not, in the host's words. | ||
async fn call_as( | ||
self: &Arc<Self>, | ||
who: &McpGrant, | ||
tool: Tool, | ||
args: Value, | ||
) -> Result<Value, String> { | ||
let planned = group_host_mcp::plan(&tool, &args, &iso(now_millis())); | ||
self.carry_out(who, planned?).await | ||
} | ||
} | ||
| ||
/// The MCP server: each message an assistant sends, answered as the | ||
/// The MCP server: each message an MCP client sends, answered as the | ||
/// member it acts as, in their group. | ||
pub async fn mcp( | ||
State(host): State<Arc<Host>>, | ||
| @@ -851,7 +865,7 @@ pub async fn mcp( | ||
}; | ||
let found = host | ||
.store | ||
.assistant_by_access(&jose::sha256(token), now_millis()); | ||
.mcp_grant_by_access(&jose::sha256(token), now_millis()); | ||
let Some(who) = found.map_err(XrpcError::internal)? else { | ||
return Ok(challenge(&host, Some("invalid_token"))); | ||
}; | ||
| @@ -866,7 +880,7 @@ pub async fn mcp( | ||
}) | ||
} | ||
| ||
/// The assistants the caller connected to a group. | ||
/// The MCP clients the caller connected to a group. | ||
pub async fn list_connected_apps( | ||
State(host): State<Arc<Host>>, | ||
Query(p): Query<Params>, | ||
| @@ -875,7 +889,7 @@ pub async fn list_connected_apps( | ||
let me = signed_in(&host, &headers, &format!("{NS}.listConnectedApps")).await?; | ||
let group = param(&p, "group")?; | ||
group_of(&host, group)?; | ||
let connected = host.store.assistants_of(group, &me, now_millis()); | ||
let connected = host.store.mcp_clients_of(group, &me, now_millis()); | ||
let apps: Vec<Value> = connected | ||
.map_err(XrpcError::internal)? | ||
.iter() | ||
| @@ -891,7 +905,7 @@ pub async fn list_connected_apps( | ||
Ok(Json(json!({ "apps": apps }))) | ||
} | ||
| ||
/// Disconnects an assistant the caller connected to a group. | ||
/// Disconnects an MCP client the caller connected to a group. | ||
pub async fn revoke_connected_app( | ||
State(host): State<Arc<Host>>, | ||
headers: HeaderMap, | ||
| @@ -902,7 +916,7 @@ pub async fn revoke_connected_app( | ||
let client = body["clientId"].as_str(); | ||
let client = client.expect("its lexicon requires it"); | ||
group_of(&host, group)?; | ||
let ended = host.store.disconnect_assistant(group, &me, client); | ||
let ended = host.store.disconnect_mcp_client(group, &me, client); | ||
ended.map_err(XrpcError::internal)?; | ||
Ok(Json(json!({}))) | ||
} | ||
crates/group-host/src/oauth_store.rs+2−2
| @@ -399,8 +399,8 @@ 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"; | ||
// Their MCP clients, too, act as them no more. | ||
let sql = "DELETE FROM mcp_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+10−2
| @@ -413,6 +413,14 @@ pub const MIGRATIONS: &[&str] = &[ | ||
UPDATE mod_event SET kind = 'status', status = coalesce((SELECT p.status FROM mod_event p | ||
WHERE p.grp = mod_event.grp AND p.subject = mod_event.subject AND p.seq < mod_event.seq | ||
AND p.status IS NOT NULL ORDER BY p.seq DESC LIMIT 1), 'open') WHERE kind = 'note'; | ||
", | ||
// The MCP server's clients, requests and grants, named for it. | ||
" | ||
ALTER TABLE assistant_client RENAME TO mcp_client; | ||
ALTER TABLE assistant_request RENAME TO mcp_request; | ||
ALTER TABLE assistant_grant RENAME TO mcp_grant; | ||
DROP INDEX IF EXISTS assistant_grant_member; | ||
CREATE INDEX IF NOT EXISTS mcp_grant_member ON mcp_grant (grp, member); | ||
", | ||
]; | ||
| ||
| @@ -532,8 +540,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 mcp_grant WHERE grp = ?1", | ||
"DELETE FROM mcp_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/identity.rs+7−2
| @@ -188,10 +188,15 @@ fn gives_an_account_made_before_addresses_its_handle_as_its_address() { | ||
.iter() | ||
.position(|m| m.contains("INSERT OR IGNORE INTO address")) | ||
.unwrap(); | ||
// A table made after it is dropped, under the name a later one gave it. | ||
for later in &migrations[backfill + 1..] { | ||
for table in later.split("CREATE TABLE ").skip(1) { | ||
let made = later.split("CREATE TABLE ").skip(1); | ||
let renamed = later.split("RENAME TO ").skip(1); | ||
for table in made.chain(renamed) { | ||
let name = table.split_whitespace().next().unwrap(); | ||
conn.execute(&format!("DROP TABLE {name}"), []).unwrap(); | ||
let name = name.trim_end_matches(';'); | ||
let drop = format!("DROP TABLE IF EXISTS {name}"); | ||
conn.execute(&drop, []).unwrap(); | ||
} | ||
} | ||
conn.pragma_update(None, "user_version", backfill as i64) | ||
crates/group-host/tests/assistants.rs → crates/group-host/tests/mcp.rsrenamed+85−64
| @@ -1,4 +1,4 @@ | ||
//! Assistants: an MCP client, signed in at the host as MCP's authorization | ||
//! MCP: a client, signed in at the host as MCP's authorization | ||
//! spec has it, acting as the member who connected it, in the one group | ||
//! they chose, with what their roles allow and nothing more. | ||
| ||
| @@ -51,7 +51,7 @@ async fn make_member(h: &Running, group: &str, who: &str) { | ||
.unwrap(); | ||
} | ||
| ||
/// An assistant, registered: its client ID. | ||
/// An MCP client, registered: its client ID. | ||
async fn register(h: &Running) -> String { | ||
let res = h | ||
.http | ||
| @@ -73,7 +73,7 @@ fn pkce() -> (String, String) { | ||
(verifier, challenge) | ||
} | ||
| ||
/// The assistant's authorization request, with `extra` changes: where | ||
/// The MCP client's authorization request, with `extra` changes: where | ||
/// the browser is sent. | ||
async fn authorize( | ||
h: &Running, | ||
| @@ -129,7 +129,7 @@ async fn token(h: &Running, form: &[(&str, &str)]) -> (u16, Json) { | ||
(res.status().as_u16(), res.json().await.unwrap()) | ||
} | ||
| ||
/// Connects an assistant as `who`, in `group`: its client ID and tokens. | ||
/// Connects an MCP client as `who`, in `group`: its client ID and tokens. | ||
async fn connect(h: &Running, who: &Authority, group: &str) -> (String, Json) { | ||
let client = register(h).await; | ||
let (verifier, challenge) = pkce(); | ||
| @@ -177,7 +177,7 @@ async fn tool(h: &Running, token: &str, name: &str, arguments: Json) -> Json { | ||
} | ||
| ||
#[tokio::test] | ||
async fn says_where_an_assistant_signs_in() { | ||
async fn says_where_an_mcp_client_signs_in() { | ||
let h = start(&[], false).await; | ||
let (_, resource) = h | ||
.get_path("/.well-known/oauth-protected-resource/mcp") | ||
| @@ -225,7 +225,7 @@ async fn acts_as_the_member_in_the_group_they_chose() { | ||
let (_, challenge) = pkce(); | ||
let uri = requested(&h, &client, &challenge).await; | ||
| ||
// The approval page reads it as an assistant's. | ||
// The approval page reads it as an MCP client's. | ||
let lxm = format!("{NS}.getAuthorization"); | ||
let (status, view) = get( | ||
&h, | ||
| @@ -235,7 +235,7 @@ async fn acts_as_the_member_in_the_group_they_chose() { | ||
) | ||
.await; | ||
assert_eq!(status, 200, "{view}"); | ||
assert_eq!(view["assistant"], true); | ||
assert_eq!(view["mcp"], true); | ||
assert_eq!(view["client"]["name"], "Claude"); | ||
assert_eq!(view["groups"][0]["did"], group.as_str()); | ||
assert_eq!(view["groups"][0]["granted"], json!([])); | ||
| @@ -259,21 +259,21 @@ async fn acts_as_the_member_in_the_group_they_chose() { | ||
assert!(said["result"]["tools"].as_array().unwrap().len() > 15); | ||
| ||
// A query, in her group, without saying which. | ||
let got = tool(&h, access, "getGroup", json!({})).await; | ||
let got = tool(&h, access, "group_show", json!({})).await; | ||
assert_eq!( | ||
got["structuredContent"]["group"]["did"], | ||
group.as_str(), | ||
"{got}" | ||
); | ||
// Who is in it, found by part of their DID. | ||
let got = tool(&h, access, "listMembers", json!({"q": &alice.did[8..]})).await; | ||
let got = tool(&h, access, "member_list", json!({"q": &alice.did[8..]})).await; | ||
let found = &got["structuredContent"]["members"]; | ||
assert_eq!(found[0]["actor"]["did"], alice.did.as_str(), "{got}"); | ||
assert_eq!(found.as_array().unwrap().len(), 1, "{got}"); | ||
let got = tool( | ||
&h, | ||
access, | ||
"listInvites", | ||
"invite_list", | ||
json!({"limit": 5, "also": ["a", "b"]}), | ||
) | ||
.await; | ||
| @@ -282,8 +282,8 @@ async fn acts_as_the_member_in_the_group_they_chose() { | ||
let got = tool( | ||
&h, | ||
access, | ||
"sendInvite", | ||
json!({"invitee": bob.did, "message": "Ride with us", "expiresAt": "2099-01-01T00:00:00Z"}), | ||
"invite_send", | ||
json!({"person": bob.did, "message": "Ride with us", "expires_at": "2099-01-01T00:00:00Z"}), | ||
) | ||
.await; | ||
assert!(got.get("isError").is_none(), "{got}"); | ||
| @@ -292,7 +292,7 @@ async fn acts_as_the_member_in_the_group_they_chose() { | ||
.unwrap() | ||
.to_string(); | ||
assert!(uri.contains(&format!("/{group}/{NS}.invite/")), "{uri}"); | ||
let got = tool(&h, access, "sendInvite", json!({"invitee": "bob"})).await; | ||
let got = tool(&h, access, "invite_send", json!({"person": "bob"})).await; | ||
assert_eq!(got["isError"], true, "{got}"); | ||
let lxm = format!("{NS}.listInvites"); | ||
let (_, invites) = get( | ||
| @@ -311,9 +311,21 @@ async fn acts_as_the_member_in_the_group_they_chose() { | ||
"{invites}" | ||
); | ||
// Taken back; then there is none. | ||
let got = tool(&h, access, "takeBackInvite", json!({"invitee": bob.did})).await; | ||
let got = tool( | ||
&h, | ||
access, | ||
"invite_send", | ||
json!({"person": bob.did, "undo": true}), | ||
) | ||
.await; | ||
assert_eq!(got["structuredContent"]["uri"], uri.as_str(), "{got}"); | ||
let got = tool(&h, access, "takeBackInvite", json!({"invitee": bob.did})).await; | ||
let got = tool( | ||
&h, | ||
access, | ||
"invite_send", | ||
json!({"person": bob.did, "undo": true}), | ||
) | ||
.await; | ||
let said = got["content"][0]["text"].as_str().unwrap(); | ||
assert!(said.contains("InviteNotFound"), "{got}"); | ||
// What the host refuses, it says why. | ||
| @@ -325,25 +337,25 @@ async fn acts_as_the_member_in_the_group_they_chose() { | ||
let got = tool( | ||
&h, | ||
access, | ||
"putMembership", | ||
json!({"rkey": carol.did, "member": carol.did, "roles": ["member"], "createdAt": "2026-11-03T00:00:00Z"}), | ||
"member_assign", | ||
json!({"member": carol.did, "roles": ["member"]}), | ||
) | ||
.await; | ||
refused(&got, "JoinRequestNotFound"); | ||
let got = tool(&h, access, "deleteMembership", json!({"rkey": alice.did})).await; | ||
let got = tool(&h, access, "member_eject", json!({"member": alice.did})).await; | ||
refused(&got, "LastConfigurer"); | ||
let got = tool(&h, access, "deleteRole", json!({"rkey": "member"})).await; | ||
let got = tool(&h, access, "role_delete", json!({"role": "member"})).await; | ||
refused(&got, "RoleInUse"); | ||
// A method of the host's refused says why in its words. | ||
let got = tool(&h, access, "denyJoinRequest", json!({"member": carol.did})).await; | ||
let got = tool(&h, access, "join_deny", json!({"member": carol.did})).await; | ||
refused(&got, "JoinRequestNotFound"); | ||
// The group's records, written as the group, as she may: a role, what | ||
// it may do, and who holds it. | ||
let got = tool( | ||
&h, | ||
access, | ||
"putRole", | ||
json!({"rkey": "leader", "displayName": "Ride leader"}), | ||
"role_set", | ||
json!({"role": "leader", "display_name": "Ride leader"}), | ||
) | ||
.await; | ||
let uri = format!( | ||
| @@ -359,19 +371,28 @@ async fn acts_as_the_member_in_the_group_they_chose() { | ||
}; | ||
let leader = kept("role", "leader").unwrap(); | ||
assert_eq!(leader.get("rkey"), None); | ||
let mut permissions = kept("permissions", "self").unwrap(); | ||
permissions["grants"] | ||
.as_array_mut() | ||
.unwrap() | ||
.push(json!({"role": "leader", "scopes": [], "assignable": []})); | ||
let grants = |p: Json| p["grants"].as_array().unwrap().clone(); | ||
let before = grants(kept("permissions", "self").unwrap()); | ||
let got = tool( | ||
&h, | ||
access, | ||
"putPermissions", | ||
json!({"grants": permissions["grants"]}), | ||
"role_grant", | ||
json!({"role": "leader", "assignable": []}), | ||
) | ||
.await; | ||
assert!(got.get("isError").is_none(), "{got}"); | ||
let mut after = before.clone(); | ||
after.push(json!({"role": "leader", "scopes": [], "assignable": []})); | ||
assert_eq!(grants(kept("permissions", "self").unwrap()), after); | ||
// Dropped, it would be a grant of a role she may not assign: refused, | ||
// as any write of the record is. | ||
let undo = json!({"role": "leader", "undo": true}); | ||
let got = tool(&h, access, "role_grant", undo).await; | ||
refused(&got, "NotAssignable"); | ||
assert_eq!(grants(kept("permissions", "self").unwrap()), after); | ||
// What a tool is not given, it says it wants. | ||
let got = tool(&h, access, "role_grant", json!({})).await; | ||
refused(&got, "role is required"); | ||
let lxm = format!("{NS}.requestJoin"); | ||
post( | ||
&h, | ||
| @@ -383,13 +404,13 @@ async fn acts_as_the_member_in_the_group_they_chose() { | ||
let got = tool( | ||
&h, | ||
access, | ||
"putMembership", | ||
json!({"rkey": carol.did, "member": carol.did, "roles": ["member"], "createdAt": "2026-11-03T00:00:00Z"}), | ||
"member_assign", | ||
json!({"member": carol.did, "roles": ["member"]}), | ||
) | ||
.await; | ||
assert!(got.get("isError").is_none(), "{got}"); | ||
assert!(kept("membership", &carol.did).is_some()); | ||
let got = tool(&h, access, "deleteMembership", json!({"rkey": carol.did})).await; | ||
let got = tool(&h, access, "member_eject", json!({"member": carol.did})).await; | ||
assert!(got.get("isError").is_none(), "{got}"); | ||
assert!(kept("membership", &carol.did).is_none()); | ||
// Another group's, never: the group is the one she chose. | ||
| @@ -399,7 +420,7 @@ async fn acts_as_the_member_in_the_group_they_chose() { | ||
json!({"handle": "hikers.groups.test", "displayName": "Hikers"}), | ||
) | ||
.await; | ||
let got = tool(&h, access, "getGroup", json!({"group": other})).await; | ||
let got = tool(&h, access, "group_show", json!({"group": other})).await; | ||
assert_eq!(got["structuredContent"]["group"]["did"], group.as_str()); | ||
} | ||
| ||
| @@ -422,8 +443,8 @@ async fn writes_the_groups_profile_and_rules_as_the_group() { | ||
}; | ||
| ||
// The profile, at its one key, replaced whole. | ||
let profile = json!({"displayName": "Riders United", "joinPolicy": "open"}); | ||
let got = tool(&h, access, "putProfile", profile).await; | ||
let profile = json!({"display_name": "Riders United", "join_policy": "open"}); | ||
let got = tool(&h, access, "profile_set", profile).await; | ||
assert!(got.get("isError").is_none(), "{got}"); | ||
let uri = format!("{meta}/{group}/{NS}.profile/self"); | ||
assert_eq!(got["structuredContent"]["uri"], uri); | ||
| @@ -438,7 +459,7 @@ async fn writes_the_groups_profile_and_rules_as_the_group() { | ||
let got = tool( | ||
&h, | ||
access, | ||
"putRule", | ||
"rule_set", | ||
json!({"title": "Be kind", "text": ""}), | ||
) | ||
.await; | ||
| @@ -446,11 +467,11 @@ async fn writes_the_groups_profile_and_rules_as_the_group() { | ||
let made = got["structuredContent"]["uri"].as_str().unwrap(); | ||
let rkey = made.rsplit('/').next().unwrap().to_string(); | ||
assert_eq!(kept("rule", &rkey).unwrap()["title"], "Be kind"); | ||
let again = json!({"rkey": rkey, "title": "Be very kind", "text": "Always."}); | ||
let got = tool(&h, access, "putRule", again).await; | ||
let again = json!({"rule": rkey, "title": "Be very kind", "text": "Always."}); | ||
let got = tool(&h, access, "rule_set", again).await; | ||
assert_eq!(got["structuredContent"]["uri"], made, "{got}"); | ||
assert_eq!(kept("rule", &rkey).unwrap()["title"], "Be very kind"); | ||
let got = tool(&h, access, "deleteRule", json!({"rkey": rkey})).await; | ||
let got = tool(&h, access, "rule_delete", json!({"rule": rkey})).await; | ||
assert_eq!(got["structuredContent"], json!({"uri": made}), "{got}"); | ||
assert_eq!(kept("rule", &rkey), None); | ||
| ||
| @@ -458,8 +479,8 @@ async fn writes_the_groups_profile_and_rules_as_the_group() { | ||
let got = tool( | ||
&h, | ||
access, | ||
"putProfile", | ||
json!({"displayName": " ", "joinPolicy": "open"}), | ||
"profile_set", | ||
json!({"display_name": " ", "join_policy": "open"}), | ||
) | ||
.await; | ||
assert_eq!(got["isError"], true, "{got}"); | ||
| @@ -468,13 +489,13 @@ async fn writes_the_groups_profile_and_rules_as_the_group() { | ||
let got = tool( | ||
&h, | ||
access, | ||
"putRule", | ||
json!({"rkey": "chosen", "title": "x", "text": ""}), | ||
"rule_set", | ||
json!({"rule": "chosen", "title": "x", "text": ""}), | ||
) | ||
.await; | ||
assert_eq!(got["isError"], true, "{got}"); | ||
| ||
// What it did is in the group's log, as the assistant's. | ||
// What it did is in the group's log, as the MCP client's. | ||
let lxm = format!("{NS}.listGroupTokens"); | ||
let (_, listed) = get( | ||
&h, | ||
| @@ -514,18 +535,18 @@ async fn does_only_what_the_members_roles_allow() { | ||
make_member(&h, &group, &bob.did).await; | ||
let (_, tokens) = connect(&h, &bob, &group).await; | ||
let access = tokens["access_token"].as_str().unwrap(); | ||
let got = tool(&h, access, "putRule", json!({"title": "No spam"})).await; | ||
let got = tool(&h, access, "rule_set", json!({"title": "No spam"})).await; | ||
assert_eq!(got["isError"], true, "{got}"); | ||
// Nor may it write what his roles do not: he may give nobody roles. | ||
let got = tool( | ||
&h, | ||
access, | ||
"putMembership", | ||
json!({"rkey": bob.did, "member": bob.did, "roles": ["member", "admin"], "createdAt": "2026-11-03T00:00:00Z"}), | ||
"member_assign", | ||
json!({"member": bob.did, "roles": ["member", "admin"]}), | ||
) | ||
.await; | ||
assert_eq!(got["isError"], true, "{got}"); | ||
// Put out, his assistant acts as him there no more. | ||
// Put out, his MCP client acts as him there no more. | ||
let runs = common::members::Session::runs(&h, &alice, &group).await; | ||
let said = runs.delete(&h, "membership", &bob.did).await; | ||
assert_eq!(said.status, 200, "{}", said.body); | ||
| @@ -625,7 +646,7 @@ async fn refreshes_lists_and_disconnects() { | ||
} | ||
| ||
#[tokio::test] | ||
async fn sends_a_declined_assistant_back_saying_so() { | ||
async fn sends_a_declined_mcp_client_back_saying_so() { | ||
let h = start(&[], false).await; | ||
let [alice, ..] = people(&h).await; | ||
let group = start_group( | ||
| @@ -783,7 +804,7 @@ async fn refuses_a_request_it_cannot_trust() { | ||
.unwrap(); | ||
assert_eq!(res.status(), 201); | ||
let said: Json = res.json().await.unwrap(); | ||
assert_eq!(said["client_name"], "An assistant"); | ||
assert_eq!(said["client_name"], "An AI app"); | ||
} | ||
| ||
/// A client metadata document, served at a URL `make` is given: the URL. | ||
| @@ -881,11 +902,11 @@ async fn says_what_it_cannot_do_as_json_rpc_does() { | ||
); | ||
assert_eq!(ask(call(json!({"name": "nothing"}))).await, Some(-32602)); | ||
assert_eq!( | ||
ask(call(json!({"name": "getGroup", "arguments": 1}))).await, | ||
ask(call(json!({"name": "group_show", "arguments": 1}))).await, | ||
Some(-32602) | ||
); | ||
// No arguments at all is none to give. | ||
let said: Json = mcp(h, Some(access), call(json!({"name": "getGroup"}))) | ||
let said: Json = mcp(h, Some(access), call(json!({"name": "group_show"}))) | ||
.await | ||
.json() | ||
.await | ||
| @@ -904,16 +925,16 @@ async fn forgets_a_client_that_never_connected() { | ||
let now = 10 * day; | ||
let back = vec![BACK.to_string()]; | ||
store | ||
.register_assistant("old", "Old", &back, now - 2 * day) | ||
.register_mcp_client("old", "Old", &back, now - 2 * day) | ||
.unwrap(); | ||
store.register_assistant("new", "New", &back, now).unwrap(); | ||
assert!(store.registered_assistant("old").unwrap().is_none()); | ||
assert!(store.registered_assistant("new").unwrap().is_some()); | ||
store.register_mcp_client("new", "New", &back, now).unwrap(); | ||
assert!(store.registered_mcp_client("old").unwrap().is_none()); | ||
assert!(store.registered_mcp_client("new").unwrap().is_some()); | ||
} | ||
| ||
#[tokio::test] | ||
async fn keeps_a_client_once_connected_and_forgets_a_lapsed_connection() { | ||
use group_host::assistants::Connected; | ||
use group_host::mcp::McpGrant; | ||
let h = start(&[], false).await; | ||
let [alice, ..] = people(&h).await; | ||
let group = start_group( | ||
| @@ -927,7 +948,7 @@ async fn keeps_a_client_once_connected_and_forgets_a_lapsed_connection() { | ||
let now = 100 * day; | ||
let back = vec![BACK.to_string()]; | ||
let connect = |id: &str, client: &str, at: i64| { | ||
let c = Connected { | ||
let c = McpGrant { | ||
id: id.into(), | ||
group: group.clone(), | ||
member: alice.did.clone(), | ||
| @@ -937,21 +958,21 @@ async fn keeps_a_client_once_connected_and_forgets_a_lapsed_connection() { | ||
used_at: at, | ||
}; | ||
store | ||
.connect_assistant(&c, &format!("a-{id}"), &format!("r-{id}"), at) | ||
.connect_mcp_client(&c, &format!("a-{id}"), &format!("r-{id}"), at) | ||
.unwrap(); | ||
}; | ||
// Connected, then disconnected: kept, to connect again. | ||
store | ||
.register_assistant("kept", "Kept", &back, now - 2 * day) | ||
.register_mcp_client("kept", "Kept", &back, now - 2 * day) | ||
.unwrap(); | ||
connect("one", "kept", now - 2 * day); | ||
store | ||
.disconnect_assistant(&group, &alice.did, "kept") | ||
.disconnect_mcp_client(&group, &alice.did, "kept") | ||
.unwrap(); | ||
// A connection whose refresh token lapsed long ago. | ||
connect("two", "lapsed", now - 40 * day); | ||
store.register_assistant("new", "New", &back, now).unwrap(); | ||
assert!(store.registered_assistant("kept").unwrap().is_some()); | ||
let lapsed = store.disconnect_assistant(&group, &alice.did, "lapsed"); | ||
store.register_mcp_client("new", "New", &back, now).unwrap(); | ||
assert!(store.registered_mcp_client("kept").unwrap().is_some()); | ||
let lapsed = store.disconnect_mcp_client(&group, &alice.did, "lapsed"); | ||
assert_eq!(lapsed.unwrap(), 0); | ||
} | ||
crates/group-host/tests/moderation.rs+19−2
crates/group-host-mcp/src/lib.rs+602−203
805 lines changed: not loaded until asked for.
crates/group-host-mcp/tests/protocol.rs+351−130
481 lines changed: not loaded until asked for.
crates/opensocial/src/lib.rs+317−125
442 lines changed: not loaded until asked for.