Skip to content

Commit e6b5a9b

Browse files
committed
Add opt-in requestState sealing via RequestStateSecurity
## Motivation and Context The SEP-2322 `requestState` continuation string leaves the server, sits in the client's hands, and comes back as client-controlled input. Without protection a client can read the server's continuation state, tamper with it (for example forging an already-answered elicitation), or replay a state issued for one call against another tool, other arguments, or another server. The multi-round-trip documentation of the Python SDK is explicit that the echo must be treated as untrusted input; its high-level server seals the state by default via `RequestStateBoundary`. New `MCP::Server::RequestStateSecurity` (OpenSSL standard library only) brings that protection to this SDK as an opt-in: - `seal` encrypts the plaintext state with AES-256-GCM (clients cannot read it, not merely verify it) inside a claims envelope binding an expiry window (`ttl:`, default 300 seconds, re-sealed each round), the originating method and target (tool/prompt name or resource URI), a digest of the originating arguments (stringified and sorted recursively, so symbol/string parses of identical JSON digest identically), and an optional `audience:`. The token format is `v1.<base64url(iv || ciphertext || tag)>` with the version prefix bound as GCM associated data, following the Python SDK's `AESGCMRequestStateCodec`. - `unseal` verifies every claim fail-closed and raises `InvalidStateError` on tampering, expiry, or any mismatch. Passing an instance via `Server.new(request_state_security:)` makes the seal/unseal transparent: issuance seals the `requestState` of an outgoing `input_required` result, and dispatch unseals the echoed token for `tools/call`, `prompts/get`, and `resources/read` before any handler runs, so `server_context.request_state` always reads the plaintext the handler wrote. A tampered, expired, or cross-call echo is rejected as `-32602` with "Invalid or expired requestState", matching the Python SDK's frozen error. Without the option the state crosses the wire exactly as the handler wrote it (the Python low-level Server behavior); the README documents that this is then the handler author's responsibility, and that multi-process deployments must share the key across workers. The conformance fixture opts in with a random per-boot key, both to dogfood the feature and because the tampered-state scenario of the 2026-07-28 conformance requirements retries an MRTR request with a corrupted `requestState` and requires a JSON-RPC error; without integrity-checked state the fixture cannot detect the corruption. Every MRTR round trip completes within one server process, so no key persistence is needed. Sealing is transparent to the fixture tools, whose `requestState` plaintext round-trips unchanged, and the new `test_input_required_result_tampered_state` tool is therefore a plain MRTR elicitation flow; the tampered echo is rejected with `-32602` by the server-level unsealing before dispatch ever reaches it. Refs #382. ## How Has This Been Tested? New `test/mcp/server/request_state_security_test.rb` covers constructor validation, the seal/unseal round trip (opaque `v1.` token, plaintext not visible), expiry via time travel, fail-closed rejection of method/target/digest/audience mismatches, tampered and malformed tokens, and tokens sealed under a different key. New tests in `test/mcp/server_test.rb` drive `Server#handle` with the modern envelope: transparent sealing on issuance and plaintext restoration on the retry leg, `-32602` for tampered echoes and for echoes replayed against different arguments, and the pass-through default when `request_state_security:` is not set. Against the fixture server at `--spec-version 2026-07-28` (run with `@modelcontextprotocol/conformance@alpha`; the 2026-07-28 scenarios are not yet in a stable conformance release), `sep-2322-reject-tampered-state` reports SUCCESS, and the other 13 `input-required-result-*` scenarios stay green with sealing active, confirming that sealed states round-trip through the suite's retries without false rejections (the seal binds `method`, target, and an arguments digest, and the suite echoes all three unchanged). The `--requirements 2025-11-25` server leg still passes. ## Breaking Changes None. The feature is opt-in via a new keyword argument that defaults to `nil`, in which case behavior is byte-identical to before.
1 parent 4fac357 commit e6b5a9b

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
@@ -594,6 +597,8 @@ def handle_request(request, method, session: nil, related_request_id: nil)
594597
session.configure_logging(request_logging) if request_logging.valid_level?
595598
end
596599

600+
params = unseal_request_state(params, method: method) if @request_state_security
601+
597602
result = case method
598603
when Methods::INITIALIZE
599604
init(params, session: session)
@@ -628,7 +633,7 @@ def handle_request(request, method, session: nil, related_request_id: nil)
628633
# Runs after the cancellation check so a cancelled request stays suppressed
629634
# instead of turning into a gate error response.
630635
if result.is_a?(InputRequiredResult)
631-
result = serialize_input_required_result(result, envelope: envelope, request: params)
636+
result = serialize_input_required_result(result, envelope: envelope, request: params, method: method)
632637
end
633638

634639
# SEP-2322 makes `resultType` REQUIRED on every result a 2026-07-28 server returns;
@@ -707,7 +712,7 @@ def lift_request_envelope(params, method:, session:)
707712
# a final result. The capability gate enforces the SEP-2575 rule that servers MUST NOT rely on
708713
# (or embed requests for) capabilities the client did not declare, and reports every missing capability at
709714
# once so the client sees the full set.
710-
def serialize_input_required_result(result, envelope:, request:)
715+
def serialize_input_required_result(result, envelope:, request:, method:)
711716
if envelope.nil?
712717
raise RequestHandlerError.new(
713718
"input_required results require the 2026-07-28 stateless lifecycle (SEP-2322)",
@@ -720,7 +725,76 @@ def serialize_input_required_result(result, envelope:, request:)
720725
raise MissingRequiredClientCapabilityError.new(missing, request) unless missing.empty?
721726

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

726800
# 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)