Expose the user-defined server_context in instrumentation data

APM integrations need to tag a span with the subject of the request, but the
user-defined `server_context` hash passed to `Server.new` never reaches
`around_request` or `instrumentation_callback`. The exception reporter's
`server_context` argument is a different value — it describes where a failure
occurred (`{ request: ... }`, `{ notification: ... }`), not who made the call —
so there is currently no way to read the request subject from a hook.

Add `Configuration#instrument_server_context`, off by default. When enabled,
`instrument_call` puts the host's `server_context` into the instrumentation data
before invoking `around_request`, so it is readable both before and after
`request_handler.call`.

The flag is opt-in rather than unconditional because the hash is
application-supplied and may hold values a tracing backend should not receive.
Hosts that do not expose a `server_context` reader are unaffected.

`instrument_call` reads it through `self.server_context`: the existing
`server_context:` keyword shadows the reader, and the value wanted here is the
user-defined hash, not the reporter context.

Follows the same shape as the earlier additions of `tool_arguments` (#218) and
`client` (#221) to this hash.
This commit is contained in:
seunghan Kim 2026-08-08 08:33:07 +09:00
commit 14e02da475

View file

@ -145,6 +145,35 @@ module MCP
refute merged.validate_tool_call_arguments
end
test "defaults instrument_server_context to false" do
config = Configuration.new
refute_predicate config, :instrument_server_context?
end
test "accepts instrument_server_context in the constructor" do
config = Configuration.new(instrument_server_context: true)
assert_predicate config, :instrument_server_context?
end
test "raises ArgumentError when instrument_server_context is not a boolean value" do
config = Configuration.new
exception = assert_raises(ArgumentError) do
config.instrument_server_context = "true"
end
assert_equal("instrument_server_context must be a boolean", exception.message)
end
test "merge carries instrument_server_context from the other configuration" do
base = Configuration.new(instrument_server_context: true)
other = Configuration.new(instrument_server_context: false)
refute_predicate base.merge(other), :instrument_server_context?
assert_predicate other.merge(base), :instrument_server_context?
end
test "defaults validate_tool_call_results to false" do
config = Configuration.new
refute config.validate_tool_call_results