Class: ModelContextProtocol::Server::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/model_context_protocol/server/router.rb

Defined Under Namespace

Classes: MethodNotFoundError

Instance Method Summary collapse

Constructor Details

#initialize(configuration: nil) ⇒ Router

Returns a new instance of Router.



8
9
10
11
# File 'lib/model_context_protocol/server/router.rb', line 8

def initialize(configuration: nil)
  @handlers = {}
  @configuration = configuration
end

Instance Method Details

#map(method, &handler) ⇒ Object



13
14
15
# File 'lib/model_context_protocol/server/router.rb', line 13

def map(method, &handler)
  @handlers[method] = handler
end

#route(message, request_store: nil, session_id: nil, transport: nil) ⇒ Object

Route a message to its handler with request tracking support

Parameters:

  • message (Hash)

    the JSON-RPC message

  • request_store (Object) (defaults to: nil)

    the request store for tracking cancellation

  • session_id (String, nil) (defaults to: nil)

    the session ID for HTTP transport

  • transport (Object, nil) (defaults to: nil)

    the transport for sending notifications

Returns:

  • (Object)

    the handler result, or nil if cancelled

Raises:



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/model_context_protocol/server/router.rb', line 24

def route(message, request_store: nil, session_id: nil, transport: nil)
  method = message["method"]
  handler = @handlers[method]
  raise MethodNotFoundError, "Method not found: #{method}" unless handler

  request_id = message["id"]
  progress_token = message.dig("params", "_meta", "progressToken")

  if request_id && request_store
    request_store.register_request(request_id, session_id)
  end

  result = nil
  begin
    with_environment(@configuration&.environment_variables) do
      context = {request_id:, request_store:, session_id:, progress_token:, transport:}

      Thread.current[:mcp_context] = context

      result = handler.call(message)
    end
  rescue Server::Cancellable::CancellationError
    return nil
  ensure
    if request_id && request_store
      request_store.unregister_request(request_id)
    end

    Thread.current[:mcp_context] = nil
  end

  result
end