Swift SDK

MCP开发工具

提供方 modelcontextprotocol

开发工具 未标注 OAuth 授权 社区 / 第三方 Cursor

MCP Swift SDK是一个实现模型上下文协议的客户端和服务器组件,用于应用程序与AI和ML模型之间的标准化通信。

一句话选型结论

按资料字段整理

Swift SDK 属于开发工具类 MCP 服务器,传输方式未标注,OAuth 授权,可直接接入 Cursor,没有现成安装命令,需按官方文档接入。接入前先确认权限范围;涉及写入、删除或付款的操作,建议先在测试环境验证。

分类开发工具 传输方式未标注 鉴权OAuth 授权 部署方式未标注
GitHub 星标 1,377 仓库热度,无公开仓库时显示未标注
工具数 2 暴露给模型的工具数量
资源 / 提示词 0 / 0 资源与提示词模板数量
维护方 社区 / 第三方 核验等级 仅资料核对

工具与能力

开发工具
数量来自来源目录的标注,具体工具清单以官方文档为准
工具数量2暴露给模型可调用的工具个数
资源数量0可读取的资源条目
提示词数量0内置提示词模板数量

能力标签

支持客户端

适用场景

Swift本地部署人工智能机器学习模型通信SwiftSDK标准化协议

安装与配置

未标注 OAuth 授权
上游未给出传输方式
  1. 1
    准备运行环境

    按官方文档确认运行环境(常见为 Node.js 或 Python),装好后再执行安装命令。

  2. 2
    安装服务

    复制上面的安装命令执行;命令里带占位符的位置,换成自己的密钥或路径。

  3. 3
    写入客户端配置

    在客户端的 MCP 配置里填好启动命令和参数,保存后完全退出客户端再打开,让新配置生效。

  4. 4
    验证是否可用

    连接成功后客户端会列出约 2 个工具,随便调一个只读工具确认能返回结果。

典型使用场景

3 类
按分类与标签整理的常见用法,具体以官方文档为准
代码与仓库操作

在对话里直接查代码、提 issue、走 PR,省掉来回切工具。

本地命令与脚本

把构建、测试、格式化这类重复命令交给模型执行。

接口联调与测试

让模型调你的接口、跑一遍用例,快速定位问题。

选择建议

选之前先看这几条
按条目字段给出的判断,不替你决定用不用

值得选的地方

  • 资料标注 2 个工具,职责相对集中,接入后不容易误操作。
  • 已适配 Cursor,换客户端不用重新研究配置。
  • 仓库有一定关注度(星标 1,377),遇到问题更容易搜到资料。

先想清楚的地方

  • 没有现成安装命令,需要按官方文档自己填启动命令和参数。
  • 使用前要准备好OAuth 授权对应的凭据,并按最小权限配置。
  • 版本更新与行为细节以官方仓库为准。

更适合

  • 需要在开发工具场景里让模型直接调用外部能力的人。
  • 已经在用 Cursor 的用户,接入路径最短。
  • 想先快速试一下、能接受在本地或自有环境跑服务的人。

不太适合

  • 不方便管理密钥或第三方授权的人。
  • 需要厂商级 SLA 和技术支持的生产环境。

同类对比

6 个同类
同分类里挑最接近的几条,字段以各自详情页为准
MCP 服务器工具数传输方式部署方式安装命令最后核验
Swift SDK当前 2 未标注 未标注 无 2026-05-17
Git 838e2ec1 12 stdio · 本地进程 本地部署 有 2026-05-17
Markitdown MCP 2c653a5f 1 stdio · 本地进程 本地部署 有 2026-05-17
JavaGuide 未标注 stdio · 本地进程 本地部署 有 2026-04-11
awesome-claude-skills 未标注 stdio · 本地进程 本地部署 有 2026-04-26
Context7 831acf40 未标注 stdio · 本地进程 本地部署 有 2026-05-17

服务器档案

开发工具
字段来自项目仓库与公开索引,中文说明由本站标注
提供方modelcontextprotocol上游标注的维护方 modelcontextprotocol
分类开发工具本站按上游分类展示
连接方式未标注上游未给出传输方式
鉴权方式OAuth 授权远程服务建议用最小权限凭据
维护方社区 / 第三方核验等级 仅资料核对
包名 / 运行时未标注 · 未标注本地安装时用到的包标识与运行时
部署类型未标注上游给出的部署形态
最近核验2026-05-17上游最后核验时间

详细介绍

42.6 KB
来自项目仓库与上游目录的原文,未做删改

MCP Swift SDK

官方Swift SDK 模型上下文协议 (MCP)。

概述

模型上下文协议(MCP)定义了一种标准化的方法
用于应用程序与AI和ML模型通信。
这个Swift SDK实现了客户端和服务器端组件
根据 2025-11-25 (最新)版本
MCP规范。

