diff --git a/Gemfile b/Gemfile index 71df3a14..8e853a4d 100644 --- a/Gemfile +++ b/Gemfile @@ -6,7 +6,9 @@ gemspec group :development do if RUBY_VERSION >= "3.1.0" - gem "mcp", "~> 0.7" + gem "event_stream_parser", ">= 1" + gem "faraday", ">= 2" + gem "mcp", "~> 0.25" end # Development dependencies diff --git a/README.md b/README.md index cff5f2fc..68e56619 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ RubyLLM::MCP is a Ruby client for the [Model Context Protocol (MCP)](https://mod Use MCP tools, resources, and prompts from your RubyLLM chats over `stdio`, streamable HTTP, or SSE. -**Protocol support:** Fully supports MCP spec `2025-06-18` (stable), with draft spec `2026-01-26` available. +**Protocol support:** Fully supports MCP spec `2025-11-25` (stable), with draft spec `2026-01-26` available. ## RubyLLM::MCP Out of the Box @@ -23,7 +23,7 @@ Our goal is to be able to plug MCP into Ruby/RubyLLM apps as easily as possible. RubyLLM::MCP gives you that: - Ruby-first API for using MCP tools, resources, and prompts directly in RubyLLM chat workflows -- Stable protocol track by default (`2025-06-18`), with opt-in draft track (`2026-01-26`) +- Stable protocol track by default (`2025-11-25`), with opt-in draft track (`2026-01-26`) - Built-in notification and response handlers for real-time and interactive workflows - MCP OAuth 2.1 authentication support (PKCE, dynamic registration, discovery, and automatic token refresh) - OAuth setup paths for Rails apps (per-user connections) and browser-based CLI flows @@ -154,7 +154,11 @@ bundle install If you want the official SDK adapter, also add: ```ruby -gem "mcp", "~> 0.7" +gem "mcp", "~> 0.25" + +# Also required when mcp_sdk uses Streamable HTTP +gem "faraday", ">= 2" +gem "event_stream_parser", ">= 1" ``` ## Rails diff --git a/docs/client/elicitation.md b/docs/client/elicitation.md index 8007ebfc..9496912c 100644 --- a/docs/client/elicitation.md +++ b/docs/client/elicitation.md @@ -11,6 +11,8 @@ description: "MCP elicitation - allow servers to request additional structured i Elicitation allows MCP servers to request additional structured information from users during interactions. This enables dynamic workflows where servers can ask for clarification, gather additional context, or collect user preferences in real-time. +Elicitation is available through the native adapter's supported transports and through `:mcp_sdk` Streamable HTTP. Official SDK stdio does not expose server-request handlers in version 0.25. + ## Table of contents {: .no_toc .text-delta } diff --git a/docs/client/sampling.md b/docs/client/sampling.md index 0d8515f9..a216297d 100644 --- a/docs/client/sampling.md +++ b/docs/client/sampling.md @@ -11,6 +11,8 @@ description: "MCP sampling - allow servers to use your LLM for their own request MCP sampling allows servers to offload LLM requests to your client rather than making them directly. This enables servers to use your LLM connections and configurations while maintaining their own logic and workflows. +Sampling is available through the native adapter's supported transports and through `:mcp_sdk` Streamable HTTP. Official SDK stdio does not expose server-request handlers in version 0.25. + ## Table of contents {: .no_toc .text-delta } diff --git a/docs/configuration.md b/docs/configuration.md index 965630f1..e0c1c0d8 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -97,14 +97,15 @@ end ### Adapter Options **`:ruby_llm`** (default) -- Full MCP protocol implementation -- All transport types (stdio, SSE, HTTP) -- Advanced features (sampling, roots, progress tracking, etc.) +- Independent RubyLLM::MCP protocol implementation and transports +- Stdio, legacy SSE, and Streamable HTTP +- Full notification-oriented feature set, roots, subscriptions, progress, tasks, sampling, and elicitation **`:mcp_sdk`** -- Official Anthropic-maintained SDK -- Core features only (tools, resources, prompts) -- Limited transport support (stdio, HTTP - no SSE) +- Official Model Context Protocol Ruby SDK 0.25 +- Official stdio and Streamable HTTP transports only +- Tools, resources, prompts, templates, completions, pagination, structured output, cache hints, and extensions +- HTTP additionally supports official OAuth providers, sampling, and elicitation See the [Adapters Guide]({% link guides/adapters.md %}) for detailed feature comparison and usage examples. @@ -442,7 +443,7 @@ The RubyLLM MCP client supports multiple protocol versions. You can access these ```ruby # Latest supported protocol version puts RubyLLM::MCP::Native::Protocol.latest_version -# => "2025-06-18" +# => "2025-11-25" # Draft protocol version (opt-in) puts RubyLLM::MCP::Native::Protocol.draft_version @@ -454,7 +455,7 @@ puts RubyLLM::MCP::Native::Protocol.default_negotiated_version # All supported versions puts RubyLLM::MCP::Native::Protocol.supported_versions -# => ["2026-01-26", "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"] +# => ["2026-01-26", "2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"] # Check if a version is supported RubyLLM::MCP::Native::Protocol.supported_version?("2025-06-18") @@ -466,7 +467,8 @@ RubyLLM::MCP::Native::Protocol.supported_version?("2025-06-18") Different protocol versions support different features: - **2026-01-26** (Draft, opt-in): Draft extension negotiation path -- **2025-06-18** (Latest): Structured tool output, OAuth authentication, elicitation support, resource links, enhanced metadata +- **2025-11-25** (Latest stable): Current stable lifecycle and client/server feature set +- **2025-06-18**: Structured tool output, OAuth authentication, elicitation support, resource links, enhanced metadata - **2025-03-26** (Default): Tool calling, resources, prompts, completions, notifications - **2024-11-05**: Basic tool and resource support - **2024-10-07**: Initial MCP implementation @@ -516,7 +518,8 @@ Notes: - Outbound extension advertisement uses canonical ID `io.modelcontextprotocol/ui` - Alias `io.modelcontextprotocol/apps` is accepted for inbound capability reads and config merge - Extension advertisement is supported on stable `2025-06-18+` and draft protocol versions -- `:mcp_sdk` accepts extension config in passive mode (no capability advertisement, one warning per process when configured) +- Both adapters advertise configured extensions on supported protocol versions +- The SDK adapter passes extension capabilities through its official `connect` handshake For architecture and MCP Apps metadata details, see **[Client Extensions]({% link extensions/index.md %})** and **[MCP Apps]({% link extensions/mcp-apps.md %})**. diff --git a/docs/extensions/index.md b/docs/extensions/index.md index 53111d49..ae968976 100644 --- a/docs/extensions/index.md +++ b/docs/extensions/index.md @@ -84,7 +84,7 @@ Extension advertisement is protocol-version aware. ## Adapter Modes - `:ruby_llm` adapter: **full** extension mode (`capabilities.extensions` advertised when protocol supports it) -- `:mcp_sdk` adapter: **passive** extension mode (config accepted, metadata parsing still works, no extension capability advertisement) +- `:mcp_sdk` adapter: **full** extension mode through the official 0.25 `connect` handshake ## Next Steps diff --git a/docs/extensions/mcp-apps.md b/docs/extensions/mcp-apps.md index ffaa29da..e9a9fda1 100644 --- a/docs/extensions/mcp-apps.md +++ b/docs/extensions/mcp-apps.md @@ -98,8 +98,8 @@ puts meta.permissions.inspect ## Adapter Notes - `:ruby_llm` and `:mcp_sdk` both expose parsed `apps_metadata` -- Only `:ruby_llm` advertises extension capabilities in full mode -- `:mcp_sdk` remains passive for capability advertisement +- Both adapters expose parsed metadata and advertise extension capabilities on supported protocol versions +- `:mcp_sdk` delegates negotiation to the official SDK 0.25 lifecycle ## Practical Flow diff --git a/docs/getting-started/overview.md b/docs/getting-started/overview.md index b6467284..cc9f91a5 100644 --- a/docs/getting-started/overview.md +++ b/docs/getting-started/overview.md @@ -54,7 +54,7 @@ The same client API can then be extended with resources, prompts, notifications, 1. **RubyLLM Chat** - Your application chat/session logic 2. **RubyLLM MCP Client** - Connection and protocol wrapper -3. **Adapter** - `:ruby_llm` (full) or `:mcp_sdk` (core/passive extensions) +3. **Adapter** - `:ruby_llm` (native implementation/transports) or `:mcp_sdk` (official SDK 0.25/transports) 4. **Transport** - `stdio`, `streamable`, `sse` 5. **MCP Server** - External capability provider @@ -81,9 +81,9 @@ Use synchronous responses for short operations, notifications for real-time stat RubyLLM MCP supports two adapters: - **Native (`:ruby_llm`)** - Full-featured implementation with advanced MCP capabilities (sampling, roots, notifications, progress, tasks, elicitation). -- **MCP SDK (`:mcp_sdk`)** - Official SDK-backed adapter focused on core surfaces (tools, resources, prompts, templates, logging). +- **MCP SDK (`:mcp_sdk`)** - Official SDK 0.25 adapter with tools, resources, prompts, templates, completions, pagination, structured output, extension negotiation, and HTTP sampling/elicitation/OAuth. -Choose `:ruby_llm` when you need full protocol coverage and advanced interactions. Choose `:mcp_sdk` when you only need core MCP surfaces and want SDK alignment. +Choose `:ruby_llm` for the project's established transports and full notification-oriented feature set. Choose `:mcp_sdk` when you want the official SDK lifecycle, stdio/Streamable HTTP transports, OAuth providers, and low-level SDK access. For the full feature matrix, see **[Adapters & Transports]({% link guides/adapters.md %})**. diff --git a/docs/guides/adapters.md b/docs/guides/adapters.md index da13ea45..7725ce0b 100644 --- a/docs/guides/adapters.md +++ b/docs/guides/adapters.md @@ -3,552 +3,193 @@ layout: default title: Adapters & Transports parent: Guides nav_order: 4 -description: "Understanding MCP adapters, transports, and building custom transport implementations" +description: "Choose between RubyLLM::MCP's native implementation and the official MCP SDK 0.25." --- # Adapters & Transports -{: .no_toc } -{: .label .label-green } -1.0+ +RubyLLM::MCP has two independent client implementations. They share the public RubyLLM::MCP objects, but they do not share protocol or transport internals. -RubyLLM MCP 1.0 provides a mature, stable adapter system with multiple SDK implementations and transport types, giving you complete control over how your application communicates with MCP servers. +## Adapter Boundaries -## Table of contents -{: .no_toc .text-delta } +### Native (`:ruby_llm`) -1. TOC -{:toc} +The default adapter uses this gem's established `RubyLLM::MCP::Native` client and transports. Installing the optional `mcp` gem does not replace or modify this path. ---- - -## Overview - -RubyLLM MCP provides two key architectural components: - -**Adapters** - Choose which SDK implementation powers your MCP clients: -- Use the native `:ruby_llm` adapter for full MCP feature support built inside the gem -- Use the official `:mcp_sdk` adapter maintained by Anthropic (requires Ruby 3.1+) -- Mix both adapters in the same application for different servers - -**Transports** - Handle the communication layer between your Ruby client and MCP servers: -- Establish connections -- Send requests and receive responses -- Manage the connection lifecycle -- Handle protocol-specific details - -## Available Adapters - -### RubyLLM Adapter (`:ruby_llm`) - -The default, full-featured adapter that implements the complete MCP protocol with extensions. - -**Key Features:** -- ✅ Complete MCP protocol implementation with advanced features (sampling, roots, progress tracking, elicitation) -- ✅ Experimental task lifecycle support (`tasks/list`, `tasks/get`, `tasks/result`, `tasks/cancel`) -- ✅ All transport types supported (stdio, SSE, streamable HTTP) -- ✅ **Custom transport support** - Register and use your own transport implementations -- ✅ Ruby 2.7+ compatible - -**Best for:** Full-featured MCP integrations, custom transport requirements, and advanced protocol features. - -### MCP SDK Adapter (`:mcp_sdk`) - -Wraps the official MCP SDK maintained by Anthropic. - -{: .important } -> **Ruby 3.1+ Required** -> The official `mcp` gem requires Ruby 2.7+, and RubyLLM MCP requires Ruby 3.1.3+. If you're using an older Ruby version, use the `:ruby_llm` adapter instead. - -**Key Features:** -- ✅ Official Anthropic-maintained implementation -- ✅ Core MCP features (tools, resources, prompts, resource templates, logging) -- ✅ Basic transports (stdio, HTTP) with custom wrapper support -- ⚠️ No custom transport registration - requires Ruby 3.1+ - -**Best for:** Reference implementation compatibility and core MCP features only. - -## Feature Comparison - -| Feature | RubyLLM Adapter | MCP SDK Adapter | -|---------|-----------------|-----------------| -| **Core Features** | -| Tools (list/call) | ✅ | ✅ | -| Resources (list/read) | ✅ | ✅ | -| Prompts (list/get) | ✅ | ✅ | -| Resource Templates | ✅ | ✅ | -| **Transports** | -| stdio | ✅ | ✅ | -| HTTP/Streamable | ✅ | ✅ | -| SSE | ✅ | ✅ | -| **Advanced Features** | -| Completions | ✅ | ❌ | -| Logging | ✅ | ✅ | -| Sampling | ✅ | ❌ | -| Roots | ✅ | ❌ | -| Notifications | ✅ | ❌ | -| Progress Tracking | ✅ | ❌ | -| Human-in-the-Loop | ✅ | ❌ | -| Elicitation | ✅ | ❌ | -| Tasks | ✅ | ❌ | -| Resource Subscriptions | ✅ | ❌ | - -Task support in the `:ruby_llm` adapter is experimental and subject to change in both the MCP spec and this gem implementation. - -## Transport Compatibility +Choose native for: -Custom transports are implemented by the adapter and are not part of the official MCP SDK and are based on the native transports. - -| Transport | RubyLLM Adapter | MCP SDK Adapter | -|-----------|-----------------|-----------------| -| `:stdio` | ✅ | Custom | -| `:http` | ✅ | ✅ | -| `:streamable` | ✅ | Custom | -| `:streamable_http` | ✅ | Custom | -| `:sse` | ✅ | Custom | - ---- - -## Built-in Transport Types - -### STDIO Transport - -Best for local MCP servers that communicate via standard input/output: +- Stdio, legacy SSE, and Streamable HTTP using RubyLLM::MCP transports +- Roots and resource subscriptions +- Logging, progress, and list-changed notifications +- Sampling, elicitation, and human-in-the-loop approval +- Task lifecycle APIs +- Custom native transport registration ```ruby client = RubyLLM::MCP.client( - name: "local-server", - transport_type: :stdio, - config: { - command: "python", - args: ["-m", "my_mcp_server"], - env: { "DEBUG" => "1" } - } + name: "native-server", + adapter: :ruby_llm, + transport_type: :streamable, + config: { url: "https://example.com/mcp" } ) ``` -**Use cases:** +### Official SDK (`:mcp_sdk`) -- Local development -- Command-line MCP servers -- Subprocess-based servers +This adapter requires `mcp ~> 0.25` and delegates lifecycle and communication to the official Model Context Protocol Ruby SDK. -### SSE Transport (Server-Sent Events) +Choose it for: -Best for web-based MCP servers using HTTP with server-sent events: +- Official `MCP::Client::Stdio` and `MCP::Client::HTTP` transports +- Official initialization, session, reconnection, cancellation, and ping behavior +- Tools, resources, prompts, templates, completions, and pagination +- Structured output, metadata, cache hints, and extension negotiation +- Official HTTP OAuth providers, sampling, and elicitation +- Direct access to the connected `MCP::Client` ```ruby client = RubyLLM::MCP.client( - name: "web-server", - transport_type: :sse, - config: { - url: "https://api.example.com/mcp/sse", - version: :http2, # You can force HTTP/1.1 by setting this to :http1, default will try to setup HTTP/2 connection - headers: { "Authorization" => "Bearer token" } - } + name: "official-sdk-server", + adapter: :mcp_sdk, + transport_type: :streamable_http, + config: { url: "https://example.com/mcp" } ) ``` -**Use cases:** +See [Official MCP SDK 0.25]({% link guides/mcp-sdk-0.25.md %}) for complete installation, OAuth, server-request, and migration examples. -- Web-based MCP services -- Real-time communication needs -- HTTP-based infrastructure +## Feature Matrix -### Streamable HTTP Transport +| Feature | Native stdio | Native HTTP/SSE | SDK stdio | SDK HTTP | +|:--|:--:|:--:|:--:|:--:| +| Tools, resources, prompts, templates | Yes | Yes | Yes | Yes | +| Completions and pagination | Yes | Yes | Yes | Yes | +| Structured tool output | Yes | Yes | Yes | Yes | +| Extension/MCP Apps negotiation | Yes | Yes | Yes | Yes | +| SDK cache-hint expiry | — | — | Yes | Yes | +| Sampling and elicitation | Yes | Yes | No | Yes | +| OAuth | — | Native provider | No | Official SDK provider | +| Roots and subscriptions | Yes | Yes | No | No | +| Logging/progress callbacks | Yes | Yes | No | No | +| Tasks | Yes | Yes | No | No | +| Legacy SSE | No | Yes | No | No | -Best for HTTP-based MCP servers that support streaming responses: +Feature checks are transport-aware. For example, `client.on_sampling` is valid for SDK HTTP but raises `UnsupportedFeature` for SDK stdio. -```ruby -client = RubyLLM::MCP.client( - name: "streaming-server", - transport_type: :streamable, - config: { - url: "https://api.example.com/mcp", - version: :http2, # You can force HTTP/1.1 by setting this to :http1, default will try to setup HTTP/2 connection - headers: { "Content-Type" => "application/json" } - } -) -``` +## Transport Matrix -#### OAuth Authentication +| Configuration | Implementation | +|:--|:--| +| `adapter: :ruby_llm, transport_type: :stdio` | RubyLLM::MCP native stdio | +| `adapter: :ruby_llm, transport_type: :sse` | RubyLLM::MCP legacy SSE | +| `adapter: :ruby_llm, transport_type: :streamable` | RubyLLM::MCP Streamable HTTP | +| `adapter: :mcp_sdk, transport_type: :stdio` | `MCP::Client::Stdio` | +| `adapter: :mcp_sdk, transport_type: :http` | `MCP::Client::HTTP` | +| `adapter: :mcp_sdk, transport_type: :streamable` | `MCP::Client::HTTP` | +| `adapter: :mcp_sdk, transport_type: :streamable_http` | `MCP::Client::HTTP` | -{: .new } -OAuth authentication was introduced in MCP Protocol 2025-06-18 for Streamable HTTP transport. +SDK legacy SSE is intentionally rejected with migration guidance. Either use the native adapter for that endpoint or migrate the server to Streamable HTTP. -For servers requiring OAuth authentication: +## Installation + +The native adapter has no dependency on the official SDK. For `:mcp_sdk` stdio: ```ruby -client = RubyLLM::MCP.client( - name: "oauth-server", - transport_type: :streamable, - config: { - url: "https://api.example.com/mcp", - oauth: { - issuer: "https://oauth.provider.com", - client_id: "your-client-id", - client_secret: "your-client-secret", - scope: "mcp:read mcp:write" # Optional - } - } -) +gem "mcp", "~> 0.25" ``` -**OAuth Configuration:** +For SDK HTTP also add: -| Option | Description | Required | -|--------|-------------|----------| -| `issuer` | OAuth provider's issuer URL | Yes | -| `client_id` | OAuth client identifier | Yes | -| `client_secret` | OAuth client secret | Yes | -| `scope` | Requested OAuth scopes | No | - -The client automatically handles token acquisition, refresh, and authorization headers. - -**Use cases:** - -- REST API-based MCP servers -- HTTP-first architectures -- Cloud-based MCP services -- Enterprise servers requiring OAuth - ---- - -## Configuration +```ruby +gem "faraday", ">= 2" +gem "event_stream_parser", ">= 1" +``` -### Global Default Adapter +## Common Configuration -Set the default adapter for all clients in your configuration: +Select a default adapter: ```ruby RubyLLM::MCP.configure do |config| - config.default_adapter = :ruby_llm # or :mcp_sdk + config.default_adapter = :ruby_llm end ``` -### Per-Client Adapter - -Override the adapter for individual clients: +Override it per client: ```ruby -# Using RubyLLM adapter -client = RubyLLM::MCP.client( - name: "filesystem", +native = RubyLLM::MCP.client( + name: "native", adapter: :ruby_llm, transport_type: :stdio, - config: { - command: "npx", - args: ["@modelcontextprotocol/server-filesystem", "/path"] - } + config: { command: "native-server" } ) -# Using MCP SDK adapter -client = RubyLLM::MCP.client( - name: "weather", - adapter: :mcp_sdk, - transport_type: :http, - config: { - url: "https://api.example.com/mcp" - } -) -``` - -### YAML Configuration - -In `config/mcps.yml`: - -```yaml -mcp_servers: - filesystem: - adapter: ruby_llm - transport_type: stdio - command: npx - args: - - "@modelcontextprotocol/server-filesystem" - - "/path/to/directory" - - api_server: - adapter: mcp_sdk - transport_type: http - url: "https://api.example.com/mcp" - headers: - Authorization: "Bearer <%= ENV['API_KEY'] %>" -``` - -## Using the MCP SDK Adapter - -### Installation - -{: .warning } -> **Ruby 3.1+ Required** -> The official `mcp` gem supports Ruby 2.7+, and RubyLLM MCP supports Ruby 3.1.3+. - -The official MCP SDK is an optional dependency. Add it to your Gemfile when using the `:mcp_sdk` adapter: - -```ruby -gem 'ruby_llm-mcp', '~> 1.0' -gem 'mcp', '~> 0.7' # Required for mcp_sdk adapter -``` - -Then run: - -```bash -bundle install -``` - -### Basic Usage - -```ruby -# Configure to use MCP SDK -client = RubyLLM::MCP.client( - name: "my_server", +official = RubyLLM::MCP.client( + name: "official", adapter: :mcp_sdk, transport_type: :stdio, - config: { - command: "python", - args: ["-m", "my_mcp_server"] - } + config: { command: "official-server" } ) - -# Core features work the same -tools = client.tools -resources = client.resources -prompts = client.prompts - -# Call tools normally -tool = client.tool("calculator") -result = tool.execute(operation: "add", a: 5, b: 3) ``` -### SSE Transport +Both clients expose the same normalized tools, resources, templates, and prompts. -The `:mcp_sdk` adapter supports SSE (Server-Sent Events) transport for HTTP-based servers: +## SDK-Specific Options ```ruby -# Configure MCP SDK with SSE transport client = RubyLLM::MCP.client( - name: "remote_server", + name: "official", adapter: :mcp_sdk, - transport_type: :sse, + transport_type: :streamable_http, + request_timeout: 8_000, config: { - url: "https://api.example.com/mcp/sse", - headers: { - "Authorization" => "Bearer #{ENV['API_KEY']}" - } + url: "https://example.com/mcp", + headers: { "Authorization" => "Bearer static-token" }, + max_message_bytes: 4 * 1024 * 1024, + oauth: official_oauth_provider, + faraday: ->(connection) { connection.headers["User-Agent"] = "my-app/1.0" } } ) - -# Use the client normally -tools = client.tools -tool = client.tool("process_data") -result = tool.execute(data: "example") ``` -In YAML configuration: - -```yaml -mcp_servers: - remote_sse_server: - adapter: mcp_sdk - transport_type: sse - url: "https://api.example.com/mcp/sse" - headers: - Authorization: "Bearer <%= ENV['API_KEY'] %>" -``` - -### Feature Limitations - -When using `:mcp_sdk`, attempting to use unsupported features will raise helpful errors: - -```ruby -client = RubyLLM::MCP.client( - name: "server", - adapter: :mcp_sdk, - transport_type: :stdio, - config: { command: "server" } -) - -# This will raise UnsupportedFeature error -client.on_progress do |progress| - # Progress tracking not available in mcp_sdk -end -# => RubyLLM::MCP::Errors::UnsupportedFeature: -# Feature 'progress_tracking' is not supported by the mcp_sdk adapter. -# This feature requires the :ruby_llm adapter. -``` +For stdio, use `max_line_bytes`. The shared `request_timeout` remains milliseconds and is converted before being passed to the SDK. -## Mixed Adapter Usage +The old custom SDK-wrapper options `version`, `reconnection`, `session_id`, and `rate_limit` do not configure the official transports. The SDK manages sessions and reconnection; use Faraday customization for HTTP middleware behavior. -You can use different adapters for different servers in the same application: +## Advanced SDK Access ```ruby -RubyLLM::MCP.configure do |config| - config.default_adapter = :ruby_llm - - config.mcp_configuration = [ - # Use RubyLLM adapter for local filesystem (needs roots) - { - name: "filesystem", - adapter: :ruby_llm, - transport_type: :stdio, - config: { - command: "npx", - args: ["@modelcontextprotocol/server-filesystem", Rails.root] - } - }, - # Use MCP SDK for external API (simple HTTP) - { - name: "weather", - adapter: :mcp_sdk, - transport_type: :http, - config: { - url: "https://weather-api.example.com/mcp" - } - } - ] -end - -# Both clients work together -RubyLLM::MCP.establish_connection do |clients| - fs_client = clients["filesystem"] # Using ruby_llm adapter - weather_client = clients["weather"] # Using mcp_sdk adapter - - # Both provide tools to RubyLLM - all_tools = RubyLLM::MCP.tools -end +sdk = client.sdk_client +page = sdk.list_tools ``` ---- - -## Custom Transports +`sdk_client` is available only with `adapter: :mcp_sdk`. Raw SDK calls bypass RubyLLM::MCP normalization and use upstream result/error types. -{: .label .label-blue } -RubyLLM Adapter Only +## Custom Native Transports -The `:ruby_llm` adapter supports registering custom transport implementations, allowing you to extend the gem with your own communication protocols. - -### Transport Interface - -All transport implementations must implement the following interface: +Custom transports remain a native concern: ```ruby -class CustomTransport - # Initialize the transport - def initialize(coordinator:, **config) - @coordinator = coordinator - @config = config - end - - # Send a request and optionally wait for response - def request(body, add_id: true, wait_for_response: true) - # Implementation specific - end - - # Check if transport is alive/connected - def alive? - # Implementation specific - end - - # Start the transport connection - def start - # Implementation specific - end - - # Close the transport connection - def close - # Implementation specific - end - - # Set the MCP protocol version - def set_protocol_version(version) - @protocol_version = version - end -end +RubyLLM::MCP::Native::Transport.register_transport(:websocket, WebSocketTransport) ``` -### Registering Custom Transports +Registering a native transport never makes it available to `:mcp_sdk`. The official adapter deliberately accepts only transports implemented by the upstream SDK. -Once you've created a custom transport, register it with the transport factory: +## Unsupported Features -```ruby -# Register your custom transport -RubyLLM::MCP::Native::Transport.register_transport(:websocket, WebSocketTransport) -RubyLLM::MCP::Native::Transport.register_transport(:redis_pubsub, RedisPubSubTransport) +Calling a feature outside the chosen adapter/transport contract raises a focused error: -# Now you can use it with any client using the ruby_llm adapter +```ruby client = RubyLLM::MCP.client( - name: "websocket-server", - adapter: :ruby_llm, # Custom transports only work with ruby_llm adapter - transport_type: :websocket, - config: { - url: "ws://localhost:8080/mcp", - headers: { "Authorization" => "Bearer token" } - } + name: "sdk-stdio", + adapter: :mcp_sdk, + transport_type: :stdio, + config: { command: "server" } ) -``` - ---- - -## Best Practices - -### Choosing an Adapter - -1. **Start with `:ruby_llm`** if you're unsure - it supports all features -2. **Use `:mcp_sdk`** when you specifically need the official implementation -3. **Check feature requirements** before choosing an adapter -4. **Consider transport and feature needs** - advanced client features still require `:ruby_llm` -5. **Check Ruby version** - `:mcp_sdk` requires Ruby 3.1+ -### Upgrading from 1.0 - -If you're upgrading from version 1.0: - -1. The default adapter is `:ruby_llm` - no changes needed for existing code -2. All existing features continue to work as before -3. Optionally migrate specific clients to `:mcp_sdk` if desired - - -## Troubleshooting - -### "Feature not supported" errors - -If you see errors about unsupported features: - -1. Check which adapter you're using -2. Verify the feature is supported (see feature comparison table) -3. Switch to `:ruby_llm` adapter if you need the feature - -### "Transport not supported" errors - -If you see transport errors: - -1. Verify the transport is compatible with your adapter -2. Prefer `:stdio` or `:streamable` for maximum compatibility -3. Use `:http` for simple JSON request/response servers - -### Missing MCP gem - -If you see "LoadError: cannot load such file -- mcp": - -1. Add `gem 'mcp', '~> 0.7'` to your Gemfile -2. Run `bundle install` -3. Ensure you're running Ruby 3.1 or higher -4. This is only needed when using `adapter: :mcp_sdk` - -### Ruby Version Compatibility - -If you encounter issues with the `:mcp_sdk` adapter: - -1. Check your Ruby version: `ruby -v` -2. The `mcp` gem requires Ruby 2.7 or higher (RubyLLM MCP requires 3.1.3+) -3. Switch to `:ruby_llm` adapter if you're on an older Ruby version -4. Consider upgrading Ruby if you need the official SDK - -## Next Steps +client.on_progress { |progress| puts progress } +# RubyLLM::MCP::Errors::UnsupportedFeature +``` -- **[Configuration]({% link configuration.md %})** - Detailed configuration options -- **[Getting Started]({% link guides/getting-started.md %})** - Quick start guide -- **[Tools]({% link server/tools.md %})** - Working with MCP tools -- **[Resources]({% link server/resources.md %})** - Managing resources -- **[Notifications]({% link server/notifications.md %})** - Handling real-time updates -- **[Upgrading from 0.8 to 1.0]({% link guides/upgrading-0.8-to-1.0.md %})** - Migration guide +Switch to `:ruby_llm` when the missing feature is notification-, root-, subscription-, task-, or legacy-transport-oriented. diff --git a/docs/guides/index.md b/docs/guides/index.md index 79dd345f..dc912215 100644 --- a/docs/guides/index.md +++ b/docs/guides/index.md @@ -21,4 +21,5 @@ This section contains advanced implementation guidance. ## Upgrading +- **[Official MCP SDK 0.25]({% link guides/mcp-sdk-0.25.md %})** - SDK transports, OAuth, sampling, elicitation, advanced access, and migration from SDK 0.7 - **[Upgrading]({% link guides/upgrading.md %})** - Unified migration guide with sections for updates to 1.0, 0.8, and 0.7 diff --git a/docs/guides/mcp-apps.md b/docs/guides/mcp-apps.md index d7488d45..8f343f55 100644 --- a/docs/guides/mcp-apps.md +++ b/docs/guides/mcp-apps.md @@ -57,8 +57,7 @@ client = RubyLLM::MCP.client( ) ``` -Use `:ruby_llm` when you want full extension capability advertisement. -`:mcp_sdk` accepts the same config but remains passive for extension advertisement. +Both `:ruby_llm` and `:mcp_sdk` advertise this extension when using a supported protocol. The native adapter performs its own handshake; the SDK adapter passes it through `MCP::Client#connect`. ## Step 3: Inspect MCP Apps Metadata @@ -118,7 +117,7 @@ RubyLLM MCP canonicalizes IDs and deep-merges client extension settings over glo - Putting `resourceUri` or `visibility` in `enable_apps` (those belong in tool `_meta.ui`) - Expecting extension advertisement on protocol versions before `2025-06-18` -- Assuming `:mcp_sdk` advertises extension capabilities (it does not) +- Using a protocol older than `2025-06-18`, where extensions are not negotiated ## Next Steps diff --git a/docs/guides/mcp-sdk-0.25.md b/docs/guides/mcp-sdk-0.25.md new file mode 100644 index 00000000..c7fd5d10 --- /dev/null +++ b/docs/guides/mcp-sdk-0.25.md @@ -0,0 +1,307 @@ +--- +layout: default +title: Official MCP SDK 0.25 +parent: Guides +nav_order: 3 +description: "Use the official MCP Ruby SDK 0.25 adapter, transports, OAuth providers, sampling, elicitation, and advanced APIs." +--- + +# Official MCP SDK 0.25 + +The `:mcp_sdk` adapter delegates protocol lifecycle and transport behavior to the official Model Context Protocol Ruby SDK. It is independent from RubyLLM::MCP's native implementation: choosing this adapter uses `MCP::Client`, `MCP::Client::Stdio`, or `MCP::Client::HTTP` end to end. + +Use `:ruby_llm` when you need legacy SSE, roots, subscriptions, progress/logging callbacks, tasks, or the full native notification pipeline. Installing `mcp` does not change native clients. + +## Installation + +Stdio requires the official SDK: + +```ruby +gem "ruby_llm-mcp" +gem "mcp", "~> 0.25" +``` + +Streamable HTTP also requires the SDK's optional HTTP dependencies: + +```ruby +gem "faraday", ">= 2" +gem "event_stream_parser", ">= 1" +``` + +## Transports + +### Stdio + +```ruby +client = RubyLLM::MCP.client( + name: "local-sdk-server", + adapter: :mcp_sdk, + transport_type: :stdio, + request_timeout: 8_000, + config: { + command: "npx", + args: ["@modelcontextprotocol/server-filesystem", Dir.pwd], + env: { "NODE_ENV" => "production" }, + max_line_bytes: 4 * 1024 * 1024 + } +) +``` + +`request_timeout` remains milliseconds in RubyLLM::MCP and is converted to the SDK's seconds-based read timeout. + +### Streamable HTTP + +`:http`, `:streamable`, and `:streamable_http` all select `MCP::Client::HTTP`: + +```ruby +client = RubyLLM::MCP.client( + name: "remote-sdk-server", + adapter: :mcp_sdk, + transport_type: :streamable_http, + request_timeout: 10_000, + config: { + url: "https://mcp.example.com/mcp", + headers: { "X-Tenant" => ENV.fetch("TENANT_ID") }, + max_message_bytes: 4 * 1024 * 1024 + } +) +``` + +Legacy `transport_type: :sse` is native-only. Use `adapter: :ruby_llm` for an older SSE endpoint. + +You can customize the SDK's Faraday connection without replacing its transport: + +```ruby +config: { + url: "https://mcp.example.com/mcp", + faraday: lambda do |connection| + connection.headers["User-Agent"] = "my-app/1.0" + end +} +``` + +## Features by Transport + +| Feature | SDK stdio | SDK HTTP | Native adapter | +|:--|:--:|:--:|:--:| +| Tools, resources, prompts, templates | Yes | Yes | Yes | +| Completions and automatic pagination | Yes | Yes | Yes | +| Structured tool output and `_meta` | Yes | Yes | Yes | +| Cache hints (`ttlMs`, `cacheScope`) | Yes | Yes | Manual refresh | +| Extension/MCP Apps negotiation | Yes | Yes | Yes | +| Official OAuth providers | No | Yes | No; uses native OAuth | +| Sampling and elicitation | No | Yes | Yes | +| Roots, subscriptions, tasks | No | No | Yes | +| Progress and logging callbacks | No | No | Yes | +| Legacy SSE | No | No | Yes | + +The SDK's general transports do not expose notification hooks for RubyLLM::MCP logging or progress callbacks. Use `:ruby_llm` when those callbacks are part of your application contract. + +## Lifecycle and Capabilities + +Starting an SDK client performs the official initialization handshake. These methods now reflect the connected SDK session: + +```ruby +client.alive? # MCP::Client#connected? +client.ping # real MCP ping +client.capabilities # negotiated server capabilities +client.client_capabilities +client.restart! # closes and performs a fresh handshake +``` + +An expired HTTP session raises `RubyLLM::MCP::Errors::SessionExpiredError`. Call `restart!` before retrying. RubyLLM::MCP never automatically retries a tool call because it may have already caused a side effect. + +## Sampling over HTTP + +Configure sampling and its model selection before starting the client: + +```ruby +RubyLLM::MCP.configure do |config| + config.sampling.enabled = true + config.sampling.tools = true + config.sampling.context = true + config.sampling.preferred_model { |_preferences| "gpt-4.1-mini" } +end + +client = RubyLLM::MCP::Client.new( + name: "sampling-server", + adapter: :mcp_sdk, + transport_type: :streamable_http, + start: false, + config: { url: "https://mcp.example.com/mcp" } +) + +client.on_sampling do |sample| + # Return false to reject, or use the existing Sample handler contract. + puts sample.message + true +end + +client.start +``` + +Only SDK HTTP advertises sampling. SDK stdio does not expose server-request handlers in version 0.25. + +## Elicitation over HTTP + +```ruby +RubyLLM::MCP.configure do |config| + config.elicitation.form = true + config.elicitation.url = false +end + +client = RubyLLM::MCP::Client.new( + name: "elicitation-server", + adapter: :mcp_sdk, + transport_type: :streamable_http, + start: false, + config: { url: "https://mcp.example.com/mcp" } +) + +client.on_elicitation do |elicitation| + { + action: :accept, + response: { "confirmed" => true } + } +end + +client.start +``` + +Existing synchronous handler classes, promises, and async responses are bridged to the SDK's server-request response. An async response that exceeds `request_timeout` is cancelled. + +## Official OAuth Providers + +SDK HTTP accepts an official provider directly: + +```ruby +provider = MCP::Client::OAuth::Provider.new( + client_metadata: { + client_name: "My Ruby App", + redirect_uris: ["http://127.0.0.1:9292/callback"], + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + token_endpoint_auth_method: "none" + }, + redirect_uri: "http://127.0.0.1:9292/callback", + redirect_handler: ->(url) { Launchy.open(url.to_s) }, + callback_handler: -> { wait_for_oauth_callback }, + scope: "mcp:read mcp:write" +) + +client = RubyLLM::MCP.client( + name: "oauth-sdk-server", + adapter: :mcp_sdk, + transport_type: :streamable_http, + config: { + url: "https://mcp.example.com/mcp", + oauth: provider + } +) +``` + +`oauth: { provider: provider }` is equivalent. + +### Client credentials + +```ruby +provider = MCP::Client::OAuth::ClientCredentialsProvider.new( + client_id: ENV.fetch("MCP_CLIENT_ID"), + client_secret: ENV.fetch("MCP_CLIENT_SECRET"), + token_endpoint_auth_method: "client_secret_basic", + scope: "mcp:read" +) +``` + +Use `client_secret_post` when required by the authorization server. For `private_key_jwt`: + +```ruby +provider = MCP::Client::OAuth::ClientCredentialsProvider.new( + client_id: ENV.fetch("MCP_CLIENT_ID"), + token_endpoint_auth_method: "private_key_jwt", + private_key: ENV.fetch("MCP_PRIVATE_KEY_PEM"), + signing_algorithm: "RS256", + scope: "mcp:read" +) +``` + +### Cross-App Access / ID-JAG + +```ruby +provider = MCP::Client::OAuth::CrossAppAccessProvider.new( + client_id: ENV.fetch("MCP_CLIENT_ID"), + client_secret: ENV.fetch("MCP_CLIENT_SECRET"), + assertion_provider: lambda do |audience:, resource:| + exchange_id_token_for_id_jag(audience: audience, resource: resource) + end, + scope: "mcp:read" +) +``` + +Native `RubyLLM::MCP::Auth::OAuthProvider` objects are not interchangeable with official SDK providers. Native clients continue to use the OAuth configuration documented in the [OAuth guide]({% link guides/oauth.md %}). + +## Extensions and MCP Apps + +Configured extensions are passed through the official initialization handshake: + +```ruby +client = RubyLLM::MCP.client( + name: "apps-sdk-server", + adapter: :mcp_sdk, + transport_type: :streamable_http, + config: { + url: "https://mcp.example.com/mcp", + extensions: { + "io.modelcontextprotocol/ui" => { + "mimeTypes" => ["text/html;profile=mcp-app"] + } + } + } +) +``` + +Tool/resource `_meta`, titles, icons, annotations, sizes, and output schemas remain available through the normalized RubyLLM::MCP objects. + +## Pagination and Cache Hints + +Collection methods automatically follow `nextCursor`. RubyLLM::MCP honors SDK cache hints: + +```ruby +client.tools +client.cache_hints[:tools] +# => { ttl_ms: 30000, cache_scope: "private" } +``` + +`ttlMs: 0` disables the collection cache. A positive TTL refreshes after expiry. Missing TTL preserves the existing manual-refresh behavior. Resource reads expose their policy through `resource.cache_hint`. + +## Direct SDK Access + +Use `sdk_client` for upstream APIs that do not belong in the shared abstraction: + +```ruby +sdk = client.sdk_client + +cancellation = MCP::Cancellation.new +result = sdk.call_tool( + name: "long_operation", + arguments: { "input" => "value" }, + cancellation: cancellation, + meta: { "traceparent" => "00-..." } +) +``` + +Direct calls return upstream SDK objects and exceptions; they bypass RubyLLM::MCP normalization and cache management. + +## Migrating from SDK 0.7 + +1. Change the dependency to `gem "mcp", "~> 0.25"`. +2. Add Faraday and `event_stream_parser` when using HTTP. +3. Change SDK `transport_type: :sse` clients to either: + - `adapter: :ruby_llm` for legacy SSE, or + - `transport_type: :streamable_http` for modern MCP HTTP. +4. Replace native-style OAuth hashes/providers on SDK clients with an official `MCP::Client::OAuth` provider. +5. Remove SDK-only `version`, `reconnection`, `session_id`, and `rate_limit` settings. The official SDK owns sessions/reconnection; customize HTTP through Faraday when needed. +6. Move logging/progress callback clients to `adapter: :ruby_llm`. +7. Expect `start` to perform a real handshake and `ping` to contact the server. + +The stable integration targets MCP `2025-11-25`. The draft `2026-07-28` multi-round-trip input/resume flow is not implemented by SDK 0.25; an `input_required` result raises an unsupported-feature error instead of being treated as a final tool result. diff --git a/docs/guides/oauth.md b/docs/guides/oauth.md index a541a69d..b48b65b0 100644 --- a/docs/guides/oauth.md +++ b/docs/guides/oauth.md @@ -14,6 +14,8 @@ description: "Complete OAuth 2.1 implementation with PKCE, dynamic registration, Comprehensive OAuth 2.1 support for MCP servers with automatic token management, browser-based authentication, and pluggable storage. +This page documents RubyLLM::MCP's native OAuth provider used by `adapter: :ruby_llm`. The `:mcp_sdk` HTTP adapter instead accepts official `MCP::Client::OAuth` providers, including authorization code, client credentials, `private_key_jwt`, and Cross-App Access/ID-JAG. See [Official MCP SDK 0.25]({% link guides/mcp-sdk-0.25.md %}#official-oauth-providers). + ## Table of contents {: .no_toc .text-delta } @@ -41,8 +43,9 @@ Comprehensive OAuth 2.1 support for MCP servers with automatic token management, | Transport | OAuth Support | Details | |-----------|---------------|---------| -| **SSE** | ✅ Full support | Event streams and message endpoints | -| **StreamableHTTP** | ✅ Full support | All HTTP requests with session management | +| **Native SSE** | ✅ Full support | RubyLLM::MCP native provider | +| **Native StreamableHTTP** | ✅ Full support | RubyLLM::MCP native provider | +| **SDK Streamable HTTP** | ✅ Full support | Official `MCP::Client::OAuth` providers | | **Stdio** | N/A | Local process communication (no auth needed) | ## Architecture diff --git a/docs/guides/upgrading-0.8-to-1.0.md b/docs/guides/upgrading-0.8-to-1.0.md index 99b29281..f8f9c3e0 100644 --- a/docs/guides/upgrading-0.8-to-1.0.md +++ b/docs/guides/upgrading-0.8-to-1.0.md @@ -38,7 +38,7 @@ gem 'ruby_llm-mcp', '~> 1.0' Optional - for MCP SDK adapter (requires Ruby 3.1+): ```ruby -gem 'mcp', '~> 0.7' +gem 'mcp', '~> 0.25' ``` Then run: diff --git a/docs/guides/upgrading.md b/docs/guides/upgrading.md index f06b5cf8..c1c7998a 100644 --- a/docs/guides/upgrading.md +++ b/docs/guides/upgrading.md @@ -11,6 +11,20 @@ description: "Unified upgrade guide with version-specific migration sections" This page consolidates upgrade guidance across supported RubyLLM MCP version jumps. +## Upgrade the optional MCP SDK adapter to 0.25 + +The native `:ruby_llm` adapter does not change. If you use `adapter: :mcp_sdk`, update the optional dependency and migrate that adapter to the official 0.25 transports: + +```ruby +gem "mcp", "~> 0.25" +gem "faraday", ">= 2" # SDK HTTP only +gem "event_stream_parser", ">= 1" # SDK HTTP only +``` + +SDK stdio now uses `MCP::Client::Stdio`; SDK `:http`, `:streamable`, and `:streamable_http` use `MCP::Client::HTTP`. SDK legacy SSE is no longer accepted—keep it on `adapter: :ruby_llm` or migrate the endpoint to Streamable HTTP. + +SDK OAuth clients must pass an official `MCP::Client::OAuth` provider. Logging/progress callbacks and native transport options remain native-only. See [Official MCP SDK 0.25]({% link guides/mcp-sdk-0.25.md %}) for the complete migration and feature guide. + ## Table of contents {: .no_toc .text-delta } @@ -37,7 +51,7 @@ gem 'ruby_llm-mcp', '~> 1.0' Optional for MCP SDK adapter (Ruby 3.1+): ```ruby -gem 'mcp', '~> 0.7' +gem 'mcp', '~> 0.25' ``` 2. Run: diff --git a/docs/index.md b/docs/index.md index 54b70d6b..fb9e53da 100644 --- a/docs/index.md +++ b/docs/index.md @@ -19,7 +19,7 @@ permalink: / RubyLLM::MCP gives you a direct way to use [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) servers from [RubyLLM](https://github.com/crmne/ruby_llm). {: .fs-6 .fw-300 } -**Protocol support:** Fully supports MCP spec `2025-06-18` (stable), with draft spec `2026-01-26` available. +**Protocol support:** Fully supports MCP spec `2025-11-25` (stable), with draft spec `2026-01-26` available. Get started GitHub @@ -38,7 +38,7 @@ MCP integration in Ruby apps should be easy to reason about. RubyLLM::MCP focuses on: - Ruby-first APIs for using MCP tools, resources, and prompts in RubyLLM chat workflows -- Stable protocol defaults (`2025-06-18`) with explicit draft opt-in (`2026-01-26`) +- Stable protocol defaults (`2025-11-25`) with explicit draft opt-in (`2026-01-26`) - Built-in notification and response handlers for real-time and interactive workflows - MCP OAuth 2.1 authentication support (PKCE, dynamic registration, discovery, and automatic token refresh) - OAuth setup paths for Rails apps (per-user connections) and browser-based CLI flows @@ -168,7 +168,7 @@ gem "ruby_llm-mcp" Optional official SDK adapter: ```ruby -gem "mcp", "~> 0.7" +gem "mcp", "~> 0.25" ``` ## Rails diff --git a/lib/generators/ruby_llm/mcp/install/templates/initializer.rb b/lib/generators/ruby_llm/mcp/install/templates/initializer.rb index 41530c78..351c25c0 100644 --- a/lib/generators/ruby_llm/mcp/install/templates/initializer.rb +++ b/lib/generators/ruby_llm/mcp/install/templates/initializer.rb @@ -4,7 +4,7 @@ RubyLLM::MCP.configure do |config| # Default SDK adapter to use (:ruby_llm or :mcp_sdk) # - :ruby_llm: Full-featured, supports all MCP features + extensions - # - :mcp_sdk: Official SDK, limited features but maintained by Anthropic + # - :mcp_sdk: Official Model Context Protocol SDK and transports config.default_adapter = :ruby_llm # Request timeout in milliseconds diff --git a/lib/ruby_llm/mcp/adapters/base_adapter.rb b/lib/ruby_llm/mcp/adapters/base_adapter.rb index dd53b7e4..3409da2f 100644 --- a/lib/ruby_llm/mcp/adapters/base_adapter.rb +++ b/lib/ruby_llm/mcp/adapters/base_adapter.rb @@ -13,8 +13,21 @@ def supports(*features) features.each { |f| supported_features[f] = true } end - def support?(feature) - supported_features[feature] || false + def transport_features + @transport_features ||= Hash.new { |hash, key| hash[key] = {} } + end + + def supports_on(*transports, features:) + transports.each do |transport| + Array(features).each { |feature| transport_features[transport.to_sym][feature] = true } + end + end + + def support?(feature, transport: nil) + return true if supported_features[feature] + return false if transport.nil? + + transport_features[transport.to_sym][feature] || false end def supported_transports @@ -39,7 +52,11 @@ def initialize(client, transport_type:, config: {}) end def supports?(feature) - self.class.support?(feature) + self.class.support?(feature, transport: @transport_type) + end + + def cache_hints + {} end def supports_extension_negotiation? diff --git a/lib/ruby_llm/mcp/adapters/mcp_sdk_adapter.rb b/lib/ruby_llm/mcp/adapters/mcp_sdk_adapter.rb index 7ccbb71a..84a6ca34 100644 --- a/lib/ruby_llm/mcp/adapters/mcp_sdk_adapter.rb +++ b/lib/ruby_llm/mcp/adapters/mcp_sdk_adapter.rb @@ -1,22 +1,23 @@ # frozen_string_literal: true -require_relative "mcp_transports/coordinator_stub" -require_relative "mcp_transports/stdio" -require_relative "mcp_transports/sse" -require_relative "mcp_transports/streamable_http" - module RubyLLM module MCP module Adapters + # Adapter backed exclusively by the official mcp gem. Native transports and + # protocol behavior remain owned by RubyLLMAdapter. class MCPSdkAdapter < BaseAdapter - # Only declare features the official MCP SDK supports - supports :tools, :resources, :prompts, :resource_templates, :logging - - # Supported transports: - # - stdio: Via custom wrapper using native stdio transport ✓ FULLY TESTED - # - sse: Via custom wrapper using native SSE transport ✓ FUNCTIONAL - # - http: Via MCP::Client::HTTP (for simple JSON-only HTTP servers) - supports_transport :stdio, :http, :sse, :streamable, :streamable_http + SDK_REQUIREMENT = Gem::Requirement.new("~> 0.25") + HTTP_TRANSPORTS = %i[http streamable streamable_http].freeze + COLLECTION_METHODS = { + tools: ["tools/list", "tools"], + resources: ["resources/list", "resources"], + resource_templates: ["resources/templates/list", "resourceTemplates"], + prompts: ["prompts/list", "prompts"] + }.freeze + + supports :tools, :resources, :prompts, :resource_templates, :completions + supports_on(*HTTP_TRANSPORTS, features: %i[oauth sampling elicitation]) + supports_transport :stdio, *HTTP_TRANSPORTS attr_reader :transport_type, :config, :mcp_client @@ -26,25 +27,41 @@ def initialize(client, transport_type:, config: {}) super @mcp_client = nil - @notification_handler = NotificationHandler.new(client) - warn_passive_extension_support! if configured_extensions? + @server_info = nil + @cache_hints = {} + @elicitation_enabled = MCP.config.elicitation.enabled? end def start - return if @mcp_client + return if alive? - transport = build_transport - transport.start if transport.respond_to?(:start) + @mcp_client = ::MCP::Client.new(transport: build_transport) + register_server_request_handlers + connect_result = with_sdk_errors do + @mcp_client.connect( + client_info: { name: client.name, version: RubyLLM::MCP::VERSION }, + protocol_version: protocol_version, + capabilities: client_capabilities + ) + end + @server_info = connect_result || @mcp_client.server_info + unless @server_info.is_a?(Hash) + raise Errors::TransportError.new(message: "Official MCP SDK connected without server information") + end - @mcp_client = ::MCP::Client.new(transport: transport) - set_logging(level: client.on_logging_level) if client.logging_handler_enabled? + @capabilities = ServerCapabilities.new(@server_info.fetch("capabilities", {})) + rescue StandardError + stop + raise end def stop - if @mcp_client && @mcp_client.transport.respond_to?(:close) - @mcp_client.transport.close - end + @mcp_client&.transport&.close + ensure @mcp_client = nil + @server_info = nil + @capabilities = nil + @cache_hints = {} end def restart! @@ -53,357 +70,475 @@ def restart! end def alive? - !@mcp_client.nil? + !!@mcp_client&.connected? + rescue StandardError + false end - def ping # rubocop:disable Naming/PredicateMethod + def ping ensure_started - alive? + with_sdk_errors { @mcp_client.ping == {} } + rescue Errors::TransportError, Errors::SessionExpiredError + false end def capabilities - # Return minimal capabilities for official SDK - @capabilities ||= ServerCapabilities.new( - "tools" => {}, - "resources" => {}, - "prompts" => {}, - "logging" => {} - ) + info = @server_info || @mcp_client&.server_info || {} + @capabilities ||= ServerCapabilities.new(info["capabilities"] || {}) end def client_capabilities - {} # Official SDK handles this internally + capabilities = {} + capabilities[:sampling] = sampling_capabilities if sampling_enabled? + capabilities[:elicitation] = elicitation_capabilities if elicitation_enabled? + + extensions = build_client_extensions_capabilities(protocol_version: protocol_version) + capabilities[:extensions] = extensions unless extensions.empty? + capabilities end def supports_extension_negotiation? - false + true end def extension_mode - :passive + :full end - def build_client_extensions_capabilities(protocol_version:) # rubocop:disable Lint/UnusedMethodArgument - {} + def build_client_extensions_capabilities(protocol_version:) + return {} unless Native::Protocol.extensions_supported?(protocol_version) + + Extensions::Registry.normalize_map(@config[:extensions]).transform_values { |value| value || {} } end - def tool_list(cursor: nil) # rubocop:disable Lint/UnusedMethodArgument - ensure_started - @mcp_client.tools.map { |tool| transform_tool(tool) } + def cache_hints + @cache_hints.transform_values(&:dup).freeze + end + + # Existing handler-class factories refer to adapter.native_client as + # their response coordinator. During an SDK server request this is the + # bridge for that request, never a RubyLLM native protocol client. + def native_client + Thread.current[:ruby_llm_mcp_sdk_bridge] || self + end + + def tool_list(cursor: nil) + paginated_list(:tools, cursor: cursor) end def execute_tool(name:, parameters:) ensure_started - tool = find_tool(name) - result = @mcp_client.call_tool(tool: tool, arguments: parameters) - transform_tool_result(result) - rescue RubyLLM::MCP::Errors::TimeoutError => e - native_transport = @mcp_client&.transport&.native_transport - if native_transport&.alive? && !e.request_id.nil? - cancelled_notification(reason: "Request timed out", request_id: e.request_id) - end - raise e + response = with_sdk_errors { @mcp_client.call_tool(name: name, arguments: parameters) } + Result.new(response) end - def resource_list(cursor: nil) # rubocop:disable Lint/UnusedMethodArgument - ensure_started - @mcp_client.resources.map { |resource| transform_resource(resource) } + def resource_list(cursor: nil) + paginated_list(:resources, cursor: cursor) end def resource_read(uri:) ensure_started - result = @mcp_client.read_resource(uri: uri) - transform_resource_content(result) + response = sdk_request(method: "resources/read", params: { uri: uri }) + Result.new(response) end - def prompt_list(cursor: nil) # rubocop:disable Lint/UnusedMethodArgument - ensure_started - @mcp_client.prompts.map { |prompt| transform_prompt(prompt) } + def prompt_list(cursor: nil) + paginated_list(:prompts, cursor: cursor) end def execute_prompt(name:, arguments:) ensure_started - response = @mcp_client.transport.send_request( - request: { - jsonrpc: "2.0", - id: SecureRandom.uuid, - method: "prompts/get", - params: { - name: name, - arguments: arguments - } - } + response = sdk_request( + method: "prompts/get", + params: { name: name, arguments: arguments } ) - - transform_prompt_result(response) + Result.new(response) end - def resource_template_list(cursor: nil) # rubocop:disable Lint/UnusedMethodArgument - ensure_started - @mcp_client.resource_templates.map { |resource_template| transform_resource_template(resource_template) } + def resource_template_list(cursor: nil) + paginated_list(:resource_templates, cursor: cursor) end - def set_logging(level:) - ensure_started - @mcp_client.transport.send_request( - request: { - jsonrpc: "2.0", - id: SecureRandom.uuid, - method: "logging/setLevel", - params: { level: level } - } - ) + def completion_resource(uri:, argument:, value:, context: nil) + complete(ref: { type: "ref/resource", uri: uri }, argument: argument, value: value, context: context) end - def cancelled_notification(reason:, request_id:) - return unless @mcp_client&.transport.respond_to?(:native_transport) + def completion_prompt(name:, argument:, value:, context: nil) + complete(ref: { type: "ref/prompt", name: name }, argument: argument, value: value, context: context) + end - native_transport = @mcp_client.transport.native_transport - return unless native_transport + def set_elicitation_enabled(enabled:) + @elicitation_enabled = enabled + end - body = RubyLLM::MCP::Native::Messages::Notifications.cancelled( - request_id: request_id, - reason: reason - ) - native_transport.request(body, wait_for_response: false) - end - - # These methods remain as NotImplementedError from base class: - # - completion_resource - # - completion_prompt - # - resources_subscribe - # - initialize_notification - # - roots_list_change_notification - # - ping_response - # - roots_list_response - # - sampling_create_message_response - # - error_response - # - elicitation_response - # - register_resource + def register_resource(resource) + client.linked_resources << resource + end private def ensure_started - start unless @mcp_client + start unless alive? end def require_mcp_gem! require "mcp" - if Gem::Version.new(::MCP::VERSION) < Gem::Version.new("0.7.0") - raise Errors::AdapterConfigurationError.new(message: <<~MSG) - The official MCP SDK version 0.7 or higher is required to use the :mcp_sdk adapter. - MSG - end - rescue LoadError + return if SDK_REQUIREMENT.satisfied_by?(Gem::Version.new(::MCP::VERSION)) + + raise Errors::AdapterConfigurationError.new( + message: "The :mcp_sdk adapter requires mcp #{SDK_REQUIREMENT}; found #{::MCP::VERSION}." + ) + rescue LoadError => e + raise e unless e.path == "mcp" + raise LoadError, <<~MSG The official MCP SDK is required to use the :mcp_sdk adapter. Add to your Gemfile: - gem 'mcp', '~> 0.7' + gem "mcp", "~> 0.25" - Then run: bundle install + For HTTP also add: + gem "faraday", ">= 2" + gem "event_stream_parser", ">= 1" MSG end - def build_transport # rubocop:disable Metrics/MethodLength - protocol_version = @config[:protocol_version] || RubyLLM::MCP.config.protocol_version - notification_callback = lambda do |notification| - @notification_handler.execute(notification) - end - + def build_transport case @transport_type - when :http - # MCP::Client::HTTP is for simple JSON-only HTTP servers - # Use :streamable for servers that support the streamable HTTP/SSE protocol - ::MCP::Client::HTTP.new( - url: @config[:url], - headers: @config[:headers] || {} - ) when :stdio - MCPTransports::Stdio.new( - command: @config[:command], - args: @config[:args] || [], - env: @config[:env] || {}, - request_timeout: @config[:request_timeout] || 10_000, - protocol_version: protocol_version, - notification_callback: notification_callback + build_stdio_transport + when *HTTP_TRANSPORTS + build_http_transport + end + end + + def build_stdio_transport + options = { + command: config_value(:command), + args: config_value(:args) || [], + env: config_value(:env), + read_timeout: request_timeout_seconds + } + max_line_bytes = config_value(:max_line_bytes) + options[:max_line_bytes] = max_line_bytes if max_line_bytes + ::MCP::Client::Stdio.new(**options) + end + + def build_http_transport + options = { + url: config_value(:url), + headers: config_value(:headers) || {}, + oauth: sdk_oauth_provider + } + max_message_bytes = config_value(:max_message_bytes) + options[:max_message_bytes] = max_message_bytes if max_message_bytes + customizer = config_value(:faraday) + + ::MCP::Client::HTTP.new(**options) do |connection| + connection.options.timeout = request_timeout_seconds + connection.options.open_timeout = request_timeout_seconds + customizer&.call(connection) + end + rescue LoadError => e + raise LoadError, + "#{e.message}\nFor mcp_sdk HTTP add faraday >= 2 and event_stream_parser >= 1 to your Gemfile." + end + + def sdk_oauth_provider + oauth = config_value(:oauth) + provider = oauth.is_a?(Hash) ? (oauth[:provider] || oauth["provider"]) : oauth + return if provider.nil? + + if defined?(Auth::OAuthProvider) && provider.is_a?(Auth::OAuthProvider) + raise Errors::AdapterConfigurationError.new( + message: "RubyLLM::MCP native OAuth providers cannot be used with :mcp_sdk. " \ + "Pass an MCP::Client::OAuth provider via config: { oauth: provider }." ) - when :sse - MCPTransports::SSE.new( - url: @config[:url], - headers: @config[:headers] || {}, - version: @config[:version] || :http2, - request_timeout: @config[:request_timeout] || 10_000, - protocol_version: protocol_version, - notification_callback: notification_callback + end + + provider + end + + def register_server_request_handlers + return unless HTTP_TRANSPORTS.include?(@transport_type) + + @mcp_client.on_sampling { |params| handle_sampling_request(params) } if sampling_enabled? + @mcp_client.on_elicitation { |params| handle_elicitation_request(params) } if elicitation_enabled? + end + + def handle_sampling_request(params) + bridge = ServerRequestBridge.new(client, timeout: request_timeout_seconds) + result = Result.new({ "id" => SecureRandom.uuid, "method" => "sampling/createMessage", "params" => params }) + bridge.with_current { Sample.new(result, bridge).execute } + bridge.response!(wait: false) + end + + def handle_elicitation_request(params) + bridge = ServerRequestBridge.new(client, timeout: server_request_timeout_seconds) + result = Result.new({ "id" => SecureRandom.uuid, "method" => "elicitation/create", "params" => params }) + elicitation = Elicitation.new(bridge, result) + bridge.with_current { elicitation.execute } + bridge.response!(wait: true, timeout_response: { "action" => "cancel" }) do + elicitation.timeout! + Handlers::ElicitationRegistry.remove(elicitation.id) + end + end + + def sampling_enabled? + supports?(:sampling) && MCP.config.sampling.enabled? + end + + def elicitation_enabled? + supports?(:elicitation) && @elicitation_enabled + end + + def sampling_capabilities + value = {} + value[:tools] = {} if MCP.config.sampling.tools + value[:context] = {} if MCP.config.sampling.context + value + end + + def elicitation_capabilities + value = {} + value[:form] = {} if MCP.config.elicitation.form + value[:url] = {} if MCP.config.elicitation.url + value + end + + def complete(ref:, argument:, value:, context:) + ensure_started + completion = with_sdk_errors do + @mcp_client.complete( + ref: ref, + argument: { name: argument, value: value }, + context: context ) - when :streamable, :streamable_http - config_copy = @config.dup - oauth_provider = Auth::TransportOauthHelper.create_oauth_provider(config_copy) if Auth::TransportOauthHelper.oauth_config_present?(config_copy) - - MCPTransports::StreamableHTTP.new( - url: @config[:url], - headers: @config[:headers] || {}, - version: @config[:version] || :http2, - request_timeout: @config[:request_timeout] || 10_000, - reconnection: @config[:reconnection] || {}, - oauth_provider: oauth_provider, - rate_limit: @config[:rate_limit], - session_id: @config[:session_id], - protocol_version: protocol_version, - notification_callback: notification_callback + end + Result.new({ "result" => { "completion" => completion } }) + end + + def paginated_list(collection, cursor: nil) + ensure_started + method, result_key = COLLECTION_METHODS.fetch(collection) + items = [] + pages = [] + seen = {} + + loop do + response = sdk_request(method: method, params: cursor ? { cursor: cursor } : nil) + result = response.fetch("result", {}) + items.concat(result[result_key] || []) + pages << result + next_cursor = result["nextCursor"] + break if next_cursor.nil? || seen[next_cursor] + + seen[next_cursor] = true + cursor = next_cursor + end + + store_cache_hint(collection, pages) + items + end + + def store_cache_hint(collection, pages) + ttls = pages.filter_map { |page| page["ttlMs"] } + scopes = pages.filter_map { |page| page["cacheScope"] } + @cache_hints[collection] = { + ttl_ms: ttls.min, + cache_scope: scopes.include?("private") ? "private" : scopes.first + }.compact.freeze + end + + def sdk_request(method:, params: nil) + request = { + jsonrpc: "2.0", + id: SecureRandom.uuid, + method: method + } + request[:params] = params if params + + response = with_sdk_errors { @mcp_client.transport.send_request(request: request) } + if response.is_a?(Hash) && response["error"] + error = response["error"] + raise Errors::ResponseError.new( + message: "Response error: #{error['message']}", + error: error ) end + response end - def find_tool(name) - @mcp_client.tools.find { |t| t.name == name } || - raise(Errors::ResponseError.new( - message: "Tool '#{name}' not found", - error: { "code" => -32_602, "message" => "Tool not found" } - )) + def with_sdk_errors + yield + rescue ::MCP::Client::ServerError => e + raise Errors::ResponseError.new( + message: "Response error: #{e.message}", + error: { "code" => e.code, "message" => e.message, "data" => e.data }.compact + ) + rescue ::MCP::Client::SessionExpiredError => e + message = "MCP session expired; call restart! before retrying: #{e.message}" + raise Errors::SessionExpiredError.new(message: message) + rescue ::MCP::CancelledError => e + raise Errors::RequestCancelled.new(message: e.message, request_id: e.request_id) + rescue ::MCP::Client::InputRequiredError => e + message = "The server requested multi-round-trip input, which is not supported " \ + "on the stable 2025-11-25 integration: #{e.message}" + raise Errors::UnsupportedFeature.new( + message: message + ) + rescue ::MCP::Client::RequestHandlerError, ::MCP::Client::ValidationError => e + raise Errors::TransportError.new(message: e.message, error: e) + end + + def protocol_version + config_value(:protocol_version) || MCP.config.protocol_version + end + + def request_timeout_seconds + (config_value(:request_timeout) || 10_000).to_f / 1000 + end + + # Leave enough time for the SDK to serialize and send the server-request + # response before the enclosing HTTP request reaches its own deadline. + def server_request_timeout_seconds + request_timeout_seconds * 0.8 end - # Transform methods to normalize official SDK objects + def config_value(key) + @config[key] || @config[key.to_s] + end + + # Kept for compatibility with callers that normalized SDK model objects + # through the adapter before 0.25. The 0.25 list path now preserves the + # original wire hashes directly. def transform_tool(tool) + return tool if tool.is_a?(Hash) + { "name" => tool.name, "description" => tool.description, "inputSchema" => tool.input_schema, "outputSchema" => tool.output_schema, - "_meta" => extract_tool_meta(tool) + "_meta" => tool.respond_to?(:meta) ? tool.meta : tool["_meta"] }.compact end def transform_resource(resource) - { - "name" => resource["name"], - "uri" => resource["uri"], - "title" => resource["title"], - "description" => resource["description"], - "mimeType" => resource["mimeType"], - "annotations" => resource["annotations"], - "icons" => resource["icons"], - "_meta" => resource["_meta"] - }.compact + resource end def transform_prompt(prompt) - { - "name" => prompt["name"], - "title" => prompt["title"], - "description" => prompt["description"], - "arguments" => prompt["arguments"] - }.compact + prompt end def transform_resource_template(resource_template) - { - "name" => resource_template["name"], - "uriTemplate" => resource_template["uriTemplate"], - "title" => resource_template["title"], - "description" => resource_template["description"], - "mimeType" => resource_template["mimeType"], - "annotations" => resource_template["annotations"], - "icons" => resource_template["icons"], - "_meta" => resource_template["_meta"] - }.compact - end + resource_template + end + + # Captures responses emitted by the existing Sample/Elicitation objects so + # they can satisfy the official SDK's synchronous server-request contract. + class ServerRequestBridge + def initialize(client, timeout:) + @client = client + @timeout = timeout + @mutex = Mutex.new + @condition = ConditionVariable.new + @response = nil + @error = nil + end - def transform_tool_result(result) - # The MCP gem returns the full JSON-RPC response - # Extract the content from result["result"]["content"] - content = if result.is_a?(Hash) && result["result"] && result["result"]["content"] - result["result"]["content"] - elsif result.is_a?(Array) - result.map { |item| transform_content_item(item) } - else - [{ "type" => "text", "text" => result.to_s }] - end - - is_error = if result.is_a?(Hash) && result["result"] - result["result"]["isError"] - end - - result_data = { "content" => content } - result_data["isError"] = is_error unless is_error.nil? - - Result.new({ - "result" => result_data - }) - end - - def transform_content_item(item) - case item - when String - { "type" => "text", "text" => item } - when Hash - item - else - { "type" => "text", "text" => item.to_s } + def with_current + previous = Thread.current[:ruby_llm_mcp_sdk_bridge] + Thread.current[:ruby_llm_mcp_sdk_bridge] = self + yield + ensure + Thread.current[:ruby_llm_mcp_sdk_bridge] = previous end - end - def transform_resource_content(result) - contents = if result.is_a?(Array) - result.map { |r| transform_single_resource_content(r) } - else - [transform_single_resource_content(result)] - end + def sampling_callback + @client.on[:sampling] + end - Result.new({ - "result" => { - "contents" => contents - } - }) - end + def sampling_callback_enabled? + @client.sampling_callback_enabled? + end - def transform_single_resource_content(result) - { - "uri" => result["uri"], - "mimeType" => result["mimeType"], - "text" => result["text"], - "blob" => result["blob"] - } - end + def elicitation_callback + @client.on[:elicitation] + end - def transform_prompt_result(result) - if result.is_a?(Hash) && (result.key?("result") || result.key?("error")) - Result.new(result) - else - Result.new({ - "result" => result || {} - }) + def register_in_flight_request(*) + nil end - end - def configured_extensions? - !Extensions::Registry.normalize_map(@config[:extensions]).empty? - end + def unregister_in_flight_request(*) + nil + end - def warn_passive_extension_support! - self.class.warn_passive_extension_support_once - end + def sampling_create_message_response(id:, model:, message:, **_options) + response = Native::Messages::Responses.sampling_create_message(id: id, model: model, message: message) + resolve(response[:result]) + end - def extract_tool_meta(tool) - return tool["_meta"] if tool.respond_to?(:[]) && tool["_meta"] - return tool.meta if tool.respond_to?(:meta) - return tool.instance_variable_get(:@meta) if tool.instance_variable_defined?(:@meta) + def elicitation_response(id:, elicitation:) + normalized = elicitation.transform_keys(&:to_sym) + response = Native::Messages::Responses.elicitation(id: id, **normalized) + resolve(response[:result]) + end - nil - end + def error_response(id:, message:, code: -1) # rubocop:disable Lint/UnusedMethodArgument + @mutex.synchronize do + @error ||= [message, code] + @condition.broadcast + end + end + + def response!(wait:, timeout_response: nil) + await_response if wait + response, error = @mutex.synchronize { [@response, @error] } + if error + raise ::MCP::Client::ServerRequestError.new(error.first, code: error.last) + end + return response if response + + if wait && timeout_response + yield if block_given? + return timeout_response + end - class << self - def warn_passive_extension_support_once - @extensions_warning_mutex ||= Mutex.new + raise ::MCP::Client::ServerRequestError.new("Client handler did not produce a response", code: -1) + end + + private + + def resolve(response) + @mutex.synchronize do + @response = stringify_keys(response) + @condition.broadcast + end + end + + def await_response + deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + @timeout + @mutex.synchronize do + until @response || @error + remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC) + break if remaining <= 0 - @extensions_warning_mutex.synchronize do - return if @extensions_warning_emitted + @condition.wait(@mutex, remaining) + end + end + end - RubyLLM::MCP.logger.warn( - "MCP SDK adapter extension configuration is passive: extensions are accepted but not advertised." - ) - @extensions_warning_emitted = true + def stringify_keys(value) + case value + when Hash + value.to_h { |key, item| [key.to_s, stringify_keys(item)] } + when Array + value.map { |item| stringify_keys(item) } + else + value end end end diff --git a/lib/ruby_llm/mcp/client.rb b/lib/ruby_llm/mcp/client.rb index d0f38458..622ed06b 100644 --- a/lib/ruby_llm/mcp/client.rb +++ b/lib/ruby_llm/mcp/client.rb @@ -8,7 +8,7 @@ class Client extend Forwardable attr_reader :name, :config, :transport_type, :request_timeout, :log_level, :on, :roots, :adapter, - :on_logging_level + :on_logging_level, :adapter_type attr_accessor :linked_resources def initialize(name:, transport_type:, sdk: nil, adapter: nil, start: true, # rubocop:disable Metrics/ParameterLists, Metrics/MethodLength @@ -16,6 +16,7 @@ def initialize(name:, transport_type:, sdk: nil, adapter: nil, start: true, # ru @name = name @transport_type = transport_type.to_sym @adapter_type = adapter || sdk || MCP.config.default_adapter + @adapter_type = @adapter_type.to_sym # Validate early MCP.config.adapter_config.validate!( @@ -49,6 +50,7 @@ def initialize(name:, transport_type:, sdk: nil, adapter: nil, start: true, # ru @resources = {} @resource_templates = {} @prompts = {} + @cache_expirations = {} @log_level = nil @@ -81,6 +83,23 @@ def restart! @adapter.restart! end + # Returns the official SDK client when this client uses adapter: :mcp_sdk. + # Direct SDK calls bypass RubyLLM::MCP result normalization. + def sdk_client + unless @adapter_type == :mcp_sdk + raise Errors::UnsupportedFeature.new( + message: "sdk_client is only available when using adapter: :mcp_sdk" + ) + end + + start unless alive? + @adapter.mcp_client + end + + def cache_hints + @adapter.cache_hints + end + # Get or create OAuth provider for this client # @param type [Symbol] OAuth provider type (:standard or :browser, defaults to :standard) # @param options [Hash] additional options passed to provider @@ -135,6 +154,7 @@ def tool(name, refresh: false) def reset_tools! @tools = {} + @cache_expirations.delete(:tools) end def resources(refresh: false) @@ -172,6 +192,7 @@ def unsubscribe_from_resource(resource_or_uri) # rubocop:disable Naming/Predicat def reset_resources! @resources = {} + @cache_expirations.delete(:resources) end def resource_templates(refresh: false) @@ -194,6 +215,7 @@ def resource_template(name, refresh: false) def reset_resource_templates! @resource_templates = {} + @cache_expirations.delete(:resource_templates) end def prompts(refresh: false) @@ -216,6 +238,7 @@ def prompt(name, refresh: false) def reset_prompts! @prompts = {} + @cache_expirations.delete(:prompts) end def tasks_list @@ -336,7 +359,7 @@ def on_sampling(handler_class = nil, **options, &block) end def elicitation_enabled? - @adapter_type == :ruby_llm && MCP.config.elicitation.enabled? + @adapter.supports?(:elicitation) && MCP.config.elicitation.enabled? end def elicitation_callback_enabled? @@ -405,7 +428,7 @@ def transport_oauth_provider return nil unless @adapter # For RubyLLMAdapter - if @adapter.respond_to?(:native_client) + if @adapter_type == :ruby_llm && @adapter.respond_to?(:native_client) transport = @adapter.native_client.transport transport_protocol = transport.transport_protocol return transport_protocol.oauth_provider if transport_protocol.respond_to?(:oauth_provider) @@ -451,13 +474,30 @@ def require_feature!(feature) end def fetch(cache_key, refresh) - instance_variable_set("@#{cache_key}", {}) if refresh + refresh ||= cache_expired?(cache_key) + if refresh + instance_variable_set("@#{cache_key}", {}) + @cache_expirations.delete(cache_key) + end if instance_variable_get("@#{cache_key}").empty? instance_variable_set("@#{cache_key}", yield) + update_cache_expiration(cache_key) end instance_variable_get("@#{cache_key}") end + def cache_expired?(cache_key) + expires_at = @cache_expirations[cache_key] + expires_at && Process.clock_gettime(Process::CLOCK_MONOTONIC) >= expires_at + end + + def update_cache_expiration(cache_key) + ttl_ms = @adapter.cache_hints.dig(cache_key, :ttl_ms) + return @cache_expirations.delete(cache_key) if ttl_ms.nil? + + @cache_expirations[cache_key] = Process.clock_gettime(Process::CLOCK_MONOTONIC) + (ttl_ms.to_f / 1000) + end + def build_map(raw_data, klass, with_prefix: false) raw_data.each_with_object({}) do |item, acc| instance = if with_prefix diff --git a/lib/ruby_llm/mcp/configuration.rb b/lib/ruby_llm/mcp/configuration.rb index a7f4a6a9..1c08d145 100644 --- a/lib/ruby_llm/mcp/configuration.rb +++ b/lib/ruby_llm/mcp/configuration.rb @@ -42,8 +42,14 @@ def validate_transport!(transport) end def validate_adapter_transport_combination!(adapter, transport) - # SSE is supported by both ruby_llm and mcp_sdk adapters - # No validation needed at this time + return unless adapter == :mcp_sdk && transport == :sse + + raise Errors::AdapterConfigurationError.new( + message: <<~MSG.strip + Transport 'sse' is native-only and is not supported by the mcp_sdk adapter. + Use adapter: :ruby_llm for legacy SSE, or use transport_type: :streamable_http with adapter: :mcp_sdk. + MSG + ) end end diff --git a/lib/ruby_llm/mcp/prompt.rb b/lib/ruby_llm/mcp/prompt.rb index 6802dba9..da3866bb 100644 --- a/lib/ruby_llm/mcp/prompt.rb +++ b/lib/ruby_llm/mcp/prompt.rb @@ -21,12 +21,15 @@ def to_h end end - attr_reader :name, :description, :arguments, :adapter + attr_reader :name, :title, :description, :arguments, :adapter, :icons, :meta def initialize(adapter, prompt) @adapter = adapter @name = prompt["name"] + @title = prompt["title"] @description = prompt["description"] + @icons = prompt["icons"] || [] + @meta = prompt["_meta"] || {} @arguments = parse_arguments(prompt["arguments"]) end diff --git a/lib/ruby_llm/mcp/resource.rb b/lib/ruby_llm/mcp/resource.rb index 96ca5c17..ace70053 100644 --- a/lib/ruby_llm/mcp/resource.rb +++ b/lib/ruby_llm/mcp/resource.rb @@ -3,14 +3,22 @@ module RubyLLM module MCP class Resource - attr_reader :uri, :name, :description, :mime_type, :adapter, :subscribed, :apps_metadata + attr_reader :uri, :name, :title, :description, :mime_type, :adapter, :subscribed, :apps_metadata, + :annotations, :icons, :size, :meta, :cache_hint def initialize(adapter, resource) @adapter = adapter @uri = resource["uri"] @name = resource["name"] + @title = resource["title"] @description = resource["description"] @mime_type = resource["mimeType"] + @annotations = resource["annotations"] + @icons = resource["icons"] || [] + @size = resource["size"] + @meta = resource["_meta"] || {} + @cache_hint = nil + @content_expires_at = nil @apps_metadata = Extensions::Apps::ResourceMetadata.new(resource[Extensions::Apps::Constants::META_KEY]) if resource.key?("content_response") @content_response = resource["content_response"] @@ -21,6 +29,7 @@ def initialize(adapter, resource) end def content + reset_content! if content_cache_expired? return @content unless @content.nil? result = read_response @@ -28,6 +37,8 @@ def content @content_response = result.value.dig("contents", 0) @content = @content_response["text"] || @content_response["blob"] + apply_cache_hint(result.value) + @content end def content_loaded? @@ -57,6 +68,7 @@ def unsubscribe! def reset_content! @content = nil @content_response = nil + @content_expires_at = nil end def include(chat, **args) @@ -94,6 +106,19 @@ def to_h private + def apply_cache_hint(value) + ttl_ms = value["ttlMs"] + cache_scope = value["cacheScope"] + @cache_hint = { ttl_ms: ttl_ms, cache_scope: cache_scope }.compact.freeze + return if ttl_ms.nil? + + @content_expires_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) + (ttl_ms.to_f / 1000) + end + + def content_cache_expired? + @content_expires_at && Process.clock_gettime(Process::CLOCK_MONOTONIC) >= @content_expires_at + end + def content_type return "text" if @content_response.nil? diff --git a/lib/ruby_llm/mcp/resource_template.rb b/lib/ruby_llm/mcp/resource_template.rb index e846d6f9..7e048fe8 100644 --- a/lib/ruby_llm/mcp/resource_template.rb +++ b/lib/ruby_llm/mcp/resource_template.rb @@ -5,14 +5,19 @@ module RubyLLM module MCP class ResourceTemplate - attr_reader :uri, :name, :description, :mime_type, :adapter, :template, :apps_metadata + attr_reader :uri, :name, :title, :description, :mime_type, :adapter, :template, :apps_metadata, + :annotations, :icons, :meta def initialize(adapter, resource) @adapter = adapter @uri = resource["uriTemplate"] @name = resource["name"] + @title = resource["title"] @description = resource["description"] @mime_type = resource["mimeType"] + @annotations = resource["annotations"] + @icons = resource["icons"] || [] + @meta = resource["_meta"] || {} @apps_metadata = Extensions::Apps::ResourceMetadata.new(resource[Extensions::Apps::Constants::META_KEY]) end diff --git a/lib/ruby_llm/mcp/tool.rb b/lib/ruby_llm/mcp/tool.rb index 071fb02b..7653ee52 100644 --- a/lib/ruby_llm/mcp/tool.rb +++ b/lib/ruby_llm/mcp/tool.rb @@ -26,7 +26,7 @@ def to_h class Tool < RubyLLM::Tool attr_reader :name, :title, :description, :adapter, :annotations, :tool_response, :with_prefix, :output_schema, - :apps_metadata + :apps_metadata, :icons, :meta def initialize(adapter, tool_response, with_prefix: false) super() @@ -35,7 +35,10 @@ def initialize(adapter, tool_response, with_prefix: false) @with_prefix = with_prefix @name = format_name(tool_response["name"]) @mcp_name = tool_response["name"] + @title = tool_response["title"] @description = tool_response["description"].to_s + @icons = tool_response["icons"] || [] + @meta = tool_response["_meta"] || {} @input_schema = tool_response["inputSchema"] @output_schema = tool_response["outputSchema"] diff --git a/ruby_llm-mcp.gemspec b/ruby_llm-mcp.gemspec index 9c08b874..ced124c1 100644 --- a/ruby_llm-mcp.gemspec +++ b/ruby_llm-mcp.gemspec @@ -45,5 +45,5 @@ Gem::Specification.new do |spec| # Optional dependency for mcp_sdk adapter # Users who want to use adapter: :mcp_sdk should add to their Gemfile: - # gem 'mcp', '~> 0.7' + # gem 'mcp', '~> 0.25' end diff --git a/spec/ruby_llm/mcp/adapters/extensions_spec.rb b/spec/ruby_llm/mcp/adapters/extensions_spec.rb index 023ce86e..102aa323 100644 --- a/spec/ruby_llm/mcp/adapters/extensions_spec.rb +++ b/spec/ruby_llm/mcp/adapters/extensions_spec.rb @@ -66,36 +66,22 @@ def [](key) end describe RubyLLM::MCP::Adapters::MCPSdkAdapter do - let(:adapter) { described_class.allocate } - - before do - described_class.instance_variable_set(:@extensions_warning_emitted, nil) - described_class.instance_variable_set(:@extensions_warning_mutex, nil) + let(:adapter) do + described_class.allocate.tap do |instance| + instance.instance_variable_set(:@config, { extensions: { extension_id => { "enabled" => true } } }) + end end - it "reports passive extension support mode" do - expect(adapter.supports_extension_negotiation?).to be(false) - expect(adapter.extension_mode).to eq(:passive) - expect(adapter.build_client_extensions_capabilities(protocol_version: "2026-01-26")).to eq({}) + it "negotiates extensions through the official SDK handshake" do + expect(adapter.supports_extension_negotiation?).to be(true) + expect(adapter.extension_mode).to eq(:full) + expect(adapter.build_client_extensions_capabilities(protocol_version: "2025-11-25")).to eq( + extension_id => { "enabled" => true } + ) end - it "emits passive support warning once per process when extensions are configured" do - logger = instance_double(Logger, warn: nil) - allow(RubyLLM::MCP).to receive(:logger).and_return(logger) - - adapter_one = described_class.allocate - adapter_one.instance_variable_set(:@config, { extensions: { extension_id => {} } }) - - adapter_two = described_class.allocate - adapter_two.instance_variable_set(:@config, { extensions: { extension_id => {} } }) - - expect(adapter_one.send(:configured_extensions?)).to be(true) - expect(adapter_two.send(:configured_extensions?)).to be(true) - - adapter_one.send(:warn_passive_extension_support!) - adapter_two.send(:warn_passive_extension_support!) - - expect(logger).to have_received(:warn).once + it "suppresses extension capabilities on pre-extension protocol versions" do + expect(adapter.build_client_extensions_capabilities(protocol_version: "2025-03-26")).to eq({}) end it "passes through tool _meta for apps metadata parsing parity" do diff --git a/spec/ruby_llm/mcp/adapters/mcp_sdk_adapter_spec.rb b/spec/ruby_llm/mcp/adapters/mcp_sdk_adapter_spec.rb new file mode 100644 index 00000000..a6ebb0f4 --- /dev/null +++ b/spec/ruby_llm/mcp/adapters/mcp_sdk_adapter_spec.rb @@ -0,0 +1,305 @@ +# frozen_string_literal: true + +RSpec.describe RubyLLM::MCP::Adapters::MCPSdkAdapter do + # rubocop:disable Lint/ConstantDefinitionInBlock, RSpec/LeakyConstantDeclaration, RSpec/InstanceVariable + class FakeSdkTransport + attr_reader :connect_options, :server_info, :requests, :handlers + + def initialize(server_info: nil, &response) + @server_info = server_info || { + "protocolVersion" => "2025-11-25", + "capabilities" => { "tools" => {}, "resources" => {}, "prompts" => {}, "completions" => {} } + } + @response = response + @requests = [] + @handlers = {} + @connected = false + end + + def connect(**options) + @connect_options = options + @connected = true + @server_info + end + + def connected? + @connected + end + + def close + @connected = false + @server_info = nil + end + + def send_request(request:) + @requests << request + @response ? @response.call(request) : { "jsonrpc" => "2.0", "id" => request[:id], "result" => {} } + end + + def on_server_request(method, &handler) + @handlers[method] = handler + end + end + # rubocop:enable Lint/ConstantDefinitionInBlock, RSpec/LeakyConstantDeclaration, RSpec/InstanceVariable + + let(:client) do + instance_double( + RubyLLM::MCP::Client, + name: "contract-client", + linked_resources: [], + on: {}, + sampling_callback_enabled?: false + ) + end + + def build_adapter(transport_type: :stdio, config: {}) + described_class.new( + client, + transport_type: transport_type, + config: { protocol_version: "2025-11-25", request_timeout: 2500 }.merge(config) + ) + end + + def official_oauth_providers + redirect_uri = "http://127.0.0.1:9292/callback" + private_key = OpenSSL::PKey::RSA.generate(2048) + [ + MCP::Client::OAuth::Provider.new( + client_metadata: { redirect_uris: [redirect_uri] }, redirect_uri: redirect_uri, + redirect_handler: ->(_url) {}, callback_handler: -> {} + ), + MCP::Client::OAuth::ClientCredentialsProvider.new( + client_id: "client", client_secret: "secret", token_endpoint_auth_method: "client_secret_basic" + ), + MCP::Client::OAuth::ClientCredentialsProvider.new( + client_id: "client", client_secret: "secret", token_endpoint_auth_method: "client_secret_post" + ), + MCP::Client::OAuth::ClientCredentialsProvider.new( + client_id: "client", private_key: private_key, signing_algorithm: "RS256", + token_endpoint_auth_method: "private_key_jwt" + ), + MCP::Client::OAuth::CrossAppAccessProvider.new( + client_id: "client", client_secret: "secret", + assertion_provider: ->(audience:, resource:) { "id-jag:#{audience}:#{resource}" } + ) + ] + end + + describe "adapter boundaries" do + it "keeps native-only transports out of the SDK adapter" do + expect do + described_class.new(client, transport_type: :sse, config: {}) + end.to raise_error(RubyLLM::MCP::Errors::UnsupportedTransport, /Supported transports: stdio, http, streamable/) + end + + it "reports features by transport without changing native feature declarations" do + expect(described_class.support?(:sampling, transport: :stdio)).to be(false) + expect(described_class.support?(:sampling, transport: :streamable_http)).to be(true) + expect(described_class.support?(:oauth, transport: :http)).to be(true) + expect(described_class.support?(:logging, transport: :http)).to be(false) + expect(RubyLLM::MCP::Adapters::RubyLLMAdapter.support?(:logging, transport: :stdio)).to be(true) + end + end + + describe "official lifecycle" do + let(:transport) { FakeSdkTransport.new } + let(:adapter) { build_adapter } + + before do + allow(MCP::Client::Stdio).to receive(:new).and_return(transport) + end + + it "connects with client identity, protocol version, and capabilities" do + adapter.start + + expect(transport.connect_options).to include( + client_info: { name: "contract-client", version: RubyLLM::MCP::VERSION }, + protocol_version: "2025-11-25", + capabilities: {} + ) + expect(adapter).to be_alive + expect(adapter.capabilities.tools_list?).to be(true) + expect(adapter.ping).to be(true) + end + + it "closes and reconnects cleanly" do + allow(MCP::Client::Stdio).to receive(:new).and_return(transport, FakeSdkTransport.new) + adapter.start + first_client = adapter.mcp_client + adapter.restart! + + expect(adapter).to be_alive + expect(adapter.mcp_client).not_to equal(first_client) + adapter.stop + expect(adapter).not_to be_alive + expect(adapter.cache_hints).to eq({}) + end + + it "forwards stdio timeout and frame limit to the SDK" do + allow(MCP::Client::Stdio).to receive(:new).and_return(transport) + adapter = build_adapter(config: { command: "server", args: ["--stdio"], env: { "A" => "B" }, + max_line_bytes: 1234 }) + adapter.start + + expect(MCP::Client::Stdio).to have_received(:new).with( + command: "server", + args: ["--stdio"], + env: { "A" => "B" }, + read_timeout: 2.5, + max_line_bytes: 1234 + ) + end + end + + describe "official HTTP configuration" do + let(:transport) { FakeSdkTransport.new } + + it "passes headers, an official OAuth provider, and the message limit" do + provider = instance_double(MCP::Client::OAuth::ClientCredentialsProvider) + allow(MCP::Client::HTTP).to receive(:new).and_return(transport) + adapter = build_adapter( + transport_type: :streamable_http, + config: { + url: "http://127.0.0.1:9292/mcp", + headers: { "X-Test" => "yes" }, + oauth: { provider: provider }, + max_message_bytes: 4096 + } + ) + adapter.start + + expect(MCP::Client::HTTP).to have_received(:new).with( + url: "http://127.0.0.1:9292/mcp", + headers: { "X-Test" => "yes" }, + oauth: provider, + max_message_bytes: 4096 + ) + end + + it "accepts every documented official OAuth provider configuration" do + official_oauth_providers.each_with_index do |provider, index| + allow(MCP::Client::HTTP).to receive(:new).and_return(FakeSdkTransport.new) + oauth = index.even? ? provider : { provider: provider } + build_adapter(transport_type: :http, config: { url: "http://127.0.0.1:9292/mcp", oauth: oauth }).start + + expect(MCP::Client::HTTP).to have_received(:new).with( + url: "http://127.0.0.1:9292/mcp", headers: {}, oauth: provider + ) + end + end + + it "rejects a native OAuth provider with migration guidance" do + provider = RubyLLM::MCP::Auth::OAuthProvider.allocate + adapter = build_adapter( + transport_type: :http, + config: { url: "http://127.0.0.1:9292/mcp", oauth: provider } + ) + + expect { adapter.start }.to raise_error( + RubyLLM::MCP::Errors::AdapterConfigurationError, + /MCP::Client::OAuth provider/ + ) + end + end + + describe "payload fidelity and pagination" do + let(:pages) do + { + nil => { + "tools" => [{ + "name" => "first", "title" => "First", "description" => "one", + "inputSchema" => { "type" => "object" }, "icons" => [{ "src" => "one.svg" }], + "annotations" => { "readOnlyHint" => true }, "_meta" => { "ui" => { "resourceUri" => "ui://first" } } + }], + "nextCursor" => "page-2", "ttlMs" => 5000, "cacheScope" => "public" + }, + "page-2" => { + "tools" => [{ "name" => "second", "inputSchema" => { "type" => "object" } }], + "ttlMs" => 1000, "cacheScope" => "private" + } + } + end + let(:transport) do + FakeSdkTransport.new do |request| + if request[:method] == "tools/list" + cursor = request.dig(:params, :cursor) + { "jsonrpc" => "2.0", "id" => request[:id], "result" => pages.fetch(cursor) } + elsif request[:method] == "tools/call" + { + "jsonrpc" => "2.0", "id" => request[:id], + "result" => { + "content" => [{ "type" => "text", "text" => "ok" }], + "structuredContent" => { "answer" => 42 }, "isError" => false, + "_meta" => { "trace" => "kept" } + } + } + else + { "jsonrpc" => "2.0", "id" => request[:id], "result" => {} } + end + end + end + let(:adapter) { build_adapter } + + before do + allow(MCP::Client::Stdio).to receive(:new).and_return(transport) + adapter.start + end + + it "walks every page and preserves fields omitted by MCP::Client::Tool" do + tools = adapter.tool_list + + expect(tools.map { |tool| tool["name"] }).to eq(%w[first second]) + expect(tools.first).to include( + "title" => "First", + "icons" => [{ "src" => "one.svg" }], + "annotations" => { "readOnlyHint" => true }, + "_meta" => { "ui" => { "resourceUri" => "ui://first" } } + ) + expect(adapter.cache_hints[:tools]).to eq(ttl_ms: 1000, cache_scope: "private") + end + + it "preserves structured content, execution status, and metadata" do + result = adapter.execute_tool(name: "structured", parameters: {}) + + expect(result.value).to include( + "structuredContent" => { "answer" => 42 }, + "isError" => false, + "_meta" => { "trace" => "kept" } + ) + end + end + + describe "error translation" do + it "preserves JSON-RPC error details" do + transport = FakeSdkTransport.new do |request| + { "jsonrpc" => "2.0", "id" => request[:id], "error" => { "code" => -32_602, "message" => "missing" } } + end + allow(MCP::Client::Stdio).to receive(:new).and_return(transport) + adapter = build_adapter + adapter.start + + expect { adapter.tool_list }.to raise_error(RubyLLM::MCP::Errors::ResponseError) do |error| + expect(error.error).to include("code" => -32_602, "message" => "missing") + end + end + + it "does not retry side-effecting calls after session expiry" do + transport = FakeSdkTransport.new + allow(MCP::Client::Stdio).to receive(:new).and_return(transport) + sdk_client = instance_double(MCP::Client, transport: transport, connected?: true, + server_info: transport.server_info) + allow(sdk_client).to receive(:connect).and_return(transport.server_info) + allow(sdk_client).to receive(:call_tool).and_raise( + MCP::Client::SessionExpiredError.new("expired", { method: "tools/call" }) + ) + allow(MCP::Client).to receive(:new).and_return(sdk_client) + adapter = build_adapter + adapter.start + + expect do + adapter.execute_tool(name: "write", parameters: {}) + end.to raise_error(RubyLLM::MCP::Errors::SessionExpiredError, /restart!/) + expect(sdk_client).to have_received(:call_tool).once + end + end +end diff --git a/spec/ruby_llm/mcp/adapters/mcp_sdk_server_requests_spec.rb b/spec/ruby_llm/mcp/adapters/mcp_sdk_server_requests_spec.rb new file mode 100644 index 00000000..bc25d73d --- /dev/null +++ b/spec/ruby_llm/mcp/adapters/mcp_sdk_server_requests_spec.rb @@ -0,0 +1,164 @@ +# frozen_string_literal: true + +RSpec.describe "MCP SDK server requests" do # rubocop:disable RSpec/DescribeClass + around do |example| + # MCP::Client::HTTP keeps a concurrent Net::HTTP SSE listener open for + # server-to-client requests. WebMock's Net::HTTP adapter prevents that + # listener from receiving fixture events, so these real loopback checks run + # against the transport without interception. + WebMock.disable! + MCPTestConfiguration.reset_config! + example.run + ensure + WebMock.enable! + MCPTestConfiguration.reset_config! + end + + def build_http_client(request_timeout: 5000) + RubyLLM::MCP::Client.new( + name: "mcp-sdk-server-requests", + adapter: :mcp_sdk, + transport_type: :streamable_http, + start: false, + request_timeout: request_timeout, + config: { url: TestServerManager::HTTP_SERVER_URL } + ) + end + + it "round-trips sampling through the existing RubyLLM handler contract" do + RubyLLM::MCP.configure do |config| + config.sampling.enabled = true + config.sampling.preferred_model { "fixture-model" } + end + client = build_http_client + client.on_sampling do |sample| + expect(sample.message).to eq("Hello, how are you?") + { + accepted: true, + response: RubyLLM::Message.new(role: "assistant", content: "SDK sampling response") + } + end + client.start + + result = client.tool("sampling-test").execute + + expect(result.to_s).to include("Sampling test completed") + expect(result.to_s).to include("SDK sampling response") + ensure + client&.stop + end + + it "round-trips form elicitation through the existing RubyLLM handler contract" do + RubyLLM::MCP.configure do |config| + config.elicitation.form = true + config.elicitation.url = false + end + client = build_http_client + client.on_elicitation do |elicitation| + expect(elicitation.message).to eq("Choose a value") + { action: :accept, response: { "response" => "from-sdk", "confirmed" => true } } + end + client.start + + result = client.tool("simple_elicitation").execute(message: "Choose a value") + + expect(result.to_s).to include("Simple elicitation completed") + expect(result.to_s).to include("from-sdk") + ensure + client&.stop + end + + it "rejects sampling requests with the MCP user-rejection error" do + RubyLLM::MCP.configure do |config| + config.sampling.enabled = true + config.sampling.preferred_model { "fixture-model" } + end + client = build_http_client + client.on_sampling { false } + client.start + + result = client.tool("sampling-test").execute + + expect(result.to_s).to include("MCP error -1") + expect(result.to_s).to include("Sampling request was rejected") + ensure + client&.stop + end + + it "preserves sampling handler errors as SDK server-request errors" do + RubyLLM::MCP.configure do |config| + config.sampling.enabled = true + config.sampling.preferred_model { "fixture-model" } + end + client = build_http_client + client.on_sampling { raise "sampling guard failed" } + client.start + + result = client.tool("sampling-test").execute + + expect(result.to_s).to include("MCP error -1") + expect(result.to_s).to include("Error executing sampling request") + ensure + client&.stop + end + + it "returns decline and cancellation actions through official HTTP" do + client = build_http_client + actions = [{ action: :reject }, { action: :cancel }] + client.on_elicitation { actions.shift } + client.start + + declined = client.tool("simple_elicitation").execute(message: "decline this") + cancelled = client.tool("simple_elicitation").execute(message: "cancel this") + + expect(declined.to_s).to include('"action":"decline"') + expect(cancelled.to_s).to include('"action":"cancel"') + ensure + client&.stop + end + + it "preserves elicitation handler failures as SDK server-request errors" do + client = build_http_client + client.on_elicitation { raise "approval UI unavailable" } + client.start + + result = client.tool("simple_elicitation").execute(message: "handle failure") + + expect(result.to_s).to include("MCP error -32603") + expect(result.to_s).to include("approval UI unavailable") + ensure + client&.stop + end + + it "waits for asynchronous elicitation completion" do + client = build_http_client + client.on_elicitation do |elicitation| + response = RubyLLM::MCP::Handlers::AsyncResponse.new(elicitation_id: elicitation.id) + Thread.new do + sleep 0.02 + response.complete({ "response" => "async-sdk", "confirmed" => true }) + end + response + end + client.start + + result = client.tool("simple_elicitation").execute(message: "complete later") + + expect(result.to_s).to include("async-sdk") + ensure + client&.stop + end + + it "returns cancellation when asynchronous elicitation exceeds the request timeout" do + client = build_http_client(request_timeout: 200) + client.on_elicitation { :pending } + client.start + + result = client.tool("simple_elicitation").execute(message: "time out") + + expect(result.to_s).to include('"action":"cancel"') + expect(RubyLLM::MCP::Handlers::ElicitationRegistry.size).to eq(0) + ensure + client&.stop + end +end diff --git a/spec/ruby_llm/mcp/adapters/mcp_sdk_sse_spec.rb b/spec/ruby_llm/mcp/adapters/mcp_sdk_sse_spec.rb index bc1d1729..ec613981 100644 --- a/spec/ruby_llm/mcp/adapters/mcp_sdk_sse_spec.rb +++ b/spec/ruby_llm/mcp/adapters/mcp_sdk_sse_spec.rb @@ -1,94 +1,18 @@ # frozen_string_literal: true -class MCPSdkSSERunner - class << self - def instance - @instance ||= MCPSdkSSERunner.new - end - end - - def start - client.start - end - - def stop - client&.stop - end - - def client - @client ||= RubyLLM::MCP::Client.new( - name: "fast-mcp-ruby-sdk", - adapter: :mcp_sdk, - transport_type: :sse, - config: { - url: "http://localhost:#{TestServerManager::PORTS[:sse]}/mcp/sse", - version: :http1 - } - ) - end -end - RSpec.describe RubyLLM::MCP::Adapters::MCPSdkAdapter do # rubocop:disable RSpec/SpecFilePathFormat - let(:client) { MCPSdkSSERunner.instance.client } - - before(:all) do # rubocop:disable RSpec/BeforeAfterAll - if RUBY_VERSION < "3.1.0" || !ClientRunner.mcp_sdk_available? - skip "Specs require Ruby 3.1+ with the mcp gem available" - else - MCPSdkSSERunner.instance.start - end - end - - after(:all) do # rubocop:disable RSpec/BeforeAfterAll - if RUBY_VERSION >= "3.1.0" && ClientRunner.mcp_sdk_available? - MCPSdkSSERunner.instance.stop - end - end - - describe "connection" do - it "starts the transport and establishes connection" do - expect(client.alive?).to be(true) - end - end - - describe "tools" do - it "can list tools over SSE" do - tools = client.tools - expect(tools.count).to eq(2) - end - - it "can execute a tool over SSE" do - tool = client.tool("CalculateTool") - result = tool.execute(operation: "add", x: 1.0, y: 2.0) - expect(result.to_s).to eq("3.0") - end - end - - describe "resources" do - it "can list resources over SSE" do - resources = client.resources - expect(resources.count).to eq(1) - end - - it "can read a resource over SSE" do - resource = client.resources.first - content = resource.content - expect(content).not_to be_nil - expect(content).to be_a(String) - end - end - - describe "transport lifecycle" do - it "can restart the connection" do - client.stop - expect(client.alive?).to be(false) - - client.start - expect(client.alive?).to be(true) - - # Verify functionality after restart - tools = client.tools - expect(tools.count).to eq(2) - end + it "keeps legacy SSE on the native adapter" do + expect do + RubyLLM::MCP::Client.new( + name: "legacy-sse", + adapter: :mcp_sdk, + transport_type: :sse, + start: false, + config: { url: "http://localhost:3006/mcp/sse" } + ) + end.to raise_error( + RubyLLM::MCP::Errors::AdapterConfigurationError, + /Use adapter: :ruby_llm for legacy SSE/ + ) end end diff --git a/spec/ruby_llm/mcp/adapters/mcp_sdk_stdio_spec.rb b/spec/ruby_llm/mcp/adapters/mcp_sdk_stdio_spec.rb index 70aafc89..003dfb48 100644 --- a/spec/ruby_llm/mcp/adapters/mcp_sdk_stdio_spec.rb +++ b/spec/ruby_llm/mcp/adapters/mcp_sdk_stdio_spec.rb @@ -114,21 +114,10 @@ def client end describe "logging" do - it "can set log level and receive logging notifications over stdio" do - received_notification = nil - client.on_logging(level: RubyLLM::MCP::Logging::DEBUG) do |notification| - received_notification = notification - end - - client.tool("log_message").execute(message: "stdio sdk log", level: "debug", logger: "sdk-stdio") - - Timeout.timeout(3) do - sleep 0.05 until received_notification - end - - expect(received_notification.params["level"]).to eq("debug") - expect(received_notification.params["logger"]).to eq("sdk-stdio") - expect(received_notification.params.dig("data", "message")).to eq("stdio sdk log") + it "directs notification logging users to the native adapter" do + expect do + client.on_logging(level: RubyLLM::MCP::Logging::DEBUG) { nil } + end.to raise_error(RubyLLM::MCP::Errors::UnsupportedFeature, /ruby_llm adapter/) end end diff --git a/spec/ruby_llm/mcp/adapters/native_adapter_isolation_spec.rb b/spec/ruby_llm/mcp/adapters/native_adapter_isolation_spec.rb new file mode 100644 index 00000000..de363a3d --- /dev/null +++ b/spec/ruby_llm/mcp/adapters/native_adapter_isolation_spec.rb @@ -0,0 +1,25 @@ +# frozen_string_literal: true + +RSpec.describe "Native adapter isolation" do # rubocop:disable RSpec/DescribeClass + it "uses RubyLLM::MCP native protocol and transport objects when mcp 0.25 is installed" do + expect(defined?(MCP::VERSION)).to eq("constant") + sdk_version = Gem::Version.new(MCP::VERSION) + expect(sdk_version).to be >= Gem::Version.new("0.25.0") + expect(sdk_version).to be < Gem::Version.new("1.0.0") + + client = RubyLLM::MCP::Client.new( + name: "native-isolation", + adapter: :ruby_llm, + transport_type: :stdio, + start: false, + config: { command: "unused" } + ) + + expect(client.adapter).to be_a(RubyLLM::MCP::Adapters::RubyLLMAdapter) + expect(client.adapter.native_client).to be_a(RubyLLM::MCP::Native::Client) + expect(client.adapter.native_client.transport).to be_a(RubyLLM::MCP::Native::Transport) + expect(client.adapter).not_to respond_to(:mcp_client) + ensure + client&.stop + end +end diff --git a/spec/ruby_llm/mcp/cancellation_integration_spec.rb b/spec/ruby_llm/mcp/cancellation_integration_spec.rb index dd3ccc49..2ea88e15 100644 --- a/spec/ruby_llm/mcp/cancellation_integration_spec.rb +++ b/spec/ruby_llm/mcp/cancellation_integration_spec.rb @@ -26,7 +26,7 @@ end end - each_client_supporting(:sampling) do |config| + each_client(adapter: :native) do |config| describe "End-to-end cancellation with #{config[:name]}" do let(:client) { RubyLLM::MCP::Client.new(**config[:options], request_timeout: 30_000, start: false) } diff --git a/spec/ruby_llm/mcp/client_sdk_contract_spec.rb b/spec/ruby_llm/mcp/client_sdk_contract_spec.rb new file mode 100644 index 00000000..0c444ec7 --- /dev/null +++ b/spec/ruby_llm/mcp/client_sdk_contract_spec.rb @@ -0,0 +1,88 @@ +# frozen_string_literal: true + +RSpec.describe RubyLLM::MCP::Client do + let(:sdk_client) { instance_double(MCP::Client) } + let(:capabilities) { RubyLLM::MCP::ServerCapabilities.new("tools" => {}) } + let(:adapter) do + instance_double( + RubyLLM::MCP::Adapters::MCPSdkAdapter, + start: nil, + stop: nil, + alive?: true, + mcp_client: sdk_client, + capabilities: capabilities, + cache_hints: {} + ) + end + + before do + allow(adapter).to receive(:supports?) { |feature| feature == :tools } + allow(RubyLLM::MCP::Adapters::MCPSdkAdapter).to receive(:new).and_return(adapter) + end + + it "exposes the connected official client without leaking it into native mode" do + client = described_class.new( + name: "sdk-access", + adapter: :mcp_sdk, + transport_type: :stdio, + start: false, + config: { command: "unused" } + ) + + expect(client.sdk_client).to equal(sdk_client) + + native_client = described_class.new( + name: "native-access", + adapter: :ruby_llm, + transport_type: :stdio, + start: false, + config: { command: "unused" } + ) + expect { native_client.sdk_client }.to raise_error( + RubyLLM::MCP::Errors::UnsupportedFeature, + /only available.*mcp_sdk/ + ) + ensure + native_client&.stop + end + + it "expires collection caches according to SDK ttlMs hints" do + allow(adapter).to receive_messages(tool_list: [ + { "name" => "cached", + "inputSchema" => { "type" => "object", "properties" => {} } } + ], cache_hints: { tools: { ttl_ms: 5, cache_scope: "private" } }) + client = described_class.new( + name: "sdk-cache", + adapter: :mcp_sdk, + transport_type: :stdio, + start: false, + config: { command: "unused" } + ) + + expect(client.tools.map(&:name)).to eq(["cached"]) + expect(client.tools.map(&:name)).to eq(["cached"]) + expect(adapter).to have_received(:tool_list).once + + sleep 0.01 + expect(client.tools.map(&:name)).to eq(["cached"]) + expect(adapter).to have_received(:tool_list).twice + expect(client.cache_hints).to eq(tools: { ttl_ms: 5, cache_scope: "private" }) + end + + it "does not cache a collection when ttlMs is zero" do + allow(adapter).to receive_messages(tool_list: [ + { "name" => "uncached", + "inputSchema" => { "type" => "object", "properties" => {} } } + ], cache_hints: { tools: { ttl_ms: 0 } }) + client = described_class.new( + name: "sdk-no-cache", + adapter: :mcp_sdk, + transport_type: :stdio, + start: false, + config: { command: "unused" } + ) + + 2.times { client.tools } + expect(adapter).to have_received(:tool_list).twice + end +end diff --git a/spec/ruby_llm/mcp/elicitation_spec.rb b/spec/ruby_llm/mcp/elicitation_spec.rb index 23e5d7cc..0e9ad89c 100644 --- a/spec/ruby_llm/mcp/elicitation_spec.rb +++ b/spec/ruby_llm/mcp/elicitation_spec.rb @@ -83,7 +83,9 @@ end # Integration tests - only run on adapters that support elicitation - each_client_supporting(:elicitation) do + # The official SDK HTTP listener is covered separately without WebMock; + # its Net::HTTP streaming connection cannot run through WebMock safely. + each_client(adapter: :native) do before do # Configure elicitation handler for this test client.on_elicitation(&elicitation_handler) diff --git a/spec/ruby_llm/mcp/resource_cache_hint_spec.rb b/spec/ruby_llm/mcp/resource_cache_hint_spec.rb new file mode 100644 index 00000000..5fe3f06c --- /dev/null +++ b/spec/ruby_llm/mcp/resource_cache_hint_spec.rb @@ -0,0 +1,55 @@ +# frozen_string_literal: true + +RSpec.describe RubyLLM::MCP::Resource do + let(:adapter) { instance_double(RubyLLM::MCP::Adapters::BaseAdapter) } + let(:resource) do + described_class.new( + adapter, + { + "name" => "hinted", + "uri" => "test://hinted", + "mimeType" => "text/plain" + } + ) + end + + it "expires resource content using read ttlMs while exposing cache scope" do + allow(adapter).to receive(:resource_read).and_return( + RubyLLM::MCP::Result.new({ + "result" => { + "contents" => [{ "uri" => "test://hinted", "text" => "first" }], + "ttlMs" => 5, + "cacheScope" => "private" + } + }), + RubyLLM::MCP::Result.new({ + "result" => { + "contents" => [{ "uri" => "test://hinted", "text" => "second" }], + "ttlMs" => 5, + "cacheScope" => "private" + } + }) + ) + + expect(resource.content).to eq("first") + expect(resource.content).to eq("first") + expect(adapter).to have_received(:resource_read).once + expect(resource.cache_hint).to eq(ttl_ms: 5, cache_scope: "private") + + sleep 0.01 + expect(resource.content).to eq("second") + expect(adapter).to have_received(:resource_read).twice + end + + it "does not cache content when ttlMs is zero" do + allow(adapter).to receive(:resource_read).and_return( + RubyLLM::MCP::Result.new({ + "result" => { "contents" => [{ "uri" => "test://hinted", "text" => "value" }], + "ttlMs" => 0 } + }) + ) + + 2.times { expect(resource.content).to eq("value") } + expect(adapter).to have_received(:resource_read).twice + end +end diff --git a/spec/ruby_llm/mcp/sample_spec.rb b/spec/ruby_llm/mcp/sample_spec.rb index 8454179e..455738fb 100644 --- a/spec/ruby_llm/mcp/sample_spec.rb +++ b/spec/ruby_llm/mcp/sample_spec.rb @@ -46,7 +46,10 @@ expect(sample.message).to eq("Hello, how are you?\nI'm good, thank you!") end - each_client_supporting(:sampling) do |config| + # Native sampling exercises the full callback/model/VCR matrix here. The + # official SDK HTTP round trip has dedicated coverage without WebMock, + # whose Net::HTTP interception blocks the SDK's concurrent SSE listener. + each_client(adapter: :native) do |config| let(:client) { RubyLLM::MCP::Client.new(**config[:options], start: false) } after do diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 0c1f0873..343d849f 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -114,10 +114,12 @@ # human_in_the_loop, elicitation, subscriptions # - Transports: stdio, sse, streamable, streamable_http # -# 2. MCPSdkAdapter - Wrapper around the official MCP SDK gem -# - Supports: tools, prompts, resources, resource_templates, logging (basic features) -# - Transports: stdio, http, streamable, streamable_http -# - Requires: gem 'mcp', '~> 0.7' (optional - tests will skip if not installed) +# 2. MCPSdkAdapter - Official MCP SDK 0.25 integration +# - Supports: tools, prompts, resources, resource_templates, completions, +# pagination, structured output, and extension negotiation +# - HTTP additionally supports OAuth, sampling, and elicitation +# - Transports: official stdio and Streamable HTTP +# - Requires: gem 'mcp', '~> 0.25' (optional - tests skip if unavailable) # # Testing DSL: # Use `each_client` to run tests on all available adapters diff --git a/spec/support/adapter_test_helpers.rb b/spec/support/adapter_test_helpers.rb index 1c3c6838..2d4cfd6c 100644 --- a/spec/support/adapter_test_helpers.rb +++ b/spec/support/adapter_test_helpers.rb @@ -68,7 +68,8 @@ def each_client(adapter: :all, &block) def each_client_supporting(*features, &block) filtered_configs = CLIENT_OPTIONS.select do |config| adapter_class = get_adapter_class(config[:adapter]) - features.all? { |feature| adapter_class.support?(feature) } + transport = config.dig(:options, :transport_type) + features.all? { |feature| adapter_class.support?(feature, transport: transport) } end filtered_configs.each do |config| @@ -99,7 +100,8 @@ def clients_with_adapter(adapter) def clients_supporting(*features) CLIENT_OPTIONS.select do |config| adapter_class = get_adapter_class(config[:adapter]) - features.all? { |feature| adapter_class.support?(feature) } + transport = config.dig(:options, :transport_type) + features.all? { |feature| adapter_class.support?(feature, transport: transport) } end end @@ -110,7 +112,7 @@ def clients_supporting(*features) # @return [Boolean] Whether the client's adapter supports the feature def client_supports?(config, feature) adapter_class = get_adapter_class(config[:adapter]) - adapter_class.support?(feature) + adapter_class.support?(feature, transport: config.dig(:options, :transport_type)) end private diff --git a/spec/support/client_runner.rb b/spec/support/client_runner.rb index f135c167..767ab196 100644 --- a/spec/support/client_runner.rb +++ b/spec/support/client_runner.rb @@ -7,7 +7,7 @@ class << self def mcp_sdk_available? @mcp_sdk_available ||= begin require "mcp" - true + Gem::Version.new(MCP::VERSION) >= Gem::Version.new("0.25.0") rescue LoadError false end