Initial implementation
This commit is contained in:
parent
cc603d35fe
commit
be1e9583f8
4 changed files with 4304 additions and 884 deletions
206
Sources/MCP/Server/Prompts.swift
Normal file
206
Sources/MCP/Server/Prompts.swift
Normal file
|
|
@ -0,0 +1,206 @@
|
|||
import Foundation
|
||||
|
||||
/// The Model Context Protocol (MCP) provides a standardized way
|
||||
/// for servers to expose prompt templates to clients.
|
||||
/// Prompts allow servers to provide structured messages and instructions
|
||||
/// for interacting with language models.
|
||||
/// Clients can discover available prompts, retrieve their contents,
|
||||
/// and provide arguments to customize them.
|
||||
///
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/
|
||||
public struct Prompt: Hashable, Codable, Sendable {
|
||||
/// The prompt name
|
||||
public let name: String
|
||||
/// The prompt description
|
||||
public let description: String?
|
||||
/// The prompt arguments
|
||||
public let arguments: [Argument]?
|
||||
|
||||
public init(name: String, description: String? = nil, arguments: [Argument]? = nil) {
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.arguments = arguments
|
||||
}
|
||||
|
||||
/// An argument for a prompt
|
||||
public struct Argument: Hashable, Codable, Sendable {
|
||||
/// The argument name
|
||||
public let name: String
|
||||
/// The argument description
|
||||
public let description: String?
|
||||
/// Whether the argument is required
|
||||
public let required: Bool?
|
||||
|
||||
public init(name: String, description: String? = nil, required: Bool? = nil) {
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.required = required
|
||||
}
|
||||
}
|
||||
|
||||
/// A message in a prompt
|
||||
public struct Message: Hashable, Codable, Sendable {
|
||||
/// The message role
|
||||
public enum Role: String, Hashable, Codable, Sendable {
|
||||
/// A user message
|
||||
case user
|
||||
/// An assistant message
|
||||
case assistant
|
||||
}
|
||||
|
||||
/// The message role
|
||||
public let role: Role
|
||||
/// The message content
|
||||
public let content: Content
|
||||
|
||||
public init(role: Role, content: Content) {
|
||||
self.role = role
|
||||
self.content = content
|
||||
}
|
||||
|
||||
/// Content types for messages
|
||||
public enum Content: Hashable, Codable, Sendable {
|
||||
/// Text content
|
||||
case text(text: String)
|
||||
/// Image content
|
||||
case image(data: String, mimeType: String)
|
||||
/// Embedded resource content
|
||||
case resource(uri: String, mimeType: String, text: String?, blob: String?)
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case type, text, data, mimeType, uri, blob
|
||||
}
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
|
||||
switch self {
|
||||
case .text(let text):
|
||||
try container.encode("text", forKey: .type)
|
||||
try container.encode(text, forKey: .text)
|
||||
case .image(let data, let mimeType):
|
||||
try container.encode("image", forKey: .type)
|
||||
try container.encode(data, forKey: .data)
|
||||
try container.encode(mimeType, forKey: .mimeType)
|
||||
case .resource(let uri, let mimeType, let text, let blob):
|
||||
try container.encode("resource", forKey: .type)
|
||||
try container.encode(uri, forKey: .uri)
|
||||
try container.encode(mimeType, forKey: .mimeType)
|
||||
try container.encodeIfPresent(text, forKey: .text)
|
||||
try container.encodeIfPresent(blob, forKey: .blob)
|
||||
}
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let type = try container.decode(String.self, forKey: .type)
|
||||
|
||||
switch type {
|
||||
case "text":
|
||||
let text = try container.decode(String.self, forKey: .text)
|
||||
self = .text(text: text)
|
||||
case "image":
|
||||
let data = try container.decode(String.self, forKey: .data)
|
||||
let mimeType = try container.decode(String.self, forKey: .mimeType)
|
||||
self = .image(data: data, mimeType: mimeType)
|
||||
case "resource":
|
||||
let uri = try container.decode(String.self, forKey: .uri)
|
||||
let mimeType = try container.decode(String.self, forKey: .mimeType)
|
||||
let text = try container.decodeIfPresent(String.self, forKey: .text)
|
||||
let blob = try container.decodeIfPresent(String.self, forKey: .blob)
|
||||
self = .resource(uri: uri, mimeType: mimeType, text: text, blob: blob)
|
||||
default:
|
||||
throw DecodingError.dataCorruptedError(
|
||||
forKey: .type,
|
||||
in: container,
|
||||
debugDescription: "Unknown content type")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Reference type for prompts
|
||||
public struct Reference: Hashable, Codable, Sendable {
|
||||
/// The prompt reference name
|
||||
public let name: String
|
||||
|
||||
public init(name: String) {
|
||||
self.name = name
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case type, name
|
||||
}
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode("ref/prompt", forKey: .type)
|
||||
try container.encode(name, forKey: .name)
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
_ = try container.decode(String.self, forKey: .type)
|
||||
name = try container.decode(String.self, forKey: .name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
/// To retrieve available prompts, clients send a `prompts/list` request.
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#listing-prompts
|
||||
public enum ListPrompts: Method {
|
||||
public static let name: String = "prompts/list"
|
||||
|
||||
public struct Parameters: Hashable, Codable, Sendable {
|
||||
public let cursor: String?
|
||||
|
||||
public init(cursor: String? = nil) {
|
||||
self.cursor = cursor
|
||||
}
|
||||
}
|
||||
|
||||
public struct Result: Hashable, Codable, Sendable {
|
||||
public let prompts: [Prompt]
|
||||
public let nextCursor: String?
|
||||
|
||||
public init(prompts: [Prompt], nextCursor: String? = nil) {
|
||||
self.prompts = prompts
|
||||
self.nextCursor = nextCursor
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// To retrieve a specific prompt, clients send a `prompts/get` request.
|
||||
/// Arguments may be auto-completed through the completion API.
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#getting-a-prompt
|
||||
public enum GetPrompt: Method {
|
||||
public static let name: String = "prompts/get"
|
||||
|
||||
public struct Parameters: Hashable, Codable, Sendable {
|
||||
public let name: String
|
||||
public let arguments: [String: Value]?
|
||||
|
||||
public init(name: String, arguments: [String: Value]? = nil) {
|
||||
self.name = name
|
||||
self.arguments = arguments
|
||||
}
|
||||
}
|
||||
|
||||
public struct Result: Hashable, Codable, Sendable {
|
||||
public let description: String?
|
||||
public let messages: [Prompt.Message]
|
||||
|
||||
public init(description: String?, messages: [Prompt.Message]) {
|
||||
self.description = description
|
||||
self.messages = messages
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// When the list of available prompts changes, servers that declared the listChanged capability SHOULD send a notification.
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/prompts/#list-changed-notification
|
||||
public struct PromptListChangedNotification: Notification {
|
||||
public static let name: String = "notifications/prompts/list_changed"
|
||||
}
|
||||
195
Sources/MCP/Server/Resources.swift
Normal file
195
Sources/MCP/Server/Resources.swift
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
import Foundation
|
||||
|
||||
/// The Model Context Protocol (MCP) provides a standardized way
|
||||
/// for servers to expose resources to clients.
|
||||
/// Resources allow servers to share data that provides context to language models,
|
||||
/// such as files, database schemas, or application-specific information.
|
||||
/// Each resource is uniquely identified by a URI.
|
||||
///
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/
|
||||
public struct Resource: Hashable, Codable, Sendable {
|
||||
/// The resource name
|
||||
public var name: String
|
||||
/// The resource URI
|
||||
public var uri: String
|
||||
/// The resource description
|
||||
public var description: String?
|
||||
/// The resource MIME type
|
||||
public var mimeType: String?
|
||||
/// The resource metadata
|
||||
public var metadata: [String: String]?
|
||||
|
||||
public init(
|
||||
name: String,
|
||||
uri: String,
|
||||
description: String? = nil,
|
||||
mimeType: String? = nil,
|
||||
metadata: [String: String]? = nil
|
||||
) {
|
||||
self.name = name
|
||||
self.uri = uri
|
||||
self.description = description
|
||||
self.mimeType = mimeType
|
||||
self.metadata = metadata
|
||||
}
|
||||
|
||||
/// Content of a resource.
|
||||
public struct Content: Hashable, Codable, Sendable {
|
||||
/// The resource URI
|
||||
public let uri: String
|
||||
/// The resource MIME type
|
||||
public let mimeType: String?
|
||||
/// The resource text content
|
||||
public let text: String?
|
||||
/// The resource binary content
|
||||
public let blob: String?
|
||||
|
||||
public static func text(_ content: String, uri: String, mimeType: String? = nil) -> Self {
|
||||
.init(uri: uri, mimeType: mimeType, text: content)
|
||||
}
|
||||
|
||||
public static func binary(_ data: Data, uri: String, mimeType: String? = nil) -> Self {
|
||||
.init(uri: uri, mimeType: mimeType, blob: data.base64EncodedString())
|
||||
}
|
||||
|
||||
private init(uri: String, mimeType: String? = nil, text: String? = nil) {
|
||||
self.uri = uri
|
||||
self.mimeType = mimeType
|
||||
self.text = text
|
||||
self.blob = nil
|
||||
}
|
||||
|
||||
private init(uri: String, mimeType: String? = nil, blob: String) {
|
||||
self.uri = uri
|
||||
self.mimeType = mimeType
|
||||
self.text = nil
|
||||
self.blob = blob
|
||||
}
|
||||
}
|
||||
|
||||
/// A resource template.
|
||||
public struct Template: Hashable, Codable, Sendable {
|
||||
/// The URI template pattern
|
||||
public var uriTemplate: String
|
||||
/// The template name
|
||||
public var name: String
|
||||
/// The template description
|
||||
public var description: String?
|
||||
/// The resource MIME type
|
||||
public var mimeType: String?
|
||||
|
||||
public init(
|
||||
uriTemplate: String,
|
||||
name: String,
|
||||
description: String? = nil,
|
||||
mimeType: String? = nil
|
||||
) {
|
||||
self.uriTemplate = uriTemplate
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.mimeType = mimeType
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
/// To discover available resources, clients send a `resources/list` request.
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#listing-resources
|
||||
public enum ListResources: Method {
|
||||
public static let name: String = "resources/list"
|
||||
|
||||
public struct Parameters: Hashable, Codable, Sendable {
|
||||
public let cursor: String?
|
||||
|
||||
public init(cursor: String? = nil) {
|
||||
self.cursor = cursor
|
||||
}
|
||||
}
|
||||
|
||||
public struct Result: Hashable, Codable, Sendable {
|
||||
public let resources: [Resource]
|
||||
public let nextCursor: String?
|
||||
|
||||
public init(resources: [Resource], nextCursor: String? = nil) {
|
||||
self.resources = resources
|
||||
self.nextCursor = nextCursor
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// To retrieve resource contents, clients send a `resources/read` request:
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#reading-resources
|
||||
public enum ReadResource: Method {
|
||||
public static let name: String = "resources/read"
|
||||
|
||||
public struct Parameters: Hashable, Codable, Sendable {
|
||||
public let uri: String
|
||||
|
||||
public init(uri: String) {
|
||||
self.uri = uri
|
||||
}
|
||||
}
|
||||
|
||||
public struct Result: Hashable, Codable, Sendable {
|
||||
public let contents: [Resource.Content]
|
||||
|
||||
public init(contents: [Resource.Content]) {
|
||||
self.contents = contents
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// To discover available resource templates, clients send a `resources/templates/list` request.
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#resource-templates
|
||||
public enum ListResourceTemplates: Method {
|
||||
public static let name: String = "resources/templates/list"
|
||||
|
||||
public typealias Parameters = Empty
|
||||
|
||||
public struct Result: Hashable, Codable, Sendable {
|
||||
public let templates: [Resource.Template]
|
||||
|
||||
public init(templates: [Resource.Template]) {
|
||||
self.templates = templates
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case templates = "resourceTemplates"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// When the list of available resources changes, servers that declared the listChanged capability SHOULD send a notification.
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#list-changed-notification
|
||||
public struct ResourceListChangedNotification: Notification {
|
||||
public static let name: String = "notifications/resources/list_changed"
|
||||
|
||||
public typealias Parameters = Empty
|
||||
}
|
||||
|
||||
/// Clients can subscribe to specific resources and receive notifications when they change.
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#subscriptions
|
||||
public enum ResourceSubscribe: Method {
|
||||
public static let name: String = "resources/subscribe"
|
||||
|
||||
public struct Parameters: Hashable, Codable, Sendable {
|
||||
public let uri: String
|
||||
}
|
||||
|
||||
public typealias Result = Empty
|
||||
}
|
||||
|
||||
/// When a resource changes, servers that declared the updated capability SHOULD send a notification to subscribed clients.
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/resources/#subscriptions
|
||||
public struct ResourceUpdatedNotification: Notification {
|
||||
public static let name: String = "notifications/resources/updated"
|
||||
|
||||
public struct Parameters: Hashable, Codable, Sendable {
|
||||
public let uri: String
|
||||
|
||||
public init(uri: String) {
|
||||
self.uri = uri
|
||||
}
|
||||
}
|
||||
}
|
||||
393
Sources/MCP/Server/Server.swift
Normal file
393
Sources/MCP/Server/Server.swift
Normal file
|
|
@ -0,0 +1,393 @@
|
|||
import Logging
|
||||
import SystemPackage
|
||||
|
||||
import struct Foundation.Data
|
||||
import struct Foundation.Date
|
||||
import class Foundation.JSONDecoder
|
||||
import class Foundation.JSONEncoder
|
||||
|
||||
/// Model Context Protocol server
|
||||
public actor Server {
|
||||
/// Implementation information
|
||||
public struct Info: Hashable, Codable, Sendable {
|
||||
/// The server name
|
||||
public let name: String
|
||||
/// The server version
|
||||
public let version: String
|
||||
|
||||
public init(name: String, version: String) {
|
||||
self.name = name
|
||||
self.version = version
|
||||
}
|
||||
}
|
||||
|
||||
/// Server capabilities
|
||||
public struct Capabilities: Hashable, Codable, Sendable {
|
||||
/// Resources capabilities
|
||||
public struct Resources: Hashable, Codable, Sendable {
|
||||
/// Whether the list of resources has changed
|
||||
public var list: Bool?
|
||||
/// Whether the resource can be read
|
||||
public var read: Bool?
|
||||
/// Whether the resource can be subscribed to
|
||||
public var subscribe: Bool?
|
||||
/// Whether the list of resources has changed
|
||||
public var listChanged: Bool?
|
||||
|
||||
public init(
|
||||
list: Bool? = nil,
|
||||
read: Bool? = nil,
|
||||
subscribe: Bool? = nil,
|
||||
listChanged: Bool? = nil
|
||||
) {
|
||||
self.list = list
|
||||
self.read = read
|
||||
self.subscribe = subscribe
|
||||
self.listChanged = listChanged
|
||||
}
|
||||
}
|
||||
|
||||
/// Tools capabilities
|
||||
public struct Tools: Hashable, Codable, Sendable {
|
||||
/// Whether the server notifies clients when tools change
|
||||
public var listChanged: Bool?
|
||||
|
||||
public init(listChanged: Bool? = nil) {
|
||||
self.listChanged = listChanged
|
||||
}
|
||||
}
|
||||
|
||||
/// Prompts capabilities
|
||||
public struct Prompts: Hashable, Codable, Sendable {
|
||||
/// Whether the server notifies clients when prompts change
|
||||
public var listChanged: Bool?
|
||||
|
||||
public init(listChanged: Bool? = nil) {
|
||||
self.listChanged = listChanged
|
||||
}
|
||||
}
|
||||
|
||||
/// Logging capabilities
|
||||
public struct Logging: Hashable, Codable, Sendable {
|
||||
public init() {}
|
||||
}
|
||||
|
||||
/// Logging capabilities
|
||||
public var logging: Logging?
|
||||
/// Prompts capabilities
|
||||
public var prompts: Prompts?
|
||||
/// Resources capabilities
|
||||
public var resources: Resources?
|
||||
/// Tools capabilities
|
||||
public var tools: Tools?
|
||||
|
||||
public init(
|
||||
logging: Logging? = nil,
|
||||
prompts: Prompts? = nil,
|
||||
resources: Resources? = nil,
|
||||
tools: Tools? = nil
|
||||
) {
|
||||
self.logging = logging
|
||||
self.prompts = prompts
|
||||
self.resources = resources
|
||||
self.tools = tools
|
||||
}
|
||||
}
|
||||
|
||||
/// Server information
|
||||
private let serverInfo: Server.Info
|
||||
/// The server connection
|
||||
private var connection: (any Transport)?
|
||||
/// The server logger
|
||||
private var logger: Logger? {
|
||||
get async {
|
||||
await connection?.logger
|
||||
}
|
||||
}
|
||||
|
||||
/// The server name
|
||||
public nonisolated var name: String { serverInfo.name }
|
||||
/// The server version
|
||||
public nonisolated var version: String { serverInfo.version }
|
||||
/// The server capabilities
|
||||
public var capabilities = Capabilities()
|
||||
|
||||
/// Request handlers
|
||||
private var methodHandlers: [String: RequestHandlerBox] = [:]
|
||||
/// Notification handlers
|
||||
private var notificationHandlers: [String: [NotificationHandlerBox]] = [:]
|
||||
|
||||
/// Whether the server is initialized
|
||||
private var isInitialized = false
|
||||
/// The client information
|
||||
private var clientInfo: Client.Info?
|
||||
/// The client capabilities
|
||||
private var clientCapabilities: Client.Capabilities?
|
||||
/// The protocol version
|
||||
private var protocolVersion: String?
|
||||
/// The list of subscriptions
|
||||
private var subscriptions: [String: Set<ID>] = [:]
|
||||
/// The task for the message handling loop
|
||||
private var task: Task<Void, Never>?
|
||||
|
||||
public init(
|
||||
name: String,
|
||||
version: String,
|
||||
capabilities: Server.Capabilities = .init()
|
||||
) {
|
||||
self.serverInfo = Server.Info(name: name, version: version)
|
||||
self.capabilities = capabilities
|
||||
}
|
||||
|
||||
/// Start the server
|
||||
public func start(transport: any Transport) async throws {
|
||||
self.connection = transport
|
||||
registerDefaultHandlers()
|
||||
try await transport.connect()
|
||||
|
||||
await logger?.info(
|
||||
"Server started", metadata: ["name": "\(name)", "version": "\(version)"])
|
||||
|
||||
// Start message handling loop
|
||||
task = Task {
|
||||
do {
|
||||
let stream = await transport.receive()
|
||||
for try await string in stream {
|
||||
if Task.isCancelled { break } // Check cancellation inside loop
|
||||
|
||||
var requestID: ID?
|
||||
do {
|
||||
guard let data = string.data(using: .utf8) else {
|
||||
throw Error.parseError("Invalid UTF-8 data")
|
||||
}
|
||||
|
||||
// Attempt to decode string data as AnyRequest or AnyMessage
|
||||
let decoder = JSONDecoder()
|
||||
if let request = try? decoder.decode(AnyRequest.self, from: data) {
|
||||
try await handleRequest(request)
|
||||
} else if let message = try? decoder.decode(AnyMessage.self, from: data) {
|
||||
try await handleMessage(message)
|
||||
} else {
|
||||
// Try to extract request ID from raw JSON if possible
|
||||
if let json = try? JSONDecoder().decode(
|
||||
[String: Value].self, from: data),
|
||||
let idValue = json["id"]
|
||||
{
|
||||
if let strValue = idValue.stringValue {
|
||||
requestID = .string(strValue)
|
||||
} else if let intValue = idValue.intValue {
|
||||
requestID = .number(intValue)
|
||||
}
|
||||
}
|
||||
throw Error.parseError("Invalid message format")
|
||||
}
|
||||
} catch let error as Errno where error == .resourceTemporarilyUnavailable {
|
||||
// Resource temporarily unavailable, retry after a short delay
|
||||
try? await Task.sleep(nanoseconds: 10_000_000) // 10ms
|
||||
continue
|
||||
} catch {
|
||||
await logger?.error(
|
||||
"Error processing message", metadata: ["error": "\(error)"])
|
||||
// Only send error responses for requests
|
||||
if let requestID = requestID {
|
||||
let mcpError =
|
||||
error as? Error ?? Error.internalError(error.localizedDescription)
|
||||
let response = AnyMethod.response(id: requestID, error: mcpError)
|
||||
try? await send(response)
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
await logger?.error(
|
||||
"Fatal error in message handling loop", metadata: ["error": "\(error)"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop the server
|
||||
public func stop() async {
|
||||
task?.cancel()
|
||||
task = nil
|
||||
if let connection = connection {
|
||||
await connection.disconnect()
|
||||
}
|
||||
connection = nil
|
||||
}
|
||||
|
||||
// MARK: - Registration
|
||||
|
||||
/// Register a method handler
|
||||
@discardableResult
|
||||
public func withMethodHandler<M: Method>(
|
||||
_ type: M.Type,
|
||||
handler: @escaping @Sendable (M.Parameters) async throws -> M.Result
|
||||
) -> Self {
|
||||
methodHandlers[M.name] = TypedRequestHandler { (request: Request<M>) -> Response<M> in
|
||||
let result = try await handler(request.params)
|
||||
return Response(id: request.id, result: result)
|
||||
}
|
||||
return self
|
||||
}
|
||||
|
||||
/// Register a notification handler
|
||||
@discardableResult
|
||||
public func onNotification<N: Notification>(
|
||||
_ type: N.Type,
|
||||
handler: @escaping @Sendable (Message<N>) async throws -> Void
|
||||
) -> Self {
|
||||
let handlers = notificationHandlers[N.name, default: []]
|
||||
notificationHandlers[N.name] = handlers + [TypedNotificationHandler(handler)]
|
||||
return self
|
||||
}
|
||||
|
||||
// MARK: - Sending
|
||||
|
||||
/// Send a response to a client
|
||||
public func send<M: Method>(_ response: Response<M>) async throws {
|
||||
guard let connection = connection else {
|
||||
throw Error.internalError("Server connection not initialized")
|
||||
}
|
||||
let responseData = try JSONEncoder().encode(response)
|
||||
if let responseStr = String(data: responseData, encoding: .utf8) {
|
||||
try await connection.send(responseStr)
|
||||
}
|
||||
}
|
||||
|
||||
/// Send a notification to connected clients
|
||||
public func notify<N: Notification>(_ notification: Message<N>) async throws {
|
||||
guard let connection = connection else {
|
||||
throw Error.internalError("Server connection not initialized")
|
||||
}
|
||||
let notificationData = try JSONEncoder().encode(notification)
|
||||
if let notificationStr = String(data: notificationData, encoding: .utf8) {
|
||||
try await connection.send(notificationStr)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
private func handleRequest(_ request: Request<AnyMethod>) async throws {
|
||||
await logger?.debug(
|
||||
"Processing request",
|
||||
metadata: [
|
||||
"method": "\(request.method)",
|
||||
"id": "\(request.id)",
|
||||
])
|
||||
|
||||
// The client SHOULD NOT send requests other than pings
|
||||
// before the server has responded to the initialize request.
|
||||
switch request.method {
|
||||
case Initialize.name, Ping.name:
|
||||
break
|
||||
default:
|
||||
try checkInitialized()
|
||||
}
|
||||
|
||||
// Find handler for method name
|
||||
guard let handler = methodHandlers[request.method] else {
|
||||
let error = Error.methodNotFound("Unknown method: \(request.method)")
|
||||
let response = AnyMethod.response(id: request.id, error: error)
|
||||
try await send(response)
|
||||
throw error
|
||||
}
|
||||
|
||||
do {
|
||||
// Handle request and get response
|
||||
let response = try await handler(request)
|
||||
try await send(response)
|
||||
} catch {
|
||||
let mcpError = error as? Error ?? Error.internalError(error.localizedDescription)
|
||||
let response = AnyMethod.response(id: request.id, error: mcpError)
|
||||
try await send(response)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private func handleMessage(_ message: Message<AnyNotification>) async throws {
|
||||
await logger?.debug(
|
||||
"Processing notification",
|
||||
metadata: ["method": "\(message.method)"])
|
||||
|
||||
// Check initialization state unless this is an initialized notification
|
||||
if message.method != InitializedNotification.name {
|
||||
try checkInitialized()
|
||||
}
|
||||
|
||||
// Find notification handlers for this method
|
||||
guard let handlers = notificationHandlers[message.method] else { return }
|
||||
|
||||
// Convert notification parameters to concrete type and call handlers
|
||||
for handler in handlers {
|
||||
do {
|
||||
try await handler(message)
|
||||
} catch {
|
||||
await logger?.error(
|
||||
"Error handling notification",
|
||||
metadata: [
|
||||
"method": "\(message.method)",
|
||||
"error": "\(error)",
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func checkInitialized() throws {
|
||||
guard isInitialized else {
|
||||
throw Error.invalidRequest("Server is not initialized")
|
||||
}
|
||||
}
|
||||
|
||||
private func registerDefaultHandlers() {
|
||||
// Initialize
|
||||
withMethodHandler(Initialize.self) { [weak self] params in
|
||||
guard let self = self else {
|
||||
throw Error.internalError("Server was deallocated")
|
||||
}
|
||||
|
||||
guard await !self.isInitialized else {
|
||||
throw Error.invalidRequest("Server is already initialized")
|
||||
}
|
||||
|
||||
// Validate protocol version
|
||||
guard Version.latest == params.protocolVersion else {
|
||||
throw Error.invalidRequest(
|
||||
"Unsupported protocol version: \(params.protocolVersion)")
|
||||
}
|
||||
|
||||
await self.setInitialState(
|
||||
clientInfo: params.clientInfo,
|
||||
clientCapabilities: params.capabilities,
|
||||
protocolVersion: params.protocolVersion
|
||||
)
|
||||
|
||||
let result = Initialize.Result(
|
||||
protocolVersion: Version.latest,
|
||||
capabilities: await self.capabilities,
|
||||
serverInfo: self.serverInfo,
|
||||
instructions: nil
|
||||
)
|
||||
|
||||
// Send initialized notification after a short delay
|
||||
Task {
|
||||
try? await Task.sleep(nanoseconds: 100_000_000) // 100ms
|
||||
try? await self.notify(InitializedNotification.message())
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// Ping
|
||||
withMethodHandler(Ping.self) { _ in return Empty() }
|
||||
}
|
||||
|
||||
private func setInitialState(
|
||||
clientInfo: Client.Info,
|
||||
clientCapabilities: Client.Capabilities,
|
||||
protocolVersion: String
|
||||
) async {
|
||||
self.clientInfo = clientInfo
|
||||
self.clientCapabilities = clientCapabilities
|
||||
self.protocolVersion = protocolVersion
|
||||
self.isInitialized = true
|
||||
}
|
||||
}
|
||||
170
Sources/MCP/Server/Tools.swift
Normal file
170
Sources/MCP/Server/Tools.swift
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
import Foundation
|
||||
|
||||
/// The Model Context Protocol (MCP) allows servers to expose tools
|
||||
/// that can be invoked by language models.
|
||||
/// Tools enable models to interact with external systems, such as
|
||||
/// querying databases, calling APIs, or performing computations.
|
||||
/// Each tool is uniquely identified by a name and includes metadata
|
||||
/// describing its schema.
|
||||
///
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/
|
||||
public struct Tool: Hashable, Codable, Sendable {
|
||||
/// The tool name
|
||||
public let name: String
|
||||
/// The tool description
|
||||
public let description: String
|
||||
/// The tool input schema
|
||||
public let inputSchema: Value?
|
||||
|
||||
public init(name: String, description: String, inputSchema: Value? = nil) {
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.inputSchema = inputSchema
|
||||
}
|
||||
|
||||
/// Content types that can be returned by a tool
|
||||
public enum Content: Hashable, Codable, Sendable {
|
||||
/// Text content
|
||||
case text(String)
|
||||
/// Image content
|
||||
case image(data: String, mimeType: String, metadata: [String: String]?)
|
||||
/// Embedded resource content
|
||||
case resource(uri: String, mimeType: String, text: String?)
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case type
|
||||
case text
|
||||
case image
|
||||
case resource
|
||||
case uri
|
||||
case mimeType
|
||||
case data
|
||||
case metadata
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let type = try container.decode(String.self, forKey: .type)
|
||||
|
||||
switch type {
|
||||
case "text":
|
||||
let text = try container.decode(String.self, forKey: .text)
|
||||
self = .text(text)
|
||||
case "image":
|
||||
let data = try container.decode(String.self, forKey: .data)
|
||||
let mimeType = try container.decode(String.self, forKey: .mimeType)
|
||||
let metadata = try container.decodeIfPresent(
|
||||
[String: String].self, forKey: .metadata)
|
||||
self = .image(data: data, mimeType: mimeType, metadata: metadata)
|
||||
case "resource":
|
||||
let uri = try container.decode(String.self, forKey: .uri)
|
||||
let mimeType = try container.decode(String.self, forKey: .mimeType)
|
||||
let text = try container.decodeIfPresent(String.self, forKey: .text)
|
||||
self = .resource(uri: uri, mimeType: mimeType, text: text)
|
||||
default:
|
||||
throw DecodingError.dataCorruptedError(
|
||||
forKey: .type, in: container, debugDescription: "Unknown tool content type")
|
||||
}
|
||||
}
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
|
||||
switch self {
|
||||
case .text(let text):
|
||||
try container.encode("text", forKey: .type)
|
||||
try container.encode(text, forKey: .text)
|
||||
case .image(let data, let mimeType, let metadata):
|
||||
try container.encode("image", forKey: .type)
|
||||
try container.encode(data, forKey: .data)
|
||||
try container.encode(mimeType, forKey: .mimeType)
|
||||
try container.encodeIfPresent(metadata, forKey: .metadata)
|
||||
case .resource(let uri, let mimeType, let text):
|
||||
try container.encode("resource", forKey: .type)
|
||||
try container.encode(uri, forKey: .uri)
|
||||
try container.encode(mimeType, forKey: .mimeType)
|
||||
try container.encodeIfPresent(text, forKey: .text)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case name
|
||||
case description
|
||||
case inputSchema
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
name = try container.decode(String.self, forKey: .name)
|
||||
description = try container.decode(String.self, forKey: .description)
|
||||
inputSchema = try container.decodeIfPresent(Value.self, forKey: .inputSchema)
|
||||
}
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(name, forKey: .name)
|
||||
try container.encode(description, forKey: .description)
|
||||
if let schema = inputSchema {
|
||||
try container.encode(schema, forKey: .inputSchema)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: -
|
||||
|
||||
/// To discover available tools, clients send a `tools/list` request.
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#listing-tools
|
||||
public enum ListTools: Method {
|
||||
public static let name = "tools/list"
|
||||
|
||||
public struct Parameters: Hashable, Codable, Sendable {
|
||||
public let cursor: String?
|
||||
|
||||
public init(cursor: String? = nil) {
|
||||
self.cursor = cursor
|
||||
}
|
||||
}
|
||||
|
||||
public struct Result: Hashable, Codable, Sendable {
|
||||
public let tools: [Tool]
|
||||
public let nextCursor: String?
|
||||
|
||||
public init(tools: [Tool], nextCursor: String? = nil) {
|
||||
self.tools = tools
|
||||
self.nextCursor = nextCursor
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// To call a tool, clients send a `tools/call` request.
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#calling-tools
|
||||
public enum CallTool: Method {
|
||||
public static let name = "tools/call"
|
||||
|
||||
public struct Parameters: Hashable, Codable, Sendable {
|
||||
public let name: String
|
||||
public let arguments: [String: Value]?
|
||||
|
||||
public init(name: String, arguments: [String: Value]? = nil) {
|
||||
self.name = name
|
||||
self.arguments = arguments
|
||||
}
|
||||
}
|
||||
|
||||
public struct Result: Hashable, Codable, Sendable {
|
||||
public let content: [Tool.Content]
|
||||
public let isError: Bool
|
||||
|
||||
public init(content: [Tool.Content], isError: Bool) {
|
||||
self.content = content
|
||||
self.isError = isError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// When the list of available tools changes, servers that declared the listChanged capability SHOULD send a notification:
|
||||
/// - SeeAlso: https://spec.modelcontextprotocol.io/specification/2024-11-05/server/tools/#list-changed-notification
|
||||
public struct ToolListChangedNotification: Notification {
|
||||
public static let name: String = "notifications/tools/list_changed"
|
||||
}
|
||||
Loading…
Reference in a new issue