### MCP Resource Management Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Explains how to interact with resources provided by MCP servers. This includes listing, reading, getting resources using templates, subscribing to updates, and unsubscribing. ```dart // List available resources final resources = await client.listResources(); _logger.debug('Available resources: ${resources.map((r) => r.name).join(', ')}'); // Read a resource final resourceResult = await client.readResource('file:///path/to/file.txt'); final content = resourceResult.contents.first; _logger.debug('Resource content: ${content.text}'); // Get a resource using a template final templateResult = await client.getResourceWithTemplate('file:///{path}', { 'path': 'example.txt' }); _logger.debug('Template result: ${templateResult.contents.first.text}'); // Subscribe to resource updates await client.subscribeResource('file:///path/to/file.txt'); client.onResourceContentUpdated((uri, content) { _logger.debug('Resource updated: $uri'); _logger.debug('New content: ${content.text}'); }); // Unsubscribe when no longer needed await client.unsubscribeResource('file:///path/to/file.txt'); ``` -------------------------------- ### List, Get, and Process Prompts with MCP Client Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Demonstrates how to list available prompts, get a specific prompt's result by providing code and language, and process the text content of the prompt's messages using the MCP client. ```dart final prompts = await client.listPrompts(); _logger.debug('Available prompts: ${prompts.map((p) => p.name).join(', ')}'); final promptResult = await client.getPrompt('analyze-code', { 'code': 'function add(a, b) { return a + b; }', 'language': 'javascript', }); for (final message in promptResult.messages) { final content = message.content; if (content is TextContent) { _logger.debug('${message.role}: ${content.text}'); } } ``` -------------------------------- ### Install MCP Client Package Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md This snippet shows how to add the mcp_client package as a dependency to your Flutter or Dart project's pubspec.yaml file, or how to install it using the dart pub add command. ```yaml dependencies: mcp_client: ^1.0.1 ``` ```bash dart pub add mcp_client ``` -------------------------------- ### MCP Tool Execution Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Provides examples for executing tools exposed by MCP servers. This covers listing available tools, calling tools with parameters, tracking long-running operations, and cancelling operations. ```dart // List available tools final tools = await client.listTools(); _logger.debug('Available tools: ${tools.map((t) => t.name).join(', ')}'); // Call a tool final result = await client.callTool('search-web', { 'query': 'Model Context Protocol', 'maxResults': 5, }); // Call a tool with progress tracking final trackingResult = await client.callToolWithTracking('long-running-operation', { 'parameter': 'value' }); final operationId = trackingResult.operationId; // Register progress handler client.onProgress((requestId, progress, message) { _logger.debug('Operation $requestId: $progress% - $message'); }); // Process the result final content = result.content.first; if (content is TextContent) { _logger.debug('Search results: ${content.text}'); } // Cancel an operation if needed await client.cancelOperation(operationId); ``` -------------------------------- ### Configure Streamable HTTP Transport Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Shows how to configure the Streamable HTTP transport for high-performance HTTP/2 communication. This includes basic setup, setting timeouts, managing concurrent requests, enabling HTTP/2, configuring OAuth, and enabling compression and heartbeats. ```Dart final transportConfig = TransportConfig.streamableHttp( baseUrl: 'https://api.example.com', headers: {'User-Agent': 'MCP-Client/1.0'}, ); ``` ```Dart final transportConfig = TransportConfig.streamableHttp( baseUrl: 'https://api.example.com', headers: {'User-Agent': 'MCP-Client/1.0'}, timeout: const Duration(seconds: 60), maxConcurrentRequests: 20, useHttp2: true, oauthConfig: OAuthConfig( authorizationEndpoint: 'https://auth.example.com/authorize', tokenEndpoint: 'https://auth.example.com/token', clientId: 'your-client-id', ), enableCompression: true, heartbeatInterval: const Duration(seconds: 60), ); ``` -------------------------------- ### Configure Server-Sent Events (SSE) Transport Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Demonstrates how to configure Server-Sent Events (SSE) transport for the MCP client. This includes basic setup, authentication with Bearer tokens or OAuth, enabling compression (Gzip, Deflate), and configuring heartbeat monitoring for connection health. ```Dart final transportConfig = TransportConfig.sse( serverUrl: 'http://localhost:8080/sse', headers: {'User-Agent': 'MCP-Client/1.0'}, ); ``` ```Dart final transportConfig = TransportConfig.sse( serverUrl: 'https://secure-api.example.com/sse', bearerToken: 'your-bearer-token', headers: {'User-Agent': 'MCP-Client/1.0'}, ); ``` ```Dart final transportConfig = TransportConfig.sse( serverUrl: 'https://api.example.com/sse', oauthConfig: OAuthConfig( authorizationEndpoint: 'https://auth.example.com/authorize', tokenEndpoint: 'https://auth.example.com/token', clientId: 'your-client-id', ), ); ``` ```Dart final transportConfig = TransportConfig.sse( serverUrl: 'http://localhost:8080/sse', enableCompression: true, enableGzip: true, enableDeflate: true, ); ``` ```Dart final transportConfig = TransportConfig.sse( serverUrl: 'http://localhost:8080/sse', heartbeatInterval: const Duration(seconds: 30), maxMissedHeartbeats: 3, ); ``` -------------------------------- ### Check MCP Server Health Status Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Provides an example of how to check the health status of connected MCP servers, retrieving information such as whether the server is running, the number of connected sessions, registered tools, and server uptime. ```dart final health = await client.healthCheck(); _logger.debug('Server running: ${health.isRunning}'); _logger.debug('Connected sessions: ${health.connectedSessions}'); _logger.debug('Registered tools: ${health.registeredTools}'); _logger.debug('Uptime: ${health.uptime.inMinutes} minutes'); ``` -------------------------------- ### MCP Client Creation Methods Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Illustrates different ways to create an MCP client instance. It shows using unified configuration with production settings and capabilities, as well as manual client creation. ```dart // Method 1: Using unified configuration final config = McpClient.productionConfig( name: 'My App', version: '1.0.0', capabilities: ClientCapabilities( roots: true, rootsListChanged: true, sampling: true, ), ); final clientResult = await McpClient.createAndConnect( config: config, transportConfig: transportConfig, ); // Method 2: Manual client creation final client = McpClient.createClient(config); ``` -------------------------------- ### Basic MCP Client Usage Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Demonstrates the fundamental steps to create, connect, and use an MCP client. This includes setting up client and transport configurations, listing tools, calling a tool, and disconnecting. ```dart import 'package:mcp_client/mcp_client.dart'; void main() async { // Create client configuration final config = McpClient.simpleConfig( name: 'Example Client', version: '1.0.0', enableDebugLogging: true, ); // Create transport configuration final transportConfig = TransportConfig.stdio( command: 'npx', arguments: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/allowed/directory'], ); // Create and connect client final clientResult = await McpClient.createAndConnect( config: config, transportConfig: transportConfig, ); final client = clientResult.fold( (c) => c, (error) => throw Exception('Failed to connect: $error'), ); // List available tools on the server final tools = await client.listTools(); print('Available tools: ${tools.map((t) => t.name).join(', ')}'); // Call a tool final result = await client.callTool('calculator', { 'operation': 'add', 'a': 5, 'b': 3, }); print('Result: ${(result.content.first as TextContent).text}'); // Disconnect when done client.disconnect(); } ``` -------------------------------- ### Set Up Dart Logging Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Provides instructions on setting up and using the standard Dart logging package within the MCP client. This includes configuring the root logger level, listening for log records, creating component-specific loggers, and logging messages at various severity levels. ```Dart import 'package:logging/logging.dart'; Logger.root.level = Level.INFO; Logger.root.onRecord.listen((record) { print('${record.level.name}: ${record.time}: ${record.message}'); }); final Logger _logger = Logger('mcp_client.example'); _logger.fine('Debugging information'); _logger.info('Important information'); _logger.warning('Warning message'); _logger.severe('Error message'); ``` ```Dart final config = McpClient.simpleConfig( name: 'My Client', version: '1.0.0', enableDebugLogging: true, // This enables detailed transport logging ); ``` -------------------------------- ### Manage Filesystem Roots with MCP Client Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Shows how to add, list, and remove filesystem roots using the MCP client. It also includes registering a callback for changes in the roots list. ```dart await client.addRoot(Root( uri: 'file:///path/to/allowed/directory', name: 'Project Files', description: 'Files for the current project', )); final roots = await client.listRoots(); _logger.debug('Configured roots: ${roots.map((r) => r.name).join(', ')}'); await client.removeRoot('file:///path/to/allowed/directory'); client.onRootsListChanged(() { _logger.debug('Roots list has changed'); client.listRoots().then((roots) { _logger.debug('New roots: ${roots.map((r) => r.name).join(', ')}'); }); }); ``` -------------------------------- ### Configure and Connect MCP Client via Standard I/O Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Demonstrates two methods for configuring and connecting an MCP client using the Standard I/O transport. This includes setting up client configuration, transport configuration with command and arguments, and handling connection results. ```dart // Method 1: Using createAndConnect final config = McpClient.simpleConfig(name: 'STDIO Client', version: '1.0.0'); final transportConfig = TransportConfig.stdio( command: 'npx', arguments: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/allowed/directory'], workingDirectory: '/path/to/working/directory', environment: {'ENV_VAR': 'value'}, ); final clientResult = await McpClient.createAndConnect( config: config, transportConfig: transportConfig, ); // Method 2: Manual transport creation final transportResult = await McpClient.createStdioTransport( command: 'npx', arguments: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/allowed/directory'], ); final transport = transportResult.fold((t) => t, (error) => throw error); await client.connect(transport); ``` -------------------------------- ### Perform LLM Text Generation (Sampling) with MCP Client Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Illustrates how to create a sampling request with messages, model preferences, and generation parameters, send it to the MCP client, and process the response. It also covers registering for sampling response callbacks. ```dart final request = CreateMessageRequest( messages: [ Message( role: 'user', content: TextContent(text: 'What is the Model Context Protocol?'), ), ], modelPreferences: ModelPreferences( hints: [ ModelHint(name: 'claude-3-sonnet'), ModelHint(name: 'claude-3-opus'), ], intelligencePriority: 0.8, speedPriority: 0.4, ), maxTokens: 1000, temperature: 0.7, ); final result = await client.createMessage(request); _logger.debug('Model used: ${result.model}'); _logger.debug('Response: ${(result.content as TextContent).text}'); client.onSamplingResponse((requestId, result) { _logger.debug('Sampling response for request $requestId:'); _logger.debug('Model: ${result.model}'); _logger.debug('Content: ${(result.content as TextContent).text}'); }); ``` -------------------------------- ### Handle MCP Client Event Notifications Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Demonstrates how to register event handlers for changes in the MCP client's state, such as updates to the tools list, resources list, and prompts list. It also shows how to handle server-sent logging messages. ```Dart client.onToolsListChanged(() { _logger.debug('Tools list has changed'); client.listTools().then((tools) { _logger.debug('New tools: ${tools.map((t) => t.name).join(', ')}'); }); }); ``` ```Dart client.onResourcesListChanged(() { _logger.debug('Resources list has changed'); client.listResources().then((resources) { _logger.debug('New resources: ${resources.map((r) => r.name).join(', ')}'); }); }); ``` ```Dart client.onPromptsListChanged(() { _logger.debug('Prompts list has changed'); client.listPrompts().then((prompts) { _logger.debug('New prompts: ${prompts.map((p) => p.name).join(', ')}'); }); }); ``` ```Dart client.onLogging((level, message, logger, data) { _logger.debug('Server log [$level]${logger != null ? " [$logger]" : ""}: $message'); if (data != null) { _logger.debug('Additional data: $data'); } }); ``` -------------------------------- ### Dart: Catch MCP Protocol Errors with Try-Catch Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Shows how to implement traditional try-catch blocks in Dart to handle specific McpError exceptions, including those related to calling tools, and also catches any other unexpected errors. ```dart try { await client.callTool('unknown-tool', {}); } on McpError catch (e) { print('MCP error (${e.code}): ${e.message}'); } catch (e) { print('Unexpected error: $e'); } ``` -------------------------------- ### MCP Connection State Monitoring Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Details how to monitor the connection status of an MCP client using event streams. It covers listening for connection, disconnection, and error events, and includes cleanup. ```dart // Listen for connection events client.onConnect.listen((serverInfo) { _logger.info('Connected to ${serverInfo.name} v${serverInfo.version}'); _logger.info('Protocol version: ${serverInfo.protocolVersion}'); // Initialize your application after connection }); // Listen for disconnection events client.onDisconnect.listen((reason) { _logger.info('Disconnected: $reason'); // Handle different disconnect reasons switch (reason) { case DisconnectReason.transportError: // Attempt reconnection break; case DisconnectReason.serverDisconnected: // Show notification to user break; case DisconnectReason.clientDisconnected: // Normal shutdown break; } }); // Listen for error events client.onError.listen((error) { _logger.error('Error: ${error.message}'); // Log errors or show to user }); // Clean up resources when done client.dispose(); ``` -------------------------------- ### Dart: Handle Client Connection Errors with Result Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Demonstrates how to use the Result type to handle potential errors during the creation and connection of an McpClient. It shows how to process a successful connection or a failure, including throwing the error. ```dart final clientResult = await McpClient.createAndConnect( config: config, transportConfig: transportConfig, ); final client = clientResult.fold( (client) { print('Successfully connected'); return client; }, (error) { print('Connection failed: $error'); throw error; }, ); ``` -------------------------------- ### Dart: Handle Transport Creation Errors with Result Source: https://github.com/app-appplayer/mcp_client/blob/main/README.md Illustrates the use of the Result type for managing errors that may occur during the creation of an stdio transport for McpClient. It covers successful transport connection and error scenarios. ```dart final transportResult = await McpClient.createStdioTransport( command: 'npx', arguments: ['-y', '@modelcontextprotocol/server-filesystem'], ); await transportResult.fold( (transport) async { await client.connect(transport); print('Connected successfully'); }, (error) { print('Transport creation failed: $error'); }, ); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.