API Reference

This page contains the complete API reference for ModelContextProtocol.jl.

Base.convertMethod
convert(::Type{URI}, s::String) -> URI

Convert a string to a URI object.

Arguments

  • s::String: The string to convert

Returns

  • URI: The resulting URI object
source
Logging.handle_messageMethod
Logging.handle_message(logger::MCPLogger, level, message, _module, group, id, filepath, line; kwargs...) -> Nothing

Format and output log messages according to the MCP protocol format.

Arguments

  • logger::MCPLogger: The MCP logger instance
  • level: The log level of the message
  • message: The log message content
  • _module: The module where the log was generated
  • group: The log group
  • id: The log message ID
  • filepath: The source file path
  • line: The source line number
  • kwargs...: Additional contextual information to include in the log

Returns

  • Nothing: Function writes to the logger stream but doesn't return a value
source
ModelContextProtocol.auto_register!Method
auto_register!(server::Server, dir::AbstractString) -> Server

Automatically register MCP components found in the specified directory structure.

Arguments

  • server::Server: The server to register components with
  • dir::AbstractString: Root directory containing component subdirectories

Directory Structure

  • dir/tools/: Contains tool definition files
  • dir/resources/: Contains resource definition files
  • dir/prompts/: Contains prompt definition files

Each subdirectory is optional. Files should be .jl files containing component definitions.

Returns

  • Server: The updated server instance for method chaining
source
ModelContextProtocol.capabilities_to_protocolMethod
capabilities_to_protocol(capabilities::Vector{Capability}, server::Server) -> Dict{String,Any}

Convert server capabilities to the initialization response format required by the MCP protocol.

Arguments

  • capabilities::Vector{Capability}: List of server capabilities.
  • server::Server: The server containing tools and resources.

Returns

  • Dict{String,Any}: Protocol-formatted capabilities dictionary including available tools and resources.
source
ModelContextProtocol.convert_to_content_typeMethod
convert_to_content_type(result::Any, return_type::Type) -> Content

Convert various return types to the appropriate MCP Content type.

Arguments

  • result::Any: The result value to convert
  • return_type::Type: The target Content type to convert to

Returns

  • Content: The converted Content object or the original result if no conversion is applicable
source
ModelContextProtocol.create_init_responseMethod
create_init_response(server::Server, protocol_version::String) -> InitializeResult

Create the initialization response for an MCP server.

Arguments

  • server::Server: The server to create the response for.
  • protocol_version::String: MCP protocol version string.

Returns

  • InitializeResult: Initialization response including server capabilities and info.
source
ModelContextProtocol.default_capabilitiesMethod
default_capabilities() -> Vector{Capability}

Create the default set of server capabilities for an MCP server.

Returns

  • Vector{Capability}: Default capabilities including resources, tools, and prompts
source
ModelContextProtocol.get_params_typeMethod
get_params_type(method::String) -> Union{Type,Nothing}

Get the appropriate parameter type for a given JSON-RPC method name.

Arguments

  • method::String: The JSON-RPC method name

Returns

  • Union{Type,Nothing}: The Julia type to use for parsing parameters, or nothing if no specific type is defined
source
ModelContextProtocol.get_result_typeMethod
get_result_type(id::RequestId) -> Union{Type{<:ResponseResult},Nothing}

Get the expected result type for a response based on the request ID.

Arguments

  • id::RequestId: The request ID to look up

Returns

  • Union{Type{<:ResponseResult},Nothing}: The expected response result type, or nothing if not known

Note: This is a placeholder that needs to be implemented with request tracking.

source
ModelContextProtocol.handle_call_toolMethod
handle_call_tool(ctx::RequestContext, params::CallToolParams) -> HandlerResult

Handle requests to call a specific tool with the provided parameters.

Arguments

  • ctx::RequestContext: The current request context
  • params::CallToolParams: Parameters containing the tool name and arguments

Returns

  • HandlerResult: Contains either the tool execution results or an error if the tool is not found or execution fails
source
ModelContextProtocol.handle_initializeMethod
handle_initialize(ctx::RequestContext, params::InitializeParams) -> HandlerResult

Handle MCP protocol initialization requests by setting up the server and returning capabilities.

Arguments

  • ctx::RequestContext: The current request context
  • params::InitializeParams: The initialization parameters from the client

Returns

  • HandlerResult: Contains the server's capabilities and configuration
source
ModelContextProtocol.handle_list_promptsMethod
handle_list_prompts(ctx::RequestContext, params::ListPromptsParams) -> HandlerResult

Handle requests to list available prompts on the MCP server.

Arguments

  • ctx::RequestContext: The current request context
  • params::ListPromptsParams: Parameters for the list request (including optional cursor)

Returns

  • HandlerResult: Contains information about all available prompts
source
ModelContextProtocol.handle_list_resourcesMethod
handle_list_resources(ctx::RequestContext, params::ListResourcesParams) -> HandlerResult

Handle requests to list all available resources on the MCP server.

