The @MCPResource macro allows you to expose functions as resources accessible via URI templates. This enables clients to access data using structured URIs with path and query parameters.
Key Features
- URI Templates: Define patterns using curly braces for placeholders (e.g.,
{param}). - Path Parameters: Extract values directly from the URI path.
- Query Parameters: Extract values from the query string (e.g.,
?q={query}). - Optional Parameters: Supports Swift default values for optional parameters.
- MIME Types: You can specify the content type using the
mimeType: parameter. - Type Safety: Parameters are automatically converted from URI strings to the correct Swift types.
Automatic Server Capabilities
When using @MCPResource, the server automatically handles:
- Resource discovery via
mcpResourceTemplates. - URI matching and parameter extraction.
- Type conversion, validation, and error handling for invalid parameters.
@MCPServer(name: "ResourceServer")
actor ResourceServer {
/// Get user profile by ID
@MCPResource("users://{user_id}/profile")
func getUserProfile(user_id: Int) -> String {
return "Profile for user \(user_id)"
}
/// Search users with pagination
@MCPResource("users://search?q={query}&page={page}", mimeType: "application/json")
func searchUsers(query: String, page: Int = 1) -> String {
return "{\"query\": الش\"query\"\", \"page\": \(page)\"}"
}
}