Admin tools for Claude: an MCP server, connected with an admin's approval
CI / build (push) Skipped
CI / deploy (push) Skipped
CI / test (push) Successful in 4m27s

- services/mcp: the MCP server at /mcp (Streamable HTTP, stateless): the
  admin's reading tools, the daily tasks and the forum's moderation; every
  tool calls the site's API with the caller's token, and members' e-mail
  addresses and names are masked in the answers.
- Backend: OAuth 2.1 for MCP clients (registration with Claude's or a local
  return address only, PKCE, rotating refresh tokens, revocation); the admin
  guards accept the token for reading and the writes in MCP_WRITES only.
- Forum: an admin's token reaches the moderator endpoints only.
- Frontend: the approval page (/oauth/engedely), Admin → Claude to revoke a
  connection, the authorization server's metadata at its standard address.
- Deploy: the mcp service in compose, Caddy, CI; the worker removes old
  codes, tokens and clients. docs/mcp.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-27 17:09:14 +00:00
co-authored by Claude Opus 5.5
parent 08ad7b0a79
commit 2c63384606
40 changed files with 3695 additions and 49 deletions
+16 -1
View File
@@ -8,7 +8,7 @@ use tokio::sync::watch;
const INTERVAL: Duration = Duration::from_secs(3600);
/// (what, statement) pairs; each returns the number of deleted rows.
const STATEMENTS: [(&str, &str); 16] = [
const STATEMENTS: [(&str, &str); 20] = [
("sessions", "DELETE FROM sessions WHERE expires_at < now()"),
("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"),
// Sent e-mails contain links with tokens; keep them a week for support.
@@ -60,6 +60,21 @@ const STATEMENTS: [(&str, &str); 16] = [
"DELETE FROM forum.conversations WHERE status IN ('pending', 'declined') AND last_message_at IS NULL \
AND coalesce(responded_at, created_at) < now() - interval '90 days'",
),
// MCP clients (docs/mcp.md): codes and tokens past their time, connections
// revoked a month ago or with no token left, and clients a month without
// a connection (a client registered but never approved, or long revoked).
("oauth_codes", "DELETE FROM oauth_codes WHERE expires_at < now() - interval '1 day'"),
("oauth_tokens", "DELETE FROM oauth_tokens WHERE refresh_expires_at < now()"),
(
"oauth_grants",
"DELETE FROM oauth_grants g WHERE g.revoked_at < now() - interval '30 days' \
OR NOT EXISTS (SELECT 1 FROM oauth_tokens t WHERE t.grant_id = g.id)",
),
(
"oauth_clients",
"DELETE FROM oauth_clients c WHERE c.created_at < now() - interval '30 days' \
AND NOT EXISTS (SELECT 1 FROM oauth_grants g WHERE g.client_id = c.id)",
),
];
pub async fn run_once(db: &PgPool) -> Result<Vec<(&'static str, u64)>, sqlx::Error> {
+54
View File
@@ -281,6 +281,10 @@ async fn cleanup_removes_only_expired_data(db: PgPool) {
("forum_mod_log", 0),
("forum_bans", 0),
("forum_requests", 0),
("oauth_codes", 0),
("oauth_tokens", 0),
("oauth_grants", 0),
("oauth_clients", 0),
]
);
let kept: Vec<Uuid> = sqlx::query_scalar("SELECT id FROM gifts ORDER BY id").fetch_all(&db).await.unwrap();
@@ -1351,3 +1355,53 @@ async fn monday_weekly_horoscope_emails_go_once_a_week(db: PgPool) {
let next = monday.saturating_add(time::Duration::days(7));
assert_eq!(crate::weekly::queue_week(&db, "https://sorsfonalak.test", next).await.unwrap(), 1);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn cleanup_ends_old_mcp_connections(db: PgPool) {
let user = Uuid::now_v7();
sqlx::query("INSERT INTO users (id, email, roles) VALUES ($1, 'admin@example.com', '{user,admin}')")
.bind(user)
.execute(&db)
.await
.unwrap();
// Clients: one in use, one never approved for a month, one just registered.
sqlx::query(
"INSERT INTO oauth_clients (id, name, redirect_uris, created_at) VALUES \
('used', 'Claude', '{}', now() - interval '60 days'), \
('stale', 'Claude', '{}', now() - interval '31 days'), \
('fresh', 'Claude', '{}', now())",
)
.execute(&db)
.await
.unwrap();
// Connections: a live one, one whose refresh token ran out.
let (live, ended) = (Uuid::now_v7(), Uuid::now_v7());
for (grant, refresh_expires) in [(live, "now() + interval '1 day'"), (ended, "now() - interval '1 second'")] {
sqlx::query("INSERT INTO oauth_grants (id, client_id, user_id, scope) VALUES ($1, 'used', $2, 'admin')")
.bind(grant)
.bind(user)
.execute(&db)
.await
.unwrap();
sqlx::query(&format!(
"INSERT INTO oauth_tokens (id, grant_id, access_hash, access_expires_at, refresh_hash, refresh_expires_at) \
VALUES ($1, $2, $3, now() - interval '1 hour', $4, {refresh_expires})"
))
.bind(Uuid::now_v7())
.bind(grant)
.bind(Uuid::now_v7().as_bytes().to_vec())
.bind(Uuid::now_v7().as_bytes().to_vec())
.execute(&db)
.await
.unwrap();
}
let deleted = crate::cleanup::run_once(&db).await.unwrap();
let count = |what: &str| deleted.iter().find(|(w, _)| *w == what).unwrap().1;
assert_eq!((count("oauth_tokens"), count("oauth_grants"), count("oauth_clients")), (1, 1, 1));
let grants: Vec<Uuid> = sqlx::query_scalar("SELECT id FROM oauth_grants").fetch_all(&db).await.unwrap();
assert_eq!(grants, vec![live]);
let clients: Vec<String> =
sqlx::query_scalar("SELECT id FROM oauth_clients ORDER BY id").fetch_all(&db).await.unwrap();
assert_eq!(clients, vec!["fresh", "used"]);
}