Skip to content

Commit 27044b0

Browse files
committed
Add a resources_list_handler for context-dependent resource lists
## Motivation and Context `resources/read` can be taken over with `resources_read_handler`, but `resources/list` had no equivalent: it was bound to the internal `list_resources`, which paginates the constructor-provided `resources` array, and `define_custom_method` refuses to rebind a method the server already handles. An application whose visible resources depend on the request - authenticated versus anonymous sessions, or an OAuth-scoped connector that must see a scope-filtered set - had to build a fresh `Server` per request or override a private method. Both reference SDKs let the list vary per request. The TypeScript SDK exposes `resources/list` through `setRequestHandler` and gives resource templates a per-context `listCallback(ctx)`; the Python SDK takes an `on_list_resources` handler. This adds the Ruby equivalent. `resources_list_handler(&block)` registers a block that returns the resource collection to serve. It feeds `list_resources` rather than replacing it, so the framework still paginates the returned array and stamps the SEP-2549 cache hints; the block returns only the array, matching how `resources_read_handler` returns only the contents and the framework wraps them. A block that declares a `server_context:` keyword receives an `MCP::ServerContext`, reusing the same opt-in rule the read handler uses, so the list can be filtered by the authenticated principal or granted scope. The block is invoked once per page and must return a stable ordering across the pages of one query, since the cursor is a positional offset. When no handler is set, the constructor-provided resources are served unchanged. The `resources` capability is advertised whether or not the constructor array is populated, so a server that provides only a `resources_list_handler` still answers `resources/list`. Fixes #507. ## How Has This Been Tested? New tests in `test/mcp/server_test.rb` cover a handler replacing the served collection, a handler receiving `server_context:` and returning different sets for authenticated and anonymous requests, pagination and cache hints still applying to the handler-provided array, and a server with no constructor-provided resources served entirely by the handler. The existing `resources/list` test, which exercises the no-handler default path, is unchanged. ## Breaking Changes None. When no `resources_list_handler` is set, `resources/list` serves the constructor-provided resources exactly as before.
1 parent b195a21 commit 27044b0

3 files changed

Lines changed: 98 additions & 3 deletions

File tree

‎README.md‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1244,6 +1244,20 @@ end
12441244
otherwise `resources/read` requests will be a no-op. Note that a `resources_read_handler` fully replaces
12451245
the default `resources/read` handling, including the automatic routing to class-based resources described above.
12461246

