Rename test directory from model_context_protocol to mcp

Follow-up to #24.

The directory structure of the product code and test code is expected to match.
This commit is contained in:
Koichi ITO 2025-06-01 02:09:26 +09:00
commit f33fe309b4
9 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,65 @@
# frozen_string_literal: true
require "test_helper"
module MCP
class ConfigurationTest < ActiveSupport::TestCase
test "initializes with a default no-op exception reporter" do
config = Configuration.new
assert_respond_to config, :exception_reporter
# The default reporter should be callable but do nothing
exception = StandardError.new("test error")
server_context = { test: "context" }
# Should not raise any errors
config.exception_reporter.call(exception, server_context)
end
test "allows setting a custom exception reporter" do
config = Configuration.new
reported_exception = nil
reported_context = nil
config.exception_reporter = ->(exception, server_context) do
reported_exception = exception
reported_context = server_context
end
test_exception = StandardError.new("test error")
test_context = { foo: "bar" }
config.exception_reporter.call(test_exception, test_context)
assert_equal test_exception, reported_exception
assert_equal test_context, reported_context
end
test "initializes with default protocol version" do
config = Configuration.new
assert_equal Configuration::DEFAULT_PROTOCOL_VERSION, config.protocol_version
end
test "allows setting a custom protocol version" do
config = Configuration.new
custom_version = "2025-03-27"
config.protocol_version = custom_version
assert_equal custom_version, config.protocol_version
end
test "merges protocol version from other configuration" do
config1 = Configuration.new(protocol_version: "2025-03-27")
config2 = Configuration.new(protocol_version: "2025-03-28")
config3 = Configuration.new
merged = config1.merge(config2)
assert_equal "2025-03-28", merged.protocol_version
merged = config1.merge(config3)
assert_equal "2025-03-27", merged.protocol_version
merged = config3.merge(config1)
assert_equal "2025-03-27", merged.protocol_version
end
end
end

View file

@ -0,0 +1,63 @@
# frozen_string_literal: true
require "test_helper"
module MCP
class InstrumentationTest < ActiveSupport::TestCase
class Subject
include Instrumentation
attr_reader :instrumentation_data_received, :configuration
def initialize
@configuration = MCP::Configuration.new
@configuration.instrumentation_callback = ->(data) { @instrumentation_data_received = data }
end
def instrumented_method
instrument_call("instrumented_method") do
# nothing to do
end
end
def instrumented_method_with_additional_data
instrument_call("instrumented_method_with_additional_data") do
add_instrumentation_data(additional_data: "test")
end
end
end
test "#instrument_call adds the method name to the instrumentation data" do
subject = Subject.new
subject.instrumented_method
assert_equal({ method: "instrumented_method" }, subject.instrumentation_data_received.tap do |data|
data.delete(:duration)
end)
end
test "#instrument_call exposes data added via add_instrumentation_data" do
subject = Subject.new
subject.instrumented_method_with_additional_data
assert_equal(
{ method: "instrumented_method_with_additional_data", additional_data: "test" },
subject.instrumentation_data_received.tap { |data| data.delete(:duration) },
)
end
test "#instrument_call resets the instrumentation data between calls" do
subject = Subject.new
subject.instrumented_method_with_additional_data
assert_equal(
{ method: "instrumented_method_with_additional_data", additional_data: "test" },
subject.instrumentation_data_received.tap { |data| data.delete(:duration) },
)
subject.instrumented_method
assert_equal({ method: "instrumented_method" }, subject.instrumentation_data_received.tap do |data|
data.delete(:duration)
end)
end
end
end

75
test/mcp/methods_test.rb Normal file
View file

@ -0,0 +1,75 @@
# typed: strict
# frozen_string_literal: true
require "test_helper"
module MCP
class MethodsTest < ActiveSupport::TestCase
test "ensure_capability! for tools/list method raises an error if tools capability is not present" do
error = assert_raises(Methods::MissingRequiredCapabilityError) do
Methods.ensure_capability!(Methods::TOOLS_LIST, {})
end
assert_equal "Server does not support tools (required for tools/list)", error.message
end
test "ensure_capability! for sampling/createMessage raises an error if sampling capability is not present" do
error = assert_raises(Methods::MissingRequiredCapabilityError) do
Methods.ensure_capability!(Methods::SAMPLING_CREATE_MESSAGE, {})
end
assert_equal "Server does not support sampling (required for sampling/createMessage)", error.message
end
test "ensure_capability! for completion/complete raises an error if completions capability is not present" do
error = assert_raises(Methods::MissingRequiredCapabilityError) do
Methods.ensure_capability!(Methods::COMPLETION_COMPLETE, {})
end
assert_equal "Server does not support completions (required for completion/complete)", error.message
end
test "ensure_capability! for logging/setLevel raises an error if logging capability is not present" do
error = assert_raises(Methods::MissingRequiredCapabilityError) do
Methods.ensure_capability!(Methods::LOGGING_SET_LEVEL, {})
end
assert_equal "Server does not support logging (required for logging/setLevel)", error.message
end
test "ensure_capability! for prompts/get and prompts/list raise an error if prompts capability is not present" do
[Methods::PROMPTS_GET, Methods::PROMPTS_LIST].each do |method|
error = assert_raises(Methods::MissingRequiredCapabilityError) do
Methods.ensure_capability!(method, {})
end
assert_equal "Server does not support prompts (required for #{method})", error.message
end
end
test "ensure_capability! for resources/list, resources/templates/list, resources/read raise an error if resources capability is not present" do
[Methods::RESOURCES_LIST, Methods::RESOURCES_TEMPLATES_LIST, Methods::RESOURCES_READ].each do |method|
error = assert_raises(Methods::MissingRequiredCapabilityError) do
Methods.ensure_capability!(method, {})
end
assert_equal "Server does not support resources (required for #{method})", error.message
end
end
test "ensure_capability! for tools/call and tools/list raise an error if tools capability is not present" do
[Methods::TOOLS_CALL, Methods::TOOLS_LIST].each do |method|
error = assert_raises(Methods::MissingRequiredCapabilityError) do
Methods.ensure_capability!(method, {})
end
assert_equal "Server does not support tools (required for #{method})", error.message
end
end
test "ensure_capability! for resources/subscribe raises an error if resources subscribe capability is not present" do
error = assert_raises(Methods::MissingRequiredCapabilityError) do
Methods.ensure_capability!(Methods::RESOURCES_SUBSCRIBE, { resources: {} })
end
assert_equal "Server does not support resources_subscribe (required for resources/subscribe)", error.message
end
test "ensure_capability! does not raise for ping and initialize methods" do
assert_nothing_raised { Methods.ensure_capability!(Methods::PING, {}) }
assert_nothing_raised { Methods.ensure_capability!(Methods::INITIALIZE, {}) }
end
end
end

