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
5 changes: 3 additions & 2 deletions lib/mcp/client/http.rb
Original file line number Diff line number Diff line change
Expand Up @@ -792,15 +792,16 @@ def session_headers

# Per SEP-2243, mirror the JSON-RPC method and target name/uri into HTTP headers so intermediaries
# can route and inspect requests without parsing the body. `Mcp-Name` comes from `params.name`
# (tools, prompts) or, when absent, `params.uri` (resources).
# (tools, prompts) or, when absent, `params.uri` (resources). A `resources/read` is named by its `uri`
# whatever else its `params` carry, since that is the member the server checks the header against.
#
# https://modelcontextprotocol.io/specification/draft/basic/transports/streamable-http#request-metadata
def request_metadata_headers(method, params)
return {} unless method

metadata_headers = { METHOD_HEADER => method }
if params.is_a?(Hash)
name = params[:name] || params["name"]
name = params[:name] || params["name"] unless method == MCP::Methods::RESOURCES_READ
name = params[:uri] || params["uri"] unless name.is_a?(String)
metadata_headers[NAME_HEADER] = encode_header_value(name) if name.is_a?(String)

Expand Down
12 changes: 8 additions & 4 deletions lib/mcp/server.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1079,7 +1079,7 @@ def serialize_input_required_result(result, instrumentation_data:, envelope:, re
serialized = serialized.merge(requestState: @request_state_security.seal(
serialized[:requestState],
method: method,
target: mrtr_target(request),
target: mrtr_target(request, method: method),
arguments_digest: mrtr_arguments_digest(request),
))
end
Expand Down Expand Up @@ -1207,7 +1207,7 @@ def unseal_request_state(params, method:)
plaintext = @request_state_security.unseal(
sealed,
method: method,
target: mrtr_target(params),
target: mrtr_target(params, method: method),
arguments_digest: mrtr_arguments_digest(params),
)
key = params.key?("requestState") ? "requestState" : :requestState
Expand All @@ -1222,10 +1222,14 @@ def unseal_request_state(params, method:)
)
end

def mrtr_target(params)
# What a sealed state is bound to besides the method and the arguments: the resource URI of a `resources/read`,
# the tool or prompt name otherwise. The member is fixed per method, so a `name` added to the `params` of
# a `resources/read` cannot stand in for the URI and carry a state over to another resource.
def mrtr_target(params, method:)
return "" unless params.is_a?(Hash)

params[:name] || params["name"] || params[:uri] || params["uri"] || ""
member = method == Methods::RESOURCES_READ ? "uri" : "name"
params[member.to_sym] || params[member] || ""
end

# Digest of the originating arguments, binding a sealed state to retries of
Expand Down
21 changes: 14 additions & 7 deletions lib/mcp/server/transports/streamable_http_transport.rb
Original file line number Diff line number Diff line change
Expand Up @@ -451,8 +451,15 @@ class StreamWriteTimeoutError < IOError; end
# protected out of the box; non-loopback deployments widen the list via `allowed_hosts:`.
DEFAULT_LOOPBACK_HOSTS = ["127.0.0.1", "::1", "localhost"].freeze

# JSON-RPC methods whose target name is mirrored into the `Mcp-Name` header (SEP-2575).
NAME_BEARING_METHODS = [Methods::TOOLS_CALL, Methods::RESOURCES_READ, Methods::PROMPTS_GET].freeze
# JSON-RPC methods whose target is mirrored into the `Mcp-Name` header (SEP-2575), with the `params` member
# that names it. The member is fixed per method: a `resources/read` is named by its `uri` whatever else
# its `params` carry, so a `name` added to them cannot stand in for the URI the header is checked against.
NAME_MEMBER_BY_METHOD = {
Methods::TOOLS_CALL => :name,
Methods::RESOURCES_READ => :uri,
Methods::PROMPTS_GET => :name,
}.freeze
NAME_BEARING_METHODS = NAME_MEMBER_BY_METHOD.keys.freeze

# Maps broadcast notification methods to the `SubscriptionFilter` field that opts in to them on
# a `subscriptions/listen` stream (SEP-2575). `notifications/resources/updated` is matched by URI
Expand Down Expand Up @@ -1144,9 +1151,8 @@ def handle_modern(request, header_version, body_string: nil)
end

