Swift MCP Server Generator

Swift MCP Server Generator

Generates a complete Model Context Protocol server project in Swift with the official SDK, including package setup, tools, resources, prompts, tests and a README.

Skill files1 file
SKILL.md670 lines
1
---
2
name: swift-mcp-server-generator
3
description: 'Generate a complete Model Context Protocol server project in Swift using the official MCP Swift SDK package.'
4
---
5
6
# Swift MCP Server Generator
7
8
Generate a complete, production-ready MCP server in Swift using the official Swift SDK package.
9
10
## Project Generation
11
12
When asked to create a Swift MCP server, generate a complete project with this structure:
13
14
```
15
my-mcp-server/
16
├── Package.swift
17
├── Sources/
18
│ └── MyMCPServer/
19
│ ├── main.swift
20
│ ├── Server.swift
21
│ ├── Tools/
22
│ │ ├── ToolDefinitions.swift
23
│ │ └── ToolHandlers.swift
24
│ ├── Resources/
25
│ │ ├── ResourceDefinitions.swift
26
│ │ └── ResourceHandlers.swift
27
│ └── Prompts/
28
│ ├── PromptDefinitions.swift
29
│ └── PromptHandlers.swift
30
├── Tests/
31
│ └── MyMCPServerTests/
32
│ └── ServerTests.swift
33
└── README.md
34
```
35
36
## Package.swift Template
37
38
```swift
39
// swift-tools-version: 6.0
40
import PackageDescription
41
42
let package = Package(
43
name: "MyMCPServer",
44
platforms: [
45
.macOS(.v13),
46
.iOS(.v16),
47
.watchOS(.v9),
48
.tvOS(.v16),
49
.visionOS(.v1)
50
],
51
dependencies: [
52
.package(
53
url: "https://github.com/modelcontextprotocol/swift-sdk.git",
54
from: "0.10.0"
55
),
56
.package(
57
url: "https://github.com/apple/swift-log.git",
58
from: "1.5.0"
59
),
60
.package(
61
url: "https://github.com/swift-server/swift-service-lifecycle.git",
62
from: "2.0.0"
63
)
64
],
65
targets: [
66
.executableTarget(
67
name: "MyMCPServer",
68
dependencies: [
69
.product(name: "MCP", package: "swift-sdk"),
70
.product(name: "Logging", package: "swift-log"),
71
.product(name: "ServiceLifecycle", package: "swift-service-lifecycle")
72
]
73
),
74
.testTarget(
75
name: "MyMCPServerTests",
76
dependencies: ["MyMCPServer"]
77
)
78
]
79
)
80
```
81
82
## main.swift Template
83
84
```swift
85
import MCP
86
import Logging
87
import ServiceLifecycle
88
89
struct MCPService: Service {
90
let server: Server
91
let transport: Transport
92
93
func run() async throws {
94
try await server.start(transport: transport) { clientInfo, capabilities in
95
logger.info("Client connected", metadata: [
96
"name": .string(clientInfo.name),
97
"version": .string(clientInfo.version)
98
])
99
}
100
101
// Keep service running
102
try await Task.sleep(for: .days(365 * 100))
103
}
104
105
func shutdown() async throws {
106
logger.info("Shutting down MCP server")
107
await server.stop()
108
}
109
}
110
111
var logger = Logger(label: "com.example.mcp-server")
112
logger.logLevel = .info
113
114
do {
115
let server = await createServer()
116
let transport = StdioTransport(logger: logger)
117
let service = MCPService(server: server, transport: transport)
118
119
let serviceGroup = ServiceGroup(
120
services: [service],
121
configuration: .init(
122
gracefulShutdownSignals: [.sigterm, .sigint]
123
),
124
logger: logger
125
)
126
127
try await serviceGroup.run()
128
} catch {
129
logger.error("Fatal error", metadata: ["error": .string("\(error)")])
130
throw error
131
}
132
```
133
134
## Server.swift Template
135
136
```swift
137
import MCP
138
import Logging
139
140
func createServer() async -> Server {
141
let server = Server(
142
name: "MyMCPServer",
143
version: "1.0.0",
144
capabilities: .init(
145
prompts: .init(listChanged: true),
146
resources: .init(subscribe: true, listChanged: true),
147
tools: .init(listChanged: true)
148
)
149
)
150
151
// Register tool handlers
152
await registerToolHandlers(server: server)
153
154
// Register resource handlers
155
await registerResourceHandlers(server: server)
156
157
// Register prompt handlers
158
await registerPromptHandlers(server: server)
159
160
return server
161
}
162
```
163
164
## ToolDefinitions.swift Template
165
166
```swift
167
import MCP
168
169
func getToolDefinitions() -> [Tool] {
170
[
171
Tool(
172
name: "greet",
173
description: "Generate a greeting message",
174
inputSchema: .object([
175
"type": .string("object"),
176
"properties": .object([
177
"name": .object([
178
"type": .string("string"),
179
"description": .string("Name to greet")
180
])
181
]),
182
"required": .array([.string("name")])
183
])
184
),
185
Tool(
186
name: "calculate",
187
description: "Perform mathematical calculations",
188
inputSchema: .object([
189
"type": .string("object"),
190
"properties": .object([
191
"operation": .object([
192
"type": .string("string"),
193
"enum": .array([
194
.string("add"),
195
.string("subtract"),
196
.string("multiply"),
197
.string("divide")
198
]),
199
"description": .string("Operation to perform")
200
]),
201
"a": .object([
202
"type": .string("number"),
203
"description": .string("First operand")
204
]),
205
"b": .object([
206
"type": .string("number"),
207
"description": .string("Second operand")
208
])
209
]),
210
"required": .array([
211
.string("operation"),
212
.string("a"),
213
.string("b")
214
])
215
])
216
)
217
]
218
}
219
```
220
221
## ToolHandlers.swift Template
222
223
```swift
224
import MCP
225
import Logging
226
227
private let logger = Logger(label: "com.example.mcp-server.tools")
228
229
func registerToolHandlers(server: Server) async {
230
await server.withMethodHandler(ListTools.self) { _ in
231
logger.debug("Listing available tools")
232
return .init(tools: getToolDefinitions())
233
}
234
235
await server.withMethodHandler(CallTool.self) { params in
236
logger.info("Tool called", metadata: ["name": .string(params.name)])
237
238
switch params.name {
239
case "greet":
240
return handleGreet(params: params)
241
242
case "calculate":
243
return handleCalculate(params: params)
244
245
default:
246
logger.warning("Unknown tool requested", metadata: ["name": .string(params.name)])
247
return .init(
248
content: [.text("Unknown tool: \(params.name)")],
249
isError: true
250
)
251
}
252
}
253
}
254
255
private func handleGreet(params: CallTool.Params) -> CallTool.Result {
256
guard let name = params.arguments?["name"]?.stringValue else {
257
return .init(
258
content: [.text("Missing 'name' parameter")],
259
isError: true
260
)
261
}
262
263
let greeting = "Hello, \(name)! Welcome to MCP."
264
logger.debug("Generated greeting", metadata: ["name": .string(name)])
265
266
return .init(
267
content: [.text(greeting)],
268
isError: false
269
)
270
}
271
272
private func handleCalculate(params: CallTool.Params) -> CallTool.Result {
273
guard let operation = params.arguments?["operation"]?.stringValue,
274
let a = params.arguments?["a"]?.doubleValue,
275
let b = params.arguments?["b"]?.doubleValue else {
276
return .init(
277
content: [.text("Missing or invalid parameters")],
278
isError: true
279
)
280
}
281
282
let result: Double
283
switch operation {
284
case "add":
285
result = a + b
286
case "subtract":
287
result = a - b
288
case "multiply":
289
result = a * b
290
case "divide":
291
guard b != 0 else {
292
return .init(
293
content: [.text("Division by zero")],
294
isError: true
295
)
296
}
297
result = a / b
298
default:
299
return .init(
300
content: [.text("Unknown operation: \(operation)")],
301
isError: true
302
)
303
}
304
305
logger.debug("Calculation performed", metadata: [
306
"operation": .string(operation),
307
"result": .string("\(result)")
308
])
309
310
return .init(
311
content: [.text("Result: \(result)")],
312
isError: false
313
)
314
}
315
```
316
317
## ResourceDefinitions.swift Template
318
319
```swift
320
import MCP
321
322
func getResourceDefinitions() -> [Resource] {
323
[
324
Resource(
325
name: "Example Data",
326
uri: "resource://data/example",
327
description: "Example resource data",
328
mimeType: "application/json"
329
),
330
Resource(
331
name: "Configuration",
332
uri: "resource://config",
333
description: "Server configuration",
334
mimeType: "application/json"
335
)
336
]
337
}
338
```
339
340
## ResourceHandlers.swift Template
341
342
```swift
343
import MCP
344
import Logging
345
import Foundation
346
347
private let logger = Logger(label: "com.example.mcp-server.resources")
348
349
actor ResourceState {
350
private var subscriptions: Set<String> = []
351
352
func addSubscription(_ uri: String) {
353
subscriptions.insert(uri)
354
}
355
356
func removeSubscription(_ uri: String) {
357
subscriptions.remove(uri)
358
}
359
360
func isSubscribed(_ uri: String) -> Bool {
361
subscriptions.contains(uri)
362
}
363
}
364
365
private let state = ResourceState()
366
367
func registerResourceHandlers(server: Server) async {
368
await server.withMethodHandler(ListResources.self) { params in
369
logger.debug("Listing available resources")
370
return .init(resources: getResourceDefinitions(), nextCursor: nil)
371
}
372
373
await server.withMethodHandler(ReadResource.self) { params in
374
logger.info("Reading resource", metadata: ["uri": .string(params.uri)])
375
376
switch params.uri {
377
case "resource://data/example":
378
let jsonData = """
379
{
380
"message": "Example resource data",
381
"timestamp": "\(Date())"
382
}
383
"""
384
return .init(contents: [
385
.text(jsonData, uri: params.uri, mimeType: "application/json")
386
])
387
388
case "resource://config":
389
let config = """
390
{
391
"serverName": "MyMCPServer",
392
"version": "1.0.0"
393
}
394
"""
395
return .init(contents: [
396
.text(config, uri: params.uri, mimeType: "application/json")
397
])
398
399
default:
400
logger.warning("Unknown resource requested", metadata: ["uri": .string(params.uri)])
401
throw MCPError.invalidParams("Unknown resource URI: \(params.uri)")
402
}
403
}
404
405
await server.withMethodHandler(ResourceSubscribe.self) { params in
406
logger.info("Client subscribed to resource", metadata: ["uri": .string(params.uri)])
407
await state.addSubscription(params.uri)
408
return .init()
409
}
410
411
await server.withMethodHandler(ResourceUnsubscribe.self) { params in
412
logger.info("Client unsubscribed from resource", metadata: ["uri": .string(params.uri)])
413
await state.removeSubscription(params.uri)
414
return .init()
415
}
416
}
417
```
418
419
## PromptDefinitions.swift Template
420
421
```swift
422
import MCP
423
424
func getPromptDefinitions() -> [Prompt] {
425
[
426
Prompt(
427
name: "code-review",
428
description: "Generate a code review prompt",
429
arguments: [
430
.init(name: "language", description: "Programming language", required: true),
431
.init(name: "focus", description: "Review focus area", required: false)
432
]
433
)
434
]
435
}
436
```
437
438
## PromptHandlers.swift Template
439
440
```swift
441
import MCP
442
import Logging
443
444
private let logger = Logger(label: "com.example.mcp-server.prompts")
445
446
func registerPromptHandlers(server: Server) async {
447
await server.withMethodHandler(ListPrompts.self) { params in
448
logger.debug("Listing available prompts")
449
return .init(prompts: getPromptDefinitions(), nextCursor: nil)
450
}
451
452
await server.withMethodHandler(GetPrompt.self) { params in
453
logger.info("Getting prompt", metadata: ["name": .string(params.name)])
454
455
switch params.name {
456
case "code-review":
457
return handleCodeReviewPrompt(params: params)
458
459
default:
460
logger.warning("Unknown prompt requested", metadata: ["name": .string(params.name)])
461
throw MCPError.invalidParams("Unknown prompt: \(params.name)")
462
}
463
}
464
}
465
466
private func handleCodeReviewPrompt(params: GetPrompt.Params) -> GetPrompt.Result {
467
guard let language = params.arguments?["language"]?.stringValue else {
468
return .init(
469
description: "Missing language parameter",
470
messages: []
471
)
472
}
473
474
let focus = params.arguments?["focus"]?.stringValue ?? "general quality"
475
476
let description = "Code review for \(language) with focus on \(focus)"
477
let messages: [Prompt.Message] = [
478
.user("Please review this \(language) code with focus on \(focus)."),
479
.assistant("I'll review the code focusing on \(focus). Please share the code."),
480
.user("Here's the code to review: [paste code here]")
481
]
482
483
logger.debug("Generated code review prompt", metadata: [
484
"language": .string(language),
485
"focus": .string(focus)
486
])
487
488
return .init(description: description, messages: messages)
489
}
490
```
491
492
## ServerTests.swift Template
493
494
```swift
495
import XCTest
496
@testable import MyMCPServer
497
498
final class ServerTests: XCTestCase {
499
func testGreetTool() async throws {
500
let params = CallTool.Params(
501
name: "greet",
502
arguments: ["name": .string("Swift")]
503
)
504
505
let result = handleGreet(params: params)
506
507
XCTAssertFalse(result.isError ?? true)
508
XCTAssertEqual(result.content.count, 1)
509
510
if case .text(let message) = result.content[0] {
511
XCTAssertTrue(message.contains("Swift"))
512
} else {
513
XCTFail("Expected text content")
514
}
515
}
516
517
func testCalculateTool() async throws {
518
let params = CallTool.Params(
519
name: "calculate",
520
arguments: [
521
"operation": .string("add"),
522
"a": .number(5),
523
"b": .number(3)
524
]
525
)
526
527
let result = handleCalculate(params: params)
528
529
XCTAssertFalse(result.isError ?? true)
530
XCTAssertEqual(result.content.count, 1)
531
532
if case .text(let message) = result.content[0] {
533
XCTAssertTrue(message.contains("8"))
534
} else {
535
XCTFail("Expected text content")
536
}
537
}
538
539
func testDivideByZero() async throws {
540
let params = CallTool.Params(
541
name: "calculate",
542
arguments: [
543
"operation": .string("divide"),
544
"a": .number(10),
545
"b": .number(0)
546
]
547
)
548
549
let result = handleCalculate(params: params)
550
551
XCTAssertTrue(result.isError ?? false)
552
}
553
}
554
```
555
556
## README.md Template
557
558
```markdown
559
# MyMCPServer
560
561
A Model Context Protocol server built with Swift.
562
563
## Features
564
565
- ✅ Tools: greet, calculate
566
- ✅ Resources: example data, configuration
567
- ✅ Prompts: code-review
568
- ✅ Graceful shutdown with ServiceLifecycle
569
- ✅ Structured logging with swift-log
570
- ✅ Full test coverage
571
572
## Requirements
573
574
- Swift 6.0+
575
- macOS 13+, iOS 16+, or Linux
576
577
## Installation
578
579
```bash
580
swift build -c release
581
```
582
583
## Usage
584
585
Run the server:
586
587
```bash
588
swift run
589
```
590
591
Or with logging:
592
593
```bash
594
LOG_LEVEL=debug swift run
595
```
596
597
## Testing
598
599
```bash
600
swift test
601
```
602
603
## Development
604
605
The server uses:
606
- [MCP Swift SDK](https://github.com/modelcontextprotocol/swift-sdk) - MCP protocol implementation
607
- [swift-log](https://github.com/apple/swift-log) - Structured logging
608
- [swift-service-lifecycle](https://github.com/swift-server/swift-service-lifecycle) - Graceful shutdown
609
610
## Project Structure
611
612
- `Sources/MyMCPServer/main.swift` - Entry point with ServiceLifecycle
613
- `Sources/MyMCPServer/Server.swift` - Server configuration
614
- `Sources/MyMCPServer/Tools/` - Tool definitions and handlers
615
- `Sources/MyMCPServer/Resources/` - Resource definitions and handlers
616
- `Sources/MyMCPServer/Prompts/` - Prompt definitions and handlers
617
- `Tests/` - Unit tests
618
619
## License
620
621
MIT
622
```
623
624
## Generation Instructions
625
626
1. **Ask for project name and description**
627
2. **Generate all files** with proper naming
628
3. **Use actor-based state** for thread safety
629
4. **Include comprehensive logging** with swift-log
630
5. **Implement graceful shutdown** with ServiceLifecycle
631
6. **Add tests** for all handlers
632
7. **Use modern Swift concurrency** (async/await)
633
8. **Follow Swift naming conventions** (camelCase, PascalCase)
634
9. **Include error handling** with proper MCPError usage
635
10. **Document public APIs** with doc comments
636
637
## Build and Run
638
639
```bash
640
# Build
641
swift build
642
643
# Run
644
swift run
645
646
# Test
647
swift test
648
649
# Release build
650
swift build -c release
651
652
# Install
653
swift build -c release
654
cp .build/release/MyMCPServer /usr/local/bin/
655
```
656
657
## Integration with Claude Desktop
658
659
Add to `claude_desktop_config.json`:
660
661
```json
662
{
663
"mcpServers": {
664
"my-mcp-server": {
665
"command": "/path/to/MyMCPServer"
666
}
667
}
668
}
669
```
670

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 13,704 prompts