146
test/mcp/prompt_test.rb Normal file
View file

@ -0,0 +1,146 @@
# typed: strict
# frozen_string_literal: true
require "test_helper"
module MCP
class PromptTest < ActiveSupport::TestCase
class TestPrompt < Prompt
description "Test prompt"
arguments [
Prompt::Argument.new(name: "test_argument", description: "Test argument", required: true),
]
class << self
def template(args, server_context:)
Prompt::Result.new(
description: "Hello, world!",
messages: [
Prompt::Message.new(role: "user", content: Content::Text.new("Hello, world!")),
Prompt::Message.new(role: "assistant", content: Content::Text.new("Hello, friend!")),
],
)
end
end
end
test "#template returns a Result with description and messages" do
prompt = TestPrompt
expected_template_result = {
description: "Hello, world!",
messages: [
{ role: "user", content: { text: "Hello, world!", type: "text" } },
{ role: "assistant", content: { text: "Hello, friend!", type: "text" } },
],
}
result = prompt.template({ "test_argument" => "Hello, friend!" }, server_context: { user_id: 123 })
assert_equal expected_template_result, result.to_h
end
test "allows declarative definition of prompts as classes" do
class MockPrompt < Prompt
prompt_name "my_mock_prompt"
description "a mock prompt for testing"
arguments [
Prompt::Argument.new(name: "test_argument", description: "Test argument", required: true),
]
class << self
def template(args, server_context:)
Prompt::Result.new(
description: "Hello, world!",
messages: [
Prompt::Message.new(role: "user", content: Content::Text.new("Hello, world!")),
Prompt::Message.new(role: "assistant", content: Content::Text.new(args["test_argument"])),
],
)
end
end
end
prompt = MockPrompt
assert_equal "my_mock_prompt", prompt.name_value
assert_equal "a mock prompt for testing", prompt.description
assert_equal "test_argument", prompt.arguments.first.name
assert_equal "Test argument", prompt.arguments.first.description
assert prompt.arguments.first.required
expected_template_result = {
description: "Hello, world!",
messages: [
{ role: "user", content: { text: "Hello, world!", type: "text" } },
{ role: "assistant", content: { text: "Hello, friend!", type: "text" } },
],
}
result = prompt.template({ "test_argument" => "Hello, friend!" }, server_context: { user_id: 123 })
assert_equal expected_template_result, result.to_h
end
test "defaults to class name as prompt name" do
class DefaultNamePrompt < Prompt
description "a mock prompt for testing"
arguments [
Prompt::Argument.new(name: "test_argument", description: "Test argument", required: true),
]
class << self
def template(args, server_context:)
Prompt::Result.new(
description: "Hello, world!",
messages: [
Prompt::Message.new(role: "user", content: Content::Text.new("Hello, world!")),
Prompt::Message.new(role: "assistant", content: Content::Text.new(args["test_argument"])),
],
)
end
end
end
prompt = DefaultNamePrompt
assert_equal "default_name_prompt", prompt.name_value
assert_equal "a mock prompt for testing", prompt.description
assert_equal "test_argument", prompt.arguments.first.name
end
test ".define allows definition of simple prompts with a block" do
prompt = Prompt.define(
name: "mock_prompt",
description: "a mock prompt for testing",
arguments: [
Prompt::Argument.new(name: "test_argument", description: "Test argument", required: true),
],
) do |args, server_context:|
content = Content::Text.new(args["test_argument"] + " user: #{server_context[:user_id]}")
Prompt::Result.new(
description: "Hello, world!",
messages: [
Prompt::Message.new(role: "user", content: Content::Text.new("Hello, world!")),
Prompt::Message.new(role: "assistant", content:),
],
)
end
assert_equal "mock_prompt", prompt.name_value
assert_equal "a mock prompt for testing", prompt.description
assert_equal "test_argument", prompt.arguments.first.name
expected = {
description: "Hello, world!",
messages: [
{ role: "user", content: { text: "Hello, world!", type: "text" } },
{ role: "assistant", content: { text: "Hello, friend! user: 123", type: "text" } },
],
}
result = prompt.template({ "test_argument" => "Hello, friend!" }, server_context: { user_id: 123 })
assert_equal expected, result.to_h
end
end
end

