Skip to content

Commit a2575b2

Browse files
committed
Use accessor method in server_context_with_meta instead of ivar
## Motivation and Context `server_context_with_meta` reads `@server_context` (the instance variable) directly instead of calling the `server_context` accessor method. This prevents subclasses from overriding `server_context`. Ffor example, to provide thread-local context in multi-threaded servers like Puma. Fixes #271. ## How Has This Been Tested? Added a regression test and passed. ## Breaking Changes None. This restores the expected behavior of `attr_accessor :server_context`.
1 parent e189d78 commit a2575b2

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

lib/mcp/server.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -531,14 +531,14 @@ def call_prompt_template_with_args(prompt, args, server_context)
531531

532532
def server_context_with_meta(request)
533533
meta = request[:_meta]
534-
if meta && @server_context.is_a?(Hash)
535-
context = @server_context.dup
534+
if meta && server_context.is_a?(Hash)
535+
context = server_context.dup
536536
context[:_meta] = meta
537537
context
538-
elsif meta && @server_context.nil?
538+
elsif meta && server_context.nil?
539539
{ _meta: meta }
540540
else
541-
@server_context
541+
server_context
542542
end
543543
end
544544
end

test/mcp/server_test.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1731,5 +1731,31 @@ def call(numbers:, strings:, objects:, server_context: nil)
17311731
end
17321732
end
17331733
end
1734+
1735+
test "server_context_with_meta uses accessor method, not ivar directly" do
1736+
subclass = Class.new(Server) do
1737+
def server_context
1738+
{ custom: "from_accessor" }
1739+
end
1740+
end
1741+
1742+
server = subclass.new(name: "test", tools: [])
1743+
1744+
received_context = nil
1745+
server.define_tool(name: "ctx_tool") do |server_context:|
1746+
received_context = server_context
1747+
Tool::Response.new([{ type: "text", text: "ok" }])
1748+
end
1749+
1750+
request = {
1751+
jsonrpc: "2.0",
1752+
method: "tools/call",
1753+
id: 1,
1754+
params: { name: "ctx_tool", arguments: {} },
1755+
}
1756+
1757+
server.handle(request)
1758+
assert_equal "from_accessor", received_context[:custom]
1759+
end
17341760
end
17351761
end

0 commit comments

Comments
 (0)