Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
895b4cb
feat(mcp): add delete_event and reports_action, with the report sette…
chappie-daemon Nov 21, 2026
2c5142f
feat(mcp): finish slice 3's oracle, count sites and record
chappie-daemon Nov 21, 2026
7b95e7f
docs(adr): the absent-name grep reads test sources, not the snapshot'…
chappie-daemon Nov 21, 2026
8bb14e4
docs(adr): the scope column carries three write tools, not one
chappie-daemon Nov 21, 2026
1313082
test(mcp): pin the report ordering, the refused row and the two flag …
chappie-daemon Nov 21, 2026
eeff5da
test(mcp): give the refused write a row it would have moved
chappie-daemon Nov 21, 2026
81469f5
test(mcp): say what the ungated cases do seed, and the gate's count w…
chappie-daemon Nov 21, 2026
bd9ffc8
docs(config): the write scope carries three tools, and says what the …
chappie-daemon Nov 21, 2026
66e9554
docs(adr): the sort is the contract's, the double's zero is its own, …
chappie-daemon Nov 21, 2026
6ba6eb3
feat(storage): add the ungated exact-id read the delete path needs
chappie-daemon Nov 21, 2026
6a7cb23
docs(mcp): say the short id is refused, not that it names nothing
chappie-daemon Nov 21, 2026
04816bb
test(storage): pin the ungated read on both backends, and say in D1 w…
chappie-daemon Nov 21, 2026
3004e51
docs(adr): the gate's real line, and what the call-count leg does and…
chappie-daemon Nov 21, 2026
89a53e0
test(mcp): give the post-read outcome a subject, and fix the gate's f…
chappie-daemon Nov 21, 2026
b50b8c4
docs(adr): count the implementors, and say why each one has to be tru…
chappie-daemon Nov 21, 2026
0a01867
docs(adr): a false double reddens its case; the hidden one does not u…
chappie-daemon Nov 21, 2026
File filter

Filter by extension

Filter by extension

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

feat(mcp): add the delete_event and reports_action tools

`delete_event` marks one stored event deleted through the store's own soft delete: the event
leaves REQ and COUNT, keeps its row, and the payload says so — `get_event` and `list_events` still
return it with `deleted_at` set unless an actionable report hides it, and the four outcomes are
`deleted`, `already_deleted`, `not_deleteable` (kind 62 is never deleted) and `not_found`. `reports_action` acts on a report's
own kind-1984 event id, flipping `Report.actionable` for `hide` and `allow` on every row that
event wrote.

The report store now reaches the MCP door as a `reports` field on `ServiceStores`, and
`ReportRepository` gains one setter: the LMDB arm moves the three denormalised
`reports_actionable_*` entries with the flag, so the NIP-56 gate and the actionable reads follow a
flip at once, and the Postgres arm is one `UPDATE` with no migration. The hidden-content mirror
needs no work: reads are gated per query and the mirror refreshes wholesale every 30 s.
`reports_list` remains out of scope and unowned.

Rust only; no published package changes. The decisions are in
`docs/rewrite/decisions/0017-report-and-event-writes.md`, and ADR 0014's audit table gains the two
`mcp.*` names.
5 changes: 3 additions & 2 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`) on stdin/stdout and exits when stdin closes. It binds no socket,
`list_events`, `get_event`, `delete_event`, `reports_action`) on stdin/stdout and exits when stdin
closes. It binds no socket,
opens no store of its own, and writes its log lines to **stderr** so nothing but JSON-RPC crosses
stdout.

Expand All @@ -96,7 +97,7 @@ 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 `settings_set`. |
| `{ "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). |

`write` is the only accepted scope, and an unknown name — a typo, or a document from another tool
— refuses to start rather than being narrowed silently. A call the document's scopes deny is
Expand Down
9 changes: 9 additions & 0 deletions crates/nostream-admin/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,8 @@ impl TestServer {
Arc::clone(&backend)
as Arc<dyn nostream_storage::repositories::NotificationDeliveryLogRepository>
}),
reports: Arc::clone(&backend)
as Arc<dyn nostream_storage::repositories::ReportRepository>,
});

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

fn find_stored<'a>(
&'a self,
_id: &'a nostream_core::EventId,
) -> nostream_storage::repositories::StorageFuture<'a, Option<EventRecord>> {
Box::pin(async { Err(not_implemented()) })
}

fn delete_by_pubkey_and_ids<'a>(
&'a self,
_pubkey: &'a nostream_core::Pubkey,
Expand Down
14 changes: 8 additions & 6 deletions crates/nostream-mcp/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! `nostream-mcp` owns the admin MCP server: the tool router, the five tools, the credential
//! `nostream-mcp` owns the admin MCP server: the tool router, the seven tools, the credential
//! and its scopes, and the audit sink.
//!
//! It owns no transport and no socket. `nostreamd --mcp-stdio` serves this server on
Expand All @@ -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: `delete_event`, `user_admin`, `invoices_*`,
//! `reports_*` and `maintenance_*` are later slices of #1183.
//! - every tool family outside this surface: `user_admin`, `invoices_*` and `maintenance_*` are
//! later slices of #1183.

