Skip to content

Commit a8cef4a

Browse files
feat(mcp): add delete_event and reports_action over a report setter (#1222)
Slice 3 of #1183. Two write tools on the MCP door, and the store seams they need. ### `delete_event` Soft delete through `delete_by_pubkey_and_ids` — the store's own single-row delete — with four outcomes (`deleted`, `already_deleted`, `not_deleteable` for kind 62, `not_found`) and the event row read back after the call. The outcome is decided by the row **as it stands after** the call, so two concurrent deletes answer `already_deleted` rather than `not_deleteable`. The description states what the store actually does: the event leaves REQ and COUNT, keeps its row, and `get_event` / `list_events` still return it with `deleted_at` set — **unless an actionable report hides it**, in which case it stays hidden until the report is allowed. ### `reports_action` Acts on a report's **own kind-1984 event id** through `find_by_event_id`, setting `Report.actionable` for `hide` and `allow` across every row that event wrote, and answers `changed` — the rows whose value actually moved — with every row of the event sorted by `id` by the handler, not by either backend's order. The LMDB arm removes the three denormalised `reports_actionable_*` index entries in the same write, which is what keeps the NIP-56 filter honest; `allow` cannot re-publish a target that another actionable report still names. ### The seams - `ReportRepository::set_actionable`, implemented by LMDB, Postgres, InMemory, Unavailable and Noop, reached through a new `ServiceStores.reports` field (one field at ten construction sites) rather than a third `AdminState` field. - `EventRepository::find_stored(&EventId)` — one ungated exact-id read, LMDB one `get`, Postgres one `SELECT ... WHERE event_id = $1`. The NIP-56 gate is a read's, and the delete path must see the row a report hides: with the gated read, "hide the report, then delete the event" answered `not_found` and deleted nothing, which made the two tools incoherent with each other. Its doc says who may call it, and an acceptance leg counts `.find_stored(` call sites — two, both the handler's — so a third caller in the method-call form fails the criterion. The leg is a deterrent rather than a proof: a fully qualified `EventRepository::find_stored` spells past it, as the parity cases themselves do, and the record says so. - Both tools sit at `Requires::Write` and audit through the existing path: `mcp.delete_event` / `mcp.reports_action` with `detail {"tool": ...}` and nothing else. ### Record ADR 0017 with D1–D6, each with its cost; ADR 0014's scope column, D7's bundle and D18's table brought current; `CONFIGURATION.md`'s write-scope table now names all three write tools and what they reach; the eleven count sites; the two absent-name inversions moved to `user_admin`; changeset added. ### Verification `cargo fmt --all --check`, both clippy passes, `cargo test --workspace --all-features` (**1 781 passed / 0 failed / 9 ignored**) and a release build, all exit 0. The oracle is `crates/nostream-mcp/tests/write_tools.rs` (18 cases), five new `parity_lmdb` cases plus two `#[ignore]`d Postgres ones that CI runs, an audit case and a real-binary case. Each load-bearing assertion was made to fail once: the four delete outcomes, the hidden-event delete, the post-call read-back, the write gate on both tools, the ordering sort through a reversed repository seam, each of the three index removals, the cross-report rule and the mixed-row count. The reds are in the job record. Known and stated rather than fixed here: the raced double-delete (two deletes of one row in flight) has no deterministic case — the branch is correct by the post-read, and no test claims a proof it cannot make; the Postgres setter arm runs only in CI, where a database exists. Out of scope, deliberately: the hidden-content mirror's 30 s refresh (per-query reads are already gated, so the only consequence is a bounded disclosure the description names), and `reports_list`, which no slice owns. Implements #1183 (slice 3 of 5).
2 parents 443cb98 + 0a01867 commit a8cef4a

35 files changed

Lines changed: 2236 additions & 55 deletions

‎.changeset/mcp-write-tools.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
---
3+
4+
feat(mcp): add the delete_event and reports_action tools
5+
6+
`delete_event` marks one stored event deleted through the store's own soft delete: the event
7+
leaves REQ and COUNT, keeps its row, and the payload says so — `get_event` and `list_events` still
8+
return it with `deleted_at` set unless an actionable report hides it, and the four outcomes are
9+
`deleted`, `already_deleted`, `not_deleteable` (kind 62 is never deleted) and `not_found`. `reports_action` acts on a report's
10+
own kind-1984 event id, flipping `Report.actionable` for `hide` and `allow` on every row that
11+
event wrote.
12+
13+
The report store now reaches the MCP door as a `reports` field on `ServiceStores`, and
14+
`ReportRepository` gains one setter: the LMDB arm moves the three denormalised
15+
`reports_actionable_*` entries with the flag, so the NIP-56 gate and the actionable reads follow a
16+
flip at once, and the Postgres arm is one `UPDATE` with no migration. The hidden-content mirror
17+
needs no work: reads are gated per query and the mirror refreshes wholesale every 30 s.
18+
`reports_list` remains out of scope and unowned.
19+
20+
Rust only; no published package changes. The decisions are in
21+
`docs/rewrite/decisions/0017-report-and-event-writes.md`, and ADR 0014's audit table gains the two
22+
`mcp.*` names.

‎CONFIGURATION.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,8 @@ The following environment variables can be set:
7575
## The admin MCP mode (`--mcp-stdio`)
7676

7777
`nostreamd --mcp-stdio` serves the admin MCP server (`settings_get`, `settings_set`,
78-
`list_events`, `get_event`) on stdin/stdout and exits when stdin closes. It binds no socket,
78+
`list_events`, `get_event`, `delete_event`, `reports_action`) on stdin/stdout and exits when stdin
79+
closes. It binds no socket,
7980
opens no store of its own, and writes its log lines to **stderr** so nothing but JSON-RPC crosses
8081
stdout.
8182

