20.7 C
Canberra
Friday, October 24, 2025

4 Months within the Making: SwiftMCP 1.0 is Right here


After 4 months of intensive improvement, I’m thrilled to announce that SwiftMCP 1.0 is feature-complete and prepared so that you can use.

For these simply becoming a member of, SwiftMCP is a local Swift implementation of the Mannequin Context Protocol (MCP). The purpose is to offer a dead-simple means for any developer to make their app, or elements of it, obtainable as a robust server for AI brokers and Massive Language Fashions. You may learn the official specification at modelcontextprotocol.io.

I did a SwiftMCP 1.0 Function Pace Run on YouTube, if that’s what you like.

The Core Concept: Your Documentation is the API

Earlier than diving into options, it’s essential to know the philosophy of SwiftMCP. The framework is constructed on the precept that your current documentation ought to be the first supply of fact for an AI. By utilizing customary Swift documentation feedback, you present all of the context an AI wants to know and use your server’s capabilities.

/**
 Provides two numbers and returns their sum.

 - Parameter a: The primary quantity so as to add
 - Parameter b: The second quantity so as to add
 - Returns: The sum of a and b
 */
@MCPTool
func add(a: Int, b: Int) -> Int {
    a + b
}

This code exhibits the only use case. The @MCPTool macro inspects the add perform and its documentation remark. It routinely extracts the primary description (ā€œProvides two numbersā€¦ā€), the descriptions for parameters a and b, and the outline of the return worth, making all of this data obtainable to an AI shopper with none additional work.

Server Options: Exposing Your App’s Logic

These are the capabilities your Swift software (the server) exposes to a shopper.

Instruments: The Basis of Motion

Instruments are the first option to expose your app’s performance. By adorning any perform with @MCPTool, you make it a callable motion for an AI. A great instrument is well-documented, handles potential errors, and supplies clear performance.

// Outline a easy error and enum for the instrument
enum TaskError: Error { case invalidName }
enum Precedence: String, Codable, CaseIterable { case low, medium, excessive }

/**
 Schedules a job with a given precedence.
 - Parameter title: The title of the duty. Can't be empty.
 - Parameter precedence: The execution precedence.
 - Parameter delay: The delay in seconds earlier than the duty runs. Defaults to 0.
 - Returns: A affirmation message.
 - Throws: `TaskError.invalidName` if the title is empty.
 */
@MCPTool
func scheduleTask(title: String, precedence: Precedence, delay: Double = 0) async throws -> String {
    guard !title.isEmpty else {
        throw TaskError.invalidName
    }

    // Simulate async work
    attempt await Activity.sleep(for: .seconds(delay))

    return "Activity '(title)' scheduled with (precedence.rawValue) precedence."
}

This instance demonstrates a number of key options directly. The perform is async to carry out work that takes time, and it throws a customized TaskError for invalid enter. It makes use of a CaseIterable enum, Precedence, as a parameter, which SwiftMCP can use to supply auto-completion to shoppers. Lastly, the delay parameter has a default worth, making it non-compulsory for the caller.

Sources: Publishing Learn-Solely Information

Sources mean you can publish information that shoppers can question by URI. SwiftMCP presents a versatile system for this, which might be damaged down into two principal classes: function-backed assets and provider-based assets.

Perform-Backed Sources

These assets are outlined by particular person capabilities embellished with the @MCPResource macro. If a perform has no parameters, it acts as a static endpoint. If it has parameters, they have to be represented as placeholders within the URI template.

/// Static Useful resource: Returns a server information string
@MCPResource("server://information")
func getServerInfo() -> String {
    "SwiftMCP Demo Server v1.0"
}

/// Dynamic Useful resource: Returns a greeting for a consumer by ID
/// - Parameter user_id: The consumer's distinctive identifier
@MCPResource("customers://{user_id}/greeting")
func getUserGreeting(user_id: Int) -> String {
    "Hiya, consumer #(user_id)!"
}

The getServerInfo perform is a static useful resource; a shopper can request the URI server://information and can at all times get the identical string again. The getUserGreeting perform is dynamic; the {user_id} placeholder within the URI tells SwiftMCP to anticipate a price. When a shopper requests customers://123/greeting, the framework routinely extracts ā€œ123ā€, converts it to an Int, and passes it to the user_id parameter.

Supplier-Based mostly Sources (like information)

For exposing a dynamic assortment of assets, like information in a listing, you may conform your server to MCPResourceProviding. This requires implementing a property to find the assets and a perform to offer their content material on request.

extension DemoServer: MCPResourceProviding {
    // Announce obtainable file assets
    var mcpResources: [any MCPResource] {
        let docURL = URL(fileURLWithPath: "/Customers/Shared/doc.pdf")
        return [FileResource(uri: docURL, name: "Shared Document")]
    }

    // Present the file's content material when its URI is requested
    func getNonTemplateResource(uri: URL) async throws ->
        [MCPResourceContent] {
        guard FileManager.default.fileExists(atPath: uri.path) else {
            return []
        }

        return attempt [FileResourceContent.from(fileURL: uri)]
    }
}

This code exhibits the two-part mechanism. First, the mcpResources property is known as by the framework to find what assets can be found. Right here, we announce a single PDF file. Second, when a shopper truly requests the content material of that file’s URI, the getNonTemplateResource(uri:) perform is known as. It verifies the file exists after which returns its contents.

Prompts: Reusable Templates for LLMs

For reusable immediate templates, the @MCPPrompt macro works similar to @MCPTool. It exposes a perform that returns a string or PromptMessage objects, making its parameters obtainable for the AI to fill in.

