Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .changeset/mcp-maintenance.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
---

feat(mcp): the maintenance tools, the counts the pass drops, and the run record

The admin MCP server gains `maintenance_run`, which runs the maintenance pass's retention purge
in the answering process through the same `MaintenanceService` the worker's `MaintenanceTasks`
arm delegates to, and `maintenance_last_run`, which reads the last run this process recorded.

`MaintenanceService::clear_old_events` now answers `EventPurgeCounts` instead of `()`, the
`MaintenanceTasks` trait's future carries them, and `PassOutcome` gains
`counts: Option<EventPurgeCounts>` — `None` on a failed or timed-out purge, never zeros. Every
implementor and test double moves with it; `crates/nostream-storage` is untouched.

The run record lives in `AdminState`'s process memory (`MaintenanceRun`: `ranAt`, `deleted`,
`expired`, `retained`), so "never ran" is `null` and "ran, nothing to purge" is three zeros. ADR
0019 records the six decisions, including why the door runs the purge step rather than the whole
pass and why the record is not a sixth key in the published status document.

Rust only: no version bump.
7 changes: 4 additions & 3 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ The following environment variables can be set:

`nostreamd --mcp-stdio` serves the admin MCP server (`settings_get`, `settings_set`,
`list_events`, `get_event`, `relay_status`, `delete_event`, `reports_action`, `reports_list`,
`user_admin`, `user_get`, `invoices_list` and `invoices_get`) on stdin/stdout and exits when stdin
`user_admin`, `user_get`, `invoices_list`, `invoices_get`, `maintenance_run` and
`maintenance_last_run`) on stdin/stdout and exits when stdin
closes. It binds no socket,
opens no store of its own, and writes its log lines to **stderr** so nothing but JSON-RPC crosses
stdout.
Expand All @@ -97,8 +98,8 @@ The document is JSON, and `scopes` is optional:

