Skip to content

Commit 6dfef81

Browse files
authored
Merge pull request #496 from koic/request_state_security
Add opt-in `requestState` sealing via `RequestStateSecurity`
2 parents b98b783 + e6b5a9b commit 6dfef81

6 files changed

Lines changed: 417 additions & 6 deletions

File tree

‎README.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,11 @@ It implements the Model Context Protocol specification, handling model context r
6060
which the modern lifecycle forbids. On the retried request the handler re-runs from the start and reads the answers via
6161
`server_context.input_responses` / `server_context.input_response(key)` and the echoed opaque `server_context.request_state`
6262
(deterministic replay; the server holds no memory between rounds). The SDK rejects issuance on legacy requests and returns `-32021`
63-
when an embedded request needs a client capability the request did not declare. Note that the echoed `requestState` arrives as
64-
client-controlled input; treat it accordingly
63+
when an embedded request needs a client capability the request did not declare. The echoed `requestState` arrives as
64+
client-controlled input: pass `MCP::Server::RequestStateSecurity.new(key:)` (a 32-byte key) via `Server.new(request_state_security:)` to
65+
have it sealed with AES-256-GCM and bound to a TTL plus the originating method, target, and arguments, all transparently to handlers.
66+
Multi-process deployments must share the key across workers; without `request_state_security:` the state crosses the wire exactly as
67+
the handler wrote it and protecting it is the handler author's responsibility
6568
- `ping` - Simple health check
6669
- `logging/setLevel` - Configures the minimum log level for the server
6770
- `tools/list` - Lists all registered tools and their schemas

‎conformance/server.rb‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,40 @@ def second_round(name)
575575
end
576576
end
577577

