Skip to content
Back to search

SwiftMCP

Model Context Protocol Server for Swift

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/cocoanetics--swiftmcp/badge.svg)](/listings/cocoanetics--swiftmcp)

HTML

<a href="/listings/cocoanetics--swiftmcp"><img src="/api/listings/cocoanetics--swiftmcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Add SwiftMCP as a dependency in your `Package.swift`:

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

Package traits

SwiftMCP exposes its optional feature areas as [SwiftPM package traits](https://docs.swift.org/swiftpm/documentation/packagemanagerdocs/packagetraits/), **all enabled by default** — existing consumers and a plain `swift build` are unaffected. The single `import SwiftMCP` module is unchanged.

| Trait | Enables | Extra dependencies | | --- | --- | --- | | `Server` | HTTP/SSE + TCP server transports | swift-nio, swift-crypto, swift-certificates | | `Client` | The MCP client (`MCPServerProxy`) | — | | `OpenAPI` | OpenAPI / AI-plugin manifest models and routes | — |

The tool/schema foundation — `JSONValue`, `JSONSchema`, `MCPToolProviding`, the `@MCPTool` / `@MCPServer` macros, errors — is always-on core and needs no trait.

Disabling `Server` drops swift-nio (and swift-crypto/swift-certificates) entirely, which makes the package **build on Windows** and gives client/tools-only consumers a lighter graph. A consumer that only talks to remote MCP servers selects just what it needs (your manifest must be `swift-tools-version: 6.1` or newer to choose traits):

.package(
    url: "https://github.com/Cocoanetics/SwiftMCP.git",
    branch: "main",
    traits: ["Client"]   // tool/schema core + client, no swift-nio
)

> AppIntents bridging (`@MCPAppIntentTool`, AppShortcuts discovery) is not a trait: it is already gated by `#if canImport(AppIntents)`, so it is automatically excluded on platforms without AppIntents (Linux, Windows, Android).

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 464 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # SwiftMCP
  2. A Swift implementation of the MCP (Model Context Protocol) for JSON-RPC over various transports.
  3. ## Features
  4. - Multiple transport options
  5. - Standard I/O (stdio) for command-line usage
  6. - HTTP+SSE (Server-Sent Events) for web applications
  7. - TCP+Bonjour for local discovery over raw TCP
  8. - JSON-RPC 2.0 compliant with OpenAPI generation
  9. - Built-in authorization and optional OAuth validation
  10. - Transparent OAuth proxy mode for MCP and OpenAPI
  11. - Cross-platform compatibility
  12. ### Server Features
  13. - **Tools** – expose functions with `@MCPTool`
  14. - **Resources** – publish data with `@MCPResource`
  15. - **Prompts** – build prompts using `@MCPPrompt`
  16. - **Events** – declare webhook events with `@MCPEvent` and publish with `emit` (modern `2026-07-28`)
  17. - **Utilities**
  18. - Progress notifications via `RequestContext.current`
  19. - Structured logging streamed through `Session.current`
  20. - Completion suggestions for parameters (defaults for `Bool` and `CaseIterable`)
  21. ### Client Features
  22. - **Roots** – dynamic filesystem roots announced by the client
  23. - **Sampling** – request small previews of client files
  24. - **Events** – `listEvents` / `subscribeEvent` / `unsubscribeEvent` on `MCPServerProxy` (era-gated)
  25. ## Installation
  26. CI builds and tests with Swift 6.4 across macOS, iOS, Linux, Windows, and Android.
  27. Apple CI lanes use Xcode 27.1; Linux, Windows, and Android use Swift 6.4.2.
  28. Add SwiftMCP as a dependency in your `Package.swift`:
  29. ```swift
  30. dependencies: [
  31. .package(url: "https://github.com/Cocoanetics/SwiftMCP.git", branch: "main")
  32. ]
  33. ```
  34. ### Package traits
  35. SwiftMCP exposes its optional feature areas as [SwiftPM package traits](https://docs.swift.org/swiftpm/documentation/packagemanagerdocs/packagetraits/), **all enabled by default** — existing consumers and a plain `swift build` are unaffected. The single `import SwiftMCP` module is unchanged.
  36. | Trait | Enables | Extra dependencies |
  37. | --- | --- | --- |
  38. | `Server` | HTTP/SSE + TCP server transports | swift-nio, swift-crypto, swift-certificates |
  39. | `Client` | The MCP client (`MCPServerProxy`) | — |
  40. | `OpenAPI` | OpenAPI / AI-plugin manifest models and routes | — |
  41. The tool/schema foundation — `JSONValue`, `JSONSchema`, `MCPToolProviding`, the `@MCPTool` / `@MCPServer` macros, errors — is always-on core and needs no trait.
  42. Disabling `Server` drops swift-nio (and swift-crypto/swift-certificates) entirely, which makes the package **build on Windows** and gives client/tools-only consumers a lighter graph. A consumer that only talks to remote MCP servers selects just what it needs (your manifest must be `swift-tools-version: 6.1` or newer to choose traits):
  43. ```swift
  44. .package(
  45. url: "https://github.com/Cocoanetics/SwiftMCP.git",
  46. branch: "main",
  47. traits: ["Client"] // tool/schema core + client, no swift-nio
  48. )
  49. ```
  50. > AppIntents bridging (`@MCPAppIntentTool`, AppShortcuts discovery) is not a trait: it is already gated by `#if canImport(AppIntents)`, so it is automatically excluded on platforms without AppIntents (Linux, Windows, Android).
  51. ## Usage
  52. ### Command Line Demo
  53. The included demo application shows how to use SwiftMCP with different transport options:
  54. ```bash
  55. # Using stdio transport
  56. SwiftMCPDemo stdio
  57. # Using HTTP+SSE transport
  58. SwiftMCPDemo httpsse --port 8080
  59. # Using HTTP+SSE with authorization
  60. SwiftMCPDemo httpsse --port 8080 --token your-secret-token
  61. # Using HTTP+SSE with OpenAPI support
  62. SwiftMCPDemo httpsse --port 8080 --openapi
  63. # Using HTTP+SSE with authorization and OpenAPI support
  64. SwiftMCPDemo httpsse --port 8080 --token your-secret-token --openapi
  65. # Using HTTP+SSE with OAuth (JSON config)
  66. SwiftMCPDemo httpsse --port 8080 --oauth oauth-config-example.json
  67. # Using TCP+Bonjour transport
  68. SwiftMCPDemo tcp --name "SwiftMCP Demo"
  69. # Using HTTP+SSE plus TCP+Bonjour in parallel
  70. SwiftMCPDemo httpsse --port 8080 --tcp
  71. ```
  72. When using HTTP+SSE transport with the `--token` option, clients must include an Authorization header with their requests:
  73. ```bash
  74. Authorization: Bearer your-secret-token
  75. ```
  76. ## OpenAPI support
  77. 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.
  78. ## OAuth support
  79. MCP OAuth conformance helpers (`OAuthConformanceError`, `OAuthAuthorizationResponse`, `OAuthClientRegistrationValidator`,
  80. `OAuthClientCredentialStore`, `ClientIDMetadataDocument`): authorization-response `iss` validation (RFC 9207 / SEP-2468),
  81. mandatory `application_type` on dynamic client registration (SEP-837, enforced by the proxy's `/oauth/register`),
  82. issuer-bound client credentials that force re-registration when the issuer changes (SEP-2352), and Client ID Metadata
  83. Documents. Dynamic client registration is deprecated in favor of CIMD; it remains available as a fallback.
  84. When `HTTPSSETransport` is configured with ``OAuthConfiguration``, the transport
  85. validates incoming bearer tokens through the configured OAuth provider.
  86. Validation can use an introspection endpoint or by checking JWT claims against
  87. the provider's JWKS when introspection is not available. The transport also
  88. serves metadata at `/.well-known/oauth-authorization-server` and
  89. `/.well-known/oauth-protected-resource` for discovery by clients.
  90. ## Progress, Logging, Roots and Sampling
  91. SwiftMCP can send progress updates while a tool is running, stream structured
  92. log messages to connected clients, handle dynamic filesystem roots announced
  93. by the client and request small data samples for preview. See the demo server for
  94. simple implementations of these features. The <doc:ServerCapabilities> and <doc:Sampling>
  95. articles describe the APIs in detail.
  96. ## Protocol Revisions
  97. SwiftMCP serves both MCP eras side by side:
  98. - **Legacy** (`2025-03-26`, `2025-06-18`, `2025-11-25`): sessions opened with
  99. the `initialize` handshake.
  100. - **Modern** (`2026-07-28`): stateless requests that carry the version,
  101. identity and capabilities in `_meta`, discovered through `server/discover`.
  102. Servers advertise `2026-07-28` by default: `server/discover` and the `-32004`
  103. unsupported-version error list `MCPProtocolVersion.supported`, newest first.
  104. Legacy `initialize` only negotiates the legacy revisions, so a client that
  105. proposes `2026-07-28` (or anything unknown) there still gets `2025-11-25`.
  106. To stay legacy-only, opt out on the server. `server/discover` then answers
  107. `-32601`, which discover-first clients treat as "fall back to `initialize`":
  108. ```swift
  109. @MCPServer
  110. actor MyServer {
  111. nonisolated var advertisesModernEra: Bool { false }
  112. }
  113. ```
  114. On the client, `MCPServerProxy.eraPreference` picks the era: `.auto` (the
  115. default: probe `server/discover`, fall back to `initialize`), `.legacy`
  116. (`initialize` only, no probe) or `.modern` (modern only).
  117. To steer the revision itself, set `preferredProtocolVersion`. A legacy revision
  118. is proposed in `initialize` without a probe (the server may still answer with
  119. an older one; `negotiatedProtocolVersion` holds the result). A modern revision
  120. is selected from `server/discover`, with `.auto` still falling back to
  121. `initialize`. `connect()` throws if the two settings contradict each other.
  122. ```swift
  123. let proxy = MCPServerProxy(config: config)
  124. await proxy.setPreferredProtocolVersion("2025-06-18")
  125. try await proxy.connect()
  126. ```
  127. Server pushes work in both eras. On a modern connection the proxy holds one
  128. `subscriptions/listen` request open — a long-lived SSE stream over HTTP, the
  129. connection itself over stdio and TCP — whose filter follows the registered
  130. list-changed handlers and `subscribeResource(uri:)`. `subscribeResource` and
  131. `unsubscribeResource` update that filter and return once the server has
  132. acknowledged it.
  133. ### Migrating
  134. - **Servers** need no changes. Opt out with `advertisesModernEra == false` if
  135. a host must keep seeing a legacy-only server.
  136. - **Clients** probe `server/discover` before `initialize`. A legacy server
  137. answers with an error and the client falls back, but a stdio server that
  138. ignores unknown methods costs `eraProbeTimeout` (3 s) and a respawn. Set
  139. `eraPreference = .legacy` for such servers, and for code that depends on
  140. legacy session state (`sessionID`, `negotiatedProtocolVersion`, `logging/setLevel`).
  141. - The modern era has no `ping`. A dual-era server still answers a legacy
  142. `ping` at any time, even before `initialize`. On a modern connection
  143. `MCPServerProxy.ping()` sends that legacy ping when `server/discover` listed
  144. a legacy revision, and a `server/discover` round trip otherwise.
  145. - `MCPProtocolVersion.supported` now includes `2026-07-28`. Code that used it
  146. as "what `initialize` negotiates" should use
  147. `MCPProtocolVersion.legacySupported` instead.
  148. ## Custom Server Implementation
  149. To implement your own MCP server:
  150. 1. Attach the `@MCPServer` macro to a reference type like class or actor
  151. 2. Define your tools using `@MCPTool` attribute
  152. 3. Choose and configure a transport (stdio, HTTP+SSE, or TCP+Bonjour)
  153. Example:
  154. ```swift
  155. @MCPServer
  156. class MyServer {
  157. @MCPTool
  158. func add(a: Int, b: Int) -> Int {
  159. return a + b
  160. }
  161. }
  162. // Using HTTP+SSE transport with authorization
  163. let server = MyServer()
  164. let transport = HTTPSSETransport(server: server, port: 8080)
  165. // Optional: Add authorization
  166. transport.authorizationHandler = { token in
  167. guard let token = token, token == "your-secret-token" else {
  168. return .unauthorized("Invalid token")
  169. }
  170. return .authorized
  171. }
  172. // Or configure OAuth validation
  173. transport.oauthConfiguration = OAuthConfiguration(
  174. issuer: URL(string: "https://example.com")!,
  175. authorizationEndpoint: URL(string: "https://example.com/authorize")!,
  176. tokenEndpoint: URL(string: "https://example.com/oauth/token")!,
  177. introspectionEndpoint: URL(string: "https://example.com/oauth/introspect")!,
  178. jwksEndpoint: URL(string: "https://example.com/.well-known/jwks.json")!,
  179. audience: "your-api-identifier",
  180. clientID: "client",
  181. clientSecret: "secret"
  182. )
  183. try transport.run()
  184. ```
  185. To serve TCP+Bonjour instead:
  186. ```swift
  187. let server = MyServer()
  188. let tcpTransport = TCPBonjourTransport(server: server)
  189. try await tcpTransport.run()
  190. ```
  191. ## Typed Client Proxy
  192. SwiftMCP can generate a typed client proxy for any server. This proxy mirrors the
  193. `@MCPTool`, `@MCPResource`, and `@MCPPrompt` signatures and forwards calls through
  194. `MCPServerProxy`. Enable it with `generateClient: true` on the server macro.
  195. ```swift
  196. @MCPServer(generateClient: true)
  197. actor Calculator {
  198. @MCPTool
  199. func add(a: Int, b: Int) -> Int {
  200. a + b
  201. }
  202. }
  203. let url = URL(string: "http://localhost:8080/mcp")!
  204. let config = MCPServerConfig.sse(config: MCPServerSseConfig(url: url))
  205. let proxy = MCPServerProxy(config: config)
  206. try await proxy.connect()
  207. let client = Calculator.Client(proxy: proxy)
  208. let result = try await client.add(a: 2, b: 3)
  209. ```
  210. For TCP+Bonjour discovery:
  211. ```swift
  212. let config = MCPServerConfig.tcp(config: MCPServerTcpConfig(instanceName: "SwiftMCP Demo"))
  213. let proxy = MCPServerProxy(config: config)
  214. try await proxy.connect()
  215. ```
  216. ### Discovery scope
  217. Every MCP service advertises on the single service type `_mcp._tcp`. Identity lives
  218. in the Bonjour **instance name**, and how far that name reaches is one decision:
  219. | scope | reach | advertised name for base `Post` |
  220. |---|---|---|
  221. | `.localUser` *(default)* | loopback, name qualified by user | `Post (oliver)` |
  222. | `.localMachine` | loopback, bare name | `Post` |
  223. | `.localNetwork` | the attached link, bare name | `Post` |
  224. Only `.localUser` decorates the name, and only because the decoration is derivable
  225. on *both* sides — client and server are the same user on the same machine. Nothing
  226. qualifies by host: DNS-SD already resolves a service to its target host, and a
  227. hostname changes when the machine is renamed. Two machines advertising the same
  228. name are separated by mDNS, which renames the second to `Post (2)`.
  229. The scope drives binding, advertising, **and** browsing together, so a service can
  230. never be advertised more widely than it is served. Client and server pass the same
  231. *base* name and let the scope derive the rest:
  232. ```swift
  233. // server
  234. let transport = TCPBonjourTransport(server: server) // .localUser
  235. // client
  236. let config = MCPServerTcpConfig(instanceName: server.serverName) // .localUser
  237. ```
  238. `.localUser` is the default because instance names are machine-wide: two accounts
  239. running the same server would otherwise collide, and the second user's client would
  240. silently connect to the first user's process. It prevents that mis-binding — it is
  241. not an access boundary, since a loopback socket is visible to every account on the
  242. machine. Authenticate if you need one.
  243. `.localNetwork` is opt-in — the TCP transport has no authorization hook, so anything
  244. reachable there is reachable unauthenticated unless you add your own layer.
  245. When discovery isn't an option, connect directly and skip it:
  246. ```swift
  247. let config = MCPServerTcpConfig(host: "127.0.0.1", port: 8181)
  248. ```
  249. Notes:
  250. - Client generation is opt-in (`generateClient` defaults to `false`).
  251. - Client methods always `throw` to surface transport or server errors.
  252. - Prefer the Streamable HTTP `/mcp` endpoint for new clients. The legacy `/sse` endpoint remains available for backwards compatibility.
  253. ## MCP Events
  254. On a modern (`2026-07-28`) connection, servers can advertise application events
  255. and deliver them to webhook subscribers. Declare a type with `@MCPEvent`
  256. (optional `name:` for dotted wire names such as `ci.failed`), publish with
  257. `emit`, and use the era-gated client helpers:
  258. ```swift
  259. let events = try await proxy.listEvents()
  260. let delivery = EventsWebhookDelivery(
  261. url: "https://receiver.example.com/hook",
  262. secret: WebhookSigner.generateSecret()
  263. )
  264. let subscription = try await proxy.subscribeEvent(name: "ci.failed", delivery: delivery)
  265. try await proxy.unsubscribeEvent(
  266. name: "ci.failed",
  267. delivery: EventsWebhookDelivery(url: delivery.url)
  268. )
  269. ```
  270. Subscribe requires an authenticated principal (for example
  271. `await proxy.setMeta(["accessToken": .string("…")])`). The demo server exposes `ci.failed`
  272. and an `emitCIFailed` tool. For ChatGPT Work interop, see
  273. [`docs/chatgpt-work-events-runbook.md`](docs/chatgpt-work-events-runbook.md).
  274. Events are not a replacement for protocol notifications — see the DocC article
  275. *Events vs. subscriptions/listen*.
  276. ## Client Notification Handlers
  277. `MCPServerProxy` can also surface typed JSON-RPC notifications from the server.
  278. Use `setNotificationHandler(_:as:handler:)` for custom app/domain events and
  279. use `setLogNotificationHandler(_:)` / `setProgressNotificationHandler(_:)` for
  280. the built-in convenience paths.
  281. ```swift
  282. struct RunStatusUpdate: Codable, Sendable {
  283. let runID: String
  284. let status: String
  285. }
  286. await proxy.setNotificationHandler("notifications/runStatusChanged", as: RunStatusUpdate.self) { update in
  287. print("Run \(update.runID) is now \(update.status)")
  288. }
  289. ```
  290. ## SwiftMCPUtility Proxy Generation
  291. Use `SwiftMCPUtility generate-proxy` to create a client proxy for any MCP server,
  292. including non-SwiftMCP servers. The generated proxy calls `MCPServerProxy` under
  293. the hood, generates typed tool methods from MCP tool schemas, and adds first-class
  294. resource/prompt convenience APIs when the server advertises those capabilities.
  295. Input parameters are inferred from the server's tool schemas, and only string
  296. formats such as `date-time`, `uri`, `uuid`, and `byte` can be mapped to native
  297. types (`Date`, `URL`, `UUID`, `Data`).
  298. ```bash
  299. SwiftMCPUtility generate-proxy --sse http://localhost:8080/mcp -o ToolsProxy.swift
  300. ```
  301. All generated methods are `async throws` so transport and server errors are surfaced.
  302. ### OpenAPI Return Types
  303. If the MCP server exposes an OpenAPI JSON document, pass its URL (or file path)
  304. to `--openapi` to enrich return types. The generator overlays OpenAPI response
  305. schemas onto the MCP tool list, produces Codable structs/enums for structured
  306. responses, and uses those types in the proxy's return signatures.
  307. ```bash
  308. SwiftMCPUtility generate-proxy \
  309. --sse http://localhost:8080/mcp \
  310. --openapi http://localhost:8080/openapi.json \
  311. -o ToolsProxy.swift
  312. ```
  313. The generated Codable types can be used as-is or replaced with your own models
  314. later if you have local definitions.
  315. ## Documentation Extraction
  316. The `@MCPServer` and `@MCPTool` macros extract documentation comments to describe class, parameters and return value.
  317. ## Macros Functionality
  318. 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:
  319. * `@MCPServer`: This macro is used to define a class or actor as an MCP server. It extracts the server description from documentation comments (or the optional `description:` override). 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")`.
  320. * `@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`.
  321. * `@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.
  322. ### Using @MCPResource
  323. The `@MCPResource` macro allows you to expose functions as resources that can be accessed via URI patterns:
  324. ```swift
  325. @MCPServer(name: "ResourceServer")
  326. actor ResourceServer {
  327. /// Get user profile by ID
  328. @MCPResource("users://{user_id}/profile")
  329. func getUserProfile(user_id: Int) -> String {
  330. return "Profile for user \(user_id)"
  331. }
  332. /// Search users with pagination
  333. @MCPResource("users://search?q={query}&page={page}", mimeType: "application/json")
  334. func searchUsers(query: String, page: Int = 1) -> String {
  335. return """
  336. {"query": "\(query)", "page": \(page), "results": [...]}
  337. """
  338. }
  339. }
  340. ```
  341. Key features:
  342. - **URI Templates**: Define patterns with placeholders in curly braces `{param}`
  343. - **Path Parameters**: Extract values from the URI path (e.g., `/users/{id}`)
  344. - **Query Parameters**: Extract values from query strings (e.g., `?page={page}`)
  345. - **Optional Parameters**: Support default values for optional parameters
  346. - **MIME Types**: Optionally specify content type with `mimeType` parameter
  347. - **Type Safety**: Parameters are automatically converted to the correct Swift types
  348. The server automatically provides:
  349. - Resource discovery through `mcpResourceTemplates`
  350. - URI matching and parameter extraction
  351. - Type conversion and validation
  352. - Error handling for missing or invalid parameters
  353. 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.
  354. ## License
  355. This project is licensed under the BSD 2-clause License - see the LICENSE file for details.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.