Module types

Module types 

Source
Expand description

§Types Module

Core type definitions for the Model Context Protocol (MCP).

This module provides all the fundamental types used throughout the MCP ecosystem, including tools, resources, prompts, and various request/response structures. These types are designed to be type-safe, serializable, and fully compliant with the MCP 2025-06-18 specification.

§Overview

The types module serves as the foundation for all MCP data structures and provides:

  • Tool Types: Tool definitions, calls, and results
  • Resource Types: Resource management and content handling
  • Prompt Types: Prompt generation and management
  • Client/Server Types: Information and capability structures
  • Notification Types: Progress, logging, and status updates
  • Utility Types: Common patterns like pagination and cursors

§Core Concepts

§Tools

Tools are the primary mechanism for extending MCP functionality:

  • Tool Definition: Schema, description, and metadata
  • Tool Call: Request to execute a tool with parameters
  • Tool Result: Response from tool execution

§Resources

Resources provide access to external data and content:

  • Resource Definition: URI, content type, and metadata
  • Resource Content: Actual data with MIME type information
  • Resource Templates: Reusable resource definitions

§Prompts

Prompts enable dynamic content generation:

  • Prompt Definition: Template with arguments and metadata
  • Prompt Content: Generated content with role information
  • Prompt Arguments: Parameters for prompt generation

§Modules

  • tools: Tool-related types including definitions, calls, and results
  • resources: Resource management types and content handling
  • prompts: Prompt generation and template management
  • client: Client information and capability structures
  • server: Server information and capability structures
  • notifications: Progress, logging, and status notification types
  • completion: Autocompletion and suggestion types
  • elicitation: User input collection and validation types
  • sampling: LLM sampling and message generation types
  • roots: Filesystem root and boundary management types

§Usage Examples

§Tool Definition and Usage

use ultrafast_mcp_core::types::{
    Tool, ToolCall, ToolResult, ToolContent,
    ListToolsRequest, ListToolsResponse
};
use ultrafast_mcp_core::types::prompts::{PromptArgument, PromptMessage};
use ultrafast_mcp_core::types::{PromptContent};

// Define a tool
let tool = Tool {
    name: "greet".to_string(),
    description: "Greet a person by name".to_string(),
    input_schema: serde_json::json!({
        "type": "object",
        "properties": {
            "name": {"type": "string"},
            "greeting": {"type": "string", "default": "Hello"}
        },
        "required": ["name"]
    }),
    output_schema: None,
    annotations: None,
};

// Create a tool call
let tool_call = ToolCall {
    name: "greet".to_string(),
    arguments: Some(serde_json::json!({
        "name": "Alice",
        "greeting": "Hello there"
    })),
};

// Create a tool result
let tool_result = ToolResult {
    content: vec![ToolContent::text("Hello there, Alice!".to_string())],
    is_error: Some(false),
};

§Resource Management

use ultrafast_mcp_core::types::{
    Resource, ResourceContent, ReadResourceRequest, ReadResourceResponse
};

// Define a resource
let resource = Resource {
    uri: "file:///path/to/document.txt".to_string(),
    name: "Document".to_string(),
    description: Some("A text document".to_string()),
    mime_type: Some("text/plain".to_string()),
};

// Create a read request
let read_request = ReadResourceRequest {
    uri: "file:///path/to/document.txt".to_string(),
};

// Create a read response
let read_response = ReadResourceResponse {
    contents: vec![ResourceContent::text("file:///path/to/document.txt".to_string(), "Document content".to_string())],
};

§Prompt Generation

use ultrafast_mcp_core::types::{
    Prompt, PromptContent, PromptRole, GetPromptRequest, GetPromptResponse
};

// Define a prompt
let prompt = Prompt {
    name: "summarize".to_string(),
    description: Some("Summarize text content".to_string()),
    arguments: Some(vec![
        ultrafast_mcp_core::types::prompts::PromptArgument::new("text".to_string()).required(true),
        ultrafast_mcp_core::types::prompts::PromptArgument::new("max_length".to_string()).required(false),
    ]),
};

// Create a prompt request
let prompt_request = GetPromptRequest {
    name: "summarize".to_string(),
    arguments: Some(serde_json::json!({
        "text": "Long text to summarize...",
        "max_length": 50
    })),
};

// Create a prompt response
let prompt_response = GetPromptResponse {
    messages: vec![ultrafast_mcp_core::types::prompts::PromptMessage::system(PromptContent::text("Summarize this text...".to_string()))],
    description: None,
};

