AppleFoundationMCPTool
一个Swift软件包,充当苹果与苹果之间的动态桥梁 FoundationModels 框架(或 AnyLanguageModel)以及任何实现 模型上下文协议(MCP).
关于本项目的说明 该项目主要由人工智能代理开发,作为集成苹果的技术演示FoundationModels框架和模型上下文协议(MCP)。 虽然功能强大,但它应该被视为概念验证,而不是生产就绪的解决方案。目前,实际效用受到可用模型上下文大小的限制FoundationModels框架,这可能会使模型难以有效地使用具有复杂输入模式或冗长描述的工具。 切换到AnyLanguageModel修复了允许更大型号的问题
概述
随着macOS 26.0中新的设备上AI功能的引入,苹果的 FoundationModels 框架提供了一种与大型语言模型交互的强大方式。该项目通过利用开放标准的模型上下文协议,使新框架能够与更广泛的工具和服务器生态系统进行通信。
AppleFoundationMCPTool 在运行时发现MCP服务器上可用的工具,并动态创建相应的工具 FoundationModels.Tool 物体。这允许LLM在 FoundationModels 会话查看和执行外部工具,而无需在编译时知道它们的具体细节。
特性
- 动态工具桥接:自动发现并包装MCP工具以供使用
FoundationModels. - 柔性连接:支持通过两种方法连接到MCP服务器:
- HTTP/SSE:连接到给定URL的远程MCP服务器。 - 工作室:启动本地MCP服务器可执行文件,并通过标准输入/输出与之通信。
- 流程管理:使用stdio连接时,自动管理服务器进程的生命周期。
- 现代型&安全型:采用现代Swift并发构建(
async/await)并利用最新FoundationModelsAPI。
需求
- macOS 26.0+
- Swift 6.0+
- 符合MCP的服务器或服务器可执行文件。
用法
此库的主要入口点是 MCPToolBridge 类。
1.添加包依赖关系
将以下内容添加到您的 Package.swift 文件:
dependencies: [
.package(url: "https://github.com/your-username/AppleFoundationMCPTool.git", from: "1.0.0")
]然后将依赖关系添加到目标:
.target(
name: "YourTarget",
dependencies: [
"AppleFoundationMCPTool"
]
)2.初始化网桥
您可以初始化 MCPToolBridge 根据您的服务器设置,有两种方式之一。
选项A:连接到HTTP服务器
如果您有一个正在运行并侦听特定URL的MCP服务器,请使用此方法。
import AppleFoundationMCPTool
import Foundation
let serverURL = URL(string: "http://127.0.0.1:8000/mcp")!
let bridge = MCPToolBridge(serverURL: serverURL)选项B:启动本地可执行文件(Stdio)
使用此方法启动网桥并管理本地MCP服务器可执行文件,通过stdin/stdout与之通信。
import AppleFoundationMCPTool
let serverPath = "/path/to/your/mcp_server_executable"
let bridge = MCPToolBridge(executablePath: serverPath)3.连接和使用工具
初始化网桥后,您可以连接到服务器,发现其工具,并在 FoundationModels 会议。
import AppleFoundationMCPTool // Will also import FoundationModels or AnyLanguageModel, depending on how the Package was built
// Assuming you have a SessionManager or similar class to manage the LLM session
do {
// Connect to the server and get the dynamically created Apple Foundation tools
let tools = try await bridge.connectAndDiscoverTools()
print("Successfully discovered \(appleTools.count) tools.")
let session = LanguageModelSession(model: model, tools: tools)
// You can now use the session, and the LLM will be able to see and call the tools.
let response = try await session.prompt("Use the 'add' tool to calculate 5 + 7.")
print(response)
} catch {
print("An error occurred: \(error.localizedDescription)")
}
// Don't forget to disconnect when you're done.
// This will also terminate the server process if it was launched by the bridge.
await bridge.disconnect()示例目标
该项目包括两个可执行目标来演示其功能。
AppleFoundationMCPToolChat (推荐示例)
这是一个完全交互式的命令行聊天应用程序,演示了网桥的端到端功能。它连接到MCP服务器,注册发现的工具,并允许您与可以使用这些工具的LLM聊天。
如何跑步
- 修改
main.swift:打开Sources/AppleFoundationMCPToolChat/main.swift并配置MCPToolBridge初始化以指向您的MCP服务器(通过URL或可执行路径)。 - 从命令行运行:
swift run AppleFoundationMCPToolChatAppleFoundationMCPToolExample
此目标包含各种概念代码段。它不是一个工作示例,而更像是一个草稿栏,显示了库组件的不同使用方式。有关实用的工作演示,请参阅 AppleFoundationMCPToolChat 例子。
