diff --git a/docs/_server/cancellation.md b/docs/_server/cancellation.md index 1939a24e..08a4ea85 100644 --- a/docs/_server/cancellation.md +++ b/docs/_server/cancellation.md @@ -27,8 +27,9 @@ is never cancellable per the spec. ## Handlers that Check for Cancellation Any handler that opts in to `server_context:` - tools (`Tool.call`), prompt templates, -`resources_read_handler`, `resources_list_handler`, `completion_handler`, `resources_subscribe_handler`, -`resources_unsubscribe_handler`, and [`define_custom_method`](/server/custom-methods/) blocks - receives +`resources_read_handler`, `resources_list_handler`, `tools_list_handler`, `completion_handler`, +`resources_subscribe_handler`, `resources_unsubscribe_handler`, and +[`define_custom_method`](/server/custom-methods/) blocks - receives an `MCP::ServerContext` wired to the in-flight request's cancellation token. Handlers check `cancelled?` in their work loop, or call `raise_if_cancelled!` to raise `MCP::CancelledError` at a safe point: diff --git a/docs/_server/pagination.md b/docs/_server/pagination.md index 7be144c5..a67e7f9b 100644 --- a/docs/_server/pagination.md +++ b/docs/_server/pagination.md @@ -11,7 +11,7 @@ for list operations that may return large result sets. Pagination uses string cu treated as opaque by clients: the server decides page size, and the client follows `nextCursor` until the server omits it. Pagination applies to `tools/list`, `prompts/list`, `resources/list`, and `resources/templates/list`, -including lists produced by a custom `resources_list_handler`. +including lists produced by a custom `resources_list_handler` or `tools_list_handler`. ## Enabling Pagination diff --git a/docs/_server/tools.md b/docs/_server/tools.md index e2c8c198..9e16046e 100644 --- a/docs/_server/tools.md +++ b/docs/_server/tools.md @@ -89,6 +89,27 @@ end The [`server_context`](/server/server-context/) parameter is the `server_context` passed into the server and can be used to pass per request information, e.g. around authentication state. +To make the visible *tools* depend on the request, register a `tools_list_handler`. The block returns the tool collection for the request, +so the visible tools can vary by the authenticated principal or the granted scope. The framework paginates the returned array +and stamps the same cache hints it applies to the registered tools, so the block returns only the array. +A block that declares `server_context:` receives it: + +```ruby +server.tools_list_handler do |params, server_context:| + server_context[:admin] ? all_tools : member_tools +end +``` + +The returned collection is both what `tools/list` advertises and what `tools/call` resolves against: a tool the block leaves out +is refused as not found, and a tool it returns is callable whether or not it is registered on the server. +The block is invoked once per `tools/list` page and once per `tools/call`, with that request's params, so it should be cheap +and must return a stable ordering across the pages of one query; the cursor is a positional offset into the returned collection. +When no handler is set, the registered tools are used unchanged. + +{: .note } +> The [custom header](#custom-headers-from-tool-parameters) check runs in the transport against the registered tools, +> so it is skipped for a tool that only the `tools_list_handler` returns. + Icons for tools are documented on the [Icons](/server/icons/) page. ## Tool argument keys diff --git a/lib/mcp/server.rb b/lib/mcp/server.rb index 4fc37f7b..1da6e8fc 100644 --- a/lib/mcp/server.rb +++ b/lib/mcp/server.rb @@ -253,6 +253,7 @@ def initialize( ensure_no_skill_file_collision!(resources.map(&:uri)) @resource_index = index_resources_by_uri(resources) @resources_list_handler = nil + @tools_list_handler = nil @server_context = server_context self.page_size = page_size self.ttl_ms = ttl_ms @@ -476,6 +477,28 @@ def roots_list_changed_handler(&block) @handlers[Methods::NOTIFICATIONS_ROOTS_LIST_CHANGED] = block end + # Sets a custom handler for the tools visible to a request, letting them depend on request context such as + # the authenticated principal or granted scope. The block returns the tool collection for the request; + # the framework paginates it for `tools/list` and stamps the same cache hints it applies to the registered tools, + # so the block returns only the array, not the paginated result. + # A block that declares a `server_context:` keyword receives an `MCP::ServerContext`. When no handler is set, + # the registered tools are used unchanged. + # + # The returned collection is both what `tools/list` advertises and what `tools/call` resolves against: + # a tool the block leaves out is refused as not found, and a tool it returns is callable + # whether or not it is registered on the server. + # + # The block is invoked once per `tools/list` page and once per `tools/call`, so it should be cheap and + # must return a stable ordering across the pages of one logical query; the cursor is a positional offset + # into the returned collection. + # + # @yield [params, server_context:] The `tools/list` or `tools/call` request params, + # and an `MCP::ServerContext` when declared. + # @yieldreturn [Array] The tools visible to the request. + def tools_list_handler(&block) + @tools_list_handler = block + end + # Sets a custom handler for `resources/list` requests, letting the visible list depend on request context such as # the authenticated principal or granted scope. The block returns the resource collection to serve; # the framework paginates it and stamps SEP-2549 cache hints exactly as it does for the constructor-provided resources, @@ -1407,16 +1430,49 @@ def configure_logging_level(request, session: nil) {} end - def list_tools(request) - page = paginate(@tools.values, cursor: cursor_from(request), page_size: @page_size, request: request, &:to_h) + def list_tools(request, server_context: nil) + tools = if @tools_list_handler + invoke_tools_list_handler(request, server_context) + else + @tools.values + end + + page = paginate(tools, cursor: cursor_from(request), page_size: @page_size, request: request, &:to_h) apply_cache_metadata({ tools: page[:items], nextCursor: page[:next_cursor] }.compact) end + # Calls the `tools_list_handler` block, forwarding `server_context:` only when the block opts in + # by declaring the keyword (the same rule `dispatch_optional_context_handler` applies). + def invoke_tools_list_handler(request, server_context) + if handler_declares_server_context?(@tools_list_handler) + @tools_list_handler.call(request, server_context: server_context) + else + @tools_list_handler.call(request) + end + end + + def resolve_tool(request, session:, related_request_id:, cancellation:, envelope:, auth_info:) + return tools[request[:name]] unless @tools_list_handler + + server_context = if handler_declares_server_context?(@tools_list_handler) + build_server_context( + request: request, + session: session, + related_request_id: related_request_id, + cancellation: cancellation, + envelope: envelope, + auth_info: auth_info, + ) + end + + invoke_tools_list_handler(request, server_context).find { |tool| tool.name_value == request[:name] } + end + def call_tool(request, instrumentation_data:, session: nil, related_request_id: nil, cancellation: nil, envelope: nil, auth_info: nil) tool_name = request[:name] - tool = tools[tool_name] + tool = resolve_tool(request, session: session, related_request_id: related_request_id, cancellation: cancellation, envelope: envelope, auth_info: auth_info) unless tool instrumentation_data.merge!(tool_name: tool_name, error: :tool_not_found) diff --git a/test/mcp/server_test.rb b/test/mcp/server_test.rb index 80460cc0..78d5318f 100644 --- a/test/mcp/server_test.rb +++ b/test/mcp/server_test.rb @@ -4789,6 +4789,88 @@ def server_context refute second_result.key?(:nextCursor) end + test "#tools_list_handler replaces the advertised tool collection" do + other = Tool.define(name: "other_tool", title: "Other", description: "Other") + @server.tools_list_handler { |_params| [other] } + + response = @server.handle({ jsonrpc: "2.0", method: "tools/list", id: 1 }) + + assert_equal(["other_tool"], response[:result][:tools].map { |tool| tool[:name] }) + end + + test "#tools_list_handler receives server_context when it opts in" do + public_tool = Tool.define(name: "public_tool", title: "Public", description: "Public") + admin_tool = Tool.define(name: "admin_tool", title: "Admin", description: "Admin") + @server.tools_list_handler do |_params, server_context:| + server_context[:admin] ? [public_tool, admin_tool] : [public_tool] + end + + @server.server_context = { admin: false } + member = @server.handle({ jsonrpc: "2.0", method: "tools/list", id: 1 }) + @server.server_context = { admin: true } + admin = @server.handle({ jsonrpc: "2.0", method: "tools/list", id: 2 }) + + assert_equal(["public_tool"], member[:result][:tools].map { |tool| tool[:name] }) + assert_equal(["public_tool", "admin_tool"], admin[:result][:tools].map { |tool| tool[:name] }) + end + + test "#tools_list_handler paginates and stamps cache hints on the returned collection" do + first = Tool.define(name: "first_tool", title: "First", description: "First") + second = Tool.define(name: "second_tool", title: "Second", description: "Second") + server = Server.new(name: "tools_list_handler_test", tools: [], page_size: 1, ttl_ms: 60_000) + server.tools_list_handler { |_params| [first, second] } + + response = server.handle({ jsonrpc: "2.0", method: "tools/list", id: 1 }) + + assert_equal(["first_tool"], response[:result][:tools].map { |tool| tool[:name] }) + assert_equal("1", response[:result][:nextCursor]) + assert_equal(60_000, response[:result][:ttlMs]) + end + + test "#tools_list_handler refuses a tools/call for a registered tool it leaves out" do + hidden = Tool.define(name: "hidden_tool", title: "Hidden", description: "Hidden") do + Tool::Response.new([{ type: "text", text: "ran" }]) + end + server = Server.new(name: "tools_list_handler_test", tools: [hidden]) + server.tools_list_handler { |_params| [] } + + response = server.handle({ jsonrpc: "2.0", method: "tools/call", id: 1, params: { name: "hidden_tool", arguments: {} } }) + + assert_nil(response[:result]) + assert_equal(-32602, response[:error][:code]) + assert_includes(response[:error][:data], "Tool not found: hidden_tool") + end + + test "#tools_list_handler lets tools/call run a tool that is not registered on the server" do + unregistered = Tool.define(name: "unregistered_tool", title: "Unregistered", description: "Unregistered") do + Tool::Response.new([{ type: "text", text: "ran" }]) + end + server = Server.new(name: "tools_list_handler_test", tools: []) + server.tools_list_handler { |_params| [unregistered] } + + response = server.handle({ jsonrpc: "2.0", method: "tools/call", id: 1, params: { name: "unregistered_tool", arguments: {} } }) + + assert_equal("ran", response[:result][:content][0][:text]) + end + + test "#tools_list_handler receives server_context on tools/call when it opts in" do + admin_tool = Tool.define(name: "admin_tool", title: "Admin", description: "Admin") do + Tool::Response.new([{ type: "text", text: "ran" }]) + end + @server.tools_list_handler do |_params, server_context:| + server_context[:admin] ? [admin_tool] : [] + end + request = { jsonrpc: "2.0", method: "tools/call", id: 1, params: { name: "admin_tool", arguments: {} } } + + @server.server_context = { admin: false } + member = @server.handle(request) + @server.server_context = { admin: true } + admin = @server.handle(request) + + assert_equal(-32602, member[:error][:code]) + assert_equal("ran", admin[:result][:content][0][:text]) + end + test "#handle tools/list returns all tools when page_size is not set" do response = @server.handle({ jsonrpc: "2.0", method: "tools/list", id: 1 }) result = response[:result]