API Reference
This page contains the complete API reference for ModelContextProtocol.jl.
Base.convert
— Methodconvert(::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
Logging.handle_message
— MethodLogging.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 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.api
— MethodModelContextProtocol.jl API Overview
What is the Model Context Protocol (MCP)?
The Model Context Protocol (MCP) is an open standard introduced by Anthropic in 2024 that standardizes how AI applications connect with external tools, data sources, and systems. Think of it as "USB for AI integrations" - it provides a universal way for Large Language Models (LLMs) to access and interact with external resources without requiring custom integrations for each combination.
MCP Architecture Overview
MCP follows a client-server architecture built on JSON-RPC 2.0, where:
- MCP Hosts: AI applications (Claude Desktop, IDEs, chatbots) that want to access external capabilities
- MCP Clients: Protocol clients embedded within hosts that maintain 1:1 connections with servers
- MCP Servers: Lightweight programs that expose specific capabilities (tools, resources, prompts) through the standardized protocol
- Transport Layer: Communication mechanism using STDIO (local) or HTTP+SSE (remote)
Client-Server Interaction Flow
When an MCP server starts and a client connects, the following happens:
- Initialization Handshake: Client and server exchange capabilities and protocol versions
- Capability Discovery: Client requests what features (tools/resources/prompts) the server offers
- Registration: Server responds with available capabilities, but doesn't send tool details yet
- Active Discovery: Client must explicitly call
tools/list
,resources/list
, orprompts/list
to get actual definitions - Invocation: When the LLM needs to use a tool, the client sends invocation requests to the server
- Execution: Server executes the request and returns structured results
ModelContextProtocol.jl's Role
ModelContextProtocol.jl is a Julia implementation that makes it extremely easy to create MCP servers. It handles all the protocol complexity, JSON-RPC communication, and provides a developer-friendly API focused on simply defining tools, resources, and prompts.
Architecture Overview
ModelContextProtocol.jl is built around several key architectural principles that make MCP server development intuitive:
1. Auto-Registration System
The package's flagship feature automatically discovers and registers MCP components without explicit registration code. This leverages Julia's metaprogramming capabilities to scan modules or directories for tool definitions.
2. Content-Centric Design
All communication revolves around Content
objects that provide type safety while allowing flexibility:
abstract type Content end
Base.@kwdef struct TextContent <: Content
type::String = "text" # Required by MCP schema
text::String # The actual text content
annotations::AbstractDict{String,Any} = LittleDict{String,Any}() # Optional metadata
end
Base.@kwdef struct ImageContent <: Content
type::String = "image" # Required by MCP schema
data::Vector{UInt8} # Binary image data (NOT base64 string)
mime_type::String # MIME type of the image
annotations::AbstractDict{String,Any} = LittleDict{String,Any}() # Optional metadata
end
Base.@kwdef struct EmbeddedResource <: Content
type::String = "resource" # Required by MCP schema
resource::Union{TextResourceContents, BlobResourceContents} # The embedded resource
annotations::AbstractDict{String,Any} = LittleDict{String,Any}() # Optional metadata
end
3. Functional Handler Pattern
Tools, prompts, and resources use consistent handler functions:
# Tool handler: Dict -> Content or Vector{Content}
handler = (params::Dict) -> TextContent(text = "Result: $(params["input"])")
# Resource handler: String -> ResourceContents
resource_handler = (uri::String) -> TextResourceContents(uri = uri, text = read(uri, String))
# Prompt handler: Dict -> MCPPromptMessage
prompt_handler = (args::Dict) -> MCPPromptMessage(role = "user", content = TextContent(...))
Auto-Registration System Detailed
The auto-registration system is the core innovation that eliminates boilerplate. Here's how it works:
Directory-Based Auto-Registration
The most powerful approach uses a structured directory layout:
my_mcp_project/
├── Project.toml
├── main.jl # Server startup script
└── mcp_components/ # Auto-registration directory
├── tools/ # Tool definitions
│ ├── calculator.jl
│ ├── file_reader.jl
│ └── web_scraper.jl
├── resources/ # Resource definitions (optional)
│ ├── docs.jl
│ └── config.jl
└── prompts/ # Prompt definitions (optional)
└── code_review.jl
How to Structure Components
Each .jl
file in the component directories should define one or more MCP components:
tools/calculator.jl
:
# Simple tool definition - no exports or module setup needed
calculator = MCPTool(
name = "calculate",
description = "Perform basic mathematical calculations",
parameters = [
ToolParameter(name = "expression", description = "Mathematical expression to evaluate", type = "string", required = true),
ToolParameter(name = "precision", description = "Decimal places for rounding", type = "number", default = 2.0)
],
handler = function(params)
expr = params["expression"]
precision = params["precision"]
# Note: In production, use a safe expression parser instead of eval
result = Base.eval(Main, Meta.parse(expr))
return TextContent(text = "Result: $(round(result, digits=Int(precision)))")
end
)
tools/file_reader.jl
:
using Base64
file_tool = MCPTool(
name = "read_file",
description = "Read and return file contents",
parameters = [
ToolParameter(name = "path", description = "File path to read", type = "string", required = true),
ToolParameter(name = "encoding", description = "Text encoding", type = "string", default = "utf-8")
],
handler = function(params)
path = params["path"]
if !isfile(path)
return CallToolResult(
content = [TextContent(text = "File not found: $path")],
is_error = true
)
end
content = read(path, String)
return [
TextContent(text = "File: $path"),
TextContent(text = content)
]
end,
return_type = Vector{Content}
)
resources/docs.jl
:
docs_resource = MCPResource(
uri = "docs://*",
name = "Documentation",
description = "Access to project documentation",
mime_type = "text/markdown",
data_provider = function(uri::String)
# Strip the docs:// prefix and read file
file_path = replace(uri, "docs://" => "docs/")
if isfile(file_path)
content = read(file_path, String)
return TextResourceContents(
uri = uri,
mime_type = "text/markdown",
text = content
)
else
error("Documentation file not found: $file_path")
end
end
)
Server Startup Script
main.jl
:
#!/usr/bin/env julia
using Pkg
Pkg.activate(@__DIR__) # Activate local project environment
using ModelContextProtocol
# Create server with auto-registration
server = mcp_server(
name = "my-awesome-server",
description = "A comprehensive MCP server with auto-discovered components",
auto_register_dir = "mcp_components" # Scans this directory structure
)
# Start the server (uses STDIO transport by default)
println("Starting MCP Server...")
start!(server)
Advanced Auto-Registration Features
1. Multiple Variables Per File
Files can define multiple components:
# tools/math_tools.jl
add_tool = MCPTool(
name = "add",
description = "Add two numbers",
parameters = [
ToolParameter(name = "a", type = "number", required = true),
ToolParameter(name = "b", type = "number", required = true)
],
handler = (p) -> TextContent(text = "$(p["a"] + p["b"])")
)
multiply_tool = MCPTool(
name = "multiply",
description = "Multiply two numbers",
parameters = [
ToolParameter(name = "a", type = "number", required = true),
ToolParameter(name = "b", type = "number", required = true)
],
handler = (p) -> TextContent(text = "$(p["a"] * p["b"])")
)
# Both tools are automatically discovered
2. Auto-Registration Implementation
The system works by scanning .jl
files and looking for variables of the correct types:
function auto_register!(server::Server, dir::AbstractString)
component_dirs = [
("tools", MCPTool),
("resources", MCPResource),
("prompts", MCPPrompt)
]
for (subdir, type) in component_dirs
component_dir = joinpath(dir, subdir)
if isdir(component_dir)
for file in readdir(component_dir, join=true)
if endswith(file, ".jl")
# Create temporary module and include file
mod = Module()
Core.eval(mod, :(using ModelContextProtocol))
Base.include(mod, file)
# Find all variables matching the target type
for name in names(mod, all=true)
if isdefined(mod, name)
component = getfield(mod, name)
if component isa type
register!(server, component)
@info "Registered $type from $file: $name"
end
end
end
end
end
end
end
end
3. Benefits of Auto-Registration
- Zero Boilerplate: No manual registration calls needed
- File-Based Organization: Natural separation of concerns
- Dynamic Discovery: Add new tools by creating new files
- Error Isolation: Problems in one file don't affect others
- Clear Structure: Easy to understand and maintain
Module-Based Registration (Alternative Approach)
For simpler cases, you can also register from Julia modules:
module MyTools
using ModelContextProtocol
time_tool = MCPTool(
name = "current_time",
description = "Get current time",
parameters = [],
handler = (p) -> TextContent(text = string(now()))
)
weather_tool = MCPTool(
name = "weather",
description = "Get weather info",
parameters = [ToolParameter(name = "location", description = "Location to get weather for", type = "string", required = true)],
handler = (p) -> TextContent(text = "Weather in $(p["location"]): Sunny")
)
end
# Create server and register tools from module
server = mcp_server(name = "time-weather-server")
# Manual registration from module
for name in names(MyTools, all=true)
obj = getfield(MyTools, name)
if obj isa MCPTool
register!(server, obj)
end
end
start!(server)
Type Hierarchy
Content (abstract)
├── TextContent # Has: type="text", text, annotations
├── ImageContent # Has: type="image", data::Vector{UInt8}, mime_type, annotations
└── EmbeddedResource # Has: type="resource", resource::Union{TextResourceContents, BlobResourceContents}, annotations
ResourceContents (abstract)
├── TextResourceContents # Has: uri, text, mime_type::Union{String,Nothing}
└── BlobResourceContents # Has: uri, blob::Vector{UInt8}, mime_type::Union{String,Nothing}
Tool (abstract)
└── MCPTool # Has: name, description, parameters, handler, return_type
Resource (abstract)
└── MCPResource # Has: uri::URI, name, description, mime_type, data_provider, annotations
MCPPrompt # Has: name, description, arguments, messages (NO handler - static templates)
PromptArgument # Has: name, description, required
PromptMessage # Has: content, role
ResponseResult (abstract)
└── CallToolResult # Has: content::Vector{Dict{String,Any}}, is_error::Bool (NO metadata field)
Essential Types
Tool Definition
Base.@kwdef struct MCPTool <: Tool
name::String # Unique tool identifier
description::String # Human-readable description
parameters::Vector{ToolParameter} # Input parameters schema
handler::Function # Processing function
return_type::Type = Vector{Content} # Expected return type (v0.2+)
end
Base.@kwdef struct ToolParameter
name::String # Parameter name
description::String # Parameter description
type::String # JSON Schema type ("string", "number", "boolean", "object", "array")
required::Bool = false # Whether parameter is required
default::Any = nothing # Default value if not provided
end
Content Types
# Text content constructor
TextContent(text = "Hello, world!")
# Image content constructor - note: data is Vector{UInt8}, not base64 string
ImageContent(
data = image_bytes, # Vector{UInt8}
mime_type = "image/png"
)
# Embedded resource constructor
EmbeddedResource(
resource = TextResourceContents(
uri = "file:///path/to/file.txt",
text = "content"
)
)
# Direct result control (v0.2+) - content is Vector{Dict}, not Vector{Content}
CallToolResult(
content = [Dict("type" => "text", "text" => "result")], # Pre-serialized
is_error = false
)
Resource Definition
Base.@kwdef struct MCPResource <: Resource
uri::URI # URI pattern (uses URI type, not String)
name::String # Human-readable name
description::String = "" # Resource description
mime_type::String = "application/json" # MIME type of resource content
data_provider::Function # Function that provides data (NOT handler)
annotations::AbstractDict{String,Any} = LittleDict{String,Any}() # Optional metadata
end
Base.@kwdef struct TextResourceContents <: ResourceContents
uri::String # Actual URI
text::String # Text content
mime_type::Union{String,Nothing} = nothing # Optional MIME type
end
Base.@kwdef struct BlobResourceContents <: ResourceContents
uri::String # Actual URI
blob::Vector{UInt8} # Binary content
mime_type::Union{String,Nothing} = nothing # Optional MIME type
end
Prompt Definition
Base.@kwdef struct MCPPrompt
name::String # Prompt identifier
description::String = "" # Prompt description
arguments::Vector{PromptArgument} = PromptArgument[] # Input arguments
messages::Vector{PromptMessage} = PromptMessage[] # Static template messages (NO handler)
end
Base.@kwdef struct PromptArgument
name::String # Argument name
description::String = "" # Argument description
required::Bool = false # Whether required
end
Base.@kwdef struct PromptMessage
content::Union{TextContent, ImageContent, EmbeddedResource} # Message content
role::Role = user # Role enum (user or assistant), not String
end
Core Functions
Server Creation
# Basic server creation
server = mcp_server(name = "my-server")
# Server with auto-registration
server = mcp_server(
name = "auto-server",
description = "Server with auto-discovered components",
auto_register_dir = "mcp_components"
)
# Server with explicit components
server = mcp_server(
name = "explicit-server",
tools = [tool1, tool2],
resources = [resource1],
prompts = [prompt1]
)
# Start the server (STDIO transport)
start!(server)
Component Registration
# Manual registration
register!(server, my_tool)
register!(server, my_resource)
register!(server, my_prompt)
# Batch registration
tools = [tool1, tool2, tool3]
foreach(t -> register!(server, t), tools)
Content Creation
# Text content
text = TextContent(text = "Hello, world!")
# Image content (raw bytes - base64 encoding happens automatically during JSON serialization)
image = ImageContent(
data = image_bytes, # Vector{UInt8} - raw binary data, NOT base64 string
mime_type = "image/png"
)
# Multi-content response
results = [
TextContent(text = "Analysis complete"),
ImageContent(data = chart_data, mime_type = "image/png"),
TextContent(text = "See chart above for details")
]
Tool Creation Patterns
Simple Text Tool
echo_tool = MCPTool(
name = "echo",
description = "Echo the input message",
parameters = [
ToolParameter(name = "message", description = "Message to echo back", type = "string", required = true)
],
handler = (params) -> TextContent(text = params["message"])
)
Tool with Default Parameters
format_tool = MCPTool(
name = "format_json",
description = "Format JSON with configurable options",
parameters = [
ToolParameter(name = "json_string", description = "JSON string to format", type = "string", required = true),
ToolParameter(name = "indent", description = "Number of spaces for indentation", type = "number", default = 2),
ToolParameter(name = "sort_keys", description = "Whether to sort object keys", type = "boolean", default = false)
],
handler = function(params)
data = JSON3.read(params["json_string"])
indent = Int(params["indent"])
sort_keys = params["sort_keys"]
formatted = JSON3.pretty(data, indent = indent, sort_keys = sort_keys)
return TextContent(text = formatted)
end
)
Multi-Content Tool
analyze_tool = MCPTool(
name = "analyze_data",
description = "Analyze data and return text + visualization",
parameters = [
ToolParameter(name = "data", description = "JSON data to analyze", type = "string", required = true)
],
handler = function(params)
# Process data
data = JSON3.read(params["data"])
# Create summary
summary = TextContent(
text = "Data contains $(length(data)) items with keys: $(join(keys(first(data)), ", "))"
)
# Create visualization (mock chart)
chart = ImageContent(
data = generate_chart_bytes(data), # Your chart generation function returns Vector{UInt8}
mime_type = "image/png"
)
return [summary, chart] # Return multiple content items
end,
return_type = Vector{Content}
)
Error-Handling Tool
file_reader = MCPTool(
name = "read_file",
description = "Read file with comprehensive error handling",
parameters = [
ToolParameter(name = "path", description = "File path to read", type = "string", required = true)
],
handler = function(params)
path = params["path"]
# Validate file exists
if !isfile(path)
return CallToolResult(
content = [TextContent(text = "Error: File not found at path '$path'")],
is_error = true
)
end
# Check file permissions
if !isreadable(path)
return CallToolResult(
content = [TextContent(text = "Error: File '$path' is not readable")],
is_error = true
)
end
try
content = read(path, String)
file_size = filesize(path)
return [
TextContent(text = "Successfully read file: $path"),
TextContent(text = "File size: $file_size bytes"),
TextContent(text = "Content:\n$content")
]
catch e
return CallToolResult(
content = [TextContent(text = "Error reading file: $(string(e))")],
is_error = true
)
end
end,
return_type = Union{Vector{Content}, CallToolResult}
)
Complete Workflow Examples
1. Creating a File Management Server
Project Structure:
file_server/
├── main.jl
└── mcp_components/
├── tools/
│ ├── file_operations.jl
│ └── directory_scanner.jl
└── resources/
└── file_system.jl
tools/file_operations.jl
:
using Base64
read_file = MCPTool(
name = "read_file",
description = "Read file contents",
parameters = [
ToolParameter(name = "path", description = "File path to read", type = "string", required = true),
ToolParameter(name = "max_size", type = "number", default = 1048576) # 1MB default
],
handler = function(params)
path = params["path"]
max_size = Int(params["max_size"])
if !isfile(path)
return TextContent(text = "File not found: $path")
end
size = filesize(path)
if size > max_size
return TextContent(text = "File too large: $(size) bytes (max: $(max_size))")
end
content = read(path, String)
return TextContent(text = "File: $path\n\n$content")
end
)
write_file = MCPTool(
name = "write_file",
description = "Write content to file",
parameters = [
ToolParameter(name = "path", description = "File path to read", type = "string", required = true),
ToolParameter(name = "content", type = "string", required = true),
ToolParameter(name = "append", type = "boolean", default = false)
],
handler = function(params)
path = params["path"]
content = params["content"]
append_mode = params["append"]
try
if append_mode
open(path, "a") do file
write(file, content)
end
else
write(path, content)
end
return TextContent(text = "Successfully wrote to $path")
catch e
return CallToolResult(
content = [TextContent(text = "Failed to write file: $(string(e))")],
is_error = true
)
end
end
)
tools/directory_scanner.jl
:
list_directory = MCPTool(
name = "list_directory",
description = "List directory contents with file information",
parameters = [
ToolParameter(name = "path", description = "File path to read", type = "string", required = true),
ToolParameter(name = "recursive", type = "boolean", default = false),
ToolParameter(name = "show_hidden", type = "boolean", default = false)
],
handler = function(params)
path = params["path"]
recursive = params["recursive"]
show_hidden = params["show_hidden"]
if !isdir(path)
return TextContent(text = "Directory not found: $path")
end
files = []
if recursive
for (root, dirs, filenames) in walkdir(path)
for filename in filenames
if show_hidden || !startswith(filename, ".")
full_path = joinpath(root, filename)
size = filesize(full_path)
modified = Dates.format(Dates.unix2datetime(mtime(full_path)), "yyyy-mm-dd HH:MM:SS")
push!(files, "$full_path ($size bytes, modified: $modified)")
end
end
end
else
for item in readdir(path, join=true)
if show_hidden || !startswith(basename(item), ".")
if isfile(item)
size = filesize(item)
modified = Dates.format(Dates.unix2datetime(mtime(item)), "yyyy-mm-dd HH:MM:SS")
push!(files, "$(basename(item)) ($size bytes, modified: $modified)")
else
push!(files, "$(basename(item))/ (directory)")
end
end
end
end
result = "Directory listing for $path:\n" * join(files, "\n")
return TextContent(text = result)
end
)
resources/file_system.jl
:
file_system = MCPResource(
uri = "file://*",
name = "File System Access",
description = "Direct access to local file system",
mime_type = "application/octet-stream",
data_provider = function(uri::String)
# Remove file:// prefix
local_path = replace(uri, "file://" => "")
if isfile(local_path)
# Detect MIME type based on extension
ext = lowercase(splitext(local_path)[2])
mime_type = if ext in [".txt", ".md", ".json", ".xml", ".csv"]
"text/plain"
elseif ext in [".html", ".htm"]
"text/html"
elseif ext in [".js"]
"application/javascript"
elseif ext in [".css"]
"text/css"
else
"application/octet-stream"
end
if startswith(mime_type, "text/")
content = read(local_path, String)
return TextResourceContents(
uri = uri,
mime_type = mime_type,
text = content
)
else
content = read(local_path)
return BlobResourceContents(
uri = uri,
mime_type = mime_type,
blob = content
)
end
else
error("File not found: $local_path")
end
end
)
main.jl
:
#!/usr/bin/env julia
using Pkg
Pkg.activate(@__DIR__)
using ModelContextProtocol
# Create server with auto-registration
server = mcp_server(
name = "file-management-server",
version = "2024-11-05",
description = "Comprehensive file management MCP server",
auto_register_dir = "mcp_components"
)
println("Starting File Management MCP Server...")
println("Available tools will be auto-discovered from mcp_components/")
start!(server)
2. Creating a Data Analysis Server
Project Structure:
data_server/
├── main.jl
├── data/
│ ├── sample.csv
│ └── config.json
└── mcp_components/
├── tools/
│ ├── data_loader.jl
│ ├── statistics.jl
│ └── visualization.jl
└── resources/
└── datasets.jl
tools/data_loader.jl
:
using CSV, DataFrames, JSON3
load_csv = MCPTool(
name = "load_csv",
description = "Load and preview CSV data",
parameters = [
ToolParameter(name = "file_path", type = "string", required = true),
ToolParameter(name = "delimiter", type = "string", default = ","),
ToolParameter(name = "preview_rows", type = "number", default = 5)
],
handler = function(params)
file_path = params["file_path"]
delimiter = params["delimiter"][1] # Convert to char
preview_rows = Int(params["preview_rows"])
try
df = CSV.read(file_path, DataFrame, delim = delimiter)
total_rows, total_cols = size(df)
# Create summary
summary_text = """
Dataset loaded successfully!
- File: $file_path
- Dimensions: $total_rows rows × $total_cols columns
- Columns: $(join(names(df), ", "))
"""
# Create preview
preview_df = first(df, preview_rows)
preview_text = sprint(show, preview_df, context = :limit => true)
return [
TextContent(text = summary_text),
TextContent(text = "Preview (first $preview_rows rows):\n$preview_text")
]
catch e
return CallToolResult(
content = [TextContent(text = "Error loading CSV: $(string(e))")],
is_error = true
)
end
end,
return_type = Vector{Content}
)
3. Running the Servers
To run any of these servers:
# Navigate to the project directory
cd file_server/ # or data_server/
# Run the server
julia main.jl
# The server will start and listen on STDIO
# Connect from Claude Desktop or other MCP clients
Important Architecture Patterns
1. Stateless Handlers
Handlers should be pure functions without side effects in server state:
# Good: External state management
const cache = Dict{String, Any}()
cached_tool = MCPTool(
name = "cached_compute",
handler = function(params)
key = params["key"]
if haskey(cache, key)
return TextContent(text = "Cached: $(cache[key])")
end
result = expensive_computation(params)
cache[key] = result
return TextContent(text = "Computed: $result")
end
)
2. Content Serialization
The package automatically serializes content via content2dict
(src/utils/serialization.jl):
# Automatic serialization
TextContent(text = "Hello")
# → {"type": "text", "text": "Hello"}
ImageContent(data = base64_data, mime_type = "image/png")
# → {"type": "image", "data": "...", "mimeType": "image/png"}
[TextContent(text = "Part 1"), TextContent(text = "Part 2")]
# → [{"type": "text", "text": "Part 1"}, {"type": "text", "text": "Part 2"}]
3. Error Handling Strategies
# Strategy 1: Exception handling (automatic error response)
error_tool1 = MCPTool(
handler = function(params)
if invalid_input(params)
error("Invalid input provided") # Becomes MCP error response
end
return TextContent(text = "Success")
end
)
# Strategy 2: Explicit error control
error_tool2 = MCPTool(
handler = function(params)
if invalid_input(params)
return CallToolResult(
content = [TextContent(text = "Validation failed")],
is_error = true
)
end
return TextContent(text = "Success")
end
)
4. Performance Considerations
- LittleDict Usage: Package uses
LittleDict
for small dictionaries (< 10 items) for better performance - Lazy Resource Loading: Resources are loaded on-demand via handlers
- Content Chunking: For large content, consider splitting into multiple content items
5. Protocol Compliance
ModelContextProtocol.jl ensures MCP compliance automatically:
- Tools are not included in initialization response (only capability indication)
- Clients must call
tools/list
to discover actual tools - Proper JSON-RPC message formatting
- Automatic parameter validation and default application
- Correct error response formatting
This architecture enables ModelContextProtocol.jl to provide an intuitive, powerful API while maintaining full MCP specification compliance and excellent performance characteristics.
api()
returns this documentation as a plain String
.
ModelContextProtocol.auto_register!
— Methodauto_register!(server::Server, dir::AbstractString) -> Server
Automatically 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.
Returns
Server
: The updated server instance for method chaining
ModelContextProtocol.capabilities_to_protocol
— Methodcapabilities_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.content2dict
— Functioncontent2dict(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())
ModelContextProtocol.convert_to_content_type
— Methodconvert_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 convertreturn_type::Type
: The target Content type to convert to
Returns
Content
: The converted Content object or the original result if no conversion is applicable
ModelContextProtocol.create_init_response
— Methodcreate_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.
ModelContextProtocol.default_capabilities
— Methoddefault_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.get_params_type
— Methodget_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, ornothing
if no specific type is defined
ModelContextProtocol.get_result_type
— Methodget_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, ornothing
if not known
Note: This is a placeholder that needs to be implemented with request tracking.
ModelContextProtocol.handle_call_tool
— Methodhandle_call_tool(ctx::RequestContext, params::CallToolParams) -> HandlerResult
Handle requests to call a specific tool with the provided parameters.
Arguments
ctx::RequestContext
: The current request contextparams::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
ModelContextProtocol.handle_initialize
— Methodhandle_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 contextparams::InitializeParams
: The initialization parameters from the client
Returns
HandlerResult
: Contains the server's capabilities and configuration
ModelContextProtocol.handle_list_prompts
— Methodhandle_list_prompts(ctx::RequestContext, params::ListPromptsParams) -> HandlerResult
Handle requests to list available prompts on the MCP server.
Arguments
ctx::RequestContext
: The current request contextparams::ListPromptsParams
: Parameters for the list request (including optional cursor)
Returns
HandlerResult
: Contains information about all available prompts
ModelContextProtocol.handle_list_resources
— Methodhandle_list_resources(ctx::RequestContext, params::ListResourcesParams) -> HandlerResult
Handle requests to list all available resources on the MCP server.
Arguments
ctx::RequestContext
: The current request contextparams::ListResourcesParams
: Parameters for the list request (including optional cursor)
Returns
HandlerResult
: Contains information about all registered resources
ModelContextProtocol.handle_list_tools
— Methodhandle_list_tools(ctx::RequestContext, params::ListToolsParams) -> HandlerResult
Handle requests to list all available tools on the MCP server.
Arguments
ctx::RequestContext
: The current request contextparams::ListToolsParams
: Parameters for the list request (including optional cursor)
Returns
HandlerResult
: Contains information about all registered tools
ModelContextProtocol.handle_notification
— Methodhandle_notification(ctx::RequestContext, notification::JSONRPCNotification) -> Nothing
Process notification messages from clients that don't require responses.
Arguments
ctx::RequestContext
: The current request contextnotification::JSONRPCNotification
: The notification to process
Returns
Nothing
: Notifications don't generate responses
ModelContextProtocol.handle_ping
— Methodhandle_ping(ctx::RequestContext, params::Nothing) -> HandlerResult
Handle MCP protocol ping requests.
Arguments
ctx::RequestContext
: The current request contextparams::Nothing
: The ping parameters does not contain any data
Returns
HandlerResult
: Ping returns an empty response payload
ModelContextProtocol.handle_read_resource
— Methodhandle_read_resource(ctx::RequestContext, params::ReadResourceParams) -> HandlerResult
Handle requests to read content from a specific resource by URI.
Arguments
ctx::RequestContext
: The current request contextparams::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
ModelContextProtocol.handle_request
— Methodhandle_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 requestrequest::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 initializationresources/list
: List available resourcesresources/read
: Read a specific resourcetools/list
: List available toolstools/call
: Invoke a specific toolprompts/list
: List available promptsprompts/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
ModelContextProtocol.init_logging
— Functioninit_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
ModelContextProtocol.mcp_server
— Methodmcp_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 instanceversion::String
: Server implementation versiontools
: Tools to expose to the modelresources
: Resources available to the modelprompts
: Predefined prompts for the modeldescription::String
: Optional server descriptioncapabilities::Vector{Capability}
: Server capability configurationauto_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)
ModelContextProtocol.merge_capabilities
— Methodmerge_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.normalize_path
— Methodnormalize_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
ModelContextProtocol.parse_error_response
— Methodparse_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
ModelContextProtocol.parse_message
— Methodparse_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)
ModelContextProtocol.parse_notification
— Methodparse_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
ModelContextProtocol.parse_request
— Methodparse_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
ModelContextProtocol.parse_success_response
— Methodparse_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
ModelContextProtocol.process_message
— Methodprocess_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.register!
— Functionregister!(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 withcomponent
: The component to register (can be a tool, resource, or prompt)
Returns
Server
: The server instance for method chaining
ModelContextProtocol.run_server_loop
— Methodrun_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 instancestate::ServerState
: The server state object to track running status
Returns
Nothing
: The function runs until interrupted or state.running becomes false
ModelContextProtocol.scan_mcp_components
— Methodscan_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
ModelContextProtocol.serialize_message
— Methodserialize_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
ModelContextProtocol.serialize_resource_contents
— Methodserialize_resource_contents(resource::ResourceContents) -> Dict{String,Any}
Serialize resource contents to protocol format.
Arguments
resource::ResourceContents
: The resource contents to serialize
Returns
Dict{String,Any}
: The serialized resource contents
ModelContextProtocol.start!
— Methodstart!(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
ModelContextProtocol.stop!
— Methodstop!(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
ModelContextProtocol.subscribe!
— Methodsubscribe!(server::Server, uri::String, callback::Function) -> Server
Subscribe 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.to_protocol_format
— Methodto_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.unsubscribe!
— Methodunsubscribe!(server::Server, uri::String, callback::Function) -> Server
Remove 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
StructTypes.omitempties
— MethodStructTypes.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
— MethodStructTypes.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
ModelContextProtocol.BlobResourceContents
— TypeBlobResourceContents(; uri::String, blob::Vector{UInt8}, mime_type::Union{String,Nothing}=nothing) <: ResourceContents
Binary contents for MCP resources.
Fields
uri::String
: Unique identifier for the resourceblob::Vector{UInt8}
: The binary content of the resourcemime_type::Union{String,Nothing}
: Optional MIME type of the content
ModelContextProtocol.CallToolParams
— TypeCallToolParams(; 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 callarguments::Union{Dict{String,Any},Nothing}
: Optional arguments to pass to the tool
ModelContextProtocol.CallToolResult
— TypeCallToolResult(; 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 toolis_error::Bool
: Whether the tool execution resulted in an error
ModelContextProtocol.Capability
— TypeCapability
Abstract base type for all MCP protocol capabilities. Capabilities represent protocol features that servers can support. Concrete implementations define configuration for specific feature sets.
ModelContextProtocol.CapabilityResponse
— TypeCapabilityResponse(;
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.ClientCapabilities
— TypeClientCapabilities(; 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.Content
— TypeContent
Abstract base type for all content formats in the MCP protocol. Content can be exchanged between clients and servers in various formats.
ModelContextProtocol.EmbeddedResource
— TypeEmbeddedResource(; resource::Union{TextResourceContents, BlobResourceContents},
annotations::AbstractDict{String,Any}=LittleDict{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 contentannotations::AbstractDict{String,Any}
: Optional metadata about the resource
ModelContextProtocol.ErrorInfo
— TypeErrorInfo(; 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
— TypeGetPromptParams(; 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 retrievearguments::Union{Dict{String,String},Nothing}
: Optional arguments to apply to the prompt template
ModelContextProtocol.GetPromptResult
— TypeGetPromptResult(; description::String, messages::Vector{PromptMessage}) <: ResponseResult
Result returned from a get prompt request.
Fields
description::String
: Description of the promptmessages::Vector{PromptMessage}
: The prompt messages with template variables replaced
ModelContextProtocol.HandlerResult
— TypeHandlerResult(; 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.
ModelContextProtocol.ImageContent
— TypeImageContent(; data::Vector{UInt8}, mime_type::String, annotations::AbstractDict{String,Any}=LittleDict{String,Any}()) <: Content
Image-based content for MCP protocol messages.
Fields
type::String
: Content type identifier (always "image")data::Vector{UInt8}
: The binary image datamime_type::String
: MIME type of the image (e.g., "image/png")annotations::AbstractDict{String,Any}
: Optional metadata about the content
ModelContextProtocol.Implementation
— TypeImplementation(; 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 implementationversion::String
: Version string of the implementation
ModelContextProtocol.InitializeParams
— TypeInitializeParams(; capabilities::ClientCapabilities=ClientCapabilities(),
clientInfo::Implementation=Implementation(),
protocolVersion::String) <: RequestParams
Parameters for MCP protocol initialization requests.
Fields
capabilities::ClientCapabilities
: Client capabilities being reportedclientInfo::Implementation
: Information about the client implementationprotocolVersion::String
: Version of the MCP protocol being used
ModelContextProtocol.InitializeResult
— TypeInitializeResult(; 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 implementationcapabilities::Dict{String,Any}
: Server capabilities being reportedprotocolVersion::String
: Version of the MCP protocol being usedinstructions::String
: Optional usage instructions for clients
ModelContextProtocol.JSONRPCError
— TypeJSONRPCError(; 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 nullerror::ErrorInfo
: Information about the error that occurred
ModelContextProtocol.JSONRPCNotification
— TypeJSONRPCNotification(; 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 methodparams::Union{RequestParams,Dict{String,Any}}
: Parameters for the notification
ModelContextProtocol.JSONRPCRequest
— TypeJSONRPCRequest(; 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 requestmethod::String
: Name of the method to invokeparams::Union{RequestParams, Nothing}
: Parameters for the methodmeta::RequestMeta
: Additional metadata for the request
ModelContextProtocol.JSONRPCResponse
— TypeJSONRPCResponse(; id::RequestId, result::Union{ResponseResult,AbstractDict{String,Any}}) <: Response
JSON-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
— TypeListPromptsParams(; 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
ModelContextProtocol.ListPromptsResult
— TypeListPromptsResult(; 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 metadatanextCursor::Union{String,Nothing}
: Optional pagination cursor for fetching more prompts
ModelContextProtocol.ListResourcesParams
— TypeListResourcesParams(; 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
ModelContextProtocol.ListResourcesResult
— TypeListResourcesResult(; 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 metadatanextCursor::Union{String,Nothing}
: Optional pagination cursor for fetching more resources
ModelContextProtocol.ListToolsParams
— TypeListToolsParams(; 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
ModelContextProtocol.ListToolsResult
— TypeListToolsResult(; 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 metadatanextCursor::Union{String,Nothing}
: Optional pagination cursor for fetching more tools
ModelContextProtocol.LoggingCapability
— TypeLoggingCapability(; levels::Vector{String}=["info", "warn", "error"])
Configure logging-related capabilities for an MCP server.
Fields
levels::Vector{String}
: Supported logging levels.
ModelContextProtocol.MCPLogger
— TypeMCPLogger(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 writtenlevel::LogLevel=Info
: The minimum logging level to display
Returns
MCPLogger
: A new logger instance
ModelContextProtocol.MCPLogger
— TypeMCPLogger <: AbstractLogger
Define 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 displaymessage_limits::Dict{Any,Int}
: Message limit settings for rate limiting
ModelContextProtocol.MCPMessage
— TypeMCPMessage
Abstract base type for all message types in the MCP protocol. Serves as the root type for requests, responses, and notifications.
ModelContextProtocol.MCPPrompt
— TypeMCPPrompt(; 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 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 prompt
ModelContextProtocol.MCPPrompt
— MethodMCPPrompt(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 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
— TypeMCPResource(; 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 resourcename::String
: Human-readable name for the resourcedescription::String
: Detailed description of the resourcemime_type::String
: MIME type of the resource datadata_provider::Function
: Function that provides the resource data when calledannotations::AbstractDict{String,Any}
: Additional metadata for the resource
ModelContextProtocol.MCPResource
— MethodMCPResource(; uri, name, description="", mime_type="application/json",
data_provider, annotations=LittleDict{String,Any}()) -> MCPResource
Create a resource with automatic URI conversion from strings.
Arguments
uri
: String or URI identifier for the resourcename
: Human-readable name for the resourcedescription
: Detailed descriptionmime_type
: MIME type of the resourcedata_provider
: Function that returns the resource data when calledannotations
: Additional metadata for the resource
Returns
MCPResource
: A new resource with the provided configuration
ModelContextProtocol.MCPTool
— TypeMCPTool(; name::String, description::String, parameters::Vector{ToolParameter},
handler::Function, return_type::Type=Vector{Content}) <: Tool
Implement 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}
: Parameters that the tool acceptshandler::Function
: Function that implements the tool's functionalityreturn_type::Type
: Expected return type of the handler (defaults to Vector{Content})
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.Notification
— TypeNotification <: MCPMessage
Abstract base type for one-way notifications in the MCP protocol. Notification messages don't expect a corresponding response.
ModelContextProtocol.Progress
— TypeProgress(; 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 trackercurrent::Float64
: Current progress valuetotal::Union{Float64,Nothing}
: Optional total expected valuemessage::Union{String,Nothing}
: Optional status message
ModelContextProtocol.ProgressParams
— TypeProgressParams(; 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 onprogress::Float64
: Current progress valuetotal::Union{Float64,Nothing}
: Optional total expected value
ModelContextProtocol.PromptArgument
— TypePromptArgument(; 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 argumentrequired::Bool
: Whether the argument is required when using the prompt
ModelContextProtocol.PromptCapability
— TypePromptCapability(; 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.PromptMessage
— TypePromptMessage(; 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 messagerole::Role
: Whether this message is from the user or assistant (defaults to user)
ModelContextProtocol.PromptMessage
— MethodPromptMessage(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
ModelContextProtocol.ReadResourceParams
— TypeReadResourceParams(; uri::String) <: RequestParams
Parameters for requesting the contents of a specific resource.
Fields
uri::String
: URI identifier of the resource to read
ModelContextProtocol.ReadResourceResult
— TypeReadResourceResult(; 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
ModelContextProtocol.Request
— TypeRequest <: MCPMessage
Abstract base type for client-to-server requests in the MCP protocol. Request messages expect a corresponding response from the server.
ModelContextProtocol.RequestContext
— TypeRequestContext(; 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 requestrequest_id::Union{RequestId,Nothing}
: The ID of the current request (if any)progress_token::Union{ProgressToken,Nothing}
: Optional token for progress reporting
ModelContextProtocol.RequestHandler
— TypeRequestHandler
Define base type for all request handlers.
ModelContextProtocol.RequestMeta
— TypeRequestMeta(; 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.RequestParams
— TypeRequestParams
Abstract base type for all parameter structures in MCP protocol requests. Concrete subtypes define parameters for specific request methods.
ModelContextProtocol.Resource
— TypeResource
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.
ModelContextProtocol.ResourceCapability
— TypeResourceCapability(; 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.ResourceContents
— TypeResourceContents
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.).
ModelContextProtocol.ResourceTemplate
— TypeResourceTemplate(; 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 templateuri_template::String
: Template string with placeholders for parametersmime_type::Union{String,Nothing}
: MIME type of the generated resourcesdescription::String
: Human-readable description of the template
ModelContextProtocol.Response
— TypeResponse <: 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.
ModelContextProtocol.ResponseResult
— TypeResponseResult
Abstract base type for all result structures in MCP protocol responses. Concrete subtypes define result formats for specific response methods.
ModelContextProtocol.Role
— TypeRole
Enum representing roles in the MCP protocol.
Values
user
: Content or messages from the userassistant
: Content or messages from the assistant
ModelContextProtocol.Server
— TypeServer(config::ServerConfig)
Represent a running MCP server instance that manages resources, tools, and prompts.
Fields
config::ServerConfig
: Server configuration settingsresources::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 operationsactive::Bool
: Whether the server is currently active
Constructor
Server(config::ServerConfig)
: Creates a new server with the specified configuration
ModelContextProtocol.ServerConfig
— TypeServerConfig(; 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 clientsversion::String
: Server version stringdescription::String
: Human-readable server descriptioncapabilities::Vector{Capability}
: Protocol capabilities supported by the serverinstructions::String
: Usage instructions for clients
ModelContextProtocol.ServerError
— TypeServerError(message::String) <: Exception
Exception type for MCP server-specific errors.
Fields
message::String
: The error message describing what went wrong
ModelContextProtocol.ServerState
— TypeServerState()
Track the internal state of an MCP server during operation.
Fields
initialized::Bool
: Whether the server has been initialized by a clientrunning::Bool
: Whether the server main loop is activelast_request_id::Int
: Last used request ID for server-initiated requestspending_requests::Dict{RequestId,String}
: Map of request IDs to method names
ModelContextProtocol.Subscription
— TypeSubscription(; 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 resourcecallback::Function
: Function to call when the resource is updatedcreated_at::DateTime
: When the subscription was created
ModelContextProtocol.TextContent
— TypeTextContent(; text::String, annotations::AbstractDict{String,Any}=LittleDict{String,Any}()) <: Content
Text-based content for MCP protocol messages.
Fields
type::String
: Content type identifier (always "text")text::String
: The actual text contentannotations::AbstractDict{String,Any}
: Optional metadata about the content
ModelContextProtocol.TextResourceContents
— TypeTextResourceContents(; uri::String, text::String, mime_type::Union{String,Nothing}=nothing) <: ResourceContents
Text-based contents for MCP resources.
Fields
uri::String
: Unique identifier for the resourcetext::String
: The text content of the resourcemime_type::Union{String,Nothing}
: Optional MIME type of the content
ModelContextProtocol.Tool
— TypeTool
Abstract base type for all MCP tools. Tools represent operations that can be invoked by clients. Concrete implementations define specific tool functionality and parameters.
ModelContextProtocol.ToolCapability
— TypeToolCapability(; 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.ToolParameter
— TypeToolParameter(; 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)
ModelContextProtocol.ModelContextProtocol
— ModuleModelContextProtocol
Julia implementation of the Model Context Protocol (MCP), enabling standardized communication between AI applications and external tools, resources, and data sources.
Quick Start
Create and start an MCP server:
using ModelContextProtocol
# Create a simple server with a tool
server = mcp_server(
name = "my-server",
tools = [
MCPTool(
name = "hello",
description = "Say hello",
parameters = [],
handler = (p) -> TextContent(text = "Hello, world!")
)
]
)
start!(server)
API Overview
For a comprehensive overview of the API, use the help mode on api
:
?ModelContextProtocol.api
Or access the complete API documentation programmatically:
docs = ModelContextProtocol.api()
See Also
mcp_server
- Create an MCP server instanceMCPTool
- Define tools that can be invoked by clientsMCPResource
- Define resources that can be accessed by clientsMCPPrompt
- Define prompt templates for LLMs
ModelContextProtocol.ProgressToken
— TypeProgressToken
Type alias for tokens used to track long-running operations.
Type
Union{String,Int} - Can be either a string or integer identifier
ModelContextProtocol.RequestId
— TypeRequestId
Type alias for JSON-RPC request identifiers.
Type
Union{String,Int} - Can be either a string or integer identifier