### Install Ruby Client Dependencies Source: https://github.com/simonx1/ruby-mcp-client/blob/main/examples/README_ECHO_SERVER.md Installs the required Ruby gems for the MCP client using Bundler. Ensure you are in the project's root directory. ```bash # Make sure you're in the ruby-mcp-client directory bundle install ``` -------------------------------- ### Install ruby-mcp-client Gem Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Instructions for installing the ruby-mcp-client gem using Bundler or directly via gem install. ```bash gem 'ruby-mcp-client' ``` ```bash bundle install ``` ```bash gem install ruby-mcp-client ``` -------------------------------- ### Start FastMCP Echo Server Source: https://github.com/simonx1/ruby-mcp-client/blob/main/examples/README_ECHO_SERVER.md Launches the Python FastMCP echo server. This server provides several tools for the client to interact with. ```bash # From the ruby-mcp-client directory python examples/echo_server.py ``` -------------------------------- ### Install Python FastMCP Dependency Source: https://github.com/simonx1/ruby-mcp-client/blob/main/examples/README_ECHO_SERVER.md Installs the necessary Python package for the FastMCP server using pip. ```bash pip install fastmcp ``` -------------------------------- ### Run Ruby MCP Client Source: https://github.com/simonx1/ruby-mcp-client/blob/main/examples/README_ECHO_SERVER.md Executes the Ruby client script to connect to the running FastMCP server and demonstrate tool usage. Requires the server to be active. ```bash # From the ruby-mcp-client directory (not the examples directory) bundle exec ruby examples/echo_server_client.rb ``` -------------------------------- ### FastMCP Echo Server Tools Source: https://github.com/simonx1/ruby-mcp-client/blob/main/examples/README_ECHO_SERVER.md Defines the tools available on the FastMCP echo server, including their purpose and required parameters. ```APIDOC FastMCP Echo Server Tools: Tool Definitions: - echo: Description: Echo back the provided message. Parameters: - message: The string message to be echoed back. - reverse: Description: Reverse the provided text. Parameters: - text: The string text to be reversed. - uppercase: Description: Convert the provided text to uppercase. Parameters: - text: The string text to be converted to uppercase. - count_words: Description: Count words and characters in the provided text. Parameters: - text: The string text to analyze. Returns: - word_count: The number of words in the text. - character_count: The total number of characters in the text. - character_count_no_spaces: The number of characters excluding spaces. ``` -------------------------------- ### Manual OAuth Provider Initialization Source: https://github.com/simonx1/ruby-mcp-client/blob/main/OAUTH.md Shows how to create an OAuth provider instance directly for more granular control over the authorization process. This includes starting the authorization flow and completing it after user consent. ```ruby # Create OAuth provider directly for more control oauth_provider = MCPClient::Auth::OAuthProvider.new( server_url: 'https://api.example.com/mcp', redirect_uri: 'http://localhost:8080/callback', scope: 'mcp:read mcp:write' ) # Start authorization flow auth_url = oauth_provider.start_authorization_flow # Complete flow after user authorization token = oauth_provider.complete_authorization_flow(code, state) ``` -------------------------------- ### Basic Usage of OAuth Client Source: https://github.com/simonx1/ruby-mcp-client/blob/main/OAUTH.md Demonstrates how to create an OAuth-enabled HTTP server and initiate the OAuth authorization flow. It checks for valid tokens and guides the user to authorize the application if needed. ```ruby require 'mcp_client' # Create an OAuth-enabled HTTP server server = MCPClient::OAuthClient.create_http_server( server_url: 'https://api.example.com/mcp', redirect_uri: 'http://localhost:8080/callback', scope: 'mcp:read mcp:write' ) # Check if authorization is needed unless MCPClient::OAuthClient.valid_token?(server) # Start OAuth flow auth_url = MCPClient::OAuthClient.start_oauth_flow(server) puts "Please visit: #{auth_url}" # After user authorization, complete the flow # token = MCPClient::OAuthClient.complete_oauth_flow(server, code, state) end # Use the server normally server.connect tools = server.list_tools ``` -------------------------------- ### FastMCP Server Integration Example Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Demonstrates integrating the Ruby MCP client with a Python FastMCP server. It shows how to connect, list tools provided by the Python server, and call tools like 'echo' and 'reverse'. ```ruby # Start the FastMCP server # python examples/echo_server.py # Run the Ruby client # bundle exec ruby examples/echo_server_client.rb require 'mcp_client' # Connect to FastMCP server client = MCPClient.create_client( mcp_server_configs: [ MCPClient.sse_config( base_url: 'http://127.0.0.1:8000/sse/', read_timeout: 30 ) ] ) # List available tools tools = client.list_tools puts "Found #{tools.length} tools:" tools.each { |tool| puts "- #{tool.name}: #{tool.description}" } # Use the tools result = client.call_tool('echo', { message: 'Hello from Ruby!' }) result = client.call_tool('reverse', { text: 'FastMCP rocks!' }) client.cleanup # The FastMCP example includes: # - `echo_server.py` - A Python FastMCP server with 4 interactive tools # - `echo_server_client.rb` - Ruby client demonstrating all features # - `README_ECHO_SERVER.md` - Complete setup and usage instructions # This example showcases redirect support, proper line ending handling, and seamless integration between Ruby and Python MCP implementations. ``` -------------------------------- ### Custom Token Storage Implementation Source: https://github.com/simonx1/ruby-mcp-client/blob/main/OAUTH.md Provides an example of how to implement a custom storage backend for tokens and client credentials. This class must define methods for retrieving and storing token information, client details, PKCE verifiers, and state parameters. ```ruby class DatabaseTokenStorage def get_token(server_url) # Return MCPClient::Auth::Token or nil end def set_token(server_url, token) # Store token end def get_client_info(server_url) # Return MCPClient::Auth::ClientInfo or nil end def set_client_info(server_url, client_info) # Store client info end # Implement other required methods: # get_server_metadata, set_server_metadata # get_pkce, set_pkce, delete_pkce # get_state, set_state, delete_state end # Use custom storage storage = DatabaseTokenStorage.new server = MCPClient::OAuthClient.create_http_server( server_url: 'https://api.example.com/mcp', storage: storage ) ``` -------------------------------- ### Ruby Error Handling for Connection Errors Source: https://github.com/simonx1/ruby-mcp-client/blob/main/OAUTH.md Provides an example of how to catch and handle MCPClient::Errors::ConnectionError, specifically checking for OAuth authorization requirements to initiate the OAuth flow or handling other connection-related issues. ```ruby begin server.connect rescue MCPClient::Errors::ConnectionError => e if e.message.include?('OAuth authorization required') # Start OAuth flow auth_url = MCPClient::OAuthClient.start_oauth_flow(server) # Handle authorization... else # Handle other connection errors puts "Connection failed: #{e.message}" end end ``` -------------------------------- ### Automatic Session Termination Example Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Demonstrates the automatic session termination feature of the MCPClient. The client automatically sends an HTTP DELETE request with the session ID during cleanup, ensuring proper session closure. ```Ruby # Session is automatically terminated when client is cleaned up client = MCPClient.create_client( mcp_server_configs: [ MCPClient.http_config(base_url: 'https://api.example.com/mcp') ] ) # Use the client... tools = client.list_tools # Session automatically terminated with HTTP DELETE request client.cleanup ``` -------------------------------- ### MCP Client Configuration and Usage Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Demonstrates how to create an MCP client instance with various server configurations (stdio, SSE, HTTP) and how to interact with the client to list and find tools. ```ruby require 'mcp_client' # Create client with local stdio server configuration client_stdio = MCPClient.create_client( mcp_server_configs: [ MCPClient.stdio_config( command: 'npx -y @modelcontextprotocol/server-filesystem /home/user', name: 'filesystem' ) ], logger: Logger.new($stdout, level: Logger::INFO) ) # Create client with remote SSE and HTTP server configurations client_remote = MCPClient.create_client( mcp_server_configs: [ MCPClient.sse_config( base_url: 'https://api.example.com/sse', headers: { 'Authorization' => 'Bearer YOUR_TOKEN' }, name: 'sse_api', read_timeout: 30, ping: 10, retries: 3, retry_backoff: 1, logger: Logger.new($stdout, level: Logger::INFO) ), MCPClient.http_config( base_url: 'https://api.example.com', endpoint: '/rpc', headers: { 'Authorization' => 'Bearer YOUR_TOKEN' }, name: 'http_api', read_timeout: 30, retries: 3, retry_backoff: 1, logger: Logger.new($stdout, level: Logger::INFO) ) ], logger: Logger.new($stdout, level: Logger::WARN) ) # Load server definitions from a JSON file client_from_file = MCPClient.create_client( server_definition_file: 'path/to/server_definition.json', logger: Logger.new($stdout, level: Logger::WARN) ) # List all available tools across configured servers tools = client_stdio.list_tools # Find a specific server by its assigned name filesystem_server = client_stdio.find_server('filesystem') # Find tools matching a string pattern file_tools = client_stdio.find_tools('file') # Find the first tool matching a regex pattern first_tool = client_stdio.find_tool(/^file_/) ``` -------------------------------- ### Loading Server Definitions Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Shows how to load MCP client configurations from a JSON server definition file. ```ruby client = MCPClient.create_client(server_definition_file: 'path/to/definition.json') ``` -------------------------------- ### Basic MCP Client Usage (SSE) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Demonstrates fundamental operations of the MCP client, including listing available tools and calling a tool. The client automatically handles Server-Sent Events (SSE) formatted responses. ```ruby require 'mcp_client' # Assuming streamable_client is an initialized MCP client instance # Example: streamable_client = MCPClient.create_client(...) # List available tools (server responds with SSE-formatted JSON) tools = streamable_client.list_tools puts "Found #{tools.size} tools:" tools.each { |tool| puts "- #{tool.name}: #{tool.description}" } # Call a tool (response will be in SSE format) result = streamable_client.call_tool('google_calendar_find_event', { instructions: 'Find today\'s meetings', calendarid: 'primary' }) # The client automatically parses SSE responses like: # event: message # data: {"jsonrpc":"2.0","id":1,"result":{"content":[...]}} puts "Tool result: #{result.inspect}" # Clean up streamable_client.cleanup ``` -------------------------------- ### Anthropic Integration with MCP Client Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Demonstrates creating an MCP client and converting its tools to the format required by the Anthropic client for integration. ```ruby require 'mcp_client' require 'anthropic' # Create MCP client mcp_client = MCPClient.create_client( mcp_server_configs: [ MCPClient.stdio_config( command: %W[npx -y @modelcontextprotocol/server-filesystem #{Dir.pwd}] ) ] ) # Convert tools to Anthropic format claude_tools = mcp_client.to_anthropic_tools # Use with Anthropic client client = Anthropic::Client.new(access_token: ENV['ANTHROPIC_API_KEY']) ``` -------------------------------- ### OAuth Provider Configuration Options Source: https://github.com/simonx1/ruby-mcp-client/blob/main/OAUTH.md Outlines the configuration parameters for initializing an OAuthProvider object. These include essential details like the server URL, redirect URI, requested scopes, and optional logging or custom storage. ```ruby oauth_provider = MCPClient::Auth::OAuthProvider.new( server_url: 'https://api.example.com/mcp', # MCP server URL (required) redirect_uri: 'http://localhost:8080/callback', # OAuth redirect URI scope: 'mcp:read mcp:write', # OAuth scope logger: Logger.new($stdout), # Logger instance storage: custom_storage # Custom storage backend ) ``` -------------------------------- ### Ruby Client Metadata Configuration Source: https://github.com/simonx1/ruby-mcp-client/blob/main/OAUTH.md Shows how to instantiate MCPClient::Auth::ClientMetadata with details like redirect URIs, token endpoint authentication methods, grant types, response types, and scope, essential for client registration and OAuth flows. ```ruby metadata = MCPClient::Auth::ClientMetadata.new( redirect_uris: ['http://localhost:8080/callback'], token_endpoint_auth_method: 'none', grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], scope: 'mcp:read mcp:write' ) ``` -------------------------------- ### Server Creation Configuration Options Source: https://github.com/simonx1/ruby-mcp-client/blob/main/OAUTH.md Details the various configuration options available when creating an OAuth-enabled MCP HTTP server. These options control aspects like server URL, redirect URI, scopes, timeouts, and logging. ```ruby server = MCPClient::OAuthClient.create_http_server( server_url: 'https://api.example.com/mcp', # MCP server URL (required) redirect_uri: 'http://localhost:8080/callback', # OAuth redirect URI scope: 'mcp:read mcp:write', # OAuth scope endpoint: '/rpc', # JSON-RPC endpoint headers: {}, # Additional HTTP headers read_timeout: 30, # Request timeout retries: 3, # Retry attempts retry_backoff: 1, # Retry backoff name: 'my-server', # Server name logger: Logger.new($stdout), # Logger instance storage: custom_storage # Custom storage backend ) ``` -------------------------------- ### OpenAI Integration (Community Gem) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Demonstrates integrating the Ruby MCP client with the community `alexrudall/ruby-openai` gem. Similar to the official gem integration, it covers converting MCP tools for use with the OpenAI client. ```ruby # Using the alexrudall/ruby-openai gem (community) require 'mcp_client' require 'openai' # Create MCP client mcp_client = MCPClient.create_client( mcp_server_configs: [ MCPClient.stdio_config(command: 'npx @playwright/mcp@latest') ] ) # Convert tools to OpenAI format tools = mcp_client.to_openai_tools # Use with Ruby-OpenAI client client = OpenAI::Client.new(access_token: ENV['OPENAI_API_KEY']) ``` -------------------------------- ### Manual OAuth Provider Configuration Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Shows how to manually configure and manage an OAuth provider for more granular control over the authentication flow. This includes direct instantiation, updating configuration parameters like scope and redirect URI, and initiating/completing authorization. ```Ruby # Create OAuth provider directly oauth_provider = MCPClient::Auth::OAuthProvider.new( server_url: 'https://api.example.com/mcp', redirect_uri: 'http://localhost:8080/callback', scope: 'mcp:read mcp:write' ) # Update configuration at runtime oauth_provider.scope = 'mcp:read mcp:write admin' oauth_provider.redirect_uri = 'http://localhost:9000/callback' # Start authorization flow auth_url = oauth_provider.start_authorization_flow # Complete flow after user authorization token = oauth_provider.complete_authorization_flow(code, state) ``` -------------------------------- ### MCP Server Compatibility Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Lists various MCP-compatible servers and frameworks that the Ruby MCP client can interact with. ```APIDOC MCP Server Compatibility: This client works with any MCP-compatible server, including: - @modelcontextprotocol/server-filesystem: File system access - @playwright/mcp: Browser automation - FastMCP: Python framework for building MCP servers - Custom servers implementing the MCP protocol ``` -------------------------------- ### MCP Server Configuration Options Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Illustrates defining MCP server configurations using JSON, supporting multiple server types like SSE, HTTP, and stdio, with various connection parameters. ```json { "mcpServers": { "playwright": { "type": "sse", "url": "http://localhost:8931/sse", "headers": { "Authorization": "Bearer TOKEN" } }, "api_server": { "type": "http", "url": "https://api.example.com", "endpoint": "/mcp", "headers": { "Authorization": "Bearer API_TOKEN", "X-Custom-Header": "value" } }, "filesystem": { "type": "stdio", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"], "env": { "DEBUG": "true" } } } } ``` ```json { "mcpServers": { "playwright": { "url": "http://localhost:8931/sse", "headers": {}, "comment": "Local Playwright MCP Server running on port 8931" } } } ``` -------------------------------- ### Format Tools for AI Services (Ruby) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Converts the client's available tools into formats compatible with specific AI service APIs, such as OpenAI, Anthropic, or Google. This simplifies integration with AI models. ```ruby # Format tools for specific AI servicesopenai_tools = client.to_openai_tools anthropic_tools = client.to_anthropic_tools google_tools = client.to_google_tools ``` -------------------------------- ### Call Tool by Name (Ruby) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Demonstrates how to invoke a specific tool on an MCP server using its name and providing parameters. This is the primary method for executing tool functionality. ```ruby result = client.call_tool('example_tool', { param1: 'value1', param2: 42 }) ``` -------------------------------- ### OpenAI Integration (Official Gem) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Illustrates how to integrate the Ruby MCP client with the official `openai/openai-ruby` gem. It shows converting MCP tools into OpenAI's format and using them within an OpenAI client for chat completions. ```ruby # Using the openai/openai-ruby gem (official) require 'mcp_client' require 'openai' # Create MCP client mcp_client = MCPClient.create_client( mcp_server_configs: [ MCPClient.stdio_config( command: %W[npx -y @modelcontextprotocol/server-filesystem #{Dir.pwd}] ) ] ) # Convert tools to OpenAI format tools = mcp_client.to_openai_tools # Use with OpenAI client client = OpenAI::Client.new(api_key: ENV['OPENAI_API_KEY']) response = client.chat.completions.create( model: 'gpt-4', messages: [ { role: 'user', content: 'List files in current directory' } ], tools: tools ) # Process tool calls and results # See examples directory for complete implementation ``` -------------------------------- ### OAuth 2.1 Authentication Flow Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Illustrates how to set up and use OAuth 2.1 authentication with the Ruby MCP Client. It covers creating an OAuth-enabled server configuration, checking token validity, initiating the OAuth flow, and completing it after user authorization. ```Ruby require 'mcp_client' # Create an OAuth-enabled HTTP server server = MCPClient::OAuthClient.create_http_server( server_url: 'https://api.example.com/mcp', redirect_uri: 'http://localhost:8080/callback', scope: 'mcp:read mcp:write' ) # Check if authorization is needed unless MCPClient::OAuthClient.valid_token?(server) # Start OAuth flow auth_url = MCPClient::OAuthClient.start_oauth_flow(server) puts "Please visit: #{auth_url}" # After user authorization, complete the flow # token = MCPClient::OAuthClient.complete_oauth_flow(server, code, state) end # Use the server normally server.connect tools = server.list_tools ``` -------------------------------- ### Ruby Token Creation and Usage Source: https://github.com/simonx1/ruby-mcp-client/blob/main/OAUTH.md Demonstrates creating an MCPClient::Auth::Token object with access token, type, expiry, scope, and refresh token. Includes methods for checking token status (expired?, expires_soon?) and formatting for headers (to_header). ```ruby token = MCPClient::Auth::Token.new( access_token: 'abc123', token_type: 'Bearer', expires_in: 3600, scope: 'mcp:read mcp:write', refresh_token: 'refresh123' ) # Check token status token.expired? # Boolean token.expires_soon? # Boolean (within 5 minutes) token.to_header # "Bearer abc123" ``` -------------------------------- ### MCP Server Definition JSON Formats Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Illustrates the different JSON structures that can be used to define MCP servers for client configuration. ```APIDOC MCP Server Definition JSON Formats: 1. Single Server Object: - SSE Type: { "type": "sse", "url": "http://example.com/sse" } - HTTP Type: { "type": "http", "url": "http://example.com", "endpoint": "/rpc" // Optional, defaults to "/rpc" } 2. Array of Server Objects: [ { "type": "stdio", "command": "npx server" }, { "type": "sse", "url": "http://..." }, { "type": "http", "url": "http://...", "endpoint": "/api" } ] 3. Object with Named Servers: { "mcpServers": { "server1": { "type": "sse", "url": "http://..." }, "server2": { "type": "http", "url": "http://..." } } } Note: Servers defined this way are accessible by their keys (e.g., 'server1', 'server2'). ``` -------------------------------- ### MCP Client Tool Formatting Methods Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Helper methods within the MCPClient::Client class to format tool definitions for specific AI service APIs. ```APIDOC MCPClient::Client Tool Formatting Methods: - `to_openai_tools()` - Description: Formats the client's tools for compatibility with the OpenAI API. - Parameters: None. - Returns: An array of tool definitions suitable for OpenAI. - `to_anthropic_tools()` - Description: Formats the client's tools for compatibility with the Anthropic Claude API. - Parameters: None. - Returns: An array of tool definitions suitable for Anthropic. - `to_google_tools()` - Description: Formats the client's tools for compatibility with the Google Vertex AI API. Automatically removes '$schema' keys which are not accepted by Vertex AI. - Parameters: None. - Returns: An array of tool definitions suitable for Google Vertex AI. ``` -------------------------------- ### Ruby Server Metadata Configuration Source: https://github.com/simonx1/ruby-mcp-client/blob/main/OAUTH.md Illustrates creating an MCPClient::Auth::ServerMetadata object, specifying the issuer, authorization endpoint, token endpoint, and registration endpoint. This metadata is crucial for clients to discover and interact with the authorization server. ```ruby metadata = MCPClient::Auth::ServerMetadata.new( issuer: 'https://auth.example.com', authorization_endpoint: 'https://auth.example.com/authorize', token_endpoint: 'https://auth.example.com/token', registration_endpoint: 'https://auth.example.com/register' ) ``` -------------------------------- ### Call Tool on Specific Server (Ruby) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Shows how to target a specific server for tool execution by providing a server identifier. This allows for routing requests to particular server instances or types. ```ruby # Call a tool on a specific server by name result = client.call_tool('example_tool', { param1: 'value1' }, server: 'filesystem') # You can also call a tool on a server directly result = filesystem_server.call_tool('example_tool', { param1: 'value1' }) ``` -------------------------------- ### Running OAuth-related Tests Source: https://github.com/simonx1/ruby-mcp-client/blob/main/OAUTH.md Commands to execute the unit tests for the MCP Client's OAuth functionality using RSpec. These tests cover various aspects of authentication and authorization flows. ```bash bundle exec rspec spec/lib/mcp_client/auth_spec.rb bundle exec rspec spec/lib/mcp_client/auth/oauth_provider_spec.rb bundle exec rspec spec/lib/mcp_client/oauth_client_spec.rb ``` -------------------------------- ### Manage Client Cache and Cleanup (Ruby) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Includes utility methods for managing the client's internal state. 'clear_cache' forces a refresh of tool information, and 'cleanup' releases resources and closes connections. ```ruby # Clear cached tools to force fresh fetch on next list client.clear_cache # Clean up connections client.cleanup ``` -------------------------------- ### Register for Server Notifications (Ruby) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Allows the client to subscribe to real-time notifications from servers. The provided block is executed whenever a notification is received, enabling event-driven updates. ```ruby # Register for server notifications client.on_notification do |server, method, params| puts "Server notification: #{server.class}[#{server.name}] - #{method} - #{params}" # Handle specific notifications based on method name # 'notifications/tools/list_changed' is handled automatically by the client end ``` -------------------------------- ### Tool Schema Definition Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Defines the structure for describing tools, including their name, a textual description, and a JSON Schema for validating parameters. This schema is used by the MCP client to understand and interact with available tools. ```json { "name": "example_tool", "description": "Does something useful", "schema": { "type": "object", "properties": { "param1": { "type": "string" }, "param2": { "type": "number" } }, "required": ["param1"] } } ``` -------------------------------- ### Server-Sent Events (SSE) Client Configuration and Usage Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Shows how to configure and use the MCP client with a Playwright MCP server via SSE. It details connection parameters like base URL, timeouts, ping intervals, retries, and logging, along with common browser automation tool calls. ```ruby require 'mcp_client' require 'logger' # Optional logger for debugging logger = Logger.new($stdout) logger.level = Logger::INFO # Create an MCP client that connects to a Playwright MCP server via SSE # First run: npx @playwright/mcp@latest --port 8931 sse_client = MCPClient.create_client( mcp_server_configs: [ MCPClient.sse_config( base_url: 'http://localhost:8931/sse', read_timeout: 30, # Timeout in seconds for request fulfillment ping: 10, # Send ping after 10 seconds of inactivity # Connection closes automatically after inactivity (2.5x ping interval) retries: 2, # Number of retry attempts on transient errors logger: logger # Optional logger for debugging connection issues ) ] ) # List available tools tools = sse_client.list_tools # Launch a browser result = sse_client.call_tool('browser_install', {}) result = sse_client.call_tool('browser_navigate', { url: 'about:blank' }) # No browser ID needed with these tool names # Create a new page page_result = sse_client.call_tool('browser_tab_new', {}) # No page ID needed with these tool names # Navigate to a website sse_client.call_tool('browser_navigate', { url: 'https://example.com' }) # Get page title title_result = sse_client.call_tool('browser_snapshot', {}) puts "Page snapshot: #{title_result}" # Take a screenshot screenshot_result = sse_client.call_tool('browser_take_screenshot', {}) # Ping the server to verify connectivity ping_result = sse_client.ping puts "Ping successful: #{ping_result.inspect}" # Clean up sse_client.cleanup # See `examples/mcp_sse_server_example.rb` for the full Playwright SSE example. ``` -------------------------------- ### MCP Server Interaction and JSON-RPC Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Details the expected interactions with an MCP server, including required request handling for tool listing and execution, and supported JSON-RPC notifications. It also outlines the client's mechanism for handling server-sent notifications. ```APIDOC MCP Server Requirements: - Listen on chosen transport (JSON-RPC stdio, HTTP SSE, HTTP, or Streamable HTTP). - Respond to `list_tools` requests with a JSON list of tools. - Respond to `call_tool` requests by executing the specified tool. - Return results (or errors) in JSON format. - Optionally send JSON-RPC notifications for events like tool updates. JSON-RPC Notifications: - `notifications/tools/list_changed`: Default notification handler to automatically clear the tool cache. - Custom notification handling via the `on_notification` method. `on_notification` Method: - Signature: `on_notification(server_instance, method_name, parameters)` - Description: Callback for handling server-sent JSON-RPC notifications. - Parameters: - `server_instance`: The server instance sending the notification. - `method_name`: The name of the JSON-RPC method (notification). - `parameters`: The parameters associated with the notification. - Usage: Allows for custom logic to be executed when specific server events occur. ``` -------------------------------- ### Resumability and Redelivery (Streamable HTTP) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Explains the additional resumability features provided by the Streamable HTTP transport for reliable message delivery, including event ID tracking and connection recovery. ```APIDOC Resumability and Redelivery (Streamable HTTP): - Event ID Tracking: Automatically tracks event IDs from SSE responses. - Last-Event-ID Header: Includes `Last-Event-ID` header in requests for resuming from disconnection points. - Message Replay: Enables servers to replay missed messages from the last received event. - Connection Recovery: Maintains message continuity even with unstable network connections. ``` -------------------------------- ### Check Server Connectivity (Ruby) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Provides methods to check the connectivity and responsiveness of MCP servers. 'ping' performs a basic heartbeat call, optionally targeting a specific server by its index. ```ruby # Check server connectivity client.ping # Basic connectivity check (zero-parameter heartbeat call) client.ping(server_index: 1) # Ping a specific server by index ``` -------------------------------- ### Streamable HTTP Transport Configuration (Ruby) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Configures the MCP client for servers using Streamable HTTP, which handles Server-Sent Events (SSE) via POST requests. This is common for services like Zapier's MCP implementation. ```ruby require 'mcp_client' require 'logger' # Optional logger for debugging logger = Logger.new($stdout) logger.level = Logger::INFO # Create an MCP client that connects to a Streamable HTTP MCP server streamable_client = MCPClient.create_client( mcp_server_configs: [ MCPClient.streamable_http_config( base_url: 'https://mcp.zapier.com/api/mcp/s/YOUR_SESSION_ID/mcp', headers: { 'Authorization' => 'Bearer YOUR_ZAPIER_TOKEN' }, read_timeout: 60, # Timeout in seconds for HTTP requests retries: 3, # Number of retry attempts on transient errors retry_backoff: 2, # Base delay in seconds for exponential backoff logger: logger # Optional logger for debugging requests ) ] ) # Further operations with streamable_client would follow similar patterns to other clients, # but the transport handles SSE responses. ``` -------------------------------- ### Call Tools in Batch (Ruby) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Enables executing multiple tool calls concurrently or in a single request. This is useful for improving efficiency by reducing network overhead for sequential operations. ```ruby # Call multiple tools in batch results = client.call_tools([ { name: 'tool1', parameters: { key1: 'value1' } }, { name: 'tool2', parameters: { key2: 'value2' }, server: 'filesystem' } # Specify server for a specific tool ]) ``` -------------------------------- ### HTTP Transport Configuration (Ruby) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Configures the MCP client to use the HTTP transport for communication. This involves specifying the server's base URL, endpoint, headers, timeouts, and retry logic. ```ruby require 'mcp_client' require 'logger' # Optional logger for debugging logger = Logger.new($stdout) logger.level = Logger::INFO # Create an MCP client that connects to an HTTP MCP server http_client = MCPClient.create_client( mcp_server_configs: [ MCPClient.http_config( base_url: 'https://api.example.com', endpoint: '/mcp', # JSON-RPC endpoint path headers: { 'Authorization' => 'Bearer YOUR_API_TOKEN', 'X-Custom-Header' => 'custom-value' }, read_timeout: 30, # Timeout in seconds for HTTP requests retries: 3, # Number of retry attempts on transient errors retry_backoff: 1, # Base delay in seconds for exponential backoff logger: logger # Optional logger for debugging HTTP requests ) ] ) # List available tools tools = http_client.list_tools # Call a tool result = http_client.call_tool('analyze_data', { dataset: 'sales_2024', metrics: ['revenue', 'conversion_rate'] }) # HTTP transport also supports streaming (though implemented as single response) # This provides API compatibility with SSE transport http_client.call_tool_streaming('process_batch', { batch_id: 123 }).each do |result| puts "Processing result: #{result}" end # Send custom JSON-RPC requests custom_result = http_client.send_rpc('custom_method', params: { key: 'value' }) # Send notifications (fire-and-forget) http_client.send_notification('status_update', params: { status: 'processing' }) # Test connectivity ping_result = http_client.ping puts "Server is responsive: #{ping_result.inspect}" # Clean up http_client.cleanup ``` -------------------------------- ### Server-Sent Events (SSE) Client Features Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Details the advanced features of the SSE client, including connection management, inactivity tracking, automatic pinging, intelligent reconnection with exponential backoff, and thread safety. It supports JSON-RPC over SSE and streaming updates. ```APIDOC SSE Client Features: - Robust connection handling with configurable timeouts and retries. - Automatic redirect support (up to 3 hops). - Advanced connection management: - Inactivity tracking. - Automatic ping (default: 10s inactivity). - Automatic disconnection (2.5x ping interval). - MCP compliant: Server communication resets inactivity timer. - Intelligent reconnection: - Ping failure detection (3 consecutive failures). - Exponential backoff between attempts. - Smart retry limits (default: 5). - Connection state monitoring. - Failure transparency (background reconnection). - Thread safety using monitors and synchronized access. - Reliable error handling for network issues, timeouts, and malformed responses. - JSON-RPC 2.0 over SSE transport with initialize handshake. - Streaming support via `call_tool_streaming` (returns Enumerator). - Notification support with automatic tool cache invalidation and custom callbacks. - Custom RPC methods via `send_rpc` and `send_notification`. - Configurable retries for RPC requests with exponential backoff. - Consistent, tagged, leveled logging. - Graceful fallback to synchronous HTTP on SSE failure. - URL normalization. - Server connectivity check via `ping` method. ``` -------------------------------- ### Send Custom RPC Requests/Notifications (Ruby) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Enables sending arbitrary JSON-RPC requests or notifications to MCP servers. This is useful for custom communication or invoking methods not directly exposed as tools. ```ruby # Send custom JSON-RPC requests or notifications client.send_rpc('custom_method', params: { key: 'value' }, server: :sse) # Uses specific server by type client.send_rpc('custom_method', params: { key: 'value' }, server: 'filesystem') # Uses specific server by name result = client.send_rpc('another_method', params: { data: 123 }) # Uses first available server client.send_notification('status_update', params: { status: 'ready' }) ``` -------------------------------- ### Session Management Features Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Details the session management capabilities for HTTP and Streamable HTTP transports, including automatic session ID handling, injection, termination, validation, and backward compatibility. ```APIDOC Session Management Features: - Automatic Session Management: Captures session IDs from `initialize` response headers. - Session Header Injection: Automatically includes `Mcp-Session-Id` header in subsequent requests. - Session Termination: Sends HTTP DELETE requests to properly terminate sessions during cleanup. - Session Validation: Validates session ID format for security (8-128 alphanumeric characters with hyphens/underscores). - Backward Compatibility: Works with both session-based and stateless MCP servers. - Session Cleanup: Properly cleans up session state during connection teardown. ``` -------------------------------- ### HTTP Transport Client Features Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Details the features of the HTTP transport, which offers a stateless communication mechanism for MCP servers. It supports standard HTTP request/response cycles, session management, JSON-RPC over HTTP, and configurable retries. ```APIDOC HTTP Transport Features: - Request/Response Model: Standard HTTP request/response cycle per JSON-RPC call. - Automatic redirect support (up to 3 hops). - JSON-Only Responses: Accepts only `application/json`. - Session Support: - Automatic session header (`Mcp-Session-Id`) capture and injection. - Proper session cleanup with HTTP DELETE requests. - Security validation of session IDs. - Supports stateless and session-based servers. - HTTP Headers Support: Full support for custom headers (authorization, API keys, etc.). - Reliable Error Handling: Comprehensive HTTP status code handling. - Configurable Retries: Exponential backoff for transient network failures. - Connection Pooling: Uses Faraday's connection pooling. - Timeout Management: Configurable connection and request timeouts. - JSON-RPC 2.0 over HTTP POST requests. - MCP Protocol Compliance: Supports standard MCP methods (`initialize`, `tools/list`, `tools/call`). - Custom RPC Methods: Send any custom JSON-RPC method or notification. - Thread Safety: All operations are thread-safe. - Streaming API Compatibility: `call_tool_streaming` method (returns single response). - Graceful Degradation: Simple fallback behavior. ``` -------------------------------- ### Stream Tool Results (Ruby) Source: https://github.com/simonx1/ruby-mcp-client/blob/main/README.md Facilitates receiving results from a tool call as they become available, typically used for long-running operations or real-time data processing. Returns an Enumerator for processing chunks. ```ruby # Stream results (supported by the SSE transport) # Returns an Enumerator that yields results as they become available client.call_tool_streaming('streaming_tool', { param: 'value' }, server: 'api').each do |chunk| # Process each chunk as it arrives puts chunk end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.