Arguments

  • ctx::RequestContext: The current request context
  • params::ListResourcesParams: Parameters for the list request (including optional cursor)

Returns

  • HandlerResult: Contains information about all registered resources
source
ModelContextProtocol.handle_list_toolsMethod
handle_list_tools(ctx::RequestContext, params::ListToolsParams) -> HandlerResult

Handle requests to list all available tools on the MCP server.

Arguments

  • ctx::RequestContext: The current request context
  • params::ListToolsParams: Parameters for the list request (including optional cursor)

Returns

  • HandlerResult: Contains information about all registered tools
source
ModelContextProtocol.handle_notificationMethod
handle_notification(ctx::RequestContext, notification::JSONRPCNotification) -> Nothing

Process notification messages from clients that don't require responses.

Arguments

  • ctx::RequestContext: The current request context
  • notification::JSONRPCNotification: The notification to process

Returns

  • Nothing: Notifications don't generate responses
source
ModelContextProtocol.handle_pingMethod
handle_ping(ctx::RequestContext, params::Nothing) -> HandlerResult

Handle MCP protocol ping requests.

Arguments

  • ctx::RequestContext: The current request context
  • params::Nothing: The ping parameters does not contain any data

Returns

  • HandlerResult: Ping returns an empty response payload
source
ModelContextProtocol.handle_read_resourceMethod
handle_read_resource(ctx::RequestContext, params::ReadResourceParams) -> HandlerResult

Handle requests to read content from a specific resource by URI.

Arguments

  • ctx::RequestContext: The current request context
  • params::ReadResourceParams: Parameters containing the URI of the resource to read

Returns

  • HandlerResult: Contains either the resource contents or an error if the resource is not found or cannot be read
source
ModelContextProtocol.handle_requestMethod
handle_request(server::Server, request::Request) -> Response

Process an MCP protocol request and route it to the appropriate handler based on the request method.

Arguments

  • server::Server: The MCP server instance handling the request
  • request::Request: The parsed JSON-RPC request to process

Behavior

This function creates a request context, then dispatches the request to the appropriate handler based on the request method. Supported methods include:

  • initialize: Server initialization
  • resources/list: List available resources
  • resources/read: Read a specific resource
  • tools/list: List available tools
  • tools/call: Invoke a specific tool
  • prompts/list: List available prompts
  • prompts/get: Get a specific prompt

If an unknown method is received, a METHODNOTFOUND error is returned. Any exceptions thrown during processing are caught and converted to INTERNAL_ERROR responses.

Returns

  • Response: Either a successful response or an error response depending on the handler result
source
ModelContextProtocol.init_loggingFunction
init_logging(level::LogLevel=Info) -> Nothing

Initialize logging for the MCP server with a custom MCP-formatted logger.

Arguments

  • level::LogLevel=Info: The minimum logging level to display

Returns

  • Nothing: Function sets the global logger but doesn't return a value
source
ModelContextProtocol.mcp_serverMethod
mcp_server(; name::String, version::String="2024-11-05", 
         tools::Union{Vector{MCPTool},MCPTool,Nothing}=nothing,
         resources::Union{Vector{MCPResource},MCPResource,Nothing}=nothing, 
         prompts::Union{Vector{MCPPrompt},MCPPrompt,Nothing}=nothing,
         description::String="", 
         capabilities::Vector{Capability}=default_capabilities(),
         auto_register_dir::Union{String,Nothing}=nothing) -> Server

Primary entry point for creating and configuring a Model Context Protocol (MCP) server.

Arguments

  • name::String: Unique identifier for the server instance
  • version::String: Server implementation version
  • tools: Tools to expose to the model
  • resources: Resources available to the model
  • prompts: Predefined prompts for the model
  • description::String: Optional server description
  • capabilities::Vector{Capability}: Server capability configuration
  • auto_register_dir: Directory to auto-register components from

Returns

  • Server: A configured server instance ready to handle MCP client connections

Example

server = mcp_server(
    name = "my-server",
    description = "Demo server with time tool",
    tools = MCPTool(
        name = "get_time",
        description = "Get current time",
        parameters = [],
        handler = args -> Dates.format(now(), "HH:MM:SS")
    )
)
start!(server)
source
ModelContextProtocol.merge_capabilitiesMethod
merge_capabilities(base::Vector{Capability}, override::Vector{Capability}) -> Vector{Capability}

Merge two sets of capabilities, with the override set taking precedence.

Arguments

  • base::Vector{Capability}: Base set of capabilities.
  • override::Vector{Capability}: Override capabilities that take precedence.

Returns

  • Vector{Capability}: Merged set of capabilities.
source
ModelContextProtocol.normalize_pathMethod
normalize_path(path::String) -> String

Convert paths to absolute form, resolving relative paths against the project root.

Arguments

  • path::String: The path to normalize

Returns

  • String: Absolute, normalized path with all symbolic links resolved
source
ModelContextProtocol.parse_error_responseMethod
parse_error_response(raw::JSON3.Object) -> Response

Parse a JSON-RPC error response object into a typed Response struct.

Arguments

  • raw::JSON3.Object: The parsed JSON object representing an error response

Returns

  • Response: A JSONRPCError with properly typed error information
source
ModelContextProtocol.parse_messageMethod
parse_message(json::String) -> MCPMessage

Parse a JSON-RPC message string into the appropriate typed message object.

Arguments

  • json::String: The raw JSON-RPC message string

Returns

  • MCPMessage: A typed MCPMessage subtype (JSONRPCRequest, JSONRPCResponse, JSONRPCNotification, or JSONRPCError)
source
ModelContextProtocol.parse_notificationMethod
parse_notification(raw::JSON3.Object) -> Notification

Parse a JSON-RPC notification object into a typed Notification struct.

Arguments

  • raw::JSON3.Object: The parsed JSON object representing a notification

Returns

  • Notification: A JSONRPCNotification with properly typed parameters if possible
source
ModelContextProtocol.parse_requestMethod
parse_request(raw::JSON3.Object) -> Request

Parse a JSON-RPC request object into a typed Request struct.

Arguments

  • raw::JSON3.Object: The parsed JSON object representing a request

Returns

  • Request: A JSONRPCRequest with properly typed parameters based on the method
source
ModelContextProtocol.parse_success_responseMethod
parse_success_response(raw::JSON3.Object) -> Response

Parse a successful JSON-RPC response object into a typed Response struct.

Arguments

  • raw::JSON3.Object: The parsed JSON object representing a successful response

Returns

  • Response: A JSONRPCResponse with properly typed result if possible, or JSONRPCError if parsing fails
source
ModelContextProtocol.process_messageMethod
process_message(server::Server, state::ServerState, message::String) -> Union{String,Nothing}

Process an incoming JSON-RPC message and generate an appropriate response.

Arguments

  • server::Server: The MCP server instance
  • state::ServerState: Current server state
  • message::String: Raw JSON-RPC message to process

Returns

  • Union{String,Nothing}: A serialized response string or nothing for notifications
source
ModelContextProtocol.register!Function
register!(server::Server, component::Union{Tool,Resource,MCPPrompt}) -> Server

Register a tool, resource, or prompt with the MCP server.

Arguments

  • server::Server: The server to register the component with
  • component: The component to register (can be a tool, resource, or prompt)

Returns

  • Server: The server instance for method chaining
source
ModelContextProtocol.run_server_loopMethod
run_server_loop(server::Server, state::ServerState) -> Nothing

Execute the main server loop that reads JSON-RPC messages from stdin and writes responses to stdout. Implements optimized CPU usage by blocking on input rather than active polling.

Arguments

  • server::Server: The MCP server instance
  • state::ServerState: The server state object to track running status

Returns

  • Nothing: The function runs until interrupted or state.running becomes false
source
ModelContextProtocol.scan_mcp_componentsMethod
scan_mcp_components(dir::String) -> Dict{Symbol,Vector}

Scan a directory recursively for MCP component definitions (tools, resources, prompts).

Arguments

  • dir::String: Directory path to scan for component definitions

Returns

  • Dict{Symbol,Vector}: Dictionary of found components grouped by type
source
ModelContextProtocol.serialize_messageMethod
serialize_message(msg::MCPMessage) -> String

Serialize an MCP message object into a JSON-RPC compliant string.

Arguments

  • msg::MCPMessage: The message object to serialize (Request, Response, Notification, or Error)

Returns

  • String: A JSON string representation of the message following the JSON-RPC 2.0 specification
source
ModelContextProtocol.start!Method
start!(server::Server) -> Nothing

Start the MCP server, setting up logging and entering the main server loop.

Arguments

  • server::Server: The server instance to start

Returns

  • Nothing: The function returns after the server stops

Throws

  • ServerError: If the server is already running
source
ModelContextProtocol.stop!Method
stop!(server::Server) -> Nothing

Stop a running MCP server.

Arguments

  • server::Server: The server instance to stop

Returns

  • Nothing: The function returns after setting the server to inactive

Throws

  • ServerError: If the server is not currently running
source
ModelContextProtocol.subscribe!Method
subscribe!(server::Server, uri::String, callback::Function) -> Server

Subscribe to updates for a specific resource identified by URI.

Arguments

  • server::Server: The server instance
  • uri::String: The resource URI to subscribe to
  • callback::Function: The function to call when the resource is updated

Returns

  • Server: The server instance for method chaining
source
ModelContextProtocol.to_protocol_formatMethod
to_protocol_format(cap::Capability) -> Dict{String,Any}

Convert an MCP capability to the JSON format expected by the MCP protocol.

Arguments

  • cap::Capability: The capability to convert.

Returns

  • Dict{String,Any}: Protocol-formatted capability dictionary.
source
ModelContextProtocol.unsubscribe!Method
unsubscribe!(server::Server, uri::String, callback::Function) -> Server

