### Start OAuth Server Example Source: https://github.com/leehack/mcp_dart/blob/main/example/authentication/OAUTH_QUICK_START.md Run the example OAuth server using Dart. This command starts a local MCP server protected by OAuth, using GitHub as the provider. ```bash dart run example/authentication/oauth_server_example.dart github ``` -------------------------------- ### Install and Run MCP Dart CLI Source: https://github.com/leehack/mcp_dart/blob/main/README.md Install the CLI globally, create a new server project, navigate into it, and start the server. Use `mcp_dart inspect` to test server capabilities. ```bash # Install the CLI dart pub global activate mcp_dart_cli # Create a new project mcp_dart create my_server # Navigate and run cd my_server mcp_dart serve ``` ```bash mcp_dart inspect # List all capabilities mcp_dart inspect --tool add --json-args '{"a": 1, "b": 2}' # Call a tool ``` -------------------------------- ### Run Stdio Examples Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Commands to run the server and client examples using standard input/output streams. ```bash # Stdio examples dart run example/server_stdio.dart dart run example/client_stdio.dart ``` -------------------------------- ### Run GitHub OAuth Example Source: https://github.com/leehack/mcp_dart/blob/main/example/authentication/GITHUB_SETUP.md Navigate to the project directory and execute the Dart script to start the GitHub OAuth example. This will initiate the authentication flow. ```bash cd /path/to/mcp_dart dart run example/authentication/github_oauth_example.dart ``` -------------------------------- ### Run Stdio Server and Client Example Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md This command runs the stdio-based server and client example. The client starts the server over stdio, demonstrating tool invocation, resource reading, prompt retrieval, and shutdown. ```bash dart run example/client_stdio.dart ``` -------------------------------- ### Start MCP Server Source: https://github.com/leehack/mcp_dart/blob/main/example/jaspr-client/README.md Run this command in the terminal to start the interactive task server. Ensure you are in the 'example' directory. ```bash cd example dart run simple_task_interactive_server.dart ``` -------------------------------- ### Run Authentication Examples Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Commands to execute OAuth and GitHub OAuth authentication examples. ```bash # Auth examples dart run example/authentication/oauth_server_example.dart dart run example/authentication/github_oauth_example.dart ``` -------------------------------- ### Run HTTP/SSE Server Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Starts a Server-Sent Events based server. This example includes HTTP server setup, SSE transport configuration, and session management for multiple concurrent connections. ```bash dart run example/server_sse.dart ``` -------------------------------- ### Run GitHub OAuth Client Example Source: https://github.com/leehack/mcp_dart/blob/main/example/authentication/OAUTH_QUICK_START.md Execute the client-side example to initiate the OAuth flow. This will open your browser for authorization and output an access token. ```bash dart run example/authentication/github_oauth_example.dart ``` -------------------------------- ### Run Feature Examples Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Commands to run examples demonstrating specific features like completions and elicitation via HTTP. ```bash # Feature examples dart run example/completions_capability_demo.dart dart run example/elicitation_http_server.dart ``` -------------------------------- ### Installation Configuration Source: https://github.com/leehack/mcp_dart/blob/main/example/flutter_http_client/windows/CMakeLists.txt Configures installation settings, including the bundle directory, install prefix, and destinations for data and libraries. It ensures the 'install' step is default for Visual Studio builds. ```cmake set(BUILD_BUNDLE_DIR "$") set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") ``` -------------------------------- ### Run MCP OAuth Server Example Source: https://github.com/leehack/mcp_dart/blob/main/example/authentication/OAUTH_SERVER_GUIDE.md Execute the MCP OAuth server example, specifying either 'github' or 'google' as the provider. ```bash # GitHub OAuth dart run example/authentication/oauth_server_example.dart github # Google OAuth dart run example/authentication/oauth_server_example.dart google ``` -------------------------------- ### Run Flutter HTTP Client Example Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Instructions to run a Flutter HTTP client example. This involves navigating to the example directory and executing the Flutter run command for a Chrome target. ```bash # Flutter example dart run example/streamable_https/server_streamable_https.dart cd example/flutter_http_client flutter run -d chrome ``` -------------------------------- ### Run OAuth Server Example Source: https://github.com/leehack/mcp_dart/blob/main/example/authentication/README.md Commands to run the OAuth server example for GitHub and Google providers, with options for HTTP (development only) and HTTPS modes. ```bash # GitHub OAuth (HTTP mode - development only) export GITHUB_CLIENT_ID=your_client_id export GITHUB_CLIENT_SECRET=your_client_secret dart run example/authentication/oauth_server_example.dart github # GitHub OAuth (HTTPS mode with self-signed certificate) dart run example/authentication/oauth_server_example.dart github --https # Google OAuth export GOOGLE_CLIENT_ID=your_client_id export GOOGLE_CLIENT_SECRET=your_client_secret dart run example/authentication/oauth_server_example.dart google ``` -------------------------------- ### Run OAuth2 Client Example Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Integrate an OAuth2 client for authorization code flow and PKCE. This example demonstrates token exchange and making authenticated requests. ```bash dart run example/authentication/oauth_client_example.dart ``` -------------------------------- ### Run HTTP and SSE Examples Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Commands to run server examples utilizing HTTP and Server-Sent Events (SSE) for communication. ```bash # HTTP examples dart run example/server_sse.dart dart run example/streamable_https/server_streamable_https.dart ``` -------------------------------- ### Run Google Gemini Client Example Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Set the GEMINI_API_KEY environment variable, navigate to the example directory, and run the Dart script to integrate with the Gemini API. ```bash export GEMINI_API_KEY=your_key cd example/gemini-client dart run ``` -------------------------------- ### CORS Configuration Example Source: https://github.com/leehack/mcp_dart/blob/main/doc/transports.md Demonstrates basic CORS setup for the StreamableHTTPServerTransport. Ensure that the transport is started and connected before handling requests. CORS headers are added internally by the transport. ```dart final transport = StreamableHTTPServerTransport( options: StreamableHTTPServerTransportOptions( sessionIdGenerator: () => generateUUID(), ), ); await transport.start(); await server.connect(transport); await for (final request in httpServer) { await transport.handleRequest(request); // Adds CORS headers internally } ``` -------------------------------- ### Create a basic MCP server Source: https://github.com/leehack/mcp_dart/blob/main/doc/getting-started.md Set up a new MCP server with a name, version, and capabilities. This example demonstrates registering a simple tool and a resource. ```dart import 'package:mcp_dart/mcp_dart.dart'; void main() async { // Create the server final server = McpServer( Implementation( name: 'my-first-server', version: '1.0.0', ), options: McpServerOptions( capabilities: ServerCapabilities( tools: ServerCapabilitiesTools(), resources: ServerCapabilitiesResources(), ), ), ); // Add a simple tool server.registerTool( 'greet', description: 'Greet someone by name', inputSchema: JsonSchema.object( properties: { 'name': JsonSchema.string(description: 'Name of person to greet'), }, required: ['name'], ), callback: (args, extra) async { final name = args['name'] as String; return CallToolResult( content: [ TextContent(text: 'Hello, $name! Welcome to MCP!'), ], ); }, ); // Add a resource server.registerResource( 'Server Info', 'info://server', null, (uri, extra) async => ReadResourceResult( contents: [ TextResourceContents( uri: uri.toString(), text: 'This is my first MCP server!', mimeType: 'text/plain', ), ], ), ); // Connect via stdio print('Starting MCP server...'); final transport = StdioServerTransport(); await server.connect(transport); } ``` -------------------------------- ### Run OAuth2 Server Example Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Execute the complete OAuth2 server implementation with PKCE support. This example covers authorization flow, token management, and secure storage. ```bash dart run example/authentication/oauth_server_example.dart ``` -------------------------------- ### Run Example with AOT Compilation Source: https://github.com/leehack/mcp_dart/blob/main/example/anthropic-client/README.md Execute the pre-compiled AOT executable of the example client. This method is suitable for deployment. ```bash ./app dart ../server_stdio.dart ``` -------------------------------- ### Install Application Bundle Source: https://github.com/leehack/mcp_dart/blob/main/example/flutter_http_client/linux/CMakeLists.txt Defines installation rules for the application bundle. It ensures a clean build directory, installs the executable, data files, libraries, and assets. ```cmake set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Basic MCP Client Setup in Dart Source: https://github.com/leehack/mcp_dart/blob/main/doc/client-guide.md Demonstrates the fundamental setup for an MCP client, including initializing the client, establishing a connection via a transport layer, and cleaning up resources. ```dart import 'package:mcp_dart/mcp_dart.dart'; void main() async { final client = McpClient( Implementation( name: 'my-client', version: '1.0.0', ), ); // Connect to a server final transport = StdioClientTransport( StdioServerParameters( command: 'node', args: ['server.js'], ), ); await client.connect(transport); // Use the server's capabilities // Clean up await client.close(); } ``` -------------------------------- ### Run GitHub OAuth Client Example Source: https://github.com/leehack/mcp_dart/blob/main/example/authentication/OAUTH_SERVER_GUIDE.md Execute the GitHub OAuth client example to obtain an access token. This process involves browser authorization, code exchange, and token saving to a JSON file. ```bash # Run the GitHub OAuth client example dart run example/authentication/github_oauth_example.dart ``` -------------------------------- ### Install Dart SDK and Dependencies Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Commands to install the Dart SDK and project dependencies using Dart Pub. For Flutter projects, use 'flutter pub get'. ```bash # Install Dart SDK # Install dependencies dart pub get # For Flutter examples flutter pub get ``` -------------------------------- ### Basic Server Setup Source: https://github.com/leehack/mcp_dart/blob/main/doc/server-guide.md Sets up a basic MCP server with a name, version, and default capabilities. It then connects the server to a standard input/output transport. ```dart import 'package:mcp_dart/mcp_dart.dart'; void main() async { final server = McpServer( Implementation( name: 'my-server', version: '1.0.0', ), options: McpServerOptions( capabilities: ServerCapabilities( tools: ServerCapabilitiesTools(), resources: ServerCapabilitiesResources(), prompts: ServerCapabilitiesPrompts(), ), ), ); // Register capabilities (tools, resources, prompts) // Connect transport final transport = StdioServerTransport(); await server.connect(transport); } ``` -------------------------------- ### Install Dependencies Source: https://github.com/leehack/mcp_dart/blob/main/AGENTS.md Run this command from the repository root to fetch project dependencies. ```bash dart pub get ``` -------------------------------- ### Run Flutter HTTP Client Server Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Execute the Dart script to start the server for the Flutter HTTP client example. This server is necessary for the Flutter app to communicate. ```bash dart run example/streamable_https/server_streamable_https.dart ``` -------------------------------- ### Run Example with JIT Compilation Source: https://github.com/leehack/mcp_dart/blob/main/example/anthropic-client/README.md Execute the example client using Dart's Just-In-Time (JIT) compilation. This command runs the main Dart script directly. ```bash dart run bin/main.dart dart ../server_stdio.dart ``` -------------------------------- ### Start MCP Server Source: https://github.com/leehack/mcp_dart/blob/main/example/flutter_http_client/README.md Run this command to start the MCP server locally. Ensure you are in the mcp_dart directory. ```shell cd /path/to/mcp_dart dart run example/streamable_https/server_streamable_https.dart ``` -------------------------------- ### Set Environment Variables for Credentials Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Example environment variables required for authenticated examples, including GitHub and LLM API keys. Replace placeholder values with your actual credentials. ```bash # GitHub examples export GITHUB_CLIENT_ID=your_id export GITHUB_CLIENT_SECRET=your_secret export GITHUB_TOKEN=your_pat # LLM examples export ANTHROPIC_API_KEY=your_key export GEMINI_API_KEY=your_key ``` -------------------------------- ### Install Application Target and Data Files Source: https://github.com/leehack/mcp_dart/blob/main/example/flutter_http_client/windows/CMakeLists.txt Installs the main executable, ICU data file, and Flutter library. These components are crucial for the application's runtime. ```cmake install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Run In-Process Communication Example Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Executes a simple stream-based in-process communication example. This is useful for testing and demonstrates client-server communication without external processes. ```bash dart run example/iostream-client-server/simple.dart ``` -------------------------------- ### Compile Example with AOT Source: https://github.com/leehack/mcp_dart/blob/main/example/anthropic-client/README.md Compile the Dart example client into an executable using Ahead-Of-Time (AOT) compilation. This creates a standalone binary. ```bash dart compile exe bin/main.dart -o ./app ``` -------------------------------- ### Initialize and Connect MCP Server Source: https://github.com/leehack/mcp_dart/blob/main/doc/server-guide.md This snippet shows the basic setup for an MCP server, including registering capabilities and connecting to a transport. Ensure all capabilities are registered before connecting. ```dart void main() async { final server = McpServer( Implementation( name: 'my-server', version: '1.0.0', ), options: McpServerOptions( capabilities: ServerCapabilities( tools: ServerCapabilitiesTools(), resources: ServerCapabilitiesResources(), prompts: ServerCapabilitiesPrompts(), ), ), ); // Register all capabilities before connecting _registerTools(server); _registerResources(server); _registerPrompts(server); // Connect transport final transport = StdioServerTransport(); await server.connect(transport); // Server is now running and handling requests } ``` -------------------------------- ### Run Anthropic Claude Client Example Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Set the ANTHROPIC_API_KEY environment variable, navigate to the example directory, and run the Dart script to integrate with the Claude API. ```bash export ANTHROPIC_API_KEY=your_key cd example/anthropic-client dart run ``` -------------------------------- ### Install mcp_dart CLI Source: https://github.com/leehack/mcp_dart/blob/main/packages/mcp_dart_cli/example/example.md Install the CLI globally using Dart's package manager. Ensure Dart SDK is in your PATH. ```bash dart pub global activate mcp_dart_cli ``` -------------------------------- ### Install Dependencies Source: https://github.com/leehack/mcp_dart/blob/main/doc/getting-started.md Run the appropriate command to fetch project dependencies after updating pubspec.yaml. ```bash dart pub get ``` ```bash flutter pub get ``` -------------------------------- ### Run Gemini Client Example (AOT) Source: https://github.com/leehack/mcp_dart/blob/main/example/gemini-client/README.md Execute the pre-compiled Gemini client application (created via AOT compilation) from the command line. ```bash ./gemini_app dart ../server_stdio.dart ``` -------------------------------- ### Set Gemini API Key Source: https://github.com/leehack/mcp_dart/blob/main/example/gemini-client/README.md Before running the example, set your Gemini API key as an environment variable. Obtain your API key from the AI Studio. ```bash export GEMINI_API_KEY=your_api_key ``` -------------------------------- ### Run GitHub OAuth Integration Example Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Integrate with GitHub's OAuth provider for user authentication and API access. Ensure to set GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET environment variables. ```bash # Set environment variables export GITHUB_CLIENT_ID=your_client_id export GITHUB_CLIENT_SECRET=your_secret dart run example/authentication/github_oauth_example.dart ``` -------------------------------- ### Register and Get a Server Prompt Source: https://github.com/leehack/mcp_dart/blob/main/doc/getting-started.md Shows how a server registers a prompt template and how a client retrieves it. ```dart // Server provides a prompt server.registerPrompt( 'code-review', description: 'Review code for issues', argsSchema: { 'language': PromptArgumentDefinition( type: String, description: 'Programming language', required: true, ), }, callback: (args, extra) async => GetPromptResult( messages: [ PromptMessage( role: PromptMessageRole.user, content: TextContent( text: 'Review this ${args['language']} code...', ), ), ], ), ); // Client gets the prompt await client.getPrompt( GetPromptRequest( name: 'code-review', arguments: {'language': 'Dart'}, ), ); ``` -------------------------------- ### Run Flutter Web Client Source: https://github.com/leehack/mcp_dart/blob/main/example/flutter_http_client/README.md Execute this command to launch the Flutter MCP client example in a Chrome browser. ```shell cd /path/to/mcp_dart/example/flutter_http_client flutter run -d chrome ``` -------------------------------- ### Start Jaspr Client Development Server Source: https://github.com/leehack/mcp_dart/blob/main/example/jaspr-client/README.md Navigate to the jaspr-client directory and execute this command to start the development server with hot reload. Access the client at http://localhost:8080. ```bash cd example/jaspr-client dart pub get jaspr serve ``` -------------------------------- ### High-Level Streamable HTTP Server Setup Source: https://github.com/leehack/mcp_dart/blob/main/doc/transports.md Use StreamableMcpServer for a simplified setup that handles server creation, session management, and transport connection. It's suitable for web applications and remote deployments. ```dart import 'package:mcp_dart/mcp_dart.dart'; void main() async { final server = StreamableMcpServer( serverFactory: (sessionId) { // Create a new McpServer instance for each session return McpServer( Implementation(name: 'my-server', version: '1.0.0'), ); }, host: '0.0.0.0', port: 3000, path: '/mcp', // Optional hardening for remote deployments enableDnsRebindingProtection: true, allowedHosts: {'localhost', 'api.example.com'}, allowedOrigins: {'https://app.example.com'}, ); await server.start(); print('Server running on http://0.0.0.0:3000/mcp'); } ``` -------------------------------- ### Run High-Level Streamable Server Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Launches a simplified Streamable HTTP server using `StreamableMcpServer`. This setup includes built-in session management, event store, and automatic transport handling. ```bash dart run example/streamable_https/high_level_server.dart ``` -------------------------------- ### Client Setup Source: https://github.com/leehack/mcp_dart/blob/main/doc/transports.md Initializes an MCP.dart client and connects it to a server using the StreamableHttpClientTransport. Ensure the provided URI points to the MCP endpoint. ```dart final client = McpClient( Implementation(name: 'client', version: '1.0.0'), ); final transport = StreamableHttpClientTransport( Uri.parse('http://localhost:3000/mcp'), ); await client.connect(transport); ``` -------------------------------- ### Register Resources for Pagination Source: https://github.com/leehack/mcp_dart/blob/main/doc/server-guide.md This example shows registering resources on the server. The MCP server automatically handles pagination for client requests, allowing clients to fetch resource lists in chunks. ```dart // Clients can request paginated resource lists // Server automatically handles the pagination server.registerResource(uri: 'resource-1', ...); server.registerResource(uri: 'resource-2', ...); server.registerResource(uri: 'resource-3', ...); // ... many resources // Client requests: // listResources(cursor: null) -> first page // listResources(cursor: 'page2-token') -> second page ``` -------------------------------- ### Compile Gemini Client Example (AOT) Source: https://github.com/leehack/mcp_dart/blob/main/example/gemini-client/README.md Compile the Gemini client application into an executable using Ahead-Of-Time (AOT) compilation. This creates a standalone binary. ```bash dart compile exe bin/main.dart -o ./gemini_app ``` -------------------------------- ### Create Server Source: https://github.com/leehack/mcp_dart/blob/main/doc/quick-reference.md Demonstrates how to create a basic MCP server instance with implementation details. ```APIDOC ## Create Server ### Description Creates a basic MCP server instance. ### Method ```dart final server = McpServer( Implementation( name: 'server-name', version: '1.0.0', ), options: McpServerOptions( capabilities: ServerCapabilities( tools: ServerCapabilitiesTools(), ), ), ); ``` ``` -------------------------------- ### Using GitHub MCP Client in Dart Source: https://github.com/leehack/mcp_dart/blob/main/example/authentication/GITHUB_SETUP.md Examples demonstrate how to use the GitHub MCP client to perform common repository operations. Ensure the client is properly initialized before making calls. ```dart final searchResult = await client.callTool( CallToolRequest( name: 'search_repositories', arguments: {'query': 'mcp server'}, ), ); ``` ```dart final fileResult = await client.callTool( CallToolRequest( name: 'get_file_contents', arguments: { 'owner': 'github', 'repo': 'github-mcp-server', 'path': 'README.md', }, ), ); ``` ```dart final updateResult = await client.callTool( CallToolRequest( name: 'create_or_update_file', arguments: { 'owner': 'your-username', 'repo': 'your-repo', 'path': 'hello.txt', 'content': 'Hello from MCP Dart!', 'message': 'Add hello.txt via MCP', }, ), ); ``` -------------------------------- ### Token Storage Examples in Dart Source: https://github.com/leehack/mcp_dart/blob/main/example/authentication/README.md Demonstrates secure ways to handle authentication tokens in Dart, avoiding hardcoding and utilizing environment variables or secure storage. ```dart // ❌ Bad - hardcoded final authProvider = GitHubPATProvider(token: 'ghp_xxxxx'); // ✅ Good - from environment final authProvider = GitHubPATProvider( token: Platform.environment['GITHUB_TOKEN']!, ); // ✅ Better - from secure storage final token = await secureStorage.read(key: 'github_token'); final authProvider = GitHubPATProvider(token: token); ``` -------------------------------- ### Complete Resource Argument Source: https://github.com/leehack/mcp_dart/blob/main/doc/quick-reference.md This snippet demonstrates how to get completion suggestions for a resource argument. It's useful for providing auto-completion in user interfaces. The example shows completing a 'userId' argument. ```dart final result = await client.complete(CompleteRequest( ref: const ResourceReference( uri: 'users://{organization}/{userId}/profile', ), argument: const ArgumentCompletionInfo( name: 'userId', value: 'al', // Partial ), context: const CompletionContext( arguments: {'organization': 'engineering'}, ), )); for (final value in result.completion.values) { print(value); // alice, alex, alan, ... } ``` -------------------------------- ### Run MCP Server on Multiple Transports Source: https://github.com/leehack/mcp_dart/blob/main/doc/server-guide.md This example demonstrates how to initialize an MCP server and connect it to multiple transports, such as stdio and potentially HTTP (which would typically run in a separate process or isolate). ```dart void main() async { final server = McpServer( Implementation( name: 'multi-transport-server', version: '1.0.0', ), options: McpServerOptions( capabilities: ServerCapabilities( tools: ServerCapabilitiesTools(), resources: ServerCapabilitiesResources(), prompts: ServerCapabilitiesPrompts(), ), ), ); // Register capabilities once _registerCapabilities(server); // Connect stdio transport final stdioTransport = StdioServerTransport(); await server.connect(stdioTransport); // Also listen on HTTP (in a separate process/isolate) // See HTTP transport documentation } ``` -------------------------------- ### Run Flutter HTTP Client App Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Navigate to the Flutter HTTP client example directory and run the Flutter app on Chrome. This demonstrates a cross-platform mobile app with MCP integration. ```bash cd example/flutter_http_client flutter run -d chrome ``` -------------------------------- ### Install mcp_dart_cli Standalone Binary Source: https://github.com/leehack/mcp_dart/blob/main/packages/mcp_dart_cli/README.md Installs the latest standalone binary of mcp_dart_cli using a shell script. This is useful if you do not have the Dart SDK installed. The installation directory can be set using the MCP_DART_INSTALL_DIR environment variable. ```bash curl -fsSL https://raw.githubusercontent.com/leehack/mcp_dart/main/tool/install.sh | sh ``` -------------------------------- ### Run Baseline Project Checks Source: https://github.com/leehack/mcp_dart/blob/main/doc/migration-cookbooks.md Execute these commands after migration to verify project integrity, format code, and analyze for potential issues. Ensure all examples and nested packages are also analyzed. ```bash dart pub get dart format --output=none --set-exit-if-changed lib test dart analyze dart test ``` -------------------------------- ### Install mcp_dart_cli on Windows PowerShell Source: https://github.com/leehack/mcp_dart/blob/main/packages/mcp_dart_cli/README.md Installs the mcp_dart_cli tool on Windows using PowerShell. This command fetches and executes an installation script. ```powershell irm https://raw.githubusercontent.com/leehack/mcp_dart/main/tool/install.ps1 | iex ``` -------------------------------- ### Install AOT Library Source: https://github.com/leehack/mcp_dart/blob/main/example/flutter_http_client/windows/CMakeLists.txt Installs the Ahead-Of-Time (AOT) compilation library, but only for 'Profile' and 'Release' build configurations. This is not installed for 'Debug' builds. ```cmake install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Install Native Assets Source: https://github.com/leehack/mcp_dart/blob/main/example/flutter_http_client/windows/CMakeLists.txt Installs native assets provided by the build.dart script. These assets are copied to the installation directory to be accessible by the application. ```cmake set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Install MCP Developer Skills Source: https://github.com/leehack/mcp_dart/blob/main/packages/mcp_dart_cli/README.md Install a bundled MCP developer skill into your local Codex skill directory using `skills install`. Supports custom target directories. ```bash mcp_dart skills install ``` ```bash mcp_dart skills install --target ~/.codex/skills ``` -------------------------------- ### Get Prompt Source: https://github.com/leehack/mcp_dart/blob/main/doc/quick-reference.md Retrieve a specific prompt by name, with optional arguments, and get the messages. ```APIDOC ## Get Prompt ### Description Retrieve a specific prompt by name, with optional arguments, and get the messages. ### Code ```dart final result = await client.getPrompt(GetPromptRequest( name: 'prompt-name', arguments: {'arg1': 'value'}, )); for (final message in result.messages) { print('${message.role}: ${message.content.text}'); } ``` ``` -------------------------------- ### Install mcp_dart_cli Globally Source: https://github.com/leehack/mcp_dart/blob/main/packages/mcp_dart_cli/README.md Installs the mcp_dart_cli tool globally using the Dart SDK. This command should be run in your terminal. ```bash dart pub global activate mcp_dart_cli ``` -------------------------------- ### MCP Client Configuration Options Source: https://github.com/leehack/mcp_dart/blob/main/doc/client-guide.md Shows how to initialize an MCP client with basic implementation details. Optional handlers for elicitation requests can be set up after client creation. ```dart final client = McpClient( Implementation( name: 'my-client', version: '1.0.0', ), ); // Optional: Handle elicitation requests (user input from server) // Set up handlers after client creation if needed ``` -------------------------------- ### Create a Streamable HTTP Server Source: https://github.com/leehack/mcp_dart/blob/main/example/example.md This example demonstrates how to set up a Streamable HTTP server. It registers an 'echo' tool and handles incoming HTTP requests on port 3000, routing '/mcp' requests to the transport. This is suitable for web-based applications or services. ```dart import 'dart:io'; import 'package:mcp_dart/mcp_dart.dart'; void main() async { final server = McpServer( Implementation(name: "example-http-server", version: "1.0.0"), options: McpServerOptions( capabilities: ServerCapabilities( tools: ServerCapabilitiesTools(), ), ), ); server.registerTool( "echo", description: 'Echoes back the input', inputSchema: JsonSchema.object(properties: { 'message': JsonSchema.string(), }), callback: (args, extra) async { return CallToolResult( content: [TextContent(text: "Echo: ${args['message']}")], ); }, ); final transport = StreamableHTTPServerTransport( options: StreamableHTTPServerTransportOptions()); await server.connect(transport); final httpServer = await HttpServer.bind(InternetAddress.anyIPv4, 3000); print('Server listening on http://localhost:3000/mcp'); await for (final request in httpServer) { if (request.uri.path == '/mcp') { await transport.handleRequest(request); } else { request.response.statusCode = 404; await request.response.close(); } } } ``` -------------------------------- ### Install Bundled Plugin Libraries Source: https://github.com/leehack/mcp_dart/blob/main/example/flutter_http_client/windows/CMakeLists.txt Installs any bundled libraries provided by plugins. This ensures that plugin dependencies are available at runtime. ```cmake if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ``` -------------------------------- ### Register and Call a Server Tool Source: https://github.com/leehack/mcp_dart/blob/main/doc/getting-started.md Demonstrates how a server registers a tool and how a client calls it. ```dart // Server provides a tool server.registerTool( 'search', description: 'Search for information', callback: (args, extra) async { // Perform search return CallToolResult(content: [TextContent(text: results)]); }, ); // Client calls the tool await client.callTool( CallToolRequest( name: 'search', arguments: {'query': 'Dart programming'}, ), ); ``` -------------------------------- ### Create Client Source: https://github.com/leehack/mcp_dart/blob/main/doc/quick-reference.md Instantiate an MCP client with your implementation details. ```APIDOC ## Create Client ### Description Instantiate an MCP client with your implementation details. ### Code ```dart final client = McpClient( Implementation( name: 'client-name', version: '1.0.0', ), ); ``` ``` -------------------------------- ### Create MCP Server with Tools, Resources, and Prompts Source: https://github.com/leehack/mcp_dart/blob/main/llms.txt Instantiate an MCP server, register a tool for calculations, a resource for server status, and a prompt for code reviews. Connects using standard input/output. ```dart import 'package:mcp_dart/mcp_dart.dart'; void main() async { // Create server instance final server = McpServer( Implementation(name: 'my-server', version: '1.0.0'), options: McpServerOptions( capabilities: ServerCapabilities( tools: ServerCapabilitiesTools(), resources: ServerCapabilitiesResources(), prompts: ServerCapabilitiesPrompts(), ), ), ); // Register a tool server.registerTool( 'calculate', description: 'Perform arithmetic operations', inputSchema: ToolInputSchema( properties: { 'operation': JsonSchema.string( enumValues: ['add', 'subtract', 'multiply', 'divide'], ), 'a': JsonSchema.number(), 'b': JsonSchema.number(), }, required: ['operation', 'a', 'b'], ), callback: (args, extra) async { final op = args['operation']; final a = args['a'] as num; final b = args['b'] as num; final result = switch (op) { 'add' => a + b, 'subtract' => a - b, 'multiply' => a * b, 'divide' => b != 0 ? a / b : throw Exception('Division by zero'), _ => throw Exception('Invalid operation'), }; return CallToolResult( content: [TextContent(text: 'Result: $result')], ); }, ); // Register a resource server.registerResource( 'server-status', 'status://server', ResourceMetadata(name: 'Server Status'), (uri, extra) async => ReadResourceResult( contents: [ TextResourceContents( uri: uri.toString(), text: 'Server running at ${DateTime.now()}', mimeType: 'text/plain', ), ], ), ); // Register a prompt server.registerPrompt( 'code-review', description: 'Generate code review prompt', arguments: [ PromptArgument( name: 'language', description: 'Programming language', required: true, ), ], callback: (args, extra) async => GetPromptResult( messages: [ PromptMessage( role: PromptMessageRole.user, content: TextContent( text: 'Review this ${args['language']} code for issues...', ), ), ], ), ); // Connect transport await server.connect(StdioServerTransport()); } ``` -------------------------------- ### Create Project from GitHub Repository using Short Syntax Source: https://github.com/leehack/mcp_dart/blob/main/packages/mcp_dart_cli/example/example.md Utilize the shorthand syntax for GitHub repositories to create a project from a template, including owner, repository, path, and reference. ```bash mcp_dart create my_github_server --template owner/repo/path/to/brick@ref ``` -------------------------------- ### Run Non-Credentialed Examples Smoke Test Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Command to execute a smoke test for non-credentialed examples, typically used for CI and local release validation. ```bash # Non-credentialed smoke checks used by CI/local release validation dart test test/example/non_credentialed_examples_smoke_test.dart ``` -------------------------------- ### Create a Basic McpServer Source: https://github.com/leehack/mcp_dart/blob/main/doc/quick-reference.md Instantiate a basic McpServer with implementation details and server capabilities. ```dart final server = McpServer( Implementation( name: 'server-name', version: '1.0.0', ), options: McpServerOptions( capabilities: ServerCapabilities( tools: ServerCapabilitiesTools(), ), ), ); ``` -------------------------------- ### Create Project from Local Template Source: https://github.com/leehack/mcp_dart/blob/main/packages/mcp_dart_cli/example/example.md Create a new project using a template located on your local filesystem. Specify the path to the template directory. ```bash mcp_dart create my_custom_server --template path/to/my/template ``` -------------------------------- ### Install Flutter Assets Source: https://github.com/leehack/mcp_dart/blob/main/example/flutter_http_client/windows/CMakeLists.txt Installs the Flutter assets directory. It first removes any existing assets to ensure a clean copy, then copies the new assets from the build directory. ```cmake set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) ``` -------------------------------- ### Run Argument Completions Demo Source: https://github.com/leehack/mcp_dart/blob/main/doc/examples.md Execute the demonstration script for argument auto-completion capabilities. This includes resource URI template and prompt argument completion with pagination. ```bash dart run example/completions_capability_demo.dart ``` -------------------------------- ### Create a Stdio Server Source: https://github.com/leehack/mcp_dart/blob/main/example/example.md This snippet shows how to create a basic Stdio server. It registers a 'calculate' tool that performs arithmetic operations based on provided arguments. This is useful for command-line applications or inter-process communication. ```dart import 'package:mcp_dart/mcp_dart.dart'; void main() async { McpServer server = McpServer( Implementation(name: "example-server", version: "1.0.0"), options: McpServerOptions( capabilities: ServerCapabilities( resources: ServerCapabilitiesResources(), tools: ServerCapabilitiesTools(), ), ), ); server.registerTool( "calculate", description: 'Perform basic arithmetic operations', inputSchema: JsonSchema.object( properties: { 'operation': JsonSchema.string( enumValues: ['add', 'subtract', 'multiply', 'divide'], ), 'a': JsonSchema.number(), 'b': JsonSchema.number(), }, required: ['operation', 'a', 'b'], ), callback: (args, extra) async { final operation = args['operation']; final a = args['a']; final b = args['b']; return CallToolResult( content: [ TextContent( text: switch (operation) { 'add' => 'Result: ${a + b}', 'subtract' => 'Result: ${a - b}', 'multiply' => 'Result: ${a * b}', 'divide' => 'Result: ${a / b}', _ => throw Exception('Invalid operation'), }, ), ], ); }, ); server.connect(StdioServerTransport()); } ``` -------------------------------- ### Server Setup (Streamable HTTP) Source: https://github.com/leehack/mcp_dart/blob/main/doc/transports.md Sets up an MCP.dart server using the StreamableHTTPServerTransport. It registers a tool and handles incoming HTTP requests. Ensure the server is bound to a host and port, and requests to '/mcp' are processed by the transport. ```dart import 'dart:io'; import 'package:mcp_dart/mcp_dart.dart'; void main() async { final server = McpServer( Implementation( name: 'http-server', version: '1.0.0', ), options: McpServerOptions( capabilities: ServerCapabilities( tools: ServerCapabilitiesTools(), ), ), ); // Register capabilities server.registerTool( 'example', inputSchema: JsonSchema.object(properties: {}), callback: (args, extra) async { return CallToolResult(content: [TextContent(text: 'ok')]); }, ); final transport = StreamableHTTPServerTransport( options: StreamableHTTPServerTransportOptions( sessionIdGenerator: () => generateUUID(), eventStore: InMemoryEventStore(), enableDnsRebindingProtection: true, allowedHosts: {'localhost'}, allowedOrigins: {'http://localhost:5173'}, ), ); await transport.start(); await server.connect(transport); // Create HTTP server final httpServer = await HttpServer.bind('localhost', 3000); print('Server listening on http://localhost:3000/mcp'); await for (final request in httpServer) { if (request.uri.path != '/mcp') { request.response ..statusCode = HttpStatus.notFound ..write('Not Found'); await request.response.close(); continue; } await transport.handleRequest(request); } } ``` -------------------------------- ### First Run Output (No Tokens) Source: https://github.com/leehack/mcp_dart/blob/main/example/authentication/GITHUB_SETUP.md This output is observed when running the example for the first time without any existing OAuth tokens. It shows the process of initiating the OAuth flow, including the authorization URL and successful connection. ```text GitHub MCP Server - OAuth Authentication Example Connecting to GitHub MCP server... No existing tokens found. Starting OAuth flow... Please authorize this application in your browser: https://github.com/login/oauth/authorize?client_id=... ✓ Authorization successful! ✓ Connected to GitHub MCP server! Server: github-mcp-server | Version: 1.0.0 ✓ Found X tools: create_or_update_file, search_repositories, get_file_contents... ``` -------------------------------- ### Initialize MCP Client and Call Tool Source: https://github.com/leehack/mcp_dart/blob/main/example/flutter_http_client/example_page.html Shows how to create a StreamableHttpClientTransport, initialize the MCP client, and call a tool with streaming notifications. Ensure the test server is running before executing. ```dart // Create a transport final transport = StreamableHttpClientTransport( serverUrl: 'http://localhost:3000/mcp', ); // Create MCP client final client = Client(transport: transport); // Initialize client await client.initialize(); // Call a tool with streaming notifications final result = await client.callTool( 'processText', {'text': 'Hello, world!'}, ToolCallOptions( streamNotifications: true, notificationHandler: (notification) { print('Notification: ${notification.data}'); }, ), ); ``` -------------------------------- ### Initialize MCP Server with Capabilities Source: https://github.com/leehack/mcp_dart/blob/main/doc/quick-reference.md Instantiate an McpServer, optionally defining server capabilities. Capabilities can also be auto-detected from registrations. ```dart final server = McpServer( Implementation(name: 'server', version: '1.0.0'), // Capabilities auto-detected from registrations options: McpServerOptions( capabilities: ServerCapabilities( tools: ServerCapabilitiesTools(), ), ), ); ``` -------------------------------- ### Throw McpError Source: https://github.com/leehack/mcp_dart/blob/main/AGENTS.md Example of throwing a protocol-specific error using McpError and ErrorCode. ```dart throw McpError(ErrorCode.invalidParams.value, "Message text"); ``` -------------------------------- ### Call Tool Source: https://github.com/leehack/mcp_dart/blob/main/doc/quick-reference.md Invoke a specific tool with provided arguments and get the result. ```APIDOC ## Call Tool ### Description Invoke a specific tool with provided arguments and get the result. ### Code ```dart final result = await client.callTool( CallToolRequest( name: 'tool-name', arguments: {'param': 'value'}, ), ); print(result.content.first.text); ``` ``` -------------------------------- ### Initialize MCP Client with Capabilities Source: https://github.com/leehack/mcp_dart/blob/main/doc/quick-reference.md Instantiate an McpClient, configuring client capabilities for sampling, roots, and elicitation. ```dart final client = McpClient( Implementation(name: 'client', version: '1.0.0'), options: McpClientOptions( capabilities: ClientCapabilities( sampling: ClientCapabilitiesSampling(tools: true), roots: ClientCapabilitiesRoots(listChanged: true), elicitation: ClientElicitation( form: ClientElicitationForm(applyDefaults: true), ), ), ), ); ``` -------------------------------- ### Create MCP Project from Local Template Path Source: https://github.com/leehack/mcp_dart/blob/main/packages/templates/README.md Create a new MCP project using a template located on your local file system. Provide the relative or absolute path to the template directory. ```bash dart bin/mcp_dart.dart create my_project --template ./my_local_brick ``` -------------------------------- ### List Resources Source: https://github.com/leehack/mcp_dart/blob/main/doc/quick-reference.md Get a list of resources, including their names, URIs, sizes, and last modified dates. ```APIDOC ## List Resources ### Description Get a list of resources, including their names, URIs, sizes, and last modified dates. ### Code ```dart final result = await client.listResources(); for (final resource in result.resources) { print('${resource.name}: ${resource.uri}'); print('size: ${resource.size ?? "unknown"}'); print('lastModified: ${resource.annotations?.lastModified}'); } ``` ``` -------------------------------- ### Get a Prompt with mcp_dart inspect Source: https://github.com/leehack/mcp_dart/blob/main/packages/mcp_dart_cli/README.md Retrieve a prompt from the MCP server by providing its name and JSON-formatted arguments. ```bash mcp_dart inspect --prompt greeting --json-args '{"name": "World"}' ``` -------------------------------- ### Install MCP Dart Dependency Source: https://github.com/leehack/mcp_dart/blob/main/llms.txt Run the appropriate command to fetch the MCP Dart dependency after adding it to pubspec.yaml. ```bash dart pub get # For Dart projects flutter pub get # For Flutter projects ``` -------------------------------- ### Test Tool Execution in Dart Source: https://github.com/leehack/mcp_dart/blob/main/doc/tools.md Demonstrates how to set up a test server, register a tool with an input schema, and call the tool using a test client. Ensure the 'test' package is imported. ```dart import 'package:test/test.dart'; void main() { test('tool execution', () async { // Setup final server = McpServer( Implementation(name: 'test', version: '1.0.0'), ); server.registerTool( 'add', inputSchema: JsonSchema.object( properties: { 'a': JsonSchema.number(), 'b': JsonSchema.number(), }, ), callback: (args, extra) async { final sum = (args['a'] as num) + (args['b'] as num); return CallToolResult( content: [TextContent(text: '$sum')], ); }, ); // Create client and connect (see Stream transport) final client = await createTestClient(server); // Test final result = await client.callTool(CallToolRequest( name: 'add', arguments: {'a': 5, 'b': 3}, )); expect(result.content.first.text, '8'); }); } ``` -------------------------------- ### Create a Streamable McpServer Source: https://github.com/leehack/mcp_dart/blob/main/doc/quick-reference.md Set up a StreamableMcpServer that listens for connections on a specified host and port. Optional hardening options are available for browser deployments. ```dart final server = StreamableMcpServer( serverFactory: (sessionId) => McpServer( Implementation(name: 'server', version: '1.0.0'), ), host: '0.0.0.0', port: 3000, path: '/mcp', // Optional hardening for browser-accessible deployments enableDnsRebindingProtection: true, allowedHosts: {'localhost', 'api.example.com'}, allowedOrigins: {'https://app.example.com'}, ); await server.start(); ``` -------------------------------- ### Register Tool with Validation Source: https://github.com/leehack/mcp_dart/blob/main/doc/quick-reference.md Register a tool that includes input validation. This example demonstrates division by zero checking. ```dart server.registerTool( 'divide', inputSchema: JsonSchema.object( properties: { 'a': JsonSchema.number(), 'b': JsonSchema.number(), }, ), callback: (args, extra) async { final a = args['a'] as num; final b = args['b'] as num; if (b == 0) { return CallToolResult( isError: true, content: [TextContent(text: 'Division by zero')], ); } return CallToolResult( content: [TextContent(text: '${a / b}')], ); }, ); ``` -------------------------------- ### Create New MCP Server Project Source: https://github.com/leehack/mcp_dart/blob/main/packages/mcp_dart_cli/example/example.md Create a new MCP server project using the default template. Navigate into the created directory to manage the project. ```bash mcp_dart create my_mcp_server ```