ruby-sdk icon indicating copy to clipboard operation
ruby-sdk copied to clipboard

Add automatic _meta parameter extraction support

Open erickreutz opened this issue 2 months ago • 0 comments

Summary

This PR adds native support for the MCP protocol's _meta parameter, eliminating the need for manual extraction in controllers.

Background

The MCP specification defines a _meta field that allows clients to pass request-specific metadata. Previously, Ruby SDK users had to manually extract this field from request parameters.

Changes

  • Automatic extraction: The server now automatically extracts _meta from request parameters in call_tool and get_prompt methods
  • Nested structure: _meta is passed as a nested field within server_context (accessible via server_context[:_meta])
  • Compatibility: This implementation matches the TypeScript and Python SDKs, which also nest _meta within the context
  • Efficient context creation: Context is only created when there's either server_context or _meta present

Testing

  • Added comprehensive tests for _meta extraction and nesting behavior
  • All tests pass with the new implementation
  • Provider-agnostic test examples (no vendor-specific references)

Documentation

  • Updated README with _meta usage examples
  • Added link to official MCP specification
  • Included both access patterns and client request examples

Usage Example

class MyTool < MCP::Tool
  def self.call(message:, server_context: nil)
    # Access request-specific metadata
    session_id = server_context&.dig(:_meta, :session_id)
    
    # Access server's original context
    user_id = server_context&.dig(:user_id)
    
    MCP::Tool::Response.new([{
      type: "text",
      text: "Processing for user #{user_id} in session #{session_id}"
    }])
  end
end

Breaking Changes

None - this is backwards compatible. Tools that don't use server_context or don't access _meta will continue to work unchanged.

Notes

While implementing this feature, we discovered that the README incorrectly states that server_context is passed to exception and instrumentation callbacks, though the actual implementation only passes contextual error information to these callbacks.

erickreutz avatar Oct 26 '25 22:10 erickreutz