Remove a subscription for a specific resource URI and callback function.

Arguments

  • server::Server: The server instance
  • uri::String: The resource URI to unsubscribe from
  • callback::Function: The callback function to remove

Returns

  • Server: The server instance for method chaining
source
StructTypes.omitemptiesMethod
StructTypes.omitempties(::Type{ClientCapabilities}) -> Tuple{Symbol,Symbol,Symbol}

Specify which fields should be omitted from JSON serialization when they are empty or null.

Arguments

  • ::Type{ClientCapabilities}: The ClientCapabilities type

Returns

  • Tuple{Symbol,Symbol,Symbol}: Fields to omit when empty
source
StructTypes.omitemptiesMethod
StructTypes.omitempties(::Type{ListPromptsResult}) -> Tuple{Symbol}

Specify which fields should be omitted from JSON serialization when they are empty or null.

Arguments

  • ::Type{ListPromptsResult}: The ListPromptsResult type

Returns

  • Tuple{Symbol}: Fields to omit when empty
source
ModelContextProtocol.BlobResourceContentsType
BlobResourceContents(; uri::String, blob::Vector{UInt8}, mime_type::Union{String,Nothing}=nothing) <: ResourceContents

Binary contents for MCP resources.

Fields

  • uri::String: Unique identifier for the resource
  • blob::Vector{UInt8}: The binary content of the resource
  • mime_type::Union{String,Nothing}: Optional MIME type of the content
source
ModelContextProtocol.CallToolParamsType
CallToolParams(; name::String, arguments::Union{Dict{String,Any},Nothing}=nothing) <: RequestParams

Parameters for invoking a specific tool on an MCP server.

Fields

  • name::String: Name of the tool to call
  • arguments::Union{Dict{String,Any},Nothing}: Optional arguments to pass to the tool
source
ModelContextProtocol.CallToolResultType
CallToolResult(; content::Vector{Dict{String,Any}}, is_error::Bool=false) <: ResponseResult

Result returned from a tool invocation.

Fields

  • content::Vector{Dict{String,Any}}: Content produced by the tool
  • is_error::Bool: Whether the tool execution resulted in an error
source
ModelContextProtocol.CapabilityType
Capability

Abstract base type for all MCP protocol capabilities. Capabilities represent protocol features that servers can support. Concrete implementations define configuration for specific feature sets.

source
ModelContextProtocol.CapabilityResponseType
CapabilityResponse(; 
    listChanged::Bool=false, 
    subscribe::Union{Bool,Nothing}=nothing, 
    tools::Union{Dict{String,Any},Nothing}=nothing, 
    resources::Union{Vector{Dict{String,Any}},Nothing}=nothing)

Define response structure for capabilities including tool and resource listings.

Fields

  • listChanged::Bool: Whether listings can change during server lifetime.
  • subscribe::Union{Bool,Nothing}: Whether subscriptions are supported.
  • tools::Union{Dict{String,Any},Nothing}: Tool definitions by name.
  • resources::Union{Vector{Dict{String,Any}},Nothing}: Available resource listings.
source
ModelContextProtocol.ClientCapabilitiesType
ClientCapabilities(; experimental::Union{Dict{String,Dict{String,Any}},Nothing}=nothing,
                roots::Union{Dict{String,Bool},Nothing}=nothing,
                sampling::Union{Dict{String,Any},Nothing}=nothing)

Capabilities reported by an MCP client during initialization.

Fields

  • experimental::Union{Dict{String,Dict{String,Any}},Nothing}: Experimental features supported
  • roots::Union{Dict{String,Bool},Nothing}: Root directories client has access to
  • sampling::Union{Dict{String,Any},Nothing}: Sampling capabilities for model generation
source
ModelContextProtocol.ContentType
Content

Abstract base type for all content formats in the MCP protocol. Content can be exchanged between clients and servers in various formats.

source
ModelContextProtocol.EmbeddedResourceType
EmbeddedResource(; resource::Union{TextResourceContents, BlobResourceContents}, 
                annotations::Dict{String,Any}=Dict{String,Any}()) <: Content

Embedded resource content as defined in MCP schema.

Fields

  • type::String: Content type identifier (always "resource")
  • resource::Union{TextResourceContents, BlobResourceContents}: The embedded resource content
  • annotations::Dict{String,Any}: Optional metadata about the resource
source
ModelContextProtocol.ErrorInfoType
ErrorInfo(; code::Int, message::String, data::Union{Dict{String,Any},Nothing}=nothing)

Error information structure for JSON-RPC error responses.

Fields

  • code::Int: Numeric error code (predefined in ErrorCodes module)
  • message::String: Human-readable error description
  • data::Union{Dict{String,Any},Nothing}: Optional additional error details
source
ModelContextProtocol.GetPromptParamsType
GetPromptParams(; name::String, arguments::Union{Dict{String,String},Nothing}=nothing) <: RequestParams

