Skip to content

How to create a mcp client using Swift? #58

Done

Description

@MenJH

hello, @mattt , I am a swift beginner, I want to write a swift version of client that mimics the python example

Now that I have started a python server before swift client initialization, I wonder if I need to inject something into StdioTransport() before client initialization? Do the initialization directly as in the documentation?

python client link: https://modelcontextprotocol.io/quickstart/client
swift client link: https://github.com/modelcontextprotocol/swift-sdk?tab=readme-ov-file#basic-client-setup

Activity

  1. MenJH commented on Apr 7, 2025

    @MenJH
    Author

    In kotlin's example, StdioClientTransport() is set this way, and I was wondering how it should be set in swift?
    Image

  2. added
    question
    on Apr 9, 2025
  3. sebsto commented on Apr 16, 2025

    @sebsto
    Contributor

    Actually, an example of code that launches the process, creates the Pipe() for stdin and stdout and connect them correctly to the transport would be appreciated. The Example in the README is not detailed enough to get started.
    It is surprisingly hard to get it working in Swift.

    One thing which is unclear to me is whose input and output is it ? The client ? The server ? The above kotlin code seems to imply these are the server ones.

    But the StdioClientTransport code send() function writes on the output (which should be the input of the server)
    I’m confused.

  4. sebsto commented on Apr 20, 2025

    @sebsto
    Contributor

    I tried to spawn the process using the new Subprocess package from Swift Lang.
    https://github.com/swiftlang/swift-subprocess

    It blocks on client.initailize(). Is this expected ? Should I launch this in a separate task ? @mattt

        // Initialize the MCPclient
        let client = Client(name: ""MyClientName, version: "1.0.0")
    
        let toolConfig = try getMCPToolCommand(for: "MyTool")
        let command = toolConfig.command
    
        let serverInput: FileDescriptor = FileDescriptor(
          rawValue: Pipe().fileHandleForReading.fileDescriptor)
        let serverOutput: FileDescriptor = FileDescriptor(
          rawValue: Pipe().fileHandleForWriting.fileDescriptor)
    
        let pid = try runDetached(.path(FilePath(command)), input: serverInput, output: serverOutput)
    
        let transport = StdioTransport(
          input: serverInput,
          output: serverOutput,
          logger: logger)
        try await client.connect(transport: transport)
    
        let result = try await client.initialize() // blocks here, this call never returns 
    

    This outputs

    2025-04-20T17:02:14+0200 info BedrockCLI : [MCP] Transport connected successfully
    2025-04-20T17:02:14+0200 info BedrockCLI : name=MyClientName version=1.0.0 [MCP] Client connected
    
  5. phimage commented on Apr 20, 2025

    @phimage
    Contributor

    More than just an example, some other language SDKs treat process as a first-class citizen for std io, allowing you to launch tools like npx, uv, etc easily

    I’m using that approach for now:

    extension Process {
    
        func stdioTransport(logger: Logger? = nil) -> StdioTransport {
            let input = Pipe()
            let output = Pipe()
            self.standardInput = input
            self.standardOutput = output
            // XXX: maybe be std err too (option); some return some log "message"
    
            return StdioTransport(
                input: FileDescriptor(rawValue: output.fileHandleForReading.fileDescriptor),
                output: FileDescriptor(rawValue: input.fileHandleForWriting.fileDescriptor),
                logger: logger)
        }
    
    }

    with

    • full path for npx, uv etc... (using /usr/bin/which <exeName>) if simple name without /)
    • correct PATH in process env (for instance npx must be able to launch node, so I add npx parent directory to PATH)
  6. sebsto commented on Apr 21, 2025

    @sebsto
    Contributor

    @phimage thank youf or having shared the portion of code. That pat I have and is similar to yours. What I'm struggling with is the rest: launching the process, creating the MCP client, connecting, initializing it.

    I launch the process, create the MCP client, connect it (and it works). But then the call to client.initialize() blocks.

    Do you have the full code snippet ?

  7. phimage commented on Apr 21, 2025

    @phimage
    Contributor

    Do you have the full code snippet ?

    I share here https://github.com/phimage/mcp-cli-test a macOS CLI test app that launch a "npx" mcp server (npx installed with homebrew)

  8. sebsto commented on Apr 21, 2025

    @sebsto
    Contributor

    Thank you so much.
    I made two mistakes.

    • The input and output must be inverted on the StdioTransport (input goes to output and the opposite)
    • The transport must be created before the process is launched.

    Merci Beaucoup. I hope it will help others too.

  9. Keoooo commented on Jun 1, 2025

    @Keoooo

    Hello, is there documentation anywhere that will help me understand how to run npm and Python MCP servers from within Swift applications?

  10. mattt commented on Jun 1, 2025

    @mattt
    Contributor

    @Keoooo You can use Process to run another program like uvx or npx as a subprocess from a Swift program. If you're distributing on the App Store, you'll need to work within the App Sandbox, which has additional caveats.

  11. Keoooo commented on Jun 1, 2025

    @Keoooo

    @Keoooo You can use Process to run another program like uvx or npx as a subprocess from a Swift program. If you're distributing on the App Store, you'll need to work within the App Sandbox, which has additional caveats.

    Given how common it is to use subprocesses (especially for Node/Python-based MCP servers), do you envision the Swift SDK eventually providing a helper or utility function to abstract this setup?

  12. mattt commented on Jun 2, 2025

    @mattt
    Contributor

    @Keoooo Perhaps. There's a balance to strike between convenience and expressiveness. There are a lot of things that one might want configure when launching a subprocess, which many / most users won't need to know about that are essential to other users. I suspect a mix of documentation and API affordances will be the best approach here.

  13. sebsto commented on Jun 5, 2025

    @sebsto
    Contributor

    @Keoooo Here is the code I use and that works for me (I want to migrate to the new SubProcess library from SwiftLang group)

        package init(
            with toolConfig: MCPConfiguration.ToolConfiguration,
            name: String,
            for server: String,
            version: String = "1.0.0",
            logger: Logger
        ) async throws {
            self.name = name
            self.client = Client(name: name, version: version)
            self.logger = logger
    
            logger.trace(
                "Launching process",
                metadata: [
                    "command": "\(toolConfig.command)",
                    "arguments": "\(toolConfig.args.joined(separator: " "))",
                ]
            )
    
            // Create pipes for the server input and output
            let serverInputPipe = Pipe()
            let serverOutputPipe = Pipe()
            let serverInput: FileDescriptor = FileDescriptor(
                rawValue: serverInputPipe.fileHandleForWriting.fileDescriptor
            )
            let serverOutput: FileDescriptor = FileDescriptor(
                rawValue: serverOutputPipe.fileHandleForReading.fileDescriptor
            )
    
            self.process = Process()
            process.executableURL = URL(fileURLWithPath: toolConfig.command)
            process.arguments = toolConfig.args
            process.standardInput = serverInputPipe
            process.standardOutput = serverOutputPipe
    
            let transport = StdioTransport(
                input: serverOutput,
                output: serverInput,
                logger: logger
            )
    
            try process.run()
            logger.trace("Process launched")
    
            try await client.connect(transport: transport)
            logger.trace("Connected to MCP server")
    
            // Initialize the connection
            let result = try await client.initialize()
            logger.trace("Connection initialized", metadata: ["result": "\(result)"])
    
            // collect the list of tools available in the MCP server
            // var cursor: String? = nil
            (self.tools, _) = try await client.listTools()
            logger.trace("Available tools", metadata: ["toolsCount": "\(self.tools.count)"])
        }
  14. phimage commented on Jun 13, 2025

    @phimage
    Contributor

    The Kotlin SDK includes some samples within the project:
    https://github.com/modelcontextprotocol/kotlin-sdk/tree/main/samples
    Maybe we could do something similar. (Just a suggestion—I personally prefer independent projects, as a Swift developer.)


    As a new example/test for using the Client class and Process, I’ve created a quick and dirty command-line app to chat with the new FoundationModel using MCP server tools, based on Claude config files:
    https://github.com/phimage/FoundationModelCli

  15. ptliddle commented on Jul 2, 2025

    @ptliddle

    I'm a bit late to this thread but i wrote a step-by-step blog post on how to do this here. Building a MCP Client in Swift

  16. sebsto commented on Jul 2, 2025

    @sebsto
    Contributor

    Talking about MCP helper, I wrote this library that should help to write your servers and clients
    https://github.com/sebsto/mcpserverkit

  17. dcracker commented on Oct 17, 2025

    @dcracker

    Hello, I hope you don’t mind me asking a possibly naive question.

    According to this document:
    https://modelcontextprotocol.io/specification/2025-03-26/basic/transports

    it states that “In the stdio transport” there should be a Launch subprocess step. I was wondering if you could kindly explain why the process would be executed outside of StdioTransport.

    Thank you very much for your time and help!

  18. jeanmatthieu commented on Dec 5, 2026

    @jeanmatthieu
    Contributor

    On rel/1.0.0 (#372), we've added a complete quick-start guide (docs/quick_start.md#a-stdio-client), a runnable Examples/hello-client target, and DocC tutorials (#362, #417) showing how to spawn a subprocess with Process and pass its pipes to StdioTransport(input:output:). StdioTransport intentionally takes file descriptors rather than launching a process itself so it stays cross-platform (including platforms without Process and sandboxed hosts where the app controls process lifecycle). Also, as of #360, if the spawned server exits early, client.connect(transport:) now throws MCPError.connectionClosed rather than hanging. Closing as answered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    question

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions