Skip to content

Commit 91a188c

Browse files
committed
Add define_custom_method to define custom methods
1 parent 189d5fc commit 91a188c

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

lib/mcp/server.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,15 @@ def initialize(message, request, error_type: :internal_error, original_error: ni
2020
end
2121
end
2222

23+
class MethodAlreadyDefinedError < StandardError
24+
attr_reader :method_name
25+
26+
def initialize(method_name)
27+
super("Method #{method_name} already defined")
28+
@method_name = method_name
29+
end
30+
end
31+
2332
include Instrumentation
2433

2534
attr_accessor :name, :version, :tools, :prompts, :resources, :server_context, :configuration, :capabilities, :transport
@@ -89,6 +98,14 @@ def define_prompt(name: nil, description: nil, arguments: [], &block)
8998
@prompts[prompt.name_value] = prompt
9099
end
91100

101+
def define_custom_method(method_name:, &block)
102+
if @handlers.key?(method_name)
103+
raise MethodAlreadyDefinedError, method_name
104+
end
105+
106+
@handlers[method_name] = block
107+
end
108+
92109
def notify_tools_list_changed
93110
return unless @transport
94111

test/mcp/server_test.rb

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -653,6 +653,38 @@ def call(message:, server_context: nil)
653653
assert_instrumentation_data({ method: "unsupported_method" })
654654
end
655655

656+
test "#handle handles custom methods" do
657+
@server.define_custom_method(method_name: "add") do |params|
658+
params[:a] + params[:b]
659+
end
660+
661+
request = {
662+
jsonrpc: "2.0",
663+
id: 1,
664+
method: "add",
665+
params: { a: 1, b: 2 },
666+
}
667+
668+
response = @server.handle(request)
669+
assert_equal 3, response[:result]
670+
assert_instrumentation_data({ method: "add" })
671+
end
672+
673+
test "#handle handles custom notifications" do
674+
@server.define_custom_method(method_name: "notify") do
675+
nil
676+
end
677+
678+
request = {
679+
jsonrpc: "2.0",
680+
method: "notify",
681+
}
682+
683+
response = @server.handle(request)
684+
assert_nil response
685+
assert_instrumentation_data({ method: "notify" })
686+
end
687+
656688
test "the global configuration is used if no configuration is passed to the server" do
657689
server = Server.new(name: "test_server")
658690
assert_equal MCP.configuration.instrumentation_callback,

0 commit comments

Comments
 (0)