Parameters for requesting a specific prompt from an MCP server.

Fields

  • name::String: Name of the prompt to retrieve
  • arguments::Union{Dict{String,String},Nothing}: Optional arguments to apply to the prompt template
source
ModelContextProtocol.GetPromptResultType
GetPromptResult(; description::String, messages::Vector{PromptMessage}) <: ResponseResult

Result returned from a get prompt request.

Fields

  • description::String: Description of the prompt
  • messages::Vector{PromptMessage}: The prompt messages with template variables replaced
source
ModelContextProtocol.HandlerResultType
HandlerResult(; response::Union{Response,Nothing}=nothing, 
            error::Union{ErrorInfo,Nothing}=nothing)

Represent the result of handling a request.

Fields

  • response::Union{Response,Nothing}: The response to send (if successful)
  • error::Union{ErrorInfo,Nothing}: Error information (if request failed)

A HandlerResult must contain either a response or an error, but not both.

source
ModelContextProtocol.ImageContentType
ImageContent(; data::Vector{UInt8}, mime_type::String, annotations::Dict{String,Any}=Dict{String,Any}()) <: Content

Image-based content for MCP protocol messages.

Fields

  • type::String: Content type identifier (always "image")
  • data::Vector{UInt8}: The binary image data
  • mime_type::String: MIME type of the image (e.g., "image/png")
  • annotations::Dict{String,Any}: Optional metadata about the content
source
ModelContextProtocol.ImplementationType
Implementation(; name::String="default-client", version::String="1.0.0")

Information about a client or server implementation of the MCP protocol.

Fields

  • name::String: Name of the implementation
  • version::String: Version string of the implementation
source
ModelContextProtocol.InitializeParamsType
InitializeParams(; capabilities::ClientCapabilities=ClientCapabilities(),
               clientInfo::Implementation=Implementation(),
               protocolVersion::String) <: RequestParams

Parameters for MCP protocol initialization requests.

Fields

  • capabilities::ClientCapabilities: Client capabilities being reported
  • clientInfo::Implementation: Information about the client implementation
  • protocolVersion::String: Version of the MCP protocol being used
source
ModelContextProtocol.InitializeResultType
InitializeResult(; serverInfo::Dict{String,Any}, capabilities::Dict{String,Any},
               protocolVersion::String, instructions::String="") <: ResponseResult

Result returned in response to MCP protocol initialization.

Fields

  • serverInfo::Dict{String,Any}: Information about the server implementation
  • capabilities::Dict{String,Any}: Server capabilities being reported
  • protocolVersion::String: Version of the MCP protocol being used
  • instructions::String: Optional usage instructions for clients
source
ModelContextProtocol.JSONRPCErrorType
JSONRPCError(; id::Union{RequestId,Nothing}, error::ErrorInfo) <: Response

JSON-RPC error response message returned when requests fail.

Fields

  • id::Union{RequestId,Nothing}: Identifier matching the request this is responding to, or null
  • error::ErrorInfo: Information about the error that occurred
source
ModelContextProtocol.JSONRPCNotificationType
JSONRPCNotification(; method::String, 
                   params::Union{RequestParams,Dict{String,Any}}) <: Notification

JSON-RPC notification message that does not expect a response.

Fields

  • method::String: Name of the notification method
  • params::Union{RequestParams,Dict{String,Any}}: Parameters for the notification
source
ModelContextProtocol.JSONRPCRequestType
JSONRPCRequest(; id::RequestId, method::String, 
             params::Union{RequestParams, Nothing}, 
             meta::RequestMeta=RequestMeta()) <: Request

JSON-RPC request message used to invoke methods on the server.

Fields

  • id::RequestId: Unique identifier for the request
  • method::String: Name of the method to invoke
  • params::Union{RequestParams, Nothing}: Parameters for the method
  • meta::RequestMeta: Additional metadata for the request
source
ModelContextProtocol.JSONRPCResponseType
JSONRPCResponse(; id::RequestId, result::Union{ResponseResult,Dict{String,Any}}) <: Response

JSON-RPC response message returned for successful requests.

Fields

  • id::RequestId: Identifier matching the request this is responding to
  • result::Union{ResponseResult,Dict{String,Any}}: Results of the method execution
source
ModelContextProtocol.ListPromptsParamsType
ListPromptsParams(; cursor::Union{String,Nothing}=nothing) <: RequestParams

Parameters for requesting a list of available prompts from an MCP server.

Fields

  • cursor::Union{String,Nothing}: Optional pagination cursor for long prompt lists
source
ModelContextProtocol.ListPromptsResultType
ListPromptsResult(; prompts::Vector{Dict{String,Any}}, 
                nextCursor::Union{String,Nothing}=nothing) <: ResponseResult

Result returned from a list prompts request.

Fields

  • prompts::Vector{Dict{String,Any}}: List of available prompts with their metadata
  • nextCursor::Union{String,Nothing}: Optional pagination cursor for fetching more prompts
