Sponsored by Deepsite.site

SwiftMCP

Created By
Cocoanetics5 months ago
With SwiftMCP any Swift app can easily be enabled as MCP Server, supports stdio, HTTP+SSE and streaming HTTP.
Content

SwiftMCP

A Swift implementation of the MCP (Model Context Protocol) for JSON-RPC over various transports.

Features

  • Multiple transport options:
    • Standard I/O (stdio) for command-line usage
    • HTTP+SSE (Server-Sent Events) for web applications
  • JSON-RPC 2.0 compliant
  • Asynchronous response handling via SSE
  • Built-in authorization support
  • Optional OAuth 2.0 validation with well-known endpoints
  • Cross-platform compatibility

Installation

Add SwiftMCP as a dependency in your Package.swift:

dependencies: [
    .package(url: "https://github.com/Cocoanetics/SwiftMCP.git", branch: "main")
]

Usage

Command Line Demo

The included demo application shows how to use SwiftMCP with different transport options:

# Using stdio transport
SwiftMCPDemo stdio

# Using HTTP+SSE transport
SwiftMCPDemo httpsse --port 8080

# Using HTTP+SSE with authorization
SwiftMCPDemo httpsse --port 8080 --token your-secret-token

# Using HTTP+SSE with OpenAPI support
SwiftMCPDemo httpsse --port 8080 --openapi

# Using HTTP+SSE with authorization and OpenAPI support
SwiftMCPDemo httpsse --port 8080 --token your-secret-token --openapi

# Using HTTP+SSE with OAuth
SwiftMCPDemo httpsse --port 8080 \
    --oauth-issuer https://example.com \
    --oauth-token-endpoint https://example.com/oauth/token \
    --oauth-introspection-endpoint https://example.com/oauth/introspect \
    --oauth-jwks-endpoint https://example.com/.well-known/jwks.json \
    --oauth-audience your-api-identifier

When using HTTP+SSE transport with the --token option, clients must include an Authorization header with their requests:

Authorization: Bearer your-secret-token

OpenAPI support

The --openapi option enables OpenAPI endpoints for AI plugin integration. When this option is used, the server will provide an OpenAPI specification at /openapi.json and an AI plugin manifest at /.well-known/ai-plugin.json. This allows for easy integration with AI models and other tools that support OpenAPI.

OAuth support

When HTTPSSETransport is configured with OAuthConfiguration, the transport validates incoming bearer tokens through the configured OAuth provider. Validation can use an introspection endpoint or by checking JWT claims against the provider's JWKS when introspection is not available. The transport also serves metadata at /.well-known/oauth-authorization-server and /.well-known/oauth-protected-resource for discovery by clients.

Custom Server Implementation

To implement your own MCP server:

  1. Attach the @MCPServer macro to a reference type like class or actor
  2. Define your tools using @MCPTool attribute
  3. Choose and configure a transport

Example:

@MCPServer
class MyServer {
    @MCPTool
    func add(a: Int, b: Int) -> Int {
        return a + b
    }
}

// Using HTTP+SSE transport with authorization
let server = MyServer()
let transport = HTTPSSETransport(server: server, port: 8080)

// Optional: Add authorization
transport.authorizationHandler = { token in
    guard let token = token, token == "your-secret-token" else {
        return .unauthorized("Invalid token")
    }
    return .authorized
}

// Or configure OAuth validation
transport.oauthConfiguration = OAuthConfiguration(
    issuer: URL(string: "https://example.com")!,
    authorizationEndpoint: URL(string: "https://example.com/authorize")!,
    tokenEndpoint: URL(string: "https://example.com/oauth/token")!,
    introspectionEndpoint: URL(string: "https://example.com/oauth/introspect")!,
    jwksEndpoint: URL(string: "https://example.com/.well-known/jwks.json")!,
    audience: "your-api-identifier",
    clientID: "client",
    clientSecret: "secret"
)

try transport.run()

Documentation Extraction

The @MCPServer and @MCPTool macros extract documentation comments to describe class, parameters and return value.

Macros Functionality

The macros in this repository provide functionality for defining and exposing tools and servers in the SwiftMCP framework. Here are the main functionalities of the macros:

  • @MCPServer: This macro is used to define a class or actor as an MCP server. It extracts documentation comments to describe the class, parameters, and return values. An example of its usage can be seen in the Demos/SwiftMCPDemo/Calculator.swift file, where the Calculator actor is annotated with @MCPServer(name: "SwiftMCP Demo").
  • @MCPTool: This macro is used to define functions within an MCP server that can be called as tools. It also extracts documentation comments to describe the function, parameters, and return values. Examples of its usage can be seen in the Demos/SwiftMCPDemo/Calculator.swift file, where various functions such as add, subtract, testArray, multiply, divide, greet, ping, and noop are annotated with @MCPTool.
  • @MCPResource: This macro is used to expose read-only data through URI templates. Resources allow clients to access data using structured URIs with path and query parameters. The macro automatically generates the necessary infrastructure to match URIs against templates and extract parameters.

Using @MCPResource

The @MCPResource macro allows you to expose functions as resources that can be accessed via URI patterns:

@MCPServer(name: "ResourceServer")
actor ResourceServer {
    /// Get user profile by ID
    @MCPResource("users://{user_id}/profile")
    func getUserProfile(user_id: Int) -> String {
        return "Profile for user \(user_id)"
    }
    
    /// Search users with pagination
    @MCPResource("users://search?q={query}&page={page}", mimeType: "application/json")
    func searchUsers(query: String, page: Int = 1) -> String {
        return """
        {"query": "\(query)", "page": \(page), "results": [...]}
        """
    }
}

Key features:

  • URI Templates: Define patterns with placeholders in curly braces {param}
  • Path Parameters: Extract values from the URI path (e.g., /users/{id})
  • Query Parameters: Extract values from query strings (e.g., ?page={page})
  • Optional Parameters: Support default values for optional parameters
  • MIME Types: Optionally specify content type with mimeType parameter
  • Type Safety: Parameters are automatically converted to the correct Swift types

The server automatically provides:

  • Resource discovery through mcpResourceTemplates
  • URI matching and parameter extraction
  • Type conversion and validation
  • Error handling for missing or invalid parameters

These macros help in automatically generating the necessary metadata and documentation for the MCP server and its tools, making it easier to expose them for JSON-RPC communication and integration with AI models.

License

This project is licensed under the BSD 2-clause License - see the LICENSE file for details.

Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
Serper MCP ServerA Serper MCP Server
ChatWiseThe second fastest AI chatbot™
CursorThe AI Code Editor
WindsurfThe new purpose-built IDE to harness magic
Amap Maps高德地图官方 MCP Server
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
DeepChatYour AI Partner on Desktop
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Tavily Mcp
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright McpPlaywright MCP server
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.