843
test/mcp/server_test.rb Normal file
View file

@ -0,0 +1,843 @@
# typed: true
# frozen_string_literal: true
require "test_helper"
require "json"
require "debug"
module MCP
class ServerTest < ActiveSupport::TestCase
include InstrumentationTestHelper
setup do
@tool = Tool.define(name: "test_tool", description: "Test tool")
@tool_that_raises = Tool.define(
name: "tool_that_raises",
description: "Tool that raises",
input_schema: { type: "object", properties: { message: { type: "string" } }, required: ["message"] },
) { raise StandardError, "Tool error" }
@prompt = Prompt.define(
name: "test_prompt",
description: "Test prompt",
arguments: [
Prompt::Argument.new(name: "test_argument", description: "Test argument", required: true),
],
) do |_|
Prompt::Result.new(
description: "Hello, world!",
messages: [
Prompt::Message.new(role: "user", content: Content::Text.new("Hello, world!")),
],
)
end
@resource = Resource.new(
uri: "test_resource",
name: "Test resource",
description: "Test resource",
mime_type: "text/plain",
)
@resource_template = ResourceTemplate.new(
uri_template: "test_resource/{id}",
name: "Test resource",
description: "Test resource",
mime_type: "text/plain",
)
@server_name = "test_server"
configuration = MCP::Configuration.new
configuration.instrumentation_callback = instrumentation_helper.callback
@server = Server.new(
name: @server_name,
version: "1.2.3",
tools: [@tool, @tool_that_raises],
prompts: [@prompt],
resources: [@resource],
resource_templates: [@resource_template],
configuration:,
)
end
# https://spec.MCP.io/specification/2025-03-26/basic/utilities/ping/#behavior-requirements
test "#handle ping request returns empty response" do
request = {
jsonrpc: "2.0",
method: "ping",
id: "123",
}
response = @server.handle(request)
assert_equal(
{
"jsonrpc": "2.0",
"id": "123",
"result": {},
},
response,
)
assert_instrumentation_data({ method: "ping" })
end
test "#handle_json ping request returns empty response" do
request = JSON.generate({
jsonrpc: "2.0",
method: "ping",
id: "123",
})
response = JSON.parse(@server.handle_json(request), symbolize_names: true)
assert_equal(
{
"jsonrpc": "2.0",
"id": "123",
"result": {},
},
response,
)
assert_instrumentation_data({ method: "ping" })
end
test "#handle initialize request returns protocol info, server info, and capabilities" do
request = {
jsonrpc: "2.0",
method: "initialize",
id: 1,
}
response = @server.handle(request)
refute_nil response
expected_result = {
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {
"prompts": {},
"resources": {},
"tools": {},
},
"serverInfo": {
"name": @server_name,
"version": "1.2.3",
},
},
}
assert_equal expected_result, response
assert_instrumentation_data({ method: "initialize" })
end
test "#handle returns nil for notification requests" do
request = {
jsonrpc: "2.0",
method: "some_notification",
}
assert_nil @server.handle(request)
assert_instrumentation_data({ method: "unsupported_method" })
end
test "#handle tools/list returns available tools" do
request = {
jsonrpc: "2.0",
method: "tools/list",
id: 1,
}
response = @server.handle(request)
result = response[:result]
assert_kind_of Array, result[:tools]
assert_equal "test_tool", result[:tools][0][:name]
assert_equal "Test tool", result[:tools][0][:description]
assert_empty(result[:tools][0][:inputSchema])
assert_instrumentation_data({ method: "tools/list" })
end
test "#handle_json tools/list returns available tools" do
request = JSON.generate({
jsonrpc: "2.0",
method: "tools/list",
id: 1,
})
response = JSON.parse(@server.handle_json(request), symbolize_names: true)
result = response[:result]
assert_kind_of Array, result[:tools]
assert_equal "test_tool", result[:tools][0][:name]
assert_equal "Test tool", result[:tools][0][:description]
end
test "#tools_list_handler sets the tools/list handler" do
@server.tools_list_handler do
[{ name: "hammer", description: "Hammer time!" }]
end
request = {
jsonrpc: "2.0",
method: "tools/list",
id: 1,
}
response = @server.handle(request)
result = response[:result]
assert_equal({ tools: [{ name: "hammer", description: "Hammer time!" }] }, result)
assert_instrumentation_data({ method: "tools/list" })
end
test "#handle tools/call executes tool and returns result" do
tool_name = "test_tool"
tool_args = { arg: "value" }
tool_response = Tool::Response.new([{ result: "success" }])
@tool.expects(:call).with(arg: "value").returns(tool_response)
request = {
jsonrpc: "2.0",
method: "tools/call",
params: {
name: tool_name,
arguments: tool_args,
},
id: 1,
}
response = @server.handle(request)
assert_equal tool_response.to_h, response[:result]
assert_instrumentation_data({ method: "tools/call", tool_name: })
end
test "#handle tools/call returns error if required tool arguments are missing" do
tool_with_required_argument = Tool.define(
name: "test_tool",
description: "Test tool",
input_schema: { properties: { message: { type: "string" } }, required: ["message"] },
) do |message: nil|
Tool::Response.new("success #{message}")
end
server = Server.new(
name: "test_server",
tools: [tool_with_required_argument],
)
request = {
jsonrpc: "2.0",
method: "tools/call",
params: { name: "test_tool", arguments: {} },
id: 1,
}
response = server.handle(request)
assert_equal "Missing required arguments: message", response[:error][:data]
assert_equal "Internal error", response[:error][:message]
end
test "#handle_json tools/call executes tool and returns result" do
tool_name = "test_tool"
tool_args = { arg: "value" }
tool_response = Tool::Response.new([{ result: "success" }])
@tool.expects(:call).with(arg: "value").returns(tool_response)
request = JSON.generate({
jsonrpc: "2.0",
method: "tools/call",
params: { name: tool_name, arguments: tool_args },
id: 1,
})
raw_response = @server.handle_json(request)
response = JSON.parse(raw_response, symbolize_names: true) if raw_response
assert_equal tool_response.to_h, response[:result] if response
assert_instrumentation_data({ method: "tools/call", tool_name: })
end
test "#handle_json tools/call executes tool and returns result, when the tool is typed with Sorbet" do
class TypedTestTool < Tool
tool_name "test_tool"
description "a test tool for testing"
input_schema({ properties: { message: { type: "string" } }, required: ["message"] })
class << self
extend T::Sig
sig { params(message: String, server_context: T.nilable(T.untyped)).returns(Tool::Response) }
def call(message:, server_context: nil)
Tool::Response.new([{ type: "text", content: "OK" }])
end
end
end
request = JSON.generate({
jsonrpc: "2.0",
method: "tools/call",
params: { name: "test_tool", arguments: { message: "Hello, world!" } },
id: 1,
})
server = Server.new(
name: @server_name,
tools: [TypedTestTool],
prompts: [@prompt],
resources: [@resource],
resource_templates: [@resource_template],
)
raw_response = server.handle_json(request)
response = JSON.parse(raw_response, symbolize_names: true) if raw_response
assert_equal({ content: [{ type: "text", content: "OK" }], isError: false }, response[:result])
end
test "#handle tools/call returns internal error and reports exception if the tool raises an error" do
@server.configuration.exception_reporter.expects(:call).with do |exception, server_context|
assert_not_nil exception
assert_equal(
{
request: {
jsonrpc: "2.0",
method: "tools/call",
params: { name: "tool_that_raises", arguments: { message: "test" } },
id: 1,
},
},
server_context,
)
end
request = {
jsonrpc: "2.0",
method: "tools/call",
params: {
name: "tool_that_raises",
arguments: { message: "test" },
},
id: 1,
}
response = @server.handle(request)
assert_equal "Internal error", response[:error][:message]
assert_equal "Internal error calling tool tool_that_raises", response[:error][:data]
assert_instrumentation_data({ method: "tools/call", tool_name: "tool_that_raises", error: :internal_error })
end
test "#handle_json returns internal error and reports exception if the tool raises an error" do
request = JSON.generate({
jsonrpc: "2.0",
method: "tools/call",
params: {
name: "tool_that_raises",
arguments: { message: "test" },
},
id: 1,
})
response = JSON.parse(@server.handle_json(request), symbolize_names: true)
assert_equal "Internal error", response[:error][:message]
assert_equal "Internal error calling tool tool_that_raises", response[:error][:data]
assert_instrumentation_data({ method: "tools/call", tool_name: "tool_that_raises", error: :internal_error })
end
test "#handle tools/call returns error for unknown tool" do
request = {
jsonrpc: "2.0",
method: "tools/call",
params: {
name: "unknown_tool",
arguments: { message: "test" },
},
id: 1,
}
response = @server.handle(request)
assert_equal "Internal error", response[:error][:message]
assert_equal "Tool not found unknown_tool", response[:error][:data]
assert_instrumentation_data({ method: "tools/call", error: :tool_not_found })
end
test "#handle_json returns error for unknown tool" do
request = JSON.generate({
jsonrpc: "2.0",
method: "tools/call",
params: {
name: "unknown_tool",
arguments: {},
},
id: 1,
})
response = JSON.parse(@server.handle_json(request), symbolize_names: true)
assert_equal "Internal error", response[:error][:message]
end
test "#tools_call_handler sets the tools/call handler" do
@server.tools_call_handler do |request|
tool_name = request[:name]
return Tool::Response.new("#{tool_name} called successfully").to_h
end
request = {
jsonrpc: "2.0",
method: "tools/call",
params: { name: "my_tool", arguments: {} },
id: 1,
}
response = @server.handle(request)
assert_equal({ content: "my_tool called successfully", isError: false }, response[:result])
assert_instrumentation_data({ method: "tools/call", tool_name: "my_tool" })
end
test "#handle prompts/list returns list of prompts" do
request = {
jsonrpc: "2.0",
method: "prompts/list",
id: 1,
}
response = @server.handle(request)
assert_equal({ prompts: [@prompt.to_h] }, response[:result])
assert_instrumentation_data({ method: "prompts/list" })
end
test "#prompts_list_handler sets the prompts/list handler" do
@server.prompts_list_handler do
[{ name: "foo_prompt", description: "Foo prompt" }]
end
request = {
jsonrpc: "2.0",
method: "prompts/list",
id: 1,
}
response = @server.handle(request)
assert_equal({ prompts: [{ name: "foo_prompt", description: "Foo prompt" }] }, response[:result])
assert_instrumentation_data({ method: "prompts/list" })
end
test "#handle prompts/get returns templated prompt" do
request = {
jsonrpc: "2.0",
method: "prompts/get",
id: 1,
params: {
name: "test_prompt",
arguments: { test_argument: "Hello, friend!" },
},
}
expected_result = {
description: "Hello, world!",
messages: [
{ role: "user", content: { text: "Hello, world!", type: "text" } },
],
}
response = @server.handle(request)
assert_equal(expected_result, response[:result])
assert_instrumentation_data({ method: "prompts/get", prompt_name: "test_prompt" })
end
test "#handle prompts/get returns error if prompt is not found" do
request = {
jsonrpc: "2.0",
method: "prompts/get",
id: 1,
params: {
name: "unknown_prompt",
arguments: {},
},
}
response = @server.handle(request)
assert_equal("Prompt not found unknown_prompt", response[:error][:data])
assert_instrumentation_data({ method: "prompts/get", error: :prompt_not_found })
end
test "#handle prompts/get returns error if prompt arguments are invalid" do
request = {
jsonrpc: "2.0",
method: "prompts/get",
id: 1,
params: {
name: "test_prompt",
arguments: { "unknown_argument" => "Hello, friend!" },
},
}
response = @server.handle(request)
assert_equal "Missing required arguments: test_argument", response[:error][:data]
assert_instrumentation_data({
method: "prompts/get",
prompt_name: "test_prompt",
error: :missing_required_arguments,
})
end
test "#prompts_get_handler sets the prompts/get handler" do
@server.prompts_get_handler do |request|
prompt_name = request[:name]
return Prompt::Result.new(
description: prompt_name,
messages: [
Prompt::Message.new(role: "user", content: Content::Text.new(request[:arguments][:foo])),
],
).to_h
end
request = {
jsonrpc: "2.0",
method: "prompts/get",
id: 1,
params: { name: "foo_bar_prompt", arguments: { "foo" => "bar" } },
}
response = @server.handle(request)
assert_equal(
{ description: "foo_bar_prompt", messages: [{ role: "user", content: { text: "bar" } }] },
response[:result],
)
assert_instrumentation_data({ method: "prompts/get", prompt_name: "foo_bar_prompt" })
end
test "#handle resources/list returns a list of resources" do
request = {
jsonrpc: "2.0",
method: "resources/list",
id: 1,
}
response = @server.handle(request)
assert_equal({ resources: [@resource.to_h] }, response[:result])
assert_instrumentation_data({ method: "resources/list" })
end
test "#resources_list_handler sets the resources/list handler" do
@server.resources_list_handler do
[{ uri: "test_resource", name: "Test resource", description: "Test resource" }]
end
request = {
jsonrpc: "2.0",
method: "resources/list",
id: 1,
}
response = @server.handle(request)
assert_equal(
{ resources: [{ uri: "test_resource", name: "Test resource", description: "Test resource" }] },
response[:result],
)
assert_instrumentation_data({ method: "resources/list" })
end
test "#handle resources/read returns an empty array of contents by default" do
request = {
jsonrpc: "2.0",
method: "resources/read",
id: 1,
params: {
uri: "example.com",
},
}
response = @server.handle(request)
assert_equal({ contents: [] }, response[:result])
assert_instrumentation_data({ method: "resources/read", resource_uri: "example.com" })
end
test "#resources_read_handler sets the resources/read handler" do
@server.resources_read_handler do |request|
return {
uri: request[:uri],
mime_type: "text/plain",
text: "Lorem ipsum dolor sit amet",
}
end
request = {
jsonrpc: "2.0",
method: "resources/read",
id: 1,
params: {
uri: "example.com/my_resource",
},
}
response = @server.handle(request)
assert_equal(
{ contents: [{ uri: "example.com/my_resource", mimeType: "text/plain", text: "Lorem ipsum dolor sit amet" }] },
response[:result],
)
end
test "#handle resources/templates/list returns a list of resource templates" do
request = {
jsonrpc: "2.0",
method: "resources/templates/list",
id: 1,
}
response = @server.handle(request)
assert_equal(
{
resourceTemplates: [@resource_template.to_h],
},
response[:result],
)
assert_instrumentation_data({ method: "resources/templates/list" })
end
test "#resources_templates_list_handler sets the resources/templates/list handler" do
@server.resources_templates_list_handler do
[{ uriTemplate: "test_resource_template/{id}", name: "Test resource template", description: "a template" }]
end
request = {
jsonrpc: "2.0",
method: "resources/templates/list",
id: 1,
}
response = @server.handle(request)
assert_equal(
{
resourceTemplates: [
{
uriTemplate: "test_resource_template/{id}",
name: "Test resource template",
description: "a template",
},
],
},
response[:result],
)
assert_instrumentation_data({ method: "resources/templates/list" })
end
test "#handle method with missing required top-level capability returns an error" do
@server.capabilities = {}
response = @server.handle({ jsonrpc: "2.0", method: "prompts/list", id: 1 })
assert_equal "Server does not support prompts (required for prompts/list)", response[:error][:data]
response = @server.handle({ jsonrpc: "2.0", method: "resources/list", id: 1 })
assert_equal "Server does not support resources (required for resources/list)", response[:error][:data]
end
test "#handle method with missing required nested capability returns an error" do
@server.capabilities = { resources: {} }
response = @server.handle({ jsonrpc: "2.0", method: "resources/subscribe", id: 1 })
assert_equal "Server does not support resources_subscribe (required for resources/subscribe)",
response[:error][:data]
end
test "#handle unknown method returns method not found error" do
request = {
jsonrpc: "2.0",
id: 1,
method: "unknown_method",
}
response = @server.handle(request)
assert_equal "Method not found", response[:error][:message]
assert_equal "unknown_method", response[:error][:data]
assert_instrumentation_data({ method: "unsupported_method" })
end
test "the global configuration is used if no configuration is passed to the server" do
server = Server.new(name: "test_server")
assert_equal MCP.configuration.instrumentation_callback,
server.configuration.instrumentation_callback
assert_equal MCP.configuration.exception_reporter,
server.configuration.exception_reporter
end
test "the server configuration takes precedence over the global configuration" do
configuration = MCP::Configuration.new
local_callback = ->(data) { puts "Local callback #{data.inspect}" }
local_exception_reporter = ->(exception, server_context) {
puts "Local exception reporter #{exception.inspect} #{server_context.inspect}"
}
configuration.instrumentation_callback = local_callback
configuration.exception_reporter = local_exception_reporter
server = Server.new(name: "test_server", configuration:)
assert_equal local_callback, server.configuration.instrumentation_callback
assert_equal local_exception_reporter, server.configuration.exception_reporter
end
test "server uses default protocol version when not configured" do
request = {
jsonrpc: "2.0",
method: "initialize",
id: 1,
}
response = @server.handle(request)
assert_equal Configuration::DEFAULT_PROTOCOL_VERSION, response[:result][:protocolVersion]
end
test "server uses default version when not configured" do
server = Server.new(name: "test_server")
request = {
jsonrpc: "2.0",
method: "initialize",
id: 1,
}
response = server.handle(request)
assert_equal Server::DEFAULT_VERSION, response[:result][:serverInfo][:version]
end
test "#define_tool adds a tool to the server" do
@server.define_tool(
name: "defined_tool",
description: "Defined tool",
input_schema: { type: "object", properties: { message: { type: "string" } }, required: ["message"] },
) do |message:|
Tool::Response.new(message)
end
response = @server.handle({
jsonrpc: "2.0",
method: "tools/call",
params: { name: "defined_tool", arguments: { message: "success" } },
id: 1,
})
assert_equal({ content: "success", isError: false }, response[:result])
end
test "#define_tool call definition allows tool arguments and server context" do
@server.server_context = { user_id: "123" }
@server.define_tool(
name: "defined_tool",
description: "Defined tool",
input_schema: { type: "object", properties: { message: { type: "string" } }, required: ["message"] },
) do |message:, server_context:|
Tool::Response.new("success #{message} #{server_context[:user_id]}")
end
response = @server.handle({
jsonrpc: "2.0",
method: "tools/call",
params: { name: "defined_tool", arguments: { message: "hello" } },
id: 1,
})
assert_equal({ content: "success hello 123", isError: false }, response[:result])
end
test "#define_prompt adds a tool to the server" do
@server.define_prompt(name: "defined_prompt", description: "Defined prompt", arguments: []) do
Prompt::Result.new(
description: "a prompt description",
messages: [Prompt::Message.new(role: "user", content: Content::Text.new("a prompt message"))],
)
end
response = @server.handle({
jsonrpc: "2.0",
method: "prompts/get",
params: { name: "defined_prompt", arguments: {} },
id: 1,
})
assert_equal(
{
description: "a prompt description",
messages: [{ role: "user", content: { text: "a prompt message", type: "text" } }],
},
response[:result],
)
end
test "server protocol version can be overridden via configuration" do
custom_version = "2025-03-27"
configuration = Configuration.new(protocol_version: custom_version)
server = Server.new(name: "test_server", configuration: configuration)
request = {
jsonrpc: "2.0",
method: "initialize",
id: 1,
}
response = server.handle(request)
assert_equal custom_version, response[:result][:protocolVersion]
end
test "has tool capability only if tools or a tools_list_handler is defined" do
server_with_tools = Server.new(name: "test_server", tools: [@tool])
assert_includes server_with_tools.capabilities, :tools
server_with_handler = Server.new(name: "test_server")
server_with_handler.tools_list_handler do
[{ name: "test_tool", description: "Test tool" }]
end
assert_includes server_with_handler.capabilities, :tools
server_without_tools = Server.new(name: "test_server")
refute_includes server_without_tools.capabilities, :tools
end
test "has prompt capability only if prompts or a prompts_list_handler is defined" do
server_with_prompts = Server.new(name: "test_server", prompts: [@prompt])
assert_includes server_with_prompts.capabilities, :prompts
server_with_handler = Server.new(name: "test_server")
server_with_handler.prompts_list_handler do
[{ name: "test_prompt", description: "Test prompt" }]
end
assert_includes server_with_handler.capabilities, :prompts
server_without_prompts = Server.new(name: "test_server")
refute_includes server_without_prompts.capabilities, :prompts
end
test "has resources capability only if resources, template or custom handler is defined" do
server_with_resources = Server.new(name: "test_server", resources: [@resource])
assert_includes server_with_resources.capabilities, :resources
server_with_resource_template = Server.new(name: "test_server", resource_templates: [@resource_template])
assert_includes server_with_resource_template.capabilities, :resources
server_with_resources_list_handler = Server.new(name: "test_server")
server_with_resources_list_handler.resources_list_handler do
[{ uri: "test_resource", name: "Test resource", description: "Test resource" }]
end
assert_includes server_with_resources_list_handler.capabilities, :resources
server_with_resources_templates_list_handler = Server.new(name: "test_server")
server_with_resources_templates_list_handler.resources_templates_list_handler do
[{ uri_template: "test_resource/{id}", name: "Test resource", description: "Test resource" }]
end
assert_includes server_with_resources_templates_list_handler.capabilities, :resources
server_without_resources = Server.new(name: "test_server")
refute_includes server_without_resources.capabilities, :resources
end
end
end

