[ANN] Oxygen.jl v1.12.0 - Model Context Protocol (MCP)

Hello Everyone,

I’m excited to announce that Oxygen.jl 1.12.0+ now ships with built-in support for the MCP protocol. This feature has been in the works for a while; the protocol itself has been changing rapidly this year and finally settled around July/August when the latest version included a stateless protocol.

For me, this provided the perfect entry point to start integrating the protocol into Oxygen since I didn’t have to worry about managing additional state. After getting a feel for how the stateless protocol worked, I went back and added backwards compatibility with the previous 4 legacy specs.

In the process of making tool streaming as clean as possible, I quickly saw an opportunity I also wanted to rework how the package handles streaming across the board to make MCP and SSE easier to work with.

In my day job, I work primarily in Python and agentic systems. The one recurring interface I miss has been the ability to directly return async generators from a function and have the response automatically streamed out. While julia doesn’t have a direct 1:1, we can simulate similar behavior if we use Julia Channels.

In this post, we’ll be covering the two largest changes in this update:

  • MCP support
  • Streaming rework

Beyond these two large additions, there were a number of other bug fixes and other features included in this version we didn’t go over.


Model Context Protocol (MCP) Support

This update includes macros & functions to register tools, prompts, and resources.
With this update, you get the same first-class experience when writing tools as you do when writing normal HTTP routes.

  • Automatic schema generation (supports deeply nested structs)
  • Automatic serialization on inputs & outputs
  • A built-in UI to view and play with the resources (tools, prompts, etc.)

The package also comes with a built-in swagger-like UI to explore the MCP server.

Below is an example of a basic “mixed” server where we register normal HTTP routes alongside tools.

using Oxygen

@get "/" function ()
    text("welcome to our mcp server")
end

# Here's the most basic version of a tool
@tool "Add two integers" Dict(:a => "first number", :b => "second number") function add(a::Int, b::Int)
    return a + b
end

# Doc strings will be used as the tool description if none is provided
"""
Subtract two integers
"""
@tool Dict(:a => "first number", :b => "second number") function subtract(a::Int, b::Int)
    return a - b
end

serve() # exposes a /mcp routes

This API provides the most ergonomic way to define a tool in the Julia ecosystem. Packages like ModelContextProtocol.jl take a schema-first approach where you need to manually define the input schema, whereas Oxygen.jl takes a code-first approach by deriving the schema from the code itself.

Below are some examples that demonstrate the features mentioned above:

Nested Structs

Structs can be deeply nested and

@kwdef struct Coordinates
    lat::Float64
    lon::Float64
end

@kwdef struct Place
    name::String
    coordinates::Coordinates
    tags::Vector{String} = String[]
end

"""
Look up a saved place
"""
@tool Dict(:place => "extract the location info from a place") function lookup_place(place::Place)
    return Dict(
        "name" => uppercase(place.name), 
        "lat" => place.coordinates.lat, 
        "lon" => place.coordinates.lon, 
        "tags" => place.tags
    )
end

Tool Streaming

You can also stream values from tools with the mcp_stream() function, which runs your do-block in a producer task and queues each value into a bounded channel. Those values are forwarded to the client as progress notifications on the same SSE response, and the value you return from the do-block is still the final result.

@tool "Sync files" Dict(:files => "file names") function sync_files(files::Vector{String})
    return mcp_stream() do stream
        for file in files
            sleep(0.4)
            put!(stream, "synced $file")  # auto progress 1, 2, 3, ...
        end
        return "Synced $(length(files)) files"
    end
end

Support for string-based enums

Enums in Julia are integer-backed and don’t come with string handling out of the box. In this update, the serialization layer converts string values into enums when a call comes in, and the generated schema advertises the enum names as a string enum with the default stringified. On the way out, enums already serialize back to their names as strings.

@enum Greeting hello goodbye

"""
Greet the world
"""
@tool Dict(:style => "Greeting style") function greet(style::Greeting=hello)
    return style == hello ? "Hello, world!" : "Goodbye, world!"
end

The tool above generates this schema for the tool, which advertises the string enums

 {"type":"string","enum":["hello","goodbye"],"default":"hello","description":"Greeting style"}

Prompts

You can define prompt templates which require a key-value pair to help identify the “role” of each entry. They can only be “user” or “assistant”, but you can also pass them as symbols instead.

# Plain string responses default the role property to "user"
@prompt "Plan a trip to a place" function trip_plan(place::String, days::Int=3)
    return "Plan a $days-day trip to $place."
end

# Can also return a multi-message responses (with strings or symbols as keys)
@prompt "Review a saved place" function review_place(place::String, style::String="concise")
    return ["user" => "Write a $style review of $place.",
            "assistant" => "Sure, what should it focus on?",
            :user => "Its coordinates, tags, and nearby sites."]
end

Resources

You can also add template variables to a resource URI with {name} placeholders, and each one MUST match a parameter on the attached handler. The handler can’t declare any parameters the template doesn’t name.

# Sample data used by the resource examples below.
const PLACES = Dict(
    "seattle" => Place("Seattle", Coordinates(47.61, -122.33), ["coffee", "rain"]),
    "kyoto" => Place("Kyoto", Coordinates(35.01, 135.77), ["temples", "gardens"]),
)

@resource "oxygen://places/{name}" "Look up a place by name" function place_resource(name::String)
    place = get(PLACES, lowercase(name), nothing)
    if isnothing(place)
        return "Unknown place: $name"
    end
    return Dict("name" => place.name, "lat" => place.coordinates.lat, "lon" => place.coordinates.lon, "tags" => place.tags)
end

Streaming (Raw + SSE)

Oxygen has three ways to stream data from a handler, from the most control to the least boilerplate:

  1. @stream - write to the raw HTTP.Stream yourself.
  2. Return a Channel - Oxygen streams its values over SSE.
  3. sse_stream() - Oxygen creates the channel and runs your producer.

Raw streams with @stream

@stream hands you the raw request stream, so you can choose the headers, framing, and wire protocol. Most handlers won’t need this level of control, but it’s here when you do. You’re responsible for opening and closing the write side.

@stream "/events" function(stream::HTTP.Stream)

    HTTP.setheader(stream, "Content-Type" => "application/x-ndjson")
    HTTP.setheader(stream, "Transfer-Encoding" => "chunked")

    startwrite(stream)

    for i in 1:10
        write(stream, JSON.json(Dict("tick" => i)) \* "\\n")
        sleep(1)
    end

   closewrite(stream)
end

Returning a Channel

When you just want values to reach the client, you can let Oxygen handle the SSE framing. Any handler can return a Channel and Oxygen will read from it and write each value as a data: frame. This is a natural fit when the values already come from another task or producer.

Use result(value) as the last value to send value as the final event and close the stream and channel. A buffered channel lets the producer run ahead while Oxygen starts consuming:

@get "/events" function()
    return Channel{Any}(64) do channel
        put!(channel, Dict("tick" => 1))
        put!(channel, result(Dict("done" => true)))
    end
end

Producing a stream with sse_stream()

Use sse_stream() when the handler is the producer. It creates the stream and runs your do-block in a task:


@get "/events" function()
    return sse_stream() do stream
        for i in 1:10
            put!(stream, Dict("tick" => i))
            sleep(1)
        end
        return "done!" # sent as the final event (optional return value)
    end
end

The return value is sent as the final event, so there’s no separate result(value) marker. On a live connection it is written as the final data: frame; return nothing if you don’t want one. An error thrown in the do-block ends the stream with an event: error frame.

Compared with a bare Channel, sse_stream manages more of the lifecycle:

  • creates the channel for you and closes it when your producer finishes or fails
  • lets your producer exit when the client disconnects (put!/emit throw StreamCancelled; long loops can call check_cancelled(stream))
  • uses one buffer, sized with csize, instead of an extra internal buffer and copying step
2 Likes