目录

  • 需求
  • 安装
  • 客户端使用情况
  • 基本客户端设置
  • 客户的运输选择
  • 工具
  • 资源
  • 提示
  • 补全
  • 采样
  • 引出
  • 根
  • 日志记录
  • 错误处理
  • 取消
  • 进度跟踪
  • 高级客户端功能
  • 服务器使用情况
  • 基本服务器设置
  • 工具
  • 资源
  • 提示
  • 补全
  • 采样
  • 精英
  • 根
  • 日志记录
  • 进度跟踪
  • 初始化钩子
  • 处理程序中的HTTP请求上下文
  • 优雅地关闭
  • 运输
  • 认证
  • 客户端:客户端凭据流
  • 客户端:授权码流
  • 客户端:自定义令牌提供程序
  • 客户端:自定义令牌存储
  • 客户端:private_key_jwt身份验证
  • 客户端:端点覆盖
  • 服务器:提供受保护的资源元数据
  • 服务器:验证承载令牌
  • 平台可用性
  • 调试和记录
  • 其他资源
  • 更新日志
  • 许可证

需求

  • Swift 6.0+(Xcode 16+)

看 平台可用性 下节
针对特定平台的要求。

安装

Swift包管理器

将以下内容添加到您的 Package.swift 文件:```swift
dependencies: [
.package(url: "https://github.com/modelcontextprotocol/swift-sdk.git", from: "0.11.0")
]


然后将依赖关系添加到目标:```swift
.target(
name: "YourTarget",
dependencies: [
.product(name: "MCP", package: "swift-sdk")
]
)

客户端使用情况

客户端组件允许您的应用程序连接到MCP服务器。

基本客户端设置```swift

import MCP

// Initialize the client
let client = Client(name: "MyApp", version: "1.0.0")

// Create a transport and connect
let transport = StdioTransport()
let result = try await client.connect(transport: transport)

// Check server capabilities
if result.capabilities.tools != nil {
// Server supports tools (implicitly including tool calling if the 'tools' capability object is present)
}


> \[!注意\]
> 这 `Client.connect(transport:)` 方法返回初始化结果。
> 该返回值是可丢弃的,
> 因此,如果不需要检查服务器功能,可以忽略它。

### 客户的运输选择

#### 标准运输

对于本地子流程通信:```swift
// Create a stdio transport (simplest option)
let transport = StdioTransport()
try await client.connect(transport: transport)

HTTP传输

对于远程服务器通信:```swift
// Create a streaming HTTP transport
let transport = HTTPClientTransport(
endpoint: URL(string: "http://localhost:8080")!,
streaming: true // Enable Server-Sent Events for real-time updates
)
try await client.connect(transport: transport)


### 工具

工具表示客户端可以调用的函数:```swift
// List available tools
let (tools, cursor) = try await client.listTools()
print("Available tools: \(tools.map { $0.name }.joined(separator: ", "))")

// Call a tool with arguments and get the result
let (content, isError) = try await client.callTool(
name: "image-generator",
arguments: [
"prompt": "A serene mountain landscape at sunset",
"style": "photorealistic",
"width": 1024,
"height": 768
]
)

// Handle tool content
for item in content {
switch item {
case .text(let text):
print("Generated text: \(text)")
case .image(let data, let mimeType, let metadata):
if let width = metadata?["width"] as? Int,
let height = metadata?["height"] as? Int {
print("Generated \(width)x\(height) image of type \(mimeType)")
// Save or display the image data
}
case .audio(let data, let mimeType):
print("Received audio data of type \(mimeType)")
case .resource(let resource, _, _):
print("Received embedded resource: \(resource)")
case .resourceLink(let uri, let name, _, _, let mimeType, _):
print("Resource link: \(name) at \(uri), type: \(mimeType ?? "unknown")")
}
}

资源

资源表示可以访问和潜在订阅的数据:```swift
// List available resources
let (resources, nextCursor) = try await client.listResources()
print("Available resources: (resources.map { $0.uri }.joined(separator: ", "))")

// Read a resource
let contents = try await client.readResource(uri: "resource://example")
print("Resource content: (contents)")

// Subscribe to resource updates if supported
if result.capabilities.resources?.subscribe == true {
try await client.subscribeToResource(uri: "resource://example")

// Register notification handler
await client.onNotification(ResourceUpdatedNotification.self) { message in
let uri = message.params.uri
print("Resource (uri) updated with new content")

// Fetch the updated resource content
let updatedContents = try await client.readResource(uri: uri)
print("Updated resource content received")
}
}


### 提示

提示代表模板化的对话开始者:```swift
// List available prompts
let (prompts, nextCursor) = try await client.listPrompts()
print("Available prompts: \(prompts.map { $0.name }.joined(separator: ", "))")

// Get a prompt with arguments
let (description, messages) = try await client.getPrompt(
name: "customer-service",
arguments: [
"customerName": "Alice",
"orderNumber": "ORD-12345",
"issue": "delivery delay"
]
)