§Client/Server Information

use ultrafast_mcp_core::types::{
    ClientInfo, ServerInfo, ServerCapabilities
};

// Client information
let client_info = ClientInfo {
    name: "example-client".to_string(),
    version: "1.0.0".to_string(),
    description: Some("An example MCP client".to_string()),
    authors: None,
    homepage: None,
    license: None,
    repository: None,
};

// Server information
let server_info = ServerInfo {
    name: "example-server".to_string(),
    version: "1.0.0".to_string(),
    description: Some("An example MCP server".to_string()),
    authors: None,
    homepage: None,
    license: None,
    repository: None,
};

// Capabilities
let server_capabilities = ServerCapabilities::default();

§Serialization

All types in this module support serialization and deserialization:

  • JSON Serialization: All types implement Serialize and Deserialize
  • Schema Generation: Automatic JSON Schema generation for validation
  • Type Safety: Compile-time guarantees for data structure correctness
  • Validation: Runtime validation of data against schemas

§Type Safety

The type system provides several safety guarantees:

  • Compile-time Validation: Type checking prevents many runtime errors
  • Schema Validation: Runtime validation ensures data correctness
  • Error Handling: Comprehensive error types for all failure modes
  • Null Safety: Optional fields are properly handled

§Performance Considerations

  • Efficient Serialization: Optimized JSON serialization/deserialization
  • Minimal Allocations: Smart use of references and owned data
  • Lazy Validation: Validation only when necessary
  • Memory Efficiency: Compact data structures where possible

§Thread Safety

All types are designed to be thread-safe:

  • Types implement Send + Sync where appropriate
  • Immutable by default for safety
  • Interior mutability where needed

§Extensibility

The type system is designed to be extensible:

  • New types can be added without breaking changes
  • Optional fields allow for backward compatibility
  • Schema evolution is supported
  • Custom validation rules can be added

Modules§

client
completion
Completion types for MCP 2025-06-18 protocol
elicitation
Elicitation types for MCP
notifications
Notification types for MCP 2025-06-18 protocol
prompts
resources
roots
Roots types for MCP
sampling
server
tools

Structs§

