Class: MCP::ServerContext
- Inherits:
-
Object
- Object
- MCP::ServerContext
- Defined in:
- lib/mcp/server_context.rb
Instance Attribute Summary collapse
-
#auth_info ⇒ Object
readonly
The verified
MCP::Server::OAuth::AccessTokenfor the current request, or nil when the request was not bearer-authenticated. -
#cancellation ⇒ Object
readonly
Returns the value of attribute cancellation.
-
#envelope ⇒ Object
readonly
The SEP-2575 per-request envelope (
MCP::RequestEnvelope) when the request was classified as modern;nilon legacy requests. -
#input_responses ⇒ Object
readonly
SEP-2322 multi round-trip retry fields, present when the client re-issued the request after an
input_requiredresult:input_responsesmaps the keys of the earlierinputRequeststo the client's answers, andrequest_stateis the opaque continuation string echoed back byte-exactly. -
#request_state ⇒ Object
readonly
SEP-2322 multi round-trip retry fields, present when the client re-issued the request after an
input_requiredresult:input_responsesmaps the keys of the earlierinputRequeststo the client's answers, andrequest_stateis the opaque continuation string echoed back byte-exactly.
Instance Method Summary collapse
-
#authenticated? ⇒ Boolean
Whether the current request was bearer-authenticated.
- #cancelled? ⇒ Boolean
-
#client_capabilities ⇒ Object
Client capabilities for the current request, with the same envelope-first resolution as #client_info.
-
#client_info ⇒ Object
Client identity for the current request.
-
#close_sse_stream ⇒ Object
Closes the SSE connection carrying the current request's stream without ending the request (SEP-1699): the client reconnects with
Last-Event-IDafter the transport'sretry_interval, and the messages the handler emits meanwhile are replayed to it. -
#close_standalone_sse_stream ⇒ Object
Closes the session's standalone GET stream the same way, so the client polls for server-initiated messages.
-
#create_form_elicitation(**kwargs) ⇒ Object
Delegates to the session so the request is scoped to the originating client.
-
#create_sampling_message(**kwargs) ⇒ Object
deprecated
Deprecated.
MCP Sampling (
sampling/createMessage) is deprecated as of MCP protocol version 2026-07-28 (SEP-2577). Use direct LLM provider APIs instead. -
#create_url_elicitation(**kwargs) ⇒ Object
Delegates to the session so the request is scoped to the originating client.
-
#initialize(context, progress:, notification_target:, related_request_id: nil, cancellation: nil, envelope: nil, input_responses: nil, request_state: nil, auth_info: nil) ⇒ ServerContext
constructor
A new instance of ServerContext.
-
#input_response(key) ⇒ Object
Reads one entry of #input_responses by its
inputRequestskey, tolerating symbol or string keys. -
#list_roots(timeout: nil) ⇒ Object
deprecated
Deprecated.
MCP Roots (
roots/listandnotifications/roots/list_changed) is deprecated as of MCP protocol version 2026-07-28 (SEP-2577). Use tool parameters, resource URIs, server configuration, or environment variables instead. -
#method_missing(name, *args, **kwargs, &block) ⇒ Object
Forward arguments explicitly with
*args, **kwargs, &blockrather than the...forwarding syntax. -
#modern? ⇒ Boolean
Whether the current request follows the stateless modern lifecycle (SEP-2575).
-
#notify_elicitation_complete(**kwargs) ⇒ Object
Delegates to the session so the notification is scoped to the originating client.
-
#notify_log_message(data:, level:, logger: nil) ⇒ Object
deprecated
Deprecated.
MCP Logging (
logging/setLevelandnotifications/message) is deprecated as of MCP protocol version 2026-07-28 (SEP-2577). Use stderr or OpenTelemetry instead. -
#notify_resources_updated(uri:) ⇒ Object
Sends a resource updated notification scoped to the originating session.
-
#ping(timeout: nil) ⇒ Hash
Sends a
pingrequest to the originating client to verify it is still responsive. -
#protocol_version ⇒ Object
The protocol version the current request was made with.
- #raise_if_cancelled! ⇒ Object
-
#report_progress(progress, total: nil, message: nil) ⇒ Object
Reports progress for the current tool operation.
-
#require_client_capability!(*path) ⇒ Object
Guards the current request on a declared client capability (SEP-2575).
-
#require_scopes!(*scopes) ⇒ Object
Guards the current operation on OAuth scopes the token must carry, for authorization decisions finer-grained than the transport-wide
required_scopes. - #respond_to_missing?(name, include_private = false) ⇒ Boolean
Constructor Details
#initialize(context, progress:, notification_target:, related_request_id: nil, cancellation: nil, envelope: nil, input_responses: nil, request_state: nil, auth_info: nil) ⇒ ServerContext
Returns a new instance of ServerContext.
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/mcp/server_context.rb', line 22 def initialize(context, progress:, notification_target:, related_request_id: nil, cancellation: nil, envelope: nil, input_responses: nil, request_state: nil, auth_info: nil) @context = context @progress = progress @notification_target = notification_target @related_request_id = @cancellation = cancellation @envelope = envelope @input_responses = input_responses @request_state = request_state @auth_info = auth_info end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, **kwargs, &block) ⇒ Object
Forward arguments explicitly with *args, **kwargs, &block rather than the ... forwarding syntax.
The gem supports Ruby 2.7.0 (see required_ruby_version), but RuboCop's Parser backend only runs on Ruby 2.7.8,
so leading-argument forwarding like def method_missing(name, ...) is allowed by the linter even though it
raises a SyntaxError on Ruby 2.7.0 through 2.7.2 (it was added in Ruby 2.7.3). Explicit forwarding keeps
this method loadable on Ruby 2.7.0.
280 281 282 283 284 285 286 |
# File 'lib/mcp/server_context.rb', line 280 def method_missing(name, *args, **kwargs, &block) if @context.respond_to?(name) @context.public_send(name, *args, **kwargs, &block) else super end end |
Instance Attribute Details
#auth_info ⇒ Object (readonly)
The verified MCP::Server::OAuth::AccessToken for the current request, or nil when the request was not bearer-authenticated.
This reader is the canonical accessor; when the underlying context is a Hash the same value is also reachable as server_context[:auth_info].
20 21 22 |
# File 'lib/mcp/server_context.rb', line 20 def auth_info @auth_info end |
#cancellation ⇒ Object (readonly)
Returns the value of attribute cancellation.
5 6 7 |
# File 'lib/mcp/server_context.rb', line 5 def cancellation @cancellation end |
#envelope ⇒ Object (readonly)
The SEP-2575 per-request envelope (MCP::RequestEnvelope) when the request was classified as modern;
nil on legacy requests.
9 10 11 |
# File 'lib/mcp/server_context.rb', line 9 def envelope @envelope end |
#input_responses ⇒ Object (readonly)
SEP-2322 multi round-trip retry fields, present when the client re-issued the request after
an input_required result: input_responses maps the keys of the earlier inputRequests to
the client's answers, and request_state is the opaque continuation string echoed back byte-exactly.
Both are nil on a first-round request. Only handlers that opt in to server_context: can read them
(the same access model as the envelope readers).
16 17 18 |
# File 'lib/mcp/server_context.rb', line 16 def input_responses @input_responses end |
#request_state ⇒ Object (readonly)
SEP-2322 multi round-trip retry fields, present when the client re-issued the request after
an input_required result: input_responses maps the keys of the earlier inputRequests to
the client's answers, and request_state is the opaque continuation string echoed back byte-exactly.
Both are nil on a first-round request. Only handlers that opt in to server_context: can read them
(the same access model as the envelope readers).
16 17 18 |
# File 'lib/mcp/server_context.rb', line 16 def request_state @request_state end |
Instance Method Details
#authenticated? ⇒ Boolean
Whether the current request was bearer-authenticated.
97 98 99 |
# File 'lib/mcp/server_context.rb', line 97 def authenticated? !@auth_info.nil? end |
#cancelled? ⇒ Boolean
42 43 44 |
# File 'lib/mcp/server_context.rb', line 42 def cancelled? !!@cancellation&.cancelled? end |
#client_capabilities ⇒ Object
Client capabilities for the current request, with the same envelope-first resolution as #client_info.
65 66 67 68 69 |
# File 'lib/mcp/server_context.rb', line 65 def client_capabilities return @envelope.client_capabilities if @envelope @notification_target.client_capabilities if @notification_target.respond_to?(:client_capabilities) end |
#client_info ⇒ Object
Client identity for the current request. Modern requests carry it in the _meta envelope;
legacy sessions fall back to the state stored by initialize. The envelope always wins
because servers MUST NOT infer identity from prior requests.
58 59 60 61 62 |
# File 'lib/mcp/server_context.rb', line 58 def client_info return @envelope.client_info if @envelope @notification_target.client if @notification_target.respond_to?(:client) end |
#close_sse_stream ⇒ Object
Closes the SSE connection carrying the current request's stream without ending the request (SEP-1699):
the client reconnects with Last-Event-ID after the transport's retry_interval, and the messages
the handler emits meanwhile are replayed to it. Use it to let a long-running operation go on without
a connection held open for it. Returns true when a connection was closed and false when there was none to close:
a transport without an event store, a client that negotiated a protocol version before 2025-11-25,
a request answered as JSON, or a connection closed already.
163 164 165 166 167 |
# File 'lib/mcp/server_context.rb', line 163 def close_sse_stream return false unless @related_request_id && @notification_target.respond_to?(:close_sse_stream) @notification_target.close_sse_stream(related_request_id: @related_request_id) end |
#close_standalone_sse_stream ⇒ Object
Closes the session's standalone GET stream the same way, so the client polls for server-initiated messages.
170 171 172 173 174 |
# File 'lib/mcp/server_context.rb', line 170 def close_standalone_sse_stream return false unless @notification_target.respond_to?(:close_standalone_sse_stream) @notification_target.close_standalone_sse_stream end |
#create_form_elicitation(**kwargs) ⇒ Object
Delegates to the session so the request is scoped to the originating client.
Falls back to @context (via method_missing) when @notification_target
does not support elicitation.
The originating request id is stamped as a non-overridable
related_request_id, as with create_sampling_message (SEP-2260).
240 241 242 243 244 245 246 247 248 |
# File 'lib/mcp/server_context.rb', line 240 def create_form_elicitation(**kwargs) if @notification_target.respond_to?(:create_form_elicitation) @notification_target.create_form_elicitation(**kwargs, related_request_id: @related_request_id) elsif @context.respond_to?(:create_form_elicitation) @context.create_form_elicitation(**kwargs, related_request_id: @related_request_id) else raise NoMethodError, "undefined method 'create_form_elicitation' for #{self}" end end |
#create_sampling_message(**kwargs) ⇒ Object
MCP Sampling (sampling/createMessage) is deprecated as of
MCP protocol version 2026-07-28 (SEP-2577). Use direct LLM provider
APIs instead.
Delegates to the session so the request is scoped to the originating client.
Falls back to @context (via method_missing) when @notification_target
does not support sampling.
The originating request id is stamped as related_request_id and cannot be
overridden by callers (the literal keyword after **kwargs wins),
satisfying SEP-2260's requirement that server-to-client requests be
associated with the client request being processed.
225 226 227 228 229 230 231 232 233 |
# File 'lib/mcp/server_context.rb', line 225 def (**kwargs) if @notification_target.respond_to?(:create_sampling_message) @notification_target.(**kwargs, related_request_id: @related_request_id) elsif @context.respond_to?(:create_sampling_message) @context.(**kwargs, related_request_id: @related_request_id) else raise NoMethodError, "undefined method 'create_sampling_message' for #{self}" end end |
#create_url_elicitation(**kwargs) ⇒ Object
Delegates to the session so the request is scoped to the originating client.
Falls back to @context when @notification_target does not support URL mode elicitation.
The originating request id is stamped as a non-overridable related_request_id,
as with create_sampling_message (SEP-2260).
254 255 256 257 258 259 260 261 262 |
# File 'lib/mcp/server_context.rb', line 254 def create_url_elicitation(**kwargs) if @notification_target.respond_to?(:create_url_elicitation) @notification_target.create_url_elicitation(**kwargs, related_request_id: @related_request_id) elsif @context.respond_to?(:create_url_elicitation) @context.create_url_elicitation(**kwargs, related_request_id: @related_request_id) else raise NoMethodError, "undefined method 'create_url_elicitation' for #{self}" end end |
#input_response(key) ⇒ Object
Reads one entry of #input_responses by its inputRequests key, tolerating symbol or string keys.
35 36 37 38 39 40 |
# File 'lib/mcp/server_context.rb', line 35 def input_response(key) return unless @input_responses.is_a?(Hash) value = @input_responses[key.to_sym] value.nil? ? @input_responses[key.to_s] : value end |
#list_roots(timeout: nil) ⇒ Object
MCP Roots (roots/list and
notifications/roots/list_changed) is deprecated as of MCP protocol
version 2026-07-28 (SEP-2577). Use tool parameters, resource URIs,
server configuration, or environment variables instead.
Delegates to the session so the request is scoped to the originating client.
The originating request id is stamped as related_request_id, satisfying
SEP-2260's requirement that server-to-client requests be associated with
the client request being processed.
184 185 186 187 188 189 190 |
# File 'lib/mcp/server_context.rb', line 184 def list_roots(timeout: nil) if @notification_target.respond_to?(:list_roots) @notification_target.list_roots(related_request_id: @related_request_id, **timeout_kwarg(timeout)) else raise NoMethodError, "undefined method 'list_roots' for #{self}" end end |
#modern? ⇒ Boolean
Whether the current request follows the stateless modern lifecycle (SEP-2575).
51 52 53 |
# File 'lib/mcp/server_context.rb', line 51 def modern? !@envelope.nil? end |
#notify_elicitation_complete(**kwargs) ⇒ Object
Delegates to the session so the notification is scoped to the originating client.
265 266 267 268 269 270 271 272 273 |
# File 'lib/mcp/server_context.rb', line 265 def notify_elicitation_complete(**kwargs) if @notification_target.respond_to?(:notify_elicitation_complete) @notification_target.notify_elicitation_complete(**kwargs) elsif @context.respond_to?(:notify_elicitation_complete) @context.notify_elicitation_complete(**kwargs) else raise NoMethodError, "undefined method 'notify_elicitation_complete' for #{self}" end end |
#notify_log_message(data:, level:, logger: nil) ⇒ Object
MCP Logging (logging/setLevel and notifications/message)
is deprecated as of MCP protocol version 2026-07-28 (SEP-2577).
Use stderr or OpenTelemetry instead.
Sends a log message notification scoped to the originating session.
134 135 136 137 138 139 140 141 142 143 144 145 146 |
# File 'lib/mcp/server_context.rb', line 134 def (data:, level:, logger: nil) return unless @notification_target # Modern requests opt in to logging per request (SEP-2575): without `io.modelcontextprotocol/logLevel` in `_meta`, # the server MUST NOT send any `notifications/message` for the request, and an insufficient level drops # the message the same way. Session- or server-level gating still applies downstream on delegation. if @envelope threshold = @envelope.log_level && LoggingMessageNotification.new(level: @envelope.log_level) return unless threshold&.valid_level? && threshold.should_notify?(level) end @notification_target.(data: data, level: level, logger: logger, related_request_id: @related_request_id) end |
#notify_resources_updated(uri:) ⇒ Object
Sends a resource updated notification scoped to the originating session.
151 152 153 154 155 |
# File 'lib/mcp/server_context.rb', line 151 def notify_resources_updated(uri:) return unless @notification_target @notification_target.notify_resources_updated(uri: uri) end |
#ping(timeout: nil) ⇒ Hash
Sends a ping request to the originating client to verify it is still responsive.
Per the MCP spec, the client MUST respond promptly with an empty result.
206 207 208 209 210 211 212 |
# File 'lib/mcp/server_context.rb', line 206 def ping(timeout: nil) if @notification_target.respond_to?(:ping) @notification_target.ping(related_request_id: @related_request_id, **timeout_kwarg(timeout)) else raise NoMethodError, "undefined method 'ping' for #{self}" end end |
#protocol_version ⇒ Object
The protocol version the current request was made with. nil on legacy requests,
where the version is a session-level negotiation result rather than per-request data.
73 74 75 |
# File 'lib/mcp/server_context.rb', line 73 def protocol_version @envelope&.protocol_version end |
#raise_if_cancelled! ⇒ Object
46 47 48 |
# File 'lib/mcp/server_context.rb', line 46 def raise_if_cancelled! @cancellation&.raise_if_cancelled! end |
#report_progress(progress, total: nil, message: nil) ⇒ Object
Reports progress for the current tool operation. The notification is automatically scoped to the originating session.
122 123 124 |
# File 'lib/mcp/server_context.rb', line 122 def report_progress(progress, total: nil, message: nil) @progress.report(progress, total: total, message: ) end |
#require_client_capability!(*path) ⇒ Object
Guards the current request on a declared client capability (SEP-2575). path names nested capability keys,
e.g. require_client_capability!(:elicitation, :form). Raises Server::MissingRequiredClientCapabilityError
(JSON-RPC error -32021 with data: { requiredCapabilities: ... }) when the capability was not declared.
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/mcp/server_context.rb', line 80 def require_client_capability!(*path) raise ArgumentError, "at least one capability key is required" if path.empty? declared = client_capabilities value = path.reduce(declared) do |acc, key| break unless acc.is_a?(Hash) symbol_value = acc[key.to_sym] symbol_value.nil? ? acc[key.to_s] : symbol_value end return unless value.nil? required = path.reverse.inject({}) { |acc, key| { key.to_sym => acc } } raise Server::MissingRequiredClientCapabilityError, required end |
#require_scopes!(*scopes) ⇒ Object
Guards the current operation on OAuth scopes the token must carry, for authorization decisions finer-grained than
the transport-wide required_scopes. Raises Server::OAuth::InsufficientScopeError, which surfaces as
a JSON-RPC invalid-request error naming the missing scopes. HTTP-level 403 step-up challenges remain the job of
the transport's required_scopes gate, matching how the Python and TypeScript SDKs split endpoint-level challenges
from in-handler authorization. The transport's scope_matcher: applies here as well: the authenticator attaches it
to the token it hands over, so a scope hierarchy is judged the same way at the gate and in handlers.
107 108 109 110 111 112 113 114 |
# File 'lib/mcp/server_context.rb', line 107 def require_scopes!(*scopes) raise ArgumentError, "at least one scope is required" if scopes.empty? missing_scopes = scopes.reject { |scope| @auth_info&.scope?(scope) } return if missing_scopes.empty? raise Server::OAuth::InsufficientScopeError.new("Token is missing required scopes: #{missing_scopes.join(", ")}", required_scopes: scopes) end |
#respond_to_missing?(name, include_private = false) ⇒ Boolean
288 289 290 |
# File 'lib/mcp/server_context.rb', line 288 def respond_to_missing?(name, include_private = false) @context.respond_to?(name) || super end |