Merge pull request #24 from modelcontextprotocol/update-gemspec

Update gemspec to reflect `mcp` naming
This commit is contained in:
Topher Bullock 2025-05-29 17:45:45 -04:00 • committed by GitHub
commit 91219d30b7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
38 changed files with 156 additions and 145 deletions

View file

@ -1,23 +1,20 @@
---
description: writing changelog markdown when cutting a new release of the gem
globs:
globs:
alwaysApply: false
---
- output the changelog as markdown when asked.
- output the changelog as markdown when asked.
- git tags are used to mark the commit that cut a new release of the gem
- the gem version is located in [version.rb](mdc:lib/model_context_protocol/version.rb)
- the gem version is located in [version.rb](mdc:lib/mcp/version.rb)
- use the git history, especially merge commits from PRs to construct the changelog
- when necessary, look at the diff of files changed to determine whether a PR should be listed in
- when necessary, look at the diff of files changed to determine whether a PR should be listed in
- ## Added; adds new functionality
- ## Changed; alters functionality; especially backward compatible changes
- ## Fixed; bugfixes that are forward compatible
- ## Fixed; bugfixes that are forward compatible
use the following format for changelogs:
https://cloudsmith.io/~shopify/repos/gems/packages/detail/ruby/mcp-ruby/{gem version}/
# Changelog
```
## Added
- New functionality added that was not present before
@ -25,8 +22,9 @@ https://cloudsmith.io/~shopify/repos/gems/packages/detail/ruby/mcp-ruby/{gem ver
- Alterations to functionality that may indicate breaking changes
## Fixed
- Bug fixes
- Bug fixes
#### Full change list:
- [Name of the PR #123](mdc:https:/github.com/Shopify/mcp-ruby/pull/123) @github-author-username
- [Name of the PR #456](mdc:https:/github.com/Shopify/mcp-ruby/pull/456) @another-github-author
- [Name of the PR #123](https:/github.com/modelcontextprotocol/ruby-sdk/pull/123) @github-author-username
- [Name of the PR #456](https:/github.com/modelcontextprotocol/ruby-sdk/pull/456) @another-github-author
```

View file