View file

@ -0,0 +1,22 @@
# frozen_string_literal: true
require "test_helper"
module MCP
class StringUtilsTest < Minitest::Test
def test_handle_from_class_name_returns_the_class_name_without_the_module_for_a_class_without_a_module
assert_equal("test", StringUtils.handle_from_class_name("Test"))
assert_equal("test_class", StringUtils.handle_from_class_name("TestClass"))
end
def test_handle_from_class_name_returns_the_class_name_without_the_module_for_a_class_with_a_single_parent_module
assert_equal("test", StringUtils.handle_from_class_name("Module::Test"))
assert_equal("test_class", StringUtils.handle_from_class_name("Module::TestClass"))
end
def test_handle_from_class_name_returns_the_class_name_without_the_module_for_a_class_with_multiple_parent_modules
assert_equal("test", StringUtils.handle_from_class_name("Module::Submodule::Test"))
assert_equal("test_class", StringUtils.handle_from_class_name("Module::Submodule::TestClass"))
end
end
end

View file

@ -0,0 +1,32 @@
# frozen_string_literal: true
require "test_helper"
module MCP
class Tool
class InputSchemaTest < ActiveSupport::TestCase
test "required arguments are converted to symbols" do
input_schema = InputSchema.new(properties: { message: { type: "string" } }, required: ["message"])
assert_equal [:message], input_schema.required
end
test "to_h returns a hash representation of the input schema" do
input_schema = InputSchema.new(properties: { message: { type: "string" } }, required: [:message])
assert_equal(
{ type: "object", properties: { message: { type: "string" } }, required: [:message] },
input_schema.to_h,
)
end
test "missing_required_arguments returns an array of missing required arguments" do
input_schema = InputSchema.new(properties: { message: { type: "string" } }, required: [:message])
assert_equal [:message], input_schema.missing_required_arguments({})
end
test "missing_required_arguments returns an empty array if no required arguments are missing" do
input_schema = InputSchema.new(properties: { message: { type: "string" } }, required: [:message])
assert_empty input_schema.missing_required_arguments({ message: "Hello, world!" })
end
end
end
end

