From 6f046bc39a039c31fef27889559562ca1b472b80 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 21 Nov 2026 18:13:41 -0500 Subject: [PATCH 1/8] feat(mcp): add the user, invoice and report read and write tools user_admin carries admit, revoke, vanish and unvanish as one closed action enum, and user_get reads the same row and its balance under a document that grants nothing: the scope is a property of the TOOLS row, so one tool would have made a balance read cost a write document or an admission reachable with a read-only one. The read path is find_by_pubkey plus get_balance_by_pubkey and never is_vanished, which hydrates a live kind-62 and stores a row. invoices_list is the store's pending walk, paged by offset and limit; invoices_get takes the opaque id verbatim and answers a miss as {invoice: null}. reports_list is the review queue over find_actionable, newest first, with no offset. Both list tools share the door's one page bound. The audit vocabulary gains five mcp.* names, each carrying {tool} and nothing else; the four absent-name sites move to maintenance_run; the count sites read twelve. --- Cargo.lock | 1 + crates/nostream-mcp/Cargo.toml | 1 + crates/nostream-mcp/src/credential.rs | 6 +- crates/nostream-mcp/src/lib.rs | 20 +- crates/nostream-mcp/src/server.rs | 371 +++++++- crates/nostream-mcp/tests/audit.rs | 102 ++- crates/nostream-mcp/tests/auth.rs | 44 +- crates/nostream-mcp/tests/common/mod.rs | 2 +- .../tests/fixtures/tools_list.json | 117 ++- crates/nostream-mcp/tests/store_families.rs | 801 ++++++++++++++++++ crates/nostream-mcp/tests/tool_payloads.rs | 2 +- crates/nostream-mcp/tests/tools_list.rs | 19 +- crates/nostreamd/tests/mcp_stdio.rs | 42 +- 13 files changed, 1468 insertions(+), 60 deletions(-) create mode 100644 crates/nostream-mcp/tests/store_families.rs diff --git a/Cargo.lock b/Cargo.lock index fb3b7f6c..514aa582 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1527,6 +1527,7 @@ dependencies = [ name = "nostream-mcp" version = "0.1.0" dependencies = [ + "chrono", "futures-core", "futures-util", "nostream-admin", diff --git a/crates/nostream-mcp/Cargo.toml b/crates/nostream-mcp/Cargo.toml index 7a673d2b..0dba547a 100644 --- a/crates/nostream-mcp/Cargo.toml +++ b/crates/nostream-mcp/Cargo.toml @@ -8,6 +8,7 @@ repository.workspace = true description = "The admin MCP server: the tool router, the credential gate and the audit sink" [dependencies] +chrono.workspace = true nostream-admin.workspace = true nostream-config.workspace = true nostream-core.workspace = true diff --git a/crates/nostream-mcp/src/credential.rs b/crates/nostream-mcp/src/credential.rs index ec16fae5..628106af 100644 --- a/crates/nostream-mcp/src/credential.rs +++ b/crates/nostream-mcp/src/credential.rs @@ -28,7 +28,7 @@ use serde::Deserialize; use crate::error::McpError; -/// The one scope beyond reading: the right to call `settings_set` (R28). +/// The one scope beyond reading: the right to call the four tools that write (R28). pub const SCOPE_WRITE: &str = "write"; /// The scopes a token document may name, as a refusal states them. @@ -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 `settings_set` callable. +/// document may add, and it is what makes the four 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 four read tools. + /// The grant a document with no `scopes` carries: the eight read tools. pub fn read_only() -> Self { Self::default() } diff --git a/crates/nostream-mcp/src/lib.rs b/crates/nostream-mcp/src/lib.rs index 91255c72..3162e3b1 100644 --- a/crates/nostream-mcp/src/lib.rs +++ b/crates/nostream-mcp/src/lib.rs @@ -1,4 +1,4 @@ -//! `nostream-mcp` owns the admin MCP server: the tool router, the seven tools, the credential +//! `nostream-mcp` owns the admin MCP server: the tool router, the twelve tools, the credential //! and its scopes, and the audit sink. //! //! It owns no transport and no socket. `nostreamd --mcp-stdio` serves this server on @@ -24,8 +24,8 @@ //! `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: `user_admin`, `invoices_*` and `maintenance_*` are -//! later slices of #1183. +//! - every tool family outside this surface: `maintenance_run` and `maintenance_last_run` are +//! slice 5 of #1183. mod credential; mod error; @@ -36,10 +36,12 @@ pub use credential::{ }; pub use error::McpError; pub use server::{ - AUDIT_DENIED, AdminMcp, DeleteEventArgs, FORBIDDEN, GetEventArgs, ListEventsArgs, - MAX_FILTER_TERMS, MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, - OUTCOME_ALREADY_DELETED, OUTCOME_DELETED, OUTCOME_NOT_DELETEABLE, OUTCOME_NOT_FOUND, - ReportAction, ReportsActionArgs, Requires, SettingsSetArgs, TOOL_DELETE_EVENT, TOOL_GET_EVENT, - TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, - TOOLS, Tool, UNAUTHORIZED, arguments_parse, audit_action, required_scope, + AUDIT_DENIED, AdminMcp, DeleteEventArgs, FORBIDDEN, GetEventArgs, InvoicesGetArgs, + InvoicesListArgs, ListEventsArgs, MAX_FILTER_TERMS, MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, + 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, }; diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index 8c91e65c..ab94265c 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -1,4 +1,4 @@ -//! The MCP server: the seven tools, the credential gate and the audit sink. +//! The MCP server: the twelve 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 @@ -11,11 +11,12 @@ use std::borrow::Cow; use std::sync::Arc; +use chrono::{DateTime, Utc}; use nostream_admin::AdminState; use nostream_admin::controllers::admin_json_body_middleware::settings_patch; use nostream_admin::controllers::patch_settings::{self, SettingsWrite}; use nostream_admin::utils::status; -use nostream_core::{EventId, Filter, Kind}; +use nostream_core::{EventId, Filter, Kind, Pubkey}; use nostream_relay::nip11; use nostream_storage::repositories::{EventRecord, collect_page, collect_records}; use rmcp::handler::server::router::tool::ToolRouter; @@ -47,9 +48,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 ` or `--admin-token-fd `, exactly one, its shape \ {\"scopes\": [\"write\"]}: the document's presence authorises `settings_get`, `list_events`, \ -`get_event` and `relay_status`, and the \"write\" scope authorises `settings_set`, \ -`delete_event` and `reports_action` (else the call \ -is `Forbidden`). \ +`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` \ +(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.` line to \ `/admin-audit.jsonl`, and a call the document's scopes deny appends one `mcp.denied` \ @@ -63,6 +64,11 @@ pub const TOOL_GET_EVENT: &str = "get_event"; pub const TOOL_RELAY_STATUS: &str = "relay_status"; pub const TOOL_DELETE_EVENT: &str = "delete_event"; pub const TOOL_REPORTS_ACTION: &str = "reports_action"; +pub const TOOL_REPORTS_LIST: &str = "reports_list"; +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"; /// What a delete call did, as the payload's `outcome` (R3, R4): this call marked the row /// deleted. @@ -90,7 +96,10 @@ pub const MAX_FILTER_TERMS: usize = 64; /// newest rows rather than the first. /// /// It is not `nostream_storage::MAX_PAGE_ROWS`, the relay's 5,000-row clamp: this is the page a -/// read materialises, which is the number a backend opens with. +/// read materialises, which is the number a backend opens with. It is also the door's page +/// bound, and for the invoice and report reads it is only a bound, because neither store's read +/// takes a direction from `limit`., and for the invoice and report reads it is only a bound, because +/// neither store's read takes a direction from `limit`. pub const MAX_ROWS_PER_PAGE: u64 = nostream_storage::DEFAULT_PAGE_ROWS; /// The refusal for a credential whose document is absent, unreadable or no longer a document this @@ -117,10 +126,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 four read tools say this in the table rather than leaving + /// asked for at dispatch. The eight 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 `settings_set`. + /// [`SCOPE_WRITE`]: the one scope a document may add, and the right to call the four tools + /// that write. Write, } @@ -214,6 +224,31 @@ pub const TOOLS: &[Tool] = &[ parses: reports_action_parses, needs: Requires::Write, }, + Tool { + name: TOOL_REPORTS_LIST, + parses: reports_list_parses, + needs: Requires::Read, + }, + Tool { + name: TOOL_USER_ADMIN, + parses: user_admin_parses, + needs: Requires::Write, + }, + Tool { + name: TOOL_USER_GET, + parses: user_get_parses, + needs: Requires::Read, + }, + Tool { + name: TOOL_INVOICES_LIST, + parses: invoices_list_parses, + needs: Requires::Read, + }, + Tool { + name: TOOL_INVOICES_GET, + parses: invoices_get_parses, + needs: Requires::Read, + }, ]; /// `tool`'s row; `None` when the table does not name it. @@ -266,6 +301,26 @@ fn reports_action_parses(arguments: Option<&Map>) -> bool { serde_json::from_value::(arguments_value(arguments)).is_ok() } +fn reports_list_parses(arguments: Option<&Map>) -> bool { + serde_json::from_value::(arguments_value(arguments)).is_ok() +} + +fn user_admin_parses(arguments: Option<&Map>) -> bool { + serde_json::from_value::(arguments_value(arguments)).is_ok() +} + +fn user_get_parses(arguments: Option<&Map>) -> bool { + serde_json::from_value::(arguments_value(arguments)).is_ok() +} + +fn invoices_list_parses(arguments: Option<&Map>) -> bool { + serde_json::from_value::(arguments_value(arguments)).is_ok() +} + +fn invoices_get_parses(arguments: Option<&Map>) -> bool { + serde_json::from_value::(arguments_value(arguments)).is_ok() +} + fn arguments_value(arguments: Option<&Map>) -> Value { Value::Object(arguments.cloned().unwrap_or_default()) } @@ -351,6 +406,96 @@ impl JsonSchema for ReportAction { } } +/// The user write's arguments: one pubkey and one of the four decisions (R2). +#[derive(Debug, Clone, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct UserAdminArgs { + /// The pubkey's 64-character hex key, in either case + pub pubkey: String, + /// `admit`, `revoke`, `vanish` or `unvanish` + pub action: UserAction, +} + +/// The four things an operator may decide about one pubkey. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum UserAction { + /// `admit`: sets `is_admitted` and stamps `tos_accepted_at` from the server clock. + Admit, + /// `revoke`: clears `is_admitted`; a pubkey with no row is left with none. + Revoke, + /// `vanish`: sets the stored vanished flag, writing a minimal row when the pubkey has none. + Vanish, + /// `unvanish`: clears the stored vanished flag, writing a minimal row (not admitted, balance + /// 0) when the pubkey has none. The relay's gate reads this cache, so a cleared flag lets the + /// pubkey publish again — the events the kind-62 request deleted are not restored. + Unvanish, +} + +impl UserAction { + /// The action's own name: the schema's `enum` member and the payload's `action` (R4). + fn as_str(self) -> &'static str { + match self { + Self::Admit => "admit", + Self::Revoke => "revoke", + Self::Vanish => "vanish", + Self::Unvanish => "unvanish", + } + } +} + +impl JsonSchema for UserAction { + fn schema_name() -> Cow<'static, str> { + "UserAction".into() + } + + /// The four literals as the schema's `enum`, for the reason `ReportAction`'s schema states: + /// the derive would spell a described unit enum as a `oneOf` of `const` variants. + fn json_schema(_: &mut SchemaGenerator) -> Schema { + json_schema!({ "type": "string", "enum": ["admit", "revoke", "vanish", "unvanish"] }) + } + + fn inline_schema() -> bool { + true + } +} + +/// The `user_get` arguments: the one pubkey whose row is read (R7). +#[derive(Debug, Clone, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct UserGetArgs { + /// The pubkey's 64-character hex key, in either case + pub pubkey: String, +} + +/// The `invoices_list` page: the store's own pending walk, paged (R11). +#[derive(Debug, Clone, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct InvoicesListArgs { + /// Rows to skip, oldest first; absent skips none. + pub offset: Option, + /// Page size: 1 to 500 rows, oldest first; absent uses 500. + #[schemars(range(min = 1, max = 500))] + pub limit: Option, +} + +/// The `invoices_get` arguments: one invoice's own id (R11). +#[derive(Debug, Clone, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct InvoicesGetArgs { + /// The invoice's own identifier, taken verbatim — not a hex id + pub id: String, +} + +/// The `reports_list` page: the review queue takes a bound and no offset (R16). +#[derive(Debug, Clone, Default, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct ReportsListArgs { + /// Page size: 1 to 500 reports, newest first; absent uses 500. + #[schemars(range(min = 1, max = 500))] + pub limit: Option, +} + /// The `settings_set` arguments: the same JSON object the console's HTTP body carries (R12). /// /// Kept as a raw map rather than a typed struct because the schema's rule is that an explicit @@ -566,6 +711,92 @@ next refresh, up to 30 s" } } + /// The review queue: the reports still actionable, newest first, at most `limit` (R16, D4). + #[tool( + description = "The review queue: the reports still actionable, newest first, at most \ +`limit` — 1 to 500, absent 500. This is not every report: a report an operator allowed has left \ +the queue, and the queue has no offset, so there is nothing to page. `reports_action` takes an \ +id this list shows" + )] + async fn reports_list( + &self, + Parameters(arguments): Parameters, + ) -> CallToolResult { + match self.review_queue(&arguments).await { + Ok(payload) => tool_ok(payload), + Err(error) => tool_error(&error), + } + } + + /// One pubkey's four decisions: the same row writes the relay's own strategies make, with + /// the one difference each that the description names (R1–R5). + #[tool( + description = "Administer one pubkey's user row: `admit` sets `is_admitted` and stamps \ +`tos_accepted_at` from the server clock, `revoke` clears `is_admitted` and writes no row for a \ +pubkey that has none, and `vanish`/`unvanish` set and clear the stored vanished flag, writing a \ +minimal row (not admitted, balance 0) when the pubkey has none. These are the same writes the \ +relay's own strategies make, with one difference each: `vanish` publishes no kind-62 request and \ +deletes no event, `unvanish` is the only path in the tree that clears the flag, and an admitted \ +pubkey is still held to `limits.event.pubkey.minBalance` by the relay's gate. Answers `action` \ +and the row as it stands after the call — `user` null when no row exists, `balance` 0 for that \ +same pubkey — so `revoke` and an unknown key answer the same shape as `admit`" + )] + async fn user_admin(&self, Parameters(arguments): Parameters) -> CallToolResult { + match self.administer(&arguments).await { + Ok(payload) => tool_ok(payload), + Err(error) => tool_error(&error), + } + } + + /// The read half: the stored row and its balance, and nothing written (R6–R10, D2). + #[tool( + description = "Read one pubkey's stored user row — `is_admitted`, `is_vanished`, \ +`balance` in msats and the two timestamps — and its balance on its own, so a missing row and an \ +empty balance are different answers: `user` is null and `balance` is 0 for a pubkey with no row. \ +`is_vanished` is the stored flag, never hydrated from a kind-62 request by this tool, so a pubkey \ +the relay has not cached and the door has never written reads as absent. Changes nothing" + )] + async fn user_get(&self, Parameters(arguments): Parameters) -> CallToolResult { + match self.read_user(&arguments).await { + Ok(payload) => tool_ok(payload), + Err(error) => tool_error(&error), + } + } + + /// The pending invoices, oldest first, paged by the store's own `(offset, limit)` (R12, D5). + #[tool( + description = "List the pending invoices, oldest first, paged by `offset` and `limit` — \ +the store's own pending walk, so a completed or expired invoice is not here and `invoices_get` \ +is how to read one whatever its status. `limit` is 1 to 500 rows, absent 500; `offset` skips \ +that many. A confirmed invoice stays in this list while its status reads `pending`" + )] + async fn invoices_list( + &self, + Parameters(arguments): Parameters, + ) -> CallToolResult { + match self.pending_invoices(&arguments).await { + Ok(payload) => tool_ok(payload), + Err(error) => tool_error(&error), + } + } + + /// One invoice by its own id, whatever its status; a miss is a result (R13, D5). + #[tool( + description = "Read one invoice by id, whatever its status; `invoice` is null when no \ +row carries the id. The id is the invoice's own opaque identifier — not a 64-character hex id — \ +and is taken verbatim. A confirmed invoice can still read `status: \"pending\"`: confirmation \ +sets `amount_paid` and `confirmed_at`, and only a status update moves the status" + )] + async fn invoices_get( + &self, + Parameters(arguments): Parameters, + ) -> CallToolResult { + match self.invoice(&arguments).await { + Ok(payload) => tool_ok(payload), + Err(error) => tool_error(&error), + } + } + /// 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). /// @@ -627,6 +858,86 @@ next refresh, up to 30 s" Ok(json!({ "reports": rows, "changed": changed })) } + /// The four decisions in one call: the store's own write, chosen by the closed enum, then + /// one read-back through `find_by_pubkey` (R3). Never `is_vanished`: that read hydrates and + /// stores (D2). + async fn administer(&self, arguments: &UserAdminArgs) -> Result { + let pubkey = pubkey_argument(&arguments.pubkey)?; + let users = &self.state.stores().users; + match arguments.action { + UserAction::Admit => users.admit_user(&pubkey, self.admitted_at()).await?, + UserAction::Revoke => { + users.revoke_admission(&pubkey).await?; + } + UserAction::Vanish => { + users.set_vanished(&pubkey, true).await?; + } + UserAction::Unvanish => { + users.set_vanished(&pubkey, false).await?; + } + } + let mut payload = self.user_row(&pubkey).await?; + payload["action"] = json!(arguments.action.as_str()); + Ok(payload) + } + + /// The instant an admission stamps, from the door's own clock: no module outside + /// `nostream-core` reads the system clock (R3). + fn admitted_at(&self) -> DateTime { + DateTime::from_timestamp_millis( + i64::try_from(self.state.clock().now_ms()).unwrap_or(i64::MAX), + ) + .unwrap_or(DateTime::UNIX_EPOCH) + } + + /// The read half's payload: the two reads the pair needs, in one place (R8, R9). + async fn read_user(&self, arguments: &UserGetArgs) -> Result { + let pubkey = pubkey_argument(&arguments.pubkey)?; + self.user_row(&pubkey).await + } + + /// The pair both user tools answer: the row as the store holds it, and the balance on its + /// own — `balance` is `0` for a pubkey with no row and for a row nothing has credited, so + /// `user` is the field that says which. + async fn user_row(&self, pubkey: &Pubkey) -> Result { + let users = &self.state.stores().users; + let user = users.find_by_pubkey(pubkey).await?; + let balance = users.get_balance_by_pubkey(pubkey).await?; + Ok(json!({ "user": user, "balance": balance })) + } + + /// The store's own pending walk, paged: no re-sort and no marker, because the store cannot + /// decide either (R12). + async fn pending_invoices(&self, arguments: &InvoicesListArgs) -> Result { + let limit = page_bound(arguments.limit)?; + let invoices = self + .state + .stores() + .invoices + .find_pending_invoices(arguments.offset.unwrap_or(0), limit) + .await?; + Ok(json!({ "invoices": invoices })) + } + + /// One invoice by the caller's own id, verbatim: `invoice.id` is opaque text, so no hex + /// criterion applies to it (R13). + async fn invoice(&self, arguments: &InvoicesGetArgs) -> Result { + let invoice = self + .state + .stores() + .invoices + .find_by_id(&arguments.id) + .await?; + Ok(json!({ "invoice": invoice })) + } + + /// `find_actionable`'s rows in the store's own order: the queue, never a re-sort (R17). + async fn review_queue(&self, arguments: &ReportsListArgs) -> Result { + let limit = page_bound(arguments.limit)?; + let reports = self.state.stores().reports.find_actionable(limit).await?; + Ok(json!({ "reports": reports })) + } + fn settings_document(&self) -> Result { let (merged, defaults) = self.state.merged_document()?; let filtered = nostream_config::store::filter_against_defaults(&merged, &defaults); @@ -776,17 +1087,26 @@ next refresh, up to 30 s" } } -/// The page a call asks for, checked against the bounds its `inputSchema` states. +/// The page a call asks for, checked against the bounds its `inputSchema` states (R14, D6). +/// +/// One bound and one refusal for the events and the two list tools, all of which name their +/// argument `limit` — which is why this takes no field name. +fn page_bound(limit: Option) -> Result { + let limit = limit.unwrap_or(MAX_ROWS_PER_PAGE); + (1..=MAX_ROWS_PER_PAGE) + .contains(&limit) + .then_some(limit) + .ok_or_else(|| { + McpError::Criterion(format!( + "limit: a page holds between 1 and {MAX_ROWS_PER_PAGE} rows, {limit} was given" + )) + }) +} + +/// The events' page size, from the one bound. fn page_size(criteria: &ListEventsArgs) -> Result { - let limit = criteria.limit.unwrap_or(MAX_ROWS_PER_PAGE); - let page = usize::try_from(limit).ok().filter(|page| { - (1..=usize::try_from(MAX_ROWS_PER_PAGE).unwrap_or(usize::MAX)).contains(page) - }); - page.ok_or_else(|| { - McpError::Criterion(format!( - "limit: a page holds between 1 and {MAX_ROWS_PER_PAGE} rows, {limit} was given" - )) - }) + // The bound caps the page at `MAX_ROWS_PER_PAGE`, so this conversion cannot narrow. + Ok(usize::try_from(page_bound(criteria.limit)?).unwrap_or(usize::MAX)) } /// One criterion list, normalised to lowercase hex: the wire's own floor, and at most @@ -827,6 +1147,21 @@ fn hex_prefix(field: &str, value: &str) -> Result { Ok(value.to_ascii_lowercase()) } +/// A pubkey argument: the wire's own floor, then exactly 64 characters (R3, R8). +/// +/// The length is checked before any store call, so a four-character prefix cannot widen to +/// whatever the store's range matches, and the lowercase form the first check produces is what +/// `TryFrom` reads. +fn pubkey_argument(value: &str) -> Result { + let pubkey = hex_prefix("pubkey", value)?; + if pubkey.len() != 64 { + return Err(McpError::Criterion(format!( + "pubkey: {pubkey:?} is not a 64-character hex pubkey" + ))); + } + Pubkey::try_from(pubkey.as_str()).map_err(|error| McpError::Criterion(error.to_string())) +} + #[tool_handler(router = self.tool_router)] impl ServerHandler for AdminMcp { fn get_info(&self) -> ServerConfig { diff --git a/crates/nostream-mcp/tests/audit.rs b/crates/nostream-mcp/tests/audit.rs index 52120768..421c3e01 100644 --- a/crates/nostream-mcp/tests/audit.rs +++ b/crates/nostream-mcp/tests/audit.rs @@ -2,11 +2,12 @@ //! //! | case | what it proves | //! |---|---| -//! | `each_call_appends_one_line` | seven calls append eight lines in call order — the seven `mcp.*` lines, then `settings_set`'s own `settings.updated` | +//! | `each_call_appends_one_line` | twelve calls append thirteen lines in call order — the twelve `mcp.*` lines, then `settings_set`'s own `settings.updated` | //! | `a_refused_call_appends_nothing` | a call with bad arguments and a call with no credential each leave the file untouched | //! | `every_registered_tool_has_a_table_row` | the table is total over the router's own list, so no tool can execute unaudited or ungated | //! | `the_audit_check_is_no_stricter_than_the_router` | the table's rule is the router's deserialiser, not the schema: a stricter check would fail open | //! | `the_write_tools_detail_carries_only_the_tool` | the two write tools' lines carry `{"tool": …}` and nothing else: no id, no action, no address | +//! | `the_store_tools_detail_carries_only_the_tool` | the five store tools' lines carry `{"tool": …}` and nothing else: no pubkey, no action, no invoice id | //! R9 appends the `mcp.*` line at dispatch, before the handler's work, so the order in the file //! is the order of the calls and a domain line always follows its own dispatch line. The one //! refusal that does write is a credential's scope denial — `mcp.denied`, R28 — and it has its @@ -20,8 +21,9 @@ use std::collections::BTreeSet; use common::{TestMcp, event, id_of, object, text}; use nostream_mcp::{ - TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, - TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOLS, audit_action, + 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, audit_action, }; use serde_json::json; @@ -32,6 +34,7 @@ async fn each_call_appends_one_line() { let id = id_of(&record); fixture.seed(std::slice::from_ref(&record)).await; let client = fixture.client().await; + let pubkey = "ab".repeat(32); client.call(TOOL_SETTINGS_GET, json!({})).await; client.call(TOOL_LIST_EVENTS, json!({})).await; @@ -44,6 +47,20 @@ async fn each_call_appends_one_line() { json!({ "id": report_id, "action": "allow" }), ) .await; + client.call(TOOL_REPORTS_LIST, json!({})).await; + client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": pubkey.clone(), "action": "admit" }), + ) + .await; + client + .call(TOOL_USER_GET, json!({ "pubkey": pubkey })) + .await; + client.call(TOOL_INVOICES_LIST, json!({})).await; + client + .call(TOOL_INVOICES_GET, json!({ "id": "inv-1" })) + .await; client.call(TOOL_RELAY_STATUS, json!({})).await; let written = client .call( @@ -66,6 +83,11 @@ async fn each_call_appends_one_line() { "mcp.get_event", "mcp.delete_event", "mcp.reports_action", + "mcp.reports_list", + "mcp.user_admin", + "mcp.user_get", + "mcp.invoices_list", + "mcp.invoices_get", "mcp.relay_status", "mcp.settings_set", "settings.updated", @@ -79,6 +101,11 @@ async fn each_call_appends_one_line() { TOOL_GET_EVENT, TOOL_DELETE_EVENT, TOOL_REPORTS_ACTION, + TOOL_REPORTS_LIST, + TOOL_USER_ADMIN, + TOOL_USER_GET, + TOOL_INVOICES_LIST, + TOOL_INVOICES_GET, TOOL_RELAY_STATUS, TOOL_SETTINGS_SET, ]) { @@ -93,19 +120,19 @@ async fn each_call_appends_one_line() { } assert_eq!( - entries[5]["detail"]["tool"], + entries[10]["detail"]["tool"], json!(TOOL_RELAY_STATUS), - "the sixth line is the status call's own: {entries:?}" + "the eleventh line is the status call's own: {entries:?}" ); assert_eq!( - entries[6]["detail"]["paths"], + entries[11]["detail"]["paths"], json!(["wot.enabled"]), "the settings write names the paths it asked for, never the values" ); assert!( - entries[6]["detail"].get("value").is_none(), + entries[11]["detail"].get("value").is_none(), "no value is recorded: {}", - entries[6] + entries[11] ); } @@ -157,6 +184,65 @@ async fn the_write_tools_detail_carries_only_the_tool() { } } +/// R22, R27: the five store tools' lines carry the tool and nothing else. A `detail` carrying the +/// pubkey, the action or an invoice id would let a caller's own text shape a record — the reason +/// `dispatch_detail` adds nothing for them. The action is compared through `audit_action` rather +/// than spelled: `each_call_appends_one_line`'s vector stays the file's only list of literals. +#[tokio::test] +async fn the_store_tools_detail_carries_only_the_tool() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + let pubkey = "ab".repeat(32); + + for (tool, arguments) in [ + ( + TOOL_USER_ADMIN, + json!({ "pubkey": pubkey, "action": "admit" }), + ), + (TOOL_USER_GET, json!({ "pubkey": pubkey })), + (TOOL_INVOICES_LIST, json!({})), + (TOOL_INVOICES_GET, json!({ "id": "inv-1" })), + (TOOL_REPORTS_LIST, json!({})), + ] { + let result = client.call(tool, arguments).await; + assert_eq!(result.is_error, Some(false), "{tool}: {}", text(&result)); + } + + let entries = fixture.audit_entries(); + let actions: Vec = entries + .iter() + .map(|entry| entry["action"].as_str().unwrap_or_default().to_owned()) + .collect(); + assert_eq!( + actions, + vec![ + audit_action(TOOL_USER_ADMIN), + audit_action(TOOL_USER_GET), + audit_action(TOOL_INVOICES_LIST), + audit_action(TOOL_INVOICES_GET), + audit_action(TOOL_REPORTS_LIST), + ], + "{entries:?}" + ); + for (entry, tool) in entries.iter().zip([ + TOOL_USER_ADMIN, + TOOL_USER_GET, + TOOL_INVOICES_LIST, + TOOL_INVOICES_GET, + TOOL_REPORTS_LIST, + ]) { + assert_eq!( + entry["detail"], + json!({ "tool": tool }), + "{tool}'s detail names the tool and nothing else: {entry}" + ); + assert!( + entry.get("remoteAddress").is_none(), + "a stdio caller has no address: {entry}" + ); + } +} + #[tokio::test] async fn a_refused_call_appends_nothing() { let fixture = TestMcp::start().await; diff --git a/crates/nostream-mcp/tests/auth.rs b/crates/nostream-mcp/tests/auth.rs index c6abe6f8..127bb2d2 100644 --- a/crates/nostream-mcp/tests/auth.rs +++ b/crates/nostream-mcp/tests/auth.rs @@ -3,13 +3,13 @@ //! //! | case | what it proves | //! |---|---| -//! | `a_revoked_token_refuses_every_tool` | a deleted document answers `Unauthorized` to all seven tools, writes nothing, and still lists them | +//! | `a_revoked_token_refuses_every_tool` | a deleted document answers `Unauthorized` to all twelve tools, writes nothing, and still lists them | //! | `a_read_only_token_is_refused_the_write` | a document with no scope reads and is refused `settings_set`, and the denial is a line in `admin-audit.jsonl` | //! | `a_disabled_surface_is_refused` | `admin.enabled: false` answers `Not Found`, as the console does | //! | `an_unknown_scope_refuses_the_load` | a document naming a scope the door does not know is refused when it is loaded, naming the scope and the accepted set | //! | `a_file_rewrite_changes_the_decision` | rewriting the file on a running server narrows the write, and rewriting it back restores it: the file's lifetime is the credential's | //! | `an_inherited_descriptor_authenticates` | the descriptor form answers `tools/list` and a read, and keeps the grant it was handed when the file it came from changes | -//! | `only_the_writing_tool_needs_a_scope` | the table names every registered tool and declares a scope for each: the four read tools read, the three writes need `write`, and a name the table does not carry needs `write` | +//! | `only_the_writing_tool_needs_a_scope` | the table names every registered tool and declares a scope for each: the eight read tools read, the four writes need `write`, and a name the table does not carry needs `write` | //! | `an_unregistered_tool_is_refused_before_the_scopes` | a name the surface does not register is refused with the router's own `-32602` before the scope decision, so a read-only document writes no denial line for it | //! | `a_group_readable_descriptor_refuses_to_start` | a `0644` document on a descriptor is refused as the same file by path is | //! | `a_device_descriptor_refuses_to_start` | a device on the descriptor is refused before a byte is read, so `/dev/zero` cannot hang the start | @@ -31,14 +31,16 @@ use std::os::unix::fs::PermissionsExt; use common::{Fixture, Grant, TestMcp, text, write_token}; use nostream_mcp::{ AUDIT_DENIED, Credential, FORBIDDEN, MAX_TOKEN_DOCUMENT_BYTES, NOT_FOUND, Requires, - TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, - TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOLS, UNAUTHORIZED, audit_action, required_scope, + 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, UNAUTHORIZED, audit_action, + required_scope, }; use serde_json::json; -/// The seven tools, each with arguments its schema accepts, so the refusal cannot be a +/// The twelve tools, each with arguments its schema accepts, so the refusal cannot be a /// deserialisation failure in disguise. -fn calls() -> [(&'static str, serde_json::Value); 7] { +fn calls() -> [(&'static str, serde_json::Value); 12] { [ (TOOL_SETTINGS_GET, json!({})), ( @@ -52,6 +54,14 @@ fn calls() -> [(&'static str, serde_json::Value); 7] { TOOL_REPORTS_ACTION, json!({ "id": "ab".repeat(32), "action": "hide" }), ), + (TOOL_REPORTS_LIST, json!({})), + ( + TOOL_USER_ADMIN, + json!({ "pubkey": "ab".repeat(32), "action": "admit" }), + ), + (TOOL_USER_GET, json!({ "pubkey": "ab".repeat(32) })), + (TOOL_INVOICES_LIST, json!({})), + (TOOL_INVOICES_GET, json!({ "id": "inv-1" })), (TOOL_RELAY_STATUS, json!({})), ] } @@ -63,7 +73,7 @@ async fn a_revoked_token_refuses_every_tool() { fixture.revoke(); let client = fixture.client().await; - assert_eq!(client.tools().await.len(), 7, "tools/list is not gated"); + assert_eq!(client.tools().await.len(), 12, "tools/list is not gated"); for (tool, arguments) in calls() { let result = client.call(tool, arguments).await; assert_eq!(result.is_error, Some(true), "{tool}: {}", text(&result)); @@ -232,7 +242,7 @@ async fn an_inherited_descriptor_authenticates() { .iter() .map(|tool| tool.name.to_string()) .collect(); - assert_eq!(names.len(), 7, "{names:?}"); + assert_eq!(names.len(), 12, "{names:?}"); let read = client.call(TOOL_SETTINGS_GET, json!({})).await; assert_eq!(read.is_error, Some(false), "{}", text(&read)); @@ -282,23 +292,31 @@ async fn only_the_writing_tool_needs_a_scope() { reading, vec![ TOOL_GET_EVENT, + TOOL_INVOICES_GET, + TOOL_INVOICES_LIST, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, - TOOL_SETTINGS_GET + TOOL_REPORTS_LIST, + TOOL_SETTINGS_GET, + TOOL_USER_GET ], "reading is the grant every document carries" ); assert_eq!( writing, - vec![TOOL_DELETE_EVENT, TOOL_REPORTS_ACTION, TOOL_SETTINGS_SET], + vec![ + TOOL_DELETE_EVENT, + TOOL_REPORTS_ACTION, + TOOL_SETTINGS_SET, + TOOL_USER_ADMIN + ], "the tools that change the relay are the ones a document opts into" ); - // A name the table does not carry needs the write: that is this helper's answer for it, and // the reason a missing row fails closed rather than open. `call_tool` refuses such a name // before it asks — see `an_unregistered_tool_is_refused_before_the_scopes` — so a rowless tool // never reaches dispatch at all. - assert_eq!(required_scope("user_admin"), Requires::Write); + assert_eq!(required_scope("maintenance_run"), Requires::Write); } /// A name the surface does not register is refused before the scope decision, so a document that @@ -315,7 +333,7 @@ async fn an_unregistered_tool_is_refused_before_the_scopes() { let client = fixture.client().await; let error = client - .try_call("user_admin", json!({})) + .try_call("maintenance_run", json!({})) .await .expect_err("a name the table does not carry is not a tool"); let rmcp::ServiceError::McpError(error) = error else { diff --git a/crates/nostream-mcp/tests/common/mod.rs b/crates/nostream-mcp/tests/common/mod.rs index 4c7e7e8c..ae21b296 100644 --- a/crates/nostream-mcp/tests/common/mod.rs +++ b/crates/nostream-mcp/tests/common/mod.rs @@ -70,7 +70,7 @@ pub fn base_settings() -> serde_yaml::Value { /// The scopes the fixture's token document names. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub enum Grant { - /// `{"scopes": ["write"]}`: the four read tools and the three writes. + /// `{"scopes": ["write"]}`: the eight read tools and the four writes. #[default] Write, /// `{"scopes": []}`: the read tools only — the door's default (R28). diff --git a/crates/nostream-mcp/tests/fixtures/tools_list.json b/crates/nostream-mcp/tests/fixtures/tools_list.json index 7c115224..bc3d817d 100644 --- a/crates/nostream-mcp/tests/fixtures/tools_list.json +++ b/crates/nostream-mcp/tests/fixtures/tools_list.json @@ -36,6 +36,54 @@ }, "name": "get_event" }, + { + "description": "Read one invoice by id, whatever its status; `invoice` is null when no row carries the id. The id is the invoice's own opaque identifier — not a 64-character hex id — and is taken verbatim. A confirmed invoice can still read `status: \"pending\"`: confirmation sets `amount_paid` and `confirmed_at`, and only a status update moves the status", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "id": { + "description": "The invoice's own identifier, taken verbatim — not a hex id", + "type": "string" + } + }, + "required": [ + "id" + ], + "type": "object" + }, + "name": "invoices_get" + }, + { + "description": "List the pending invoices, oldest first, paged by `offset` and `limit` — the store's own pending walk, so a completed or expired invoice is not here and `invoices_get` is how to read one whatever its status. `limit` is 1 to 500 rows, absent 500; `offset` skips that many. A confirmed invoice stays in this list while its status reads `pending`", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "limit": { + "description": "Page size: 1 to 500 rows, oldest first; absent uses 500.", + "format": "uint64", + "maximum": 500, + "minimum": 1, + "type": [ + "integer", + "null" + ] + }, + "offset": { + "description": "Rows to skip, oldest first; absent skips none.", + "format": "uint64", + "minimum": 0, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + }, + "name": "invoices_list" + }, { "description": "List stored events matching the given kinds, authors, ids, since and until. Rows come back oldest first, and `limit` is the page size — the first rows in that order, at most 500; `truncated` is true when the page is full, so more rows may match", "inputSchema": { @@ -140,6 +188,27 @@ }, "name": "reports_action" }, + { + "description": "The review queue: the reports still actionable, newest first, at most `limit` — 1 to 500, absent 500. This is not every report: a report an operator allowed has left the queue, and the queue has no offset, so there is nothing to page. `reports_action` takes an id this list shows", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "limit": { + "description": "Page size: 1 to 500 reports, newest first; absent uses 500.", + "format": "uint64", + "maximum": 500, + "minimum": 1, + "type": [ + "integer", + "null" + ] + } + }, + "type": "object" + }, + "name": "reports_list" + }, { "description": "Read the merged settings document, narrowed to the defaults' keys and redacted. The document arrives under `settings`", "inputSchema": { @@ -200,7 +269,53 @@ "type": "object" }, "name": "settings_set" + }, + { + "description": "Administer one pubkey's user row: `admit` sets `is_admitted` and stamps `tos_accepted_at` from the server clock, `revoke` clears `is_admitted` and writes no row for a pubkey that has none, and `vanish`/`unvanish` set and clear the stored vanished flag, writing a minimal row (not admitted, balance 0) when the pubkey has none. These are the same writes the relay's own strategies make, with one difference each: `vanish` publishes no kind-62 request and deletes no event, `unvanish` is the only path in the tree that clears the flag, and an admitted pubkey is still held to `limits.event.pubkey.minBalance` by the relay's gate. Answers `action` and the row as it stands after the call — `user` null when no row exists, `balance` 0 for that same pubkey — so `revoke` and an unknown key answer the same shape as `admit`", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "action": { + "description": "`admit`, `revoke`, `vanish` or `unvanish`", + "enum": [ + "admit", + "revoke", + "vanish", + "unvanish" + ], + "type": "string" + }, + "pubkey": { + "description": "The pubkey's 64-character hex key, in either case", + "type": "string" + } + }, + "required": [ + "pubkey", + "action" + ], + "type": "object" + }, + "name": "user_admin" + }, + { + "description": "Read one pubkey's stored user row — `is_admitted`, `is_vanished`, `balance` in msats and the two timestamps — and its balance on its own, so a missing row and an empty balance are different answers: `user` is null and `balance` is 0 for a pubkey with no row. `is_vanished` is the stored flag, never hydrated from a kind-62 request by this tool, so a pubkey the relay has not cached and the door has never written reads as absent. Changes nothing", + "inputSchema": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "additionalProperties": false, + "properties": { + "pubkey": { + "description": "The pubkey's 64-character hex key, in either case", + "type": "string" + } + }, + "required": [ + "pubkey" + ], + "type": "object" + }, + "name": "user_get" } ] } - diff --git a/crates/nostream-mcp/tests/store_families.rs b/crates/nostream-mcp/tests/store_families.rs new file mode 100644 index 00000000..f3bed9c8 --- /dev/null +++ b/crates/nostream-mcp/tests/store_families.rs @@ -0,0 +1,801 @@ +//! AC3, AC7 — the five store-family tools' oracle: the user row and its balance, the write that +//! leaves the store's own row, the read that must not hydrate, the pending invoice walk, the +//! single invoice, and the review queue — through the protocol a client uses. +//! +//! | case | what it proves | +//! |---|---| +//! | `user_get_answers_the_row_and_its_balance` | the row arrives as the store holds it, and its balance beside it | +//! | `user_get_answers_an_absent_pubkey_with_null_and_zero` | a pubkey with no row is `user: null` and `balance: 0`, not an error | +//! | `user_get_reads_the_stored_flag_and_hydrates_nothing` | a live kind-62 leaves no row behind: the read path is `find_by_pubkey`, never `is_vanished` | +//! | `user_admin_admits_an_uppercase_pubkey_and_the_store_says_so` | the criterion lowercases, and the store — not the payload — carries the admission | +//! | `admitting_a_row_keeps_its_balance` | `admit` writes the row that is there: the invoice's credit survives | +//! | `user_admin_revokes_and_an_absent_pubkey_writes_no_row` | `revoke` clears the flag and creates nothing for a pubkey with no row | +//! | `user_admin_vanishes_and_unvanishes_the_stored_flag` | the minimal row, and the tree's only clearing of the flag | +//! | `vanishing_writes_the_flag_and_deletes_no_event` | the tool is the row write, not the relay's strategy: no event is deleted | +//! | `an_unknown_user_action_never_reaches_the_handler` | the closed set is the arguments type, so nothing is written | +//! | `a_short_pubkey_is_refused_after_its_dispatch_line` | a prefix is refused by the length check before any store call, and its dispatch line exists | +//! | `a_read_only_document_reads_and_is_refused_the_user_write` | the four reads answer under a document that grants nothing, the write is denied and recorded, and no row is written | +//! | `invoices_list_is_the_pending_walk_oldest_first` | the list is the store's pending index, not a status filter: an expired row is absent and still readable by id | +//! | `invoices_list_pages_by_offset_and_refuses_a_page_outside_the_bound` | `offset`/`limit` are the store's own page, and 0 and 501 are the one refusal | +//! | `invoices_get_answers_the_row_and_a_miss_is_null` | the thirteen fields, and a miss as a result — an id that is 64 hex characters is no different | +//! | `a_confirmed_invoice_still_reads_pending` | confirmation sets the paid fields and leaves the status, and the list keeps naming the row | +//! | `reports_list_is_the_actionable_queue_newest_first` | the queue is `find_actionable`: newest first, and a report an operator allowed is not in it | +//! | `reports_list_refuses_a_page_outside_the_bound` | the queue shares the one page bound | +//! +//! The store is the harness's LMDB backend, seeded the way the storage tests seed it: the +//! repository traits' own writes, so a case reads back through `find_by_pubkey` rather than +//! trusting the payload it just asked for. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +mod common; + +use chrono::{DateTime, Utc}; +use common::{Fixture, Grant, TestMcp, event, id_of, payload, text}; +use nostream_core::{EventId, Filter, Pubkey}; +use nostream_mcp::{ + FORBIDDEN, TOOL_INVOICES_GET, TOOL_INVOICES_LIST, TOOL_REPORTS_LIST, TOOL_USER_ADMIN, + TOOL_USER_GET, audit_action, +}; +use nostream_storage::repositories::{ + EventRepository, FieldUpdate, Invoice, InvoiceRepository, InvoiceStatus, InvoiceUnit, + NewReport, Report, ReportRepository, ReportType, User, UserPatch, UserRepository, +}; +use serde_json::{Value, json}; + +/// The published keyspace's `"ab".repeat(32)`, as a pubkey. +fn key() -> Pubkey { + Pubkey::try_from("ab".repeat(32).as_str()).expect("32 bytes of hex") +} + +/// The hex form a case sends, in either case. +fn key_hex() -> String { + key().to_string() +} + +/// An instant at `seconds`, which the store truncates to microseconds. +fn instant(seconds: i64) -> DateTime { + DateTime::from_timestamp(seconds, 0).expect("an instant in range") +} + +/// One user row, admitted, written through the trait a case reads back with. +async fn seed_user(fixture: &TestMcp, pubkey: &Pubkey) { + let patch = UserPatch { + pubkey: *pubkey, + is_admitted: FieldUpdate::Set(true), + is_vanished: FieldUpdate::Absent, + tos_accepted_at: FieldUpdate::Absent, + }; + UserRepository::upsert(&*fixture.backend, &patch) + .await + .expect("the row stores"); +} + +/// The stored row, read through `find_by_pubkey` — fully qualified, because the backend answers +/// NIP-05's read of the same name. +async fn stored_user(fixture: &TestMcp, pubkey: &Pubkey) -> Option { + UserRepository::find_by_pubkey(&*fixture.backend, pubkey) + .await + .expect("the user store answers") +} + +/// One invoice row, written through the trait the list reads. +async fn seed_invoice(fixture: &TestMcp, invoice: &Invoice) { + InvoiceRepository::upsert(&*fixture.backend, invoice) + .await + .expect("the invoice stores"); +} + +/// An invoice of `status`, created at `created_at`, requesting `amount_requested` sats. +fn invoice(id: &str, pubkey: &Pubkey, status: InvoiceStatus, created_at: DateTime) -> Invoice { + Invoice { + id: id.to_owned(), + pubkey: *pubkey, + bolt11: format!("lnbc-{id}"), + amount_requested: 1_000, + amount_paid: None, + unit: InvoiceUnit::Sats, + status, + description: format!("invoice {id}"), + confirmed_at: None, + expires_at: None, + updated_at: created_at, + created_at, + verify_url: None, + } +} + +/// One report row against `pubkey`'s event, with its own event id. +async fn seed_report( + fixture: &TestMcp, + report_event: [u8; 32], + pubkey: &Pubkey, + reported_event: EventId, + actionable: bool, +) -> Report { + let report = NewReport { + event_id: EventId::from_byte_array(report_event), + reporter_pubkey: Pubkey::from_byte_array([90; 32]), + reported_pubkey: Some(*pubkey), + reported_event_id: Some(reported_event), + report_type: ReportType::Spam, + weight: 1.0, + actionable, + }; + ReportRepository::create(&*fixture.backend, &report) + .await + .expect("the report stores") +} + +/// The `id`s a list payload carried, in payload order. +fn ids(payload: &Value, field: &str) -> Vec { + payload[field] + .as_array() + .expect("a list payload") + .iter() + .map(|row| row["id"].as_str().unwrap_or_default().to_owned()) + .collect() +} + +#[tokio::test] +async fn user_get_answers_the_row_and_its_balance() { + let fixture = TestMcp::start().await; + let pubkey = key(); + seed_user(&fixture, &pubkey).await; + let client = fixture.client().await; + + let result = client + .call(TOOL_USER_GET, json!({ "pubkey": key_hex() })) + .await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let answer = payload(&result); + assert_eq!(answer["user"]["pubkey"], json!(key_hex()), "{answer}"); + assert_eq!(answer["user"]["is_admitted"], true, "{answer}"); + assert_eq!(answer["user"]["is_vanished"], false, "{answer}"); + assert_eq!(answer["user"]["balance"], 0, "{answer}"); + assert_eq!(answer["balance"], 0, "{answer}"); + assert!( + answer["user"]["created_at"].is_string(), + "the row's timestamp is the store's: {answer}" + ); + assert!( + answer["user"]["updated_at"].is_string(), + "the row's timestamp is the store's: {answer}" + ); + assert_eq!( + answer.as_object().map(serde_json::Map::len), + Some(2), + "{answer}" + ); +} + +#[tokio::test] +async fn user_get_answers_an_absent_pubkey_with_null_and_zero() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let result = client + .call(TOOL_USER_GET, json!({ "pubkey": key_hex() })) + .await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let answer = payload(&result); + assert!(answer["user"].is_null(), "{answer}"); + assert_eq!(answer["balance"], 0, "{answer}"); + assert!( + stored_user(&fixture, &key()).await.is_none(), + "no row exists" + ); +} + +#[tokio::test] +async fn user_get_reads_the_stored_flag_and_hydrates_nothing() { + let fixture = TestMcp::start().await; + let record = event(77, 62, 1_699_999_700); + let pubkey = record.event.pubkey; + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + let result = client + .call(TOOL_USER_GET, json!({ "pubkey": pubkey.to_string() })) + .await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + assert!( + payload(&result)["user"].is_null(), + "the flag was never hydrated" + ); + assert!( + stored_user(&fixture, &pubkey).await.is_none(), + "a kind-62 the relay never cached leaves no row: the read path is find_by_pubkey" + ); +} + +#[tokio::test] +async fn user_admin_admits_an_uppercase_pubkey_and_the_store_says_so() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let result = client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": key_hex().to_uppercase(), "action": "admit" }), + ) + .await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let answer = payload(&result); + assert_eq!(answer["action"], "admit", "{answer}"); + assert_eq!(answer["user"]["is_admitted"], true, "{answer}"); + assert_eq!(answer["balance"], 0, "{answer}"); + assert_eq!( + answer.as_object().map(serde_json::Map::len), + Some(3), + "{answer}" + ); + let stored = stored_user(&fixture, &key()).await.expect("the row exists"); + assert!(stored.is_admitted, "the store, not the payload, carries it"); +} + +#[tokio::test] +async fn admitting_a_row_keeps_its_balance() { + let fixture = TestMcp::start().await; + let pubkey = key(); + seed_user(&fixture, &pubkey).await; + seed_invoice( + &fixture, + &invoice( + "inv-credit", + &pubkey, + InvoiceStatus::Pending, + instant(1_699_999_000), + ), + ) + .await; + InvoiceRepository::confirm_invoice( + &*fixture.backend, + "inv-credit", + 1_000, + instant(1_699_999_800), + ) + .await + .expect("the payment confirms"); + let credited = UserRepository::get_balance_by_pubkey(&*fixture.backend, &pubkey) + .await + .expect("the balance reads"); + assert_eq!(credited, 1_000_000, "1000 sats credits 1 000 000 msats"); + + let client = fixture.client().await; + let result = client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": key_hex(), "action": "admit" }), + ) + .await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + let answer = payload(&result); + assert_eq!(answer["balance"], 1_000_000, "{answer}"); + assert_eq!(answer["user"]["balance"], 1_000_000, "{answer}"); + assert_eq!(answer["user"]["is_admitted"], true, "{answer}"); +} + +#[tokio::test] +async fn user_admin_revokes_and_an_absent_pubkey_writes_no_row() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let admitted = client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": key_hex(), "action": "admit" }), + ) + .await; + assert_eq!(admitted.is_error, Some(false), "{}", text(&admitted)); + + let revoked = client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": key_hex(), "action": "revoke" }), + ) + .await; + assert_eq!(revoked.is_error, Some(false), "{}", text(&revoked)); + let answer = payload(&revoked); + assert_eq!(answer["action"], "revoke", "{answer}"); + assert_eq!(answer["user"]["is_admitted"], false, "{answer}"); + assert_eq!(answer["balance"], 0, "{answer}"); + + let absent = "cd".repeat(32); + let missed = client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": absent, "action": "revoke" }), + ) + .await; + assert_eq!(missed.is_error, Some(false), "{}", text(&missed)); + let answer = payload(&missed); + assert!(answer["user"].is_null(), "{answer}"); + assert_eq!(answer["balance"], 0, "{answer}"); + let absent = Pubkey::try_from(absent.as_str()).expect("32 bytes of hex"); + assert!( + stored_user(&fixture, &absent).await.is_none(), + "revocation creates nothing" + ); +} + +#[tokio::test] +async fn user_admin_vanishes_and_unvanishes_the_stored_flag() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let vanished = client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": key_hex(), "action": "vanish" }), + ) + .await; + assert_eq!(vanished.is_error, Some(false), "{}", text(&vanished)); + let answer = payload(&vanished); + assert_eq!(answer["user"]["is_vanished"], true, "{answer}"); + assert_eq!( + answer["user"]["is_admitted"], false, + "the minimal row: {answer}" + ); + assert_eq!(answer["balance"], 0, "{answer}"); + assert!( + stored_user(&fixture, &key()) + .await + .is_some_and(|row| row.is_vanished) + ); + + let unvanished = client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": key_hex(), "action": "unvanish" }), + ) + .await; + assert_eq!(unvanished.is_error, Some(false), "{}", text(&unvanished)); + assert_eq!(payload(&unvanished)["user"]["is_vanished"], false); + assert!( + stored_user(&fixture, &key()) + .await + .is_some_and(|row| !row.is_vanished), + "the flag is cleared in the store, which is what the relay's gate reads" + ); +} + +#[tokio::test] +async fn vanishing_writes_the_flag_and_deletes_no_event() { + let fixture = TestMcp::start().await; + let record = event(78, 1, 1_699_999_701); + let id = id_of(&record); + let pubkey = record.event.pubkey; + fixture.seed(std::slice::from_ref(&record)).await; + let client = fixture.client().await; + + let vanished = client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": pubkey.to_string(), "action": "vanish" }), + ) + .await; + assert_eq!(vanished.is_error, Some(false), "{}", text(&vanished)); + + let count = fixture + .backend + .count_by_filters(&[Filter { + ids: Some(vec![id]), + ..Filter::default() + }]) + .await + .expect("the store counts"); + assert_eq!( + count, 1, + "the event the relay's strategy would have deleted is still stored" + ); +} + +#[tokio::test] +async fn an_unknown_user_action_never_reaches_the_handler() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let refused = client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": key_hex(), "action": "erase" }), + ) + .await; + assert_eq!(refused.is_error, Some(true), "{}", text(&refused)); + assert!( + fixture.audit_entries().is_empty(), + "the arguments type refuses it before dispatch: {:?}", + fixture.audit_entries() + ); +} + +#[tokio::test] +async fn a_short_pubkey_is_refused_after_its_dispatch_line() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + let refused = client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": "abcd", "action": "admit" }), + ) + .await; + assert_eq!(refused.is_error, Some(true), "{}", text(&refused)); + assert_eq!( + text(&refused), + "pubkey: \"abcd\" is not a 64-character hex pubkey", + "the length check refuses a prefix before any store call" + ); + + let entries = fixture.audit_entries(); + assert_eq!(entries.len(), 1, "{entries:?}"); + assert_eq!( + entries[0]["action"], + audit_action(TOOL_USER_ADMIN), + "{entries:?}" + ); + + // The key it would have widened to is absent, so nothing reached the store. + let widened = Pubkey::try_from("abcd".repeat(16).as_str()).expect("32 bytes of hex"); + assert!(stored_user(&fixture, &widened).await.is_none()); +} + +#[tokio::test] +async fn a_read_only_document_reads_and_is_refused_the_user_write() { + let fixture = TestMcp::start_with(Fixture { + grant: Grant::Read, + ..Fixture::default() + }) + .await; + let record = event(79, 1, 1_699_999_702); + let pubkey = record.event.pubkey; + fixture.seed(std::slice::from_ref(&record)).await; + seed_invoice( + &fixture, + &invoice( + "inv-read", + &pubkey, + InvoiceStatus::Pending, + instant(1_699_999_010), + ), + ) + .await; + let client = fixture.client().await; + + for (tool, arguments) in [ + (TOOL_USER_GET, json!({ "pubkey": pubkey.to_string() })), + (TOOL_INVOICES_LIST, json!({})), + (TOOL_INVOICES_GET, json!({ "id": "inv-read" })), + (TOOL_REPORTS_LIST, json!({})), + ] { + let result = client.call(tool, arguments).await; + assert_eq!(result.is_error, Some(false), "{tool}: {}", text(&result)); + } + + let denied = client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": pubkey.to_string(), "action": "admit" }), + ) + .await; + assert_eq!(denied.is_error, Some(true), "{}", text(&denied)); + let refusal = text(&denied); + assert!(refusal.contains(FORBIDDEN), "{refusal}"); + assert!(refusal.contains(TOOL_USER_ADMIN), "{refusal}"); + + let entries = fixture.audit_entries(); + let actions: Vec<&str> = entries + .iter() + .map(|entry| entry["action"].as_str().unwrap_or_default()) + .collect(); + assert_eq!( + actions, + vec![ + audit_action(TOOL_USER_GET).as_str(), + audit_action(TOOL_INVOICES_LIST).as_str(), + audit_action(TOOL_INVOICES_GET).as_str(), + audit_action(TOOL_REPORTS_LIST).as_str(), + nostream_mcp::AUDIT_DENIED, + ], + "{entries:?}" + ); + assert_eq!( + entries[4]["detail"], + json!({ "tool": TOOL_USER_ADMIN, "scope": "write" }), + "{entries:?}" + ); + assert!( + entries[4].get("remoteAddress").is_none(), + "a stdio caller has no address" + ); + assert!( + stored_user(&fixture, &pubkey).await.is_none(), + "the refused write wrote no row" + ); +} + +#[tokio::test] +async fn invoices_list_is_the_pending_walk_oldest_first() { + let fixture = TestMcp::start().await; + let pubkey = key(); + for row in [ + invoice( + "inv-t1", + &pubkey, + InvoiceStatus::Pending, + instant(1_699_999_100), + ), + invoice( + "inv-t2", + &pubkey, + InvoiceStatus::Pending, + instant(1_699_999_200), + ), + invoice( + "inv-expired", + &pubkey, + InvoiceStatus::Expired, + instant(1_699_999_300), + ), + ] { + seed_invoice(&fixture, &row).await; + } + let client = fixture.client().await; + + let listed = client.call(TOOL_INVOICES_LIST, json!({})).await; + assert_eq!(listed.is_error, Some(false), "{}", text(&listed)); + assert_eq!( + ids(&payload(&listed), "invoices"), + vec!["inv-t1", "inv-t2"], + "the pending index, oldest first" + ); + + let single = client + .call(TOOL_INVOICES_GET, json!({ "id": "inv-expired" })) + .await; + assert_eq!(single.is_error, Some(false), "{}", text(&single)); + assert_eq!(payload(&single)["invoice"]["status"], "expired"); +} + +#[tokio::test] +async fn invoices_list_pages_by_offset_and_refuses_a_page_outside_the_bound() { + let fixture = TestMcp::start().await; + let pubkey = key(); + for row in [ + invoice( + "inv-p1", + &pubkey, + InvoiceStatus::Pending, + instant(1_699_999_100), + ), + invoice( + "inv-p2", + &pubkey, + InvoiceStatus::Pending, + instant(1_699_999_200), + ), + invoice( + "inv-p3", + &pubkey, + InvoiceStatus::Pending, + instant(1_699_999_300), + ), + ] { + seed_invoice(&fixture, &row).await; + } + let client = fixture.client().await; + + let paged = client + .call(TOOL_INVOICES_LIST, json!({ "offset": 1, "limit": 1 })) + .await; + assert_eq!(paged.is_error, Some(false), "{}", text(&paged)); + assert_eq!(ids(&payload(&paged), "invoices"), vec!["inv-p2"]); + + for given in [0, 501] { + let refused = client + .call(TOOL_INVOICES_LIST, json!({ "limit": given })) + .await; + assert_eq!(refused.is_error, Some(true), "{given}: {}", text(&refused)); + assert_eq!( + text(&refused), + format!("limit: a page holds between 1 and 500 rows, {given} was given"), + "{given}" + ); + } +} + +#[tokio::test] +async fn invoices_get_answers_the_row_and_a_miss_is_null() { + let fixture = TestMcp::start().await; + let pubkey = key(); + seed_invoice( + &fixture, + &invoice( + "inv-1", + &pubkey, + InvoiceStatus::Pending, + instant(1_699_999_100), + ), + ) + .await; + let client = fixture.client().await; + + let found = client + .call(TOOL_INVOICES_GET, json!({ "id": "inv-1" })) + .await; + assert_eq!(found.is_error, Some(false), "{}", text(&found)); + let answer = payload(&found); + let row = answer["invoice"].as_object().expect("one invoice row"); + assert_eq!( + row.len(), + 13, + "the struct's own field count: {}", + row.keys().cloned().collect::>().join(", ") + ); + for field in [ + "id", + "pubkey", + "bolt11", + "amount_requested", + "amount_paid", + "unit", + "status", + "description", + "confirmed_at", + "expires_at", + "updated_at", + "created_at", + "verify_url", + ] { + assert!( + row.contains_key(field), + "{field} is one of the thirteen: {answer}" + ); + } + assert_eq!(answer["invoice"]["unit"], "sats", "{answer}"); + assert_eq!(answer["invoice"]["status"], "pending", "{answer}"); + for field in ["amount_paid", "confirmed_at", "expires_at", "verify_url"] { + assert!(answer["invoice"][field].is_null(), "{field}: {answer}"); + } + + let missing = client + .call(TOOL_INVOICES_GET, json!({ "id": "missing" })) + .await; + assert_eq!(missing.is_error, Some(false), "{}", text(&missing)); + assert_eq!(payload(&missing), json!({ "invoice": null })); + + // An id that is 64 hex characters is an id: no hex criterion applies to an invoice. + let hex_id = "ef".repeat(32); + let accepted = client + .call(TOOL_INVOICES_GET, json!({ "id": hex_id })) + .await; + assert_eq!(accepted.is_error, Some(false), "{}", text(&accepted)); + assert_eq!(payload(&accepted), json!({ "invoice": null })); +} + +#[tokio::test] +async fn a_confirmed_invoice_still_reads_pending() { + let fixture = TestMcp::start().await; + let pubkey = key(); + seed_user(&fixture, &pubkey).await; + seed_invoice( + &fixture, + &invoice( + "inv-paid", + &pubkey, + InvoiceStatus::Pending, + instant(1_699_999_100), + ), + ) + .await; + InvoiceRepository::confirm_invoice( + &*fixture.backend, + "inv-paid", + 1_000, + instant(1_699_999_500), + ) + .await + .expect("the payment confirms"); + let client = fixture.client().await; + + let read = client + .call(TOOL_INVOICES_GET, json!({ "id": "inv-paid" })) + .await; + assert_eq!(read.is_error, Some(false), "{}", text(&read)); + let answer = payload(&read); + assert_eq!(answer["invoice"]["status"], "pending", "{answer}"); + assert_eq!(answer["invoice"]["amount_paid"], 1_000, "{answer}"); + assert!( + answer["invoice"]["confirmed_at"].is_string(), + "confirmation stamps the instant: {answer}" + ); + + let listed = client.call(TOOL_INVOICES_LIST, json!({})).await; + assert_eq!(listed.is_error, Some(false), "{}", text(&listed)); + assert_eq!( + ids(&payload(&listed), "invoices"), + vec!["inv-paid"], + "the pending index still holds the confirmed row" + ); +} + +#[tokio::test] +async fn reports_list_is_the_actionable_queue_newest_first() { + let fixture = TestMcp::start().await; + let pubkey = key(); + let first = seed_report( + &fixture, + [0xa1; 32], + &pubkey, + EventId::from_byte_array([1; 32]), + true, + ) + .await; + let second = seed_report( + &fixture, + [0xb2; 32], + &pubkey, + EventId::from_byte_array([2; 32]), + true, + ) + .await; + let allowed = seed_report( + &fixture, + [0xc3; 32], + &pubkey, + EventId::from_byte_array([3; 32]), + false, + ) + .await; + let client = fixture.client().await; + + let listed = client.call(TOOL_REPORTS_LIST, json!({})).await; + assert_eq!(listed.is_error, Some(false), "{}", text(&listed)); + let answer = payload(&listed); + let rows = answer["reports"].as_array().expect("the queue"); + assert_eq!( + rows.len(), + 2, + "the non-actionable row is not in the queue: {answer}" + ); + assert_eq!(rows[0]["id"], second.id, "newest first: {answer}"); + assert_eq!(rows[1]["id"], first.id, "{answer}"); + assert!( + !rows.iter().any(|row| row["id"] == allowed.id), + "a report an operator allowed has left the queue: {answer}" + ); + let still_stored = ReportRepository::find_by_event_id(&*fixture.backend, &allowed.event_id) + .await + .expect("the report store answers"); + assert_eq!( + still_stored.len(), + 1, + "the row exists: its absence from the list is the list's filter" + ); + + let one = client.call(TOOL_REPORTS_LIST, json!({ "limit": 1 })).await; + assert_eq!(one.is_error, Some(false), "{}", text(&one)); + let answer = payload(&one); + let rows = answer["reports"].as_array().expect("the queue"); + assert_eq!(rows.len(), 1, "the bound holds: {answer}"); + assert_eq!(rows[0]["id"], second.id, "and it is the newest: {answer}"); +} + +#[tokio::test] +async fn reports_list_refuses_a_page_outside_the_bound() { + let fixture = TestMcp::start().await; + let client = fixture.client().await; + + for given in [0, 501] { + let refused = client + .call(TOOL_REPORTS_LIST, json!({ "limit": given })) + .await; + assert_eq!(refused.is_error, Some(true), "{given}: {}", text(&refused)); + assert_eq!( + text(&refused), + format!("limit: a page holds between 1 and 500 rows, {given} was given"), + "{given}" + ); + } +} diff --git a/crates/nostream-mcp/tests/tool_payloads.rs b/crates/nostream-mcp/tests/tool_payloads.rs index bf406f13..ba1daf0c 100644 --- a/crates/nostream-mcp/tests/tool_payloads.rs +++ b/crates/nostream-mcp/tests/tool_payloads.rs @@ -330,7 +330,7 @@ async fn an_unknown_tool_is_a_protocol_error() { let client = fixture.client().await; let error = client - .try_call("user_admin", json!({})) + .try_call("maintenance_run", json!({})) .await .expect_err("an absent tool is a JSON-RPC error, not a result"); let rmcp::ServiceError::McpError(error) = error else { diff --git a/crates/nostream-mcp/tests/tools_list.rs b/crates/nostream-mcp/tests/tools_list.rs index f2185865..5b408d32 100644 --- a/crates/nostream-mcp/tests/tools_list.rs +++ b/crates/nostream-mcp/tests/tools_list.rs @@ -18,8 +18,9 @@ mod common; use common::TestMcp; use nostream_mcp::{ - MAX_ROWS_PER_PAGE, TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, - TOOL_REPORTS_ACTION, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, + MAX_ROWS_PER_PAGE, 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, }; use serde_json::{Value, json}; @@ -175,13 +176,18 @@ async fn the_required_parameters_are_typed() { vec![ 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_SETTINGS_SET, + TOOL_USER_ADMIN, + TOOL_USER_GET ], - "the seven tools, name-sorted" + "the twelve tools, name-sorted" ); } @@ -219,6 +225,11 @@ async fn initialize_publishes_the_prerequisites() { TOOL_RELAY_STATUS, TOOL_DELETE_EVENT, TOOL_REPORTS_ACTION, + TOOL_REPORTS_LIST, + TOOL_USER_ADMIN, + TOOL_USER_GET, + TOOL_INVOICES_LIST, + TOOL_INVOICES_GET, ] { assert!( instructions.contains(needle), diff --git a/crates/nostreamd/tests/mcp_stdio.rs b/crates/nostreamd/tests/mcp_stdio.rs index f9e6db29..514a0eac 100644 --- a/crates/nostreamd/tests/mcp_stdio.rs +++ b/crates/nostreamd/tests/mcp_stdio.rs @@ -12,6 +12,7 @@ //! | `the_process_exits_zero_on_stdin_eof` | closing stdin ends the process with `0` | //! | `the_store_backed_tools_report_the_unwired_store` | `list_events` answers the store's own `NotImplemented` message, not an empty list | //! | `the_write_tools_report_the_unwired_store` | both write tools reach the unwired store and answer its message, rather than a protocol error | +//! | `the_store_family_tools_report_the_unwired_store` | the five store-family tools reach the unwired store and answer its message | //! | `the_help_text_names_the_credential` | `--help` names the two flags, the document's shape and scopes, the file rule and the retired variable | //! | `a_console_session_token_in_the_environment_refuses_to_start` | the retired variable is named rather than ignored, even when it carries a token the console would accept | //! | `a_group_readable_token_file_refuses_to_start` | mode 0644 fails the start, and the message names both modes | @@ -489,7 +490,7 @@ async fn the_mode_binds_no_socket() { assert_eq!( listed["result"]["tools"].as_array().map(Vec::len), - Some(7), + Some(12), "{listed}" ); assert!(outcome.status.success(), "{}", outcome.stderr); @@ -555,6 +556,43 @@ async fn the_write_tools_report_the_unwired_store() { assert!(outcome.status.success(), "{}", outcome.stderr); } +/// The five store-family tools exist in the real binary and reach the daemon's unwired bundle: +/// their answer is the store's own message, not the router's `tool not found` that was true +/// before this slice. +#[tokio::test] +async fn the_store_family_tools_report_the_unwired_store() { + let prepared = Prepared::new(); + let mut daemon = Daemon::start(&prepared, &[]); + daemon.initialize().await; + let pubkey = "ab".repeat(32); + let admitted = daemon + .call("user_admin", json!({ "pubkey": pubkey, "action": "admit" })) + .await; + let read = daemon.call("user_get", json!({ "pubkey": pubkey })).await; + let listed = daemon.call("invoices_list", json!({})).await; + let invoice = daemon.call("invoices_get", json!({ "id": "inv-1" })).await; + let queue = daemon.call("reports_list", json!({})).await; + let outcome = daemon.finish().await; + + for (tool, response) in [ + ("user_admin", &admitted), + ("user_get", &read), + ("invoices_list", &listed), + ("invoices_get", &invoice), + ("reports_list", &queue), + ] { + assert_eq!(response["result"]["isError"], true, "{tool}: {response}"); + let text = response["result"]["content"][0]["text"] + .as_str() + .unwrap_or_default(); + assert!( + text.contains("not implemented in Phase 1 (job 005): storage::backend::wiring"), + "{tool}: {text}" + ); + } + assert!(outcome.status.success(), "{}", outcome.stderr); +} + #[tokio::test] async fn the_help_text_names_the_credential() { let output = tokio::process::Command::new(env!("CARGO_BIN_EXE_nostreamd")) @@ -752,7 +790,7 @@ async fn an_inherited_descriptor_authenticates() { assert_eq!( listed["result"]["tools"].as_array().map(Vec::len), - Some(7), + Some(12), "{listed}" ); assert_eq!(read["result"]["isError"], false, "{read}"); From 5ffba517fda5ddb196ddf2f501e40cbbd2a66bc3 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 21 Nov 2026 18:13:45 -0500 Subject: [PATCH 2/8] docs(adr): record the fourth slice, and extend the audit vocabulary ADR 0018 records D1-D7 with a cost each: the two rows the scope forces, the read path that never hydrates, the row-not-a-count payload, the queue and the price of a full listing, pending-only invoices with a miss as a result, one page bound, and the absent-name move with the five audit names. ADR 0014's D18 table gains the five names and its two sentences say twelve. CONFIGURATION.md's two tool lists and nostreamd --help name the twelve tools and the eight/four split. The changeset is empty: Rust only, no published package moves. --- .changeset/mcp-users-invoices.md | 23 +++ CONFIGURATION.md | 7 +- crates/nostreamd/src/main.rs | 5 +- .../decisions/0014-admin-http-surface.md | 13 +- .../0018-users-invoices-and-report-reads.md | 159 ++++++++++++++++++ 5 files changed, 199 insertions(+), 8 deletions(-) create mode 100644 .changeset/mcp-users-invoices.md create mode 100644 docs/rewrite/decisions/0018-users-invoices-and-report-reads.md diff --git a/.changeset/mcp-users-invoices.md b/.changeset/mcp-users-invoices.md new file mode 100644 index 00000000..d2a3fbc5 --- /dev/null +++ b/.changeset/mcp-users-invoices.md @@ -0,0 +1,23 @@ +--- +--- + +feat(mcp): five store-family tools — `user_admin`, `user_get`, the invoice reads and `reports_list` + +`user_admin` carries the four decisions an operator makes about one pubkey — `admit`, `revoke`, +`vanish` and `unvanish` — as one closed action enum, and `user_get` reads the same row and its +balance under a document that grants nothing: the scope is a property of the `TOOLS` row, so one +tool would have made a balance read cost a `write` document or an admission reachable with a +read-only one. The read path is `find_by_pubkey` plus `get_balance_by_pubkey`, never +`is_vanished`, which hydrates a live kind-62 and stores a row — so `user_get` never writes. + +`invoices_list` is the store's pending walk, oldest first, paged by `offset` and `limit`; +`invoices_get` takes the invoice's own opaque id verbatim and answers a miss as +`{"invoice": null}`, as `get_event` answers an unknown event id. `reports_list` is the review +queue over `find_actionable`: the reports still actionable, newest first, with no offset — a full +listing would be one new trait method on six implementors and is left for a slice that takes it +deliberately. + +The two list tools share the door's one page bound (500, the default and the ceiling), and the +events' page size now goes through the same function. The audit vocabulary gains five `mcp.*` +names, each carrying `{"tool": …}` and nothing else. `docs/rewrite/decisions/0018-users-invoices-and-report-reads.md` +records the seven decisions. Rust only: no published package changes. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 4849fcf6..491d2e7f 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -75,7 +75,8 @@ The following environment variables can be set: ## The admin MCP mode (`--mcp-stdio`) `nostreamd --mcp-stdio` serves the admin MCP server (`settings_get`, `settings_set`, -`list_events`, `get_event`, `delete_event`, `reports_action`) on stdin/stdout and exits when stdin +`list_events`, `get_event`, `delete_event`, `reports_action`, `reports_list`, `user_admin`, +`user_get`, `invoices_list` and `invoices_get`) 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. @@ -96,8 +97,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`. | -| `{ "scopes": ["write"] }` | The read tools, and the three 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) and `reports_action` (sets the relay-wide NIP-56 filter for the target an actionable report names). | +| `{}` 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). | `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 diff --git a/crates/nostreamd/src/main.rs b/crates/nostreamd/src/main.rs index 6d0ec7e6..0aab891b 100644 --- a/crates/nostreamd/src/main.rs +++ b/crates/nostreamd/src/main.rs @@ -50,8 +50,9 @@ struct Cli { /// start — and at most 4 KiB. /// /// The document is `{"scopes": ["write"]}`; a document with no scopes grants the read tools - /// (`settings_get`, `list_events`, `get_event`, `relay_status`), and the "write" scope adds - /// `settings_set`, `delete_event` and `reports_action`. + /// (`settings_get`, `list_events`, `get_event`, `relay_status`, `user_get`, `invoices_list`, + /// `invoices_get` and `reports_list`), and the "write" scope adds `settings_set`, + /// `delete_event`, `reports_action` and `user_admin`. /// An unknown scope refuses to start, naming it. The mode also needs `admin.enabled: true` in /// the settings. /// diff --git a/docs/rewrite/decisions/0014-admin-http-surface.md b/docs/rewrite/decisions/0014-admin-http-surface.md index 911a0230..a09dece4 100644 --- a/docs/rewrite/decisions/0014-admin-http-surface.md +++ b/docs/rewrite/decisions/0014-admin-http-surface.md @@ -281,8 +281,9 @@ backend, whose query is a real await, that the shape is for. The MCP server writes its calls to the same `/admin-audit.jsonl` (D9), one line per executed call, and it extends the recorded action vocabulary by **one name per registered tool** -rather than reusing one. Seven names have landed: four with the first slice, `relay_status` with -the second, and `delete_event` and `reports_action` with the third; each later slice adds its own: +rather than reusing one. **Twelve names have landed:** four with the first slice, `relay_status` +with the second, `delete_event` and `reports_action` with the third, and `user_admin`, `user_get`, +`invoices_list`, `invoices_get` and `reports_list` with the fourth; each later slice adds its own: | action | written by | |---|---| @@ -293,6 +294,11 @@ the second, and `delete_event` and `reports_action` with the third; each later s | `mcp.relay_status` | a dispatched `relay_status` (ADR 0016) | | `mcp.delete_event` | a dispatched `delete_event` (ADR 0017) | | `mcp.reports_action` | a dispatched `reports_action` (ADR 0017) | +| `mcp.user_admin` | a dispatched `user_admin` (ADR 0018) | +| `mcp.user_get` | a dispatched `user_get` (ADR 0018) | +| `mcp.invoices_list` | a dispatched `invoices_list` (ADR 0018) | +| `mcp.invoices_get` | a dispatched `invoices_get` (ADR 0018) | +| `mcp.reports_list` | a dispatched `reports_list` (ADR 0018) | **These extend the capture's nine names; they do not replace them.** The capture's vocabulary is a closed nine-name union (`src/@types/admin-audit.ts:1-10`), and the rewrite's writer takes @@ -310,7 +316,8 @@ costs the column its meaning. **What each line carries.** `detail` holds `{"tool": ""}`, plus `{"paths": [...]}` for `settings_set` (the paths requested, never a value); `delete_event` and `reports_action` carry -`{"tool": …}` and nothing else, so neither an id nor an action enters the file, and +`{"tool": …}` and nothing else, and the five tools of the fourth slice carry `{"tool": …}` and +nothing else either, so neither an id nor an action enters the file, and `remoteAddress` is omitted because a stdio caller has no address (`state.rs:509-525`). The line is appended at dispatch, before the tool's work, so the file's order is the dispatch order: `mcp.settings_set` precedes the `settings.updated` line the shared write path then appends, and a call the credential refuses diff --git a/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md b/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md new file mode 100644 index 00000000..b9a44225 --- /dev/null +++ b/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md @@ -0,0 +1,159 @@ +# ADR 0018: The user, invoice and report reads, and the split `user_admin` / `user_get` + +- **Status:** accepted (job 037, Phase 2) +- **Deciders:** the rewrite team, on the operator's steer recorded in #1183 and this job's spec +- **Date:** 2026-11-21 + +## Context + +Slice 4 of #1183 adds five MCP tools — `user_admin`, `user_get`, `invoices_list`, `invoices_get` +and `reports_list` — over repository seams that all exist. Nothing in +`crates/nostream-storage` changes: every method these tools call is already on a trait both +backends implement. + +Four facts at the base commit shaped the slice. + +**The scope is a property of the table row, not of the handler.** `Requires` is one field of the +door's `TOOLS` row, asked once per call at dispatch, and `Requires::Read` is the grant every +accepted document carries while `Requires::Write` needs the document's `write` scope. A single +`user_admin` tool covering both a balance read and an admission could only carry one of the two, +and a second check inside the handler would write no `mcp.denied` line, because the denial +record is written only at dispatch. + +**`is_vanished` writes.** The trait's doc says the hydration is deliberate: on a pubkey with no +row it reads a live kind-62 and **stores** the answer, so a later call short-circuits. The +relay's gate is a write path with a budget for that; a door read is not. + +**`find_pending_invoices` is the only list read on the invoice store**, and both backends +implement it pending-only: Postgres filters `status = 'pending'` and orders by `created_at`; +LMDB walks `invoices_pending`, an index holding only the pending rows. `confirm_invoice` sets +`amount_paid` and `confirmed_at` and leaves `status` alone, so a confirmed invoice stays in that +index until a status update moves it. + +**`ReportRepository` has one listing, `find_actionable(limit)`**, and it is the repository's own +answer to the console's question: a report an operator allowed leaves the queue, and the queue is +newest first. There is no unfiltered listing, and on LMDB there is no ordered key to walk for +one. + +## Decisions + +### D1 — `user_admin` and `user_get` are two rows, because the scope is a row property + +`user_admin` is one write tool whose arguments carry a pubkey and a closed `action` enum over +`admit`, `revoke`, `vanish` and `unvanish` — the shape `reports_action` established for a closed +set, with a hand-written `JsonSchema` stating the four literals as the schema's `enum`. +`user_get` is the read row: two reads, `find_by_pubkey` and `get_balance_by_pubkey`, in one +payload. + +The name is `user_get` because it is the same noun as `user_admin`, so the two rows sort next to +each other in `tools/list`; because the door already spells a single-document read +`_get`; and because `status` is the door's word for liveness, not for a row. + +Four write tools were rejected: four schemas, four handlers and four audit names for one +operator's four decisions about one pubkey. + +**Cost:** the audit file cannot tell an admission from a revocation. Each dispatch line carries +`{"tool": …}` and nothing else — ADR 0017's `detail` rule forbids putting an argument value in it +— so an operator correlates the two by time. Paid for: one schema, one handler and one name for +four writes, and a read that is reachable with a document that grants nothing. + +### D2 — The read path is `find_by_pubkey` plus `get_balance_by_pubkey`, never `is_vanished` + +Both tools read the same pair, through one helper, so they cannot disagree about the row's shape +or the balance's source. A pair is needed rather than either read alone: `find_by_pubkey` answers +the balance as a field of its row but answers nothing for a pubkey with no row, and +`get_balance_by_pubkey` answers `0` both for a pubkey with no row and for a row nothing has +credited. Only the pair distinguishes the two, and `user_get`'s description says so. + +`is_vanished` is called by neither tool. It hydrates a live kind-62 into a stored row, and +`user_get` is reachable with a document that carries no scope at all — so calling it would make +a read write, leaving a row behind for every pubkey anyone inspects. The stored flag is what the +payload reports. + +**Cost:** a pubkey whose only vanish evidence is a kind-62 the relay's cache never saw reads as +absent, and an operator must run `user_admin vanish` to make it visible. Paid for: no write under +a read-only grant, and one meaning for the flag. + +### D3 — `user_admin`'s payload is `action`, the row after the call and the balance — never a count + +`admit_user` returns `()`, `set_vanished` returns an upsert count that is always one, and +`revoke_admission` returns a match count. One `changed` field would mean three different things. +The row as it stands after the call is the same answer for all four actions: `user` null when the +pubkey has no row, `balance` `0` for that same pubkey. + +**Cost:** a caller cannot tell that `admit` created the row rather than updating it, and a revoke +of an admitted row and a revoke of an already-false row answer an identical payload — both end +`is_admitted: false`, and the store counts one for each. Paid for: one payload shape for four +actions, and a store read-back instead of a number whose meaning depends on which arm ran. + +### D4 — `reports_list` is the actionable review queue, and a full listing is priced rather than built + +The tool takes a `limit` and no other argument, and answers `find_actionable(limit)`'s rows in the +store's own order. Its name, description and payload say "the review queue": a report an operator +allowed has left the queue, and the queue has no offset, so there is nothing to page. + +A full listing — every report, a filter by `actionable` or `report_type`, an offset — is one new +trait method on six implementors, a parity arm, and an unordered LMDB scan that materialises and +sorts the whole table. It was measured at `find_stored`'s price, 15 files and +196/−19, and it is +out of scope here, named with its price so a later slice takes it deliberately. + +**Cost:** a report an operator allowed is not listable through MCP at all, and the queue cannot be +paged past 500. Paid for: zero storage code in this slice. + +### D5 — `invoices_list` is pending-only, and `invoices_get` answers a miss as a result + +`invoices_list` takes `offset` and `limit`, passes them to `find_pending_invoices`, and answers +`{"invoices": [...]}` with no re-sort and no `truncated` marker: a caller pages with `offset`, and +the store's own `(offset, limit)` is the whole protocol. A marker no repository state can decide +would be a guess. + +`invoices_get` takes the id verbatim — no hex prefix, no length rule, no normalisation — because +`invoice.id` is opaque text by migration, and an id that happens to be 64 hex characters is a +valid id. A miss answers `{"invoice": null}` with `isError: false`, as `get_event` answers an +unknown event id. + +**Cost:** an operator cannot list a completed or expired invoice — only read one by id — and the +pending list keeps a confirmed invoice until its status moves, which the two descriptions state so +a caller is not misled. Paid for: no new invoice read on either backend. + +### D6 — One page bound for the two new list tools + +`MAX_ROWS_PER_PAGE` is both the default and the ceiling, held by one `page_bound` that reproduces +the events' existing rule and refusal text byte for byte; the events' page size becomes a call to +it and converts the answer at its own site. A second 500 would be the same number in two places, +and the payments worker's `PENDING_INVOICE_PAGE_SIZE` is that worker's page rather than a bound +the door states. + +**Cost:** `reports_list` has no offset, so a queue longer than 500 is unreadable past the first +page, and `invoices_list`'s offset walks a live index, so a row inserted between two pages can be +skipped. Paid for: one number and one message for the three tools that page. + +### D7 — The absent-name example moves to `maintenance_run`, and five audit names land + +ADR 0017 left `user_admin` as the standing example of a tool that does not exist, in three test +sites and one crate-doc sentence. `user_admin` exists now, so the example moves to +`maintenance_run`, slice 5's name, which no constant, row or handler carries — and the parity of +the example is a grep, so it is checked rather than assumed. + +The audit vocabulary gains `mcp.user_admin`, `mcp.user_get`, `mcp.invoices_list`, +`mcp.invoices_get` and `mcp.reports_list`, each composed by `audit_action` from the tool's own +constant. Every one carries `{"tool": …}` and nothing else: no pubkey, no action, no invoice id, +and no `remoteAddress` for a stdio caller. ADR 0014's table is extended with all five. + +**Cost:** the example must move again when slice 5 lands, and the criterion for it is a grep +rather than a compile error. Paid for: three sites that keep testing what their sentences claim, +and a denial record that names the tool whose scope was missing. + +## Consequences + +The surface is twelve tools, eight of them reads. `tools_list.json` is regenerated from the live +server and compared, never rewritten by a test. The four lists that count the tools — the crate +docs, `--help`, `CONFIGURATION.md` and the test headers — say twelve, eight and four. + +Nothing under `crates/nostream-storage` moves: no trait method, no backend arm, no parity step. +A slice that finds it needs one has mis-cut the work, and that is an escalation rather than a +quiet addition. + +`set_vanished(false)` has its first caller in the tree. Because the relay's gate reads the stored +flag, clearing it lets a pubkey publish again; the events a kind-62 request deleted are not +restored, and the tool's description says so. From 20f977878fa35e75f73f59aec61f837aa55c2d6a Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 21 Nov 2026 18:42:32 -0500 Subject: [PATCH 3/8] fix(mcp): drop the duplicated page-bound sentence R14 asks MAX_ROWS_PER_PAGE's doc for one sentence; the first copy was spliced into the paragraph's previous line and said the same thing twice. Doc prose is what fmt and clippy cannot see, so the round-1 gate's read found it. --- crates/nostream-mcp/src/server.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index ab94265c..bf03c447 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -98,8 +98,7 @@ pub const MAX_FILTER_TERMS: usize = 64; /// It is not `nostream_storage::MAX_PAGE_ROWS`, the relay's 5,000-row clamp: this is the page a /// read materialises, which is the number a backend opens with. It is also the door's page /// bound, and for the invoice and report reads it is only a bound, because neither store's read -/// takes a direction from `limit`., and for the invoice and report reads it is only a bound, because -/// neither store's read takes a direction from `limit`. +/// takes a direction from `limit`. pub const MAX_ROWS_PER_PAGE: u64 = nostream_storage::DEFAULT_PAGE_ROWS; /// The refusal for a credential whose document is absent, unreadable or no longer a document this From 04ccac78e0b7795c4c4269976cb6f4329258d9ab Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 21 Nov 2026 19:01:25 -0500 Subject: [PATCH 4/8] docs: name relay_status in the admin MCP mode's tool list The --mcp-stdio sentence was rewritten for this slice and still named eleven of the twelve tools; relay_status was missing at base too, which is not a reason to carry the omission through a rewrite. --- CONFIGURATION.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 491d2e7f..2a756446 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -75,8 +75,8 @@ The following environment variables can be set: ## The admin MCP mode (`--mcp-stdio`) `nostreamd --mcp-stdio` serves the admin MCP server (`settings_get`, `settings_set`, -`list_events`, `get_event`, `delete_event`, `reports_action`, `reports_list`, `user_admin`, -`user_get`, `invoices_list` and `invoices_get`) on stdin/stdout and exits when stdin +`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 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. From ef6761e17f12d6d8148248a2425f5886f31bb241 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 21 Nov 2026 19:25:10 -0500 Subject: [PATCH 5/8] fix(mcp): read the user row once and publish its actions from one table MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The user payload called get_balance_by_pubkey after find_by_pubkey, which loads and decodes the same row a second time on the read path — and on a read reachable with a scopeless document. The row carries its balance, so the payload derives it: user is null versus Some(row) is what distinguishes no row from no funds, and one read keeps one snapshot in one answer. D2 states that, and D6's cost names the cause that actually shifts the offset walk: a pending row leaving the index when its status moves off Pending, not an insertion after the cursor. The four action names were spelled twice — as_str and the schema literal — and only two of the four payloads were pinned. The enum now comes from as_str over one ALL table, and the vanish case asserts each payload's action against the members the schema publishes. --- crates/nostream-mcp/src/server.rs | 34 ++++++++++----- crates/nostream-mcp/tests/store_families.rs | 43 ++++++++++++++++++- .../0018-users-invoices-and-report-reads.md | 26 ++++++----- 3 files changed, 80 insertions(+), 23 deletions(-) diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index bf03c447..0fe6df92 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -432,7 +432,10 @@ pub enum UserAction { } impl UserAction { - /// The action's own name: the schema's `enum` member and the payload's `action` (R4). + /// The four actions, in the order the schema publishes them (R4). + const ALL: [Self; 4] = [Self::Admit, Self::Revoke, Self::Vanish, Self::Unvanish]; + + /// The action's own name: the payload's `action` (R4). fn as_str(self) -> &'static str { match self { Self::Admit => "admit", @@ -448,10 +451,19 @@ impl JsonSchema for UserAction { "UserAction".into() } - /// The four literals as the schema's `enum`, for the reason `ReportAction`'s schema states: - /// the derive would spell a described unit enum as a `oneOf` of `const` variants. + /// The four names as the schema's `enum`, read from [`UserAction::as_str`] so a published + /// member and the payload's `action` are one spelling rather than two hand-kept copies — for + /// the reason `ReportAction`'s schema states: the derive would spell a described unit enum as + /// a `oneOf` of `const` variants. fn json_schema(_: &mut SchemaGenerator) -> Schema { - json_schema!({ "type": "string", "enum": ["admit", "revoke", "vanish", "unvanish"] }) + let members = json!( + UserAction::ALL + .iter() + .copied() + .map(UserAction::as_str) + .collect::>() + ); + json_schema!({ "type": "string", "enum": members }) } fn inline_schema() -> bool { @@ -889,19 +901,19 @@ sets `amount_paid` and `confirmed_at`, and only a status update moves the status .unwrap_or(DateTime::UNIX_EPOCH) } - /// The read half's payload: the two reads the pair needs, in one place (R8, R9). + /// The read half's payload: the row and the balance it carries, in one place (R8, R9). async fn read_user(&self, arguments: &UserGetArgs) -> Result { let pubkey = pubkey_argument(&arguments.pubkey)?; self.user_row(&pubkey).await } - /// The pair both user tools answer: the row as the store holds it, and the balance on its - /// own — `balance` is `0` for a pubkey with no row and for a row nothing has credited, so - /// `user` is the field that says which. + /// The payload both user tools answer: the row as the store holds it, and the balance that + /// row carries — `balance` is `0` for a pubkey with no row and for a row nothing has + /// credited, so `user` is the field that says which. One read: the row already holds the + /// balance, and a second read would put two snapshots in one answer. async fn user_row(&self, pubkey: &Pubkey) -> Result { - let users = &self.state.stores().users; - let user = users.find_by_pubkey(pubkey).await?; - let balance = users.get_balance_by_pubkey(pubkey).await?; + let user = self.state.stores().users.find_by_pubkey(pubkey).await?; + let balance = user.as_ref().map_or(0, |row| row.balance); Ok(json!({ "user": user, "balance": balance })) } diff --git a/crates/nostream-mcp/tests/store_families.rs b/crates/nostream-mcp/tests/store_families.rs index f3bed9c8..25257eda 100644 --- a/crates/nostream-mcp/tests/store_families.rs +++ b/crates/nostream-mcp/tests/store_families.rs @@ -10,7 +10,7 @@ //! | `user_admin_admits_an_uppercase_pubkey_and_the_store_says_so` | the criterion lowercases, and the store — not the payload — carries the admission | //! | `admitting_a_row_keeps_its_balance` | `admit` writes the row that is there: the invoice's credit survives | //! | `user_admin_revokes_and_an_absent_pubkey_writes_no_row` | `revoke` clears the flag and creates nothing for a pubkey with no row | -//! | `user_admin_vanishes_and_unvanishes_the_stored_flag` | the minimal row, and the tree's only clearing of the flag | +//! | `user_admin_vanishes_and_unvanishes_the_stored_flag` | the minimal row, the tree's only clearing of the flag, and the payload's `action` for all four names the schema publishes | //! | `vanishing_writes_the_flag_and_deletes_no_event` | the tool is the row write, not the relay's strategy: no event is deleted | //! | `an_unknown_user_action_never_reaches_the_handler` | the closed set is the arguments type, so nothing is written | //! | `a_short_pubkey_is_refused_after_its_dispatch_line` | a prefix is refused by the length check before any store call, and its dispatch line exists | @@ -332,6 +332,7 @@ async fn user_admin_vanishes_and_unvanishes_the_stored_flag() { .await; assert_eq!(vanished.is_error, Some(false), "{}", text(&vanished)); let answer = payload(&vanished); + assert_eq!(answer["action"], "vanish", "{answer}"); assert_eq!(answer["user"]["is_vanished"], true, "{answer}"); assert_eq!( answer["user"]["is_admitted"], false, @@ -351,13 +352,51 @@ async fn user_admin_vanishes_and_unvanishes_the_stored_flag() { ) .await; assert_eq!(unvanished.is_error, Some(false), "{}", text(&unvanished)); - assert_eq!(payload(&unvanished)["user"]["is_vanished"], false); + let answer = payload(&unvanished); + assert_eq!(answer["action"], "unvanish", "{answer}"); + assert_eq!(answer["user"]["is_vanished"], false, "{answer}"); assert!( stored_user(&fixture, &key()) .await .is_some_and(|row| !row.is_vanished), "the flag is cleared in the store, which is what the relay's gate reads" ); + + // The four names the schema publishes, and the payload's own `action` for each (R4): the + // enum is read from the same spelling the payload is, so a mistyped arm cannot answer a + // value outside the contract a validating client checked the call against. + let tools = client.tools().await; + let tool = tools + .iter() + .find(|tool| tool.name == TOOL_USER_ADMIN) + .expect("user_admin is listed"); + let schema = Value::Object((*tool.input_schema).clone()); + let advertised: Vec = schema["properties"]["action"]["enum"] + .as_array() + .expect("the action enum is published") + .iter() + .map(|name| name.as_str().expect("a member is a name").to_owned()) + .collect(); + assert_eq!( + advertised, + ["admit", "revoke", "vanish", "unvanish"], + "{schema}" + ); + for action in &advertised { + let answered = client + .call( + TOOL_USER_ADMIN, + json!({ "pubkey": key_hex(), "action": action }), + ) + .await; + assert_eq!(answered.is_error, Some(false), "{}", text(&answered)); + let answered = payload(&answered); + assert_eq!( + answered["action"], + json!(action), + "the payload's action is the schema's member: {answered}" + ); + } } #[tokio::test] diff --git a/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md b/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md index b9a44225..2083f9b7 100644 --- a/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md +++ b/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md @@ -42,8 +42,8 @@ one. `user_admin` is one write tool whose arguments carry a pubkey and a closed `action` enum over `admit`, `revoke`, `vanish` and `unvanish` — the shape `reports_action` established for a closed set, with a hand-written `JsonSchema` stating the four literals as the schema's `enum`. -`user_get` is the read row: two reads, `find_by_pubkey` and `get_balance_by_pubkey`, in one -payload. +`user_get` is the read row: the row `find_by_pubkey` answers, and the balance that row carries, +in one payload. The name is `user_get` because it is the same noun as `user_admin`, so the two rows sort next to each other in `tools/list`; because the door already spells a single-document read @@ -57,13 +57,16 @@ operator's four decisions about one pubkey. — so an operator correlates the two by time. Paid for: one schema, one handler and one name for four writes, and a read that is reachable with a document that grants nothing. -### D2 — The read path is `find_by_pubkey` plus `get_balance_by_pubkey`, never `is_vanished` +### D2 — The read path is `find_by_pubkey`, never `is_vanished` -Both tools read the same pair, through one helper, so they cannot disagree about the row's shape -or the balance's source. A pair is needed rather than either read alone: `find_by_pubkey` answers -the balance as a field of its row but answers nothing for a pubkey with no row, and -`get_balance_by_pubkey` answers `0` both for a pubkey with no row and for a row nothing has -credited. Only the pair distinguishes the two, and `user_get`'s description says so. +Both tools read the same row, through one helper, so they cannot disagree about the row's shape +or the balance's source. One read answers both fields: `find_by_pubkey` answers `None` for a +pubkey with no row and `Some(row)` — carrying `row.balance` — for a row, so `balance` is `0` for +a pubkey with no row and the row's own number otherwise. `get_balance_by_pubkey` would answer +the same two values from a second load of the row just decoded — a second query on Postgres, a +second decode on LMDB — and its reading could land after a credit the first did not see, which +is two snapshots in one answer. `None` versus `Some(row)` is what distinguishes no row from no +funds, and `user_get`'s description says so. `is_vanished` is called by neither tool. It hydrates a live kind-62 into a stored row, and `user_get` is reachable with a document that carries no scope at all — so calling it would make @@ -125,8 +128,11 @@ and the payments worker's `PENDING_INVOICE_PAGE_SIZE` is that worker's page rath the door states. **Cost:** `reports_list` has no offset, so a queue longer than 500 is unreadable past the first -page, and `invoices_list`'s offset walks a live index, so a row inserted between two pages can be -skipped. Paid for: one number and one message for the three tools that page. +page, and `invoices_list`'s offset walks a live index, so a pending row that leaves the queue +between two pages — its status moving off `Pending`, which the payments worker's expiry does — +shifts the walk, and a row can be skipped or answered twice. Insertion cannot: the index is +`created_at ‖ id` ascending, so a new invoice lands after the cursor. Paid for: one number and +one message for the three tools that page. ### D7 — The absent-name example moves to `maintenance_run`, and five audit names land From a1de51c5913b03fb852d28ad6c98c10c0ac9d19d Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 21 Nov 2026 19:42:25 -0500 Subject: [PATCH 6/8] test(mcp): refuse the balance read to prove the user payload reads once MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The one-read invariant had no case: a store that answers get_balance_by_pubkey cannot say whether the call happened. A forwarding UserRepository refuses it instead, seeded through a users factory beside the event and report ones, and user_get on an absent pubkey answers {user: null, balance: 0} only if nothing calls the removed read — with the second read restored the case fails. D2 gains the edge the pair was not outcome-identical on: a NULL balance coalesces to 0 in the row read and would have failed the removed try_get. --- crates/nostream-mcp/tests/common/mod.rs | 88 ++++++++++++++++++- crates/nostream-mcp/tests/store_families.rs | 28 ++++++ .../0018-users-invoices-and-report-reads.md | 5 ++ 3 files changed, 119 insertions(+), 2 deletions(-) diff --git a/crates/nostream-mcp/tests/common/mod.rs b/crates/nostream-mcp/tests/common/mod.rs index ae21b296..d40d0f70 100644 --- a/crates/nostream-mcp/tests/common/mod.rs +++ b/crates/nostream-mcp/tests/common/mod.rs @@ -111,6 +111,9 @@ pub struct Fixture { pub stores: Stores, /// The report repository a case supplies in place of the backend's own. pub reports: Option, + /// The user repository a case supplies in place of the backend's own — for a case whose + /// subject is which reads the door makes, where the backend would answer them all. + pub users: Option, } impl Default for Fixture { @@ -122,6 +125,7 @@ impl Default for Fixture { now_ms: NOW_MS, stores: Stores::Seeded, reports: None, + users: None, } } } @@ -147,6 +151,14 @@ pub type ReportRepositoryFactory = Arc< + Sync, >; +/// Builds the user repository a case wants over the harness's own backend — for a case whose +/// subject is which reads the door makes, which a store that answers them all cannot show. +pub type UserRepositoryFactory = Arc< + dyn Fn(Arc) -> Arc + + Send + + Sync, +>; + /// One composed server over a temporary config dir, and what it was composed with. pub struct TestMcp { pub state: Arc, @@ -208,8 +220,13 @@ impl TestMcp { || Arc::clone(&backend) as Arc, |wrap| wrap(Arc::clone(&backend)), ), - users: Arc::clone(&backend) - as Arc, + users: fixture.users.as_ref().map_or_else( + || { + Arc::clone(&backend) + as Arc + }, + |wrap| wrap(Arc::clone(&backend)), + ), invoices: Arc::clone(&backend) as Arc, nip05: Arc::clone(&backend) @@ -803,3 +820,70 @@ impl EventRepository for ZeroCountDeleter { self.inner.delete_all_events() } } + +/// The real users, with the balance read refused. +/// +/// The user tools answer the row and the balance that row carries, so nothing on their path may +/// call `get_balance_by_pubkey`: the backend would answer it, and a store that answers cannot say +/// whether the call happened. This one refuses it, so a case can tell. Every other method is the +/// backend's own. +pub struct NoBalanceRead { + inner: Arc, +} + +impl NoBalanceRead { + /// The backend, with its balance read refused. + pub fn new(inner: Arc) -> Self { + Self { inner } + } +} + +impl nostream_storage::repositories::UserRepository for NoBalanceRead { + fn find_by_pubkey<'a>( + &'a self, + pubkey: &'a Pubkey, + ) -> StorageFuture<'a, Option> { + nostream_storage::repositories::UserRepository::find_by_pubkey(&*self.inner, pubkey) + } + + fn upsert<'a>( + &'a self, + user: &'a nostream_storage::repositories::UserPatch, + ) -> StorageFuture<'a, u64> { + nostream_storage::repositories::UserRepository::upsert(&*self.inner, user) + } + + /// Refused: the balance is the row's own field, and a case that reaches this read has found + /// a caller making the second load the user tools were written not to make. + fn get_balance_by_pubkey<'a>(&'a self, _pubkey: &'a Pubkey) -> StorageFuture<'a, i64> { + Box::pin(async { + Err(StorageError::InvalidArgument { + message: "the user tools derive the balance from the row and must not read it twice", + }) + }) + } + + fn is_vanished<'a>(&'a self, pubkey: &'a Pubkey) -> StorageFuture<'a, bool> { + nostream_storage::repositories::UserRepository::is_vanished(&*self.inner, pubkey) + } + + fn set_vanished<'a>(&'a self, pubkey: &'a Pubkey, vanished: bool) -> StorageFuture<'a, u64> { + nostream_storage::repositories::UserRepository::set_vanished(&*self.inner, pubkey, vanished) + } + + fn admit_user<'a>( + &'a self, + pubkey: &'a Pubkey, + admitted_at: chrono::DateTime, + ) -> StorageFuture<'a, ()> { + nostream_storage::repositories::UserRepository::admit_user( + &*self.inner, + pubkey, + admitted_at, + ) + } + + fn revoke_admission<'a>(&'a self, pubkey: &'a Pubkey) -> StorageFuture<'a, u64> { + nostream_storage::repositories::UserRepository::revoke_admission(&*self.inner, pubkey) + } +} diff --git a/crates/nostream-mcp/tests/store_families.rs b/crates/nostream-mcp/tests/store_families.rs index 25257eda..cadb3906 100644 --- a/crates/nostream-mcp/tests/store_families.rs +++ b/crates/nostream-mcp/tests/store_families.rs @@ -21,6 +21,7 @@ //! | `a_confirmed_invoice_still_reads_pending` | confirmation sets the paid fields and leaves the status, and the list keeps naming the row | //! | `reports_list_is_the_actionable_queue_newest_first` | the queue is `find_actionable`: newest first, and a report an operator allowed is not in it | //! | `reports_list_refuses_a_page_outside_the_bound` | the queue shares the one page bound | +//! | `user_get_never_calls_the_balance_read` | a users store that refuses `get_balance_by_pubkey` still answers the absent pubkey: the payload's one read is the row | //! //! The store is the harness's LMDB backend, seeded the way the storage tests seed it: the //! repository traits' own writes, so a case reads back through `find_by_pubkey` rather than @@ -838,3 +839,30 @@ async fn reports_list_refuses_a_page_outside_the_bound() { ); } } + +/// The payload's one read, with a store that refuses the removed second: `user_get` on a pubkey +/// with no row answers `user: null` and `balance: 0`, which is only possible when nothing calls +/// `get_balance_by_pubkey`. It proves no second read happens on this path; it cannot prove the +/// two answers would have differed, which with no writer between them they would not (D2). +#[tokio::test] +async fn user_get_never_calls_the_balance_read() { + let fixture = TestMcp::start_with(Fixture { + users: Some(std::sync::Arc::new(|backend| { + std::sync::Arc::new(common::NoBalanceRead::new(backend)) + as std::sync::Arc + })), + ..Fixture::default() + }) + .await; + let client = fixture.client().await; + + let result = client + .call(TOOL_USER_GET, json!({ "pubkey": key_hex() })) + .await; + assert_eq!(result.is_error, Some(false), "{}", text(&result)); + assert_eq!( + payload(&result), + json!({ "user": null, "balance": 0 }), + "the row is absent and the balance is the row's own field, so no second read answers it" + ); +} diff --git a/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md b/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md index 2083f9b7..d3bc66f6 100644 --- a/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md +++ b/docs/rewrite/decisions/0018-users-invoices-and-report-reads.md @@ -68,6 +68,11 @@ second decode on LMDB — and its reading could land after a credit the first di is two snapshots in one answer. `None` versus `Some(row)` is what distinguishes no row from no funds, and `user_get`'s description says so. +The pair was not even outcome-identical where a row's `balance` was NULL, which the migration +allows (`20230107230901_create_users_table.sql:4` carries no `NOT NULL`): the row read coalesces +it to `0` (`postgres/users.rs:24`), and the removed read's bare `try_get` would have failed on +the same row (`postgres/users.rs:130`). + `is_vanished` is called by neither tool. It hydrates a live kind-62 into a stored row, and `user_get` is reachable with a document that carries no scope at all — so calling it would make a read write, leaving a row behind for every pubkey anyone inspects. The stored flag is what the From d57ce93332dc27b2987474c158b03f5ad59b9fa5 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 21 Nov 2026 20:25:57 -0500 Subject: [PATCH 7/8] docs(changeset): the user read is one lookup, not a pair The approver found this sentence was the one false claim in the merged artifact: it named a second read the branch had removed in its own rework. --- .changeset/mcp-users-invoices.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.changeset/mcp-users-invoices.md b/.changeset/mcp-users-invoices.md index d2a3fbc5..c9d3c93e 100644 --- a/.changeset/mcp-users-invoices.md +++ b/.changeset/mcp-users-invoices.md @@ -7,8 +7,9 @@ feat(mcp): five store-family tools — `user_admin`, `user_get`, the invoice rea `vanish` and `unvanish` — as one closed action enum, and `user_get` reads the same row and its balance under a document that grants nothing: the scope is a property of the `TOOLS` row, so one tool would have made a balance read cost a `write` document or an admission reachable with a -read-only one. The read path is `find_by_pubkey` plus `get_balance_by_pubkey`, never -`is_vanished`, which hydrates a live kind-62 and stores a row — so `user_get` never writes. +read-only one. The read path is one `find_by_pubkey` with the balance taken from the row it +answers, never `is_vanished`, which hydrates a live kind-62 and stores a row — so `user_get` never +writes. `invoices_list` is the store's pending walk, oldest first, paged by `offset` and `limit`; `invoices_get` takes the invoice's own opaque id verbatim and answers a miss as From e31c919fa72d2853b2d064cf573aaad148710372 Mon Sep 17 00:00:00 2001 From: chappie-daemon Date: Sat, 21 Nov 2026 20:31:27 -0500 Subject: [PATCH 8/8] docs(mcp): the review queue names the id reports_action takes Its rows carry an integer id and a separate hex event_id, and reports_action takes the latter. Copying the id the list shows is a refusal, which is what the old sentence invited. --- crates/nostream-mcp/src/server.rs | 4 ++-- crates/nostream-mcp/tests/fixtures/tools_list.json | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/nostream-mcp/src/server.rs b/crates/nostream-mcp/src/server.rs index 0fe6df92..d8da2219 100644 --- a/crates/nostream-mcp/src/server.rs +++ b/crates/nostream-mcp/src/server.rs @@ -726,8 +726,8 @@ next refresh, up to 30 s" #[tool( description = "The review queue: the reports still actionable, newest first, at most \ `limit` — 1 to 500, absent 500. This is not every report: a report an operator allowed has left \ -the queue, and the queue has no offset, so there is nothing to page. `reports_action` takes an \ -id this list shows" +the queue, and the queue has no offset, so there is nothing to page. `reports_action` takes the \ +`event_id` this list shows, not the row's own `id`" )] async fn reports_list( &self, diff --git a/crates/nostream-mcp/tests/fixtures/tools_list.json b/crates/nostream-mcp/tests/fixtures/tools_list.json index bc3d817d..b04b8f45 100644 --- a/crates/nostream-mcp/tests/fixtures/tools_list.json +++ b/crates/nostream-mcp/tests/fixtures/tools_list.json @@ -189,7 +189,7 @@ "name": "reports_action" }, { - "description": "The review queue: the reports still actionable, newest first, at most `limit` — 1 to 500, absent 500. This is not every report: a report an operator allowed has left the queue, and the queue has no offset, so there is nothing to page. `reports_action` takes an id this list shows", + "description": "The review queue: the reports still actionable, newest first, at most `limit` — 1 to 500, absent 500. This is not every report: a report an operator allowed has left the queue, and the queue has no offset, so there is nothing to page. `reports_action` takes the `event_id` this list shows, not the row's own `id`", "inputSchema": { "$schema": "https://json-schema.org/draft/2020-12/schema", "additionalProperties": false,