Class: MCP::Server
- Inherits:
-
Object
- Object
- MCP::Server
- Includes:
- Instrumentation, Pagination
- Defined in:
- lib/mcp/server.rb,
lib/mcp/server/pagination.rb,
lib/mcp/server/transports.rb,
lib/mcp/server/capabilities.rb,
lib/mcp/server/pending_response.rb,
lib/mcp/server/input_required_result.rb,
lib/mcp/server/request_state_security.rb,
lib/mcp/server/transports/stdio_transport.rb,
lib/mcp/server/transports/streamable_http_transport.rb
Defined Under Namespace
Modules: Pagination, Transports Classes: Capabilities, InputRequiredResult, MethodAlreadyDefinedError, MissingRequiredClientCapabilityError, PendingResponse, RequestHandlerError, RequestStateSecurity, RequestTimeoutError, ResourceNotFoundError, URLElicitationRequiredError, UnsupportedProtocolVersionError, ValidationError
Constant Summary collapse
- DEFAULT_VERSION =
"0.1.0"- UNSUPPORTED_PROPERTIES_UNTIL_2025_06_18 =
[:description, :icons].freeze
- UNSUPPORTED_PROPERTIES_UNTIL_2025_03_26 =
[:title, :websiteUrl].freeze
- DEFAULT_COMPLETION_RESULT =
{ completion: { values: [], hasMore: false } }.freeze
- MAX_COMPLETION_VALUES =
Servers return an array of completion values ranked by relevance, with maximum 100 items per response. https://modelcontextprotocol.io/specification/2025-11-25/server/utilities/completion#completion-results
100- CACHE_SCOPES =
Allowed values for the SEP-2549
cacheScopecache hint. ["public", "private"].freeze
- CACHEABLE_RESULT_METHODS =
Methods whose results are cacheable per SEP-2549. On the modern wire (2026-07-28) the
ttlMs/cacheScopehints are REQUIRED on these results, so unset hints get the spec defaults there; on stable protocol versions emission stays opt-in viaapply_cache_metadata. [ Methods::TOOLS_LIST, Methods::PROMPTS_LIST, Methods::RESOURCES_LIST, Methods::RESOURCES_TEMPLATES_LIST, Methods::RESOURCES_READ, ].freeze
Instance Attribute Summary collapse
-
#cache_scope ⇒ Object
Returns the value of attribute cache_scope.
-
#capabilities ⇒ Object
Returns the value of attribute capabilities.
-
#client_capabilities ⇒ Object
readonly
Returns the value of attribute client_capabilities.
-
#configuration ⇒ Object
Returns the value of attribute configuration.
-
#description ⇒ Object
Returns the value of attribute description.
-
#icons ⇒ Object
Returns the value of attribute icons.
-
#instructions ⇒ Object
Returns the value of attribute instructions.
-
#logging_message_notification ⇒ Object
Returns the value of attribute logging_message_notification.
-
#name ⇒ Object
Returns the value of attribute name.
-
#page_size ⇒ Object
Returns the value of attribute page_size.
-
#prompts ⇒ Object
Returns the value of attribute prompts.
-
#request_state_security ⇒ Object
readonly
Returns the value of attribute request_state_security.
-
#resource_templates ⇒ Object
Returns the value of attribute resource_templates.
-
#resources ⇒ Object
Returns the value of attribute resources.
-
#server_context ⇒ Object
Returns the value of attribute server_context.
-
#title ⇒ Object
Returns the value of attribute title.
-
#tools ⇒ Object
Returns the value of attribute tools.
-
#transport ⇒ Object
Returns the value of attribute transport.
-
#ttl_ms ⇒ Object
Returns the value of attribute ttl_ms.
-
#version ⇒ Object
Returns the value of attribute version.
-
#website_url ⇒ Object
Returns the value of attribute website_url.
Instance Method Summary collapse
- #build_sampling_params(capabilities, messages:, max_tokens:, system_prompt: nil, model_preferences: nil, include_context: nil, temperature: nil, stop_sequences: nil, metadata: nil, tools: nil, tool_choice: nil) ⇒ Object
-
#completion_handler {|params| ... } ⇒ Object
Sets a custom handler for
completion/completerequests. - #define_custom_method(method_name:, &block) ⇒ Object
- #define_prompt(name: nil, title: nil, description: nil, arguments: [], &block) ⇒ Object
- #define_resource(uri: nil, name: nil, title: nil, description: nil, icons: [], mime_type: nil, annotations: nil, size: nil, meta: nil, &block) ⇒ Object
- #define_resource_template(uri_template: nil, name: nil, title: nil, description: nil, icons: [], mime_type: nil, annotations: nil, meta: nil, &block) ⇒ Object
- #define_tool(name: nil, title: nil, description: nil, input_schema: nil, output_schema: nil, annotations: nil, meta: nil, &block) ⇒ Object
-
#handle(request, session: nil) ⇒ Hash?
Processes a parsed JSON-RPC request and returns the response as a Hash.
-
#handle_json(request, session: nil) ⇒ String?
Processes a JSON-RPC request string and returns the response as a JSON string.
-
#initialize(description: nil, icons: [], name: "model_context_protocol", title: nil, version: DEFAULT_VERSION, website_url: nil, instructions: nil, tools: [], prompts: [], resources: [], resource_templates: [], server_context: nil, configuration: nil, capabilities: nil, page_size: nil, ttl_ms: nil, cache_scope: nil, request_state_security: nil, input_required_legacy_shim: true, transport: nil) ⇒ Server
constructor
A new instance of Server.
-
#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_prompts_list_changed ⇒ Object
- #notify_resources_list_changed ⇒ Object
- #notify_tools_list_changed ⇒ Object
-
#resources_list_handler {|params, server_context:| ... } ⇒ Object
Sets a custom handler for
resources/listrequests, letting the visible list depend on request context such as the authenticated principal or granted scope. -
#resources_read_handler {|params| ... } ⇒ Object
Sets a custom handler for
resources/readrequests. -
#resources_subscribe_handler {|params| ... } ⇒ Object
Sets a custom handler for
resources/subscriberequests. -
#resources_unsubscribe_handler {|params| ... } ⇒ Object
Sets a custom handler for
resources/unsubscriberequests. -
#roots_list_changed_handler {|params| ... } ⇒ 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.
Methods included from Instrumentation
#add_instrumentation_data, #instrument_call
Constructor Details
#initialize(description: nil, icons: [], name: "model_context_protocol", title: nil, version: DEFAULT_VERSION, website_url: nil, instructions: nil, tools: [], prompts: [], resources: [], resource_templates: [], server_context: nil, configuration: nil, capabilities: nil, page_size: nil, ttl_ms: nil, cache_scope: nil, request_state_security: nil, input_required_legacy_shim: true, transport: nil) ⇒ Server
Returns a new instance of Server.
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
# File 'lib/mcp/server.rb', line 187 def initialize( description: nil, icons: [], name: "model_context_protocol", title: nil, version: DEFAULT_VERSION, website_url: nil, instructions: nil, tools: [], prompts: [], resources: [], resource_templates: [], server_context: nil, configuration: nil, capabilities: nil, page_size: nil, ttl_ms: nil, cache_scope: nil, request_state_security: nil, input_required_legacy_shim: true, transport: nil ) @description = description @icons = icons @name = name @title = title @version = version @website_url = website_url @instructions = instructions @tool_names = tools.map(&:name_value) @tools = tools.to_h { |t| [t.name_value, t] } @prompts = prompts.to_h { |p| [p.name_value, p] } @resources = resources @resource_templates = resource_templates @resource_index = index_resources_by_uri(resources) @resources_list_handler = nil @server_context = server_context self.page_size = page_size self.ttl_ms = ttl_ms self.cache_scope = cache_scope @request_state_security = request_state_security # Dual-era authoring (SEP-2322): on the legacy wire, an `input_required` result is fulfilled # through real server-to-client requests and the handler re-runs, so handlers written # in the 2026 style serve both eras. `false` restores the strict rejection of `input_required` # on legacy requests. Matches the TypeScript SDK's default-on legacy shim. @input_required_legacy_shim = input_required_legacy_shim @configuration = MCP.configuration.merge(configuration) @client = nil @client_protocol_version = nil validate! # Accept either a plain Hash or an `MCP::Server::Capabilities` builder. @capabilities = if capabilities.is_a?(Capabilities) capabilities.to_h else capabilities || default_capabilities end @client_capabilities = nil @logging_message_notification = nil @handlers = { Methods::RESOURCES_LIST => method(:list_resources), Methods::RESOURCES_READ => method(:read_resource), Methods::RESOURCES_TEMPLATES_LIST => method(:list_resource_templates), Methods::RESOURCES_SUBSCRIBE => ->(_) { {} }, Methods::RESOURCES_UNSUBSCRIBE => ->(_) { {} }, Methods::TOOLS_LIST => method(:list_tools), Methods::TOOLS_CALL => method(:call_tool), Methods::PROMPTS_LIST => method(:list_prompts), Methods::PROMPTS_GET => method(:get_prompt), Methods::INITIALIZE => method(:init), Methods::SERVER_DISCOVER => method(:discover), Methods::PING => ->(_) { {} }, Methods::NOTIFICATIONS_INITIALIZED => ->(_) {}, Methods::NOTIFICATIONS_PROGRESS => ->(_) {}, Methods::NOTIFICATIONS_ROOTS_LIST_CHANGED => ->(_) {}, Methods::COMPLETION_COMPLETE => ->(_) { DEFAULT_COMPLETION_RESULT }, Methods::LOGGING_SET_LEVEL => method(:configure_logging_level), } @transport = transport end |
Instance Attribute Details
#cache_scope ⇒ Object
Returns the value of attribute cache_scope.
185 186 187 |
# File 'lib/mcp/server.rb', line 185 def cache_scope @cache_scope end |
#capabilities ⇒ Object
Returns the value of attribute capabilities.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def capabilities @capabilities end |
#client_capabilities ⇒ Object (readonly)
Returns the value of attribute client_capabilities.
185 186 187 |
# File 'lib/mcp/server.rb', line 185 def client_capabilities @client_capabilities end |
#configuration ⇒ Object
Returns the value of attribute configuration.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def configuration @configuration end |
#description ⇒ Object
Returns the value of attribute description.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def description @description end |
#icons ⇒ Object
Returns the value of attribute icons.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def icons @icons end |
#instructions ⇒ Object
Returns the value of attribute instructions.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def instructions @instructions end |
#logging_message_notification ⇒ Object
Returns the value of attribute logging_message_notification.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def @logging_message_notification end |
#name ⇒ Object
Returns the value of attribute name.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def name @name end |
#page_size ⇒ Object
Returns the value of attribute page_size.
185 186 187 |
# File 'lib/mcp/server.rb', line 185 def page_size @page_size end |
#prompts ⇒ Object
Returns the value of attribute prompts.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def prompts @prompts end |
#request_state_security ⇒ Object (readonly)
Returns the value of attribute request_state_security.
185 186 187 |
# File 'lib/mcp/server.rb', line 185 def request_state_security @request_state_security end |
#resource_templates ⇒ Object
Returns the value of attribute resource_templates.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def resource_templates @resource_templates end |
#resources ⇒ Object
Returns the value of attribute resources.
185 186 187 |
# File 'lib/mcp/server.rb', line 185 def resources @resources end |
#server_context ⇒ Object
Returns the value of attribute server_context.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def server_context @server_context end |
#title ⇒ Object
Returns the value of attribute title.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def title @title end |
#tools ⇒ Object
Returns the value of attribute tools.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def tools @tools end |
#transport ⇒ Object
Returns the value of attribute transport.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def transport @transport end |
#ttl_ms ⇒ Object
Returns the value of attribute ttl_ms.
185 186 187 |
# File 'lib/mcp/server.rb', line 185 def ttl_ms @ttl_ms end |
#version ⇒ Object
Returns the value of attribute version.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def version @version end |
#website_url ⇒ Object
Returns the value of attribute website_url.
184 185 186 |
# File 'lib/mcp/server.rb', line 184 def website_url @website_url end |
Instance Method Details
#build_sampling_params(capabilities, messages:, max_tokens:, system_prompt: nil, model_preferences: nil, include_context: nil, temperature: nil, stop_sequences: nil, metadata: nil, tools: nil, tool_choice: nil) ⇒ Object
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 |
# File 'lib/mcp/server.rb', line 489 def build_sampling_params( capabilities, messages:, max_tokens:, system_prompt: nil, model_preferences: nil, include_context: nil, temperature: nil, stop_sequences: nil, metadata: nil, tools: nil, tool_choice: nil ) unless capabilities&.dig(:sampling) raise "Client does not support sampling." end if tools && !capabilities.dig(:sampling, :tools) raise "Client does not support sampling with tools." end if tool_choice && !capabilities.dig(:sampling, :tools) raise "Client does not support sampling with tool_choice." end { messages: , maxTokens: max_tokens, systemPrompt: system_prompt, modelPreferences: model_preferences, includeContext: include_context, temperature: temperature, stopSequences: stop_sequences, metadata: , tools: tools, toolChoice: tool_choice, }.compact end |
#completion_handler {|params| ... } ⇒ Object
Sets a custom handler for completion/complete requests.
The block receives the parsed request params and should return completion values.
461 462 463 |
# File 'lib/mcp/server.rb', line 461 def completion_handler(&block) @handlers[Methods::COMPLETION_COMPLETE] = block end |
#define_custom_method(method_name:, &block) ⇒ Object
342 343 344 345 346 347 348 |
# File 'lib/mcp/server.rb', line 342 def define_custom_method(method_name:, &block) if @handlers.key?(method_name) raise MethodAlreadyDefinedError, method_name end @handlers[method_name] = block end |
#define_prompt(name: nil, title: nil, description: nil, arguments: [], &block) ⇒ Object
307 308 309 310 311 312 |
# File 'lib/mcp/server.rb', line 307 def define_prompt(name: nil, title: nil, description: nil, arguments: [], &block) prompt = Prompt.define(name: name, title: title, description: description, arguments: arguments, &block) @prompts[prompt.name_value] = prompt validate! end |
#define_resource(uri: nil, name: nil, title: nil, description: nil, icons: [], mime_type: nil, annotations: nil, size: nil, meta: nil, &block) ⇒ Object
314 315 316 317 318 319 320 321 322 323 324 |
# File 'lib/mcp/server.rb', line 314 def define_resource(uri: nil, name: nil, title: nil, description: nil, icons: [], mime_type: nil, annotations: nil, size: nil, meta: nil, &block) resource = Resource.define( uri: uri, name: name, title: title, description: description, icons: icons, mime_type: mime_type, annotations: annotations, size: size, meta: , &block ) @resources << resource @resource_index[resource.uri] = resource validate! end |
#define_resource_template(uri_template: nil, name: nil, title: nil, description: nil, icons: [], mime_type: nil, annotations: nil, meta: nil, &block) ⇒ Object
326 327 328 329 330 331 332 333 334 335 |
# File 'lib/mcp/server.rb', line 326 def define_resource_template(uri_template: nil, name: nil, title: nil, description: nil, icons: [], mime_type: nil, annotations: nil, meta: nil, &block) resource_template = ResourceTemplate.define( uri_template: uri_template, name: name, title: title, description: description, icons: icons, mime_type: mime_type, annotations: annotations, meta: , &block ) @resource_templates << resource_template validate! end |
#define_tool(name: nil, title: nil, description: nil, input_schema: nil, output_schema: nil, annotations: nil, meta: nil, &block) ⇒ Object
297 298 299 300 301 302 303 304 305 |
# File 'lib/mcp/server.rb', line 297 def define_tool(name: nil, title: nil, description: nil, input_schema: nil, output_schema: nil, annotations: nil, meta: nil, &block) tool = Tool.define(name: name, title: title, description: description, input_schema: input_schema, output_schema: output_schema, annotations: annotations, meta: , &block) tool_name = tool.name_value @tool_names << tool_name @tools[tool_name] = tool validate! end |
#handle(request, session: nil) ⇒ Hash?
Processes a parsed JSON-RPC request and returns the response as a Hash.
278 279 280 281 282 |
# File 'lib/mcp/server.rb', line 278 def handle(request, session: nil) JsonRpcHandler.handle(request) do |method, request_id| handle_request(request, method, session: session, related_request_id: request_id) end end |
#handle_json(request, session: nil) ⇒ String?
Processes a JSON-RPC request string and returns the response as a JSON string.
291 292 293 294 295 |
# File 'lib/mcp/server.rb', line 291 def handle_json(request, session: nil) JsonRpcHandler.handle_json(request) do |method, request_id| handle_request(request, method, session: session, related_request_id: request_id) 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.
406 407 408 409 410 411 412 413 414 415 416 |
# File 'lib/mcp/server.rb', line 406 def (data:, level:, logger: nil) return unless @transport return unless &.should_notify?(level) params = { "data" => data, "level" => level } params["logger"] = logger if logger @transport.send_notification(Methods::NOTIFICATIONS_MESSAGE, params) rescue => e report_exception(e, { notification: "log_message" }) end |
#notify_prompts_list_changed ⇒ Object
387 388 389 390 391 392 393 |
# File 'lib/mcp/server.rb', line 387 def notify_prompts_list_changed return unless @transport @transport.send_notification(Methods::NOTIFICATIONS_PROMPTS_LIST_CHANGED) rescue => e report_exception(e, { notification: "prompts_list_changed" }) end |
#notify_resources_list_changed ⇒ Object
395 396 397 398 399 400 401 |
# File 'lib/mcp/server.rb', line 395 def notify_resources_list_changed return unless @transport @transport.send_notification(Methods::NOTIFICATIONS_RESOURCES_LIST_CHANGED) rescue => e report_exception(e, { notification: "resources_list_changed" }) end |
#notify_tools_list_changed ⇒ Object
379 380 381 382 383 384 385 |
# File 'lib/mcp/server.rb', line 379 def notify_tools_list_changed return unless @transport @transport.send_notification(Methods::NOTIFICATIONS_TOOLS_LIST_CHANGED) rescue => e report_exception(e, { notification: "tools_list_changed" }) end |
#resources_list_handler {|params, server_context:| ... } ⇒ Object
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,
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 constructor-provided resources array is served unchanged.
The block is invoked once per page, so it must return a stable ordering across the pages of one logical query; the cursor is a positional offset into the returned collection.
442 443 444 |
# File 'lib/mcp/server.rb', line 442 def resources_list_handler(&block) @resources_list_handler = block end |
#resources_read_handler {|params| ... } ⇒ Object
Sets a custom handler for resources/read requests.
The block receives the parsed request params and should return resource
contents. The return value is set as the contents field of the response.
452 453 454 |
# File 'lib/mcp/server.rb', line 452 def resources_read_handler(&block) @handlers[Methods::RESOURCES_READ] = block end |
#resources_subscribe_handler {|params| ... } ⇒ Object
Sets a custom handler for resources/subscribe requests.
The block receives the parsed request params. The response is an empty result, except that
a _meta hash the block returns is passed through - the spec defines no other member for this result,
so any other field the block returns is dropped. Nest a subscription identifier or other advisory data
under _meta.
473 474 475 |
# File 'lib/mcp/server.rb', line 473 def resources_subscribe_handler(&block) @handlers[Methods::RESOURCES_SUBSCRIBE] = block end |
#resources_unsubscribe_handler {|params| ... } ⇒ Object
Sets a custom handler for resources/unsubscribe requests.
The block receives the parsed request params. The response is an empty result, except that
a _meta hash the block returns is passed through - the spec defines no other member for this result,
so any other field the block returns is dropped. Nest a subscription identifier or other advisory data
under _meta.
485 486 487 |
# File 'lib/mcp/server.rb', line 485 def resources_unsubscribe_handler(&block) @handlers[Methods::RESOURCES_UNSUBSCRIBE] = block end |
#roots_list_changed_handler {|params| ... } ⇒ 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.
Sets a handler for notifications/roots/list_changed notifications.
Called when a client notifies the server that its filesystem roots have changed.
426 427 428 |
# File 'lib/mcp/server.rb', line 426 def roots_list_changed_handler(&block) @handlers[Methods::NOTIFICATIONS_ROOTS_LIST_CHANGED] = block end |