| Document | What it may call |
|---|---|
| `{}` or `{ "scopes": [] }` | The read tools: `settings_get`, `list_events`, `get_event`, `relay_status`, `user_get`, `invoices_list`, `invoices_get` and `reports_list`. |
| `{ "scopes": ["write"] }` | The read tools, and the four that change something: `settings_set`, `delete_event` (soft-deletes **any author's** stored event by id — there is no per-author restriction, the holder of the token is the operator), `reports_action` (sets the relay-wide NIP-56 filter for the target an actionable report names) and `user_admin` (admits, revokes, vanishes and unvanishes one pubkey). |
| `{}` or `{ "scopes": [] }` | The read tools: `settings_get`, `list_events`, `get_event`, `relay_status`, `user_get`, `invoices_list`, `invoices_get`, `reports_list` and `maintenance_last_run`. |
| `{ "scopes": ["write"] }` | The read tools, and the five that change something: `settings_set`, `delete_event` (soft-deletes **any author's** stored event by id — there is no per-author restriction, the holder of the token is the operator), `reports_action` (sets the relay-wide NIP-56 filter for the target an actionable report names), `user_admin` (admits, revokes, vanishes and unvanishes one pubkey) and `maintenance_run` (runs the retention purge in the calling process and records it). |

`write` is the only accepted scope, and an unknown name — a typo, or a document from another tool
— refuses to start rather than being narrowed silently. A call the document's scopes deny is
Expand Down
2 changes: 1 addition & 1 deletion crates/nostream-admin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub mod utils;

pub use error::AdminError;
pub use routes::{ADMIN_ROUTES, AdminRoute, PREFIX_MIDDLEWARE, mount};
pub use state::{AdminState, AdminStateConfig, GrafanaSettings};
pub use state::{AdminState, AdminStateConfig, GrafanaSettings, MaintenanceRun};

/// The CSP nonce the page's `<script>` tags carry, for a caller that mounts the page itself.
pub use controllers::admin_enabled_middleware::Nonce;
Expand Down
46 changes: 46 additions & 0 deletions crates/nostream-admin/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ use nostream_core::nip05::Nip05Fetch;
use nostream_core::random::{RandomSource, SystemRandom};
use nostream_relay::limits::{RateLimitConfig, RateLimiter, strategy_from_settings};
use nostream_services::{HttpClient, ServiceStores};
use nostream_storage::repositories::EventPurgeCounts;
use serde::{Deserialize, Serialize};
use serde_json::Value;

Expand Down Expand Up @@ -96,10 +97,23 @@ struct ProbeState {
runs: VecDeque<ProbeRun>,
}

/// The last retention purge a process ran (D3): stamped by the clock, and the counts the store
/// answered.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MaintenanceRun {
pub ran_at: String,
pub deleted: u64,
pub expired: u64,
pub retained: u64,
}

/// What one `AdminState` keeps in process, replacing the capture's Redis keys (D2).
#[derive(Debug)]
pub struct AdminRuntime {
heartbeats: Mutex<HashMap<String, WorkerHeartbeat>>,
/// The last purge this process ran, beside the heartbeats and the probe ring (D3).
maintenance: Mutex<Option<MaintenanceRun>>,
probe: Mutex<ProbeState>,
/// Appends since the last compaction.
audit: Mutex<usize>,
Expand All @@ -119,6 +133,7 @@ impl Default for AdminRuntime {
fn default() -> Self {
Self {
heartbeats: Mutex::new(HashMap::new()),
maintenance: Mutex::new(None),
probe: Mutex::new(ProbeState::default()),
audit: Mutex::new(0),
login_verifications: Arc::new(tokio::sync::Semaphore::new(
Expand Down Expand Up @@ -414,6 +429,37 @@ impl AdminState {
.collect()
}

/// Records the retention purge this process just ran, stamping it with the clock and
/// replacing the previous record — never summing it into one — and answers the record it
/// stored, so the caller reads back exactly what a later read will.
///
/// The counts arrive as the store's own value rather than three positional numbers: a
/// transposed `deleted`/`expired` pair is a call the compiler can refuse, one it cannot.
pub fn record_maintenance_run(&self, counts: EventPurgeCounts) -> MaintenanceRun {
let run = MaintenanceRun {
ran_at: iso8601(self.clock.now_ms()),
deleted: counts.deleted,
expired: counts.expired,
retained: counts.retained,
};
*self
.runtime
.maintenance
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()) = Some(run.clone());
run
}

/// The last purge this process ran; `None` until one records it, which is how "never ran"
/// stays distinct from "ran and purged nothing".
pub fn latest_maintenance_run(&self) -> Option<MaintenanceRun> {
self.runtime
.maintenance
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone()
}

/// The latest probe snapshot, if a run recorded one.
pub fn latest_probe_snapshot(&self) -> Option<Value> {
self.runtime
Expand Down
2 changes: 1 addition & 1 deletion crates/nostream-mcp/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ nostream-admin.workspace = true
nostream-config.workspace = true
nostream-core.workspace = true
nostream-relay.workspace = true
nostream-services.workspace = true
nostream-storage.workspace = true
rmcp.workspace = true
serde.workspace = true
Expand All @@ -23,7 +24,6 @@ tracing.workspace = true
[dev-dependencies]
futures-core.workspace = true
futures-util.workspace = true
nostream-services.workspace = true
rmcp = { workspace = true, features = ["client"] }
serde_yaml.workspace = true
tempfile.workspace = true
Expand Down
6 changes: 3 additions & 3 deletions crates/nostream-mcp/src/credential.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use serde::Deserialize;

use crate::error::McpError;

/// The one scope beyond reading: the right to call the four tools that write (R28).
/// The one scope beyond reading: the right to call the five tools that write (R28).
pub const SCOPE_WRITE: &str = "write";

/// The scopes a token document may name, as a refusal states them.
Expand Down Expand Up @@ -57,14 +57,14 @@ pub const MAX_TOKEN_DOCUMENT_BYTES: u64 = 4 * 1024;
/// The scopes a token document grants.
///
/// Reading is not a scope: every accepted document reads (R28). `write` is the one name a
/// document may add, and it is what makes the four writes callable.
/// document may add, and it is what makes the five writes callable.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Scopes {
write: bool,
}

impl Scopes {
/// The grant a document with no `scopes` carries: the eight read tools.
/// The grant a document with no `scopes` carries: the nine read tools.
pub fn read_only() -> Self {
Self::default()
}
Expand Down
5 changes: 5 additions & 0 deletions crates/nostream-mcp/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ pub enum McpError {
#[error(transparent)]
Storage(#[from] StorageError),

/// A service call failed, such as the retention purge. Its message is the service's own —
/// the store's, for a store the mode never wired (R8).
#[error(transparent)]
Services(#[from] nostream_services::ServicesError),

/// A tool's arguments are not the shape its `inputSchema` states.
#[error("the tool's arguments could not be read: {0}")]
Arguments(String),
Expand Down
13 changes: 6 additions & 7 deletions crates/nostream-mcp/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `nostream-mcp` owns the admin MCP server: the tool router, the twelve tools, the credential
//! `nostream-mcp` owns the admin MCP server: the tool router, the fourteen tools, the credential
//! and its scopes, and the audit sink.
//!
//! It owns no transport and no socket. `nostreamd --mcp-stdio` serves this server on
Expand All @@ -23,9 +23,7 @@
//! - the admin state, the console's session token, the audit file and the settings write path —
//! `nostream-admin` (used here, not re-implemented);
//! - the settings merge, validation, redaction and the guided catalogue — `nostream-config`;
//! - the event store and the repositories — `nostream-storage`;
//! - every tool family outside this surface: `maintenance_run` and `maintenance_last_run` are
//! slice 5 of #1183.
//! - the event store and the repositories — `nostream-storage`.

mod credential;
mod error;
Expand All @@ -41,7 +39,8 @@ pub use server::{
MCP_SERVER_NAME, NOT_FOUND, OUTCOME_ALREADY_DELETED, OUTCOME_DELETED, OUTCOME_NOT_DELETEABLE,
OUTCOME_NOT_FOUND, ReportAction, ReportsActionArgs, ReportsListArgs, Requires, SettingsSetArgs,
TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_INVOICES_GET, TOOL_INVOICES_LIST, TOOL_LIST_EVENTS,
TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, TOOL_REPORTS_LIST, TOOL_SETTINGS_GET,
TOOL_SETTINGS_SET, TOOL_USER_ADMIN, TOOL_USER_GET, TOOLS, Tool, UNAUTHORIZED, UserAction,
UserAdminArgs, UserGetArgs, arguments_parse, audit_action, required_scope,
TOOL_MAINTENANCE_LAST_RUN, TOOL_MAINTENANCE_RUN, TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION,
TOOL_REPORTS_LIST, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOL_USER_ADMIN, TOOL_USER_GET, TOOLS,
Tool, UNAUTHORIZED, UserAction, UserAdminArgs, UserGetArgs, arguments_parse, audit_action,
required_scope,
};
72 changes: 66 additions & 6 deletions crates/nostream-mcp/src/server.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! The MCP server: the twelve tools, the credential gate and the audit sink.
//! The MCP server: the fourteen tools, the credential gate and the audit sink.
//!
//! Every tool is a thin handler over a seam that already exists — `AdminState` for the settings,
//! `EventRepository` for the events — and nothing here knows what an HTTP status is (R3). The
Expand All @@ -18,6 +18,7 @@ use nostream_admin::controllers::patch_settings::{self, SettingsWrite};
use nostream_admin::utils::status;
use nostream_core::{EventId, Filter, Kind, Pubkey};
use nostream_relay::nip11;
use nostream_services::services::maintenance_service::MaintenanceService;
use nostream_storage::repositories::{EventRecord, collect_page, collect_records};
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::tool::ToolCallContext;
Expand Down Expand Up @@ -48,8 +49,9 @@ pub const MCP_INSTRUCTIONS: &str = "\
The nostream admin MCP server. Every call is decided by the scoped token document the mode was \
started with — `--admin-token-file <path>` or `--admin-token-fd <n>`, exactly one, its shape \
{\"scopes\": [\"write\"]}: the document's presence authorises `settings_get`, `list_events`, \
`get_event`, `relay_status`, `user_get`, `invoices_list`, `invoices_get` and `reports_list`, and \
the \"write\" scope authorises `settings_set`, `delete_event`, `reports_action` and `user_admin` \
`get_event`, `relay_status`, `user_get`, `invoices_list`, `invoices_get`, `reports_list` and \
`maintenance_last_run`, and the \"write\" scope authorises `settings_set`, `delete_event`, \
`reports_action`, `user_admin` and `maintenance_run` \
(else the call is `Forbidden`). \
`admin.enabled` must be true in the settings, or every call answers `Not Found`; a document \
that cannot be read answers `Unauthorized`. Each executed call appends one `mcp.<tool>` line to \
Expand All @@ -69,6 +71,8 @@ pub const TOOL_USER_ADMIN: &str = "user_admin";
pub const TOOL_USER_GET: &str = "user_get";
pub const TOOL_INVOICES_LIST: &str = "invoices_list";
pub const TOOL_INVOICES_GET: &str = "invoices_get";
pub const TOOL_MAINTENANCE_RUN: &str = "maintenance_run";
pub const TOOL_MAINTENANCE_LAST_RUN: &str = "maintenance_last_run";

/// What a delete call did, as the payload's `outcome` (R3, R4): this call marked the row
/// deleted.
Expand Down Expand Up @@ -125,11 +129,11 @@ pub fn audit_action(tool: &str) -> String {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Requires {
/// Reading: the grant every accepted document carries, so no scope names it and none is
/// asked for at dispatch. The eight read tools say this in the table rather than leaving
/// asked for at dispatch. The nine read tools say this in the table rather than leaving
/// the column empty.
Read,
/// [`SCOPE_WRITE`]: the one scope a document may add, and the right to call the four tools
/// that write.
/// [`SCOPE_WRITE`]: the one scope a document may add, and the right to call
/// the five tools that write.
Write,
}

Expand Down Expand Up @@ -248,6 +252,16 @@ pub const TOOLS: &[Tool] = &[
parses: invoices_get_parses,
needs: Requires::Read,
},
Tool {
name: TOOL_MAINTENANCE_RUN,
parses: accepts_any_arguments,
needs: Requires::Write,
},
Tool {
name: TOOL_MAINTENANCE_LAST_RUN,
parses: accepts_any_arguments,
needs: Requires::Read,
},
];

/// `tool`'s row; `None` when the table does not name it.
Expand Down Expand Up @@ -808,6 +822,52 @@ sets `amount_paid` and `confirmed_at`, and only a status update moves the status
}
}

/// The purge step, in the answering process, through the function the trait's own
/// `clear_old_events` arm delegates to — the worker's code path, not a second one (D2).
/// The tool applies no cap of its own; the 5 s cap is `run_pass`'s, for the loop's cadence.
///
/// A failed purge answers the store's own message and records nothing, so the previous run's
/// record stands: a failure is not the same fact as "never ran".
#[tool(
description = "Run the retention purge now — the purge step of the maintenance worker's \
pass, over this process's store. When `limits.event.retention.maxDays` is absent or not positive \
the purge is skipped: the store is not called and the answer is three zeros. Answers `run` — \
`ranAt`, and `deleted`, `expired` and `retained` as the store counted them; the same object is \
what `maintenance_last_run` reports"
)]
async fn maintenance_run(&self) -> CallToolResult {
match self.purge().await {
Ok(payload) => tool_ok(payload),
Err(error) => tool_error(&error),
}
}

/// The record this process keeps, and nothing else: one `AdminState` read, no store call and
/// nothing run (D3). `None` renders `null`, which is how "never ran" stays distinct from
/// "ran and purged nothing".
#[tool(
description = "Read the last retention purge this process ran: `run` is null until a \
`maintenance_run` call in this process records one, and otherwise carries `ranAt` and the \
`deleted`, `expired` and `retained` counts. It reports this door's own runs — the daemon's \
maintenance worker runs in another process and its passes are not visible here"
)]
async fn maintenance_last_run(&self) -> CallToolResult {
tool_ok(json!({ "run": self.state.latest_maintenance_run() }))
}

/// The purge, the record it leaves and the payload both tools share (R5, R7). The settings
/// are read per call, as every other tool's are, so a rewritten `settings.yaml` is in force
/// on the next call.
async fn purge(&self) -> Result<Value, McpError> {
let settings = self.state.settings()?;
let store = Arc::clone(&self.state.stores().events);
let counts = MaintenanceService::new(store, Arc::new(settings))
.clear_old_events()
.await?;
let run = self.state.record_maintenance_run(counts);
Ok(json!({ "run": run }))
}

/// The delete payload: one outcome from the store's own count and the row **as it stands
/// after** the call, and that row (R3, R4).
///
Expand Down
Loading
Loading