ReferenceMetadata

Struct ReferenceMetadata 

Source
pub struct ReferenceMetadata {
    pub summary: Option<String>,
    pub description: Option<String>,
}
Expand description

Metadata extracted from OpenAPI 3.1 reference objects for MCP tool generation

This struct encapsulates the OpenAPI 3.1 reference metadata fields (summary and description) that provide contextual, usage-specific documentation for referenced schema objects. It implements the proper precedence hierarchy as defined by the OpenAPI 3.1 specification.

§OpenAPI 3.1 Reference Metadata Semantics

In OpenAPI 3.1, reference objects can contain additional metadata fields:

$ref: '#/components/schemas/Pet'
summary: Pet information for store operations
description: Detailed pet data including status and ownership

This metadata serves a different semantic purpose than schema definitions:

  • Reference metadata: Provides contextual, usage-specific information about how a schema is used in a particular location within the API specification
  • Schema metadata: Provides general, reusable documentation about the schema itself

§Precedence Hierarchy

Following OpenAPI 3.1 semantics, this implementation enforces the precedence:

  1. Reference description (highest priority) - Contextual usage description
  2. Reference summary (medium priority) - Contextual usage summary
  3. Schema description (lowest priority) - General schema description
  4. Generated fallback (last resort) - Auto-generated descriptive text

This hierarchy ensures that human-authored contextual information takes precedence over generic schema documentation, providing more meaningful tool descriptions for AI assistants consuming the MCP interface.

§Usage in Tool Generation

Reference metadata is used throughout the tool generation process:

  • Parameter descriptions: Enhanced with contextual information about parameter usage
  • Request body schemas: Enriched with operation-specific documentation
  • Response schemas: Augmented with endpoint-specific response information
  • Tool descriptions: Combined with operation metadata for comprehensive tool documentation

§Example

use rmcp_openapi::tool_generator::ReferenceMetadata;

let ref_meta = ReferenceMetadata::new(
    Some("Pet data".to_string()),
    Some("Complete pet information including health records".to_string())
);

// Reference description takes precedence
assert_eq!(
    ref_meta.best_description(),
    Some("Complete pet information including health records")
);

// Merge with existing schema description (reference wins)
let enhanced = ref_meta.merge_with_description(
    Some("Generic pet schema"),
    false
);
assert_eq!(enhanced, Some("Complete pet information including health records".to_string()));

Fields§

§summary: Option<String>

Optional contextual summary from the OpenAPI 3.1 reference object

This field captures the summary property from a reference object, providing a brief, contextual description of how the referenced schema is used in this specific location. Takes precedence over schema summaries when available.

§description: Option<String>

Optional contextual description from the OpenAPI 3.1 reference object

This field captures the description property from a reference object, providing detailed, contextual documentation about how the referenced schema is used in this specific location. This is the highest priority description in the precedence hierarchy and overrides any schema-level descriptions.

Implementations§

Source§

impl ReferenceMetadata

Source

pub fn new(summary: Option<String>, description: Option<String>) -> Self

Create new reference metadata from optional summary and description

Source

pub fn is_empty(&self) -> bool

Check if this metadata contains any useful information

Source

pub fn best_description(&self) -> Option<&str>

Get the best available description from reference metadata

This helper method implements the core fallback logic for selecting the most appropriate description from the available reference metadata fields. It follows OpenAPI 3.1 semantics where detailed descriptions take precedence over brief summaries.

§Selection Logic
  1. Primary: Returns reference description if available
    • Source: $ref.description field
    • Rationale: Detailed contextual information is most valuable
  2. Fallback: Returns reference summary if no description available
    • Source: $ref.summary field
    • Rationale: Brief context is better than no context
  3. None: Returns None if neither field is available
    • Behavior: Caller must handle absence of reference metadata
§Usage in Precedence Hierarchy

This method provides the first-priority input for all description enhancement methods (merge_with_description(), enhance_parameter_description()). It encapsulates the “reference description OR reference summary” logic that forms the top of the precedence hierarchy.

§Examples
use rmcp_openapi::tool_generator::ReferenceMetadata;

// Description takes precedence over summary
let both = ReferenceMetadata::new(
    Some("Brief summary".to_string()),
    Some("Detailed description".to_string())
);
assert_eq!(both.best_description(), Some("Detailed description"));

