modelcontextprotocol/ruby-sdk
MCP Ruby SDK
The official Ruby SDK for Model Context Protocol servers and clients.
Installation
Add this line to your application’s Gemfile:
|
|
And then execute:
|
|
Or install it yourself as:
|
|
MCP Server
The MCP::Server class is the core component that handles JSON-RPC requests and responses.
It implements the Model Context Protocol specification, handling model context requests and responses.
Key Features
- Implements JSON-RPC 2.0 message handling
- Supports protocol initialization and capability negotiation
- Manages tool registration and invocation
- Supports prompt registration and execution
- Supports resource registration and retrieval
Supported Methods
initialize- Initializes the protocol and returns server capabilitiesping- Simple health checktools/list- Lists all registered tools and their schemastools/call- Invokes a specific tool with provided argumentsprompts/list- Lists all registered prompts and their schemasprompts/get- Retrieves a specific prompt by nameresources/list- Lists all registered resources and their schemasresources/read- Retrieves a specific resource by nameresources/templates/list- Lists all registered resource templates and their schemas
Unsupported Features ( to be implemented in future versions )
- Notifications
- Log Level
- Resource subscriptions
- Completions
- Complete StreamableHTTP implementation with streaming responses
Usage
Rails Controller
When added to a Rails controller on a route that handles POST requests, your server will be compliant with non-streaming StreamableHTTP transport requests.
You can use the Server#handle_json method to handle requests.
|
|
Stdio Transport
If you want to build a local command-line application, you can use the stdio transport:
|
|
You can run this script and then type in requests to the server at the command line.
|
|
Configuration
The gem can be configured using the MCP.configure block:
|
|
or by creating an explicit configuration and passing it into the server. This is useful for systems where an application hosts more than one MCP server but they might require different instrumentation callbacks.
|
|
Server Context and Configuration Block Data
server_context
The server_context is a user-defined hash that is passed into the server instance and made available to tools, prompts, and exception/instrumentation callbacks. It can be used to provide contextual information such as authentication state, user IDs, or request-specific data.
Type:
|
|
Example:
|
|
This hash is then passed as the server_context argument to tool and prompt calls, and is included in exception and instrumentation callbacks.
Configuration Block Data
Exception Reporter
The exception reporter receives:
exception: The Ruby exception object that was raisedserver_context: The context hash provided to the server
Signature:
|
|
Instrumentation Callback
The instrumentation callback receives a hash with the following possible keys:
method: (String) The protocol method called (e.g., “ping”, “tools/list”)tool_name: (String, optional) The name of the tool calledprompt_name: (String, optional) The name of the prompt calledresource_uri: (String, optional) The URI of the resource callederror: (String, optional) Error code if a lookup failedduration: (Float) Duration of the call in seconds
Type:
|
|
Example:
|
|
Server Protocol Version
The server’s protocol version can be overridden using the protocol_version class method:
|
|
This will make all new server instances use the specified protocol version instead of the default version. The protocol version can be reset to the default by setting it to nil:
|
|
Be sure to check the MCP spec for the protocol version to understand the supported features for the version being set.
Exception Reporting
The exception reporter receives two arguments:
exception: The Ruby exception object that was raisedserver_context: A hash containing contextual information about where the error occurred
The server_context hash includes:
- For tool calls:
{ tool_name: "name", arguments: { ... } } - For general request handling:
{ request: { ... } }
When an exception occurs:
- The exception is reported via the configured reporter
- For tool calls, a generic error response is returned to the client:
{ error: "Internal error occurred", isError: true } - For other requests, the exception is re-raised after reporting
If no exception reporter is configured, a default no-op reporter is used that silently ignores exceptions.
Tools
MCP spec includes Tools which provide functionality to LLM apps.
This gem provides a MCP::Tool class that can be used to create tools in two ways:
- As a class definition:
|
|
- By using the
MCP::Tool.definemethod with a block:
|
|
The server_context parameter is the server_context passed into the server and can be used to pass per request information, e.g. around authentication state.
Tool Annotations
Tools can include annotations that provide additional metadata about their behavior. The following annotations are supported:
title: A human-readable title for the toolread_only_hint: Indicates if the tool only reads data (doesn’t modify state)destructive_hint: Indicates if the tool performs destructive operationsidempotent_hint: Indicates if the tool’s operations are idempotentopen_world_hint: Indicates if the tool operates in an open world context
Annotations can be set either through the class definition using the annotations class method or when defining a tool using the define method.
Prompts
MCP spec includes Prompts, which enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs.
The MCP::Prompt class provides two ways to create prompts:
- As a class definition with metadata:
|
|
- Using the
MCP::Prompt.definemethod:
|
|
The server_context parameter is the server_context passed into the server and can be used to pass per request information, e.g. around authentication state or user preferences.
Key Components
Prompt::Argument- Defines input parameters for the prompt templatePrompt::Message- Represents a message in the conversation with a role and contentPrompt::Result- The output of a prompt template containing description and messagesContent::Text- Text content for messages
Usage
Register prompts with the MCP server:
|
|
The server will handle prompt listing and execution through the MCP protocol methods:
prompts/list- Lists all registered prompts and their schemasprompts/get- Retrieves and executes a specific prompt with arguments
Instrumentation
The server allows registering a callback to receive information about instrumentation.
To register a handler pass a proc/lambda to as instrumentation_callback into the server constructor.
|
|
The data contains the following keys:
method: the metod called, e.g. ping, tools/list, tools/call etc
tool_name: the name of the tool called
prompt_name: the name of the prompt called
resource_uri: the uri of the resource called
error: if looking up tools/prompts etc failed, e.g. tool_not_found
duration: the duration of the call in seconds
tool_name, prompt_name and resource_uri are only populated if a matching handler is registered.
This is to avoid potential issues with metric cardinality
Resources
MCP spec includes Resources
The MCP::Resource class provides a way to register resources with the server.
|
|
The server must register a handler for the resources/read method to retrieve a resource dynamically.
|
|
otherwise ‘resources/read’ requests will be a no-op.
Releases
This gem is published to RubyGems.org
Releases are triggered by PRs to the main branch updating the version number in lib/mcp/version.rb.
- Update the version number in
lib/mcp/version.rb, following semver - Create A PR and get approval from a maintainer
- Merge your PR to the main branch - This will automatically trigger the release workflow via GitHub Actions
When changes are merged to the main branch, the GitHub Actions workflow (.github/workflows/release.yml) is triggered and the gem is published to RubyGems.