-
Notifications
You must be signed in to change notification settings - Fork 51
Add more and better examples #228
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
Show all changes
11 commits
Select commit
Hold shift + click to select a range
c493e29
add stdioChannel function and use it across the repo
jakemac53 1f8f49a
add tools and resources examples
jakemac53 5806250
fix PromptMessage constructor, add prompts example
jakemac53 fa30b61
cleanup
jakemac53 23a9925
add roots and logging examples
jakemac53 4f5ab4d
update changelog
jakemac53 0f71aa4
fix some grammar mistakes
jakemac53 041fae3
add docs, clean up some things
jakemac53 e24711f
fix lint
jakemac53 146eb0c
Merge branch 'main' into examples
jakemac53 183bc20
fix up deprecation warnings after merging
jakemac53 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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| // 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 interacts with a server that provides prompts. | ||
| library; | ||
|
|
||
| import 'dart:async'; | ||
| import 'dart:io'; | ||
|
|
||
| import 'package:dart_mcp/client.dart'; | ||
| import 'package:dart_mcp/stdio.dart'; | ||
|
|
||
| void main() async { | ||
| // Create the client, which is the top level object that manages all | ||
| // server connections. | ||
| final client = MCPClient( | ||
| 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/prompts_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'); | ||
|
|
||
| // Ensure the server supports the prompts capability. | ||
| if (initializeResult.capabilities.prompts == null) { | ||
| await server.shutdown(); | ||
| throw StateError('Server doesn\'t support prompts!'); | ||
| } | ||
|
|
||
| // Notify the server that we are initialized. | ||
| server.notifyInitialized(); | ||
| print('sent initialized notification'); | ||
|
|
||
| // List all the available prompts from the server. | ||
| print('Listing prompts from server'); | ||
| final promptsResult = await server.listPrompts(ListPromptsRequest()); | ||
| for (final prompt in promptsResult.prompts) { | ||
| // For each prompt, get the full prompt text, filling in any arguments. | ||
| final promptResult = await server.getPrompt( | ||
| GetPromptRequest( | ||
| name: prompt.name, | ||
| arguments: { | ||
| for (var arg in prompt.arguments ?? <PromptArgument>[]) | ||
| arg.name: switch (arg.name) { | ||
| 'tags' => 'myTag myOtherTag', | ||
| 'platforms' => 'vm,chrome', | ||
| _ => throw ArgumentError('Unrecognized argument ${arg.name}'), | ||
| }, | ||
| }, | ||
| ), | ||
| ); | ||
| final promptText = promptResult.messages | ||
| .map((m) => (m.content as TextContent).text) | ||
| .join(''); | ||
| print('Found prompt `${prompt.name}`: "$promptText"'); | ||
| } | ||
|
|
||
| // Shutdown the client, which will also shutdown the server connection. | ||
| await client.shutdown(); | ||
| } |
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,80 @@ | ||
| // 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 implements the prompts API using the [PromptsSupport] 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. | ||
| MCPServerWithPrompts(stdioChannel(input: io.stdin, output: io.stdout)); | ||
| } | ||
|
|
||
| /// Our actual MCP server. | ||
| /// | ||
| /// This server uses the [PromptsSupport] mixin to provide prompts to the | ||
| /// client. | ||
| base class MCPServerWithPrompts extends MCPServer with PromptsSupport { | ||
| MCPServerWithPrompts(super.channel) | ||
| : super.fromStreamChannel( | ||
| implementation: Implementation( | ||
| name: 'An example dart server with prompts support', | ||
| version: '0.1.0', | ||
| ), | ||
| instructions: 'Just list the prompts :D', | ||
| ) { | ||
| // Actually add the prompt. | ||
| addPrompt(runTestsPrompt, _runTestsPrompt); | ||
| } | ||
|
|
||
| /// The prompt implementation, takes in a [request] and builds the prompt | ||
| /// by substituting in arguments. | ||
| GetPromptResult _runTestsPrompt(GetPromptRequest request) { | ||
| // The actual arguments should be comma separated, but we allow for space | ||
| // separated and then convert it here. | ||
| final tags = (request.arguments?['tags'] as String?)?.split(' ').join(','); | ||
| final platforms = (request.arguments?['platforms'] as String?) | ||
| ?.split(' ') | ||
| .join(','); | ||
| return GetPromptResult( | ||
| messages: [ | ||
| // This is a prompt that should execute as if it came from the user, | ||
| // instructing the LLM to run a specific CLI command based on the | ||
| // arguments given. | ||
| PromptMessage( | ||
| role: Role.user, | ||
| content: Content.text( | ||
| text: | ||
| 'Execute the shell command `dart test --failures-only' | ||
| '${tags != null ? ' -t $tags' : ''}' | ||
| '${platforms != null ? ' -p $platforms' : ''}' | ||
| '`', | ||
| ), | ||
| ), | ||
| ], | ||
| ); | ||
| } | ||
|
|
||
| /// A prompt that can be used to run tests. | ||
| /// | ||
| /// This prompt has two arguments, `tags` and `platforms`. | ||
| final runTestsPrompt = Prompt( | ||
| name: 'run_tests', | ||
| description: 'Run your dart tests', | ||
| arguments: [ | ||
| PromptArgument( | ||
| name: 'tags', | ||
| description: 'The test tags to include, space or comma separated', | ||
| ), | ||
| PromptArgument( | ||
| name: 'platforms', | ||
| description: 'The platforms to run on, space or comma separated', | ||
| ), | ||
| ], | ||
| ); | ||
| } | ||
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,87 @@ | ||
| // 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 exercises the resources API. | ||
| import 'dart:async'; | ||
| import 'dart:io'; | ||
|
|
||
| import 'package:dart_mcp/client.dart'; | ||
| import 'package:dart_mcp/stdio.dart'; | ||
|
|
||
| void main() async { | ||
| // Create a client, which is the top level object that manages all | ||
| // server connections. | ||
| final client = MCPClient( | ||
| 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/resources_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'); | ||
|
|
||
| // Ensure the server supports the resources capability. | ||
| if (initializeResult.capabilities.resources == null) { | ||
| await server.shutdown(); | ||
| throw StateError('Server doesn\'t support resources!'); | ||
| } | ||
|
|
||
| // Notify the server that we are initialized. | ||
| server.notifyInitialized(); | ||
| print('sent initialized notification'); | ||
|
|
||
| // List all the available resources from the server. | ||
| print('Listing resources from server'); | ||
| final resourcesResult = await server.listResources(ListResourcesRequest()); | ||
| for (final resource in resourcesResult.resources) { | ||
| // For each resource, read its content. | ||
| final content = (await server.readResource( | ||
| ReadResourceRequest(uri: resource.uri), | ||
| )).contents.map((part) => (part as TextResourceContents).text).join(''); | ||
| print( | ||
| 'Found resource: ${resource.name} with uri ${resource.uri} and contents: ' | ||
| '"$content"', | ||
| ); | ||
| } | ||
|
|
||
| // List all the available resource templates from the server. | ||
| print('Listing resource templates from server'); | ||
| final templatesResult = await server.listResourceTemplates( | ||
| ListResourceTemplatesRequest(), | ||
| ); | ||
| for (final template in templatesResult.resourceTemplates) { | ||
| print('Found resource template `${template.uriTemplate}`'); | ||
| // For each template, fill in the path variable and read the resource. | ||
| for (var path in ['zip', 'zap']) { | ||
| final uri = template.uriTemplate.replaceFirst(RegExp('{.*}'), path); | ||
| final contents = (await server.readResource( | ||
| ReadResourceRequest(uri: uri), | ||
| )).contents.map((part) => (part as TextResourceContents).text).join(''); | ||
| print('Read resource `$uri`: "$contents"'); | ||
| } | ||
| } | ||
|
|
||
| // Shutdown the client, which will also shutdown the server connection. | ||
| await client.shutdown(); | ||
| } |
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,64 @@ | ||
| // 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 implements the resources API using the [ResourcesSupport] | ||
| /// 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. | ||
| MCPServerWithResources(stdioChannel(input: io.stdin, output: io.stdout)); | ||
| } | ||
|
|
||
| /// An MCP server with resource and resource template support. | ||
| /// | ||
| /// This server uses the [ResourcesSupport] mixin to provide resources to the | ||
| /// client. | ||
| base class MCPServerWithResources extends MCPServer with ResourcesSupport { | ||
| MCPServerWithResources(super.channel) | ||
| : super.fromStreamChannel( | ||
| implementation: Implementation( | ||
| name: 'An example dart server with resources support', | ||
| version: '0.1.0', | ||
| ), | ||
| instructions: 'Just list and read the resources :D', | ||
| ) { | ||
| // Add a standard resource with a fixed URI. | ||
| addResource( | ||
| Resource(uri: 'example://resource.txt', name: 'An example resource'), | ||
| (request) => ReadResourceResult( | ||
| contents: [TextResourceContents(text: 'Example!', uri: request.uri)], | ||
| ), | ||
| ); | ||
|
|
||
| // A resource template which always just returns the path portion of the | ||
| // requested URI as the content of the resource. | ||
| addResourceTemplate( | ||
| ResourceTemplate( | ||
| uriTemplate: 'example_template://{path}', | ||
| name: 'Example resource template', | ||
| ), | ||
| (request) { | ||
| // This template only handles resource URIs with this exact prefix, | ||
| // returning null defers to the next resource template handler. | ||
| if (!request.uri.startsWith('example_template://')) { | ||
| return null; | ||
| } | ||
| return ReadResourceResult( | ||
| contents: [ | ||
| TextResourceContents( | ||
| text: request.uri.substring('example_template://'.length), | ||
| uri: request.uri, | ||
| ), | ||
| ], | ||
| ); | ||
| }, | ||
| ); | ||
| } | ||
| } |
Oops, something went wrong.
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.
Maybe for these examples, it would be good to add a dartdoc comment at the top that describes what each example is meant to show and a pointer to the
README.md. In general, for examples, these don't have enough comments.It's also helpful when perusing the code in an IDE to have dartdoc links back to the classes that are relevant (e.g. to
MCPServerandPromptsSupportfor this one).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.
I had Gemini add some comments and then cleaned them up a bit, also moved some things around to simplify it.
The version checking for instance doesn't need to happen manually (it is handled for you) and also things can be registered in the constructor instead of initialize which is more concise (no need to override and call super).