|
| 1 | +// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +/// A client that connects to a server and supports elicitation requests. |
| 6 | +library; |
| 7 | + |
| 8 | +import 'dart:async'; |
| 9 | +import 'dart:io'; |
| 10 | + |
| 11 | +import 'package:dart_mcp/client.dart'; |
| 12 | +import 'package:dart_mcp/stdio.dart'; |
| 13 | +import 'package:stream_channel/stream_channel.dart'; |
| 14 | + |
| 15 | +void main() async { |
| 16 | + // Create a client, which is the top level object that manages all |
| 17 | + // server connections. |
| 18 | + final client = TestMCPClientWithElicitationSupport( |
| 19 | + Implementation(name: 'example dart client', version: '0.1.0'), |
| 20 | + ); |
| 21 | + print('connecting to server'); |
| 22 | + |
| 23 | + // Start the server as a separate process. |
| 24 | + final process = await Process.start('dart', [ |
| 25 | + 'run', |
| 26 | + 'example/elicitations_server.dart', |
| 27 | + ]); |
| 28 | + // Connect the client to the server. |
| 29 | + final server = client.connectServer( |
| 30 | + stdioChannel(input: process.stdout, output: process.stdin), |
| 31 | + ); |
| 32 | + // When the server connection is closed, kill the process. |
| 33 | + unawaited(server.done.then((_) => process.kill())); |
| 34 | + |
| 35 | + print('server started'); |
| 36 | + |
| 37 | + // Initialize the server and let it know our capabilities. |
| 38 | + print('initializing server'); |
| 39 | + final initializeResult = await server.initialize( |
| 40 | + InitializeRequest( |
| 41 | + protocolVersion: ProtocolVersion.latestSupported, |
| 42 | + capabilities: client.capabilities, |
| 43 | + clientInfo: client.implementation, |
| 44 | + ), |
| 45 | + ); |
| 46 | + print('initialized: $initializeResult'); |
| 47 | + |
| 48 | + // Notify the server that we are initialized. |
| 49 | + server.notifyInitialized(); |
| 50 | + print('sent initialized notification'); |
| 51 | + |
| 52 | + print('waiting for elicitation requests'); |
| 53 | +} |
| 54 | + |
| 55 | +/// A client that supports elicitation requests using the [ElicitationSupport] |
| 56 | +/// mixin. |
| 57 | +/// |
| 58 | +/// Prompts the user for values on stdin. |
| 59 | +final class TestMCPClientWithElicitationSupport extends MCPClient |
| 60 | + with ElicitationSupport { |
| 61 | + TestMCPClientWithElicitationSupport(super.implementation); |
| 62 | + |
| 63 | + @override |
| 64 | + /// Handle the actual elicitation from the server by reading from stdin. |
| 65 | + FutureOr<ElicitResult> handleElicitation(ElicitRequest request) { |
| 66 | + // Ask the user if they are willing to provide the information first. |
| 67 | + print(''' |
| 68 | +Elicitation received from server: ${request.message} |
| 69 | +
|
| 70 | +Do you want to accept (a), reject (r), or cancel (c) the elicitation? |
| 71 | +'''); |
| 72 | + final answer = stdin.readLineSync(); |
| 73 | + final action = switch (answer) { |
| 74 | + 'a' => ElicitationAction.accept, |
| 75 | + 'r' => ElicitationAction.reject, |
| 76 | + 'c' => ElicitationAction.cancel, |
| 77 | + _ => throw ArgumentError('Invalid answer: $answer'), |
| 78 | + }; |
| 79 | + |
| 80 | + // If they don't accept it, just return the reason. |
| 81 | + if (action != ElicitationAction.accept) { |
| 82 | + return ElicitResult(action: action); |
| 83 | + } |
| 84 | + |
| 85 | + // User has accepted the elicitation, prompt them for each value. |
| 86 | + final arguments = <String, Object?>{}; |
| 87 | + for (final property in request.requestedSchema.properties!.entries) { |
| 88 | + final name = property.key; |
| 89 | + final type = property.value.type; |
| 90 | + final allowedValues = |
| 91 | + type == JsonType.enumeration |
| 92 | + ? ' (${(property.value as EnumSchema).values.join(', ')})' |
| 93 | + : ''; |
| 94 | + // Ask the user in a loop until the value provided matches the schema, |
| 95 | + // at which point we will `break` from the loop. |
| 96 | + while (true) { |
| 97 | + stdout.write('$name$allowedValues: '); |
| 98 | + final userValue = stdin.readLineSync()!; |
| 99 | + try { |
| 100 | + // Convert the value to the correct type. |
| 101 | + final convertedValue = switch (type) { |
| 102 | + JsonType.string || JsonType.enumeration => userValue, |
| 103 | + JsonType.num => num.parse(userValue), |
| 104 | + JsonType.int => int.parse(userValue), |
| 105 | + JsonType.bool => bool.parse(userValue), |
| 106 | + JsonType.object || |
| 107 | + JsonType.list || |
| 108 | + JsonType.nil || |
| 109 | + null => throw StateError('Unsupported field type $type'), |
| 110 | + }; |
| 111 | + // Actually validate the value based on the schema. |
| 112 | + final errors = property.value.validate(convertedValue); |
| 113 | + if (errors.isEmpty) { |
| 114 | + // No errors, we can assign the value and exit the loop. |
| 115 | + arguments[name] = convertedValue; |
| 116 | + break; |
| 117 | + } else { |
| 118 | + print('Invalid value, got the following errors:'); |
| 119 | + for (final error in errors) { |
| 120 | + print(' - $error'); |
| 121 | + } |
| 122 | + } |
| 123 | + } catch (e) { |
| 124 | + // Handles parse errors etc. |
| 125 | + print('Invalid value, got the following errors:\n - $e'); |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + // Return the final result with the arguments. |
| 130 | + return ElicitResult(action: ElicitationAction.accept, content: arguments); |
| 131 | + } |
| 132 | + |
| 133 | + /// Whenever connecting to a server, we also listen for log messages. |
| 134 | + /// |
| 135 | + /// The server we connect to will log the elicitation responses it receives. |
| 136 | + @override |
| 137 | + ServerConnection connectServer( |
| 138 | + StreamChannel<String> channel, { |
| 139 | + Sink<String>? protocolLogSink, |
| 140 | + }) { |
| 141 | + final connection = super.connectServer( |
| 142 | + channel, |
| 143 | + protocolLogSink: protocolLogSink, |
| 144 | + ); |
| 145 | + // Whenever a log message is received, print it to the console. |
| 146 | + connection.onLog.listen((message) { |
| 147 | + print('[${message.level}]: ${message.data}'); |
| 148 | + }); |
| 149 | + return connection; |
| 150 | + } |
| 151 | +} |
0 commit comments