// Use the prompt messages in your application
print("Prompt description: \(description)")
for message in messages {
if case .text(text: let text) = message.content {
print("\(message.role): \(text)")
}
}

补全

补全允许服务器在用户键入时为提示和资源模板参数提供自动补全建议:```swift
// Request completions for a prompt argument
let completion = try await client.complete(
promptName: "code_review",
argumentName: "language",
argumentValue: "py"
)

// Display suggestions to the user
for value in completion.values {
print("Suggestion: (value)")
}

if completion.hasMore == true {
print("More suggestions available (total: (completion.total ?? 0))")
}


您还可以提供已解析参数的上下文:```swift
// First, user selects a language
let languageCompletion = try await client.complete(
promptName: "code_review",
argumentName: "language",
argumentValue: "py"
)
// User selects "python"

// Then get framework suggestions based on the selected language
let frameworkCompletion = try await client.complete(
promptName: "code_review",
argumentName: "framework",
argumentValue: "fla",
context: ["language": .string("python")]
)
// Returns: ["flask"]

完成资源模板的工作:```swift
// Get path completions for a resource URI template
let pathCompletion = try await client.complete(
resourceURI: "file:///{path}",
argumentName: "path",
argumentValue: "/usr/"
)
// Returns: ["/usr/bin", "/usr/lib", "/usr/local"]


### 采样

采样允许服务器通过客户端请求LLM完成,
实现代理行为,同时保持人类在环控制。
客户端注册一个处理程序来处理来自服务器的传入采样请求。

> \[!提示\]
> 采样请求来自 **服务器到客户端**,
> 不是客户端到服务器。
> 这使服务器能够请求AI协助
> 而客户端保持对模型访问和用户批准的控制。```swift
// Register a sampling handler in the client
await client.withSamplingHandler { parameters in
// Review the sampling request (human-in-the-loop step 1)
print("Server requests completion for: \(parameters.messages)")

// Optionally modify the request based on user input
var messages = parameters.messages
if let systemPrompt = parameters.systemPrompt {
print("System prompt: \(systemPrompt)")
}

// Sample from your LLM (this is where you'd call your AI service)
let completion = try await callYourLLMService(
messages: messages,
maxTokens: parameters.maxTokens,
temperature: parameters.temperature
)

// Review the completion (human-in-the-loop step 2)
print("LLM generated: \(completion)")
// User can approve, modify, or reject the completion here

// Return the result to the server
return CreateSamplingMessage.Result(
model: "your-model-name",
stopReason: .endTurn,
role: .assistant,
content: .text(completion)
)
}

引出

Elicitation允许服务器通过客户端直接向用户请求结构化信息。
当服务器需要原始请求中未提供的用户输入时,这很有用,
例如凭据、配置选择或敏感操作的批准。

> [!提示]
> 征集请求来自 服务器到客户端,
> 类似于采样。
> 客户端必须注册一个处理程序来响应来自服务器的启发请求。

客户端:处理激励请求

注册一个启发处理程序来响应服务器请求:```swift
// Register an elicitation handler in the client
await client.withElicitationHandler { parameters in
switch parameters {
case .form(let form):
// Display the request to the user
print("Server requests: (form.message)")

// If a schema was provided, inspect it
if let schema = form.requestedSchema {
print("Required fields: (schema.required ?? [])")
print("Schema: (schema.properties)")
}

// Present UI to collect user input
let userResponse = presentElicitationUI(form)

// Return the user's response
if userResponse.accepted {
return CreateElicitation.Result(
action: .accept,
content: userResponse.data
)
} else if userResponse.canceled {
return CreateElicitation.Result(action: .cancel)
} else {
return CreateElicitation.Result(action: .decline)
}

case .url(let url):
// Direct the user to an external URL (e.g., for OAuth)
openURL(url.url)
return CreateElicitation.Result(action: .accept)
}
}


启发的常见用例:

- **认证**:在需要时申请证书,而不是预先申请
- **确认**:在进行敏感操作之前,请获得用户批准
- **配置**:在操作过程中收集偏好或设置
- **遗漏信息**:请求最初未提供的其他详细信息

### 根

根定义了客户端向服务器公开的文件系统边界。服务器通过发送 `roots/list` 向客户提出请求;当列表更改时,客户端会通知服务器。

> \[!提示\]
> 要使用根,请声明 `roots` 创建客户端时的能力。```swift
let client = Client(
name: "MyApp",
version: "1.0.0",
capabilities: .init(
roots: .init(listChanged: true)
)
)

// Register a handler for roots/list requests from servers
await client.withRootsHandler {
return [
Root(uri: "file:///Users/user/projects", name: "Projects"),
Root(uri: "file:///Users/user/documents", name: "Documents")
]
}

// Notify connected servers whenever roots change
try await client.notifyRootsChanged()

日志记录

