Class: MCP::Server::Transports::StdioTransport

Inherits:
Transport
  • Object
show all
Defined in:
lib/mcp/server/transports/stdio_transport.rb

Constant Summary collapse

STATUS_INTERRUPTED =
Signal.list["INT"] + 128

Instance Method Summary collapse

Methods inherited from Transport

#handle_json_request, #handle_request

Constructor Details

#initialize(server) ⇒ StdioTransport

Returns a new instance of StdioTransport.



12
13
14
15
16
17
18
# File 'lib/mcp/server/transports/stdio_transport.rb', line 12

def initialize(server)
  @server = server
  @open = false
  $stdin.set_encoding("UTF-8")
  $stdout.set_encoding("UTF-8")
  super
end

Instance Method Details

#closeObject



31
32
33
# File 'lib/mcp/server/transports/stdio_transport.rb', line 31

def close
  @open = false
end

#openObject



20
21
22
23
24
25
26
27
28
29
# File 'lib/mcp/server/transports/stdio_transport.rb', line 20

def open
  @open = true
  while @open && (line = $stdin.gets)
    handle_json_request(line.strip)
  end
rescue Interrupt
  warn("\nExiting...")

  exit(STATUS_INTERRUPTED)
end

#send_notification(method, params = nil) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/mcp/server/transports/stdio_transport.rb', line 41

def send_notification(method, params = nil)
  notification = {
    jsonrpc: "2.0",
    method: method,
  }
  notification[:params] = params if params

  send_response(notification)
  true
rescue => e
  MCP.configuration.exception_reporter.call(e, { error: "Failed to send notification" })
  false
end

#send_response(message) ⇒ Object



35
36
37
38
39
# File 'lib/mcp/server/transports/stdio_transport.rb', line 35

def send_response(message)
  json_message = message.is_a?(String) ? message : JSON.generate(message)
  $stdout.puts(json_message)
  $stdout.flush
end