-
Notifications
You must be signed in to change notification settings - Fork 29
add elicitation example, fix some issues with the elicitation APIs #229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,151 @@ | ||
// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file | ||
// for details. All rights reserved. Use of this source code is governed by a | ||
// BSD-style license that can be found in the LICENSE file. | ||
|
||
/// A client that connects to a server and supports elicitation requests. | ||
library; | ||
|
||
import 'dart:async'; | ||
import 'dart:io'; | ||
|
||
import 'package:dart_mcp/client.dart'; | ||
import 'package:dart_mcp/stdio.dart'; | ||
import 'package:stream_channel/stream_channel.dart'; | ||
|
||
void main() async { | ||
// Create a client, which is the top level object that manages all | ||
// server connections. | ||
final client = TestMCPClientWithElicitationSupport( | ||
Implementation(name: 'example dart client', version: '0.1.0'), | ||
); | ||
print('connecting to server'); | ||
|
||
// Start the server as a separate process. | ||
final process = await Process.start('dart', [ | ||
'run', | ||
'example/elicitations_server.dart', | ||
]); | ||
// Connect the client to the server. | ||
final server = client.connectServer( | ||
stdioChannel(input: process.stdout, output: process.stdin), | ||
); | ||
// When the server connection is closed, kill the process. | ||
unawaited(server.done.then((_) => process.kill())); | ||
|
||
print('server started'); | ||
|
||
// Initialize the server and let it know our capabilities. | ||
print('initializing server'); | ||
final initializeResult = await server.initialize( | ||
InitializeRequest( | ||
protocolVersion: ProtocolVersion.latestSupported, | ||
capabilities: client.capabilities, | ||
clientInfo: client.implementation, | ||
), | ||
); | ||
print('initialized: $initializeResult'); | ||
|
||
// Notify the server that we are initialized. | ||
server.notifyInitialized(); | ||
print('sent initialized notification'); | ||
|
||
print('waiting for elicitation requests'); | ||
} | ||
|
||
/// A client that supports elicitation requests using the [ElicitationSupport] | ||
/// mixin. | ||
/// | ||
/// Prompts the user for values on stdin. | ||
final class TestMCPClientWithElicitationSupport extends MCPClient | ||
with ElicitationSupport { | ||
TestMCPClientWithElicitationSupport(super.implementation); | ||
|
||
@override | ||
/// Handle the actual elicitation from the server by reading from stdin. | ||
FutureOr<ElicitResult> handleElicitation(ElicitRequest request) { | ||
// Ask the user if they are willing to provide the information first. | ||
print(''' | ||
Elicitation received from server: ${request.message} | ||
|
||
Do you want to accept (a), reject (r), or cancel (c) the elicitation? | ||
'''); | ||
final answer = stdin.readLineSync(); | ||
final action = switch (answer) { | ||
'a' => ElicitationAction.accept, | ||
'r' => ElicitationAction.reject, | ||
'c' => ElicitationAction.cancel, | ||
_ => throw ArgumentError('Invalid answer: $answer'), | ||
}; | ||
|
||
// If they don't accept it, just return the reason. | ||
if (action != ElicitationAction.accept) { | ||
return ElicitResult(action: action); | ||
} | ||
|
||
// User has accepted the elicitation, prompt them for each value. | ||
final arguments = <String, Object?>{}; | ||
for (final property in request.requestedSchema.properties!.entries) { | ||
final name = property.key; | ||
final type = property.value.type; | ||
final allowedValues = | ||
type == JsonType.enumeration | ||
? ' (${(property.value as EnumSchema).values.join(', ')})' | ||
: ''; | ||
// Ask the user in a loop until the value provided matches the schema, | ||
// at which point we will `break` from the loop. | ||
while (true) { | ||
stdout.write('$name$allowedValues: '); | ||
final userValue = stdin.readLineSync()!; | ||
try { | ||
// Convert the value to the correct type. | ||
final convertedValue = switch (type) { | ||
JsonType.string || JsonType.enumeration => userValue, | ||
JsonType.num => num.parse(userValue), | ||
JsonType.int => int.parse(userValue), | ||
JsonType.bool => bool.parse(userValue), | ||
JsonType.object || | ||
JsonType.list || | ||
JsonType.nil || | ||
null => throw StateError('Unsupported field type $type'), | ||
}; | ||
// Actually validate the value based on the schema. | ||
final errors = property.value.validate(convertedValue); | ||
if (errors.isEmpty) { | ||
// No errors, we can assign the value and exit the loop. | ||
arguments[name] = convertedValue; | ||
break; | ||
} else { | ||
print('Invalid value, got the following errors:'); | ||
for (final error in errors) { | ||
print(' - $error'); | ||
} | ||
} | ||
} catch (e) { | ||
// Handles parse errors etc. | ||
print('Invalid value, got the following errors:\n - $e'); | ||
} | ||
} | ||
} | ||
// Return the final result with the arguments. | ||
return ElicitResult(action: ElicitationAction.accept, content: arguments); | ||
} | ||
|
||
/// Whenever connecting to a server, we also listen for log messages. | ||
/// | ||
/// The server we connect to will log the elicitation responses it receives. | ||
@override | ||
ServerConnection connectServer( | ||
StreamChannel<String> channel, { | ||
Sink<String>? protocolLogSink, | ||
}) { | ||
final connection = super.connectServer( | ||
channel, | ||
protocolLogSink: protocolLogSink, | ||
); | ||
// Whenever a log message is received, print it to the console. | ||
connection.onLog.listen((message) { | ||
print('[${message.level}]: ${message.data}'); | ||
}); | ||
return connection; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file | ||
// for details. All rights reserved. Use of this source code is governed by a | ||
// BSD-style license that can be found in the LICENSE file. | ||
|
||
/// A server that makes an elicitation request to the client using the | ||
/// [ElicitationRequestSupport] mixin. | ||
library; | ||
|
||
import 'dart:io' as io; | ||
|
||
import 'package:dart_mcp/server.dart'; | ||
import 'package:dart_mcp/stdio.dart'; | ||
|
||
void main() { | ||
// Create the server and connect it to stdio. | ||
MCPServerWithElicitation(stdioChannel(input: io.stdin, output: io.stdout)); | ||
} | ||
|
||
/// This server uses the [ElicitationRequestSupport] mixin to make elicitation | ||
/// requests to the client. | ||
base class MCPServerWithElicitation extends MCPServer | ||
with LoggingSupport, ElicitationRequestSupport { | ||
MCPServerWithElicitation(super.channel) | ||
: super.fromStreamChannel( | ||
implementation: Implementation( | ||
name: 'An example dart server which makes elicitations', | ||
version: '0.1.0', | ||
), | ||
instructions: 'Handle the elicitations and ask the user for the values', | ||
) { | ||
// You must wait for initialization to complete before you can make an | ||
// elicitation request. | ||
initialized.then((_) => _elicitName()); | ||
} | ||
|
||
/// Elicits a name from the user, and logs a message based on the response. | ||
void _elicitName() async { | ||
final response = await elicit( | ||
ElicitRequest( | ||
message: 'I would like to ask you some personal information.', | ||
requestedSchema: Schema.object( | ||
properties: { | ||
'name': Schema.string(), | ||
'age': Schema.int(), | ||
'gender': Schema.enumeration(values: ['male', 'female', 'other']), | ||
}, | ||
), | ||
), | ||
); | ||
switch (response.action) { | ||
case ElicitationAction.accept: | ||
final {'age': int age, 'name': String name, 'gender': String gender} = | ||
(response.content as Map<String, dynamic>); | ||
log( | ||
LoggingLevel.warning, | ||
'Hello $name! I see that you are $age years ' | ||
'old and identify as $gender', | ||
); | ||
case ElicitationAction.reject: | ||
log(LoggingLevel.warning, 'Request for name was rejected'); | ||
case ElicitationAction.cancel: | ||
log(LoggingLevel.warning, 'Request for name was cancelled'); | ||
} | ||
|
||
// Ask again after a second. | ||
await Future<void>.delayed(const Duration(seconds: 1)); | ||
_elicitName(); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oops. I thought the server had that in its schema to indicate that it might send elicitations.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The capabilities are only there for the client/server indicating they can handle certain requests, not whether or not they will issue them.
I think you could argue it might be useful to know what kind of requests a server would like to make, but that isn't how its structured 🤷♂️