ruby-sdk/test/mcp/server/pagination_test.rb
Koichi ITO b97b922a36 Support pagination per MCP specification
## Motivation and Context

The MCP specification defines cursor-based pagination for list operations that
may return large result sets:
https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/pagination

Pagination allows servers to yield results in smaller chunks rather than all at once,
which is especially important when connecting to external services over the internet.

The Ruby SDK previously returned complete arrays for all list endpoints
(`tools/list`, `resources/list`, `prompts/list`, `resources/templates/list`)
without pagination support. This adds cursor-based pagination.

### Server-side

A new `MCP::Server::Pagination` module is introduced (mixed into `MCP::Server`)
that provides the `paginate` helper for slicing a collection by cursor and
a `cursor_from` helper that extracts the cursor from the request params
while rejecting non-Hash inputs with `-32602 Invalid params` per the specification.

`MCP::Server.new` accepts a new `page_size:` keyword argument.
When `nil` (the default), all items are returned in a single response,
preserving the existing behavior. When set to a positive integer,
list responses include a `nextCursor` field if more pages are available.

`Server#page_size=` is a validating setter that rejects anything other than
`nil` or a positive `Integer`, raising `ArgumentError` on invalid inputs.
The constructor routes through the setter, so both `Server.new(page_size: 0)`
and `server.page_size = -1` raise.

Cursors are string tokens carrying a zero-based offset, treated as opaque by
clients. Cursor inputs are validated to be strings per the MCP spec;
invalid cursors (non-string, non-numeric, negative, or out-of-range) raise
`RequestHandlerError` with error code `-32602 (Invalid params)` per the spec.

### Client-side: two complementary APIs

The SDK exposes two API shapes for listing, each serving a different use case:

1. **Single-page with cursor** (`client.list_tools(cursor:)`,
   `list_resources`, `list_resource_templates`, `list_prompts`): each call issues
   one JSON-RPC request and returns a result object (`MCP::Client::ListToolsResult` etc.)
   carrying the page items and an optional `next_cursor`.
   These methods match the single-page-with-cursor convention used by the Python SDK
   (`session.list_tools(params=PaginatedRequestParams(cursor=...))`)
   and the TypeScript SDK (`client.listTools({ cursor })`). The method name and
   the `cursor` parameter name are identical across the three SDKs,
   so pagination code translates directly between languages.

2. **Whole-collection** (`client.tools`, `client.resources`, `client.resource_templates`,
   `client.prompts`): auto-iterates through all pages and returns a plain array of items,
   guaranteeing the full collection regardless of the server's `page_size` setting.
   The auto-pagination loop tracks previously seen cursors in a set and exits if the server
   revisits any of them, guarding against both immediate repeats and multi-cursor cycles
   (e.g. `A -> B -> A`). This mirrors Rust SDK's `list_all_*` convenience methods,
   though the Ruby names are preserved from the pre-pagination 0.13.0 API for backward compatibility.
   Future rename to `list_all_*` is left as a TODO in the source.

Result classes are `Struct`s named to mirror Python SDK's `ListToolsResult` /
`ListPromptsResult` / etc. to align naming with other SDKs. Each struct exposes
its page items (e.g. `result.tools`), an optional `next_cursor` for continuation,
and an optional `meta` field mirroring the MCP `Result` type's `_meta` response field
so servers that decorate list responses do not lose metadata through the client.

### Ruby-specific ergonomics

`Server.new(page_size:)` and the `Pagination` module are Ruby-specific.
The Python and TypeScript SDKs do not expose a built-in `page_size` helper;
developers there re-implement cursor slicing inside each handler.
In Ruby, setting `page_size:` on the server is enough for the SDK to handle
the slicing across the four built-in list endpoints.

### README

A Pagination section documents both the server-side `page_size:` option and
the client-side iteration patterns, including an explicit note that each `list_*` call
is a single JSON-RPC round trip whose response size depends on the server's `page_size`,
and that `client.tools` / `.resources` / `.resource_templates` / `.prompts` return
the complete collection when needed.

## How Has This Been Tested?

- Added tests for the `Pagination` module (`test/mcp/server/pagination_test.rb`),
  server-side pagination (`test/mcp/server_test.rb`), and client-side pagination
  (`test/mcp/client_test.rb`).
- Added and existing tests pass. `rake rubocop` is clean and `rake conformance` passes.

## Breaking Changes

None. This is a new feature addition. Existing code continues to work unchanged:
`page_size` defaults to `nil` on the server (returns all items, no `nextCursor`),
and the client's existing `tools` / `resources` / `resource_templates` / `prompts` methods
continue to return complete arrays by transparently iterating through pages.
2026-04-18 18:23:30 +09:00

166 lines
6 KiB
Ruby