@@ -96,7 +97,7 @@ The document is JSON, and `scopes` is optional:
9697
| Document | What it may call |
9798
|---|---|
9899
| `{}` or `{ "scopes": [] }` | The read tools: `settings_get`, `list_events`, `get_event`. |
99-
| `{ "scopes": ["write"] }` | The read tools and `settings_set`. |
100+
| `{ "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). |
100101

101102
`write` is the only accepted scope, and an unknown name — a typo, or a document from another tool
102103
— refuses to start rather than being narrowed silently. A call the document's scopes deny is

‎crates/nostream-admin/tests/common/mod.rs‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,8 @@ impl TestServer {
182182
Arc::clone(&backend)
183183
as Arc<dyn nostream_storage::repositories::NotificationDeliveryLogRepository>
184184
}),
185+
reports: Arc::clone(&backend)
186+
as Arc<dyn nostream_storage::repositories::ReportRepository>,
185187
});
186188

187189
let client = Arc::new(ReqwestClient::new().unwrap());
@@ -531,6 +533,13 @@ impl EventRepository for SlowEventRepository {
531533
Box::pin(async { Err(not_implemented()) })
532534
}
533535

536+
fn find_stored<'a>(
537+
&'a self,
538+
_id: &'a nostream_core::EventId,
539+
) -> nostream_storage::repositories::StorageFuture<'a, Option<EventRecord>> {
540+
Box::pin(async { Err(not_implemented()) })
541+
}
542+
534543
fn delete_by_pubkey_and_ids<'a>(
535544
&'a self,
536545
_pubkey: &'a nostream_core::Pubkey,

‎crates/nostream-mcp/src/lib.rs‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//! `nostream-mcp` owns the admin MCP server: the tool router, the five tools, the credential
1+
//! `nostream-mcp` owns the admin MCP server: the tool router, the seven tools, the credential
22
//! and its scopes, and the audit sink.
33
//!
44
//! It owns no transport and no socket. `nostreamd --mcp-stdio` serves this server on
@@ -24,8 +24,8 @@
2424
//! `nostream-admin` (used here, not re-implemented);
2525
//! - the settings merge, validation, redaction and the guided catalogue — `nostream-config`;
2626
//! - the event store and the repositories — `nostream-storage`;
27-
//! - every tool family outside this surface: `delete_event`, `user_admin`, `invoices_*`,
28-
//! `reports_*` and `maintenance_*` are later slices of #1183.
27+
//! - every tool family outside this surface: `user_admin`, `invoices_*` and `maintenance_*` are
28+
//! later slices of #1183.
2929
3030
mod credential;
3131
mod error;
@@ -36,8 +36,10 @@ pub use credential::{
3636
};
3737
pub use error::McpError;
3838
pub use server::{
39-
AUDIT_DENIED, AdminMcp, FORBIDDEN, GetEventArgs, ListEventsArgs, MAX_FILTER_TERMS,
40-
MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, Requires, SettingsSetArgs,
41-
TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET,
39+
AUDIT_DENIED, AdminMcp, DeleteEventArgs, FORBIDDEN, GetEventArgs, ListEventsArgs,
40+
MAX_FILTER_TERMS, MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND,
41+
OUTCOME_ALREADY_DELETED, OUTCOME_DELETED, OUTCOME_NOT_DELETEABLE, OUTCOME_NOT_FOUND,
42+
ReportAction, ReportsActionArgs, Requires, SettingsSetArgs, TOOL_DELETE_EVENT, TOOL_GET_EVENT,
43+
TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET,
4244
TOOLS, Tool, UNAUTHORIZED, arguments_parse, audit_action, required_scope,
4345
};

‎crates/nostream-mcp/src/server.rs‎

Lines changed: 187 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
//! The MCP server: the five tools, the credential gate and the audit sink.
1+
//! The MCP server: the seven tools, the credential gate and the audit sink.
22
//!
33
//! Every tool is a thin handler over a seam that already exists — `AdminState` for the settings,
44
//! `EventRepository` for the events — and nothing here knows what an HTTP status is (R3). The
@@ -15,7 +15,7 @@ use nostream_admin::AdminState;
1515
use nostream_admin::controllers::admin_json_body_middleware::settings_patch;
1616
use nostream_admin::controllers::patch_settings::{self, SettingsWrite};
1717
use nostream_admin::utils::status;
18-
use nostream_core::{Filter, Kind};
18+
use nostream_core::{EventId, Filter, Kind};
1919
use nostream_relay::nip11;
2020
use nostream_storage::repositories::{EventRecord, collect_page, collect_records};
2121
use rmcp::handler::server::router::tool::ToolRouter;
@@ -47,7 +47,8 @@ pub const MCP_INSTRUCTIONS: &str = "\
4747
The nostream admin MCP server. Every call is decided by the scoped token document the mode was \
4848
started with — `--admin-token-file <path>` or `--admin-token-fd <n>`, exactly one, its shape \
4949
{\"scopes\": [\"write\"]}: the document's presence authorises `settings_get`, `list_events`, \
50-
`get_event` and `relay_status`, and the \"write\" scope authorises `settings_set` (else the call \
50+
`get_event` and `relay_status`, and the \"write\" scope authorises `settings_set`, \
51+
`delete_event` and `reports_action` (else the call \
5152
is `Forbidden`). \
5253
`admin.enabled` must be true in the settings, or every call answers `Not Found`; a document \
5354
that cannot be read answers `Unauthorized`. Each executed call appends one `mcp.<tool>` line to \
@@ -60,6 +61,21 @@ pub const TOOL_SETTINGS_SET: &str = "settings_set";
6061
pub const TOOL_LIST_EVENTS: &str = "list_events";
6162
pub const TOOL_GET_EVENT: &str = "get_event";
6263
pub const TOOL_RELAY_STATUS: &str = "relay_status";
64+
pub const TOOL_DELETE_EVENT: &str = "delete_event";
65+
pub const TOOL_REPORTS_ACTION: &str = "reports_action";
66+
67+
/// What a delete call did, as the payload's `outcome` (R3, R4): this call marked the row
68+
/// deleted.
69+
pub const OUTCOME_DELETED: &str = "deleted";
70+
71+
/// The row already carried `deleted_at`, so the store skipped it and this call changed nothing.
72+
pub const OUTCOME_ALREADY_DELETED: &str = "already_deleted";
73+
74+
/// The store skipped a live row for the only other reason it has: kind 62 is never deleted.
75+
pub const OUTCOME_NOT_DELETEABLE: &str = "not_deleteable";
76+
77+
/// No row carries the id this call named.
78+
pub const OUTCOME_NOT_FOUND: &str = "not_found";
6379

6480
/// The most `ids` or `authors` criteria one call may carry.
6581
///
@@ -188,6 +204,16 @@ pub const TOOLS: &[Tool] = &[
188204
parses: accepts_any_arguments,
189205
needs: Requires::Read,
190206
},
207+
Tool {
208+
name: TOOL_DELETE_EVENT,
209+
parses: delete_event_parses,
210+
needs: Requires::Write,
211+
},
212+
Tool {
213+
name: TOOL_REPORTS_ACTION,
214+
parses: reports_action_parses,
215+
needs: Requires::Write,
216+
},
191217
];
192218

193219
/// `tool`'s row; `None` when the table does not name it.
@@ -232,6 +258,14 @@ fn get_event_parses(arguments: Option<&Map<String, Value>>) -> bool {
232258
serde_json::from_value::<GetEventArgs>(arguments_value(arguments)).is_ok()
233259
}
234260

261+
fn delete_event_parses(arguments: Option<&Map<String, Value>>) -> bool {
262+
serde_json::from_value::<DeleteEventArgs>(arguments_value(arguments)).is_ok()
263+
}
264+
265+
fn reports_action_parses(arguments: Option<&Map<String, Value>>) -> bool {
266+
serde_json::from_value::<ReportsActionArgs>(arguments_value(arguments)).is_ok()
267+
}
268+
235269
fn arguments_value(arguments: Option<&Map<String, Value>>) -> Value {
236270
Value::Object(arguments.cloned().unwrap_or_default())
237271
}
@@ -271,6 +305,52 @@ pub struct GetEventArgs {
271305
pub id: String,
272306
}
273307

308+
/// The delete tool's arguments: one id and nothing else (R2).
309+
#[derive(Debug, Clone, Deserialize, JsonSchema)]
310+
#[serde(deny_unknown_fields)]
311+
pub struct DeleteEventArgs {
312+
/// The event's hex id, in either case; a prefix shorter than 64 characters is refused and deletes nothing
313+
pub id: String,
314+
}
315+
316+
/// The report action's arguments: one report event's id and the decision to give it (R12).
317+
#[derive(Debug, Clone, Deserialize, JsonSchema)]
318+
#[serde(deny_unknown_fields)]
319+
pub struct ReportsActionArgs {
320+
/// The report's own kind-1984 event id, exactly 64 hex characters in either case; not the reported event's id
321+
pub id: String,
322+
/// `hide` marks the report's targets hidden; `allow` clears them
323+
pub action: ReportAction,
324+
}
325+
326+
/// The two decisions a report can be given.
327+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
328+
#[serde(rename_all = "lowercase")]
329+
pub enum ReportAction {
330+
/// `hide`: the report's targets are hidden (`actionable: true`).
331+
Hide,
332+
/// `allow`: the report's targets are not hidden (`actionable: false`).
333+
Allow,
334+
}
335+
336+
impl JsonSchema for ReportAction {
337+
fn schema_name() -> Cow<'static, str> {
338+
"ReportAction".into()
339+
}
340+
341+
/// The closed set as the schema's `enum`, which is what a validating client reads and what
342+
/// the field's own description calls it. The derive would state a described unit enum as a
343+
/// `oneOf` of `const` variants instead, because each variant's doc comment has nowhere to go
344+
/// in a plain `enum` list; the set is the same either way.
345+
fn json_schema(_: &mut SchemaGenerator) -> Schema {
346+
json_schema!({ "type": "string", "enum": ["hide", "allow"] })
347+
}
348+
349+
fn inline_schema() -> bool {
350+
true
351+
}
352+
}
353+
274354
/// The `settings_set` arguments: the same JSON object the console's HTTP body carries (R12).
275355
///
276356
/// Kept as a raw map rather than a typed struct because the schema's rule is that an explicit
@@ -443,6 +523,110 @@ impl AdminMcp {
443523
}
444524
}
445525

526+
/// The store's own soft delete, on one row: the exact-id read names the pubkey the seam
527+
/// needs, one call flips the row, and the read-back carries the `deleted_at` the store
528+
/// stamped (R1, R3).
529+
#[tool(
530+
description = "Mark one stored event deleted: the same soft delete a NIP-09 request from the \
531+
author makes. The event leaves REQ and COUNT and keeps its row, so `get_event` and `list_events` \
532+
still return it with `deleted_at` set — unless an actionable report hides it, in which case it \
533+
stays hidden until the report is allowed. The argument is the event's hex id; a prefix shorter \
534+
than 64 characters is refused rather than widened to whatever the store's range would match. Answers `outcome` — `deleted`, \
535+
`already_deleted`, `not_deleteable` (kind 62 is never deleted), or `not_found` — and the row as \
536+
it stands after the call"
537+
)]
538+
async fn delete_event(
539+
&self,
540+
Parameters(arguments): Parameters<DeleteEventArgs>,
541+
) -> CallToolResult {
542+
match self.deleted(&arguments.id).await {
543+
Ok(payload) => tool_ok(payload),
544+
Err(error) => tool_error(&error),
545+
}
546+
}
547+
548+
/// One report event's triage decision: its own id, resolved through the report store, and
549+
/// every row it wrote flipped to `actionable` or off it (R7, R13).
550+
#[tool(
551+
description = "Act on one report event: `hide` marks its targets hidden (`actionable: true`, \
552+
so REQ and COUNT withhold them while `nip56.hideActionableReports` is on) and `allow` clears them \
553+
(`actionable: false`). The argument is the report's own kind-1984 event id — exactly 64 hex \
554+
characters, not the reported event's id — and every report row that event wrote is flipped. \
555+
Answers `reports` (the rows as they stand, by `id`) and `changed` (how many this call flipped). \
556+
Every new REQ reflects the change at once; already-connected subscriptions see it at the relay's \
557+
next refresh, up to 30 s"
558+
)]
559+
async fn reports_action(
560+
&self,
561+
Parameters(arguments): Parameters<ReportsActionArgs>,
562+
) -> CallToolResult {
563+
match self.act_on_report(&arguments).await {
564+
Ok(payload) => tool_ok(payload),
565+
Err(error) => tool_error(&error),
566+
}
567+
}
568+
569+
/// The delete payload: one outcome from the store's own count and the row **as it stands
570+
/// after** the call, and that row (R3, R4).
571+
///
572+
/// The read is [`EventRepository::find_stored`], not `get_event`'s gated read: a delete must
573+
/// reach the events a moderator has just hidden, or this slice's two tools contradict each
574+
/// other. The outcome comes from the post-call row rather than the pre-read, because a
575+
/// pre-read is stale the moment a second caller deletes the row first — that row answers
576+
/// `already_deleted`, and only a live one answers `not_deleteable`.
577+
async fn deleted(&self, id: &str) -> Result<Value, McpError> {
578+
let id = hex_prefix("id", id)?;
579+
if id.len() != 64 {
580+
return Err(McpError::Criterion(format!(
581+
"id: {id:?} is not a 64-character hex id"
582+
)));
583+
}
584+
let event_id = EventId::try_from(id.as_str())
585+
.map_err(|error| McpError::Criterion(error.to_string()))?;
586+
let events = &self.state.stores().events;
587+
let Some(row) = events.find_stored(&event_id).await? else {
588+
return Ok(json!({ "outcome": OUTCOME_NOT_FOUND, "event": null }));
589+
};
590+
let count = events
591+
.delete_by_pubkey_and_ids(&row.event.pubkey, &[row.event.id])
592+
.await?;
593+
let after = events.find_stored(&event_id).await?;
594+
let outcome = if count > 0 {
595+
OUTCOME_DELETED
596+
} else if after.as_ref().is_some_and(|row| row.deleted_at.is_some()) {
597+
OUTCOME_ALREADY_DELETED
598+
} else {
599+
OUTCOME_NOT_DELETEABLE
600+
};
601+
Ok(json!({ "outcome": outcome, "event": after }))
602+
}
603+
604+
/// The report payload: the rows one report event wrote, sorted by `id` because neither
605+
/// backend orders that read, and how many this call flipped (R13).
606+
///
607+
/// An id with no rows is a result rather than an error — the answer `get_event` gives an
608+
/// unknown id — so a caller that mistyped one sees an empty list and not `Not Found`.
609+
async fn act_on_report(&self, arguments: &ReportsActionArgs) -> Result<Value, McpError> {
610+
let id = hex_prefix("id", &arguments.id)?;
611+
if id.len() != 64 {
612+
return Err(McpError::Criterion(format!(
613+
"id: {id:?} is not a 64-character hex id"
614+
)));
615+
}
616+
let event_id = EventId::try_from(id.as_str())
617+
.map_err(|error| McpError::Criterion(error.to_string()))?;
618+
let reports = &self.state.stores().reports;
619+
if reports.find_by_event_id(&event_id).await?.is_empty() {
620+
return Ok(json!({ "reports": [], "changed": 0 }));
621+
}
622+
let changed = reports
623+
.set_actionable(&event_id, !matches!(arguments.action, ReportAction::Allow))
624+
.await?;
625+
let mut rows = reports.find_by_event_id(&event_id).await?;
626+
rows.sort_by_key(|report| report.id);
627+
Ok(json!({ "reports": rows, "changed": changed }))
628+
}
629+
446630
fn settings_document(&self) -> Result<Value, McpError> {
447631
let (merged, defaults) = self.state.merged_document()?;
448632
let filtered = nostream_config::store::filter_against_defaults(&merged, &defaults);

0 commit comments

Comments
 (0)