/// A immediate for saying Hiya
@MCPPrompt()
func helloPrompt(title: String) -> [PromptMessage] {
    let message = PromptMessage(function: .assistant, 
        content material: .init(textual content: "Hiya (title)!"))
    return [message]
}

This instance defines a easy immediate template. An AI shopper can uncover this immediate and see that it requires a title parameter. The shopper can then name the immediate with a selected title, and the server will execute the perform to assemble and return the absolutely fashioned immediate message, able to be despatched to an LLM.

Progress Reporting: Dealing with Lengthy-Operating Duties

For duties that take time, you may report progress again to the shopper utilizing RequestContext.present, which prevents the shopper from being left at nighttime.

@MCPTool
func countdown() async -> String {
    for i in (0...30).reversed() {
        let completed = Double(30 - i) / 30
        await RequestContext.present?.reportProgress(completed, 
            complete: 1.0, message: "(i)s left")
        attempt? await Activity.sleep(nanoseconds: 1_000_000_000)
    }
    return "Countdown accomplished!"
}

On this perform, the server loops for 30 seconds. Contained in the loop, reportProgress is known as on the RequestContext.present. This sends a notification again to the unique shopper that made the request, which may then use the progress worth and message to replace a UI ingredient like a progress bar.

Consumer Options: The Consumer is in Management

Whereas SwiftMCP is a server framework, it absolutely helps the highly effective capabilities a shopper can supply. The shopper holds an excessive amount of management, and your server can adapt its conduct by checking Session.present?.clientCapabilities.

Roots: Managing File Entry

The shopper is in full management of what native information the server can see. When a shopper provides or removes a root listing, your server is notified and may react by implementing handleRootsListChanged().

func handleRootsListChanged() async {
    guard let session = Session.present else { return }
    do {
        let updatedRoots = attempt await session.listRoots()
        await session.sendLogNotification(LogMessage(
            degree: .information,
            information: [ "message": "Roots list updated", "roots": updatedRoots ]
        ))
    } catch {
        // Deal with error...
    }
}

This perform is a notification handler. When a shopper modifies its listing of shared directories (or ā€œrootsā€), it sends a notification to the server. SwiftMCP routinely calls this perform, which may then use session.listRoots() to get the up to date listing and react accordingly, for instance, by refreshing its personal listing of obtainable information.

Cancellation: Stopping Duties Gracefully

If the shopper is exhibiting a progress bar for that countdown, it also needs to have a cancel button. The shopper can ship a cancellation notification, and your server code have to be a superb citizen and verify for it with attempt Activity.checkCancellation().

Elicitation: Asking the Consumer for Enter

Elicitation is a robust interplay the place the server determines it wants particular, structured data. It sends a JSON schema to the shopper, and the shopper is chargeable for rendering a kind to ā€œelicitā€ that information.

@MCPTool
func requestContactInfo() async throws -> String {
    // Outline the info you want with a JSON schema
    let schema = JSONSchema.object(JSONSchema.Object(
        properties: [
            "name": .string(description: "Your full name"),
            "email": .string(description: "Your email address", 
            format: "email")
        ],
        required: ["name", "email"]
    ))

    // Elicit the knowledge from the shopper
    let response = attempt await RequestContext.present?.elicit(
        message: "Please present your contact data",
        schema: schema
    )

    // Deal with the consumer's response
    change response?.motion {
    case .settle for:
        let title = response?.content material?["name"]?.worth as? String ?? "Consumer"
        return "Thanks, (title)!"
    case .decline:
        return "Consumer declined to offer data."
    case .cancel, .none:
        return "Consumer cancelled the request."
    }
}

This instrument demonstrates the three steps of elicitation. First, it defines a JSONSchema that specifies the required fields (title and electronic mail). Second, it calls elicit on the present request context, sending the schema and a message to the shopper. Third, it waits for the consumer’s response and makes use of a change assertion to deal with the totally different outcomes: the consumer accepting, declining, or canceling the request.

Sampling: Utilizing the Consumer’s LLM

Maybe essentially the most fascinating characteristic is Sampling, which flips the script. The server can request that the shopper carry out a generative job utilizing its personal LLM. This permits your server to be light-weight and delegate AI-heavy lifting.

@MCPTool
func sampleFromClient(immediate: String) async throws -> String {
    // Test if the shopper helps sampling
    guard await Session.present?.clientCapabilities?.sampling != nil else {
        throw MCPServerError.clientHasNoSamplingSupport
    }

    // Request the era
    return attempt await RequestContext.present?.pattern(immediate: immediate) ?? "No response from shopper"
}

This code exhibits how a server can leverage a shopper’s personal generative capabilities. It first checks if the shopper has marketed help for sampling. If that’s the case, it calls pattern(immediate:), which sends the immediate to the shopper. The shopper is then chargeable for working the immediate by means of its personal LLM and returning the generated textual content, which the server receives as the results of the await name.

What’s Subsequent?

My imaginative and prescient is for builders to combine MCP servers straight into their Mac apps. My API.me personal app does precisely this, exposing a consumer’s native emails, contacts, and calendar by means of an area server that an LLM can securely work together with. I’m pondering if I ought to put this on the app retailer or presumably open supply it. What do you assume?

It has been plenty of work, and it’s lastly prepared. SwiftMCP 1.0 is right here.

I’m very a lot trying ahead to your suggestions. Please give it a attempt, take a look at the examples on GitHub, and let me know what you assume. I hope to see you construct some superb issues with it.

Oh and in the event you haven’t watched it but, I actually suggest watching my demonstration of all the brand new options:


Classes: Updates

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles