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
+123
View File
@@ -0,0 +1,123 @@
//! The token check in front of `/mcp`. The backend knows the tokens: it is
//! asked once a minute per token (`/oauth/whoami`); the tools send the token
//! on with every call, and the backend checks it again there, so a revoked
//! connection stops at once whatever this cache says.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use axum::extract::{Request, State};
use axum::http::header::{AUTHORIZATION, WWW_AUTHENTICATE};
use axum::http::{HeaderValue, StatusCode};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use sha2::{Digest, Sha256};
use crate::App;
const CACHE_TTL: Duration = Duration::from_secs(60);
const CACHE_MAX: usize = 1000;
/// The caller's token, for the tools (in the HTTP request's extensions).
#[derive(Clone)]
pub struct Bearer(pub String);
/// What the backend said about a token.
#[derive(Debug, PartialEq, Eq)]
pub enum Verdict {
Valid,
/// Unknown, expired, revoked, or for another server.
Invalid,
/// Valid, but its owner is no admin any more.
Forbidden,
/// The backend did not answer.
Unavailable,
}
/// Tokens found valid in the last minute (by their hash).
#[derive(Default)]
pub struct TokenCache(Mutex<HashMap<[u8; 32], Instant>>);
impl TokenCache {
fn fresh(&self, key: &[u8; 32]) -> bool {
self.0.lock().expect("token cache").get(key).is_some_and(|at| at.elapsed() < CACHE_TTL)
}
fn remember(&self, key: [u8; 32]) {
let mut map = self.0.lock().expect("token cache");
if map.len() >= CACHE_MAX {
map.retain(|_, at| at.elapsed() < CACHE_TTL);
}
map.insert(key, Instant::now());
}
/// The backend refused the token in a tool call: the next request asks again
/// (and gets 401, so the client logs in again or refreshes).
pub fn forget(&self, token: &str) {
let key: [u8; 32] = Sha256::digest(token.as_bytes()).into();
self.0.lock().expect("token cache").remove(&key);
}
}
/// Asks the backend (or the cache) about a token.
pub async fn check(app: &App, token: &str) -> Verdict {
let key: [u8; 32] = Sha256::digest(token.as_bytes()).into();
if app.tokens.fresh(&key) {
return Verdict::Valid;
}
let verdict = match app.api.whoami(token).await {
Ok(Some(who)) => {
let resource = who["resource"].as_str();
let ours = |r: &str| r.trim_end_matches('/') == app.config.mcp_public_url.trim_end_matches('/');
if resource.is_none_or(ours) { Verdict::Valid } else { Verdict::Invalid }
}
Ok(None) => Verdict::Invalid,
Err(status) if status == StatusCode::FORBIDDEN => Verdict::Forbidden,
Err(status) if status == StatusCode::UNAUTHORIZED => Verdict::Invalid,
Err(_) => Verdict::Unavailable,
};
if verdict == Verdict::Valid {
app.tokens.remember(key);
}
verdict
}
/// 401 (or 403) with where to find the OAuth metadata, as MCP clients expect.
fn refuse(app: &App, status: StatusCode, error: Option<&str>) -> Response {
let mut value = String::from("Bearer");
if let Some(error) = error {
value.push_str(&format!(" error=\"{error}\","));
}
value.push_str(&format!(" scope=\"admin\", resource_metadata=\"{}\"", app.config.resource_metadata_url()));
let mut response =
(status, axum::Json(serde_json::json!({ "error": error.unwrap_or("unauthorized") }))).into_response();
if let Ok(header) = HeaderValue::from_str(&value) {
response.headers_mut().insert(WWW_AUTHENTICATE, header);
}
response
}
/// Middleware: only requests with a valid token reach the MCP service.
pub async fn require_token(State(app): State<Arc<App>>, mut request: Request, next: Next) -> Response {
let token = request
.headers()
.get(AUTHORIZATION)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.strip_prefix("Bearer "))
.map(|t| t.trim().to_string())
.filter(|t| !t.is_empty());
let Some(token) = token else { return refuse(&app, StatusCode::UNAUTHORIZED, None) };
match check(&app, &token).await {
Verdict::Valid => {
request.extensions_mut().insert(Bearer(token));
next.run(request).await
}
Verdict::Invalid => refuse(&app, StatusCode::UNAUTHORIZED, Some("invalid_token")),
Verdict::Forbidden => refuse(&app, StatusCode::FORBIDDEN, Some("insufficient_scope")),
Verdict::Unavailable => {
(StatusCode::SERVICE_UNAVAILABLE, axum::Json(serde_json::json!({ "error": "backend_unavailable" })))
.into_response()
}
}
}