### Configure MCP Server Connection and Client Source: https://context7.com/nischhal-applore/flutter-mcp-docs/llms.txt Sets up a configured MCP client with specified server URL, API key, timeout, retry settings, and logging. Includes connection testing and server information retrieval. It supports environment-specific configurations for development and production. ```dart import 'package:flutter_mcp/flutter_mcp.dart'; class McpConfiguration { final String serverUrl; final String? apiKey; final Duration timeout; final int maxRetries; final bool enableLogging; McpConfiguration({ required this.serverUrl, this.apiKey, this.timeout = const Duration(seconds: 30), this.maxRetries = 3, this.enableLogging = false, }); } Future createConfiguredClient( McpConfiguration config, ) async { try { final client = McpClient( serverUrl: config.serverUrl, apiKey: config.apiKey, timeout: config.timeout, retryConfig: RetryConfig( maxAttempts: config.maxRetries, backoffMultiplier: 2.0, initialDelay: Duration(seconds: 1), ), logLevel: config.enableLogging ? LogLevel.debug : LogLevel.error, interceptors: [ LoggingInterceptor(), AuthInterceptor(apiKey: config.apiKey), RetryInterceptor(), ], ); // Test connection await client.connect(); final info = await client.getServerInfo(); print('Connected to ${info.name} v${info.version}'); print('Capabilities: ${info.capabilities}'); return client; } catch (e) { print('Configuration failed: $e'); rethrow; } } // Environment-specific configuration Future main() async { final devConfig = McpConfiguration( serverUrl: 'http://localhost:3000/mcp', apiKey: 'dev_key', enableLogging: true, ); final prodConfig = McpConfiguration( serverUrl: 'https://api.production.com/mcp', apiKey: 'prod_key_secure', timeout: Duration(seconds: 60), maxRetries: 5, ); final client = await createConfiguredClient( const bool.fromEnvironment('dart.vm.product') ? prodConfig : devConfig, ); // Use client final tools = await client.listTools(); print('Available tools: ${tools.length}'); } ``` -------------------------------- ### Initialize MCP Client in Flutter Source: https://context7.com/nischhal-applore/flutter-mcp-docs/llms.txt Initializes an MCP client to establish communication with MCP servers. It requires the server URL, an API key, and a timeout duration. This function connects to the server and lists available tools and resources. ```dart import 'package:flutter_mcp/flutter_mcp.dart'; Future initializeMcpClient() async { try { final client = McpClient( serverUrl: 'http://localhost:3000/mcp', apiKey: 'your_api_key_here', timeout: Duration(seconds: 30), ); await client.connect(); // List available tools final tools = await client.listTools(); print('Available tools: ${tools.map((t) => t.name).join(", ")}'); // List available resources final resources = await client.listResources(); print('Available resources: ${resources.length} resources found'); } catch (e) { print('Failed to initialize MCP client: $e'); } } ``` -------------------------------- ### Send Prompts with Context in Dart Source: https://context7.com/nischhal-applore/flutter-mcp-docs/llms.txt Sends prompts to LLMs with MCP context, including tools and resources for enhanced AI responses. It handles basic tool calls and returns the content from the LLM. Dependencies include the flutter_mcp package. ```dart import 'package:flutter_mcp/flutter_mcp.dart'; Future sendPromptWithContext( McpClient client, String userMessage, List resourceUris, ) async { try { final prompt = McpPrompt( messages: [ McpMessage( role: 'user', content: userMessage, ), ], resources: resourceUris, tools: ['read_file', 'search_database', 'web_search'], maxTokens: 1000, ); final response = await client.sendPrompt(prompt); // Handle tool calls if present if (response.toolCalls.isNotEmpty) { for (final toolCall in response.toolCalls) { print('Tool call: ${toolCall.name} with ${toolCall.arguments}'); final toolResult = await client.callTool( name: toolCall.name, arguments: toolCall.arguments, ); print('Tool result: ${toolResult.content}'); } } return response.content; } catch (e) { print('Error sending prompt: $e'); return 'Failed to get response'; } } // Complete example void main() async { final client = McpClient( serverUrl: 'http://localhost:3000/mcp', apiKey: 'sk-abc123', ); await client.connect(); final response = await sendPromptWithContext( client, 'Summarize the contents of my project files', ['file:///project/README.md', 'file:///project/src/main.dart'], ); print('AI Response: $response'); } ``` -------------------------------- ### Implement and Register Custom Tools for MCP Source: https://context7.com/nischhal-applore/flutter-mcp-docs/llms.txt Defines a custom tool ('calculate_distance') implementing the McpTool interface, including its name, description, input schema, and execution logic using the Haversine formula. It also demonstrates registering multiple custom tools with the MCP client. ```dart import 'package:flutter_mcp/flutter_mcp.dart'; import 'dart:math'; // Required for pi, sin, cos, atan2, sqrt class CustomTool implements McpTool { @override String get name => 'calculate_distance'; @override String get description => 'Calculate distance between two coordinates'; @override Map get inputSchema => { 'type': 'object', 'properties': { 'lat1': {'type': 'number', 'description': 'First latitude'}, 'lon1': {'type': 'number', 'description': 'First longitude'}, 'lat2': {'type': 'number', 'description': 'Second latitude'}, 'lon2': {'type': 'number', 'description': 'Second longitude'}, 'unit': {'type': 'string', 'enum': ['km', 'miles'], 'default': 'km'}, }, 'required': ['lat1', 'lon1', 'lat2', 'lon2'], }; @override Future execute(Map arguments) async { try { final lat1 = arguments['lat1'] as double; final lon1 = arguments['lon1'] as double; final lat2 = arguments['lat2'] as double; final lon2 = arguments['lon2'] as double; final unit = arguments['unit'] as String? ?? 'km'; // Haversine formula const R = 6371; // Earth's radius in km final dLat = _toRadians(lat2 - lat1); final dLon = _toRadians(lon2 - lon1); final a = sin(dLat / 2) * sin(dLat / 2) + cos(_toRadians(lat1)) * cos(_toRadians(lat2)) * sin(dLon / 2) * sin(dLon / 2); final c = 2 * atan2(sqrt(a), sqrt(1 - a)); var distance = R * c; if (unit == 'miles') { distance *= 0.621371; } return ToolResult.success({ 'distance': distance, 'unit': unit, 'from': {'lat': lat1, 'lon': lon1}, 'to': {'lat': lat2, 'lon': lon2}, }); } catch (e) { return ToolResult.error('Calculation failed: $e'); } } double _toRadians(double degrees) => degrees * pi / 180; } // Assume WeatherTool and DatabaseQueryTool are defined elsewhere class WeatherTool implements McpTool { @override String get name => 'get_weather'; @override String get description => 'Get weather information'; @override Map get inputSchema => {}; @override Future execute(Map arguments) async { return ToolResult.success({'condition': 'sunny'}); } } class DatabaseQueryTool implements McpTool { @override String get name => 'query_database'; @override String get description => 'Query a database'; @override Map get inputSchema => {}; @override Future execute(Map arguments) async { return ToolResult.success({'data': 'sample data'}); } } // Register and use custom tool Future setupCustomTools(McpClient client) async { final toolRegistry = ToolRegistry(); toolRegistry.register(CustomTool()); toolRegistry.register(WeatherTool()); toolRegistry.register(DatabaseQueryTool()); await client.setToolRegistry(toolRegistry); // Test tool execution final result = await client.callTool( name: 'calculate_distance', arguments: { 'lat1': 40.7128, 'lon1': -74.0060, // New York 'lat2': 51.5074, 'lon2': -0.1278, // London 'unit': 'miles', }, ); print('Distance: ${result.content['distance']} ${result.content['unit']}'); } ``` -------------------------------- ### Subscribe to Resource Updates in Dart Source: https://context7.com/nischhal-applore/flutter-mcp-docs/llms.txt Subscribes to real-time updates from MCP resources to keep Flutter UI synchronized with data changes. It uses Dart Streams for efficient handling of updates. Dependencies include the flutter_mcp package. ```dart import 'package:flutter_mcp/flutter_mcp.dart'; import 'dart:async'; StreamSubscription subscribeToResource( McpClient client, String resourceUri, Function(ResourceUpdate) onUpdate, ) { try { final subscription = client.subscribeToResource(resourceUri).listen( (update) { print('Resource updated: ${update.uri}'); print('Update type: ${update.type}'); print('New content: ${update.content}'); onUpdate(update); }, onError: (error) { print('Subscription error: $error'); }, onDone: () { print('Subscription closed'); }, ); return subscription; } catch (e) { print('Failed to subscribe: $e'); rethrow; } } // Flutter widget example class ResourceMonitorWidget extends StatefulWidget { @override _ResourceMonitorWidgetState createState() => _ResourceMonitorWidgetState(); } class _ResourceMonitorWidgetState extends State { late McpClient client; StreamSubscription? subscription; String content = 'Loading...'; @override void initState() { super.initState(); client = McpClient(serverUrl: 'http://localhost:3000/mcp'); _initialize(); } Future _initialize() async { await client.connect(); subscription = subscribeToResource( client, 'file:///data/live_feed.json', (update) { setState(() { content = update.content.toString(); }); }, ); } @override void dispose() { subscription?.cancel(); client.disconnect(); super.dispose(); } @override Widget build(BuildContext context) { return Text(content); } } ``` -------------------------------- ### Execute Tool Calls with MCP Client Source: https://context7.com/nischhal-applore/flutter-mcp-docs/llms.txt Executes a tool registered with the MCP server, passing the tool's name and arguments. It handles potential errors during execution, including MCP-specific exceptions and timeouts. The function returns the content of the tool's result. ```dart import 'package:flutter_mcp/flutter_mcp.dart'; Future> executeToolCall( McpClient client, String toolName, Map arguments, ) async { try { final result = await client.callTool( name: toolName, arguments: arguments, ); if (result.isError) { throw Exception('Tool execution failed: ${result.error}'); } print('Tool executed successfully: ${result.content}'); return result.content as Map; } on McpException catch (e) { print('MCP Error: ${e.message}'); rethrow; } on TimeoutException catch (e) { print('Request timed out: $e'); rethrow; } } // Usage example void main() async { final client = McpClient(serverUrl: 'http://localhost:3000/mcp'); await client.connect(); final result = await executeToolCall( client, 'read_file', {'path': '/documents/notes.txt'}, ); print('File contents: ${result['content']}'); } ``` -------------------------------- ### Dart: MCP Error Handling with Retries Source: https://context7.com/nischhal-applore/flutter-mcp-docs/llms.txt Provides a class `McpErrorHandler` to manage MCP operation errors. It supports customizable retry counts, delays, and error callbacks. This is crucial for network-dependent operations to ensure resilience against transient failures. ```dart import 'package:flutter_mcp/flutter_mcp.dart'; import 'dart:async'; enum McpErrorType { connection, authentication, timeout, toolExecution, resourceAccess, unknown, } class McpError extends Error { final McpErrorType type; final String message; McpError(this.type, this.message); @override String toString() => 'McpError($type: $message)'; } class McpErrorHandler { static Future handleMcpOperation( Future Function() operation, { int maxRetries = 3, Duration retryDelay = const Duration(seconds: 2), Function(McpErrorType, String)? onError, } ) async { int attempts = 0; while (attempts < maxRetries) { try { return await operation(); } on McpConnectionException catch (e) { attempts++; final errorType = McpErrorType.connection; final message = 'Connection failed: ${e.message}'; onError?.call(errorType, message); if (attempts >= maxRetries) { throw McpError(errorType, message); } await Future.delayed(retryDelay * attempts); } on McpAuthenticationException catch (e) { final errorType = McpErrorType.authentication; final message = 'Authentication failed: ${e.message}'; onError?.call(errorType, message); throw McpError(errorType, message); } on TimeoutException catch (e) { attempts++; final errorType = McpErrorType.timeout; final message = 'Request timed out: $e'; onError?.call(errorType, message); if (attempts >= maxRetries) { throw McpError(errorType, message); } await Future.delayed(retryDelay * attempts); } on McpToolException catch (e) { final errorType = McpErrorType.toolExecution; final message = 'Tool execution failed: ${e.message}'; onError?.call(errorType, message); throw McpError(errorType, message); } catch (e) { final errorType = McpErrorType.unknown; final message = 'Unexpected error: $e'; onError?.call(errorType, message); throw McpError(errorType, message); } } throw McpError(McpErrorType.unknown, 'Operation failed after $maxRetries attempts'); } } // Usage in Flutter app example: class McpService { final McpClient client; McpService(this.client); Future getAiResponse(String prompt) async { return McpErrorHandler.handleMcpOperation( () async { final response = await client.sendPrompt(McpPrompt( messages: [McpMessage(role: 'user', content: prompt)], )); return response.content; }, maxRetries: 3, onError: (errorType, message) { print('Error occurred: $errorType - $message'); _showErrorSnackbar(errorType, message); }, ); } void _showErrorSnackbar(McpErrorType type, String message) { final userMessage = switch (type) { McpErrorType.connection => 'Unable to connect to server. Check your internet connection.', McpErrorType.authentication => 'Authentication failed. Please check your credentials.', McpErrorType.timeout => 'Request timed out. Please try again.', McpErrorType.toolExecution => 'Operation failed. Please try again.', McpErrorType.resourceAccess => 'Unable to access resource.', McpErrorType.unknown => 'An unexpected error occurred.', }; print('User Message: $userMessage'); } } ``` -------------------------------- ### Read MCP Resources in Flutter Source: https://context7.com/nischhal-applore/flutter-mcp-docs/llms.txt Reads a specific resource exposed by an MCP server using its URI. This function retrieves resource details such as URI, MIME type, and content length. It can handle various resource types including files, database records, and remote content. ```dart import 'package:flutter_mcp/flutter_mcp.dart'; Future readResource( McpClient client, String resourceUri, ) async { try { final resource = await client.readResource(uri: resourceUri); print('Resource URI: ${resource.uri}'); print('MIME Type: ${resource.mimeType}'); print('Content length: ${resource.content.length}'); return resource; } catch (e) { print('Failed to read resource: $e'); rethrow; } } // Example with multiple resources Future loadProjectResources(McpClient client) async { final resources = [ 'file:///documents/config.json', 'db://users/profile/123', 'https://api.example.com/data', ]; for (final uri in resources) { try { final content = await readResource(client, uri); print('Loaded: $uri (${content.mimeType})'); } catch (e) { print('Failed to load $uri: $e'); } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.