source
ModelContextProtocol.ListResourcesParamsType
ListResourcesParams(; cursor::Union{String,Nothing}=nothing) <: RequestParams

Parameters for requesting a list of available resources from an MCP server.

Fields

  • cursor::Union{String,Nothing}: Optional pagination cursor for long resource lists
source
ModelContextProtocol.ListResourcesResultType
ListResourcesResult(; resources::Vector{Dict{String,Any}}, 
                  nextCursor::Union{String,Nothing}=nothing) <: ResponseResult

Result returned from a list resources request.

Fields

  • resources::Vector{Dict{String,Any}}: List of available resources with their metadata
  • nextCursor::Union{String,Nothing}: Optional pagination cursor for fetching more resources
source
ModelContextProtocol.ListToolsParamsType
ListToolsParams(; cursor::Union{String,Nothing}=nothing) <: RequestParams

Parameters for requesting a list of available tools from an MCP server.

Fields

  • cursor::Union{String,Nothing}: Optional pagination cursor for long tool lists
source
ModelContextProtocol.ListToolsResultType
ListToolsResult(; tools::Vector{Dict{String,Any}}, 
              nextCursor::Union{String,Nothing}=nothing) <: ResponseResult

Result returned from a list tools request.

Fields

  • tools::Vector{Dict{String,Any}}: List of available tools with their metadata
  • nextCursor::Union{String,Nothing}: Optional pagination cursor for fetching more tools
source
ModelContextProtocol.LoggingCapabilityType
LoggingCapability(; levels::Vector{String}=["info", "warn", "error"])

Configure logging-related capabilities for an MCP server.

Fields

  • levels::Vector{String}: Supported logging levels.
source
ModelContextProtocol.MCPLoggerType
MCPLogger(stream::IO=stderr, level::LogLevel=Info) -> MCPLogger

Create a new MCPLogger instance with specified stream and level.

Arguments

  • stream::IO=stderr: The output stream where log messages will be written
  • level::LogLevel=Info: The minimum logging level to display

Returns

  • MCPLogger: A new logger instance
source
ModelContextProtocol.MCPLoggerType
MCPLogger <: AbstractLogger

Define a custom logger for MCP server that formats messages according to protocol requirements.

Fields

  • stream::IO: The output stream for log messages
  • min_level::LogLevel: Minimum logging level to display
  • message_limits::Dict{Any,Int}: Message limit settings for rate limiting
source
ModelContextProtocol.MCPMessageType
MCPMessage

Abstract base type for all message types in the MCP protocol. Serves as the root type for requests, responses, and notifications.

source
ModelContextProtocol.MCPPromptType
MCPPrompt(; name::String, description::String="", 
        arguments::Vector{PromptArgument}=PromptArgument[], 
        messages::Vector{PromptMessage}=PromptMessage[])

Implement a prompt or prompt template as defined in the MCP schema. Prompts can include variables that are replaced with arguments when retrieved.

Fields

  • name::String: Unique identifier for the prompt
  • description::String: Human-readable description of the prompt's purpose
  • arguments::Vector{PromptArgument}: Arguments that this prompt accepts
  • messages::Vector{PromptMessage}: The sequence of messages in the prompt
source
ModelContextProtocol.MCPPromptMethod
MCPPrompt(name::String, description::String, arguments::Vector{PromptArgument}, text::String) -> MCPPrompt

Create a prompt with a single text message.

Arguments

  • name::String: Unique identifier for the prompt
  • description::String: Human-readable description
  • arguments::Vector{PromptArgument}: Arguments the prompt accepts
  • text::String: Text content for the prompt message

Returns

  • MCPPrompt: A new prompt with a single user message containing the text
source
ModelContextProtocol.MCPResourceType
MCPResource(; uri, name::String, description::String="",
          mime_type::String="application/json", data_provider::Function,
          annotations::Dict{String,Any}=Dict{String,Any}()) <: Resource

Implement a resource that clients can access in the MCP protocol. Resources represent data that can be read by models and tools.

Fields

  • uri::URI: Unique identifier for the resource
  • name::String: Human-readable name for the resource
  • description::String: Detailed description of the resource
  • mime_type::String: MIME type of the resource data
  • data_provider::Function: Function that provides the resource data when called
  • annotations::Dict{String,Any}: Additional metadata for the resource
source
ModelContextProtocol.MCPResourceMethod
MCPResource(; uri, name, description="", mime_type="application/json", 
          data_provider, annotations=Dict{String,Any}()) -> MCPResource

Create a resource with automatic URI conversion from strings.

Arguments

  • uri: String or URI identifier for the resource
  • name: Human-readable name for the resource
  • description: Detailed description
  • mime_type: MIME type of the resource
  • data_provider: Function that returns the resource data when called
  • annotations: Additional metadata for the resource

Returns

  • MCPResource: A new resource with the provided configuration
source
ModelContextProtocol.MCPToolType
MCPTool(; name::String, description::String, parameters::Vector{ToolParameter},
      handler::Function, return_type::Type{<:Content}=TextContent) <: Tool

