Token导航 LogoToken导航TokenDH.com
Swift Fast MCP logo
AI代理未说明官方级别未说明来源级核验

Swift Fast MCP

MCP Server

FastMCP是一个用于快速构建MCP服务器的Swift工具,支持多种传输方式和工具集成。

工具数

3

提示词数

0

GitHub Stars

8

资源数

0
Swift服务器构建HTTP传输ClaudeClaude DesktopClaude

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

mehmetbaykar

提供方

mehmetbaykar

最后核验

2026/5/17 20:20

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

详细介绍

FastMCP

在Swift中构建MCP服务器的最快方法。

If you found this helpful, you can support more open source work!

______________________________________________________________________

try await FastMCP.builder()
    .name("My Server")
    .addTools([WeatherTool()])
    .run()

通过stdio连接到工作的MCP服务器的三条线路。或者通过HTTP服务:

try await FastMCP.builder()
    .name("My Server")
    .addTools([WeatherTool()])
    .transport(.http(port: 8080))
    .run()

或者从另一个Streamable HTTP MCP服务器聚合工具并公开它们 在您本地的Swift工具旁边:

try await FastMCP.builder()
    .name("Gateway")
    .addTools([WeatherTool()])
    .addUpstreamMCPServers([
        .streamableHTTP(
            name: "firecrawl",
            endpoint: URL(string: "https://mcp.firecrawl.dev/v2/mcp")!,
            headers: ["Authorization": "Bearer "]
        )
    ])
    .run()

安装

添加到您的 Package.swift:

dependencies: [
    .package(url: "https://github.com/mehmetbaykar/swift-fast-mcp", from: "2.7.0")
]

然后添加 "FastMCP" 作为目标的依赖:

.target(
    name: "MyServer",
    dependencies: [
        .product(name: "FastMCP", package: "swift-fast-mcp")
    ]
)

FastMCP会自动引入这些依赖关系:

FastMCPAIBridge 故意公开并通过以下方式再出口 FastMCP 为了 高级桥接测试和自定义适配器使用。大多数应用程序仍应 更喜欢构建器API。

快速开始

标准传输(默认)

import FastMCP

@Tool("Get weather for a location")
struct WeatherTool {
    @Parameter("City or coordinates")
    var location: String = ""

    func execute() async throws -> String {
        "Weather in \(location): 22°C, Sunny"
    }
}

@main
struct MyServer {
    static func main() async throws {
        try await FastMCP.builder()
            .name("Weather Server")
            .addTools([WeatherTool()])
            .run()
    }
}

通过添加将其连接到Claude Desktop claude_desktop_config.json:

{
    "mcpServers": {
        "weather": {
            "command": "/path/to/my-server"
        }
    }
}

HTTP传输

@main
struct MyServer {
    static func main() async throws {
        try await FastMCP.builder()
            .name("Weather Server")
            .addTools([WeatherTool()])
            .transport(.http(port: 8080))
            .run()
        // Listening on http://127.0.0.1:8080/mcp
    }
}

交通方式

public enum Transport: Sendable {
    case stdio
    case inMemory
    case http(
        mode: HTTPMode = .stateful,
        host: String = "127.0.0.1",
        port: Int = 3000,
        endpoint: String = "/mcp"
    )
    case custom(MCP.Transport)
}
运输用例
.stdioClaude Desktop,CLI工具。违约。
.inMemory单元测试。
.http(...)远程服务器、多客户端访问、web部署。
.custom(transport)提供您自己的 MCP.Transport 实施。

Http模式

public enum HTTPMode: Sendable {
    case stateful
    case stateless
}

有状态的 (默认)--完全MCP流式HTTP。每个客户端都可以通过以下方式获得与SSE流的会话,并可恢复 Last-Event-IDGET表示服务器发起的消息,DELETE表示会话终止。

无状态 --最小HTTP。无会话,直接JSON响应,仅POST。当会话管理由外部处理或不需要时使用。

// Stateful (default)
.transport(.http(port: 8080))
.transport(.http(mode: .stateful, host: "0.0.0.0", port: 3000, endpoint: "/mcp"))

// Stateless
.transport(.http(mode: .stateless, port: 8080))

生成器API

所有生成器方法都返回一个新的 Builder (值语义),并且可以被链接。

服务器元数据

.name("My Server")               // Server name (default: process name)
.version("2.7.0")                // Server version (default: "1.0.0")
.title("My Display Name")        // Human-readable display name for UIs
.instructions("Use this server to...") // Instructions for LLM clients
.icons([...])                     // Server icons for display in UIs

能力