客户端可以控制服务器日志级别并接收结构化日志消息:```swift
// Set the minimum logging level
try await client.setLoggingLevel(.warning)

// Register a handler for log messages from the server
await client.onNotification(LogMessageNotification.self) { message in
let level = message.params.level // LogLevel (debug, info, warning, etc.)
let logger = message.params.logger // Optional logger name
let data = message.params.data // Arbitrary JSON data

// Display log message based on level
switch level {
case .error, .critical, .alert, .emergency:
print("❌ [(logger ?? "server")] (data)")
case .warning:
print("⚠️ [(logger ?? "server")] (data)")
default:
print("ℹ️ [(logger ?? "server")] (data)")
}
}


日志级别遵循标准系统日志严重性级别(RFC 5424):

- **调试**:详细的调试信息
- **信息**:一般信息性消息
- **通知**:正常但重要的事件
- **警告**:警告条件
- **错误**:错误条件
- **关键的**:临界条件
- **警报**:必须立即采取行动
- **紧急情况**:系统不可用

### 错误处理

处理常见的客户端错误:```swift
do {
try await client.connect(transport: transport)
// Success
} catch let error as MCPError {
print("MCP Error: \(error.localizedDescription)")
} catch {
print("Unexpected error: \(error)")
}

取消

任何一方都可以取消正在进行的请求,并优雅地处理传入的取消:

选项1:具有请求上下文过载的便利方法

对于工具调用等常见操作,使用重载方法返回 RequestContext:```swift
// Call a tool and get a context for cancellation
let context = try client.callTool(
name: "long-running-analysis",
arguments: ["data": largeDataset]
)

// You can cancel the request at any time
try await client.cancelRequest(context.requestID, reason: "User cancelled")

// Await the result (will throw CancellationError if cancelled)
do {
let result = try await context.value
print("Result: (result.content)")
} catch is CancellationError {
print("Request was cancelled")
}


#### 选项2:直接发送()以获得最大的灵活性

对于完全控制或自定义请求,请使用 `send()` 直接:```swift
// Create any request type
let request = CallTool.request(.init(
name: "long-running-analysis",
arguments: ["data": largeDataset]
))

// Send and get a context for cancellation tracking
let context: RequestContext = try client.send(request)

// Cancel when needed
try await client.cancelRequest(context.requestID, reason: "Timeout")

// Get the result
let result = try await context.value
let content = result.content
let isError = result.isError

进度跟踪

客户端可以将进度令牌附加到请求中,并接收长时间运行的操作的增量进度更新:```swift
// Call a tool with progress tracking
let progressToken = ProgressToken.unique()

// Register a notification handler to receive progress updates
await client.onNotification(ProgressNotification.self) { message in
let params = message.params
// Filter by your progress token
if params.progressToken == progressToken {
print("Progress: (params.progress)/(params.total ?? 0)")
if let message = params.message {
print("Status: (message)")
}
}
}

// Make the request with the progress token
let (content, isError) = try await client.callTool(
name: "long-running-tool",
arguments: ["input": "value"],
meta: Metadata(progressToken: progressToken)
)


### 高级客户端功能

#### 严格配置与非严格配置

配置客户端行为以进行能力检查:```swift
// Strict configuration - fail fast if a capability is missing
let strictClient = Client(
name: "StrictClient",
version: "1.0.0",
configuration: .strict
)

// With strict configuration, calling a method for an unsupported capability
// will throw an error immediately without sending a request
do {
// This will throw an error if resources.list capability is not available
let resources = try await strictClient.listResources()
} catch let error as MCPError {
print("Capability not available: \(error.localizedDescription)")
}

// Default (non-strict) configuration - attempt the request anyway
let client = Client(
name: "FlexibleClient",
version: "1.0.0",
configuration: .default
)

// With default configuration, the client will attempt the request
// even if the capability wasn't advertised by the server
do {
let resources = try await client.listResources()
} catch let error as MCPError {
// Still handle the error if the server rejects the request
print("Server rejected request: \(error.localizedDescription)")
}

请求批处理

通过在单个批中发送多个请求来提高性能:```swift
// Array to hold tool call tasks
var toolTasks: [Task] = []

// Send a batch of requests
try await client.withBatch { batch in
// Add multiple tool calls to the batch
for i in 0..<10 {
toolTasks.append(
try await batch.addRequest(
CallTool.request(.init(name: "square", arguments: ["n": Value(i)]))
)
)
}
}

// Process results after the batch is sent
print("Processing (toolTasks.count) tool results...")
for (index, task) in toolTasks.enumerated() {
do {
let result = try await task.value
print("(index): (result.content)")
} catch {
print("(index) failed: (error)")
}
}


您还可以批量处理不同类型的请求:```swift
// Declare task variables
var pingTask: Task?
var promptTask: Task?

// Send a batch with different request types
try await client.withBatch { batch in
pingTask = try await batch.addRequest(Ping.request())
promptTask = try await batch.addRequest(
GetPrompt.request(.init(name: &quot;greeting&quot;))
)
}

// Process individual results
do {
if let pingTask = pingTask {
try await pingTask.value
print(&quot;Ping successful&quot;)
}

if let promptTask = promptTask {
let promptResult = try await promptTask.value
print(&quot;Prompt: \(promptResult.description ?? &quot;None&quot;)&quot;)
}
} catch {
print(&quot;Error processing batch results: \(error)&quot;)
}

> [!注意]
> Server 自动处理来自MCP客户端的批处理请求。

服务器使用情况

服务器组件允许您的应用程序承载模型功能并响应客户端请求。

基本服务器设置```swift

import MCP

// Create a server with given capabilities
let server = Server(
name: "MyModelServer",
version: "1.0.0",
capabilities: .init(
completions: .init(),
logging: .init(),
prompts: .init(listChanged: true),
resources: .init(subscribe: true, listChanged: true),
tools: .init(listChanged: true)
)
)

// Create transport and start server
let transport = StdioTransport()
try await server.start(transport: transport)

// Now register handlers for the capabilities you've enabled


### 工具

注册工具处理程序以响应客户端工具调用:```swift
// Register a tool list handler
await server.withMethodHandler(ListTools.self) { _ in
let tools = [
Tool(
name: &quot;weather&quot;,
description: &quot;Get current weather for a location&quot;,
inputSchema: .object([
&quot;properties&quot;: .object([
&quot;location&quot;: .string(&quot;City name or coordinates&quot;),
&quot;units&quot;: .string(&quot;Units of measurement, e.g., metric, imperial&quot;)
])
])
),
Tool(
name: &quot;calculator&quot;,
description: &quot;Perform calculations&quot;,
inputSchema: .object([
&quot;properties&quot;: .object([
&quot;expression&quot;: .string(&quot;Mathematical expression to evaluate&quot;)
])
])
)
]
return .init(tools: tools)
}

// Register a tool call handler
await server.withMethodHandler(CallTool.self) { params in
switch params.name {
case &quot;weather&quot;:
let location = params.arguments?[&quot;location&quot;]?.stringValue ?? &quot;Unknown&quot;
let units = params.arguments?[&quot;units&quot;]?.stringValue ?? &quot;metric&quot;
let weatherData = getWeatherData(location: location, units: units) // Your implementation
return .init(
content: [.text(&quot;Weather for \(location): \(weatherData.temperature)°, \(weatherData.conditions)&quot;)],
isError: false
)

case &quot;calculator&quot;:
if let expression = params.arguments?[&quot;expression&quot;]?.stringValue {
let result = evaluateExpression(expression) // Your implementation
return .init(content: [.text(&quot;\(result)&quot;)], isError: false)
} else {
return .init(content: [.text(&quot;Missing expression parameter&quot;)], isError: true)
}

default:
return .init(content: [.text(&quot;Unknown tool&quot;)], isError: true)
}
}

资源

实现数据访问的资源处理程序:```swift
// Register a resource list handler
await server.withMethodHandler(ListResources.self) { params in
let resources = [
Resource(
name: "Knowledge Base Articles",
uri: "resource://knowledge-base/articles",
description: "Collection of support articles and documentation"
),
Resource(
name: "System Status",
uri: "resource://system/status",
description: "Current system operational status"
)
]
return .init(resources: resources, nextCursor: nil)
}

// Register a resource read handler
await server.withMethodHandler(ReadResource.self) { params in
switch params.uri {
case "resource://knowledge-base/articles":
return .init(contents: [Resource.Content.text("# Knowledge Base\n\nThis is the content of the knowledge base...", uri: params.uri)])

case "resource://system/status":
let status = getCurrentSystemStatus() // Your implementation
let statusJson = """
{
"status": "(status.overall)",
"components": {
"database": "(status.database)",
"api": "(status.api)",
"model": "(status.model)"
},
"lastUpdated": "(status.timestamp)"
}
"""
return .init(contents: [Resource.Content.text(statusJson, uri: params.uri, mimeType: "application/json")])

default:
throw MCPError.invalidParams("Unknown resource URI: (params.uri)")
}
}

// Register a resource subscribe handler
await server.withMethodHandler(ResourceSubscribe.self) { params in
// Store subscription for later notifications.
// Client identity for multi-client scenarios needs to be managed by the server application,
// potentially using information from the initialize handshake if the server handles one client post-init.
// addSubscription(clientID: / some_client_identifier /, uri: params.uri)
print("Client subscribed to (params.uri). Server needs to implement logic to track this subscription.")
return .init()
}


### 提示

实现提示处理程序:```swift
// Register a prompt list handler
await server.withMethodHandler(ListPrompts.self) { params in
let prompts = [
Prompt(
name: &quot;interview&quot;,
description: &quot;Job interview conversation starter&quot;,
arguments: [
.init(name: &quot;position&quot;, description: &quot;Job position&quot;, required: true),
.init(name: &quot;company&quot;, description: &quot;Company name&quot;, required: true),
.init(name: &quot;interviewee&quot;, description: &quot;Candidate name&quot;)
]
),
Prompt(
name: &quot;customer-support&quot;,
description: &quot;Customer support conversation starter&quot;,
arguments: [
.init(name: &quot;issue&quot;, description: &quot;Customer issue&quot;, required: true),
.init(name: &quot;product&quot;, description: &quot;Product name&quot;, required: true)
]
)
]
return .init(prompts: prompts, nextCursor: nil)
}