AlternativeModel
Alternative model that was considered
CancelledNotification
Cancellation notification for MCP 2025-06-18 protocol
ClientCapabilities
Client capabilities that can be negotiated during initialization
ClientCapabilityNotification
Client capability notification - sent when client capabilities change
ClientInfo
Client information
CompleteRequest
Completion request (MCP 2025-06-18 compliant)
CompleteResponse
Completion response
Completion
Completion result set
CompletionArgument
Completion argument (MCP 2025-06-18 compliant)
CompletionCapability
Completion capability for argument autocompletion
CompletionContext
Context for completion requests
CompletionDocumentation
Completion documentation
CompletionFilter
Filter criteria for completions
CompletionMetadata
Completion metadata
CompletionRange
Completion range
CompletionReference
Completion reference (MCP 2025-06-18 compliant)
CompletionStatistics
Completion statistics
CompletionValue
Individual completion value
ConnectionStatusNotification
Connection status notification
CostInfo
Cost information for the sampling request
ElicitationCapability
Elicitation capability for user input collection
ElicitationRequest
Server-initiated request for user input
ElicitationResponse
User response to elicitation request
EmbeddedResourceReference
Enhanced embedded resource reference for prompts
EmbeddedResourceValidator
Prompt embedded resource validator
GetPromptRequest
Get prompt request
GetPromptResponse
Get prompt response
HumanFeedback
Human feedback for sampling requests
HumanInTheLoopSettings
Human-in-the-loop settings
Implementation
Information about the implementation
ListPromptsRequest
List prompts request
ListPromptsResponse
List prompts response
ListResourceTemplatesRequest
ListResourceTemplatesResponse
List resource templates response
ListResourcesRequest
ListResourcesResponse
List resources response
ListRootsRequest
Request to list available roots
ListRootsResponse
Response containing available roots
ListToolsRequest
List tools request
ListToolsResponse
List tools response
LogLevelSetRequest
Log level set request - MCP 2025-06-18 compliant
LogLevelSetResponse
Log level set response - MCP 2025-06-18 compliant
LoggingCapability
Logging capability
LoggingMessageNotification
Logging message notification - MCP 2025-06-18 compliant
ModelCapability
Model capability information for intelligent selection
ModelHint
Model hint for sampling
ModelPerformanceRecord
Historical performance data for a model
ModelPreferences
Model preferences for sampling
ModelSelectionContext
Model selection context for intelligent choice
ModelSelectionResult
Result of model selection with reasoning
ModelSelector
Intelligent model selector that considers preferences and context
NotificationSettings
Notification settings for human-in-the-loop
PingRequest
Ping request for connection health monitoring
PingResponse
Ping response for connection health monitoring
PriorityScores
Calculated priority scores
ProgressNotification
Progress notification for MCP 2025-06-18 protocol
Prompt
Prompt definition
PromptArgument
Prompt argument definition
PromptMessage
Prompt message
PromptMessages
Helper for building prompt messages
PromptsCapability
Prompts capability
PromptsListChangedNotification
Prompts list changed notification
RateLimitNotification
Rate limit notification
ReadResourceRequest
ReadResourceResponse
Read resource response
RequestContext
Context information about the current request
RequestTimeoutNotification
Request timeout notification
ResolutionMetadata
Resource resolution metadata
Resource
Resource definition
ResourceContextInfo
Resource context information
ResourceInclusionOptions
Resource inclusion options
ResourceReference
Reference to a resource
ResourceResolution
Resource resolution result
ResourceSecurityPolicy
Security policy for embedded resources
ResourceTemplate
Resource template definition (for parameterized resources)
ResourceUpdatedNotification
Resource updated notification
ResourcesCapability
Resources capability
ResourcesListChangedNotification
Resources list changed notification
Root
A filesystem root that defines boundary for file operations
RootListChangedNotification
Notification sent when the list of roots changes
RootSecurityConfig
Security configuration for a root
RootSecurityValidator
Comprehensive security validator for roots
RootsCapability
Roots capability for filesystem boundary management
RootsListChangedNotification
Notification sent when the list of roots changes
SamplingCapability
Sampling capability for LLM completions
SamplingContext
Context information for sampling requests
SamplingMessage
Sampling message
SamplingRequest
Enhanced sampling request with context and human-in-the-loop support
SamplingResponse
Enhanced sampling response with human-in-the-loop support
SelectionFactor
Factors that influenced model selection
SelectionReasoning
Detailed reasoning for model selection
ServerCapabilities
Server capabilities that can be advertised during initialization
ServerCapabilityNotification
Server capability notification - sent when server capabilities change
ServerContextInfo
Server context information
ServerInfo
Information about the server
SetRootsRequest
Request to set/update the list of roots
SetRootsResponse
Response to a set roots request
SubscribeRequest
Subscribe to resource request
SubscribeResponse
Response to a resource subscription request
TemplateExpansionOptions
Template expansion options
TemplateMetadata
Template metadata
TemplateSecurityPolicy
Template security policy
Tool
Tool definition
ToolAnnotations
Tool annotations provide metadata about tool behavior
ToolCallRequest
Tool call request
ToolCallResponse
Tool call response
ToolContextInfo
Tool context information
ToolsCapability
Tools capability
ToolsListChangedNotification
Tools list changed notification
UnsubscribeRequest
Unsubscribe from resource request
UserPreferences
User preferences for sampling
VariableNamePolicy
Variable name policy
_OldRootsListChangedNotification
Roots list changed notification

Enums§

ApprovalStatus
Human-in-the-loop approval status
CompletionKind
Completion kind
ConnectionStatus
Connection status enum
DocumentationKind
Documentation kind
ElicitationAction
User response actions
IncludeContext
Context inclusion options for sampling requests
LogLevel
Log level - RFC 5424 compliant levels
Modality
Supported input/output modalities
PromptContent
Prompt content
PromptRole
Prompt message role
RateLimitType
Rate limit type
ResourceContent
Resource content
ResourceResolutionError
Resource resolution errors
RootOperation
Operation type for security validation
RootSecurityError
SamplingContent
Sampling content
SamplingRole
Sampling message role
ScoringStrategy
Strategy for scoring and ranking models
StopReason
Stop reason for sampling responses
TemplateError
Template expansion errors
ToolContent
Tool content (result of tool execution)

Functions§

validate_path_within_root
Legacy function for backward compatibility

Type Aliases§

CreateMessageRequest
Type aliases for consistency
CreateMessageResponse
ToolCall
Type aliases for consistency
ToolResult