578+
class TestInputRequiredResultTamperedState < MCP::Tool
579+
tool_name "test_input_required_result_tampered_state"
580+
description "A tool whose sealed requestState rejects tampered echoes (SEP-2322)"
581+
582+
class << self
583+
# A tampered `requestState` never reaches this handler: the server-level unsealing rejects it with -32602
584+
# before dispatch, so the tool body is a plain MRTR flow.
585+
def call(server_context:, **_args)
586+
state = Mrtr.parse_state(server_context.request_state)
587+
confirmed = Mrtr.accepted_content(server_context.input_response("confirm"))
588+
589+
if state && state["kind"] == "tamper-check" && confirmed
590+
return MCP::Tool::Response.new([MCP::Content::Text.new("requestState integrity verified").to_h])
591+
end
592+
593+
MCP::Server::InputRequiredResult.new(
594+
input_requests: {
595+
confirm: {
596+
method: "elicitation/create",
597+
params: {
598+
message: "Confirm to continue",
599+
requestedSchema: {
600+
type: "object",
601+
properties: { ok: { type: "boolean" } },
602+
},
603+
},
604+
},
605+
},
606+
request_state: JSON.generate({ kind: "tamper-check", nonce: SecureRandom.hex(8) }),
607+
)
608+
end
609+
end
610+
end
611+
578612
class TestInputRequiredResultCapabilities < MCP::Tool
579613
tool_name "test_input_required_result_capabilities"
580614
description "A tool that only embeds input requests the client's declared capabilities can fulfill (SEP-2322)"
@@ -869,6 +903,7 @@ def build_server
869903
Tools::TestInputRequiredResultRequestState,
870904
Tools::TestInputRequiredResultMultipleInputs,
871905
Tools::TestInputRequiredResultMultiRound,
906+
Tools::TestInputRequiredResultTamperedState,
872907
Tools::TestInputRequiredResultCapabilities,
873908
Tools::TestStreamingElicitation,
874909
Tools::TestLoggingTool,
@@ -882,6 +917,10 @@ def build_server
882917
],
883918
resources: resources,
884919
resource_templates: resource_templates,
920+
# A per-boot random key is enough for conformance: every MRTR round trip completes
921+
# within one server process, and sealing keeps the fixture's `requestState` values
922+
# tamper-evident without any tool-level verification code.
923+
request_state_security: MCP::Server::RequestStateSecurity.new(key: SecureRandom.bytes(32)),
885924
capabilities: {
886925
tools: { listChanged: true },
887926
prompts: { listChanged: true },

‎lib/mcp/server.rb‎

Lines changed: 78 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
require_relative "server/capabilities"
1313
require_relative "server/input_required_result"
1414
require_relative "server/pagination"
15+
require_relative "server/request_state_security"
1516
require_relative "server/transports"
1617

1718
module MCP
@@ -145,7 +146,7 @@ class ValidationError < StandardError; end
145146
CACHE_SCOPES = ["public", "private"].freeze
146147

147148
attr_accessor :description, :icons, :name, :title, :version, :website_url, :instructions, :tools, :prompts, :resource_templates, :server_context, :configuration, :capabilities, :transport, :logging_message_notification
148-
attr_reader :resources, :page_size, :client_capabilities, :ttl_ms, :cache_scope
149+
attr_reader :resources, :page_size, :client_capabilities, :ttl_ms, :cache_scope, :request_state_security
149150

150151
def initialize(
151152
description: nil,
@@ -165,6 +166,7 @@ def initialize(
165166
page_size: nil,
166167
ttl_ms: nil,
167168
cache_scope: nil,
169+
request_state_security: nil,
168170
transport: nil
169171
)
170172
@description = description
@@ -184,6 +186,7 @@ def initialize(
184186
self.page_size = page_size
185187
self.ttl_ms = ttl_ms
186188
self.cache_scope = cache_scope
189+
@request_state_security = request_state_security
187190
@configuration = MCP.configuration.merge(configuration)
188191
@client = nil
189192
@client_protocol_version = nil
@@ -606,6 +609,8 @@ def handle_request(request, method, session: nil, related_request_id: nil)
606609
session.configure_logging(request_logging) if request_logging.valid_level?
607610
end
608611

612+
params = unseal_request_state(params, method: method) if @request_state_security
613+
609614
result = case method
610615
when Methods::INITIALIZE
611616
init(params, session: session)
@@ -640,7 +645,7 @@ def handle_request(request, method, session: nil, related_request_id: nil)
640645
# Runs after the cancellation check so a cancelled request stays suppressed
641646
# instead of turning into a gate error response.
642647
if result.is_a?(InputRequiredResult)
643-
result = serialize_input_required_result(result, envelope: envelope, request: params)
648+
result = serialize_input_required_result(result, envelope: envelope, request: params, method: method)
644649
end
645650

646651
# SEP-2322 makes `resultType` REQUIRED on every result a 2026-07-28 server returns;
@@ -718,7 +723,7 @@ def lift_request_envelope(params, method:, session:)
718723
# a final result. The capability gate enforces the SEP-2575 rule that servers MUST NOT rely on
719724
# (or embed requests for) capabilities the client did not declare, and reports every missing capability at
720725
# once so the client sees the full set.
721-
def serialize_input_required_result(result, envelope:, request:)
726+
def serialize_input_required_result(result, envelope:, request:, method:)
722727
if envelope.nil?
723728
raise RequestHandlerError.new(
724729
"input_required results require the 2026-07-28 stateless lifecycle (SEP-2322)",
@@ -731,7 +736,76 @@ def serialize_input_required_result(result, envelope:, request:)
731736
raise MissingRequiredClientCapabilityError.new(missing, request) unless missing.empty?
732737

733738
add_instrumentation_data(input_required: true)
734-
result.to_h
739+
serialized = result.to_h
740+
741+
if @request_state_security && serialized[:requestState]
742+
serialized = serialized.merge(requestState: @request_state_security.seal(
743+
serialized[:requestState],
744+
method: method,
745+
target: mrtr_target(request),
746+
arguments_digest: mrtr_arguments_digest(request),
747+
))
748+
end
749+
750+
serialized
751+
end
752+
753+
# Methods whose results may be `input_required` and whose retried requests carry
754+
# `inputResponses`/`requestState` (SEP-2322).
755+
MRTR_METHODS = [Methods::TOOLS_CALL, Methods::PROMPTS_GET, Methods::RESOURCES_READ].freeze
756+
757+
# Replaces a sealed client-echoed `requestState` with its verified plaintext before dispatch,
758+
# so handlers always read the state they wrote. A tampered, expired, or cross-request token is
759+
# rejected as invalid params, matching the Python SDK's "Invalid or expired requestState" behavior.
760+
def unseal_request_state(params, method:)
761+
return params unless MRTR_METHODS.include?(method)
762+
return params unless params.is_a?(Hash)
763+
764+
sealed = params[:requestState] || params["requestState"]
765+
return params unless sealed
766+
767+
plaintext = @request_state_security.unseal(
768+
sealed,
769+
method: method,
770+
target: mrtr_target(params),
771+
arguments_digest: mrtr_arguments_digest(params),
772+
)
773+
key = params.key?("requestState") ? "requestState" : :requestState
774+
params.merge(key => plaintext)
775+
rescue RequestStateSecurity::InvalidStateError => e
776+
raise RequestHandlerError.new(
777+
"Invalid or expired requestState",
778+
params,
779+
error_type: :invalid_params,
780+
error_code: JsonRpcHandler::ErrorCode::INVALID_PARAMS,
781+
original_error: e,
782+
)
783+
end
784+
785+
def mrtr_target(params)
786+
return "" unless params.is_a?(Hash)
787+
788+
params[:name] || params["name"] || params[:uri] || params["uri"] || ""
789+
end
790+
791+
# Digest of the originating arguments, binding a sealed state to retries of
792+
# the same call with the same inputs. Keys are stringified and sorted recursively
793+
# so symbol/string parses of identical JSON digest identically.
794+
def mrtr_arguments_digest(params)
795+
arguments = params.is_a?(Hash) ? params[:arguments] || params["arguments"] : nil
796+
OpenSSL::Digest::SHA256.hexdigest(canonical_json(arguments || {}))
797+
end
798+
799+
def canonical_json(value)
800+
case value
801+
when Hash
802+
pairs = value.map { |key, nested| [key.to_s, nested] }.sort_by(&:first)
803+
"{#{pairs.map { |key, nested| "#{key.to_json}:#{canonical_json(nested)}" }.join(",")}}"
804+
when Array
805+
"[#{value.map { |element| canonical_json(element) }.join(",")}]"
806+
else
807+
value.to_json
808+
end
735809
end
736810

737811
# Extracts the SEP-2322 retry fields a client sends when re-issuing a request:
Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,131 @@
1+
# frozen_string_literal: true
2+
3+
require "json"
4+
require "openssl"
5+
6+
module MCP
7+
class Server
8+
# Opt-in protection for the SEP-2322 `requestState` echo. The opaque continuation string leaves the server,
9+
# sits in the client's hands, and comes back as client-controlled input, so it must be treated like
10+
# any other untrusted data. Sealing encrypts the state with AES-256-GCM (clients cannot read it) and binds
11+
# a claims envelope that unsealing verifies fail-closed:
12+
#
13+
# - `exp`: a TTL window (re-sealed each round)
14+
# - `m` / `t`: the originating method and target (tool/prompt name or resource URI)
15+
# - `a`: a digest of the originating arguments, so the state only resumes the same call with the same inputs
16+
# - `aud`: an optional audience, so tokens cannot cross servers sharing a key
17+
#
18+
# Pass an instance via `Server.new(request_state_security:)` and the seal/unseal happens transparently;
19+
# handlers keep reading plaintext through `server_context.request_state`. Without it, the state crosses
20+
# the wire exactly as the handler wrote it (the author's responsibility, matching the Python SDK's low-level Server).
21+
# The key must be shared across workers in multi-process
22+
#
23+
# deployments; a per-process random key makes retries that land on another worker fail with an invalid-state error,
24+
# forcing clients to restart the flow.
25+
#
26+
# The token format is `v1.<base64url(iv || ciphertext || tag)>`, with the version prefix bound as GCM associated data,
27+
# following the Python SDK's `AESGCMRequestStateCodec`.
28+
class RequestStateSecurity
29+
class InvalidStateError < StandardError; end
30+
31+
VERSION_PREFIX = "v1."
32+
KEY_BYTES = 32
33+
IV_BYTES = 12
34+
TAG_BYTES = 16
35+
DEFAULT_TTL = 300
36+
37+
def initialize(key:, ttl: DEFAULT_TTL, audience: nil)
38+
unless key.is_a?(String) && key.bytesize == KEY_BYTES
39+
raise ArgumentError, "key must be a #{KEY_BYTES}-byte String"
40+
end
41+
unless ttl.is_a?(Numeric) && ttl.positive?
42+
raise ArgumentError, "ttl must be a positive number of seconds"
43+
end
44+
45+
@key = key.dup.force_encoding(Encoding::BINARY).freeze
46+
@ttl = ttl
47+
@audience = audience
48+
end
49+
50+
# Seals a plaintext state into an opaque token bound to the originating request.
51+
def seal(state, method:, target:, arguments_digest:)
52+
claims = {
53+
v: 1,
54+
exp: Time.now.to_i + @ttl,
55+
m: method,
56+
t: target,
57+
a: arguments_digest,
58+
aud: @audience,
59+
s: state,
60+
}.compact
61+
62+
cipher = OpenSSL::Cipher.new("aes-256-gcm").encrypt
63+
cipher.key = @key
64+
iv = cipher.random_iv
65+
cipher.auth_data = VERSION_PREFIX
66+
ciphertext = cipher.update(JSON.generate(claims)) + cipher.final
67+
68+
VERSION_PREFIX + base64url_encode(iv + ciphertext + cipher.auth_tag)
69+
end
70+
71+
# Unseals a client-echoed token and verifies every claim, failing closed with
72+
# `InvalidStateError` on tampering, expiry, or a claims mismatch.
73+
def unseal(sealed, method:, target:, arguments_digest:)
74+
unless sealed.is_a?(String) && sealed.start_with?(VERSION_PREFIX)
75+
raise InvalidStateError, "malformed token"
76+
end
77+
78+
blob = base64url_decode(sealed.delete_prefix(VERSION_PREFIX))
79+
raise InvalidStateError, "malformed token" if blob.bytesize < IV_BYTES + TAG_BYTES
80+
81+
iv = blob.byteslice(0, IV_BYTES)
82+
tag = blob.byteslice(-TAG_BYTES, TAG_BYTES)
83+
ciphertext = blob.byteslice(IV_BYTES, blob.bytesize - IV_BYTES - TAG_BYTES)
84+
85+
cipher = OpenSSL::Cipher.new("aes-256-gcm").decrypt
86+
cipher.key = @key
87+
cipher.iv = iv
88+
cipher.auth_tag = tag
89+
cipher.auth_data = VERSION_PREFIX
90+
plaintext = begin
91+
cipher.update(ciphertext) + cipher.final
92+
rescue OpenSSL::Cipher::CipherError
93+
raise InvalidStateError, "authentication failed"
94+
end
95+
96+
claims = begin
97+
JSON.parse(plaintext, symbolize_names: true)
98+
rescue JSON::ParserError
99+
raise InvalidStateError, "malformed claims"
100+
end
101+
102+
verify!(claims, method: method, target: target, arguments_digest: arguments_digest)
103+
claims[:s]
104+
end
105+
106+
private
107+
108+
def verify!(claims, method:, target:, arguments_digest:)
109+
raise InvalidStateError, "unsupported version" unless claims[:v] == 1
110+
raise InvalidStateError, "expired" unless claims[:exp].is_a?(Integer) && Time.now.to_i <= claims[:exp]
111+
raise InvalidStateError, "method mismatch" unless claims[:m] == method
112+
raise InvalidStateError, "target mismatch" unless claims[:t] == target
113+
raise InvalidStateError, "arguments mismatch" unless claims[:a] == arguments_digest
114+
raise InvalidStateError, "audience mismatch" unless claims[:aud] == @audience
115+
raise InvalidStateError, "missing state" unless claims[:s].is_a?(String)
116+
end
117+
118+
def base64url_encode(data)
119+
[data].pack("m0").tr("+/", "-_").delete("=")
120+
end
121+
122+
def base64url_decode(encoded)
123+
padded = encoded.tr("-_", "+/")
124+
padded += "=" * ((4 - padded.length % 4) % 4)
125+
padded.unpack1("m0")
126+
rescue ArgumentError
127+
raise InvalidStateError, "malformed token"
128+
end
129+
end
130+
end
131+
end

0 commit comments

Comments
 (0)