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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changeset/mcp-offset-bound.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
16 changes: 8 additions & 8 deletions crates/nostream-mcp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ pub use credential::{
pub use error::McpError;
pub use server::{
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_MAINTENANCE_LAST_RUN, TOOL_MAINTENANCE_RUN, TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION,
TOOL_REPORTS_LIST, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOL_USER_ADMIN, TOOL_USER_GET, TOOLS,
Tool, UNAUTHORIZED, UserAction, UserAdminArgs, UserGetArgs, arguments_parse, audit_action,
required_scope,
InvoicesListArgs, ListEventsArgs, MAX_FILTER_TERMS, MAX_ROWS_PER_PAGE, MAX_ROWS_PER_SKIP,
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_MAINTENANCE_LAST_RUN, TOOL_MAINTENANCE_RUN,
TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, TOOL_REPORTS_LIST, TOOL_SETTINGS_GET,
TOOL_SETTINGS_SET, TOOL_USER_ADMIN, TOOL_USER_GET, TOOLS, Tool, UNAUTHORIZED, UserAction,
UserAdminArgs, UserGetArgs, arguments_parse, audit_action, required_scope,
};
39 changes: 36 additions & 3 deletions crates/nostream-mcp/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,21 @@ pub const MAX_FILTER_TERMS: usize = 64;
/// takes a direction from `limit`.
pub const MAX_ROWS_PER_PAGE: u64 = nostream_storage::DEFAULT_PAGE_ROWS;

/// The most rows an `invoices_list` call may skip: this door's own ceiling, 5,000 rows.
///
/// The skip is linear in the rows it passes and then saturates at the pending set, so an
/// arbitrarily large offset costs a whole index walk for an answer that may be empty. Over 20,000
/// pending rows it measured 0.941 ms at `offset: 5_000` with `limit: 0` (the skip loop alone,
/// best of five), against 7.936 ms for the 500-row page at offset 0 and 1.562 ms at `u64::MAX`.
/// A ceiling at this door's own page ([`MAX_ROWS_PER_PAGE`]) was rejected because at `limit: 500`
/// it leaves a caller two pages deep; 5,000 leaves eleven.
///
/// The magnitude matches [`nostream_storage::MAX_PAGE_ROWS`], the relay's largest event page —
/// the largest single page the tree already asks a backend to answer — and it is measured against
/// that clamp rather than derived from it: the invoice read has no page bound of its own, and a
/// relocation of the relay's event page must not move this door's published `maximum`.
pub const MAX_ROWS_PER_SKIP: u64 = 5_000;

/// The refusal for a credential whose document is absent, unreadable or no longer a document this
/// door accepts — the HTTP gate's `401`.
pub const UNAUTHORIZED: &str = "Unauthorized";
Expand Down Expand Up @@ -497,7 +512,8 @@ pub struct UserGetArgs {
#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct InvoicesListArgs {
/// Rows to skip, oldest first; absent skips none.
/// Rows to skip, oldest first; absent skips none; at most 5000.
#[schemars(range(min = 0, max = MAX_ROWS_PER_SKIP))]
pub offset: Option<u64>,
/// Page size: 1 to 500 rows, oldest first; absent uses 500.
#[schemars(range(min = 1, max = 500))]
Expand Down Expand Up @@ -793,7 +809,8 @@ the relay has not cached and the door has never written reads as absent. Changes
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`"
that many, and at most 5000. A confirmed invoice stays in this list while its status reads \
`pending`"
)]
async fn invoices_list(
&self,
Expand Down Expand Up @@ -981,11 +998,12 @@ maintenance worker runs in another process and its passes are not visible here"
/// decide either (R12).
async fn pending_invoices(&self, arguments: &InvoicesListArgs) -> Result<Value, McpError> {
let limit = page_bound(arguments.limit)?;
let offset = offset_bound(arguments.offset)?;
let invoices = self
.state
.stores()
.invoices
.find_pending_invoices(arguments.offset.unwrap_or(0), limit)
.find_pending_invoices(offset, limit)
.await?;
Ok(json!({ "invoices": invoices }))
}
Expand Down Expand Up @@ -1174,6 +1192,21 @@ fn page_bound(limit: Option<u64>) -> Result<u64, McpError> {
})
}

/// The skip a call asks for, checked against the bound its `inputSchema` states (R12, D3).
///
/// An absent offset skips none. Anything past [`MAX_ROWS_PER_SKIP`] is refused here, before the
/// repository call, so the walk's cost is bounded at the door rather than by the pending set.
fn offset_bound(offset: Option<u64>) -> Result<u64, McpError> {
let offset = offset.unwrap_or(0);
(offset <= MAX_ROWS_PER_SKIP)
.then_some(offset)
.ok_or_else(|| {
McpError::Criterion(format!(
"offset: a walk skips at most {MAX_ROWS_PER_SKIP} rows, {offset} was given"
))
})
}

/// The events' page size, from the one bound.
fn page_size(criteria: &ListEventsArgs) -> Result<usize, McpError> {
// The bound caps the page at `MAX_ROWS_PER_PAGE`, so this conversion cannot narrow.
Expand Down
5 changes: 3 additions & 2 deletions crates/nostream-mcp/tests/fixtures/tools_list.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"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`",
"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, and at most 5000. A confirmed invoice stays in this list while its status reads `pending`",
"inputSchema": {
"$schema": "https://json-schema.org/draft/2020-12/schema",
"additionalProperties": false,
Expand All @@ -71,8 +71,9 @@
]
},
"offset": {
"description": "Rows to skip, oldest first; absent skips none.",
"description": "Rows to skip, oldest first; absent skips none; at most 5000.",
"format": "uint64",
"maximum": 5000,
"minimum": 0,
"type": [
"integer",
Expand Down
74 changes: 71 additions & 3 deletions crates/nostream-mcp/tests/store_families.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
//! | `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_list_pages_by_offset_and_refuses_a_page_outside_the_bound` | `offset`/`limit` are the store's own page, 0 and 501 are the one refusal, and the skip ceiling refuses 5001 and serves 5000 |
//! | `invoices_list_serves_the_page_at_the_offset_ceiling` | the page at the ceiling is served, and the bound is on `offset`, not on `offset + limit` |
//! | `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 |
Expand All @@ -35,8 +36,8 @@ 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,
FORBIDDEN, MAX_ROWS_PER_SKIP, 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,
Expand Down Expand Up @@ -643,6 +644,73 @@ async fn invoices_list_pages_by_offset_and_refuses_a_page_outside_the_bound() {
"{given}"
);
}

let served = client
.call(TOOL_INVOICES_LIST, json!({ "offset": MAX_ROWS_PER_SKIP }))
.await;
assert_eq!(served.is_error, Some(false), "{}", text(&served));
assert!(ids(&payload(&served), "invoices").is_empty());

for given in [MAX_ROWS_PER_SKIP + 1, u64::MAX] {
let refused = client
.call(TOOL_INVOICES_LIST, json!({ "offset": given }))
.await;
assert_eq!(refused.is_error, Some(true), "{given}: {}", text(&refused));
assert_eq!(
text(&refused),
format!("offset: a walk skips at most {MAX_ROWS_PER_SKIP} rows, {given} was given"),
"{given}"
);
}

let both = client
.call(
TOOL_INVOICES_LIST,
json!({ "limit": 0, "offset": MAX_ROWS_PER_SKIP + 1 }),
)
.await;
assert_eq!(
text(&both),
"limit: a page holds between 1 and 500 rows, 0 was given"
);
}

#[tokio::test]
async fn invoices_list_serves_the_page_at_the_offset_ceiling() {
let fixture = TestMcp::start().await;
let pubkey = key();
for index in 0..=MAX_ROWS_PER_SKIP {
seed_invoice(
&fixture,
&invoice(
&format!("inv-skip-{index:05}"),
&pubkey,
InvoiceStatus::Pending,
instant(1_699_999_100 + index as i64),
),
)
.await;
}
let client = fixture.client().await;

let last = client
.call(
TOOL_INVOICES_LIST,
json!({ "offset": MAX_ROWS_PER_SKIP, "limit": 1 }),
)
.await;
assert_eq!(last.is_error, Some(false), "{}", text(&last));
assert_eq!(ids(&payload(&last), "invoices"), vec!["inv-skip-05000"]);

let below = MAX_ROWS_PER_SKIP - 1;
let paged = client
.call(TOOL_INVOICES_LIST, json!({ "offset": below, "limit": 2 }))
.await;
assert_eq!(paged.is_error, Some(false), "{}", text(&paged));
assert_eq!(
ids(&payload(&paged), "invoices"),
vec!["inv-skip-04999", "inv-skip-05000"]
);
}

#[tokio::test]
Expand Down
14 changes: 10 additions & 4 deletions crates/nostream-mcp/tests/tools_list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ mod common;

use common::TestMcp;
use nostream_mcp::{
MAX_ROWS_PER_PAGE, TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_INVOICES_GET, TOOL_INVOICES_LIST,
TOOL_LIST_EVENTS, TOOL_MAINTENANCE_LAST_RUN, TOOL_MAINTENANCE_RUN, TOOL_RELAY_STATUS,
TOOL_REPORTS_ACTION, TOOL_REPORTS_LIST, TOOL_SETTINGS_GET, TOOL_SETTINGS_SET, TOOL_USER_ADMIN,
TOOL_USER_GET,
MAX_ROWS_PER_PAGE, MAX_ROWS_PER_SKIP, TOOL_DELETE_EVENT, TOOL_GET_EVENT, TOOL_INVOICES_GET,
TOOL_INVOICES_LIST, TOOL_LIST_EVENTS, TOOL_MAINTENANCE_LAST_RUN, TOOL_MAINTENANCE_RUN,
TOOL_RELAY_STATUS, TOOL_REPORTS_ACTION, TOOL_REPORTS_LIST, TOOL_SETTINGS_GET,
TOOL_SETTINGS_SET, TOOL_USER_ADMIN, TOOL_USER_GET,
};
use serde_json::{Value, json};

Expand Down Expand Up @@ -145,6 +145,12 @@ async fn the_required_parameters_are_typed() {
json!(MAX_ROWS_PER_PAGE),
"the schema's bound is the tool's page bound"
);
assert_eq!(
tool(TOOL_INVOICES_LIST)["inputSchema"]["properties"]["offset"]["maximum"],
json!(MAX_ROWS_PER_SKIP),
"the schema's skip bound is the tool's skip ceiling"
);
assert_eq!(MAX_ROWS_PER_SKIP, 5_000, "the ceiling D2 fixes");

assert!(
tool(TOOL_GET_EVENT)["inputSchema"]["properties"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ paged past 500. Paid for: zero storage code in this slice.
`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.
would be a guess. ADR 0020 caps the skip this paragraph leaves open, at the door rather than in
the protocol.

`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
Expand All @@ -137,7 +138,8 @@ page, and `invoices_list`'s offset walks a live index, so a pending row that lea
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.
one message for the three tools that page. ADR 0020 is the record for capping how far that offset
may skip.

### D7 — The absent-name example moves to `maintenance_run`, and five audit names land

Expand Down
Loading
Loading