Implement Sampling and Elicitation Handlers
mainSampling and Elicitation are flows where the server requests information from the client.
- Sampling: The server requests an LLM completion. Use
withSamplingHandlerto intercept the request, potentially review it (human-in-the-loop), call your own LLM service, and return aCreateSamplingMessage.Result. - Elicitation: The server requests structured information (like credentials or user confirmation) via a form or a URL. Use
withElicitationHandlerto present a UI to the user and return aCreateElicitation.Result(accept, cancel, or decline).
// Sampling Handler
await client.withSamplingHandler { parameters in
let completion = try await callYourLLMService(messages: parameters.messages)
return CreateSamplingMessage.Result(
model: "my-model",
stopReason: .endTurn,
role: .assistant,
content: .text(completion)
)
}
// Elicitation Handler
await client.withElicitationHandler { parameters in
switch parameters {
case .form(let form):
let userResponse = presentElicitationUI(form)
return CreateElicitation.Result(action: .accept, content: userResponse.data)
case .url(let url):
openURL(url.url)
return CreateElicitation.Result(action: .accept)
}
}