230
test/mcp/tool_test.rb Normal file
View file

@ -0,0 +1,230 @@
# typed: true
# frozen_string_literal: true
require "test_helper"
module MCP
class ToolTest < ActiveSupport::TestCase
class TestTool < Tool
tool_name "test_tool"
description "a test tool for testing"
input_schema({ properties: { message: { type: "string" } }, required: ["message"] })
annotations(
title: "Test Tool",
read_only_hint: true,
destructive_hint: false,
idempotent_hint: true,
open_world_hint: false,
)
class << self
def call(message:, server_context: nil)
Tool::Response.new([{ type: "text", content: "OK" }])
end
end
end
test "#to_h returns a hash with name, description, and inputSchema" do
tool = Tool.define(name: "mock_tool", description: "a mock tool for testing")
assert_equal tool.to_h, { name: "mock_tool", description: "a mock tool for testing", inputSchema: {} }
end
test "#to_h includes annotations when present" do
tool = TestTool
expected_annotations = {
title: "Test Tool",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
}
assert_equal tool.to_h[:annotations], expected_annotations
end
test "#call invokes the tool block and returns the response" do
tool = TestTool
response = tool.call(message: "test")
assert_equal response.content, [{ type: "text", content: "OK" }]
assert_equal response.is_error, false
end
test "allows declarative definition of tools as classes" do
class MockTool < Tool
tool_name "my_mock_tool"
description "a mock tool for testing"
input_schema({ properties: { message: { type: "string" } }, required: [:message] })
end
tool = MockTool
assert_equal tool.name_value, "my_mock_tool"
assert_equal tool.description, "a mock tool for testing"
assert_equal tool.input_schema.to_h,
{ type: "object", properties: { message: { type: "string" } }, required: [:message] }
end
test "defaults to class name as tool name" do
class DefaultNameTool < Tool
end
tool = DefaultNameTool
assert_equal tool.tool_name, "default_name_tool"
end
test "accepts input schema as an InputSchema object" do
class InputSchemaTool < Tool
input_schema InputSchema.new(properties: { message: { type: "string" } }, required: [:message])
end
tool = InputSchemaTool
expected = { type: "object", properties: { message: { type: "string" } }, required: [:message] }
assert_equal expected, tool.input_schema.to_h
end
test ".define allows definition of simple tools with a block" do
tool = Tool.define(name: "mock_tool", description: "a mock tool for testing") do |_|
Tool::Response.new([{ type: "text", content: "OK" }])
end
assert_equal tool.name_value, "mock_tool"
assert_equal tool.description, "a mock tool for testing"
assert_equal tool.input_schema, nil
end
test ".define allows definition of tools with annotations" do
tool = Tool.define(
name: "mock_tool",
description: "a mock tool for testing",
annotations: {
title: "Mock Tool",
read_only_hint: true,
},
) do |_|
Tool::Response.new([{ type: "text", content: "OK" }])
end
assert_equal tool.name_value, "mock_tool"
assert_equal tool.description, "a mock tool for testing"
assert_equal tool.input_schema, nil
assert_equal tool.annotations_value.to_h, { title: "Mock Tool", readOnlyHint: true }
end
# Tests for Tool::Annotations class
test "Tool::Annotations initializes with all properties" do
annotations = Tool::Annotations.new(
title: "Test Tool",
read_only_hint: true,
destructive_hint: false,
idempotent_hint: true,
open_world_hint: false,
)
assert_equal annotations.title, "Test Tool"
assert_equal annotations.read_only_hint, true
assert_equal annotations.destructive_hint, false
assert_equal annotations.idempotent_hint, true
assert_equal annotations.open_world_hint, false
end
test "Tool::Annotations initializes with partial properties" do
annotations = Tool::Annotations.new(
title: "Test Tool",
read_only_hint: true,
)
assert_equal annotations.title, "Test Tool"
assert_equal annotations.read_only_hint, true
assert_nil annotations.destructive_hint
assert_nil annotations.idempotent_hint
assert_nil annotations.open_world_hint
end
test "Tool::Annotations#to_h omits nil values" do
annotations = Tool::Annotations.new(
title: "Test Tool",
read_only_hint: true,
)
expected = {
title: "Test Tool",
readOnlyHint: true,
}
assert_equal annotations.to_h, expected
end
test "Tool::Annotations#to_h handles all properties" do
annotations = Tool::Annotations.new(
title: "Test Tool",
read_only_hint: true,
destructive_hint: false,
idempotent_hint: true,
open_world_hint: false,
)
expected = {
title: "Test Tool",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: false,
}
assert_equal annotations.to_h, expected
end
test "Tool::Annotations#to_h returns empty hash when all values are nil" do
annotations = Tool::Annotations.new
assert_empty annotations.to_h
end
test "Tool class method annotations can be set and retrieved" do
class AnnotationsTestTool < Tool
tool_name "annotations_test"
annotations(
title: "Annotations Test",
read_only_hint: true,
)
end
tool = AnnotationsTestTool
assert_instance_of Tool::Annotations, tool.annotations_value
assert_equal tool.annotations_value.title, "Annotations Test"
assert_equal tool.annotations_value.read_only_hint, true
end
test "Tool class method annotations can be updated" do
class UpdatableAnnotationsTool < Tool
tool_name "updatable_annotations"
end
tool = UpdatableAnnotationsTool
tool.annotations(title: "Initial")
assert_equal tool.annotations_value.title, "Initial"
tool.annotations(title: "Updated")
assert_equal tool.annotations_value.title, "Updated"
end
test "#call with Sorbet typed tools invokes the tool block and returns the response" do
class TypedTestTool < Tool
tool_name "test_tool"
description "a test tool for testing"
input_schema({ properties: { message: { type: "string" } }, required: ["message"] })
class << self
extend T::Sig
sig { params(message: String, server_context: T.nilable(T.untyped)).returns(Tool::Response) }
def call(message:, server_context: nil)
Tool::Response.new([{ type: "text", content: "OK" }])
end
end
end
tool = TypedTestTool
response = tool.call(message: "test")
assert_equal response.content, [{ type: "text", content: "OK" }]
assert_equal response.is_error, false
end
end
end