# Enforces the SEP-2575 header/body match rules (`-32020`, HTTP 400): the `MCP-Protocol-Version` header
# MUST match the `_meta`-carried version, and the `Mcp-Method` / `Mcp-Name` mirror headers MUST match
# the body when sent. Absent mirror headers are tolerated for interoperability while other SDK serving stacks
# converge on enforcement.
# MUST match the `_meta`-carried version, and the `Mcp-Method` / `Mcp-Name` mirror headers MUST be present
# and match the body.
def validate_modern_headers(request, body, header_version)
params = body[:params]
meta_version = params.is_a?(Hash) && params[:_meta].is_a?(Hash) ? params.dig(:_meta, :"io.modelcontextprotocol/protocolVersion") : nil
Expand Down Expand Up @@ -1176,8 +1182,9 @@ def validate_modern_headers(request, body, header_version)
)
end

if NAME_BEARING_METHODS.include?(body[:method])
body_name = params.is_a?(Hash) ? params[:name] || params[:uri] : nil
name_member = NAME_MEMBER_BY_METHOD[body[:method]]
if name_member
body_name = params.is_a?(Hash) ? params[name_member] : nil
name_header = request.env["HTTP_MCP_NAME"]
if body_name
if name_header.to_s.empty?
Expand Down
19 changes: 19 additions & 0 deletions test/mcp/client/http_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,25 @@ def test_mcp_name_header_falls_back_to_uri_for_resources_read
client.send_request(request: request)
end

def test_mcp_name_header_is_the_uri_of_a_resources_read_whatever_name_the_params_carry
request = {
jsonrpc: "2.0",
id: "test_id",
method: "resources/read",
params: { uri: "file:///README.md", name: "readme" },
}

stub_request(:post, url).with(
headers: { "Mcp-Method" => "resources/read", "Mcp-Name" => "file:///README.md" },
).to_return(
status: 200,
headers: { "Content-Type" => "application/json" },
body: { jsonrpc: "2.0", result: {} }.to_json,
)

client.send_request(request: request)
end

def test_mcp_method_and_name_headers_for_prompts_get
request = {
jsonrpc: "2.0",
Expand Down
15 changes: 15 additions & 0 deletions test/mcp/server/transports/streamable_http_transport_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7291,6 +7291,21 @@ def close
assert_equal(-32020, JSON.parse(mismatched[2][0]).dig("error", "code"))
end

test "modern POST checks Mcp-Name against the uri of a resources/read whatever name the params carry" do
matched = @transport.handle_request(modern_rack_request(
modern_body("resources/read", { uri: "file:///a.txt", name: "file:///b.txt" }),
name_header: "file:///a.txt",
))
mismatched = @transport.handle_request(modern_rack_request(
modern_body("resources/read", { uri: "file:///a.txt", name: "file:///b.txt" }),
name_header: "file:///b.txt",
))

assert_equal 200, matched[0]
assert_equal 400, mismatched[0]
assert_equal(-32020, JSON.parse(mismatched[2][0]).dig("error", "code"))
end

test "modern POST rejects an Mcp-Session-Id header" do
response = @transport.handle_request(modern_rack_request(
modern_body("ping", {}),
Expand Down
21 changes: 21 additions & 0 deletions test/mcp/server_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,27 @@ class ServerTest < ActiveSupport::TestCase
assert_equal JsonRpcHandler::ErrorCode::INVALID_PARAMS, cross_call.dig(:error, :code)
end

test "#handle rejects a requestState of one resource on another whatever name the params carry" do
security = Server::RequestStateSecurity.new(key: "k" * 32)
server = Server.new(name: "mrtr_test", request_state_security: security)
server.resources_read_handler do |params, server_context:|
if server_context.request_state
[{ uri: params[:uri], text: "contents" }]
else
Server::InputRequiredResult.new(request_state: "confirmed")
end
end

first = server.handle(modern_request("resources/read", { uri: "doc://public", name: "same" }))
sealed = first.dig(:result, :requestState)
same_resource = server.handle(modern_request("resources/read", { uri: "doc://public", name: "other", requestState: sealed }))
other_resource = server.handle(modern_request("resources/read", { uri: "doc://secret", name: "same", requestState: sealed }))

refute_nil same_resource[:result]
assert_equal JsonRpcHandler::ErrorCode::INVALID_PARAMS, other_resource.dig(:error, :code)
assert_equal "Invalid or expired requestState", other_resource.dig(:error, :message)
end

test "#handle passes requestState through untouched without request_state_security" do
server = Server.new(name: "mrtr_test", tools: [])
seen_state = nil
Expand Down