@ -2,9 +2,29 @@
A Ruby gem for implementing Model Context Protocol servers
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'mcp'
```
And then execute:
```bash
$ bundle install
```
Or install it yourself as:
```bash
$ gem install mcp
```
## MCP Server
The `ModelContextProtocol::Server` class is the core component that handles JSON-RPC requests and responses.
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
@ -44,19 +64,17 @@ requests.
You can use the `Server#handle_json` method to handle requests.
```ruby
module ModelContextProtocol
class ApplicationController < ActionController::Base
class ApplicationController < ActionController::Base
def index
server = ModelContextProtocol::Server.new(
name: "my_server",
version: "1.0.0",
tools: [SomeTool, AnotherTool],
prompts: [MyPrompt],
server_context: { user_id: current_user.id },
)
render(json: server.handle_json(request.body.read).to_h)
end
def index
server = MCP::Server.new(
name: "my_server",
version: "1.0.0",
tools: [SomeTool, AnotherTool],
prompts: [MyPrompt],
server_context: { user_id: current_user.id },
)
render(json: server.handle_json(request.body.read))
end
end
```
@ -67,11 +85,11 @@ If you want to build a local command-line application, you can use the stdio tra
```ruby
#!/usr/bin/env ruby
require "model_context_protocol"
require "model_context_protocol/transports/stdio"
require "mcp"
require "mcp/transports/stdio"
# Create a simple tool
class ExampleTool < ModelContextProtocol::Tool
class ExampleTool < MCP::Tool
description "A simple example tool that echoes back its arguments"
input_schema(
properties: {
@ -82,7 +100,7 @@ class ExampleTool < ModelContextProtocol::Tool
class << self
def call(message:, server_context:)
ModelContextProtocol::Tool::Response.new([{
MCP::Tool::Response.new([{
type: "text",
text: "Hello from example tool! Message: #{message}",
}])
@ -91,13 +109,13 @@ class ExampleTool < ModelContextProtocol::Tool
end
# Set up the server
server = ModelContextProtocol::Server.new(
server = MCP::Server.new(
name: "example_server",
tools: [ExampleTool],
)
# Create and start the transport
transport = ModelContextProtocol::Transports::StdioTransport.new(server)
transport = MCP::Transports::StdioTransport.new(server)
transport.open
```
@ -112,10 +130,10 @@ $ ./stdio_server.rb
## Configuration
The gem can be configured using the `ModelContextProtocol.configure` block:
The gem can be configured using the `MCP.configure` block:
```ruby
ModelContextProtocol.configure do |config|
MCP.configure do |config|
config.exception_reporter = ->(exception, server_context) {
# Your exception reporting logic here
# For example with Bugsnag:
@ -135,7 +153,7 @@ This is useful for systems where an application hosts more than one MCP server b
they might require different instrumentation callbacks.
```ruby
configuration = ModelContextProtocol::Configuration.new
configuration = MCP::Configuration.new
configuration.exception_reporter = ->(exception, server_context) {
# Your exception reporting logic here
# For example with Bugsnag:
@ -148,7 +166,7 @@ configuration.instrumentation_callback = ->(data) {
puts "Got instrumentation data #{data.inspect}"
}
server = ModelContextProtocol::Server.new(
server = MCP::Server.new(
# ... all other options
configuration:,
)
@ -167,7 +185,7 @@ server_context: { [String, Symbol] => Any }
**Example:**
```ruby
server = ModelContextProtocol::Server.new(
server = MCP::Server.new(
name: "my_server",
server_context: { user_id: current_user.id, request_id: request.uuid }
)
@ -218,13 +236,13 @@ config.instrumentation_callback = ->(data) {
The server's protocol version can be overridden using the `protocol_version` class method:
```ruby
ModelContextProtocol::Server.protocol_version = "2024-11-05"
MCP::Server.protocol_version = "2024-11-05"
```
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`:
```ruby
ModelContextProtocol::Server.protocol_version = nil
MCP::Server.protocol_version = nil
```
Be sure to check the [MCP spec](https://spec.modelcontextprotocol.io/specification/2024-11-05/) for the protocol version to understand the supported features for the version being set.
@ -253,12 +271,12 @@ If no exception reporter is configured, a default no-op reporter is used that si
MCP spec includes [Tools](https://modelcontextprotocol.io/docs/concepts/tools) which provide functionality to LLM apps.
This gem provides a `ModelContextProtocol::Tool` class that can be used to create tools in two ways:
This gem provides a `MCP::Tool` class that can be used to create tools in two ways:
1. As a class definition:
```ruby
class MyTool < ModelContextProtocol::Tool
class MyTool < MCP::Tool
description "This tool performs specific functionality..."
input_schema(
properties: {
@ -275,17 +293,17 @@ class MyTool < ModelContextProtocol::Tool
)
def self.call(message:, server_context:)
Tool::Response.new([{ type: "text", text: "OK" }])
MCP::Tool::Response.new([{ type: "text", text: "OK" }])
end
end
tool = MyTool
```
2. By using the `ModelContextProtocol::Tool.define` method with a block:
2. By using the `MCP::Tool.define` method with a block:
```ruby
tool = ModelContextProtocol::Tool.define(
tool = MCP::Tool.define(
name: "my_tool",
description: "This tool performs specific functionality...",
annotations: {
@ -316,12 +334,12 @@ Annotations can be set either through the class definition using the `annotation
MCP spec includes [Prompts](https://modelcontextprotocol.io/docs/concepts/prompts), which enable servers to define reusable prompt templates and workflows that clients can easily surface to users and LLMs.
The `ModelContextProtocol::Prompt` class provides two ways to create prompts:
The `MCP::Prompt` class provides two ways to create prompts:
1. As a class definition with metadata:
```ruby
class MyPrompt < ModelContextProtocol::Prompt
class MyPrompt < MCP::Prompt
prompt_name "my_prompt" # Optional - defaults to underscored class name
description "This prompt performs specific functionality..."
arguments [
@ -354,10 +372,10 @@ end
prompt = MyPrompt
```
2. Using the `ModelContextProtocol::Prompt.define` method:
2. Using the `MCP::Prompt.define` method:
```ruby
prompt = ModelContextProtocol::Prompt.define(
prompt = MCP::Prompt.define(
name: "my_prompt",
description: "This prompt performs specific functionality...",
arguments: [
@ -399,7 +417,7 @@ e.g. around authentication state or user preferences.
Register prompts with the MCP server:
```ruby
server = ModelContextProtocol::Server.new(
server = MCP::Server.new(
name: "my_server",
prompts: [MyPrompt],
server_context: { user_id: current_user.id },
@ -417,7 +435,7 @@ The server allows registering a callback to receive information about instrument
To register a handler pass a proc/lambda to as `instrumentation_callback` into the server constructor.
```ruby
ModelContextProtocol.configure do |config|
MCP.configure do |config|
config.instrumentation_callback = ->(data) {
puts "Got instrumentation data #{data.inspect}"
end
@ -439,16 +457,16 @@ This is to avoid potential issues with metric cardinality
MCP spec includes [Resources](https://modelcontextprotocol.io/docs/concepts/resources)
The `ModelContextProtocol::Resource` class provides a way to register resources with the server.
The `MCP::Resource` class provides a way to register resources with the server.
```ruby
resource = ModelContextProtocol::Resource.new(
resource = MCP::Resource.new(
uri: "example.com/my_resource",
mime_type: "text/plain",
text: "Lorem ipsum dolor sit amet"
)
server = ModelContextProtocol::Server.new(
server = MCP::Server.new(
name: "my_server",
resources: [resource],
)

View file

@ -2,8 +2,8 @@
# frozen_string_literal: true
$LOAD_PATH.unshift(File.expand_path("../lib", __dir__))
require "model_context_protocol"
require "model_context_protocol/transports/stdio"
require "mcp"
require "mcp/transports/stdio"
# Create a simple tool
class ExampleTool < MCP::Tool

View file

@ -1,3 +0,0 @@
# frozen_string_literal: true
require_relative "model_context_protocol"

41
lib/mcp.rb Normal file
View file

@ -0,0 +1,41 @@
# frozen_string_literal: true
require_relative "mcp/server"
require_relative "mcp/string_utils"
require_relative "mcp/tool"
require_relative "mcp/tool/input_schema"
require_relative "mcp/tool/annotations"
require_relative "mcp/tool/response"
require_relative "mcp/content"
require_relative "mcp/resource"
require_relative "mcp/resource/contents"
require_relative "mcp/resource/embedded"
require_relative "mcp/resource_template"
require_relative "mcp/prompt"
require_relative "mcp/prompt/argument"
require_relative "mcp/prompt/message"
require_relative "mcp/prompt/result"
require_relative "mcp/version"
require_relative "mcp/configuration"
require_relative "mcp/methods"
module MCP
class << self
def configure
yield(configuration)
end
def configuration
@configuration ||= Configuration.new
end
end
class Annotations
attr_reader :audience, :priority
def initialize(audience: nil, priority: nil)
@audience = audience
@priority = priority
end
end
end

75
lib/mcp/configuration.rb Normal file
View file

@ -0,0 +1,75 @@
# frozen_string_literal: true
module MCP
class Configuration
DEFAULT_PROTOCOL_VERSION = "2024-11-05"
attr_writer :exception_reporter, :instrumentation_callback, :protocol_version
def initialize(exception_reporter: nil, instrumentation_callback: nil, protocol_version: nil)
@exception_reporter = exception_reporter
@instrumentation_callback = instrumentation_callback
@protocol_version = protocol_version
end
def protocol_version
@protocol_version || DEFAULT_PROTOCOL_VERSION
end
def protocol_version?
!@protocol_version.nil?
end
def exception_reporter
@exception_reporter || default_exception_reporter
end
def exception_reporter?
!@exception_reporter.nil?
end
def instrumentation_callback
@instrumentation_callback || default_instrumentation_callback
end
def instrumentation_callback?
!@instrumentation_callback.nil?
end
def merge(other)
return self if other.nil?
exception_reporter = if other.exception_reporter?
other.exception_reporter
else
@exception_reporter
end
instrumentation_callback = if other.instrumentation_callback?
other.instrumentation_callback
else
@instrumentation_callback
end
protocol_version = if other.protocol_version?
other.protocol_version
else
@protocol_version
end
Configuration.new(
exception_reporter:,
instrumentation_callback:,
protocol_version:,
)
end
private
def default_exception_reporter
@default_exception_reporter ||= ->(exception, server_context) {}
end
def default_instrumentation_callback
@default_instrumentation_callback ||= ->(data) {}
end
end
end

33
lib/mcp/content.rb Normal file
View file

@ -0,0 +1,33 @@
# typed: true
# frozen_string_literal: true
module MCP
module Content
class Text
attr_reader :text, :annotations
def initialize(text, annotations: nil)
@text = text
@annotations = annotations
end
def to_h
{ text:, annotations:, type: "text" }.compact
end
end
class Image
attr_reader :data, :mime_type, :annotations
def initialize(data, mime_type, annotations: nil)
@data = data
@mime_type = mime_type
@annotations = annotations
end
def to_h
{ data:, mime_type:, annotations:, type: "image" }.compact
end
end
end
end

View file

@ -0,0 +1,26 @@
# frozen_string_literal: true
module MCP
module Instrumentation
def instrument_call(method, &block)
start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
begin
@instrumentation_data = {}
add_instrumentation_data(method:)
result = yield block
result
ensure
end_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
add_instrumentation_data(duration: end_time - start_time)
configuration.instrumentation_callback.call(@instrumentation_data)
end
end
def add_instrumentation_data(**kwargs)
@instrumentation_data.merge!(kwargs)
end
end
end

73
lib/mcp/methods.rb Normal file
View file

@ -0,0 +1,73 @@
# frozen_string_literal: true
module MCP
module Methods
INITIALIZE = "initialize"
PING = "ping"
LOGGING_SET_LEVEL = "logging/setLevel"
PROMPTS_GET = "prompts/get"
PROMPTS_LIST = "prompts/list"
COMPLETION_COMPLETE = "completion/complete"
RESOURCES_LIST = "resources/list"
RESOURCES_READ = "resources/read"
RESOURCES_TEMPLATES_LIST = "resources/templates/list"
RESOURCES_SUBSCRIBE = "resources/subscribe"
RESOURCES_UNSUBSCRIBE = "resources/unsubscribe"
TOOLS_CALL = "tools/call"
TOOLS_LIST = "tools/list"
SAMPLING_CREATE_MESSAGE = "sampling/createMessage"
class MissingRequiredCapabilityError < StandardError
attr_reader :method
attr_reader :capability
def initialize(method, capability)
super("Server does not support #{capability} (required for #{method})")
@method = method
@capability = capability
end
end
extend self
def ensure_capability!(method, capabilities)
case method
when PROMPTS_GET, PROMPTS_LIST
unless capabilities[:prompts]
raise MissingRequiredCapabilityError.new(method, :prompts)
end
when RESOURCES_LIST, RESOURCES_TEMPLATES_LIST, RESOURCES_READ, RESOURCES_SUBSCRIBE, RESOURCES_UNSUBSCRIBE
unless capabilities[:resources]
raise MissingRequiredCapabilityError.new(method, :resources)
end
if method == RESOURCES_SUBSCRIBE && !capabilities[:resources][:subscribe]
raise MissingRequiredCapabilityError.new(method, :resources_subscribe)
end
when TOOLS_CALL, TOOLS_LIST
unless capabilities[:tools]
raise MissingRequiredCapabilityError.new(method, :tools)
end
when SAMPLING_CREATE_MESSAGE
unless capabilities[:sampling]
raise MissingRequiredCapabilityError.new(method, :sampling)
end
when COMPLETION_COMPLETE
unless capabilities[:completions]
raise MissingRequiredCapabilityError.new(method, :completions)
end
when LOGGING_SET_LEVEL
# Logging is unsupported by the Server
unless capabilities[:logging]
raise MissingRequiredCapabilityError.new(method, :logging)
end
when INITIALIZE, PING
# No specific capability required for initialize or ping
end
end
end
end

82
lib/mcp/prompt.rb Normal file
View file

@ -0,0 +1,82 @@
# typed: strict
# frozen_string_literal: true
module MCP
class Prompt
class << self
NOT_SET = Object.new
attr_reader :description_value
attr_reader :arguments_value
def template(args, server_context:)
raise NotImplementedError, "Subclasses must implement template"
end
def to_h
{ name: name_value, description: description_value, arguments: arguments_value.map(&:to_h) }.compact
end
def inherited(subclass)
super
subclass.instance_variable_set(:@name_value, nil)
subclass.instance_variable_set(:@description_value, nil)
subclass.instance_variable_set(:@arguments_value, nil)
end
def prompt_name(value = NOT_SET)
if value == NOT_SET
@name_value
else
@name_value = value
end
end
def name_value
@name_value || StringUtils.handle_from_class_name(name)
end
def description(value = NOT_SET)
if value == NOT_SET
@description_value
else
@description_value = value
end
end
def arguments(value = NOT_SET)
if value == NOT_SET
@arguments_value
else
@arguments_value = value
end
end
def define(name: nil, description: nil, arguments: [], &block)
Class.new(self) do
prompt_name name
description description
arguments arguments
define_singleton_method(:template) do |args, server_context:|
instance_exec(args, server_context:, &block)
end
end
end
def validate_arguments!(args)
missing = required_args - args.keys
return if missing.empty?
raise MCP::Server::RequestHandlerError.new(
"Missing required arguments: #{missing.join(", ")}", nil, error_type: :missing_required_arguments
)
end
private
def required_args
arguments_value.filter_map { |arg| arg.name.to_sym if arg.required }
end
end
end
end

View file

@ -0,0 +1,21 @@
# typed: strict
# frozen_string_literal: true
module MCP
class Prompt
class Argument
attr_reader :name, :description, :required, :arguments
def initialize(name:, description: nil, required: false)
@name = name
@description = description
@required = required
@arguments = arguments
end
def to_h
{ name:, description:, required: }.compact
end
end
end
end

19
lib/mcp/prompt/message.rb Normal file
View file

@ -0,0 +1,19 @@
# typed: strict
# frozen_string_literal: true
module MCP
class Prompt
class Message
attr_reader :role, :content
def initialize(role:, content:)
@role = role
@content = content
end
def to_h
{ role:, content: content.to_h }.compact
end
end
end
end

19
lib/mcp/prompt/result.rb Normal file
View file

@ -0,0 +1,19 @@
# typed: strict
# frozen_string_literal: true
module MCP
class Prompt
class Result
attr_reader :description, :messages
def initialize(description: nil, messages: [])
@description = description
@messages = messages
end
def to_h
{ description:, messages: messages.map(&:to_h) }.compact
end
end
end
end

24
lib/mcp/resource.rb Normal file
View file

@ -0,0 +1,24 @@
# typed: strict
# frozen_string_literal: true
module MCP
class Resource
attr_reader :uri, :name, :description, :mime_type
def initialize(uri:, name:, description:, mime_type:)
@uri = uri
@name = name
@description = description
@mime_type = mime_type
end
def to_h
{
uri: @uri,
name: @name,
description: @description,
mimeType: @mime_type,
}
end
end
end

View file

@ -0,0 +1,45 @@
# typed: strict
# frozen_string_literal: true
module MCP
class Resource
class Contents
attr_reader :uri, :mime_type
def initialize(uri:, mime_type: nil)
@uri = uri
@mime_type = mime_type
end
def to_h
{ uri:, mime_type: }.compact
end
end
class TextContents < Contents
attr_reader :text
def initialize(text:, uri:, mime_type:)
super(uri: uri, mime_type: mime_type)
@text = text
end
def to_h
super.merge(text: text)
end
end
class BlobContents < Contents
attr_reader :data
def initialize(data:, uri:, mime_type:)
super(uri: uri, mime_type: mime_type)
@data = data
end
def to_h
super.merge(data: data)
end
end
end
end

View file

@ -0,0 +1,18 @@
# typed: strict
# frozen_string_literal: true
module MCP
class Resource
class Embedded
attr_reader :resource, :annotations
def initialize(resource:, annotations: nil)
@annotations = annotations
end
def to_h
{ resource: resource.to_h, annotations: }.compact
end
end
end
end

View file

@ -0,0 +1,24 @@
# typed: strict
# frozen_string_literal: true
module MCP
class ResourceTemplate
attr_reader :uri_template, :name, :description, :mime_type
def initialize(uri_template:, name:, description: nil, mime_type: nil)
@uri_template = uri_template
@name = name
@description = description
@mime_type = mime_type
end
def to_h
{
uriTemplate: @uri_template,
name: @name,
description: @description,
mimeType: @mime_type,
}.compact
end
end
end

299
lib/mcp/server.rb Normal file
View file

@ -0,0 +1,299 @@
# frozen_string_literal: true
require "json_rpc_handler"
require_relative "instrumentation"
require_relative "methods"
module MCP
class Server
DEFAULT_VERSION = "0.1.0"
class RequestHandlerError < StandardError
attr_reader :error_type
attr_reader :original_error
def initialize(message, request, error_type: :internal_error, original_error: nil)
super(message)
@request = request
@error_type = error_type
@original_error = original_error
end
end
include Instrumentation
attr_writer :capabilities
attr_accessor :name, :version, :tools, :prompts, :resources, :server_context, :configuration
def initialize(
name: "model_context_protocol",
version: DEFAULT_VERSION,
tools: [],
prompts: [],
resources: [],
resource_templates: [],
server_context: nil,
configuration: nil,
capabilities: nil
)
@name = name
@version = version
@tools = tools.to_h { |t| [t.name_value, t] }
@prompts = prompts.to_h { |p| [p.name_value, p] }
@resources = resources
@resource_templates = resource_templates
@resource_index = index_resources_by_uri(resources)
@server_context = server_context
@configuration = MCP.configuration.merge(configuration)
@handlers = {
Methods::RESOURCES_LIST => method(:list_resources),
Methods::RESOURCES_READ => method(:read_resource_no_content),
Methods::RESOURCES_TEMPLATES_LIST => method(:list_resource_templates),
Methods::TOOLS_LIST => method(:list_tools),
Methods::TOOLS_CALL => method(:call_tool),
Methods::PROMPTS_LIST => method(:list_prompts),
Methods::PROMPTS_GET => method(:get_prompt),
Methods::INITIALIZE => method(:init),
Methods::PING => ->(_) { {} },
# No op handlers for currently unsupported methods
Methods::RESOURCES_SUBSCRIBE => ->(_) {},
Methods::RESOURCES_UNSUBSCRIBE => ->(_) {},
Methods::COMPLETION_COMPLETE => ->(_) {},
Methods::LOGGING_SET_LEVEL => ->(_) {},
}
end
def capabilities
@capabilities ||= determine_capabilities
end
def handle(request)
JsonRpcHandler.handle(request) do |method|
handle_request(request, method)
end
end
def handle_json(request)
JsonRpcHandler.handle_json(request) do |method|
handle_request(request, method)
end
end
def define_tool(name: nil, description: nil, input_schema: nil, annotations: nil, &block)
tool = Tool.define(name:, description:, input_schema:, annotations:, &block)
@tools[tool.name_value] = tool
end
def define_prompt(name: nil, description: nil, arguments: [], &block)
prompt = Prompt.define(name:, description:, arguments:, &block)
@prompts[prompt.name_value] = prompt
end
def resources_list_handler(&block)
@handlers[Methods::RESOURCES_LIST] = block
end
def resources_read_handler(&block)
@handlers[Methods::RESOURCES_READ] = block
end
def resources_templates_list_handler(&block)
@handlers[Methods::RESOURCES_TEMPLATES_LIST] = block
end
def tools_list_handler(&block)
@handlers[Methods::TOOLS_LIST] = block
end
def tools_call_handler(&block)
@handlers[Methods::TOOLS_CALL] = block
end
def prompts_list_handler(&block)
@handlers[Methods::PROMPTS_LIST] = block
end
def prompts_get_handler(&block)
@handlers[Methods::PROMPTS_GET] = block
end
private
def handle_request(request, method)
handler = @handlers[method]
unless handler
instrument_call("unsupported_method") {}
return
end
Methods.ensure_capability!(method, capabilities)
->(params) {
instrument_call(method) do
case method
when Methods::TOOLS_LIST
{ tools: @handlers[Methods::TOOLS_LIST].call(params) }
when Methods::PROMPTS_LIST
{ prompts: @handlers[Methods::PROMPTS_LIST].call(params) }
when Methods::RESOURCES_LIST
{ resources: @handlers[Methods::RESOURCES_LIST].call(params) }
when Methods::RESOURCES_READ
{ contents: @handlers[Methods::RESOURCES_READ].call(params) }
when Methods::RESOURCES_TEMPLATES_LIST
{ resourceTemplates: @handlers[Methods::RESOURCES_TEMPLATES_LIST].call(params) }
else
@handlers[method].call(params)
end
rescue => e
report_exception(e, { request: request })
if e.is_a?(RequestHandlerError)
add_instrumentation_data(error: e.error_type)
raise e
end
add_instrumentation_data(error: :internal_error)
raise RequestHandlerError.new("Internal error handling #{method} request", request, original_error: e)
end
}
end
def determine_capabilities
defines_prompts = @prompts.any? || @handlers[Methods::PROMPTS_LIST] != method(:list_prompts)
defines_tools = @tools.any? || @handlers[Methods::TOOLS_LIST] != method(:list_tools)
defines_resources = @resources.any? || @handlers[Methods::RESOURCES_LIST] != method(:list_resources)
defines_resource_templates = @resource_templates.any? || @handlers[Methods::RESOURCES_TEMPLATES_LIST] != method(:list_resource_templates)
{
prompts: defines_prompts ? {} : nil,
resources: defines_resources || defines_resource_templates ? {} : nil,
tools: defines_tools ? {} : nil,
}.compact
end
def server_info
@server_info ||= {
name:,
version:,
}
end
def init(request)
add_instrumentation_data(method: Methods::INITIALIZE)
{
protocolVersion: configuration.protocol_version,
capabilities: capabilities,
serverInfo: server_info,
}
end
def list_tools(request)
add_instrumentation_data(method: Methods::TOOLS_LIST)
@tools.map { |_, tool| tool.to_h }
end
def call_tool(request)
add_instrumentation_data(method: Methods::TOOLS_CALL)
tool_name = request[:name]
tool = tools[tool_name]
unless tool
add_instrumentation_data(error: :tool_not_found)
raise RequestHandlerError.new("Tool not found #{tool_name}", request, error_type: :tool_not_found)
end
arguments = request[:arguments]
add_instrumentation_data(tool_name:)
if tool.input_schema&.missing_required_arguments?(arguments)
add_instrumentation_data(error: :missing_required_arguments)
raise RequestHandlerError.new(
"Missing required arguments: #{tool.input_schema.missing_required_arguments(arguments).join(", ")}",
request,
error_type: :missing_required_arguments,
)
end
begin
call_params = tool_call_parameters(tool)
if call_params.include?(:server_context)
tool.call(**arguments.transform_keys(&:to_sym), server_context:).to_h
else
tool.call(**arguments.transform_keys(&:to_sym)).to_h
end
rescue => e
raise RequestHandlerError.new("Internal error calling tool #{tool_name}", request, original_error: e)
end
end
def list_prompts(request)
add_instrumentation_data(method: Methods::PROMPTS_LIST)
@prompts.map { |_, prompt| prompt.to_h }
end
def get_prompt(request)
add_instrumentation_data(method: Methods::PROMPTS_GET)
prompt_name = request[:name]
prompt = @prompts[prompt_name]
unless prompt
add_instrumentation_data(error: :prompt_not_found)
raise RequestHandlerError.new("Prompt not found #{prompt_name}", request, error_type: :prompt_not_found)
end
add_instrumentation_data(prompt_name:)
prompt_args = request[:arguments]
prompt.validate_arguments!(prompt_args)
prompt.template(prompt_args, server_context:).to_h
end
def list_resources(request)
add_instrumentation_data(method: Methods::RESOURCES_LIST)
@resources.map(&:to_h)
end
# Server implementation should set `resources_read_handler` to override no-op default
def read_resource_no_content(request)
add_instrumentation_data(method: Methods::RESOURCES_READ)
add_instrumentation_data(resource_uri: request[:uri])
[]
end
def list_resource_templates(request)
add_instrumentation_data(method: Methods::RESOURCES_TEMPLATES_LIST)
@resource_templates.map(&:to_h)
end
def report_exception(exception, server_context = {})
configuration.exception_reporter.call(exception, server_context)
end
def index_resources_by_uri(resources)
resources.each_with_object({}) do |resource, hash|
hash[resource.uri] = resource
end
end
def tool_call_parameters(tool)
method_def = tool_call_method_def(tool)
method_def.parameters.flatten
end
def tool_call_method_def(tool)
method = tool.method(:call)
if defined?(T::Utils) && T::Utils.respond_to?(:signature_for_method)
sorbet_typed_method_definition = T::Utils.signature_for_method(method)&.method
# Return the Sorbet typed method definition if it exists, otherwise fallback to original method
# definition if Sorbet is defined but not used by this tool.
sorbet_typed_method_definition || method
else
method
end
end
end
end

26
lib/mcp/string_utils.rb Normal file
View file

@ -0,0 +1,26 @@
# typed: strict
# frozen_string_literal: true
module MCP
module StringUtils
extend self
def handle_from_class_name(class_name)
underscore(demodulize(class_name))
end
private
def demodulize(path)
path.to_s.split("::").last || path.to_s
end
def underscore(camel_cased_word)
camel_cased_word.dup
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.tr("-", "_")
.downcase
end
end
end

85
lib/mcp/tool.rb Normal file
View file

@ -0,0 +1,85 @@
# frozen_string_literal: true
module MCP
class Tool
class << self
NOT_SET = Object.new
attr_reader :description_value
attr_reader :input_schema_value
attr_reader :annotations_value
def call(*args, server_context:)
raise NotImplementedError, "Subclasses must implement call"
end
def to_h
result = {
name: name_value,
description: description_value,
inputSchema: input_schema_value.to_h,
}
result[:annotations] = annotations_value.to_h if annotations_value
result
end
def inherited(subclass)
super
subclass.instance_variable_set(:@name_value, nil)
subclass.instance_variable_set(:@description_value, nil)
subclass.instance_variable_set(:@input_schema_value, nil)
subclass.instance_variable_set(:@annotations_value, nil)
end
def tool_name(value = NOT_SET)
if value == NOT_SET
name_value
else
@name_value = value
end
end
def name_value
@name_value || StringUtils.handle_from_class_name(name)
end
def description(value = NOT_SET)
if value == NOT_SET
@description_value
else
@description_value = value
end
end
def input_schema(value = NOT_SET)
if value == NOT_SET
input_schema_value
elsif value.is_a?(Hash)
properties = value[:properties] || value["properties"] || {}
required = value[:required] || value["required"] || []
@input_schema_value = InputSchema.new(properties:, required:)
elsif value.is_a?(InputSchema)
@input_schema_value = value
end
end
def annotations(hash = NOT_SET)
if hash == NOT_SET
@annotations_value
else
@annotations_value = Annotations.new(**hash)
end
end
def define(name: nil, description: nil, input_schema: nil, annotations: nil, &block)
Class.new(self) do
tool_name name
description description
input_schema input_schema
self.annotations(annotations) if annotations
define_singleton_method(:call, &block) if block
end
end
end
end
end

Some files were not shown because too many files have changed in this diff Show more