API Reference
ModelContextProtocol.FEATURE_VERSIONSModelContextProtocol.LATEST_PROTOCOL_VERSIONModelContextProtocol.MCP_LOG_LEVELSModelContextProtocol.SUPPORTED_PROTOCOL_VERSIONSModelContextProtocol.AudioContentModelContextProtocol.AuthMiddlewareModelContextProtocol.AuthProviderModelContextProtocol.AuthResultModelContextProtocol.AuthenticatedUserModelContextProtocol.BlobResourceContentsModelContextProtocol.CallToolParamsModelContextProtocol.CallToolResultModelContextProtocol.CancelTaskParamsModelContextProtocol.CapabilityResponseModelContextProtocol.ClientCapabilitiesModelContextProtocol.ContentModelContextProtocol.EmbeddedResourceModelContextProtocol.ErrorInfoModelContextProtocol.GetPromptParamsModelContextProtocol.GetPromptResultModelContextProtocol.GetTaskParamsModelContextProtocol.GitHubOAuthValidatorModelContextProtocol.HttpTransportModelContextProtocol.ImageContentModelContextProtocol.ImplementationModelContextProtocol.InitializeParamsModelContextProtocol.InitializeResultModelContextProtocol.IntrospectionValidatorModelContextProtocol.JSONRPCErrorModelContextProtocol.JSONRPCNotificationModelContextProtocol.JSONRPCRequestModelContextProtocol.JSONRPCResponseModelContextProtocol.JWTValidatorModelContextProtocol.ListPromptsParamsModelContextProtocol.ListPromptsResultModelContextProtocol.ListResourceTemplatesParamsModelContextProtocol.ListResourcesParamsModelContextProtocol.ListResourcesResultModelContextProtocol.ListTasksParamsModelContextProtocol.ListToolsParamsModelContextProtocol.ListToolsResultModelContextProtocol.LoggingCapabilityModelContextProtocol.MCPIconModelContextProtocol.MCPLoggerModelContextProtocol.MCPLoggerModelContextProtocol.MCPPromptModelContextProtocol.MCPPromptModelContextProtocol.MCPResourceModelContextProtocol.MCPResourceModelContextProtocol.MCPToolModelContextProtocol.OAuthConfigModelContextProtocol.ProgressParamsModelContextProtocol.PromptArgumentModelContextProtocol.PromptCapabilityModelContextProtocol.PromptMessageModelContextProtocol.PromptMessageModelContextProtocol.ProtectedResourceMetadataModelContextProtocol.QueuedHttpRequestModelContextProtocol.ReadResourceParamsModelContextProtocol.ReadResourceResultModelContextProtocol.RequestMetaModelContextProtocol.ResourceCapabilityModelContextProtocol.ResourceContentsModelContextProtocol.ResourceLinkModelContextProtocol.ResourceTemplateModelContextProtocol.ServerModelContextProtocol.SetLevelParamsModelContextProtocol.SimpleTokenValidatorModelContextProtocol.StdioTransportModelContextProtocol.TaskCapabilityModelContextProtocol.TaskResultParamsModelContextProtocol.TextContentModelContextProtocol.TextResourceContentsModelContextProtocol.TokenValidatorModelContextProtocol.ToolCapabilityModelContextProtocol.ToolParameterModelContextProtocol.TransportModelContextProtocol.TransportErrorLogging.handle_messageModelContextProtocol.authenticate_requestModelContextProtocol.auto_register!ModelContextProtocol.broadcast_to_sseModelContextProtocol.capabilities_to_protocolModelContextProtocol.capture_response_routeModelContextProtocol.capture_response_routeModelContextProtocol.clear_cache!ModelContextProtocol.closeModelContextProtocol.closeModelContextProtocol.closeModelContextProtocol.connectModelContextProtocol.connectModelContextProtocol.content2dictModelContextProtocol.create_auth_middlewareModelContextProtocol.create_github_authModelContextProtocol.create_github_resource_metadataModelContextProtocol.create_init_responseModelContextProtocol.create_protected_resource_metadataModelContextProtocol.create_simple_authModelContextProtocol.default_capabilitiesModelContextProtocol.deliver_responseModelContextProtocol.deliver_responseModelContextProtocol.disable_authModelContextProtocol.end_responseModelContextProtocol.extract_bearer_tokenModelContextProtocol.flushModelContextProtocol.flushModelContextProtocol.format_sse_eventModelContextProtocol.generate_session_idModelContextProtocol.get_params_typeModelContextProtocol.get_result_typeModelContextProtocol.handle_requestModelContextProtocol.handle_sse_streamModelContextProtocol.init_loggingModelContextProtocol.is_auth_enabledModelContextProtocol.is_connectedModelContextProtocol.is_connectedModelContextProtocol.is_connectedModelContextProtocol.is_supported_versionModelContextProtocol.is_valid_session_idModelContextProtocol.mcp_level_to_juliaModelContextProtocol.mcp_serverModelContextProtocol.mcp_serverModelContextProtocol.merge_capabilitiesModelContextProtocol.negotiate_versionModelContextProtocol.normalize_pathModelContextProtocol.parse_error_responseModelContextProtocol.parse_messageModelContextProtocol.parse_notificationModelContextProtocol.parse_requestModelContextProtocol.parse_success_responseModelContextProtocol.pending_auth_contextModelContextProtocol.pending_auth_contextModelContextProtocol.process_messageModelContextProtocol.read_messageModelContextProtocol.read_messageModelContextProtocol.read_messageModelContextProtocol.register!ModelContextProtocol.run_server_loopModelContextProtocol.scan_mcp_componentsModelContextProtocol.send_notificationModelContextProtocol.send_notificationModelContextProtocol.send_progressModelContextProtocol.serialize_messageModelContextProtocol.set_negotiated_version!ModelContextProtocol.set_negotiated_version!ModelContextProtocol.start!ModelContextProtocol.start!ModelContextProtocol.stop!ModelContextProtocol.stop!ModelContextProtocol.subscribe!ModelContextProtocol.subscribe!ModelContextProtocol.supportsModelContextProtocol.task_cancelledModelContextProtocol.to_protocol_formatModelContextProtocol.unsubscribe!ModelContextProtocol.unsubscribe!ModelContextProtocol.validate_tokenModelContextProtocol.validate_tokenModelContextProtocol.write_messageModelContextProtocol.write_messageModelContextProtocol.write_messageStructTypes.namesStructTypes.omitemptiesStructTypes.omitemptiesStructTypes.omitempties
Primary Interface
ModelContextProtocol.mcp_server — Function
mcp_server(; name::String, version::String="1.0.0",
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,
title::Union{String,Nothing}=nothing,
icons::Union{Vector{MCPIcon},Nothing}=nothing) -> ServerPrimary entry point for creating and configuring a Model Context Protocol (MCP) server.
Arguments
name::String: Unique identifier for the server instanceversion::String: Your server implementation version (defaults to "1.0.0") - YOUR server's version, not the MCP protocol versiontools: Tools to expose to the modelresources: Resources available to the modelresource_templates: Parameterized resource families (RFC 6570{var}URI templates with a provider; advertised viaresources/templates/list)prompts: Predefined prompts for the modeldescription::String: Optional server descriptioncapabilities::Vector{Capability}: Server capability configurationauto_register_dir: Directory to auto-register components fromtitle::Union{String,Nothing}: Optional human-friendly display name for the servericons::Union{Vector{MCPIcon},Nothing}: Optional icons for the server
Returns
Server: A configured server instance ready to handle MCP client connections
Example
server = mcp_server(
name = "my-server",
version = "1.0.0", # Your server version
title = "My MCP 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)Server Operations
ModelContextProtocol.start! — Function
start!(server::Server; transport::Union{Transport,Nothing}=nothing) -> NothingStart the MCP server, setting up logging and entering the main server loop.
Arguments
server::Server: The server instance to starttransport::Union{Transport,Nothing}: Optional transport to use. If not provided, uses StdioTransport
Returns
Nothing: The function returns after the server stops
Throws
ServerError: If the server is already running
ModelContextProtocol.stop! — Function
stop!(server::Server) -> NothingStop 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
ModelContextProtocol.register! — Function
register!(server::Server, component::Union{Tool,Resource,MCPPrompt}) -> ServerRegister a tool, resource, or prompt with the MCP server.
Arguments
server::Server: The server to register the component withcomponent: The component to register (can be a tool, resource, or prompt)
Returns
Server: The server instance for method chaining
Component Types
Tools
ModelContextProtocol.MCPTool — Type
MCPTool(; name::String, description::String, parameters::Vector{ToolParameter}=ToolParameter[],
input_schema::Union{Nothing,AbstractDict}=nothing, handler::Function,
return_type::Type=Vector{Content}) <: ToolImplement a tool that can be invoked by clients in the MCP protocol.
Fields
name::String: Unique identifier for the tooldescription::String: Human-readable description of the tool's purposeparameters::Vector{ToolParameter}: Simple parameters (ignored if input_schema is provided)input_schema::Union{Nothing,AbstractDict}: Raw JSON Schema for complex parameter typeshandler::Function: Function that implements the tool's functionalityreturn_type::Type: Expected return type of the handler (defaults to Vector{Content})annotations::Union{Nothing,Dict{String,Any}}: Optional tool annotations (behavioral hints for clients), e.g.Dict("readOnlyHint" => true, "destructiveHint" => false, "idempotentHint" => true, "openWorldHint" => false). Emitted verbatim intools/list`.output_schema::Union{Nothing,AbstractDict}: Optional JSON Schema for the tool's structured result, emitted asoutputSchemaintools/list. Pair it with aCallToolResult(structured_content=…)so clients can validate the structured output._meta::Union{Nothing,Dict{String,Any}}: Optional metadata for protocol extensions, emitted verbatim intools/listwhen settask_support::Symbol: Task-augmented execution support (MCP 2025-11-25, experimental)::forbidden(default — calls run synchronously),:optional(client may run the call as a task), or:required(client must run the call as a task). Emitted asexecution.taskSupportintools/listfor clients that negotiated 2025-11-25.
Parameter Definition
Tools can define parameters in two ways:
Simple parameters using
parameters::Vector{ToolParameter}: Good for flat schemas with basic types (string, number, boolean).Complex schemas using
input_schema::AbstractDict: Supports arrays, enums, nested objects, and any valid JSON Schema. When provided,input_schematakes precedence overparameters.
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 Vector{<:Content} for multiple content items (can mix 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)
- A CallToolResult object for full control over the response (including error handling)
When returntype is Vector{Content} (default), single Content items are automatically wrapped in a vector. Note: When returning CallToolResult directly, the returntype field is ignored.
ModelContextProtocol.ToolParameter — Type
ToolParameter(; name::String, description::String, type::String, required::Bool=false, default::Any=nothing)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 parametertype::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 invocationdefault::Any: Default value for the parameter if not provided (nothing means no default)
Resources
ModelContextProtocol.MCPResource — Type
MCPResource <: ResourceImplement 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 resourcename::String: Human-readable name for the resourcedescription::String: Detailed description of the resourcemime_type::String: MIME type of the resource datadata_provider::Function: Zero-argument function returning the resource data forresources/read. Return aTextResourceContents/BlobResourceContents(or a vector of them) for full control —BlobResourceContentsis how binary resources are served (base64blobon the wire). AStringis used as the text verbatim; any other value is JSON-encoded into a text contents entry with the resource'smime_type.annotations::AbstractDict{String,Any}: Additional metadata for the resource
ModelContextProtocol.ResourceTemplate — Type
ResourceTemplate(; name::String, uri_template::String,
mime_type::Union{String,Nothing}=nothing, description::String="",
title::Union{String,Nothing}=nothing,
icons::Union{Vector{MCPIcon},Nothing}=nothing,
data_provider::Union{Function,Nothing}=nothing,
_meta::Union{Nothing,Dict{String,Any}}=nothing)Define a parameterized family of resources: an RFC 6570 URI template (level-1 {var} placeholders, advertised via resources/templates/list) plus a provider that serves any resources/read whose URI matches the template.
Fields
name::String: Name of the resource templateuri_template::String: URI template with{var}placeholders; each placeholder matches one path segment (no/)mime_type::Union{String,Nothing}: MIME type shared by all matching resourcesdescription::String: Human-readable description of the templatetitle::Union{String,Nothing}: Optional human-friendly display nameicons::Union{Vector{MCPIcon},Nothing}: Optional icons for UI displaydata_provider::Union{Function,Nothing}: Called for a matchingresources/readasprovider(uri::String)— or opt intoprovider(uri::String, vars::Dict{String,String})to receive the extracted template variables. Return values follow the same contract asMCPResourceproviders (ResourceContents/vector,Stringverbatim, JSON fallback). Templates without a provider are advertised but not readable._meta::Union{Nothing,Dict{String,Any}}: Optional metadata for protocol extensions, emitted verbatim inresources/templates/listwhen set
Prompts
ModelContextProtocol.MCPPrompt — Type
MCPPrompt(; name::String, description::String="",
arguments::Vector{PromptArgument}=PromptArgument[],
messages::Vector{PromptMessage}=PromptMessage[],
title::Union{String,Nothing}=nothing,
icons::Union{Vector{MCPIcon},Nothing}=nothing)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 promptdescription::String: Human-readable description of the prompt's purposearguments::Vector{PromptArgument}: Arguments that this prompt acceptsmessages::Vector{PromptMessage}: The sequence of messages in the prompttitle::Union{String,Nothing}: Optional human-friendly display nameicons::Union{Vector{MCPIcon},Nothing}: Optional icons for UI display_meta::Union{Nothing,Dict{String,Any}}: Optional metadata for protocol extensions, emitted verbatim inprompts/listwhen set
ModelContextProtocol.PromptArgument — Type
PromptArgument(; name::String, description::String="", required::Bool=false,
title::Union{String,Nothing}=nothing)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 argumentrequired::Bool: Whether the argument is required when using the prompttitle::Union{String,Nothing}: Optional human-friendly display name
ModelContextProtocol.PromptMessage — Type
PromptMessage(; content::Union{TextContent, ImageContent, AudioContent, ResourceLink, EmbeddedResource}, role::Role=user)Represent a single message in a prompt template.
Fields
content::Union{TextContent, ImageContent, AudioContent, ResourceLink, EmbeddedResource}: The content of the messagerole::Role: Whether this message is from the user or assistant (defaults to user)
Content Types
Abstract Types
ModelContextProtocol.Content — Type
ContentAbstract base type for all content formats in the MCP protocol. Content can be exchanged between clients and servers in various formats.
ModelContextProtocol.ResourceContents — Type
ResourceContentsAbstract base type for resource content formats in the MCP protocol. Resources can contain different types of content based on their MIME type.
Concrete Content Types
ModelContextProtocol.TextContent — Type
TextContent(; type::String="text", text::String,
annotations::Union{Nothing,Dict{String,Any}}=nothing,
_meta::Union{Nothing,Dict{String,Any}}=nothing) <: ContentText-based content for messages and tool responses.
Fields
type::String: Content type identifier (always "text")text::String: The actual text contentannotations::Union{Nothing,Dict{String,Any}}: Optional annotations for the client_meta::Union{Nothing,Dict{String,Any}}: Optional metadata for protocol extensions
ModelContextProtocol.ImageContent — Type
ImageContent(; type::String="image", data::Vector{UInt8}, mime_type::String,
annotations::Union{Nothing,Dict{String,Any}}=nothing,
_meta::Union{Nothing,Dict{String,Any}}=nothing) <: ContentImage content for messages and tool responses.
Fields
type::String: Content type identifier (always "image")data::Vector{UInt8}: Raw image data (automatically base64-encoded when serialized)mime_type::String: MIME type of the image (e.g., "image/png")annotations::Union{Nothing,Dict{String,Any}}: Optional annotations for the client_meta::Union{Nothing,Dict{String,Any}}: Optional metadata for protocol extensions
ModelContextProtocol.AudioContent — Type
AudioContent(; type::String="audio", data::Vector{UInt8}, mime_type::String,
annotations::Union{Nothing,Dict{String,Any}}=nothing,
_meta::Union{Nothing,Dict{String,Any}}=nothing) <: ContentAudio content for messages and tool responses (protocol 2025-03-26+).
Fields
type::String: Content type identifier (always "audio")data::Vector{UInt8}: Raw audio data (automatically base64-encoded when serialized)mime_type::String: MIME type of the audio (e.g., "audio/wav"), serialized asmimeTypeannotations::Union{Nothing,Dict{String,Any}}: Optional annotations for the client_meta::Union{Nothing,Dict{String,Any}}: Optional metadata for protocol extensions
ModelContextProtocol.EmbeddedResource — Type
EmbeddedResource(; type::String="resource", resource::Dict{String,Any},
annotations::Union{Nothing,Dict{String,Any}}=nothing,
_meta::Union{Nothing,Dict{String,Any}}=nothing) <: ContentEmbedded resource content for inline resource data.
Fields
type::String: Content type identifier (always "resource")resource::Dict{String,Any}: The embedded resource dataannotations::Union{Nothing,Dict{String,Any}}: Optional annotations for the client_meta::Union{Nothing,Dict{String,Any}}: Optional metadata for protocol extensions
ModelContextProtocol.ResourceLink — Type
ResourceLink(; type::String="resource_link", uri::String, name::String,
description::Union{String,Nothing}=nothing,
mime_type::Union{String,Nothing}=nothing,
title::Union{String,Nothing}=nothing,
annotations::Union{Nothing,Dict{String,Any}}=nothing,
_meta::Union{Nothing,Dict{String,Any}}=nothing) <: ContentLink to a resource a tool result can reference without embedding it (protocol 2025-06-18). Serialized per the MCP spec as {"type": "resource_link", "uri": ..., "name": ..., ...}.
Fields
type::String: Content type identifier (always "resource_link")uri::String: URI of the linked resourcename::String: Name of the resourcedescription::Union{String,Nothing}: Optional description of the resourcemime_type::Union{String,Nothing}: Optional MIME type, serialized asmimeTypesize::Union{Int,Nothing}: Optional resource size in bytestitle::Union{String,Nothing}: Optional human-readable titleannotations::Union{Nothing,Dict{String,Any}}: Optional annotations for the client_meta::Union{Nothing,Dict{String,Any}}: Optional metadata for protocol extensions
Resource Content Types
ModelContextProtocol.TextResourceContents — Type
TextResourceContents(; uri::URI, mime_type::String="text/plain", text::String) <: ResourceContentsText content for resources in the MCP protocol.
Fields
uri::URI: Resource identifiermime_type::String: MIME type of the text contenttext::String: The actual text content
ModelContextProtocol.BlobResourceContents — Type
BlobResourceContents(; uri::URI, mime_type::String="application/octet-stream",
blob::Vector{UInt8}) <: ResourceContentsBinary content for resources.
Fields
uri::URI: Resource identifiermime_type::String: MIME type of the binary contentblob::Vector{UInt8}: Raw binary data (automatically base64-encoded when serialized)
Tool Results
ModelContextProtocol.CallToolResult — Type
CallToolResult(; content::Vector{Dict{String,Any}}, is_error::Bool=false,
structured_content=nothing) <: ResponseResultResult returned from a tool invocation.
Fields
content::Vector{Dict{String,Any}}: Content produced by the toolis_error::Bool: Whether the tool execution resulted in an errorstructured_content::Union{Nothing,AbstractDict}: Optional structured result (a JSON object per the MCP spec), serialized asstructuredContentand omitted whennothing. Pair it with the tool'soutput_schemaso clients can validate and consume it programmatically. Per the spec, a tool returning structured content SHOULD also include a human-readable serialization (e.g. the JSON as text) incontentfor clients that don't consume structured output._meta::Union{Nothing,AbstractDict}: Optional result metadata for protocol extensions, serialized as_metaand omitted whennothing
Transport Configuration
Transport types (StdioTransport, HttpTransport) are internal implementation details and are not exported. Use mcp_server with appropriate options to configure transport.
Server Type
ModelContextProtocol.Server — Type
Server(config::ServerConfig; transport::Union{Transport,Nothing}=nothing)Represent a running MCP server instance that manages resources, tools, and prompts.
Fields
config::ServerConfig: Server configuration settingstransport::Union{Transport,Nothing}: Transport implementation for client-server communicationresources::Vector{Resource}: Available resourcestools::Vector{Tool}: Available toolsprompts::Vector{MCPPrompt}: Available promptsresource_templates::Vector{ResourceTemplate}: Available resource templatessubscriptions::DefaultDict{String,Vector{Subscription}}: Resource subscription registryprogress_trackers::Dict{Union{String,Int},Progress}: Progress tracking for operationstasks::TaskStore: Registry of server-side tasks (MCP Tasks, experimental)active::Bool: Whether the server is currently active
Constructor
Server(config::ServerConfig; transport=nothing): Creates a new server with the specified configuration
Resource Subscriptions
ModelContextProtocol.subscribe! — Function
subscribe!(server::Server, uri::String, callback::Function) -> ServerSubscribe to updates for a specific resource identified by URI.
Arguments
server::Server: The server instanceuri::String: The resource URI to subscribe tocallback::Function: The function to call when the resource is updated
Returns
Server: The server instance for method chaining
ModelContextProtocol.unsubscribe! — Function
unsubscribe!(server::Server, uri::String, callback::Function) -> ServerRemove a subscription for a specific resource URI and callback function.
Arguments
server::Server: The server instanceuri::String: The resource URI to unsubscribe fromcallback::Function: The callback function to remove
Returns
Server: The server instance for method chaining
Utility Functions
ModelContextProtocol.content2dict — Function
content2dict(content::Content) -> Dict{String,Any}Convert a Content object to its dictionary representation for JSON serialization.
Arguments
content::Content: The content object to convert
Returns
Dict{String,Any}: Dictionary representation of the content
Examples
text_content = TextContent(text="Hello", type="text")
dict = content2dict(text_content)
# Returns: Dict("type" => "text", "text" => "Hello", "annotations" => Dict())Transport Options
ModelContextProtocol.jl supports multiple transport mechanisms:
STDIO Transport (Default)
server = mcp_server(name = "my-server")
start!(server) # Uses StdioTransport by defaultHTTP Transport
server = mcp_server(name = "my-http-server")
start!(server; transport = HttpTransport(; port = 3000))
# With custom configuration
start!(server; transport = HttpTransport(;
host = "127.0.0.1", # Important for Windows
port = 8080, # Default port
endpoint = "/" # Default endpoint
))Note: HTTP transport currently supports HTTP only, not HTTPS. For production use:
- Use
mcp-remotewith--allow-httpflag for secure connections - Or deploy behind a reverse proxy (nginx, Apache) for TLS termination
All Exported Symbols
Types
ModelContextProtocol.AuthMiddleware — Type
AuthMiddleware(; config::OAuthConfig,
validator::TokenValidator,
allowlist::Union{Set{String},Nothing}=nothing,
enabled::Bool=true)Middleware for authenticating HTTP requests to an MCP server.
Fields
config::OAuthConfig: OAuth configurationvalidator::TokenValidator: Token validation strategyallowlist::Union{Set{String},Nothing}: Optional set of allowed usernames/subjectsenabled::Bool: Whether authentication is enabled (for development/testing)
ModelContextProtocol.AuthProvider — Type
AuthProviderAbstract type for authentication providers (GitHub, Google, custom OAuth servers).
ModelContextProtocol.AuthResult — Type
AuthResultResult of an authentication attempt.
ModelContextProtocol.AuthenticatedUser — Type
AuthenticatedUser(; subject::String, provider::String,
username::Union{String,Nothing}=nothing,
scopes::Vector{String}=String[],
claims::Dict{String,Any}=Dict{String,Any}())Represent an authenticated user after successful token validation.
Fields
subject::String: Unique user identifier (sub claim from token)provider::String: Authentication provider name (e.g., "github", "google")username::Union{String,Nothing}: Human-readable username if availablescopes::Vector{String}: Granted OAuth scopesclaims::Dict{String,Any}: Raw claims from the token
ModelContextProtocol.GitHubOAuthValidator — Type
GitHubOAuthValidator(; cache_ttl_seconds::Int=300)Token validator for GitHub OAuth access tokens. Validates tokens by calling GitHub's /user API endpoint.
Fields
cache_ttl_seconds::Int: How long to cache user info (default: 5 minutes)user_cache::Dict{String,Tuple{AuthenticatedUser,DateTime}}: Cache of validated tokenscache_lock::ReentrantLock: Lock for thread-safe cache access
ModelContextProtocol.HttpTransport — Type
HttpTransport(; host::String="127.0.0.1", port::Int=8080, endpoint::String="/")Transport implementation following the MCP Streamable HTTP specification (2025-06-18). Supports Server-Sent Events (SSE) for streaming and session management.
Fields
host::String: Host address to bind to (default: "127.0.0.1")port::Int: Port number to listen on (default: 8080)endpoint::String: HTTP endpoint path (default: "/")server::Union{HTTP.Server,Nothing}: HTTP server instanceconnected::Bool: Connection statusserver_task::Union{Task,Nothing}: Server task handleactive_streams::Dict{String,HTTP.Stream}: Active streaming connectionsrequest_queue::Channel{QueuedHttpRequest}: Queue for incoming requests (id, body, auth user)response_channels::Dict{String,Channel{String}}: Response channels per request
ModelContextProtocol.IntrospectionValidator — Type
IntrospectionValidator(; client_id=nothing, client_secret=nothing)Token validator using OAuth 2.0 Token Introspection (RFC 7662). Used for opaque tokens that cannot be validated locally.
Fields
client_id::Union{String,Nothing}: Client ID for introspection authclient_secret::Union{String,Nothing}: Client secret for introspection auth
ModelContextProtocol.JWTValidator — Type
JWTValidator(; clock_skew_seconds::Int=60)JWT token validator that validates claims (iss, aud, exp, nbf, scope).
This validator decodes and validates JWT claims but does not verify cryptographic signatures (JWKS/JWK). Tokens from untrusted issuers can be forged. Use IntrospectionValidator (RFC 7662) when accepting tokens from external issuers. Signature verification via JWKS may be added in a future release.
Fields
jwks_cache::Dict{String,Any}: Reserved for future JWKS supportclock_skew_seconds::Int: Allowed clock skew for exp/nbf validation
ModelContextProtocol.MCPIcon — Type
MCPIcon(; src::String, mimeType=nothing, sizes=nothing, theme=nothing)Icon metadata for tools, resources, prompts, and server info (MCP 2025-11-25).
Fields
src::String: URI pointing to the icon (http/https URL or data: URI)mimeType::Union{String,Nothing}: MIME type override (e.g., "image/png", "image/svg+xml")sizes::Union{Vector{String},Nothing}: Size hints (e.g., ["48x48", "any"])theme::Union{String,Nothing}: Which background the icon is designed for ("light" or "dark")
ModelContextProtocol.MCPPrompt — Method
MCPPrompt(name::String, description::String, arguments::Vector{PromptArgument}, text::String) -> MCPPromptCreate a prompt with a single text message.
Arguments
name::String: Unique identifier for the promptdescription::String: Human-readable descriptionarguments::Vector{PromptArgument}: Arguments the prompt acceptstext::String: Text content for the prompt message
Returns
MCPPrompt: A new prompt with a single user message containing the text
ModelContextProtocol.MCPResource — Method
MCPResource(; uri, name::String="", description::String="",
mime_type::String="application/json", data_provider::Function,
annotations::AbstractDict{String,Any}=LittleDict{String,Any}(),
title::Union{String,Nothing}=nothing,
icons::Union{Vector{MCPIcon},Nothing}=nothing) -> MCPResourceCreate a resource with automatic URI conversion from strings or URIs.
Arguments
uri: String or URI identifier for the resourcename::String: Human-readable name for the resourcedescription::String: Detailed descriptionmime_type::String: MIME type of the resourcedata_provider::Function: Zero-argument function returning the resource data (ResourceContents/vector for full control incl. binaryblob;Stringverbatim; anything else JSON-encoded — seeMCPResourcefield docs)annotations::AbstractDict{String,Any}: Additional metadata for the resourcetitle::Union{String,Nothing}: Optional human-friendly display nameicons::Union{Vector{MCPIcon},Nothing}: Optional icons for UI display_meta::Union{Nothing,Dict{String,Any}}: Optional metadata for protocol extensions, emitted verbatim inresources/listwhen set
Returns
MCPResource: A new resource with the provided configuration
ModelContextProtocol.OAuthConfig — Type
OAuthConfig(; issuer::String, audience::String,
required_scopes::Vector{String}=String[],
jwks_uri::Union{String,Nothing}=nothing,
introspection_endpoint::Union{String,Nothing}=nothing)Configure OAuth 2.0 token validation for an MCP server.
Fields
issuer::String: Expected token issuer (iss claim)audience::String: Expected audience (aud claim) - typically your server's URLrequired_scopes::Vector{String}: Scopes required to access the serverjwks_uri::Union{String,Nothing}: URL to fetch JSON Web Key Set for JWT validationintrospection_endpoint::Union{String,Nothing}: Token introspection endpoint URL
ModelContextProtocol.PromptMessage — Method
PromptMessage(content::Union{TextContent, ImageContent, AudioContent, ResourceLink, EmbeddedResource}) -> PromptMessageCreate a prompt message with only content (role defaults to user).
Arguments
content::Union{TextContent, ImageContent, AudioContent, ResourceLink, EmbeddedResource}: The message content
Returns
PromptMessage: A new prompt message with the default user role
ModelContextProtocol.ProtectedResourceMetadata — Type
ProtectedResourceMetadata(; resource::String,
authorization_servers::Vector{String},
scopes_supported::Vector{String}=String[],
bearer_methods_supported::Vector{String}=["header"])MCP Protected Resource Metadata per RFC 9728. Served at .well-known/oauth-protected-resource.
Fields
resource::String: The protected resource identifier (your server URL)authorization_servers::Vector{String}: URLs of authorization servers that can issue tokensscopes_supported::Vector{String}: OAuth scopes the resource understandsbearer_methods_supported::Vector{String}: How tokens can be sent (header, body, query)
ModelContextProtocol.SimpleTokenValidator — Type
SimpleTokenValidator(; tokens::Dict{String,AuthenticatedUser})Simple token validator using a static mapping of tokens to users. Useful for API keys and development/testing.
Lookups are plain dictionary comparisons (not constant-time) and tokens are held in memory in plaintext. Intended for development and trusted static API keys, not as a general-purpose production token store.
Fields
tokens::Dict{String,AuthenticatedUser}: Map of valid tokens to user info
ModelContextProtocol.StdioTransport — Type
StdioTransport(; input::IO=stdin, output::IO=stdout)Transport implementation using standard input/output streams. This is the default transport for local MCP server processes.
Fields
input::IO: Input stream for reading messages (default: stdin)output::IO: Output stream for writing messages (default: stdout)connected::Bool: Connection status (always true for stdio)write_lock::ReentrantLock: Serializes output writes (responses and notifications share stdout, and background task executions may write concurrently with the loop)
ModelContextProtocol.TokenValidator — Type
TokenValidatorAbstract type for token validation strategies (JWT, introspection).
ModelContextProtocol.Transport — Type
TransportAbstract base type for all MCP transport implementations. Defines the interface for reading and writing messages between client and server.
Functions
ModelContextProtocol.authenticate_request — Method
authenticate_request(middleware::AuthMiddleware, authorization_header::Union{String,Nothing}) -> AuthResultAuthenticate an HTTP request using the auth middleware.
Arguments
middleware::AuthMiddleware: The authentication middlewareauthorization_header::Union{String,Nothing}: The Authorization header value
Returns
AuthResult indicating success with user info, or failure with error details.
ModelContextProtocol.clear_cache! — Method
clear_cache!(validator::GitHubOAuthValidator)Clear the token validation cache.
ModelContextProtocol.connect — Method
connect(transport::HttpTransport) -> NothingStart the HTTP server and begin listening for connections.
Arguments
transport::HttpTransport: The transport instance
Returns
Nothing
Throws
TransportError: If the server cannot be started
ModelContextProtocol.connect — Method
connect(transport::Transport) -> NothingEstablish the transport connection. Default implementation does nothing (for transports that are always connected).
Arguments
transport::Transport: The transport instance to connect
Returns
Nothing
Throws
TransportError: If connection cannot be established
ModelContextProtocol.create_auth_middleware — Method
create_auth_middleware(config::OAuthConfig;
validator::TokenValidator,
allowlist::Union{Set{String},Nothing}=nothing,
enabled::Bool=true) -> AuthMiddlewareCreate an authentication middleware for the HTTP transport.
Arguments
config::OAuthConfig: OAuth configurationvalidator::TokenValidator: Token validation strategy (REQUIRED — no default, so an unsafe validator is never selected implicitly. NoteJWTValidatordoes not verify signatures; preferIntrospectionValidatororGitHubOAuthValidatorfor tokens from external issuers.)allowlist::Union{Set{String},Nothing}: Optional allowlist of usernames/subjectsenabled::Bool: Whether auth is enabled (default: true)
Example
auth = create_auth_middleware(
OAuthConfig(
issuer = "https://github.com",
audience = "my-mcp-server"
),
validator = IntrospectionValidator(client_id = "id", client_secret = "secret"),
allowlist = Set(["user1", "user2"])
)ModelContextProtocol.create_github_auth — Method
create_github_auth(; allowed_users::Union{Vector{String},Set{String}}=String[],
required_org::Union{String,Nothing}=nothing,
cache_ttl_seconds::Int=300) -> AuthMiddlewareCreate an authentication middleware configured for GitHub OAuth.
Arguments
allowed_users: List of GitHub usernames allowed to access the serverrequired_org: Optionally require membership in a GitHub organizationcache_ttl_seconds: How long to cache validated tokens (default: 5 minutes)
Returns
AuthMiddleware configured for GitHub OAuth validation.
Example
# Allow specific users
auth = create_github_auth(
allowed_users = ["user1", "user2", "user3"]
)
# Require organization membership
auth = create_github_auth(
required_org = "JuliaSMLM"
)
# Both user allowlist and org requirement
auth = create_github_auth(
allowed_users = ["user1", "user2"],
required_org = "LidkeLab"
)ModelContextProtocol.create_github_resource_metadata — Method
create_github_resource_metadata(resource_url::String;
scopes::Vector{String}=["read:user"]) -> ProtectedResourceMetadataCreate Protected Resource Metadata configured for GitHub OAuth.
Arguments
resource_url::String: Your MCP server URLscopes::Vector{String}: GitHub OAuth scopes to request (default: ["read:user"])
Example
metadata = create_github_resource_metadata(
"https://mcp.lidkelab.org",
scopes = ["read:user", "read:org"]
)ModelContextProtocol.create_protected_resource_metadata — Method
create_protected_resource_metadata(resource_url::String,
authorization_servers::Vector{String};
scopes::Vector{String}=String[]) -> ProtectedResourceMetadataCreate Protected Resource Metadata for the MCP server.
Arguments
resource_url::String: The URL of your MCP server (the protected resource)authorization_servers::Vector{String}: URLs of OAuth authorization serversscopes::Vector{String}: OAuth scopes the server understands
Example
metadata = create_protected_resource_metadata(
"https://mcp.example.com",
["https://github.com/login/oauth"],
scopes = ["read:user", "repo"]
)ModelContextProtocol.create_simple_auth — Method
create_simple_auth(tokens::Dict{String,String};
allowlist::Union{Set{String},Nothing}=nothing) -> AuthMiddlewareCreate a simple API key-based authentication middleware.
Arguments
tokens::Dict{String,String}: Map of API keys to usernamesallowlist::Union{Set{String},Nothing}: Optional additional allowlist
Example
auth = create_simple_auth(Dict(
"sk-abc123" => "user1",
"sk-def456" => "user2"
))ModelContextProtocol.disable_auth — Method
disable_auth() -> AuthMiddlewareCreate a disabled auth middleware (for development/testing). All requests will be allowed with an anonymous user.
ModelContextProtocol.extract_bearer_token — Method
extract_bearer_token(authorization_header::String) -> Union{String,Nothing}Extract Bearer token from Authorization header.
Arguments
authorization_header::String: The Authorization header value
Returns
The token if present and valid format, nothing otherwise.
ModelContextProtocol.is_auth_enabled — Method
is_auth_enabled(transport::HttpTransport) -> BoolReturn whether OAuth Resource Server token validation is enabled on this transport.
Arguments
transport::HttpTransport: The transport instance
Returns
Bool: true if an enabledAuthMiddlewareis configured
ModelContextProtocol.is_supported_version — Method
is_supported_version(version::AbstractString) -> BoolCheck whether a protocol version is in our supported versions list.
Arguments
version::AbstractString: Protocol version string to check
Returns
Bool: true if we support this version
ModelContextProtocol.mcp_server — Method
mcp_server(; name::String, version::String="1.0.0",
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,
title::Union{String,Nothing}=nothing,
icons::Union{Vector{MCPIcon},Nothing}=nothing) -> ServerPrimary entry point for creating and configuring a Model Context Protocol (MCP) server.
Arguments
name::String: Unique identifier for the server instanceversion::String: Your server implementation version (defaults to "1.0.0") - YOUR server's version, not the MCP protocol versiontools: Tools to expose to the modelresources: Resources available to the modelresource_templates: Parameterized resource families (RFC 6570{var}URI templates with a provider; advertised viaresources/templates/list)prompts: Predefined prompts for the modeldescription::String: Optional server descriptioncapabilities::Vector{Capability}: Server capability configurationauto_register_dir: Directory to auto-register components fromtitle::Union{String,Nothing}: Optional human-friendly display name for the servericons::Union{Vector{MCPIcon},Nothing}: Optional icons for the server
Returns
Server: A configured server instance ready to handle MCP client connections
Example
server = mcp_server(
name = "my-server",
version = "1.0.0", # Your server version
title = "My MCP 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)ModelContextProtocol.negotiate_version — Method
negotiate_version(client_version::Union{AbstractString, Nothing}) -> StringNegotiate the protocol version with a client per the MCP specification.
If the client requests a version we support, return that version. Otherwise, return our latest version and let the client decide whether it can proceed.
Arguments
client_version::Union{AbstractString, Nothing}: Protocol version requested by the client, or nothing
Returns
String: The negotiated protocol version
ModelContextProtocol.send_progress — Method
send_progress(ctx::RequestContext, progress::Real;
total::Union{Real,Nothing}=nothing,
message::Union{String,Nothing}=nothing) -> BoolEmit an MCP notifications/progress for the current request. A tool handler that accepts the RequestContext (its second argument) can call this during a long operation to report progress.
Returns false (a no-op) when the client did not supply a progressToken or no transport is connected, so it is always safe to call. Send an increasing progress; include total for a determinate bar and message for a status line.
ModelContextProtocol.start! — Method
start!(server::Server; transport::Union{Transport,Nothing}=nothing) -> NothingStart the MCP server, setting up logging and entering the main server loop.
Arguments
server::Server: The server instance to starttransport::Union{Transport,Nothing}: Optional transport to use. If not provided, uses StdioTransport
Returns
Nothing: The function returns after the server stops
Throws
ServerError: If the server is already running
ModelContextProtocol.stop! — Method
stop!(server::Server) -> NothingStop 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
ModelContextProtocol.subscribe! — Method
subscribe!(server::Server, uri::String, callback::Function) -> ServerSubscribe to updates for a specific resource identified by URI.
Arguments
server::Server: The server instanceuri::String: The resource URI to subscribe tocallback::Function: The function to call when the resource is updated
Returns
Server: The server instance for method chaining
ModelContextProtocol.supports — Method
supports(version::AbstractString, feature::Symbol) -> BoolCheck whether a protocol version supports a specific feature.
Arguments
version::AbstractString: The negotiated protocol versionfeature::Symbol: Feature identifier (seeFEATURE_VERSIONSfor available features)
Returns
Bool: true if the version supports the feature
Example
if supports(negotiated_version, :tasks)
# Include task tracking in response
endModelContextProtocol.task_cancelled — Method
task_cancelled(ctx) -> BoolCheck whether the current task-augmented execution has been cancelled by the client (via tasks/cancel). Long-running, context-aware tool handlers can poll this to stop work early; the discarded result is never delivered (cancelled tasks stay cancelled). Always false for ordinary (non-task) calls, so it is safe to call unconditionally.
handler = (args, ctx) -> begin
for chunk in work_chunks
task_cancelled(ctx) && return TextContent(text = "aborted")
process(chunk)
end
TextContent(text = "done")
endModelContextProtocol.unsubscribe! — Method
unsubscribe!(server::Server, uri::String, callback::Function) -> ServerRemove a subscription for a specific resource URI and callback function.
Arguments
server::Server: The server instanceuri::String: The resource URI to unsubscribe fromcallback::Function: The callback function to remove
Returns
Server: The server instance for method chaining
ModelContextProtocol.validate_token — Function
validate_token(validator::TokenValidator, token::AbstractString, config::OAuthConfig) -> AuthResultValidate an OAuth token using the specified validator.
Arguments
validator::TokenValidator: The validation strategy to usetoken::AbstractString: The token to validateconfig::OAuthConfig: OAuth configuration with expected issuer, audience, etc.
Returns
AuthResult: Success with user info, or failure with error details
ModelContextProtocol.validate_token — Method
validate_token(validator::GitHubOAuthValidator, token::AbstractString, config::OAuthConfig) -> AuthResultValidate a GitHub OAuth access token by calling GitHub's API.
Constants
ModelContextProtocol.FEATURE_VERSIONS — Constant
Minimum protocol version required for each feature.
Features are identified by Symbol keys. The value is the minimum protocol version that introduced the feature. Use supports(version, feature) to check availability.
Features
:tasks- Experimental task tracking (SEP-1686):sse_priming_events- SSE priming for stream resumability (SEP-1699):icon_metadata- Icon metadata for tools/resources/prompts (SEP-973):tool_calling_in_sampling- Tool calling in sampling requests (SEP-1577):oauth_openid_connect- OpenID Connect discovery for OAuth (PR #797):oauth_incremental_scope- Incremental scope consent (SEP-835):url_elicitation- URL mode elicitation requests (SEP-1036):streamable_http- Streamable HTTP transport:resource_links- ResourceLink content type
ModelContextProtocol.LATEST_PROTOCOL_VERSION — Constant
Latest MCP protocol version supported by this implementation.
ModelContextProtocol.SUPPORTED_PROTOCOL_VERSIONS — Constant
All MCP protocol versions supported by this implementation, newest first.
Macros
Internal API
The following internal types and functions are documented for developers working on the package itself.
Protocol Types
ModelContextProtocol.CallToolParams — Type
CallToolParams(; name::String, arguments::Union{Dict{String,Any},Nothing}=nothing) <: RequestParamsParameters for invoking a specific tool on an MCP server.
Fields
name::String: Name of the tool to callarguments::Union{Dict{String,Any},Nothing}: Optional arguments to pass to the tooltask::Union{Dict{String,Any},Nothing}: When present, the caller requests task-augmented execution (MCP Tasks, experimental); may carry a requested"ttl"in milliseconds
ModelContextProtocol.CancelTaskParams — Type
CancelTaskParams(; taskId::String) <: RequestParamsParameters for a tasks/cancel request.
Fields
taskId::String: The task identifier to cancel
ModelContextProtocol.ClientCapabilities — Type
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 supportedroots::Union{Dict{String,Bool},Nothing}: Root directories client has access tosampling::Union{Dict{String,Any},Nothing}: Sampling capabilities for model generation
ModelContextProtocol.ErrorInfo — Type
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 descriptiondata::Union{Dict{String,Any},Nothing}: Optional additional error details
ModelContextProtocol.GetPromptParams — Type
GetPromptParams(; name::String, arguments::Union{Dict{String,String},Nothing}=nothing) <: RequestParamsParameters for requesting a specific prompt from an MCP server.
Fields
name::String: Name of the prompt to retrievearguments::Union{Dict{String,String},Nothing}: Optional arguments to apply to the prompt template
ModelContextProtocol.GetPromptResult — Type
GetPromptResult(; description::String, messages::Vector{PromptMessage}) <: ResponseResultResult returned from a get prompt request.
Fields
description::String: Description of the promptmessages::Vector{PromptMessage}: The prompt messages with template variables replaced
ModelContextProtocol.GetTaskParams — Type
GetTaskParams(; taskId::String) <: RequestParamsParameters for a tasks/get status poll.
Fields
taskId::String: The task identifier to query
ModelContextProtocol.Implementation — Type
Implementation(; name::String="default-client", version::String="1.0.0",
title::Union{String,Nothing}=nothing,
description::Union{String,Nothing}=nothing)Information about a client or server implementation of the MCP protocol.
Fields
name::String: Name of the implementationversion::String: Version string of the implementationtitle::Union{String,Nothing}: Optional human-readable display namedescription::Union{String,Nothing}: Optional human-readable description (MCP 2025-11-25)
ModelContextProtocol.InitializeParams — Type
InitializeParams(; capabilities::ClientCapabilities=ClientCapabilities(),
clientInfo::Implementation=Implementation(),
protocolVersion::Union{String,Nothing}=nothing) <: RequestParamsParameters for MCP protocol initialization requests.
Fields
capabilities::ClientCapabilities: Client capabilities being reportedclientInfo::Implementation: Information about the client implementationprotocolVersion::Union{String,Nothing}: Version of the MCP protocol requested by the client. The server negotiates againstSUPPORTED_PROTOCOL_VERSIONS(latest:LATEST_PROTOCOL_VERSION); seenegotiate_version.
ModelContextProtocol.InitializeResult — Type
InitializeResult(; serverInfo::Dict{String,Any}, capabilities::Dict{String,Any},
protocolVersion::String, instructions::String="") <: ResponseResultResult returned in response to MCP protocol initialization.
Fields
serverInfo::Dict{String,Any}: Information about the server implementationcapabilities::Dict{String,Any}: Server capabilities being reportedprotocolVersion::String: Version of the MCP protocol being usedinstructions::String: Optional usage instructions for clients
ModelContextProtocol.JSONRPCError — Type
JSONRPCError(; id::Union{RequestId,Nothing}, error::ErrorInfo) <: ResponseJSON-RPC error response message returned when requests fail.
Fields
id::Union{RequestId,Nothing}: Identifier matching the request this is responding to, or nullerror::ErrorInfo: Information about the error that occurred
ModelContextProtocol.JSONRPCNotification — Type
JSONRPCNotification(; method::String,
params::Union{RequestParams,Dict{String,Any}}) <: NotificationJSON-RPC notification message that does not expect a response.
Fields
method::String: Name of the notification methodparams::Union{RequestParams,Dict{String,Any}}: Parameters for the notification
ModelContextProtocol.JSONRPCRequest — Type
JSONRPCRequest(; id::RequestId, method::String,
params::Union{RequestParams, Nothing},
meta::RequestMeta=RequestMeta()) <: RequestJSON-RPC request message used to invoke methods on the server.
Fields
id::RequestId: Unique identifier for the requestmethod::String: Name of the method to invokeparams::Union{RequestParams, Nothing}: Parameters for the methodmeta::RequestMeta: Additional metadata for the request
ModelContextProtocol.JSONRPCResponse — Type
JSONRPCResponse(; id::RequestId, result::Union{ResponseResult,AbstractDict{String,Any}}) <: ResponseJSON-RPC response message returned for successful requests.
Fields
id::RequestId: Identifier matching the request this is responding toresult::Union{ResponseResult,AbstractDict{String,Any}}: Results of the method execution
ModelContextProtocol.ListPromptsParams — Type
ListPromptsParams(; cursor::Union{String,Nothing}=nothing) <: RequestParamsParameters for requesting a list of available prompts from an MCP server.
Fields
cursor::Union{String,Nothing}: Optional pagination cursor for long prompt lists
ModelContextProtocol.ListPromptsResult — Type
ListPromptsResult(; prompts::Vector{Dict{String,Any}},
nextCursor::Union{String,Nothing}=nothing) <: ResponseResultResult returned from a list prompts request.
Fields
prompts::Vector{Dict{String,Any}}: List of available prompts with their metadatanextCursor::Union{String,Nothing}: Optional pagination cursor for fetching more prompts
ModelContextProtocol.ListResourceTemplatesParams — Type
ListResourceTemplatesParams(; cursor::Union{String,Nothing}=nothing) <: RequestParamsParameters for a resources/templates/list request.
Fields
cursor::Union{String,Nothing}: Optional pagination cursor for long template lists
ModelContextProtocol.ListResourcesParams — Type
ListResourcesParams(; cursor::Union{String,Nothing}=nothing) <: RequestParamsParameters for requesting a list of available resources from an MCP server.
Fields
cursor::Union{String,Nothing}: Optional pagination cursor for long resource lists
ModelContextProtocol.ListResourcesResult — Type
ListResourcesResult(; resources::Vector{Dict{String,Any}},
nextCursor::Union{String,Nothing}=nothing) <: ResponseResultResult returned from a list resources request.
Fields
resources::Vector{Dict{String,Any}}: List of available resources with their metadatanextCursor::Union{String,Nothing}: Optional pagination cursor for fetching more resources
ModelContextProtocol.ListTasksParams — Type
ListTasksParams(; cursor::Union{String,Nothing}=nothing) <: RequestParamsParameters for a paginated tasks/list request.
Fields
cursor::Union{String,Nothing}: Opaque pagination cursor from a previous response
ModelContextProtocol.ListToolsParams — Type
ListToolsParams(; cursor::Union{String,Nothing}=nothing) <: RequestParamsParameters for requesting a list of available tools from an MCP server.
Fields
cursor::Union{String,Nothing}: Optional pagination cursor for long tool lists
ModelContextProtocol.ListToolsResult — Type
ListToolsResult(; tools::Vector{Dict{String,Any}},
nextCursor::Union{String,Nothing}=nothing) <: ResponseResultResult returned from a list tools request.
Fields
tools::Vector{Dict{String,Any}}: List of available tools with their metadatanextCursor::Union{String,Nothing}: Optional pagination cursor for fetching more tools
ModelContextProtocol.ProgressParams — Type
ProgressParams(; progress_token::ProgressToken, progress::Float64,
total::Union{Float64,Nothing}=nothing) <: RequestParamsParameters for progress notifications during long-running operations.
Fields
progress_token::ProgressToken: Token identifying the operation being reported onprogress::Float64: Current progress valuetotal::Union{Float64,Nothing}: Optional total expected value
ModelContextProtocol.ReadResourceParams — Type
ReadResourceParams(; uri::String) <: RequestParamsParameters for requesting the contents of a specific resource.
Fields
uri::String: URI identifier of the resource to read
ModelContextProtocol.ReadResourceResult — Type
ReadResourceResult(; contents::Vector{Dict{String,Any}}) <: ResponseResultResult returned from a read resource request.
Fields
contents::Vector{Dict{String,Any}}: The contents of the requested resource
ModelContextProtocol.RequestMeta — Type
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
ModelContextProtocol.SetLevelParams — Type
SetLevelParams(; level::String) <: RequestParamsParameters for logging/setLevel requests.
Fields
level::String: Minimum log level the client wants to receive (one of the MCP/RFC-5424 levels: "debug", "info", "notice", "warning", "error", "critical", "alert", "emergency")
ModelContextProtocol.TaskResultParams — Type
TaskResultParams(; taskId::String) <: RequestParamsParameters for a tasks/result payload retrieval. The response blocks until the task reaches a terminal status and then matches the original request's result type.
Fields
taskId::String: The task identifier to retrieve results for
ModelContextProtocol.get_params_type — Method
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, ornothingif no specific type is defined
ModelContextProtocol.get_result_type — Method
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, ornothingif not known
Note: This is a placeholder that needs to be implemented with request tracking.
ModelContextProtocol.parse_error_response — Method
parse_error_response(raw::JSON3.Object) -> ResponseParse 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
ModelContextProtocol.parse_message — Method
parse_message(json::String) -> MCPMessageParse 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)
ModelContextProtocol.parse_notification — Method
parse_notification(raw::JSON3.Object) -> NotificationParse 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
ModelContextProtocol.parse_request — Method
parse_request(raw::JSON3.Object) -> RequestParse 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
ModelContextProtocol.parse_success_response — Method
parse_success_response(raw::JSON3.Object) -> ResponseParse 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
ModelContextProtocol.serialize_message — Method
serialize_message(msg::MCPMessage) -> StringSerialize 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
Core Implementation
ModelContextProtocol.process_message — Method
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 instancestate::ServerState: Current server statemessage::String: Raw JSON-RPC message to process
Returns
Union{String,Nothing}: A serialized response string or nothing for notifications
ModelContextProtocol.run_server_loop — Method
run_server_loop(server::Server, state::ServerState) -> NothingExecute the main server loop that reads JSON-RPC messages from the transport and writes responses back. Implements optimized CPU usage by blocking on input rather than active polling.
Arguments
server::Server: The MCP server instance with configured transportstate::ServerState: The server state object to track running status
Returns
Nothing: The function runs until interrupted or state.running becomes false
ModelContextProtocol.CapabilityResponse — Type
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.
ModelContextProtocol.LoggingCapability — Type
LoggingCapability(; levels::Vector{String}=["info", "warn", "error"])Configure logging-related capabilities for an MCP server.
Fields
levels::Vector{String}: Supported logging levels.
ModelContextProtocol.PromptCapability — Type
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.
ModelContextProtocol.ResourceCapability — Type
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.
ModelContextProtocol.TaskCapability — Type
TaskCapability(; list::Bool=true, cancel::Bool=true)Configure MCP Tasks support (SEP-1686, experimental): task-augmented tools/call plus the tasks/get, tasks/result, and optionally tasks/list/tasks/cancel operations. Only advertised to clients that negotiated protocol 2025-11-25 or later.
Fields
list::Bool: Whethertasks/listis offered. Note: on an HTTP transport without authentication the server cannot identify requestors, solistis withheld from the advertised capability regardless of this setting (per the spec's security guidance).cancel::Bool: Whethertasks/cancelis offered.
ModelContextProtocol.ToolCapability — Type
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.
ModelContextProtocol.capabilities_to_protocol — Method
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.
ModelContextProtocol.create_init_response — Method
create_init_response(server::Server, protocol_version::String) -> InitializeResultCreate 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.
ModelContextProtocol.merge_capabilities — Method
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.
ModelContextProtocol.to_protocol_format — Method
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.
ModelContextProtocol.auto_register! — Method
auto_register!(server::Server, dir::AbstractString) -> ServerAutomatically register MCP components found in the specified directory structure.
Arguments
server::Server: The server to register components withdir::AbstractString: Root directory containing component subdirectories
Directory Structure
dir/tools/: Contains tool definition filesdir/resources/: Contains resource definition filesdir/prompts/: Contains prompt definition files
Each subdirectory is optional. Files should be .jl files containing component definitions.
Component File Format
Component files must have the tool/resource/prompt as the last expression in the file. The return value of include() is used to obtain the component.
Example:
# tools/my_tool.jl
julia_version_tool = MCPTool(
name = "julia_version",
description = "Get Julia version",
handler = params -> Dict("version" => string(VERSION))
) # ← This must be the last expressionReturns
Server: The updated server instance for method chaining
ModelContextProtocol.default_capabilities — Method
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
ModelContextProtocol.normalize_path — Method
normalize_path(path::String) -> StringConvert 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
ModelContextProtocol.scan_mcp_components — Method
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
Transport Implementation
ModelContextProtocol.TransportError — Type
TransportError(message::String) <: ExceptionException type for transport-specific errors.
Fields
message::String: The error message describing what went wrong
ModelContextProtocol.capture_response_route — Method
capture_response_route(transport::Transport) -> AnyCapture a route handle for delivering the CURRENT request's response later, from outside the server loop (used by tasks/result, which must block until the task completes without blocking the loop). The returned handle is passed to deliver_response.
The default returns nothing — for stream transports like stdio, responses carry their correlation in the JSON-RPC id, so no per-request route exists. Transports that route responses per request (HTTP) override this to detach and return the current request's route so the loop can move on to the next request.
Arguments
transport::Transport: The transport instance
Returns
- An opaque route handle understood by
deliver_responsefor this transport
ModelContextProtocol.close — Function
close(transport::Transport) -> NothingClose the transport connection and clean up resources.
Arguments
transport::Transport: The transport instance to close
Returns
Nothing
ModelContextProtocol.deliver_response — Method
deliver_response(transport::Transport, route::Any, message::String) -> NothingDeliver a serialized JSON-RPC response for a request whose route was captured earlier with capture_response_route. Safe to call from a background task. The default ignores the route and writes to the shared stream (correct for stdio, where write_message is lock-serialized).
Arguments
transport::Transport: The transport instanceroute::Any: The handle returned bycapture_response_routemessage::String: The serialized JSON-RPC response
Returns
Nothing
ModelContextProtocol.flush — Method
flush(transport::Transport) -> NothingFlush any buffered data in the transport. Default implementation does nothing.
Arguments
transport::Transport: The transport instance to flush
Returns
Nothing
ModelContextProtocol.is_connected — Function
is_connected(transport::Transport) -> BoolCheck if the transport is currently connected and operational.
Arguments
transport::Transport: The transport instance to check
Returns
Bool: true if connected and ready, false otherwise
ModelContextProtocol.pending_auth_context — Method
pending_auth_context(transport::Transport) -> Union{Nothing,Any}Return the authenticated user associated with the message most recently read from transport, or nothing when the transport has no per-request authentication (e.g. stdio). Transports that authenticate requests override this; the default is nothing.
ModelContextProtocol.read_message — Function
read_message(transport::Transport) -> Union{String,Nothing}Read a single message from the transport.
Arguments
transport::Transport: The transport instance to read from
Returns
Union{String,Nothing}: The message string if available, or nothing if no message or connection closed
ModelContextProtocol.send_notification — Method
send_notification(transport::Transport, message::String) -> NothingDeliver a server-to-client JSON-RPC notification over transport.
The default writes the message directly — correct for stdio, where notifications and responses share one stream. Transports that multiplex per-request responses (e.g. HTTP, where write_message routes to the calling request's response channel) override this to send notifications over a separate out-of-band channel, so a mid-request notification never corrupts that request's response.
Arguments
transport::Transport: The transport instance to send overmessage::String: The serialized JSON-RPC notification
Returns
Nothing
ModelContextProtocol.set_negotiated_version! — Method
set_negotiated_version!(transport::Transport, version::String) -> NothingInform the transport of the protocol version negotiated during initialize, so transports that advertise a version per response (e.g. the HTTP MCP-Protocol-Version header) echo the negotiated one rather than a static default. Default is a no-op (stdio carries no version metadata).
Arguments
transport::Transport: The transport instance to updateversion::String: The negotiated MCP protocol version
Returns
Nothing
ModelContextProtocol.write_message — Function
write_message(transport::Transport, message::String) -> NothingWrite a message to the transport.
Arguments
transport::Transport: The transport instance to write tomessage::String: The message to send
Returns
Nothing
Throws
TransportError: If the message cannot be sent
ModelContextProtocol.close — Method
close(transport::StdioTransport) -> NothingMark the transport as closed. Does not actually close stdin/stdout.
Arguments
transport::StdioTransport: The stdio transport instance
Returns
Nothing
ModelContextProtocol.flush — Method
flush(transport::StdioTransport) -> NothingFlush the output stream.
Arguments
transport::StdioTransport: The stdio transport instance
Returns
Nothing
ModelContextProtocol.is_connected — Method
is_connected(transport::StdioTransport) -> BoolCheck if the stdio transport is connected.
Arguments
transport::StdioTransport: The stdio transport instance
Returns
Bool: Connection status
ModelContextProtocol.read_message — Method
read_message(transport::StdioTransport) -> Union{String,Nothing}Read a line from the input stream.
Arguments
transport::StdioTransport: The stdio transport instance
Returns
Union{String,Nothing}: The message string, or nothing if empty or EOF
ModelContextProtocol.write_message — Method
write_message(transport::StdioTransport, message::String) -> NothingWrite a message to the output stream with a newline.
Arguments
transport::StdioTransport: The stdio transport instancemessage::String: The message to write
Returns
Nothing
Throws
TransportError: If writing fails
ModelContextProtocol.QueuedHttpRequest — Type
QueuedHttpRequest(id, body, user)Envelope for a request on the HTTP work queue. Carries the per-request authenticated user (or nothing) from the concurrent connection handler to the single server loop, so auth identity travels with the request rather than via shared transport state.
ModelContextProtocol.broadcast_to_sse — Method
broadcast_to_sse(transport::HttpTransport, message::String; event::String="message") -> NothingBroadcast a message immediately to all SSE streams.
Arguments
transport::HttpTransport: The transport instancemessage::String: The message to broadcastevent::String: The event type (default: "message")
Returns
Nothing
ModelContextProtocol.capture_response_route — Method
capture_response_route(transport::HttpTransport) -> Union{String,Nothing}Detach the current request's response route so its response can be delivered later from a background task (see deliver_response). Clears current_request_id so the loop's subsequent write_message calls cannot route into this request's channel.
ModelContextProtocol.close — Method
close(transport::HttpTransport) -> NothingStop the HTTP server and close all connections.
Arguments
transport::HttpTransport: The transport instance
Returns
Nothing
ModelContextProtocol.deliver_response — Method
deliver_response(transport::HttpTransport, route::Union{String,Nothing}, message::String) -> NothingDeliver a deferred response to the request identified by route (captured earlier via capture_response_route). The HTTP connection handler is still blocked on the request's response channel, so the POST stays open until this delivers — which is exactly the blocking behavior tasks/result requires. Dropped silently when the client has disconnected (its channel is gone or closed).
ModelContextProtocol.end_response — Method
end_response(transport::HttpTransport) -> NothingDeprecated: No longer needed as HTTP transport now sends complete responses. This method exists for backward compatibility but does nothing.
Arguments
transport::HttpTransport: The transport instance
Returns
Nothing
ModelContextProtocol.format_sse_event — Method
format_sse_event(data::String; event::Union{String,Nothing}=nothing, id::Union{Int64,String,Nothing}=nothing) -> StringFormat a message as a Server-Sent Event.
Arguments
data::String: The data to sendevent::Union{String,Nothing}: Optional event typeid::Union{Int64,String,Nothing}: Optional event ID
Returns
String: Formatted SSE event
ModelContextProtocol.generate_session_id — Method
generate_session_id() -> StringGenerate a cryptographically secure session ID that meets MCP requirements. Must contain only visible ASCII characters (0x21 to 0x7E).
Returns
String: A valid session ID
ModelContextProtocol.handle_request — Method
handle_request(transport::HttpTransport, stream::HTTP.Stream)Handle incoming HTTP requests following the Streamable HTTP specification. Returns a single JSON response per request.
Arguments
transport::HttpTransport: The transport instancestream::HTTP.Stream: The HTTP stream
Returns
Nothing
ModelContextProtocol.handle_sse_stream — Method
handle_sse_stream(transport::HttpTransport, stream::HTTP.Stream, stream_id::String)Handle a Server-Sent Events connection for notifications and streaming responses.
Arguments
transport::HttpTransport: The transport instancestream::HTTP.Stream: The HTTP streamstream_id::String: Unique identifier for this SSE stream
Returns
Nothing
ModelContextProtocol.is_connected — Method
is_connected(transport::HttpTransport) -> BoolCheck if the HTTP server is running and accepting connections.
Arguments
transport::HttpTransport: The transport instance
Returns
Bool: true if connected, false otherwise
ModelContextProtocol.is_valid_session_id — Method
is_valid_session_id(session_id::String) -> BoolValidate that a session ID contains only visible ASCII characters (0x21 to 0x7E).
Arguments
session_id::String: The session ID to validate
Returns
Bool: true if valid, false otherwise
ModelContextProtocol.pending_auth_context — Method
pending_auth_context(transport::HttpTransport) -> Union{AuthenticatedUser,Nothing}Return the authenticated user of the message most recently read from the queue (set in read_message, consumed immediately by the single server loop). This is how the per-request identity reaches RequestContext.authenticated_user; handlers should read it from the request context, not from the transport.
ModelContextProtocol.read_message — Method
read_message(transport::HttpTransport) -> Union{String,Nothing}Read a message from the request queue. Blocks until a request is available or the transport is disconnected.
Arguments
transport::HttpTransport: The transport instance
Returns
Union{String,Nothing}: The message string, or nothing if disconnected
ModelContextProtocol.send_notification — Method
send_notification(transport::HttpTransport, notification::String) -> NothingSend a notification to all connected SSE streams.
Arguments
transport::HttpTransport: The transport instancenotification::String: The notification message to send
Returns
Nothing
ModelContextProtocol.set_negotiated_version! — Method
set_negotiated_version!(transport::HttpTransport, version::String) -> NothingUpdate the version advertised in MCP-Protocol-Version response headers (and accepted in request headers) to the version negotiated during initialize, so per-request headers echo what the initialize response returned.
ModelContextProtocol.write_message — Method
write_message(transport::HttpTransport, message::String) -> NothingWrite a message to the current request's response channel. The request handler will send this as the HTTP response.
Arguments
transport::HttpTransport: The transport instancemessage::String: The message to send
Returns
Nothing
Utilities
ModelContextProtocol.MCP_LOG_LEVELS — Constant
MCP_LOG_LEVELSThe log levels defined by the MCP spec (RFC 5424 severities), lowest to highest.
ModelContextProtocol.MCPLogger — Type
MCPLogger(stream::IO=stderr, level::LogLevel=Info) -> MCPLoggerCreate a new MCPLogger instance with specified stream and level.
Arguments
stream::IO=stderr: The output stream where log messages will be writtenlevel::LogLevel=Info: The minimum logging level to display
Returns
MCPLogger: A new logger instance
ModelContextProtocol.MCPLogger — Type
MCPLogger <: AbstractLoggerDefine a custom logger for MCP server that formats messages according to protocol requirements.
Fields
stream::IO: The output stream for log messagesmin_level::LogLevel: Minimum logging level to display (mutable sologging/setLevelcan adjust it on the installed logger)message_limits::Dict{Any,Int}: Message limit settings for rate limiting
Logging.handle_message — Method
Logging.handle_message(logger::MCPLogger, level, message, _module, group, id, filepath, line; kwargs...) -> NothingFormat and output log messages according to the MCP protocol format.
Arguments
logger::MCPLogger: The MCP logger instancelevel: The log level of the messagemessage: The log message content_module: The module where the log was generatedgroup: The log groupid: The log message IDfilepath: The source file pathline: The source line numberkwargs...: Additional contextual information to include in the log
Returns
Nothing: Function writes to the logger stream but doesn't return a value
ModelContextProtocol.init_logging — Function
init_logging(level::LogLevel=Info) -> NothingInitialize 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
ModelContextProtocol.mcp_level_to_julia — Method
mcp_level_to_julia(level::String) -> LogLevelMap an MCP/RFC-5424 log level string to the closest Julia LogLevel.
Arguments
level::String: One ofMCP_LOG_LEVELS
Returns
LogLevel:Debug,Info,Warn, orError(the four Julia standard levels)
StructTypes.names — Method
StructTypes.names(::Type{CallToolResult})Map Julia field names to their MCP wire keys: is_error → isError (the spec key — clients rely on it to detect tool errors) and structured_content → structuredContent.
StructTypes.omitempties — Method
StructTypes.omitempties(::Type{CallToolResult}) -> Tuple{Symbol,Symbol}Omit structured_content and _meta from the response when they are nothing, so tools that don't use them emit no structuredContent/_meta keys.
StructTypes.omitempties — Method
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
StructTypes.omitempties — Method
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