Sample code for 30+ languages & platforms
Swift Requires Chilkat v11.6.0+

Call a Tool on an MCP Server

See more MCP Client Examples

Demonstrates Mcp.CallTool, which calls the MCP tools/call method for a named tool, passing a JSON arguments object and receiving the tool's result. The example calls the Microsoft Learn microsoft_docs_search tool.

Tip: Code to parse the returned JSON can be generated with Chilkat's online tool at https://tools.chilkat.io/jsonParse.

Background. The members of the arguments object are defined by the tool's input schema, which is reported by ListTools. This example uses the public, no-authentication Microsoft Learn MCP server.

Chilkat Swift Downloads

Swift

func chilkatTest() {
    var success: Bool = false

    let mcp = CkoMcp()!

    //  Connect to a public MCP (Model Context Protocol) server over its Streamable HTTP endpoint.  The
    //  Microsoft Learn MCP server is public and requires no authentication.
    success = mcp.connect(url: "https://learn.microsoft.com/api/mcp")
    if success == false {
        print("\(mcp.lastErrorText!)")
        return
    }

    //  Build the tool's input arguments.  The members required depend on the tool's input schema (see
    //  ListTools).  Here the Microsoft Learn "microsoft_docs_search" tool takes a search query.
    let args = CkoJsonObject()!
    args.updateString(jsonPath: "query", value: "How do I create an Azure storage account?")

    //  Call the MCP tools/call method for the named tool.  The tool's result is placed in the result
    //  JsonObject.
    let result = CkoJsonObject()!
    success = mcp.callTool(name: "microsoft_docs_search", arguments: args, result: result)
    if success == false {
        print("\(mcp.lastErrorText!)")
        return
    }

    result.emitCompact = false
    print("\(result.emit()!)")
    //  JSON parsing code for this result can be generated at Chilkat's online tool:
    //  https://tools.chilkat.io/jsonParse

}