try FastMCP.builder()
    .addTools([WeatherTool(), MathTool(), StructuredSearchTool()])   // Register tool implementations
    .addUpstreamMCPServers([                  // Proxy Streamable HTTP upstream tools as docs_*
        .streamableHTTP(name: "docs", endpoint: docsMCPURL)
    ])
    .addResources([ConfigResource()])         // Register resource implementations
    .addPrompts([GreetingPrompt()])           // Register prompt implementations
    .enableCompletions()                      // Advertise completions capability
    .enableLogging()                          // Advertise logging capability

重复的上游服务器名称和工具名称会提前失败。资源和提示 自动进行重复数据消除;第一次注册获胜。

延迟的SwiftAIHub工具源代码异步解析,因此 addTools(_:) 是 也可作为 async throws 建筑商电话:

import FastMCP

try await FastMCP.builder()
    .addTools(localOrDeferredToolSource)
    .run()

使用 addUpstreamMCPServers(...) 当您希望FastMCP充当MCP网关时 用于远程MCP工具,同时保留其MCP描述符和调用结果。

交通和基础设施

.transport(.stdio)                       // Transport selection (default: .stdio)
.logger(myLogger)                        // Custom swift-log Logger
.shutdownSignals([.sigterm, .sigint])    // Unix signals for graceful shutdown (default: both)

生命周期挂钩

在...之下 .stdio (默认),stdout携带JSON-RPC帧——不要使用 print 在钩子。通过注入的路由消息 Logger 相反(swift日志的默认处理程序会写入stderr)。在...之下 .http,任何一种方法都是安全的。

.onStart { logger.info("Server started") }
.onShutdown { logger.info("Server stopped") }
.onInitialize { clientInfo, capabilities in
    // Called when a client sends an initialize request.
    // Receives Client.Info and Client.Capabilities.
    // Useful for auth checks, logging, per-client setup.
    // Especially valuable for HTTP where multiple clients connect.
    logger.info("Client: \(clientInfo.name) v\(clientInfo.version)")
}

HTTP特定配置

.sessionTimeout(.seconds(1800))          // Idle session timeout (default: 3600s)
                                          // Only applies to .http with .stateful mode.

.httpValidation(
    allowedOrigins: ["https://example.com"],  // Allowed Origin headers (default: localhost only)
    customValidators: [MyAuthValidator()]     // Custom HTTPRequestValidator implementations
)

跑步

.run()  // Starts the server and blocks until shutdown

HTTP传输

多会话模型

在有状态HTTP模式下,每个连接的客户端都有自己独立的 Server + Transport 一对。服务器自动管理会话生命周期。

会话生命周期(有状态模式)

  1. 客户端向发送POST /mcp 带着一个 initialize JSON-RPC请求(无会话头)。
  2. 服务器创建新 StatefulHTTPServerTransport + Server 配对,注册所有工具/资源/提示。
  3. 传输生成会话ID,并在 Mcp-Session-Id 响应标头。
  4. 后续请求包含此标头,并被路由到匹配的会话。
  5. 客户端发送DELETE以终止会话。
  6. 清理循环每60秒运行一次,删除空闲时间超过 sessionTimeout.

无状态模式

  1. 客户端向发送POST /mcp 通过JSON-RPC请求。
  2. 服务器直接使用JSON进行响应。没有SSE,没有会话头,没有会话跟踪。

验证流程

HTTP服务器在处理之前验证传入的请求。默认情况下,只允许使用localhost源。

要允许远程来源或添加自定义验证(例如,承载令牌身份验证),请使用 .httpValidation():

.httpValidation(
    allowedOrigins: ["https://myapp.com", "https://staging.myapp.com"],
    customValidators: [BearerTokenValidator(expectedToken: "...")]
)

自定义验证器符合 HTTPRequestValidator 来自MCP SDK。

传输层安全

FastMCP不处理TLS。部署在HTTPS的反向代理(nginx、Caddy)后面。

工具

AI可调用函数,具有从任一平面生成的JSON模式 @Parameter 存储属性+ execute(),或嵌套 @Generable Arguments 结构 加 execute(_:)该工具的名称来源于结构体名称 (MathToolmath)以及它从body返回的类型 execute:

@Generable
enum Operation: String, CaseIterable {
    case add, subtract, multiply, divide
}

@Tool("Perform math operations")
struct MathTool {
    @Generable
    struct Arguments {
        @Parameter("Operation") var operation: Operation
        @Parameter("First operand") var a: Double
        @Parameter("Second operand") var b: Double
    }

    func execute(_ arguments: Arguments) async throws -> String {
        let result = switch arguments.operation {
        case .add: arguments.a + arguments.b
        case .subtract: arguments.a - arguments.b
        case .multiply: arguments.a * arguments.b
        case .divide: arguments.a / arguments.b
        }
        return "Result: \(result)"
    }
}

资源

将数据暴露给AI模型:

@MCPResource(
    "config://app/settings",
    name: "App Settings",
    description: "Application configuration",
    mimeType: .applicationJSON
)
struct ConfigResource {
    @ResourceContentBuilder
    var content: Content {
        """
        {"theme": "dark", "version": "1.0.0"}
        """
    }
}

提示

带有键入参数的可重用对话模板 @PromptArgument:

@MCPPrompt("A greeting template")
struct GreetingPrompt {
    @PromptArgument("Who to greet")
    var name: String

    @PromptArgument("Use formal tone")
    var formal: Bool = false

    func getMessages() async throws -> Messages {
        if formal {
            return [
                .user("You are a formal assistant helping \(name)."),
                .assistant("Good day, \(name). How may I assist you?"),
            ]
        } else {
            return [
                .user("You are a friendly assistant helping \(name)."),
                .assistant("Hey \(name)! What can I help you with?"),
            ]
        }
    }
}

完整示例

一个完整的stdio服务器,包括工具、资源、提示和生命周期挂钩——Claude Desktop和CLI客户端的规范MCP设置,将服务器作为子进程生成。这与发货中使用的stdio传输/生命周期模式相匹配 Sources/Example/ExampleServer.swift (它连接了自己的工具和元数据)。对于HTTP特定的变体( .httpValidation, .sessionTimeout等),请参阅 HTTP传输 上面的部分。

import FastMCP
import Logging

@main
struct ExampleServer {
    static func main() async throws {
        let logger: Logger = {
            var log = Logger(label: "my-server")
            log.logLevel = .info
            return log
        }()

        try await FastMCP.builder()
            .name("Example Server")
            .title("Example MCP Server")
            .version("2.7.0")
            .instructions("This server provides weather, math, and structured search tools.")

            .addTools([WeatherTool(), MathTool(), StructuredSearchTool()])
            .addResources([ConfigResource()])
            .addPrompts([GreetingPrompt()])

            .enableCompletions()
            .enableLogging()

            .transport(.stdio)

            .logger(logger)
            .shutdownSignals([.sigterm, .sigint])

            // Stdio owns stdout for JSON-RPC framing — route lifecycle messages
            // through `logger` (stderr) so `print` never corrupts the wire.
            .onInitialize { clientInfo, _ in
                logger.info("Client connected: \(clientInfo.name) v\(clientInfo.version)")
            }
            .onStart {
                logger.info("Server started on stdio")
            }
            .onShutdown {
                logger.info("Server shutting down")
            }

            .run()
    }
}

平台支持

  • macOS 14+
  • Linux(通过 #if canImport(FoundationNetworking) 警卫)
  • Swift 6.2+

Claude代码集成

FastMCP配备 Claude代码技能 和一个 子代理 让Claude Code为您搭建和构建MCP服务器项目。

设置

复制 skills/.claude/ 项目中的目录:

# Copy the skill (project scaffolding)
cp -r skills/ .claude/skills/

# Copy the agent (expert assistance)
cp -r .claude/agents/ .claude/agents/

用法

搭建一个新项目 凭借技能:

/swift-fast-mcp MyServer tools,resources,prompts

Claude使用Package.swift、键入的工具/资源/提示、测试和Claude Desktop配置生成一个完整的项目。

获得专家帮助 与子代理:

克劳德自动委托给 swift-mcp-expert 当你问起 @Tool, @MCPResource, @MCPPrompt 实现、构建器API, @Generable 例如类型或测试模式。您还可以显式调用它:

Use the swift-mcp-expert to help me build a weather tool

文档

  • docs/Tools.md --暴露 @Tool 通过MCP服务器从swift ai hub传输结构
  • docs/PromptsResources.md@MCPPrompt, @MCPResource, @PromptArgument, MCPResourceMimeType
  • docs/Transports.md --stdio、HTTP(有状态/无状态)、内存中、自定义; httpValidation;服务组生命周期
  • docs/DynamicServers.mdFastMCPServerHandle 用于在以下操作后添加/删除工具、资源和提示 run() 开始

@Tool, @Generable, @Parameter,以及 @Guide 宏来自 swift人工智能中心 --看看它 docs/Macros.md 供宏观参考。

许可证

麻省理工学院

目录标签

目录标签

Swift服务器构建HTTP传输Claude本地部署Swift开发工具集成MCP协议

支持客户端

Claude DesktopClaude

接入字段

传输方式(transport,传输协议)

未说明

鉴权方式(authType,认证方式)

token

工具数量(toolCount,工具数)

3

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

未说明token部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

仍需确认:installCommand

来源信息

继续浏览同类 MCP