// Summary used when no description
let summary_only = ReferenceMetadata::new(Some("Brief summary".to_string()), None);
assert_eq!(summary_only.best_description(), Some("Brief summary"));

// None when no reference metadata
let empty = ReferenceMetadata::new(None, None);
assert_eq!(empty.best_description(), None);
§Returns
  • Some(&str) - Best available description (description OR summary)
  • None - No reference metadata available
Source

pub fn summary(&self) -> Option<&str>

Get the reference summary for targeted access

This helper method provides direct access to the reference summary field without fallback logic. It’s used when summary-specific behavior is needed, such as in merge_with_description() for the special prepend functionality.

§Usage Scenarios
  1. Summary-specific operations: When caller needs to distinguish between summary and description for special formatting (e.g., prepend behavior)
  2. Metadata inspection: When caller wants to check what summary information is available without fallback to description
  3. Pattern matching: Used in complex precedence logic where summary and description need separate handling
§Relationship with best_description()

Unlike best_description() which implements fallback logic, this method provides raw access to just the summary field. This enables fine-grained control in precedence implementations.

§Examples
use rmcp_openapi::tool_generator::ReferenceMetadata;

let with_summary = ReferenceMetadata::new(Some("API token".to_string()), None);

// Direct summary access
assert_eq!(with_summary.summary(), Some("API token"));

// Compare with best_description (same result when only summary available)
assert_eq!(with_summary.best_description(), Some("API token"));

// Different behavior when both are present
let both = ReferenceMetadata::new(
    Some("Token".to_string()),      // summary
    Some("Auth token".to_string())  // description
);
assert_eq!(both.summary(), Some("Token"));            // Just summary
assert_eq!(both.best_description(), Some("Auth token")); // Prefers description
§Returns
  • Some(&str) - Reference summary if available
  • None - No summary in reference metadata
Source

pub fn merge_with_description( &self, existing_desc: Option<&str>, prepend_summary: bool, ) -> Option<String>

Merge reference metadata with existing description using OpenAPI 3.1 precedence rules

This method implements the sophisticated fallback mechanism for combining contextual reference metadata with general schema descriptions. It follows the OpenAPI 3.1 semantic hierarchy where contextual information takes precedence over generic schema documentation.

§Fallback Mechanism

The method implements a strict precedence hierarchy:

§Priority 1: Reference Description (Highest)
  • Source: $ref.description field from OpenAPI 3.1 reference object
  • Semantic: Contextual, usage-specific description for this particular reference
  • Behavior: Always takes precedence, ignoring all other descriptions
  • Rationale: Human-authored contextual information is most valuable for tool users
§Priority 2: Reference Summary (Medium)
  • Source: $ref.summary field from OpenAPI 3.1 reference object
  • Semantic: Brief contextual summary for this particular reference
  • Behavior: Used when no reference description is available
  • Special Case: When prepend_summary=true and existing description differs, combines summary with existing description using double newline separator
§Priority 3: Schema Description (Lower)
  • Source: description field from the resolved schema object
  • Semantic: General, reusable documentation about the schema itself
  • Behavior: Only used as fallback when no reference metadata is available
  • Rationale: Generic schema docs are less valuable than contextual reference docs
§Priority 4: No Description (Lowest)
  • Behavior: Returns None when no description sources are available
  • Impact: Caller should provide appropriate fallback behavior
§Implementation Details

The method uses pattern matching on a tuple of (reference_description, reference_summary, schema_description) to implement the precedence hierarchy efficiently. This ensures all possible combinations are handled explicitly and correctly.

§Examples
use rmcp_openapi::tool_generator::ReferenceMetadata;

let ref_meta = ReferenceMetadata::new(
    Some("API Key".to_string()), // summary
    Some("Authentication token for secure API access".to_string()) // description
);

// Reference description wins (Priority 1)
assert_eq!(
    ref_meta.merge_with_description(Some("Generic token schema"), false),
    Some("Authentication token for secure API access".to_string())
);

// Reference summary used when no description (Priority 2)
let summary_only = ReferenceMetadata::new(Some("API Key".to_string()), None);
assert_eq!(
    summary_only.merge_with_description(Some("Generic token schema"), false),
    Some("API Key".to_string())
);