More by @OpenSourceBuffGuy

See all
Seated woman over giant graphite watercolor face prompt image

Seated woman over giant graphite watercolor face

Paints an elegant watercolor fashion portrait of a seated woman in lavender and ivory in front of a giant graphite-and-watercolor close-up of her own face.

image-prompt, gpt-image, watercolor, portrait, woman, fashion, fashion-shoot, editorial, double-exposure, black-and-white, muted-colors, soft-lighting, full-body, vertical-format, negative-prompt, illustration, sketch, negative-space, fine-art, character-design, structured-output, for-artists, jewelry, long-form

Woman with hot cup at Christmas market prompt image

Woman with hot cup at Christmas market

Creates a candid smartphone-style photo of a woman in a white fur coat holding a hot drink at an evening Christmas market, keeping the face from a reference photo.

image-prompt, gpt-image, nano-banana, face-reference, reference-image, negative-prompt, photorealistic, portrait, woman, christmas, holiday, winter, night-scene, candid, smartphone-photo, medium-shot, fashion, street-photography, cozy, warm-colors, structured-output, for-photographers, long-form, guardrails, cityscape

Suited man enters glowing elevator, floor display at 13 prompt image

Suited man enters glowing elevator, floor display at 13

Writes a 30-second Korean mystery thriller in which a man's elevator opens onto an impossible floor 0, with scene beats, cinematography and sound design.

video-prompt, seedance, horror, thriller, short-film, cinematic, multi-shot, timed-beats, character-consistency, camera-movement, sound-effects, guardrails, structured-output, photorealistic, korea, night-scene, symmetry, moody, for-filmmakers, long-form, advanced, film-noir

Reviews

Loading reviews…

Discussion

Loading comments…