View file

@ -0,0 +1,125 @@
# frozen_string_literal: true
require "test_helper"
require "mcp/transports/stdio"
require "json"
module MCP
module Transports
class StdioTransportTest < ActiveSupport::TestCase
include InstrumentationTestHelper
setup do
configuration = MCP::Configuration.new
configuration.instrumentation_callback = instrumentation_helper.callback
@server = Server.new(name: "test_server", configuration: configuration)
@transport = StdioTransport.new(@server)
end
test "initializes with server and closed state" do
server = @transport.instance_variable_get(:@server)
assert_equal @server.object_id, server.object_id
refute @transport.instance_variable_get(:@open)
end
test "processes JSON-RPC requests from stdin and sends responses to stdout" do
request = {
jsonrpc: "2.0",
method: "ping",
id: "123",
}
input = StringIO.new(JSON.generate(request) + "\n")
output = StringIO.new
original_stdin = $stdin
original_stdout = $stdout
begin
$stdin = input
$stdout = output
thread = Thread.new { @transport.open }
sleep(0.1)
@transport.close
thread.join
response = JSON.parse(output.string, symbolize_names: true)
assert_equal("2.0", response[:jsonrpc])
assert_equal("123", response[:id])
assert_empty(response[:result])
refute(@transport.instance_variable_get(:@open))
ensure
$stdin = original_stdin
$stdout = original_stdout
end
end
test "sends string responses to stdout" do
output = StringIO.new
original_stdout = $stdout
begin
$stdout = output
@transport.send_response("test response")
assert_equal("test response\n", output.string)
ensure
$stdout = original_stdout
end
end
test "sends JSON responses to stdout" do
output = StringIO.new
original_stdout = $stdout
begin
$stdout = output
response = { key: "value" }
@transport.send_response(response)
assert_equal(JSON.generate(response) + "\n", output.string)
ensure
$stdout = original_stdout
end
end
test "handles valid JSON-RPC requests" do
request = {
jsonrpc: "2.0",
method: "ping",
id: "123",
}
output = StringIO.new
original_stdout = $stdout
begin
$stdout = output
@transport.send(:handle_request, JSON.generate(request))
response = JSON.parse(output.string, symbolize_names: true)
assert_equal("2.0", response[:jsonrpc])
assert_nil(response[:id])
assert_nil(response[:result])
ensure
$stdout = original_stdout
end
end
test "handles invalid JSON requests" do
invalid_json = "invalid json"
output = StringIO.new
original_stdout = $stdout
begin
$stdout = output
@transport.send(:handle_request, invalid_json)
response = JSON.parse(output.string, symbolize_names: true)
assert_equal("2.0", response[:jsonrpc])
assert_nil(response[:id])
assert_equal(-32600, response[:error][:code])
assert_equal("Invalid Request", response[:error][:message])
assert_equal("Request must be an array or a hash", response[:error][:data])
ensure
$stdout = original_stdout
end
end
end
end
end