Class: Raix::MCP::StdioClient

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

Overview

Client for communicating with MCP servers via stdio using JSON-RPC.

Instance Method Summary collapse

Constructor Details

#initialize(*args, env) ⇒ StdioClient

Creates a new client with a bidirectional pipe to the MCP server.



11
12
13
14
# File 'lib/mcp/stdio_client.rb', line 11

def initialize(*args, env)
  @args = args
  @io = IO.popen(env, args, "w+")
end

Instance Method Details

#call_tool(name, **arguments) ⇒ Object

Executes a tool with given arguments. Returns text content directly, or JSON-encoded data for other content types.



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
# File 'lib/mcp/stdio_client.rb', line 27

def call_tool(name, **arguments)
  result = call("tools/call", name:, arguments:)
  content = result["content"]
  return "" if content.nil? || content.empty?

  # Handle different content formats
  first_item = content.first
  case first_item
  when Hash
    case first_item["type"]
    when "text"
      first_item["text"]
    when "image"
      # Return a structured response for images
      {
        type: "image",
        data: first_item["data"],
        mime_type: first_item["mimeType"] || "image/png"
      }.to_json
    else
      # For any other type, return the item as JSON
      first_item.to_json
    end
  else
    first_item.to_s
  end
end

#closeObject

Closes the connection to the server.



56
57
58
# File 'lib/mcp/stdio_client.rb', line 56

def close
  @io.close
end

#toolsObject

Returns available tools from the server.



17
18
19
20
21
22
23
# File 'lib/mcp/stdio_client.rb', line 17

def tools
  result = call("tools/list")

  result["tools"].map do |tool_json|
    Tool.from_json(tool_json)
  end
end

#unique_keyObject



60
61
62
63
# File 'lib/mcp/stdio_client.rb', line 60

def unique_key
  parametrized_args = @args.join(" ").parameterize.underscore
  Digest::SHA256.hexdigest(parametrized_args)[0..2]
end