Implement a tool that can be invoked by clients in the MCP protocol.

Fields

  • name::String: Unique identifier for the tool
  • description::String: Human-readable description of the tool's purpose
  • parameters::Vector{ToolParameter}: Parameters that the tool accepts
  • handler::Function: Function that implements the tool's functionality
  • return_type::Type{<:Content}: Expected return type of the handler

Handler Return Types

The tool handler can return various types which are automatically converted:

  • An instance of the specified Content type (TextContent, ImageContent, etc.)
  • A Dict (automatically converted to JSON and wrapped in TextContent)
  • A String (automatically wrapped in TextContent)
  • A Tuple{Vector{UInt8}, String} (automatically wrapped in ImageContent)
source
ModelContextProtocol.NotificationType
Notification <: MCPMessage

Abstract base type for one-way notifications in the MCP protocol. Notification messages don't expect a corresponding response.

source
ModelContextProtocol.ProgressType
Progress(; token::Union{String,Int}, current::Float64, 
        total::Union{Float64,Nothing}=nothing, message::Union{String,Nothing}=nothing)

Tracks progress of long-running operations in the MCP protocol.

Fields

  • token::Union{String,Int}: Unique identifier for the progress tracker
  • current::Float64: Current progress value
  • total::Union{Float64,Nothing}: Optional total expected value
  • message::Union{String,Nothing}: Optional status message
source
ModelContextProtocol.ProgressParamsType
ProgressParams(; progress_token::ProgressToken, progress::Float64,
             total::Union{Float64,Nothing}=nothing) <: RequestParams

Parameters for progress notifications during long-running operations.

Fields

  • progress_token::ProgressToken: Token identifying the operation being reported on
  • progress::Float64: Current progress value
  • total::Union{Float64,Nothing}: Optional total expected value
source
ModelContextProtocol.PromptArgumentType
PromptArgument(; name::String, description::String="", required::Bool=false)

Define an argument that a prompt template can accept.

Fields

  • name::String: The argument name (used in template placeholders)
  • description::String: Human-readable description of the argument
  • required::Bool: Whether the argument is required when using the prompt
source
ModelContextProtocol.PromptCapabilityType
PromptCapability(; list_changed::Bool=false)

Configure prompt-related capabilities for an MCP server.

Fields

  • list_changed::Bool: Whether server supports notifications when prompt listings change.
source
ModelContextProtocol.PromptMessageType
PromptMessage(; content::Union{TextContent, ImageContent, EmbeddedResource}, role::Role=user)

Represent a single message in a prompt template.

Fields

  • content::Union{TextContent, ImageContent, EmbeddedResource}: The content of the message
  • role::Role: Whether this message is from the user or assistant (defaults to user)
source
ModelContextProtocol.PromptMessageMethod
PromptMessage(content::Union{TextContent, ImageContent, EmbeddedResource}) -> PromptMessage

Create a prompt message with only content (role defaults to user).

Arguments

  • content::Union{TextContent, ImageContent, EmbeddedResource}: The message content

Returns

  • PromptMessage: A new prompt message with the default user role
source
ModelContextProtocol.ReadResourceResultType
ReadResourceResult(; contents::Vector{Dict{String,Any}}) <: ResponseResult

Result returned from a read resource request.

Fields

  • contents::Vector{Dict{String,Any}}: The contents of the requested resource
source
ModelContextProtocol.RequestType
Request <: MCPMessage

Abstract base type for client-to-server requests in the MCP protocol. Request messages expect a corresponding response from the server.

source
ModelContextProtocol.RequestContextType
RequestContext(; server::Server, request_id::Union{RequestId,Nothing}=nothing, 
             progress_token::Union{ProgressToken,Nothing}=nothing)

Store the current request context for MCP protocol handlers.

Fields

  • server::Server: The MCP server instance handling the request
  • request_id::Union{RequestId,Nothing}: The ID of the current request (if any)
  • progress_token::Union{ProgressToken,Nothing}: Optional token for progress reporting
source
ModelContextProtocol.RequestMetaType
RequestMeta(; progress_token::Union{ProgressToken,Nothing}=nothing)

Metadata for MCP protocol requests, including progress tracking information.

Fields

  • progress_token::Union{ProgressToken,Nothing}: Optional token for tracking request progress
source
ModelContextProtocol.RequestParamsType
RequestParams

Abstract base type for all parameter structures in MCP protocol requests. Concrete subtypes define parameters for specific request methods.

source
ModelContextProtocol.ResourceType
Resource

Abstract base type for all MCP resources. Resources represent data that can be read and accessed by clients. Concrete implementations define specific resource types and access methods.

source
ModelContextProtocol.ResourceCapabilityType
ResourceCapability(; list_changed::Bool=false, subscribe::Bool=false)

Configure resource-related capabilities for an MCP server.