// Schema description as fallback (Priority 3)
let empty_ref = ReferenceMetadata::new(None, None);
assert_eq!(
    empty_ref.merge_with_description(Some("Generic token schema"), false),
    Some("Generic token schema".to_string())
);

// Summary takes precedence via best_description() (no prepending when summary is available)
assert_eq!(
    summary_only.merge_with_description(Some("Different description"), true),
    Some("API Key".to_string())
);
§Arguments
  • existing_desc - Existing description from the resolved schema object
  • prepend_summary - Whether to prepend reference summary to existing description when no reference description is available (used for special formatting cases)
§Returns
  • Some(String) - Enhanced description following precedence hierarchy
  • None - No description sources available (caller should handle fallback)
Source

pub fn enhance_parameter_description( &self, param_name: &str, existing_desc: Option<&str>, ) -> Option<String>

Create enhanced parameter descriptions following OpenAPI 3.1 precedence hierarchy

This method generates parameter descriptions specifically tailored for MCP tools by combining reference metadata with parameter names using the OpenAPI 3.1 precedence rules. Unlike general description merging, this method always includes the parameter name for clarity in tool interfaces.

§Parameter Description Hierarchy

The method follows the same precedence hierarchy as merge_with_description() but formats the output specifically for parameter documentation:

§Priority 1: Reference Description (Highest)
  • Format: "{param_name}: {reference_description}"
  • Source: $ref.description field from OpenAPI 3.1 reference object
  • Example: "petId: Unique identifier for the pet in the store"
  • Behavior: Always used when available, providing contextual parameter meaning
§Priority 2: Reference Summary (Medium)
  • Format: "{param_name}: {reference_summary}"
  • Source: $ref.summary field from OpenAPI 3.1 reference object
  • Example: "petId: Pet identifier"
  • Behavior: Used when no reference description is available
§Priority 3: Schema Description (Lower)
  • Format: "{existing_description}" (without parameter name prefix)
  • Source: description field from the parameter’s schema object
  • Example: "A unique identifier for database entities"
  • Behavior: Used only when no reference metadata is available
  • Note: Does not prepend parameter name to preserve original schema documentation
§Priority 4: Generated Fallback (Lowest)
  • Format: "{param_name} parameter"
  • Source: Auto-generated from parameter name
  • Example: "petId parameter"
  • Behavior: Always provides a description, ensuring tools have meaningful parameter docs
§Design Rationale

This method addresses the specific needs of MCP tool parameter documentation:

  1. Contextual Clarity: Reference metadata provides usage-specific context rather than generic schema documentation
  2. Parameter Name Integration: Higher priority items include parameter names for immediate clarity in tool interfaces
  3. Guaranteed Output: Always returns a description, ensuring no parameter lacks documentation in the generated MCP tools
  4. Semantic Formatting: Different formatting for different priority levels maintains consistency while respecting original schema documentation
§Examples
use rmcp_openapi::tool_generator::ReferenceMetadata;

// Reference description takes precedence
let with_desc = ReferenceMetadata::new(
    Some("Pet ID".to_string()),
    Some("Unique identifier for pet in the store".to_string())
);
assert_eq!(
    with_desc.enhance_parameter_description("petId", Some("Generic ID field")),
    Some("petId: Unique identifier for pet in the store".to_string())
);

// Reference summary when no description
let with_summary = ReferenceMetadata::new(Some("Pet ID".to_string()), None);
assert_eq!(
    with_summary.enhance_parameter_description("petId", Some("Generic ID field")),
    Some("petId: Pet ID".to_string())
);

// Schema description fallback (no name prefix)
let empty_ref = ReferenceMetadata::new(None, None);
assert_eq!(
    empty_ref.enhance_parameter_description("petId", Some("Generic ID field")),
    Some("Generic ID field".to_string())
);

// Generated fallback ensures always returns description
assert_eq!(
    empty_ref.enhance_parameter_description("petId", None),
    Some("petId parameter".to_string())
);

Trait Implementations§

Source§

impl Clone for ReferenceMetadata

Source§

fn clone(&self) -> ReferenceMetadata

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ReferenceMetadata

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ReferenceMetadata

Source§

fn default() -> ReferenceMetadata

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,