mod credential;
mod error;
Expand All @@ -36,8 +36,10 @@ pub use credential::{
};
pub use error::McpError;
pub use server::{
AUDIT_DENIED, AdminMcp, FORBIDDEN, GetEventArgs, ListEventsArgs, MAX_FILTER_TERMS,
MAX_ROWS_PER_PAGE, MCP_INSTRUCTIONS, MCP_SERVER_NAME, NOT_FOUND, Requires, SettingsSetArgs,
TOOL_GET_EVENT, TOOL_LIST_EVENTS, TOOL_RELAY_STATUS, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET,
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,
};
190 changes: 187 additions & 3 deletions crates/nostream-mcp/src/server.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! The MCP server: the five tools, the credential gate and the audit sink.
//! The MCP server: the seven tools, the credential gate and the audit sink.
//!
//! Every tool is a thin handler over a seam that already exists — `AdminState` for the settings,
//! `EventRepository` for the events — and nothing here knows what an HTTP status is (R3). The
Expand All @@ -15,7 +15,7 @@ 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::{Filter, Kind};
use nostream_core::{EventId, Filter, Kind};
use nostream_relay::nip11;
use nostream_storage::repositories::{EventRecord, collect_page, collect_records};
use rmcp::handler::server::router::tool::ToolRouter;
Expand Down Expand Up @@ -47,7 +47,8 @@ pub const MCP_INSTRUCTIONS: &str = "\
The nostream admin MCP server. Every call is decided by the scoped token document the mode was \
started with — `--admin-token-file <path>` or `--admin-token-fd <n>`, exactly one, its shape \
{\"scopes\": [\"write\"]}: the document's presence authorises `settings_get`, `list_events`, \
`get_event` and `relay_status`, and the \"write\" scope authorises `settings_set` (else the call \
`get_event` and `relay_status`, and the \"write\" scope authorises `settings_set`, \
`delete_event` and `reports_action` (else the call \
is `Forbidden`). \
`admin.enabled` must be true in the settings, or every call answers `Not Found`; a document \
that cannot be read answers `Unauthorized`. Each executed call appends one `mcp.<tool>` line to \
Expand All @@ -60,6 +61,21 @@ pub const TOOL_SETTINGS_SET: &str = "settings_set";
pub const TOOL_LIST_EVENTS: &str = "list_events";
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";

/// What a delete call did, as the payload's `outcome` (R3, R4): this call marked the row
/// deleted.
pub const OUTCOME_DELETED: &str = "deleted";

/// The row already carried `deleted_at`, so the store skipped it and this call changed nothing.
pub const OUTCOME_ALREADY_DELETED: &str = "already_deleted";

/// The store skipped a live row for the only other reason it has: kind 62 is never deleted.
pub const OUTCOME_NOT_DELETEABLE: &str = "not_deleteable";

/// No row carries the id this call named.
pub const OUTCOME_NOT_FOUND: &str = "not_found";

/// The most `ids` or `authors` criteria one call may carry.
///
Expand Down Expand Up @@ -188,6 +204,16 @@ pub const TOOLS: &[Tool] = &[
parses: accepts_any_arguments,
needs: Requires::Read,
},
Tool {
name: TOOL_DELETE_EVENT,
parses: delete_event_parses,
needs: Requires::Write,
},
Tool {
name: TOOL_REPORTS_ACTION,
parses: reports_action_parses,
needs: Requires::Write,
},
];

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

fn delete_event_parses(arguments: Option<&Map<String, Value>>) -> bool {
serde_json::from_value::<DeleteEventArgs>(arguments_value(arguments)).is_ok()
}

fn reports_action_parses(arguments: Option<&Map<String, Value>>) -> bool {
serde_json::from_value::<ReportsActionArgs>(arguments_value(arguments)).is_ok()
}

fn arguments_value(arguments: Option<&Map<String, Value>>) -> Value {
Value::Object(arguments.cloned().unwrap_or_default())
}
Expand Down Expand Up @@ -271,6 +305,52 @@ pub struct GetEventArgs {
pub id: String,
}

/// The delete tool's arguments: one id and nothing else (R2).
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct DeleteEventArgs {
/// The event's hex id, in either case; a prefix shorter than 64 characters is refused and deletes nothing
pub id: String,
}

/// The report action's arguments: one report event's id and the decision to give it (R12).
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct ReportsActionArgs {
/// The report's own kind-1984 event id, exactly 64 hex characters in either case; not the reported event's id
pub id: String,
/// `hide` marks the report's targets hidden; `allow` clears them
pub action: ReportAction,
}

/// The two decisions a report can be given.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ReportAction {
/// `hide`: the report's targets are hidden (`actionable: true`).
Hide,
/// `allow`: the report's targets are not hidden (`actionable: false`).
Allow,
}

impl JsonSchema for ReportAction {
fn schema_name() -> Cow<'static, str> {
"ReportAction".into()
}