Fields

  • list_changed::Bool: Whether server supports notifications when resource listings change.
  • subscribe::Bool: Whether server supports subscriptions to resource updates.
source
ModelContextProtocol.ResourceContentsType
ResourceContents

Abstract base type for contents of MCP resources. ResourceContents represent the actual data stored in resources. Concrete implementations define specific content formats (text, binary, etc.).

source
ModelContextProtocol.ResourceTemplateType
ResourceTemplate(; name::String, uri_template::String,
               mime_type::Union{String,Nothing}=nothing, description::String="")

Define a template for dynamically generating resources with parameterized URIs.

Fields

  • name::String: Name of the resource template
  • uri_template::String: Template string with placeholders for parameters
  • mime_type::Union{String,Nothing}: MIME type of the generated resources
  • description::String: Human-readable description of the template
source
ModelContextProtocol.ResponseType
Response <: MCPMessage

Abstract base type for server-to-client responses in the MCP protocol. Response messages are sent from the server in reply to client requests.

source
ModelContextProtocol.ResponseResultType
ResponseResult

Abstract base type for all result structures in MCP protocol responses. Concrete subtypes define result formats for specific response methods.

source
ModelContextProtocol.RoleType
Role

Enum representing roles in the MCP protocol.

Values

  • user: Content or messages from the user
  • assistant: Content or messages from the assistant
source
ModelContextProtocol.ServerType
Server(config::ServerConfig)

Represent a running MCP server instance that manages resources, tools, and prompts.

Fields

  • config::ServerConfig: Server configuration settings
  • resources::Vector{Resource}: Available resources
  • tools::Vector{Tool}: Available tools
  • prompts::Vector{MCPPrompt}: Available prompts
  • resource_templates::Vector{ResourceTemplate}: Available resource templates
  • subscriptions::DefaultDict{String,Vector{Subscription}}: Resource subscription registry
  • progress_trackers::Dict{Union{String,Int},Progress}: Progress tracking for operations
  • active::Bool: Whether the server is currently active

Constructor

  • Server(config::ServerConfig): Creates a new server with the specified configuration
source
ModelContextProtocol.ServerConfigType
ServerConfig(; name::String, version::String="1.0.0", 
           description::String="", capabilities::Vector{Capability}=Capability[],
           instructions::String="")

Define configuration settings for an MCP server instance.

Fields

  • name::String: The server name shown to clients
  • version::String: Server version string
  • description::String: Human-readable server description
  • capabilities::Vector{Capability}: Protocol capabilities supported by the server
  • instructions::String: Usage instructions for clients
source
ModelContextProtocol.ServerErrorType
ServerError(message::String) <: Exception

Exception type for MCP server-specific errors.

Fields

  • message::String: The error message describing what went wrong
source
ModelContextProtocol.ServerStateType
ServerState()

Track the internal state of an MCP server during operation.

Fields

  • initialized::Bool: Whether the server has been initialized by a client
  • running::Bool: Whether the server main loop is active
  • last_request_id::Int: Last used request ID for server-initiated requests
  • pending_requests::Dict{RequestId,String}: Map of request IDs to method names
source
ModelContextProtocol.SubscriptionType
Subscription(; uri::String, callback::Function, created_at::DateTime=now())

Represents subscriptions to resource updates in the MCP protocol.

Fields

  • uri::String: The URI of the subscribed resource
  • callback::Function: Function to call when the resource is updated
  • created_at::DateTime: When the subscription was created
source
ModelContextProtocol.TextContentType
TextContent(; text::String, annotations::Dict{String,Any}=Dict{String,Any}()) <: Content

Text-based content for MCP protocol messages.

Fields

  • type::String: Content type identifier (always "text")
  • text::String: The actual text content
  • annotations::Dict{String,Any}: Optional metadata about the content
source
ModelContextProtocol.TextResourceContentsType
TextResourceContents(; uri::String, text::String, mime_type::Union{String,Nothing}=nothing) <: ResourceContents

Text-based contents for MCP resources.

Fields

  • uri::String: Unique identifier for the resource
  • text::String: The text content of the resource
  • mime_type::Union{String,Nothing}: Optional MIME type of the content
source
ModelContextProtocol.ToolType
Tool

Abstract base type for all MCP tools. Tools represent operations that can be invoked by clients. Concrete implementations define specific tool functionality and parameters.

source
ModelContextProtocol.ToolCapabilityType
ToolCapability(; list_changed::Bool=false)

Configure tool-related capabilities for an MCP server.

Fields

  • list_changed::Bool: Whether server supports notifications when tool listings change.
source
ModelContextProtocol.ToolParameterType
ToolParameter(; name::String, description::String, type::String, required::Bool=false)

Define a parameter for an MCP tool.

Fields

  • name::String: The parameter name (used as the key in the params dictionary)
  • description::String: Human-readable description of the parameter
  • type::String: Type of the parameter as specified in the MCP schema (e.g., "string", "number", "boolean")
  • required::Bool: Whether the parameter is required for tool invocation
source