Class: Kernai::MCP::Adapter

Inherits:
Object
  • Object
show all
Defined in:
lib/kernai/mcp.rb

Overview

Adapter owns one MCPClient::Client and the mapping from MCP method names to client operations. It is instantiated by MCP.load / MCP.setup and held as a module-level singleton so Kernai::Protocol.register can reference a stable handler.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(config, client: nil) ⇒ Adapter

Returns a new instance of Adapter.

Parameters:

  • config (Hash)

    MCP config hash (same shape as the YAML file).

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

    Optional pre-built client (must quack like MCPClient::Client: list_tools, call_tool, list_resources, read_resource, list_prompts, get_prompt, cleanup). When nil the adapter builds a real client from the upstream gem. Injection is primarily meant for tests, but advanced users can also pass a pre-configured client with custom middleware or transports.



111
112
113
114
115
116
117
118
119
120
# File 'lib/kernai/mcp.rb', line 111

def initialize(config, client: nil)
  @config = config
  @server_names = config.fetch('servers').keys.map(&:to_s)
  if client
    @client = client
  else
    require_mcp_client!
    @client = build_client(config)
  end
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



102
103
104
# File 'lib/kernai/mcp.rb', line 102

def client
  @client
end

#server_namesObject (readonly)

Returns the value of attribute server_names.



102
103
104
# File 'lib/kernai/mcp.rb', line 102

def server_names
  @server_names
end

Instance Method Details

#handle(block, _ctx) ⇒ Object

Entry point registered into Kernai::Protocol. Receives the raw <block type=“mcp”> block and returns a String payload (or raises, in which case the kernel wraps it as an error block).



125
126
127
128
# File 'lib/kernai/mcp.rb', line 125

def handle(block, _ctx)
  req = parse_request(block.content)
  dispatch(req)
end

#shutdownObject



130
131
132
133
134
135
136
# File 'lib/kernai/mcp.rb', line 130

def shutdown
  @client&.cleanup
rescue StandardError
  # Best-effort: shutdown is typically called from at_exit, we must
  # not raise out of it.
  nil
end