Class: MCP::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/mcp/client.rb,
lib/mcp/client/http.rb,
lib/mcp/client/tool.rb

Defined Under Namespace

Classes: HTTP, RequestHandlerError, Tool

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(transport:) ⇒ Client

Initializes a new MCP::Client instance.

Examples:

transport = MCP::Client::HTTP.new(url: "http://localhost:3000")
client = MCP::Client.new(transport: transport)

Parameters:

  • transport (Object)

    The transport object to use for communication with the server. The transport should be a duck type that responds to ‘send_request`. See the README for more details.



13
14
15
# File 'lib/mcp/client.rb', line 13

def initialize(transport:)
  @transport = transport
end

Instance Attribute Details

#transportObject (readonly)

The user may want to access additional transport-specific methods/attributes So keeping it public



19
20
21
# File 'lib/mcp/client.rb', line 19

def transport
  @transport
end

Instance Method Details

#call_tool(tool:, arguments: nil) ⇒ Object

Note:

The exact requirements for ‘arguments` are determined by the transport layer in use. Consult the documentation for your transport (e.g., MCP::Client::HTTP) for details.

Calls a tool via the transport layer.

Examples:

tool = client.tools.first
result = client.call_tool(tool: tool, arguments: { foo: "bar" })

Parameters:

  • tool (MCP::Client::Tool)

    The tool to be called.

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

    The arguments to pass to the tool.

Returns:

  • (Object)

    The result of the tool call, as returned by the transport.



60
61
62
63
64
65
66
67
68
69
# File 'lib/mcp/client.rb', line 60

def call_tool(tool:, arguments: nil)
  response = transport.send_request(request: {
    jsonrpc: JsonRpcHandler::Version::V2_0,
    id: request_id,
    method: "tools/call",
    params: { name: tool.name, arguments: arguments },
  })

  response.dig("result", "content")
end

#toolsArray<MCP::Client::Tool>

Returns the list of tools available from the server. Each call will make a new request – the result is not cached.

Examples:

tools = client.tools
tools.each do |tool|
  puts tool.name
end

Returns:



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/mcp/client.rb', line 31

def tools
  response = transport.send_request(request: {
    jsonrpc: JsonRpcHandler::Version::V2_0,
    id: request_id,
    method: "tools/list",
  })

  response.dig("result", "tools")&.map do |tool|
    Tool.new(
      name: tool["name"],
      description: tool["description"],
      input_schema: tool["inputSchema"],
    )
  end || []
end