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
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "mcp"
description = "Sorsfonalak MCP server: the admin tools for Claude, called with the admin's OAuth token"
edition.workspace = true
version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
service-kit.workspace = true
anyhow.workspace = true
axum.workspace = true
reqwest.workspace = true
rmcp = { version = "3.12", default-features = false, features = ["server", "macros", "transport-streamable-http-server"] }
schemars = "1"
serde.workspace = true
serde_json.workspace = true
sha2.workspace = true
tokio = { workspace = true, features = ["time"] }
tower-http.workspace = true
tracing.workspace = true
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
http-body-util = "0.1"
+33
View File
@@ -0,0 +1,33 @@
# syntax=docker/dockerfile:1
#
# Build from the repository root:
# docker build -f services/mcp/Dockerfile -t sorsfonalak/mcp .
ARG RUST_VERSION=1.99
# --- 1. static (musl) build ----------------------------------------------------
FROM rust:${RUST_VERSION}-alpine AS build
RUN apk add --no-cache musl-dev
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY crates crates
COPY services services
RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \
--mount=type=cache,target=/app/target,sharing=locked \
cargo build --release --locked -p mcp \
&& cp target/release/mcp /mcp
# The log directory (LOG_DIR); a volume mounted here takes over its owner.
RUN mkdir /logs
# --- 2. runtime: the binary only (TLS roots are compiled in via webpki-roots) ---
FROM scratch
COPY --from=build /mcp /mcp
COPY --from=build --chown=65532:65532 /logs /logs
ENV BIND_ADDR=0.0.0.0:8084 \
LOG_FORMAT=json \
RUST_LOG=info,rmcp=warn
USER 65532:65532
EXPOSE 8084
HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
CMD ["/mcp", "healthcheck"]
ENTRYPOINT ["/mcp"]
+77
View File
@@ -0,0 +1,77 @@
//! Calls of the site's API with the caller's token.
use std::time::Duration;
use axum::http::StatusCode;
use reqwest::Method;
use serde_json::Value;
pub struct Api {
http: reqwest::Client,
base: String,
}
/// A refused or failed call: the status and the API's message.
#[derive(Debug)]
pub struct Failure {
pub status: Option<StatusCode>,
pub message: String,
}
impl Api {
pub fn new(base: &str) -> Self {
let http = reqwest::Client::builder()
.timeout(Duration::from_secs(60))
.user_agent("sorsfonalak-mcp")
.build()
.expect("HTTP client");
Self { http, base: base.trim_end_matches('/').to_string() }
}
/// `/oauth/whoami`: `Ok(Some)` for a valid token, `Ok(None)` for an
/// unknown one, `Err(status)` otherwise.
pub async fn whoami(&self, token: &str) -> Result<Option<Value>, StatusCode> {
let response =
self.http.get(format!("{}/oauth/whoami", self.base)).bearer_auth(token).send().await.map_err(|e| {
tracing::warn!(error = %e, "whoami");
StatusCode::BAD_GATEWAY
})?;
let status = StatusCode::from_u16(response.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
match status {
StatusCode::OK => Ok(Some(response.json().await.map_err(|_| StatusCode::BAD_GATEWAY)?)),
StatusCode::UNAUTHORIZED => Ok(None),
other => Err(other),
}
}
/// One call; the answer's JSON (`null` for an empty one).
pub async fn call(
&self,
token: &str,
method: Method,
path: &str,
query: &[(&str, String)],
body: Option<&Value>,
) -> Result<Value, Failure> {
let mut request = self.http.request(method, format!("{}{path}", self.base)).bearer_auth(token).query(query);
if let Some(body) = body {
request = request.json(body);
}
let response = request
.send()
.await
.map_err(|e| Failure { status: None, message: format!("A szerver nem érhető el: {e}") })?;
let status = StatusCode::from_u16(response.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY);
let bytes = response.bytes().await.map_err(|e| Failure { status: Some(status), message: e.to_string() })?;
let value: Value =
if bytes.is_empty() { Value::Null } else { serde_json::from_slice(&bytes).unwrap_or(Value::Null) };
if status.is_success() {
return Ok(value);
}
let message = value["error"]["message"]
.as_str()
.map(str::to_string)
.unwrap_or_else(|| format!("A kérés nem sikerült ({status})."));
Err(Failure { status: Some(status), message })
}
}
+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()
}
}
}
+149
View File
@@ -0,0 +1,149 @@
//! Sorsfonalak MCP server (docs/mcp.md): the admin tools for Claude.
//!
//! Claude connects to `/mcp` (Streamable HTTP, stateless). Without a valid
//! token it gets 401 with the address of this server's OAuth metadata, which
//! names the site as the authorization server: an admin approves the
//! connection there, and the backend issues the tokens. Every tool calls the
//! site's API (through the frontend's `/api/v1` proxy, like the admin pages)
//! with the caller's token, so the backend decides what is allowed, and the
//! answers go back with the members' e-mail addresses and names masked.
//!
//! Configuration: `API_URL` (default `http://localhost:3001/api/v1`),
//! `PUBLIC_BASE_URL` (the site, the authorization server; default
//! `http://localhost:3001`), `MCP_PUBLIC_URL` (this server's address as
//! Claude sees it; default `http://localhost:8084/mcp`), `BIND_ADDR` (default
//! `0.0.0.0:8084`), `LOG_FORMAT`, `RUST_LOG`, `LOG_DIR`.
//!
//! `mcp healthcheck` performs a local health check (for Docker).
mod api;
mod auth;
mod mask;
#[cfg(test)]
mod tests;
mod tools;
use std::sync::Arc;
use anyhow::Context;
use axum::routing::get;
use axum::{Json, Router, middleware};
use rmcp::transport::streamable_http_server::session::never::NeverSessionManager;
use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
use serde_json::{Value, json};
use tower_http::trace::TraceLayer;
const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8084";
pub struct Config {
/// The site's API (`…/api/v1`).
pub api_url: String,
/// The site: the OAuth authorization server.
pub public_base_url: String,
/// This server's `/mcp` address as clients see it (the tokens' audience).
pub mcp_public_url: String,
}
impl Config {
fn from_env() -> Self {
let var = |name: &str, default: &str| {
std::env::var(name)
.ok()
.map(|v| v.trim().trim_end_matches('/').to_string())
.filter(|v| !v.is_empty())
.unwrap_or_else(|| default.to_string())
};
Self {
api_url: var("API_URL", "http://localhost:3001/api/v1"),
public_base_url: var("PUBLIC_BASE_URL", "http://localhost:3001"),
mcp_public_url: var("MCP_PUBLIC_URL", "http://localhost:8084/mcp"),
}
}
/// `scheme://host[:port]` of the MCP address.
fn origin(&self) -> &str {
let after_scheme = self.mcp_public_url.find("://").map_or(0, |i| i + 3);
let end = self.mcp_public_url[after_scheme..].find('/').map_or(self.mcp_public_url.len(), |i| after_scheme + i);
&self.mcp_public_url[..end]
}
/// The host name of the MCP address (accepted as the `Host` header).
fn host(&self) -> String {
let origin = self.origin();
let host = origin.split("://").nth(1).unwrap_or(origin);
host.split(':').next().unwrap_or(host).to_string()
}
/// Where the protected resource's metadata is (in the 401 answers).
pub fn resource_metadata_url(&self) -> String {
format!("{}/.well-known/oauth-protected-resource/mcp", self.origin())
}
}
pub struct App {
pub config: Config,
pub api: api::Api,
pub tokens: auth::TokenCache,
}
impl App {
pub fn new(config: Config) -> Self {
Self { api: api::Api::new(&config.api_url), config, tokens: auth::TokenCache::default() }
}
}
/// The protected resource's metadata (RFC 9728).
async fn resource_metadata(axum::extract::State(app): axum::extract::State<Arc<App>>) -> Json<Value> {
Json(json!({
"resource": app.config.mcp_public_url,
"authorization_servers": [app.config.public_base_url],
"scopes_supported": ["admin"],
"bearer_methods_supported": ["header"],
"resource_name": "Sorsfonalak admin",
"resource_documentation": format!("{}/admin", app.config.public_base_url),
}))
}
async fn health() -> Json<Value> {
Json(json!({ "status": "ok" }))
}
pub fn router(app: Arc<App>) -> Router {
let mut hosts = vec![app.config.host(), "localhost".to_string(), "127.0.0.1".to_string(), "mcp".to_string()];
hosts.dedup();
let config = StreamableHttpServerConfig::default()
.with_legacy_session_mode(false)
.with_json_response(true)
.with_allowed_hosts(hosts);
let tools_app = app.clone();
let mcp = StreamableHttpService::new(
move || Ok(tools::Tools::new(tools_app.clone())),
Arc::new(NeverSessionManager::default()),
config,
);
let protected =
Router::new().nest_service("/mcp", mcp).layer(middleware::from_fn_with_state(app.clone(), auth::require_token));
Router::new()
.route("/healthz", get(health))
.route("/.well-known/oauth-protected-resource", get(resource_metadata))
.route("/.well-known/oauth-protected-resource/mcp", get(resource_metadata))
.with_state(app)
.merge(protected)
.layer(TraceLayer::new_for_http().make_span_with(service_kit::RequestLog).on_response(service_kit::RequestLog))
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let addr = service_kit::bind_addr(DEFAULT_BIND_ADDR)?;
if std::env::args().nth(1).as_deref() == Some("healthcheck") {
return service_kit::healthcheck(addr);
}
let _log = service_kit::init_logging("mcp");
let config = Config::from_env();
tracing::info!(api = %config.api_url, resource = %config.mcp_public_url, "starting");
let app = router(Arc::new(App::new(config)));
let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
tracing::info!(%addr, "listening");
axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?;
Ok(())
}
+121
View File
@@ -0,0 +1,121 @@
//! The members' personal data stays on the site: e-mail addresses go to
//! Claude as `an***@gmail.com` (in free text too), and people's names as
//! `[rejtve]`. Forum nicknames are pseudonyms and stay; so do the names of
//! famous people and packages (a `name` is a person's only beside an `email`).
use serde_json::{Map, Value};
/// Keys whose text is always a person's name.
const NAME_KEYS: [&str; 7] =
["display_name", "from_name", "inviter_name", "recipient_name", "invited_by", "accepted_by", "buyer_name"];
const HIDDEN: &str = "[rejtve]";
pub fn mask(value: &mut Value) {
match value {
Value::String(s) => {
if s.contains('@') {
*s = mask_emails(s);
}
}
Value::Array(items) => items.iter_mut().for_each(mask),
Value::Object(map) => mask_object(map),
_ => {}
}
}
fn mask_object(map: &mut Map<String, Value>) {
let has_email = map.get("email").is_some_and(Value::is_string);
for (key, child) in map.iter_mut() {
let a_name = NAME_KEYS.contains(&key.as_str()) || (has_email && key == "name");
if a_name && child.is_string() {
*child = Value::String(HIDDEN.into());
} else {
mask(child);
}
}
}
fn local_char(c: char) -> bool {
c.is_alphanumeric() || "._%+-".contains(c)
}
fn domain_char(c: char) -> bool {
c.is_alphanumeric() || ".-".contains(c)
}
/// Every e-mail address in the text: the first two characters of the name
/// part, then `***`, and the domain.
pub fn mask_emails(text: &str) -> String {
let chars: Vec<char> = text.chars().collect();
let mut out = String::with_capacity(text.len());
let mut i = 0;
while i < chars.len() {
if chars[i] != '@' {
out.push(chars[i]);
i += 1;
continue;
}
// The name part is already in `out`: find where it starts.
let mut start = i;
while start > 0 && local_char(chars[start - 1]) {
start -= 1;
}
let mut end = i + 1;
while end < chars.len() && domain_char(chars[end]) {
end += 1;
}
let domain: String = chars[i + 1..end].iter().collect::<String>().trim_end_matches('.').to_string();
let local_len = i - start;
if local_len == 0 || !domain.contains('.') {
out.push('@');
i += 1;
continue;
}
let kept: String = chars[start..start + local_len.min(2)].iter().collect();
for _ in 0..local_len {
out.pop();
}
out.push_str(&kept);
out.push_str("***@");
out.push_str(&domain);
i += 1 + domain.chars().count();
}
out
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
#[test]
fn addresses_in_text() {
assert_eq!(mask_emails("anna.kovacs@gmail.com"), "an***@gmail.com");
assert_eq!(mask_emails("Írj: b@freemail.hu, köszi."), "Írj: b***@freemail.hu, köszi.");
assert_eq!(mask_emails("x@y nem cím, @ sem"), "x@y nem cím, @ sem");
assert_eq!(mask_emails("a@b.hu és cc@dd.com."), "a***@b.hu és cc***@dd.com.");
}
#[test]
fn people_but_not_packages_or_famous_names() {
let mut v = json!({
"users": [{"id": "1", "email": "anna@example.com", "display_name": "Kovács Anna", "roles": ["user"]}],
"redeemed_by": {"email": "bea@example.com", "name": "Bea"},
"package": {"id": "couple", "name": "Páros"},
"celebrity": {"name": "Liszt Ferenc"},
"message": "Hívj: anna@example.com",
"recipient_name": "Cili",
"count": 3,
});
mask(&mut v);
assert_eq!(v["users"][0]["email"], "an***@example.com");
assert_eq!(v["users"][0]["display_name"], "[rejtve]");
assert_eq!(v["redeemed_by"], json!({"email": "be***@example.com", "name": "[rejtve]"}));
assert_eq!(v["package"]["name"], "Páros");
assert_eq!(v["celebrity"]["name"], "Liszt Ferenc");
assert_eq!(v["message"], "Hívj: an***@example.com");
assert_eq!(v["recipient_name"], "[rejtve]");
assert_eq!(v["count"], 3);
}
}
+199
View File
@@ -0,0 +1,199 @@
//! The MCP server against a fake site API.
use std::sync::{Arc, Mutex};
use axum::body::Body;
use axum::extract::{Query, State};
use axum::http::{HeaderMap, Request, StatusCode};
use axum::routing::{get, post};
use axum::{Json, Router};
use http_body_util::BodyExt;
use serde_json::{Value, json};
use tower::ServiceExt;
use crate::{App, Config, router};
const GOOD: &str = "good-token";
const ELSEWHERE: &str = "token-for-another-server";
const FORMER_ADMIN: &str = "former-admin-token";
/// Valid at the check, revoked by the time of the tool call.
const REVOKED: &str = "revoked-meanwhile";
static REVOKED_CHECKS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
/// What the fake API received: (path with query, the bearer token).
type Calls = Arc<Mutex<Vec<(String, String)>>>;
fn bearer(headers: &HeaderMap) -> String {
headers.get("authorization").and_then(|v| v.to_str().ok()).unwrap_or("").trim_start_matches("Bearer ").to_string()
}
async fn fake_whoami(headers: HeaderMap) -> (StatusCode, Json<Value>) {
match bearer(&headers).as_str() {
GOOD => (StatusCode::OK, Json(json!({"resource": "https://sorsfonalak.test/mcp", "scope": "admin"}))),
ELSEWHERE => (StatusCode::OK, Json(json!({"resource": "https://other.test/mcp"}))),
FORMER_ADMIN => (StatusCode::FORBIDDEN, Json(json!({"error": {"code": "forbidden"}}))),
REVOKED => {
REVOKED_CHECKS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
(StatusCode::OK, Json(json!({"resource": "https://sorsfonalak.test/mcp"})))
}
_ => (StatusCode::UNAUTHORIZED, Json(json!({"error": {"code": "unauthorized"}}))),
}
}
async fn fake_stats(
State(calls): State<Calls>,
headers: HeaderMap,
Query(q): Query<std::collections::HashMap<String, String>>,
) -> Json<Value> {
calls.lock().unwrap().push((format!("/admin/stats?days={}", q["days"]), bearer(&headers)));
Json(json!({
"totals": {"members": 3},
"cohort": {"details": [{"detail": "utm_source=facebook", "signups": 2}]},
"note": "Kérdezte: anna@example.com",
"user": {"email": "bea@example.com", "name": "Bea"},
}))
}
async fn fake_users_patch() -> (StatusCode, Json<Value>) {
(StatusCode::FORBIDDEN, Json(json!({"error": {"code": "forbidden", "message": "Ezt Claude-ból nem lehet."}})))
}
async fn fake_ban(State(calls): State<Calls>, uri: axum::http::Uri, headers: HeaderMap) -> Json<Value> {
calls.lock().unwrap().push((uri.path().to_string(), bearer(&headers)));
Json(json!({"banned_until": "2026-11-28T10:00:00Z"}))
}
/// The fake API on a free port; the MCP router pointed at it.
async fn setup() -> (Router, Calls) {
let calls: Calls = Arc::default();
let api = Router::new()
.route("/api/v1/oauth/whoami", get(fake_whoami))
.route("/api/v1/admin/stats", get(fake_stats))
.route("/api/v1/admin/promo-codes", post(fake_users_patch))
.route(
"/api/v1/admin/jobs",
get(|| async { (StatusCode::UNAUTHORIZED, Json(json!({"error": {"code": "unauthorized"}}))) }),
)
.route("/api/v1/forum/members/{nickname}/ban", post(fake_ban))
.with_state(calls.clone());
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, api).await.unwrap() });
let config = Config {
api_url: format!("http://{addr}/api/v1"),
public_base_url: "https://sorsfonalak.test".into(),
mcp_public_url: "https://sorsfonalak.test/mcp".into(),
};
(router(Arc::new(App::new(config))), calls)
}
/// A JSON-RPC call to `/mcp`: the status, the `WWW-Authenticate` header, the body.
async fn rpc(app: &Router, token: Option<&str>, body: Value) -> (StatusCode, Option<String>, Value) {
let mut req = Request::builder()
.method("POST")
.uri("/mcp")
.header("host", "sorsfonalak.test")
.header("content-type", "application/json")
.header("accept", "application/json, text/event-stream")
.header("mcp-protocol-version", "2025-06-18");
if let Some(t) = token {
req = req.header("authorization", format!("Bearer {t}"));
}
let resp = app.clone().oneshot(req.body(Body::from(body.to_string())).unwrap()).await.unwrap();
let status = resp.status();
let www = resp.headers().get("www-authenticate").map(|v| v.to_str().unwrap().to_string());
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
let text = String::from_utf8_lossy(&bytes);
// A JSON answer, or the data line of an event stream.
let json = text
.lines()
.find_map(|l| l.strip_prefix("data:").map(str::trim).filter(|d| d.starts_with('{')))
.unwrap_or(&text);
(status, www, serde_json::from_str(json).unwrap_or(Value::Null))
}
fn call(id: i64, name: &str, arguments: Value) -> Value {
json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": name, "arguments": arguments}})
}
/// The text of a tool result.
fn result_text(body: &Value) -> Value {
serde_json::from_str(body["result"]["content"][0]["text"].as_str().unwrap()).unwrap_or(Value::Null)
}
#[tokio::test]
async fn without_a_token_claude_learns_where_to_log_in() {
let (app, _) = setup().await;
let init = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {
"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "test", "version": "1"}}});
let (status, www, _) = rpc(&app, None, init.clone()).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
let expected = "resource_metadata=\"https://sorsfonalak.test/.well-known/oauth-protected-resource/mcp\"";
assert!(www.as_deref().unwrap().contains(expected), "{www:?}");
// The metadata points at the site.
let req = Request::builder().uri("/.well-known/oauth-protected-resource/mcp").body(Body::empty()).unwrap();
let resp = app.clone().oneshot(req).await.unwrap();
let meta: Value = serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap();
assert_eq!(meta["resource"], "https://sorsfonalak.test/mcp");
assert_eq!(meta["authorization_servers"], json!(["https://sorsfonalak.test"]));
// A wrong token, one for another server, one of a former admin.
let (status, www, _) = rpc(&app, Some("nonsense"), init.clone()).await;
assert_eq!(status, StatusCode::UNAUTHORIZED);
assert!(www.unwrap().contains("error=\"invalid_token\""));
assert_eq!(rpc(&app, Some(ELSEWHERE), init.clone()).await.0, StatusCode::UNAUTHORIZED);
assert_eq!(rpc(&app, Some(FORMER_ADMIN), init.clone()).await.0, StatusCode::FORBIDDEN);
// A good one.
let (status, _, body) = rpc(&app, Some(GOOD), init).await;
assert_eq!(status, StatusCode::OK, "{body}");
assert_eq!(body["result"]["serverInfo"]["name"], "sorsfonalak");
}
#[tokio::test]
async fn tools_call_the_api_with_the_token_and_mask_people() {
let (app, calls) = setup().await;
let (_, _, body) = rpc(&app, Some(GOOD), json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})).await;
let tools = body["result"]["tools"].as_array().unwrap_or_else(|| panic!("{body}"));
let tool = |name: &str| tools.iter().find(|t| t["name"] == name).unwrap_or_else(|| panic!("no {name}"));
assert_eq!(tool("get_stats")["annotations"]["readOnlyHint"], true);
assert_eq!(tool("forum_ban")["annotations"]["destructiveHint"], true);
assert_eq!(tool("create_promo_codes")["annotations"]["readOnlyHint"], false);
assert!(tool("create_promo_codes")["inputSchema"]["required"].as_array().unwrap().contains(&json!("package")));
assert_eq!(tools.len(), 34);
let (_, _, body) = rpc(&app, Some(GOOD), call(2, "get_stats", json!({"days": 7}))).await;
assert_eq!(body["result"]["isError"], false, "{body}");
let stats = result_text(&body);
assert_eq!(stats["totals"]["members"], 3);
assert_eq!(stats["note"], "Kérdezte: an***@example.com");
assert_eq!(stats["user"], json!({"email": "be***@example.com", "name": "[rejtve]"}));
assert_eq!(calls.lock().unwrap()[0], ("/admin/stats?days=7".to_string(), GOOD.to_string()));
// The API's refusal reaches Claude as a tool error.
let (_, _, body) =
rpc(&app, Some(GOOD), call(3, "create_promo_codes", json!({"package": "single", "count": 1}))).await;
assert_eq!(body["result"]["isError"], true, "{body}");
assert_eq!(body["result"]["content"][0]["text"], "Ezt Claude-ból nem lehet.");
// A nickname goes into the path encoded; a bad id never reaches the API.
let (_, _, body) =
rpc(&app, Some(GOOD), call(4, "forum_ban", json!({"nickname": "Hold fény", "reason": "hirdetés"}))).await;
assert_eq!(body["result"]["isError"], false, "{body}");
assert_eq!(calls.lock().unwrap()[1].0, "/api/v1/forum/members/Hold%20f%C3%A9ny/ban");
let (_, _, body) = rpc(&app, Some(GOOD), call(5, "get_celebrity", json!({"id": "../users"}))).await;
assert!(body["error"].is_object() || body["result"]["isError"] == true, "{body}");
assert_eq!(calls.lock().unwrap().len(), 2);
}
#[tokio::test]
async fn a_token_the_backend_refuses_is_checked_again() {
let (app, _) = setup().await;
let (_, _, body) = rpc(&app, Some(REVOKED), call(1, "list_jobs", json!({}))).await;
assert_eq!(body["result"]["isError"], true, "{body}");
let checks = REVOKED_CHECKS.load(std::sync::atomic::Ordering::SeqCst);
// Not from the cache: the backend is asked again.
rpc(&app, Some(REVOKED), call(2, "list_jobs", json!({}))).await;
assert_eq!(REVOKED_CHECKS.load(std::sync::atomic::Ordering::SeqCst), checks + 1);
}
+754
View File
@@ -0,0 +1,754 @@
//! The tools: each one call of the site's admin (or forum moderation) API
//! with the caller's token. The backend decides what the token may do (see
//! `auth::MCP_WRITES` there); the answers are masked (`mask`).
use std::sync::Arc;
use axum::http::StatusCode;
use axum::http::request::Parts;
use reqwest::Method;
use rmcp::handler::server::tool::Extension;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{CallToolResult, ContentBlock};
use rmcp::{ErrorData, ServerHandler, tool, tool_handler, tool_router};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::{Value, json};
use crate::App;
use crate::auth::Bearer;
use crate::mask::mask;
#[derive(Clone)]
pub struct Tools {
app: Arc<App>,
}
type ToolResult = Result<CallToolResult, ErrorData>;
/// `(name, value)` pairs of a query, without the missing values.
fn query<const N: usize>(pairs: [(&'static str, Option<String>); N]) -> Vec<(&'static str, String)> {
pairs.into_iter().filter_map(|(k, v)| v.map(|v| (k, v))).collect()
}
/// A UUID path segment (nothing else may get into the path).
fn uuid(id: &str) -> Result<&str, ErrorData> {
let ok = id.len() == 36
&& id.char_indices().all(|(i, c)| if [8, 13, 18, 23].contains(&i) { c == '-' } else { c.is_ascii_hexdigit() });
if ok { Ok(id) } else { Err(ErrorData::invalid_params(format!("Not an id: {id}"), None)) }
}
/// A path segment, percent-encoded (forum nicknames have accents and spaces).
fn segment(text: &str) -> String {
text.bytes()
.map(|b| {
if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
(b as char).to_string()
} else {
format!("%{b:02X}")
}
})
.collect()
}
impl Tools {
pub fn new(app: Arc<App>) -> Self {
Self { app }
}
/// Calls the API with the caller's token; the masked answer, or the
/// API's refusal as a tool error Claude can read.
async fn run(
&self,
parts: &Parts,
method: Method,
path: &str,
query: Vec<(&str, String)>,
body: Option<Value>,
) -> ToolResult {
let token = parts
.extensions
.get::<Bearer>()
.map(|b| b.0.clone())
.ok_or_else(|| ErrorData::invalid_request("No token.", None))?;
tracing::info!(%method, path, "tool call");
match self.app.api.call(&token, method, path, &query, body.as_ref()).await {
Ok(mut value) => {
if value.is_null() {
value = json!({ "ok": true });
}
mask(&mut value);
Ok(CallToolResult::success(vec![ContentBlock::text(value.to_string())]))
}
Err(failure) if failure.status == Some(StatusCode::UNAUTHORIZED) => {
self.app.tokens.forget(&token);
Ok(CallToolResult::error(vec![ContentBlock::text(
"The connection has ended or expired: connect again.",
)]))
}
Err(failure) => {
tracing::info!(path, status = ?failure.status, "tool call refused");
Ok(CallToolResult::error(vec![ContentBlock::text(failure.message)]))
}
}
}
async fn get(&self, parts: &Parts, path: &str, query: Vec<(&str, String)>) -> ToolResult {
self.run(parts, Method::GET, path, query, None).await
}
}
// --- parameters -------------------------------------------------------------------------
#[derive(Deserialize, JsonSchema)]
pub struct StatsParams {
/// The last this many days with today: 7, 30 or 90; 0 means since the first member. Default 30.
days: Option<i64>,
}
#[derive(Deserialize, JsonSchema)]
pub struct MembersParams {
/// Part of an e-mail address or name (a full address finds one member).
query: Option<String>,
/// At most this many (default 50, at most 200).
limit: Option<i64>,
offset: Option<i64>,
}
#[derive(Deserialize, JsonSchema)]
pub struct FeedbackParams {
/// `open` (new and in progress, the default), `new`, `in_progress`, `done`, `dismissed` or `all`.
status: Option<String>,
}
#[derive(Deserialize, JsonSchema)]
pub struct SummaryParams {
/// The period in days (default 90).
days: Option<i32>,
}
#[derive(Deserialize, JsonSchema)]
pub struct RatingsParams {
/// `natal`, `synastry`, `forecast`, `tarot`, `question`…
kind: Option<String>,
/// At most this many stars (2: the unhappy ones).
max_stars: Option<i16>,
/// Only the ones with a comment.
with_comment: Option<bool>,
/// Only the ones not reviewed yet.
unreviewed: Option<bool>,
limit: Option<i64>,
offset: Option<i64>,
}
#[derive(Deserialize, JsonSchema)]
pub struct IdParams {
/// The id (a UUID).
id: String,
}
#[derive(Deserialize, JsonSchema)]
pub struct ErrorsParams {
/// `analysis`, `question` or `preview`.
source: Option<String>,
/// `retry`, `fallback` or `failed`.
outcome: Option<String>,
limit: Option<i64>,
offset: Option<i64>,
}
#[derive(Deserialize, JsonSchema)]
pub struct PromoListParams {
/// `unused` (default), `used`, `revoked` or `all`.
status: Option<String>,
/// A package id (see list_packages).
package: Option<String>,
/// Part of the code, the note or the redeemer's e-mail.
query: Option<String>,
limit: Option<i64>,
offset: Option<i64>,
}
#[derive(Deserialize, JsonSchema)]
pub struct GiftsParams {
/// Part of the code, the buyer's or recipient's address, or the recipient's name.
query: Option<String>,
}
#[derive(Deserialize, JsonSchema)]
pub struct NewCodesParams {
/// The package id (see list_packages).
package: String,
/// How many codes (1–500).
count: i64,
/// Who they are for, which campaign.
note: Option<String>,
}
#[derive(Deserialize, JsonSchema)]
pub struct FeedbackUpdateParams {
/// The message's id.
id: String,
/// `new`, `in_progress`, `done` or `dismissed`.
status: Option<String>,
/// The answer the member sees on the site's feedback page (Hungarian); empty clears it.
reply: Option<String>,
/// A note only the admins see; empty clears it.
admin_note: Option<String>,
}
#[derive(Deserialize, JsonSchema)]
pub struct IdsParams {
/// These ids; none: all of them.
ids: Option<Vec<String>>,
}
#[derive(Deserialize, JsonSchema)]
pub struct DeleteErrorsParams {
/// One entry's id.
id: Option<i64>,
/// Every entry of this source: `analysis`, `question` or `preview`.
source: Option<String>,
/// Every entry with this outcome: `retry`, `fallback` or `failed`.
outcome: Option<String>,
/// Every entry: needed when neither an id nor a filter is given.
#[serde(default)]
all: bool,
}
#[derive(Deserialize, JsonSchema)]
pub struct InviteParams {
/// The addresses to invite (each gets an e-mail).
emails: Vec<String>,
/// A personal line in the e-mail.
message: Option<String>,
/// A package the invitees get as a promo code (see list_packages).
package: Option<String>,
/// `hu` (default) or `en`.
locale: Option<String>,
}
#[derive(Deserialize, JsonSchema)]
pub struct NumericIdParams {
/// The id (a number).
id: i64,
}
#[derive(Deserialize, JsonSchema)]
pub struct HandleReportParams {
/// The report's id.
id: i64,
/// `resolve` (acted on, or nothing more needed) or `dismiss` (unfounded).
action: String,
}
#[derive(Deserialize, JsonSchema)]
pub struct TopicDecisionParams {
/// The topic's slug.
topic: String,
/// The member's nickname.
nickname: String,
/// `approve` or `reject` (a request), or `remove` (a member).
action: String,
}
#[derive(Deserialize, JsonSchema)]
pub struct BanParams {
/// The member's nickname.
nickname: String,
/// For this many hours (1–8760); missing: for good.
hours: Option<i64>,
/// The reason, sent to the member (Hungarian).
reason: String,
}
#[derive(Deserialize, JsonSchema)]
pub struct NicknameParams {
/// The member's nickname.
nickname: String,
}
// --- the tools --------------------------------------------------------------------------
#[tool_router]
impl Tools {
// Reading.
#[tool(
description = "Site statistics for a period: new members, own charts, purchases and revenue (HUF), \
analyses and questions, weekly horoscope readers, forum posts, AI cost (USD), each with \
the previous period; day by day; the funnel from sign-up to payment; where members came \
from; packages sold; the weekly horoscope by week; what the AI wrote.",
annotations(title = "Statisztika", read_only_hint = true)
)]
async fn get_stats(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<StatsParams>,
) -> ToolResult {
self.get(&parts, "/admin/stats", query([("days", Some(p.days.unwrap_or(30).to_string()))])).await
}
#[tool(
description = "Members (admins too): id, masked e-mail, roles, verified, sign-up and last login, own \
charts, unit balances. Search by part of an e-mail or name.",
annotations(title = "Tagok", read_only_hint = true)
)]
async fn search_members(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<MembersParams>,
) -> ToolResult {
let q = query([
("q", p.query),
("limit", p.limit.map(|v| v.to_string())),
("offset", p.offset.map(|v| v.to_string())),
]);
self.get(&parts, "/admin/users", q).await
}
#[tool(
description = "Feedback messages members sent (bug reports, ideas, questions) with their state, the \
admin's note and reply.",
annotations(title = "Visszajelzések", read_only_hint = true)
)]
async fn list_feedback(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<FeedbackParams>,
) -> ToolResult {
self.get(&parts, "/admin/feedback", query([("status", p.status)])).await
}
#[tool(
description = "The feedback numbers: ratings of the AI texts by kind, model, prompt and week, the tags, \
the recommendation question (NPS), and the count of open messages.",
annotations(title = "Visszajelzések összesítve", read_only_hint = true)
)]
async fn feedback_summary(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<SummaryParams>,
) -> ToolResult {
let summary =
self.get(&parts, "/admin/feedback/summary", query([("days", p.days.map(|d| d.to_string()))])).await?;
if summary.is_error == Some(true) {
return Ok(summary);
}
let count = self.get(&parts, "/admin/feedback/count", vec![]).await?;
let text = |r: &CallToolResult| match r.content.first() {
Some(ContentBlock::Text(t)) => serde_json::from_str::<Value>(&t.text).unwrap_or(Value::Null),
_ => Value::Null,
};
let both = json!({ "summary": text(&summary), "open_messages": text(&count) });
Ok(CallToolResult::success(vec![ContentBlock::text(both.to_string())]))
}
#[tool(
description = "Members' star ratings of the AI analyses and answers, with tags and comments.",
annotations(title = "Értékelések", read_only_hint = true)
)]
async fn list_ratings(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<RatingsParams>,
) -> ToolResult {
let q = query([
("kind", p.kind),
("max_stars", p.max_stars.map(|v| v.to_string())),
("with_comment", p.with_comment.map(|v| v.to_string())),
("unreviewed", p.unreviewed.map(|v| v.to_string())),
("limit", p.limit.map(|v| v.to_string())),
("offset", p.offset.map(|v| v.to_string())),
]);
self.get(&parts, "/admin/ratings", q).await
}
#[tool(
description = "The text a rating is about (only when the member allowed it to be read).",
annotations(title = "Értékelt szöveg", read_only_hint = true)
)]
async fn get_rated_content(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<IdParams>,
) -> ToolResult {
self.get(&parts, &format!("/admin/ratings/{}/content", uuid(&p.id)?), vec![]).await
}
#[tool(
description = "The AI generation error log: retries, fallbacks to the second model, failures.",
annotations(title = "Hibanapló", read_only_hint = true)
)]
async fn list_errors(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<ErrorsParams>,
) -> ToolResult {
let q = query([
("source", p.source),
("outcome", p.outcome),
("limit", p.limit.map(|v| v.to_string())),
("offset", p.offset.map(|v| v.to_string())),
]);
self.get(&parts, "/admin/errors", q).await
}
#[tool(
description = "The AI texts waiting or being written (analyses, answers), with attempts and errors.",
annotations(title = "Háttérfeladatok", read_only_hint = true)
)]
async fn list_jobs(&self, Extension(parts): Extension<Parts>) -> ToolResult {
self.get(&parts, "/admin/jobs", vec![]).await
}
#[tool(
description = "The packages on sale: id, name, price (HUF) and what they contain.",
annotations(title = "Csomagok", read_only_hint = true)
)]
async fn list_packages(&self, Extension(parts): Extension<Parts>) -> ToolResult {
self.get(&parts, "/packages", vec![]).await
}
#[tool(
description = "Promo codes: package, note, state, who redeemed them and when.",
annotations(title = "Promókódok", read_only_hint = true)
)]
async fn list_promo_codes(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<PromoListParams>,
) -> ToolResult {
let q = query([
("status", p.status),
("package", p.package),
("q", p.query),
("limit", p.limit.map(|v| v.to_string())),
("offset", p.offset.map(|v| v.to_string())),
]);
self.get(&parts, "/admin/promo-codes", q).await
}
#[tool(
description = "Invitations sent by e-mail (the site is invitation-only for new accounts unless opened): \
state, sends, acceptance, the package code that came with them.",
annotations(title = "Meghívók", read_only_hint = true)
)]
async fn list_invitations(&self, Extension(parts): Extension<Parts>) -> ToolResult {
self.get(&parts, "/admin/invitations", vec![]).await
}
#[tool(
description = "Paid gift packages: buyer, recipient, scheduled send, redemption, refunds.",
annotations(title = "Ajándékok", read_only_hint = true)
)]
async fn list_gifts(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<GiftsParams>,
) -> ToolResult {
self.get(&parts, "/admin/gifts", query([("q", p.query)])).await
}
#[tool(
description = "The famous people's pages (public charts): name, slug, published, the analysis' state.",
annotations(title = "Hírességek", read_only_hint = true)
)]
async fn list_celebrities(&self, Extension(parts): Extension<Parts>) -> ToolResult {
self.get(&parts, "/admin/celebrities", vec![]).await
}
#[tool(description = "One famous person's page in full.", annotations(title = "Híresség", read_only_hint = true))]
async fn get_celebrity(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<IdParams>,
) -> ToolResult {
self.get(&parts, &format!("/admin/celebrities/{}", uuid(&p.id)?), vec![]).await
}
#[tool(
description = "The AI prompts of every kind and language (the current texts and versions).",
annotations(title = "Promptok", read_only_hint = true)
)]
async fn list_prompts(&self, Extension(parts): Extension<Parts>) -> ToolResult {
self.get(&parts, "/admin/prompts", vec![]).await
}
#[tool(
description = "Which AI model writes each kind of text, and the fallback models.",
annotations(title = "Modellek", read_only_hint = true)
)]
async fn list_models(&self, Extension(parts): Extension<Parts>) -> ToolResult {
self.get(&parts, "/admin/models", vec![]).await
}
// Daily tasks (Claude asks before each).
#[tool(
description = "Makes promo codes for a package. Each code gives the package once; share them as \
https://sorsfonalak.hu/bevaltas?kod=CODE.",
annotations(title = "Promókód készítése", read_only_hint = false, destructive_hint = false)
)]
async fn create_promo_codes(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<NewCodesParams>,
) -> ToolResult {
let body = json!({ "package": p.package, "count": p.count, "note": p.note });
self.run(&parts, Method::POST, "/admin/promo-codes", vec![], Some(body)).await
}
#[tool(
description = "Withdraws an unused promo code: it cannot be redeemed any more.",
annotations(title = "Promókód visszavonása", read_only_hint = false, destructive_hint = true)
)]
async fn revoke_promo_code(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<IdParams>,
) -> ToolResult {
let path = format!("/admin/promo-codes/{}/revoke", uuid(&p.id)?);
self.run(&parts, Method::POST, &path, vec![], Some(json!({}))).await
}
#[tool(
description = "Changes a feedback message: its state, the admin's note, or the reply the member sees on \
the site.",
annotations(title = "Visszajelzés kezelése", read_only_hint = false, destructive_hint = false)
)]
async fn update_feedback(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<FeedbackUpdateParams>,
) -> ToolResult {
let mut body = json!({});
for (key, value) in [("status", p.status), ("reply", p.reply), ("admin_note", p.admin_note)] {
if let Some(v) = value {
body[key] = json!(v);
}
}
self.run(&parts, Method::PATCH, &format!("/admin/feedback/{}", uuid(&p.id)?), vec![], Some(body)).await
}
#[tool(
description = "Marks ratings as looked at (these ids, or all).",
annotations(
title = "Értékelések átnézve",
read_only_hint = false,
destructive_hint = false,
idempotent_hint = true
)
)]
async fn mark_ratings_reviewed(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<IdsParams>,
) -> ToolResult {
let ids = p
.ids
.map(|ids| ids.iter().map(|i| uuid(i).map(str::to_string)).collect::<Result<Vec<_>, _>>())
.transpose()?;
self.run(&parts, Method::POST, "/admin/ratings/reviewed", vec![], Some(json!({ "ids": ids }))).await
}
#[tool(
description = "Starts open AI jobs again with the current models (these ids, or all open ones).",
annotations(title = "Feladatok újraindítása", read_only_hint = false, destructive_hint = false)
)]
async fn restart_jobs(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<IdsParams>,
) -> ToolResult {
let ids = p
.ids
.map(|ids| ids.iter().map(|i| uuid(i).map(str::to_string)).collect::<Result<Vec<_>, _>>())
.transpose()?;
self.run(&parts, Method::POST, "/admin/jobs/restart", vec![], Some(json!({ "ids": ids }))).await
}
#[tool(
description = "Deletes error log entries: one (id), the ones matching a filter, or all (all=true).",
annotations(title = "Hibák törlése", read_only_hint = false, destructive_hint = true)
)]
async fn delete_errors(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<DeleteErrorsParams>,
) -> ToolResult {
if let Some(id) = p.id {
return self.run(&parts, Method::DELETE, &format!("/admin/errors/{id}"), vec![], None).await;
}
if p.source.is_none() && p.outcome.is_none() && !p.all {
return Ok(CallToolResult::error(vec![ContentBlock::text(
"Give an id, a filter (source, outcome), or all=true.",
)]));
}
self.run(&parts, Method::DELETE, "/admin/errors", query([("source", p.source), ("outcome", p.outcome)]), None)
.await
}
#[tool(
description = "Invites people by e-mail to sign up (a real e-mail goes to each address). Each address \
gets a result: invited, already_user, already_invited, opted_out or invalid.",
annotations(
title = "Meghívó küldése",
read_only_hint = false,
destructive_hint = false,
open_world_hint = true
)
)]
async fn send_invitation(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<InviteParams>,
) -> ToolResult {
let body = json!({ "emails": p.emails, "message": p.message, "package": p.package, "locale": p.locale });
self.run(&parts, Method::POST, "/admin/invitations", vec![], Some(body)).await
}
#[tool(
description = "Sends an invitation e-mail again.",
annotations(
title = "Meghívó újraküldése",
read_only_hint = false,
destructive_hint = false,
open_world_hint = true
)
)]
async fn resend_invitation(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<IdParams>,
) -> ToolResult {
let path = format!("/admin/invitations/{}/resend", uuid(&p.id)?);
self.run(&parts, Method::POST, &path, vec![], Some(json!({}))).await
}
#[tool(
description = "Writes an analysis again in place (same id and link) with the current prompt and model; \
nobody is charged, but it costs AI money.",
annotations(title = "Elemzés újraírása", read_only_hint = false, destructive_hint = true)
)]
async fn regenerate_analysis(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<IdParams>,
) -> ToolResult {
let path = format!("/admin/analyses/{}/regenerate", uuid(&p.id)?);
self.run(&parts, Method::POST, &path, vec![], None).await
}
#[tool(
description = "Answers a member's question again in place with the current prompt and model; nobody is \
charged, but it costs AI money.",
annotations(title = "Válasz újraírása", read_only_hint = false, destructive_hint = true)
)]
async fn regenerate_answer(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<IdParams>,
) -> ToolResult {
let path = format!("/admin/questions/{}/regenerate", uuid(&p.id)?);
self.run(&parts, Method::POST, &path, vec![], None).await
}
// The forum's moderation.
#[tool(
description = "Forum reports (posts and private messages members reported), the crisis ones first, with \
the reported text and state.",
annotations(title = "Fórum: bejelentések", read_only_hint = true)
)]
async fn forum_reports(&self, Extension(parts): Extension<Parts>) -> ToolResult {
self.get(&parts, "/forum/mod/reports", vec![]).await
}
#[tool(
description = "Closes a forum report (and the other open reports of the same post): resolve or dismiss. \
The reporters get an e-mail about it.",
annotations(title = "Fórum: bejelentés lezárása", read_only_hint = false, destructive_hint = false)
)]
async fn forum_handle_report(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<HandleReportParams>,
) -> ToolResult {
let path = format!("/forum/mod/reports/{}", p.id);
self.run(&parts, Method::POST, &path, vec![], Some(json!({ "action": p.action }))).await
}
#[tool(
description = "Requests to join the forum's restricted topics, waiting for a decision.",
annotations(title = "Fórum: csatlakozási kérések", read_only_hint = true)
)]
async fn forum_topic_requests(&self, Extension(parts): Extension<Parts>) -> ToolResult {
self.get(&parts, "/forum/mod/topic-requests", vec![]).await
}
#[tool(
description = "Decides a request to join a restricted topic (approve or reject), or removes a member from it.",
annotations(title = "Fórum: kérés elbírálása", read_only_hint = false, destructive_hint = false)
)]
async fn forum_decide_topic_request(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<TopicDecisionParams>,
) -> ToolResult {
let body = json!({ "topic": p.topic, "nickname": p.nickname, "action": p.action });
self.run(&parts, Method::POST, "/forum/mod/topic-requests", vec![], Some(body)).await
}
#[tool(
description = "The forum's moderation log: who removed, banned or closed what, and why.",
annotations(title = "Fórum: moderálási napló", read_only_hint = true)
)]
async fn forum_mod_log(&self, Extension(parts): Extension<Parts>) -> ToolResult {
self.get(&parts, "/forum/mod/log", vec![]).await
}
#[tool(
description = "A forum thread with its posts (removed ones too, for moderators).",
annotations(title = "Fórum: szál", read_only_hint = true)
)]
async fn forum_get_thread(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<NumericIdParams>,
) -> ToolResult {
self.get(&parts, &format!("/forum/threads/{}", p.id), vec![]).await
}
#[tool(
description = "Bans a forum member from writing, for some hours or for good; they get an e-mail with the \
reason. Moderators and admins cannot be banned.",
annotations(title = "Fórum: kitiltás", read_only_hint = false, destructive_hint = true)
)]
async fn forum_ban(&self, Extension(parts): Extension<Parts>, Parameters(p): Parameters<BanParams>) -> ToolResult {
let path = format!("/forum/members/{}/ban", segment(&p.nickname));
self.run(&parts, Method::POST, &path, vec![], Some(json!({ "hours": p.hours, "reason": p.reason }))).await
}
#[tool(
description = "Lifts a forum member's ban.",
annotations(title = "Fórum: kitiltás feloldása", read_only_hint = false, destructive_hint = false)
)]
async fn forum_unban(
&self,
Extension(parts): Extension<Parts>,
Parameters(p): Parameters<NicknameParams>,
) -> ToolResult {
let path = format!("/forum/members/{}/ban", segment(&p.nickname));
self.run(&parts, Method::DELETE, &path, vec![], None).await
}
}
#[tool_handler(
name = "sorsfonalak",
instructions = "Admin tools of sorsfonalak.hu, a Hungarian astrology site (birth charts, AI-written \
analyses, a weekly horoscope, a forum). Members' e-mail addresses and names are masked. \
Money is in HUF, AI cost in USD. Writes are limited to the daily tasks; anything else is \
done on the site's admin pages."
)]
impl ServerHandler for Tools {}