1247+
To make the resource *list* depend on the request, register a `resources_list_handler`. The block returns the resource collection to serve,
1248+
so the visible resources can vary by the authenticated principal or the granted scope. The framework paginates the returned array
1249+
and stamps the same cache hints it applies to the constructor-provided resources, so the block returns only the array.
1250+
A block that declares `server_context:` receives it:
1251+
1252+
```ruby
1253+
server.resources_list_handler do |params, server_context:|
1254+
server_context[:authenticated] ? real_resources : demo_resources
1255+
end
1256+
```
1257+
1258+
The block is invoked once per page, so it must return a stable ordering across the pages of one query; the cursor is a positional offset
1259+
into the returned collection. When no handler is set, the resources passed to `MCP::Server.new` are served unchanged.
1260+
12471261
For unknown URIs, raise `MCP::Server::ResourceNotFoundError` from the handler.
12481262
Per SEP-2164, the server then responds with the standard JSON-RPC Invalid Params error (`-32602`)
12491263
carrying the requested URI in the error `data` member:
@@ -1613,7 +1627,7 @@ Client-initiated cancellation is also supported: see [Client-Side: Cancelling an
16131627
#### Server-Side: Handlers that Check for Cancellation
16141628

16151629
Any handler that opts in to `server_context:` - tools (`Tool.call`), prompt templates,
1616-
`resources_read_handler`, `completion_handler`, `resources_subscribe_handler`,
1630+
`resources_read_handler`, `resources_list_handler`, `completion_handler`, `resources_subscribe_handler`,
16171631
`resources_unsubscribe_handler`, and `define_custom_method` blocks - receives
16181632
an `MCP::ServerContext` wired to the in-flight request's cancellation token.
16191633
Handlers check `cancelled?` in their work loop, or call `raise_if_cancelled!` to raise

‎lib/mcp/server.rb‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ def initialize(
182182
@resources = resources
183183
@resource_templates = resource_templates
184184
@resource_index = index_resources_by_uri(resources)
185+
@resources_list_handler = nil
185186
@server_context = server_context
186187
self.page_size = page_size
187188
self.ttl_ms = ttl_ms
@@ -387,6 +388,22 @@ def roots_list_changed_handler(&block)
387388
@handlers[Methods::NOTIFICATIONS_ROOTS_LIST_CHANGED] = block
388389
end
389390

391+
# Sets a custom handler for `resources/list` requests, letting the visible list depend on request context such as
392+
# the authenticated principal or granted scope. The block returns the resource collection to serve;
393+
# the framework paginates it and stamps SEP-2549 cache hints exactly as it does for the constructor-provided resources,
394+
# so the block returns only the array, not the paginated result.
395+
# A block that declares a `server_context:` keyword receives an `MCP::ServerContext`. When no handler is set,
396+
# the constructor-provided `resources` array is served unchanged.
397+
#
398+
# The block is invoked once per page, so it must return a stable ordering across the pages of one logical query;
399+
# the cursor is a positional offset into the returned collection.
400+
#
401+
# @yield [params, server_context:] The request params, and an `MCP::ServerContext` when declared.
402+
# @yieldreturn [Array<MCP::Resource>] The resources to paginate.
403+
def resources_list_handler(&block)
404+
@resources_list_handler = block
405+
end
406+
390407
# Sets a custom handler for `resources/read` requests.
391408
# The block receives the parsed request params and should return resource
392409
# contents. The return value is set as the `contents` field of the response.
@@ -1088,12 +1105,28 @@ def get_prompt(request, session: nil, related_request_id: nil, cancellation: nil
10881105
call_prompt_template_with_args(prompt, prompt_args, server_context)
10891106
end
10901107

1091-
def list_resources(request)
1092-
page = paginate(@resources, cursor: cursor_from(request), page_size: @page_size, request: request, &:to_h)
1108+
def list_resources(request, server_context: nil)
1109+
resources = if @resources_list_handler
1110+
invoke_resources_list_handler(request, server_context)
1111+
else
1112+
@resources
1113+
end
1114+
1115+
page = paginate(resources, cursor: cursor_from(request), page_size: @page_size, request: request, &:to_h)
10931116

10941117
apply_cache_metadata({ resources: page[:items], nextCursor: page[:next_cursor] }.compact)
10951118
end
10961119

1120+
# Calls the `resources_list_handler` block, forwarding `server_context:` only when the block opts in
1121+
# by declaring the keyword (the same rule `dispatch_optional_context_handler` applies).
1122+
def invoke_resources_list_handler(request, server_context)
1123+
if handler_declares_server_context?(@resources_list_handler)
1124+
@resources_list_handler.call(request, server_context: server_context)
1125+
else
1126+
@resources_list_handler.call(request)
1127+
end
1128+
end
1129+
10971130
# Default `resources/read` handler: routes to class-based resources and resource templates.
10981131
# Fully replaced when `resources_read_handler` is set. When no class-based resource or template is registered,
10991132
# unknown URIs keep the historical no-op `[]` response instead of raising.

‎test/mcp/server_test.rb‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1356,6 +1356,54 @@ class Example < Tool
13561356
assert_instrumentation_data({ method: "resources/list" })
13571357
end
13581358

1359+
test "#resources_list_handler replaces the served resource collection" do
1360+
other = Resource.new(uri: "https://other.invalid", name: "other", mime_type: "text/plain")
1361+
@server.resources_list_handler { |_params| [other] }
1362+
1363+
response = @server.handle({ jsonrpc: "2.0", method: "resources/list", id: 1 })
1364+
1365+
assert_equal({ resources: [other.to_h] }, response[:result])
1366+
end
1367+
1368+
test "#resources_list_handler receives server_context when it opts in" do
1369+
real = Resource.new(uri: "https://real.invalid", name: "real", mime_type: "text/plain")
1370+
demo = Resource.new(uri: "https://demo.invalid", name: "demo", mime_type: "text/plain")
1371+
@server.resources_list_handler do |_params, server_context:|
1372+
server_context[:authenticated] ? [real] : [demo]
1373+
end
1374+
1375+
@server.server_context = { authenticated: false }
1376+
anon = @server.handle({ jsonrpc: "2.0", method: "resources/list", id: 1 })
1377+
@server.server_context = { authenticated: true }
1378+
authed = @server.handle({ jsonrpc: "2.0", method: "resources/list", id: 1 })
1379+
1380+
assert_equal({ resources: [demo.to_h] }, anon[:result])
1381+
assert_equal({ resources: [real.to_h] }, authed[:result])
1382+
end
1383+
1384+
test "#resources_list_handler paginates and stamps cache hints on the returned collection" do
1385+
first = Resource.new(uri: "https://first.invalid", name: "first", mime_type: "text/plain")
1386+
second = Resource.new(uri: "https://second.invalid", name: "second", mime_type: "text/plain")
1387+
server = Server.new(name: @server_name, resources: [], page_size: 1, ttl_ms: 60_000)
1388+
server.resources_list_handler { |_params| [first, second] }
1389+
1390+
response = server.handle({ jsonrpc: "2.0", method: "resources/list", id: 1 })
1391+
1392+
assert_equal([first.to_h], response[:result][:resources])
1393+
assert_equal("1", response[:result][:nextCursor])
1394+
assert_equal(60_000, response[:result][:ttlMs])
1395+
end
1396+
1397+
test "#resources_list_handler serves a server with no constructor-provided resources" do
1398+
only = Resource.new(uri: "https://only.invalid", name: "only", mime_type: "text/plain")
1399+
server = Server.new(name: @server_name, resources: [])
1400+
server.resources_list_handler { |_params| [only] }
1401+
1402+
response = server.handle({ jsonrpc: "2.0", method: "resources/list", id: 1 })
1403+
1404+
assert_equal({ resources: [only.to_h] }, response[:result])
1405+
end
1406+
13591407
test "#handle resources/read returns an empty array of contents by default" do
13601408
request = {
13611409
jsonrpc: "2.0",

0 commit comments

Comments
 (0)