# frozen_string_literal: true
require "test_helper"
module MCP
class Server
class PaginationTest < ActiveSupport::TestCase
class PaginationHost
include Pagination
# Expose private methods for testing.
public :paginate, :cursor_from
# RequestHandlerError must be accessible.
RequestHandlerError = Server::RequestHandlerError
end
setup do
@host = PaginationHost.new
@items = [{ name: "a" }, { name: "b" }, { name: "c" }, { name: "d" }, { name: "e" }]
@request = { method: "tools/list" }
end
test "paginate returns all items when page_size is nil and no cursor" do
result = @host.paginate(@items, cursor: nil, page_size: nil, request: @request)
assert_equal @items, result[:items]
assert_nil result[:next_cursor]
end
test "paginate returns first page with nextCursor when page_size is set" do
result = @host.paginate(@items, cursor: nil, page_size: 2, request: @request)
assert_equal [{ name: "a" }, { name: "b" }], result[:items]
assert_not_nil result[:next_cursor]
end
test "paginate returns correct second page when cursor is provided" do
first = @host.paginate(@items, cursor: nil, page_size: 2, request: @request)
second = @host.paginate(@items, cursor: first[:next_cursor], page_size: 2, request: @request)
assert_equal [{ name: "c" }, { name: "d" }], second[:items]
assert_not_nil second[:next_cursor]
end
test "paginate returns last page without nextCursor" do
first = @host.paginate(@items, cursor: nil, page_size: 2, request: @request)
second = @host.paginate(@items, cursor: first[:next_cursor], page_size: 2, request: @request)
third = @host.paginate(@items, cursor: second[:next_cursor], page_size: 2, request: @request)
assert_equal [{ name: "e" }], third[:items]
assert_nil third[:next_cursor]
end
test "paginate with page_size equal to items count returns all without nextCursor" do
result = @host.paginate(@items, cursor: nil, page_size: 5, request: @request)
assert_equal @items, result[:items]
assert_nil result[:next_cursor]
end
test "paginate with page_size larger than items count returns all without nextCursor" do
result = @host.paginate(@items, cursor: nil, page_size: 100, request: @request)
assert_equal @items, result[:items]
assert_nil result[:next_cursor]
end
test "paginate with empty items returns empty array" do
result = @host.paginate([], cursor: nil, page_size: 2, request: @request)
assert_equal [], result[:items]
assert_nil result[:next_cursor]
end
test "paginate raises RequestHandlerError for non-numeric cursor" do
error = assert_raises(RequestHandlerError) do
@host.paginate(@items, cursor: "not_a_number", page_size: 2, request: @request)
end
assert_equal :invalid_params, error.error_type
end
test "paginate raises RequestHandlerError for Integer cursor (spec requires string)" do
error = assert_raises(RequestHandlerError) do
@host.paginate(@items, cursor: 2, page_size: 2, request: @request)
end
assert_equal :invalid_params, error.error_type
end
test "paginate raises RequestHandlerError for Float cursor (spec requires string)" do
error = assert_raises(RequestHandlerError) do
@host.paginate(@items, cursor: 1.5, page_size: 2, request: @request)
end
assert_equal :invalid_params, error.error_type
end
test "paginate raises RequestHandlerError for negative offset cursor" do
error = assert_raises(RequestHandlerError) do
@host.paginate(@items, cursor: "-1", page_size: 2, request: @request)
end
assert_equal :invalid_params, error.error_type
end
test "paginate raises RequestHandlerError for out-of-range cursor" do
error = assert_raises(RequestHandlerError) do
@host.paginate(@items, cursor: "100", page_size: 2, request: @request)
end
assert_equal :invalid_params, error.error_type
end
test "paginate returns all items from cursor offset when page_size is nil" do
result = @host.paginate(@items, cursor: "2", page_size: nil, request: @request)
assert_equal [{ name: "c" }, { name: "d" }, { name: "e" }], result[:items]
assert_nil result[:next_cursor]
end
test "paginate raises RequestHandlerError when cursor points exactly at items.size" do
error = assert_raises(RequestHandlerError) do
@host.paginate(@items, cursor: @items.size.to_s, page_size: 2, request: @request)
end
assert_equal :invalid_params, error.error_type
end
test "paginate on empty items with any cursor raises RequestHandlerError" do
error = assert_raises(RequestHandlerError) do
@host.paginate([], cursor: "0", page_size: 2, request: @request)
end
assert_equal :invalid_params, error.error_type
end
test "cursor_from returns nil for nil request" do
assert_nil @host.cursor_from(nil)
end
test "cursor_from returns cursor for Hash request" do
assert_equal "abc", @host.cursor_from(cursor: "abc")
end
test "cursor_from returns nil when Hash request has no cursor" do
assert_nil @host.cursor_from({})
end
test "cursor_from raises RequestHandlerError for non-Hash request" do
error = assert_raises(RequestHandlerError) do
@host.cursor_from([1, 2, 3])
end
assert_equal :invalid_params, error.error_type
end
test "paginate with page_size 1 iterates one item at a time" do
results = []
cursor = nil
loop do
page = @host.paginate(@items, cursor: cursor, page_size: 1, request: @request)
results.concat(page[:items])
cursor = page[:next_cursor]
break unless cursor
end
assert_equal @items, results
end
end
end
end