/// The closed set as the schema's `enum`, which is what a validating client reads and what
/// the field's own description calls it. The derive would state a described unit enum as a
/// `oneOf` of `const` variants instead, because each variant's doc comment has nowhere to go
/// in a plain `enum` list; the set is the same either way.
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({ "type": "string", "enum": ["hide", "allow"] })
}

fn inline_schema() -> bool {
true
}
}

/// 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
Expand Down Expand Up @@ -443,6 +523,110 @@ impl AdminMcp {
}
}

/// The store's own soft delete, on one row: the exact-id read names the pubkey the seam
/// needs, one call flips the row, and the read-back carries the `deleted_at` the store
/// stamped (R1, R3).
#[tool(
description = "Mark one stored event deleted: the same soft delete a NIP-09 request from the \
author makes. The event leaves REQ and COUNT and keeps its row, so `get_event` and `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. The argument is the event's hex id; a prefix shorter \
than 64 characters is refused rather than widened to whatever the store's range would match. Answers `outcome` — `deleted`, \
`already_deleted`, `not_deleteable` (kind 62 is never deleted), or `not_found` — and the row as \
it stands after the call"
)]
async fn delete_event(
&self,
Parameters(arguments): Parameters<DeleteEventArgs>,
) -> CallToolResult {
match self.deleted(&arguments.id).await {
Ok(payload) => tool_ok(payload),
Err(error) => tool_error(&error),
}
}

/// One report event's triage decision: its own id, resolved through the report store, and
/// every row it wrote flipped to `actionable` or off it (R7, R13).
#[tool(
description = "Act on one report event: `hide` marks its targets hidden (`actionable: true`, \
so REQ and COUNT withhold them while `nip56.hideActionableReports` is on) and `allow` clears them \
(`actionable: false`). The argument is the report's own kind-1984 event id — exactly 64 hex \
characters, not the reported event's id — and every report row that event wrote is flipped. \
Answers `reports` (the rows as they stand, by `id`) and `changed` (how many this call flipped). \
Every new REQ reflects the change at once; already-connected subscriptions see it at the relay's \
next refresh, up to 30 s"
)]
async fn reports_action(
&self,
Parameters(arguments): Parameters<ReportsActionArgs>,
) -> CallToolResult {
match self.act_on_report(&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).
///
/// The read is [`EventRepository::find_stored`], not `get_event`'s gated read: a delete must
/// reach the events a moderator has just hidden, or this slice's two tools contradict each
/// other. The outcome comes from the post-call row rather than the pre-read, because a
/// pre-read is stale the moment a second caller deletes the row first — that row answers
/// `already_deleted`, and only a live one answers `not_deleteable`.
async fn deleted(&self, id: &str) -> Result<Value, McpError> {
let id = hex_prefix("id", id)?;
if id.len() != 64 {
return Err(McpError::Criterion(format!(
"id: {id:?} is not a 64-character hex id"
)));
}
let event_id = EventId::try_from(id.as_str())
.map_err(|error| McpError::Criterion(error.to_string()))?;
let events = &self.state.stores().events;
let Some(row) = events.find_stored(&event_id).await? else {
return Ok(json!({ "outcome": OUTCOME_NOT_FOUND, "event": null }));
};
let count = events
.delete_by_pubkey_and_ids(&row.event.pubkey, &[row.event.id])
.await?;
let after = events.find_stored(&event_id).await?;
let outcome = if count > 0 {
OUTCOME_DELETED
} else if after.as_ref().is_some_and(|row| row.deleted_at.is_some()) {
OUTCOME_ALREADY_DELETED
} else {
OUTCOME_NOT_DELETEABLE
};
Ok(json!({ "outcome": outcome, "event": after }))
}

/// The report payload: the rows one report event wrote, sorted by `id` because neither
/// backend orders that read, and how many this call flipped (R13).
///
/// An id with no rows is a result rather than an error — the answer `get_event` gives an
/// unknown id — so a caller that mistyped one sees an empty list and not `Not Found`.
async fn act_on_report(&self, arguments: &ReportsActionArgs) -> Result<Value, McpError> {
let id = hex_prefix("id", &arguments.id)?;
if id.len() != 64 {
return Err(McpError::Criterion(format!(
"id: {id:?} is not a 64-character hex id"
)));
}
let event_id = EventId::try_from(id.as_str())
.map_err(|error| McpError::Criterion(error.to_string()))?;
let reports = &self.state.stores().reports;
if reports.find_by_event_id(&event_id).await?.is_empty() {
return Ok(json!({ "reports": [], "changed": 0 }));
}
let changed = reports
.set_actionable(&event_id, !matches!(arguments.action, ReportAction::Allow))
.await?;
let mut rows = reports.find_by_event_id(&event_id).await?;
rows.sort_by_key(|report| report.id);
Ok(json!({ "reports": rows, "changed": changed }))
}

fn settings_document(&self) -> Result<Value, McpError> {
let (merged, defaults) = self.state.merged_document()?;
let filtered = nostream_config::store::filter_against_defaults(&merged, &defaults);
Expand Down
Loading
Loading