// Register a prompt get handler
await server.withMethodHandler(GetPrompt.self) { params in
switch params.name {
case &quot;interview&quot;:
let position = params.arguments?[&quot;position&quot;]?.stringValue ?? &quot;Software Engineer&quot;
let company = params.arguments?[&quot;company&quot;]?.stringValue ?? &quot;Acme Corp&quot;
let interviewee = params.arguments?[&quot;interviewee&quot;]?.stringValue ?? &quot;Candidate&quot;

let description = &quot;Job interview for \(position) position at \(company)&quot;
let messages: [Prompt.Message] = [
.user(.text(text: &quot;You are an interviewer for the \(position) position at \(company).&quot;)),
.user(.text(text: &quot;Hello, I&#x27;m \(interviewee) and I&#x27;m here for the \(position) interview.&quot;)),
.assistant(.text(text: &quot;Hi \(interviewee), welcome to \(company)! I&#x27;d like to start by asking about your background and experience.&quot;))
]

return .init(description: description, messages: messages)

case &quot;customer-support&quot;:
// Similar implementation for customer support prompt

default:
throw MCPError.invalidParams(&quot;Unknown prompt name: \(params.name)&quot;)
}
}

补全

服务器可以为提示和资源模板参数提供自动补全建议:```swift
// Enable completions capability
let server = Server(
name: "MyServer",
version: "1.0.0",
capabilities: .init(
completions: .init(),
prompts: .init(listChanged: true)
)
)

// Register a completion handler
await server.withMethodHandler(Complete.self) { params in
// Get the argument being completed
let argumentName = params.argument.name
let currentValue = params.argument.value

// Check which prompt or resource is being completed
switch params.ref {
case .prompt(let promptRef):
// Provide completions for a prompt argument
if promptRef.name == "code_review" && argumentName == "language" {
// Simple prefix matching
let allLanguages = ["python", "perl", "php", "javascript", "java", "swift"]
let matches = allLanguages.filter { $0.hasPrefix(currentValue.lowercased()) }

return .init(
completion: .init(
values: Array(matches.prefix(100)), // Max 100 items
total: matches.count,
hasMore: matches.count > 100
)
)
}

case .resource(let resourceRef):
// Provide completions for a resource template argument
if resourceRef.uri == "file:///{path}" && argumentName == "path" {
// Return directory suggestions
let suggestions = try getDirectoryCompletions(for: currentValue)
return .init(
completion: .init(
values: suggestions,
total: suggestions.count,
hasMore: false
)
)
}
}

// No completions available
return .init(completion: .init(values: [], total: 0, hasMore: false))
}


您还可以使用已解析参数的上下文:```swift
await server.withMethodHandler(Complete.self) { params in
// Access context from previous argument completions
if let context = params.context,
let language = context.arguments[&quot;language&quot;]?.stringValue {

// Provide framework suggestions based on selected language
if language == &quot;python&quot; {
let frameworks = [&quot;flask&quot;, &quot;django&quot;, &quot;fastapi&quot;, &quot;tornado&quot;]
let matches = frameworks.filter {
$0.hasPrefix(params.argument.value.lowercased())
}
return .init(
completion: .init(values: matches, total: matches.count, hasMore: false)
)
}
}

return .init(completion: .init(values: [], total: 0, hasMore: false))
}

采样

服务器可以通过采样向客户端请求LLM完成。这使得代理行为成为可能,服务器可以在保持人工监督的同时请求人工智能的帮助。```swift
// Enable sampling capability in server
let server = Server(
name: "MyModelServer",
version: "1.0.0",
capabilities: .init(
sampling: .init(), // Enable sampling capability
tools: .init(listChanged: true)
)
)

// Request sampling from the connected client
do {
let result = try await server.requestSampling(
messages: [
.user("Analyze this data and suggest next steps")
],
systemPrompt: "You are a helpful data analyst",
temperature: 0.7,
maxTokens: 150
)

// Use the LLM completion in your server logic
print("LLM suggested: (result.content)")

} catch {
print("Sampling request failed: (error)")
}


采样支持强大的代理工作流程:

- **决策**:要求法学硕士在选项之间做出选择
- **内容生成**:请求草稿供用户批准
- **数据分析**:获取复杂数据的人工智能见解
- **多步推理**:通过工具调用实现链式AI完成

### 精英

服务器可以通过启发向用户请求信息:```swift
// Ask the user to provide some additional information
let schema = Elicitation.RequestSchema(
title: &quot;Additional Information Required&quot;,
description: &quot;Please provide the following details to continue&quot;,
properties: [
&quot;name&quot;: .object([
&quot;type&quot;: .string(&quot;string&quot;),
&quot;description&quot;: .string(&quot;Your full name&quot;)
]),
&quot;confirmed&quot;: .object([
&quot;type&quot;: .string(&quot;boolean&quot;),
&quot;description&quot;: .string(&quot;Do you confirm the provided information?&quot;)
])
],
required: [&quot;name&quot;, &quot;confirmed&quot;]
)

let result = try await server.requestElicitation(
message: &quot;Some details are needed before proceeding&quot;,
requestedSchema: schema
)

switch result.action {
case .accept:
if let content = result.content {
let name = content[&quot;name&quot;]?.stringValue
let confirmed = content[&quot;confirmed&quot;]?.boolValue
// Use the collected data...
}
case .decline:
throw MCPError.invalidRequest(&quot;User declined to provide information&quot;)
case .cancel:
throw MCPError.invalidRequest(&quot;Operation canceled by user&quot;)
}

对于基于URL的启发(例如OAuth流),使用URL重载:```swift
let result = try await server.requestElicitation(
message: "Please sign in to continue",
url: "https://example.com/oauth/authorize?client_id=...",
elicitationId: UUID().uuidString
)


### 根

服务器可以请求客户端公开的文件系统根列表:```swift
// Request roots from the connected client
// (requires the client to declare the roots capability)
let roots = try await server.listRoots()
for root in roots {
print(&quot;Root: \(root.name ?? root.uri) at \(root.uri)&quot;)
}

// React to root list changes
await server.onNotification(RootsListChangedNotification.self) { _ in
let updatedRoots = try await server.listRoots()
print(&quot;Roots updated: \(updatedRoots.map { $0.uri })&quot;)
}

日志记录

服务器可以向客户端发送结构化日志消息:```swift
// Enable logging capability
let server = Server(
name: "MyServer",
version: "1.0.0",
capabilities: .init(
logging: .init(),
tools: .init(listChanged: true)
)
)

// Send log messages at different severity levels
try await server.log(
level: .info,
logger: "database",
data: Value.object([
"message": .string("Database connected successfully"),
"host": .string("localhost"),
"port": .int(5432)
])
)

try await server.log(
level: .error,
logger: "api",
data: Value.object([
"message": .string("Request failed"),
"statusCode": .int(500),
"error": .string("Internal server error")
])
)

// You can also use codable types directly
struct ErrorLog: Codable {
let message: String
let code: Int
let timestamp: String
}

let errorLog = ErrorLog(
message: "Operation failed",
code: 500,
timestamp: ISO8601DateFormatter().string(from: Date())
)

try await server.log(level: .error, logger: "operations", data: errorLog)


客户端可以控制接收哪些日志级别:```swift
// Register a handler for client&#x27;s logging level preferences
await server.withMethodHandler(SetLoggingLevel.self) { params in
let minimumLevel = params.level

// Store the client&#x27;s preference and filter log messages accordingly
// (Implementation depends on your server architecture)
storeLogLevel(minimumLevel)

return Empty()
}

进度跟踪

服务器可以在长时间运行的工具调用期间通过读取 progressToken 从请求元数据和发送 ProgressNotification 信息:```swift
await server.withMethodHandler(CallTool.self) { params in
// Read the progress token from request metadata
guard let token = params._meta?.progressToken else {
// No progress token provided — run without reporting progress
return .init(content: [.text("Done")], isError: false)
}

// Report initial progress
let started = ProgressNotification.message(
.init(progressToken: token, progress: 0, total: 100)
)
try await server.notify(started)

// ... do work ...

// Report intermediate progress
let halfway = ProgressNotification.message(
.init(progressToken: token, progress: 50, total: 100, message: "Halfway there")
)
try await server.notify(halfway)

// ... do more work ...

// Report completion
let done = ProgressNotification.message(
.init(progressToken: token, progress: 100, total: 100, message: "Complete")
)
try await server.notify(done)

return .init(content: [.text("Done")], isError: false)
}


#### 初始化钩子

使用初始化挂钩控制客户端连接:```swift
// Start the server with an initialize hook
try await server.start(transport: transport) { clientInfo, clientCapabilities in
// Validate client info
guard clientInfo.name != &quot;BlockedClient&quot; else {
throw MCPError.invalidRequest(&quot;This client is not allowed&quot;)
}

// You can also inspect client capabilities
if clientCapabilities.sampling == nil {
print(&quot;Client does not support sampling&quot;)
}

// Perform any server-side setup based on client info
print(&quot;Client \(clientInfo.name) v\(clientInfo.version) connected&quot;)

// If the hook completes without throwing, initialization succeeds
}

处理程序中的HTTP请求上下文

当服务器通过以下方式连接时 StatefulHTTPServerTransport 或 StatelessHTTPServerTransport,
方法处理程序可以通过以下方式观察发起的HTTP请求(标头、正文、路径、方法)
Server.currentHandlerContext --在每个处理程序运行之前自动设置的任务本地集:```swift
await server.withMethodHandler(CallTool.self) { params in
let httpRequest = Server.currentHandlerContext?.httpContext
let authHeader = httpRequest?.headers["Authorization"]
// …use the header to scope the response, audit, etc.
return .init(content: [.text("ok")], isError: false)
}


`httpContext` 是 `nil` 对于不携带HTTP上下文的传输(例如。 `StdioTransport`,
`InMemoryTransport`)而处理程序则脱离了调度路径。

任务本地人不会被继承 `Task.detached`。如果从处理程序生成分离任务,
预先捕捉上下文:```swift
let ctx = Server.currentHandlerContext
Task.detached { await doWork(with: ctx?.httpContext) }

自定义HTTP传输可以通过符合以下条件来选择加入 HTTPContextProviding 并返回
HTTPRequest 对于在飞行中的给定JSON-RPC id。

优雅地关闭

我们建议使用
Swift服务生命周期
用于管理服务的启动和关闭。

首先,将依赖关系添加到您的 Package.swift:```swift
.package(url: "https://github.com/swift-server/swift-service-lifecycle.git", from: "2.3.0"),


然后将MCP服务器实现为 `Service`:```swift
import MCP
import ServiceLifecycle
import Logging

struct MCPService: Service {
let server: Server
let transport: Transport

init(server: Server, transport: Transport) {
self.server = server
self.transport = transport
}

func run() async throws {
// Start the server
try await server.start(transport: transport)

// Keep running until external cancellation
try await Task.sleep(for: .days(365 * 100))  // Effectively forever
}

func shutdown() async throws {
// Gracefully shutdown the server
await server.stop()
}
}

然后在您的应用程序中使用它:```swift
import MCP
import ServiceLifecycle
import Logging

let logger = Logger(label: "com.example.mcp-server")

// Create the MCP server
let server = Server(
name: "MyModelServer",
version: "1.0.0",
capabilities: .init(
prompts: .init(listChanged: true),
resources: .init(subscribe: true, listChanged: true),
tools: .init(listChanged: true)
)
)

// Add handlers directly to the server
await server.withMethodHandler(ListTools.self) { _ in
// Your implementation
return .init(tools: [
Tool(name: "example", description: "An example tool")
])
}

await server.withMethodHandler(CallTool.self) { params in
// Your implementation
return .init(content: [.text("Tool result")], isError: false)
}

// Create MCP service and other services
let transport = StdioTransport(logger: logger)
let mcpService = MCPService(server: server, transport: transport)
let databaseService = DatabaseService() // Your other services

// Create service group with signal handling
let serviceGroup = ServiceGroup(
services: [mcpService, databaseService],
configuration: .init(
gracefulShutdownSignals: [.sigterm, .sigint]
),
logger: logger
)

// Run the service group - this blocks until shutdown
try await serviceGroup.run()
```

这种方法有几个好处:

  • 信号处理:
    自动捕获信号情报、信号终端并触发优雅关机
  • 平滑关闭:
    正确关闭MCP服务器和其他服务
  • 基于超时的关机:
    可配置的关机超时,以防止挂起进程
  • 高级服务管理:
    ServiceLifecycle
    还支持服务依赖性、条件服务等,
    以及其他有用的功能。

运输

MCP的传输层处理客户端和服务器之间的通信。
Swift SDK提供了多种内置传输:

交通 描述 平台 最适合
StdioTransport 机具 stdio传输 使用标准输入/输出流 苹果平台、带glibc的Linux 本地子流程、CLI工具

…(正文过长,页面只展示前面部分,完整内容见仓库)

常见问题

6 问
答案由本站依据条目字段整理,不引用上游原文
Swift SDK 怎么安装?

资料没有给出安装命令,请到官方仓库或文档按说明接入;这类条目多数是生态应用,或尚未发布可安装包。

Swift SDK 怎么在 Cursor 里配置?

它的传输方式未标注,在客户端的 MCP 配置里填好启动命令和参数,保存后完全退出客户端再打开,配置才会生效。

Swift SDK 收费吗?

本站不代收费用,也没有标注具体价格。是否收费取决于服务本身和背后的接口额度,正式使用前按官方说明确认。

Swift SDK 需要 API Key 吗?

资料标注需要OAuth 授权认证,使用前准备好对应凭据,并按最小权限配置。

Swift SDK 支持哪些客户端?

资料标注支持 Cursor;其他客户端只要能配置 MCP Server,也能用同样的命令或地址接入。

Swift SDK 能提供哪些能力?

资料显示约 2 个工具;能力标签包括 Swift、标准化协议、机器学习、Cursor。具体工具清单以官方文档为准。

热门专题

按标签挑服务器
全部专题 →

服务器信息以作者仓库与官方文档为准;分类、传输方式与鉴权方式的中文说明为中文整理,最近核验 2026-05-17。