requestClientSampling method
Server-initiated request: ask the connected client's LLM to
generate a completion (spec sampling/createMessage).
params follows the spec CreateMessageRequest.params shape:
messages, maxTokens (required), plus optional modelPreferences,
systemPrompt, includeContext, temperature, stopSequences,
metadata.
Returns the spec CreateMessageResult map (role, content,
model, optional stopReason).
The client must advertise the sampling capability during
initialize; otherwise this throws McpError with methodNotFound.
Implementation
Future<Map<String, dynamic>> requestClientSampling(
String sessionId,
Map<String, dynamic> params, {
Duration timeout = const Duration(seconds: 60),
}) async {
final session = _sessions[sessionId];
if (session == null) {
throw StateError('Unknown sessionId: $sessionId');
}
final clientHasSampling = session.capabilities?['sampling'] != null;
if (!clientHasSampling) {
throw McpError(
'Client does not advertise the `sampling` capability',
code: ErrorCode.methodNotFound,
);
}
final result = await _sendRequestToClient(
sessionId, 'sampling/createMessage', params, timeout: timeout);
return result is Map<String, dynamic>
? result
: Map<String, dynamic>.from(result as Map);
}