### Initialize and Start StreamableMcpServer Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StreamableMcpServer-class Demonstrates how to create and start an instance of StreamableMcpServer. It requires a server factory function to create MCP servers for each session, along with host and port configurations. The server can be started using the `start()` method. ```dart final server = StreamableMcpServer( serverFactory: (sessionId) { return McpServer( Implementation(name: 'my-server', version: '1.0.0'), )..tool(...); }, host: 'localhost', port: 3000, ); await server.start(); ``` -------------------------------- ### Start HTTP Server (Dart) Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StreamableMcpServer/start The `start` method initializes the HTTP server by binding it to a specified host and port. It logs the server's listening address and begins handling incoming requests. This method should only be called once, as attempting to start an already running server will result in a StateError. ```dart Future start() async { if (_httpServer != null) { throw StateError('Server already started'); } _httpServer = await HttpServer.bind(host, port); _logger.info( 'MCP Streamable HTTP Server listening on http://$host:$port$path', ); _httpServer!.listen(_handleRequest); } ``` -------------------------------- ### Start SSE Connection Setup - Dart Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/SseServerTransport/start Handles the initial Server-Sent Events (SSE) connection setup. It configures the HttpResponse for SSE, sends an initial 'endpoint' event to the client, and sets up listeners for connection closure and errors. This method is crucial for establishing bidirectional communication via SSE. ```dart @override Future start() async { if (_closeController.isClosed) { throw StateError( "SseServerTransport cannot start: Transport is already closed.", ); } try { _sseResponse.headers.chunkedTransferEncoding = false; _sseResponse.headers.contentType = ContentType('text', 'event-stream', charset: 'utf-8'); _sseResponse.headers.set(HttpHeaders.cacheControlHeader, 'no-cache'); _sseResponse.headers.set(HttpHeaders.connectionHeader, 'keep-alive'); final socket = await _sseResponse.detachSocket(writeHeaders: true); _sink = utf8.encoder.startChunkedConversion(socket); final endpointUrl = '$_messageEndpointPath?sessionId=${Uri.encodeComponent(sessionId)}'; await _sendSseEvent(name: 'endpoint', data: endpointUrl); socket.listen( (_) {}, onDone: () { _logger.debug('Client disconnected'); close(); }, onError: (error) { _logger.warn('Socket error: $error'); onerror?.call( error is Error ? error : StateError("Socket error: $error"), ); }, ); } on UnimplementedError catch (e) { _logger.error('UnimplementedError during SSE transport setup: $e'); onerror?.call(e); rethrow; } catch (error) { _logger.error('Error starting SSE transport: $error'); } } ``` -------------------------------- ### Install and Run MCP Server with CLI (Dart) Source: https://pub.dev/documentation/mcp_dart/index This snippet demonstrates how to install the `mcp_dart_cli`, create a new MCP server project, and run the server. It also shows how to inspect and test server capabilities using the CLI. ```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 # Inspect server capabilities mcp_dart inspect # List all capabilities mcp_dart inspect --tool add --json-args '{"a": 1, "b": 2}' # Call a tool ``` -------------------------------- ### Start Server Process and Communication Pipes (Dart) Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StdioClientTransport/start This method starts the server process defined by `_serverParams`. It spawns the process, sets up listeners for stdout and stderr streams, and handles process exit events. The method completes when the process is successfully started or throws an error if it fails. It prevents multiple starts by checking the `_started` flag. ```dart @override Future start() async { if (_started) { throw StateError( "StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.", ); } _started = true; try { // Start the process. _process = await io.Process.start( _serverParams.command, _serverParams.args, workingDirectory: _serverParams.workingDirectory, environment: _serverParams.environment, runInShell: false, mode: io.ProcessStartMode.normal, // Always use normal to enable piping ); _logger.debug( "StdioClientTransport: Process started (PID: ${_process?.pid})", ); // --- Setup stream listeners --- // Listen to stdout for messages _stdoutSubscription = _process!.stdout.listen( _onStdoutData, onError: _onStreamError, onDone: _onStdoutDone, cancelOnError: false, ); // Listen to stderr if piped if (_serverParams.stderrMode == io.ProcessStartMode.normal) { // Expose stderr via getter, let user handle it. // Do NOT listen here, as that would prevent the user from listening. } else { // Inherit stderr (manually pipe to parent stderr) _stderrSubscription = _process!.stderr.listen( (data) => io.stderr.add(data), onError: _onStreamError, ); } // Handle process exit _process!.exitCode.then(_onProcessExit).catchError(_onProcessExitError); // Start successful return Future.value(); } catch (error, stackTrace) { // Handle errors during Process.start() _logger.error("StdioClientTransport: Failed to start process: $error"); _started = false; // Reset state final startError = StateError( "Failed to start server process: $error\n$stackTrace", ); try { onerror?.call(startError); } catch (e) { _logger.warn("Error in onerror handler: $e"); } throw startError; // Rethrow to signal failure } } ``` -------------------------------- ### Start IOStreamTransport Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/IOStreamTransport/start Initializes the IOStreamTransport by setting up listeners on the input stream. This method must be called before sending or receiving messages. It prevents re-initialization by throwing a StateError if the transport has already been started. Error handling is included for potential issues during stream setup. ```dart @override Future start() async { if (_started) { throw StateError( "IOStreamTransport already started! Note that server/client .connect() calls start() automatically.", ); } _started = true; _closed = false; try { // Listen to input stream for messages _streamSubscription = stream.listen( _onStreamData, onError: _onStreamError, onDone: _onStreamDone, cancelOnError: false, ); return Future.value(); } catch (error, stackTrace) { _started = false; // Reset state final startError = StateError( "Failed to start IOStreamTransport: $error\n$stackTrace", ); try { onerror?.call(startError); } catch (e) { _logger.warn("Error in onerror handler: $e"); } throw startError; // Rethrow to signal failure } } ``` -------------------------------- ### connect Method Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/Protocol/connect Attaches to the given transport, starts it, and starts listening for messages. This method is crucial for establishing a communication channel. ```APIDOC ## connect Method ### Description Attaches to the given transport, starts it, and starts listening for messages. ### Method Future ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **transport** (Transport) - Required - The transport layer to connect to. ### Request Example ```dart // Assuming 'myTransport' is an instance of a Transport class await connect(myTransport); ``` ### Response #### Success Response (void) This method returns void upon successful connection. #### Response Example ```json // No direct JSON response, but the connection is established. ``` ### Error Handling - Throws a `StateError` if the protocol is already connected to a transport. - Catches and rethrows errors during the transport start process. ``` -------------------------------- ### Start Listening on Stdin - Dart Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StdioServerTransport/start The `start` method in StdioServerTransport initiates listening for incoming data on the standard input stream. It attaches listeners to handle data, errors, and stream completion, preventing multiple starts by throwing a StateError if already active. This method is crucial for real-time message processing. ```dart @override Future start() async { if (_started) { throw StateError( "StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.", ); } _started = true; _stdinSubscription = _stdin.listen( _ondata, onError: _onErrorCallback, onDone: _onStdinDone, cancelOnError: false, ); } ``` -------------------------------- ### handleSseConnection API Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/SseServerManager-class Handles the initial GET request to establish a Server-Sent Events (SSE) connection. ```APIDOC ## GET /handleSseConnection ### Description Handles the initial GET request to establish an SSE connection. ### Method GET ### Endpoint `/handleSseConnection` ### Parameters #### Query Parameters - **request** (HttpRequest) - Required - The incoming HTTP request to establish the SSE connection. ``` -------------------------------- ### Handle SSE Connection Setup and Management (Dart) Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/SseServerManager/handleSseConnection This method handles the initial HTTP GET request to establish a Server-Sent Events (SSE) connection. It sets up the SSE transport, manages active sessions, and handles connection closure and errors. Dependencies include `HttpRequest`, `SseServerTransport`, and a logger. ```dart Future handleSseConnection(HttpRequest request) async { _logger.debug("Client connecting for SSE at /sse..."); SseServerTransport? transport; try { transport = SseServerTransport( response: request.response, messageEndpointPath: messagePath, ); final sessionId = transport.sessionId; activeSseTransports[sessionId] = transport; _logger.debug("Stored new SSE transport for session: $sessionId"); transport.onclose = () { _logger.debug( "SSE transport closed (Session: $sessionId). Removing from active list.", ); activeSseTransports.remove(sessionId); }; transport.onerror = (error) { _logger.warn("Error on SSE transport (Session: $sessionId): $error"); }; await mcpServer.connect(transport); _logger.debug("SSE transport connected, session ID: $sessionId"); } catch (e) { _logger.warn("Error setting up SSE connection: $e"); if (transport != null) { activeSseTransports.remove(transport.sessionId); } if (!request.response.headers.persistentConnection) { try { request.response.statusCode = HttpStatus.internalServerError; request.response.write("Failed to initialize SSE connection."); await request.response.close(); } catch (_) {} } } } ``` -------------------------------- ### StdioServerTransport Methods Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StdioServerTransport-class Documentation for the methods of the StdioServerTransport class, including closing, sending messages, and starting the transport. ```APIDOC ## StdioServerTransport Methods ### Description Methods available for the StdioServerTransport class. ### Method Method Invocation ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart await transport.close(); await transport.send(message); await transport.start(); ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### McpClient Constructor and Handler Setup (Dart) Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/McpClient/McpClient Initializes the McpClient with client information and optional configurations. It dynamically registers request and notification handlers for methods like elicitation, task status, and sampling based on the provided client capabilities. This ensures the client can process incoming requests and notifications relevant to its features. ```dart McpClient( this._clientInfo, {McpClientOptions? options}) : _capabilities = options?.capabilities ?? const ClientCapabilities(), super(options) { // Register elicit handler if capability is present if (_capabilities.elicitation?.form != null) { setRequestHandler( Method.elicitationCreate, (request, extra) async { if (onElicitRequest == null) { throw McpError( ErrorCode.methodNotFound.value, "No elicit handler registered", ); } final result = await onElicitRequest!(request.elicitParams); // Apply defaults if client supports it and it's a form elicitation if (request.elicitParams.mode == ElicitationMode.form && result.action == 'accept' && result.content is Map && request.elicitParams.requestedSchema != null && _capabilities.elicitation?.form?.applyDefaults == true) { _applyElicitationDefaults( request.elicitParams.requestedSchema!, result.content!, ); } return result; }, (id, params, meta) => JsonRpcElicitRequest( id: id, elicitParams: ElicitRequest.fromJson(params ?? {}), meta: meta, ), ); } // Register task status notification handler if (_capabilities.tasks != null) { setNotificationHandler( Method.notificationsTasksStatus, (notification) async { await onTaskStatus?.call(notification.statusParams); }, (params, meta) => JsonRpcTaskStatusNotification( statusParams: TaskStatusNotification.fromJson(params ?? {}), meta: meta, ), ); } // Register sampling request handler if capability is present if (_capabilities.sampling != null) { setRequestHandler( Method.samplingCreateMessage, (request, extra) async { if (onSamplingRequest == null) { throw McpError( ErrorCode.methodNotFound.value, "No sampling handler registered", ); } return await onSamplingRequest!(request.createParams); }, (id, params, meta) => JsonRpcCreateMessageRequest( id: id, createParams: CreateMessageRequest.fromJson(params ?? {}), meta: meta, ), ); } } ``` -------------------------------- ### ResourceTemplateRegistration Methods Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/ResourceTemplateRegistration-class Details the methods available for the ResourceTemplateRegistration class, including getting completion callbacks and handling non-existent methods. ```APIDOC ## ResourceTemplateRegistration Methods ### Description Methods available for the ResourceTemplateRegistration class. ### Method GET ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **getCompletionCallback(String variableName)** (CompleteResourceTemplateCallback?): Gets the completion callback for a specific variable. - **noSuchMethod(Invocation invocation)** (dynamic): Invoked when a nonexistent method or property is accessed. - **toString()** (String): A string representation of this object. #### Response Example ```json { "getCompletionCallback": { "variableName": "userId", "callback": "function_to_complete_userId" }, "noSuchMethod": "Method not found", "toString": "ResourceTemplateRegistration(template='/users/{userId}')" } ``` ``` -------------------------------- ### SseServerTransport Methods Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/SseServerTransport-class Documentation for the methods available in the SseServerTransport class, including starting and closing the SSE connection, handling messages, and sending data to the client. ```APIDOC ## SseServerTransport Methods ### Description Methods of the SseServerTransport class. ### Method Method ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **close()** (Future) - Closes the SSE connection and cleans up resources. Invokes the onclose callback. - **handleMessage(Map messageJson)** (Future) - Handles a message received via any means (typically from handlePostMessage). Parses the raw JSON object and invokes the onmessage callback. - **handlePostMessage(HttpRequest request, {dynamic parsedBody})** (Future) - Handles incoming HTTP POST requests containing client messages. - **noSuchMethod(Invocation invocation)** (dynamic) - Invoked when a nonexistent method or property is accessed. - **send(JsonRpcMessage message, {int? relatedRequestId})** (Future) - Sends a JsonRpcMessage to the client over the established SSE connection. - **start()** (Future) - Handles the initial SSE connection setup. - **toString()** (String) - A string representation of this object. #### Response Example ```json { "close": "Future", "handleMessage": "Future", "handlePostMessage": "Future", "noSuchMethod": "dynamic", "send": "Future", "start": "Future", "toString": "String" } ``` ``` -------------------------------- ### StreamableHTTPServerTransport Usage Example (Dart) Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StreamableHTTPServerTransport-class Demonstrates how to instantiate and use the StreamableHTTPServerTransport in both stateful and stateless modes. It also shows integration with Dart's HttpServer for handling incoming requests. ```dart import 'dart:io'; import 'package:uuid/uuid.dart'; // Assuming StreamableHTTPServerTransport and StreamableHTTPServerTransportOptions are defined elsewhere // import 'package:your_package/streamable_http_server_transport.dart'; // Placeholder for UUID generation String generateUUID() => Uuid().v4(); void main() async { // Stateful mode - server sets the session ID final statefulTransport = StreamableHTTPServerTransport( options: StreamableHTTPServerTransportOptions( sessionIdGenerator: () => generateUUID(), ), ); // Stateless mode - explicitly set session ID to null final statelessTransport = StreamableHTTPServerTransport( options: StreamableHTTPServerTransportOptions( sessionIdGenerator: () => null, ), ); // Using with HTTP server final server = await HttpServer.bind('localhost', 8080); print('Server listening on http://localhost:8080'); server.listen((request) { if (request.uri.path == '/mcp') { // In a real application, you would decide which transport to use based on configuration or request headers statefulTransport.handleRequest(request); } else { request.response.statusCode = HttpStatus.notFound; request.response.write('Not Found'); request.response.close(); } }); } // Dummy implementations for demonstration purposes class StreamableHTTPServerTransportOptions { final String? Function()? sessionIdGenerator; StreamableHTTPServerTransportOptions({this.sessionIdGenerator}); } class StreamableHTTPServerTransport { final StreamableHTTPServerTransportOptions options; StreamableHTTPServerTransport({required this.options}); Future handleRequest(HttpRequest req, [dynamic parsedBody]) async { print('Handling request: ${req.method} ${req.uri.path}'); // Simulate response req.response.statusCode = HttpStatus.ok; req.response.headers.contentType = ContentType.text; req.response.write('MCP Response'); await req.response.close(); } } ``` -------------------------------- ### Dart StartSseOptions Constructor Implementation Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StartSseOptions/StartSseOptions Provides the concrete implementation of the StartSseOptions constructor in Dart. It assigns the provided parameter values to the instance variables. ```dart const StartSseOptions({ this.resumptionToken, this.onResumptionToken, this.replayMessageId, this.shouldReconnect = true, }); ``` -------------------------------- ### McpServerOptions Constructor Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/McpServerOptions-class Initializes McpServerOptions with optional configuration for strict capabilities, server capabilities, and instructions. ```APIDOC ## McpServerOptions Constructor ### Description Initializes McpServerOptions with optional configuration for strict capabilities, server capabilities, and instructions. ### Method CONSTRUCTOR ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **enforceStrictCapabilities** (bool) - Optional - Whether to restrict emitted requests to only those that the remote side has indicated they can handle. - **capabilities** (ServerCapabilities?) - Optional - Capabilities to advertise as being supported by this server. - **instructions** (String?) - Optional - Optional instructions describing how to use the server and its features. ### Request Example ```json { "enforceStrictCapabilities": true, "capabilities": { "someCapability": true }, "instructions": "Use this server for advanced MCP features." } ``` ### Response #### Success Response (200) N/A (Constructor) #### Response Example N/A (Constructor) ``` -------------------------------- ### McpClient Constructors Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/McpClient-class Details on how to initialize an McpClient instance. ```APIDOC ## Constructors McpClient(Implementation _clientInfo, {McpClientOptions? options}) ### Description Initializes this client with its implementation details and options. ### Method CONSTRUCTOR ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart // Example usage (assuming Implementation and McpClientOptions are defined elsewhere) // final myClient = McpClient(myImplementation, options: myOptions); ``` ### Response #### Success Response N/A (Constructor) #### Response Example N/A (Constructor) ``` -------------------------------- ### Create McpServer Instance (Dart) Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/McpServer/McpServer This snippet demonstrates the creation of an McpServer instance. It requires an 'Implementation' object for server information and accepts an optional 'McpServerOptions' object. ```dart McpServer(Implementation serverInfo, {McpServerOptions? options}) { // ignore: deprecated_member_use_from_same_package server = Server(serverInfo, options: options); } ``` -------------------------------- ### McpServer Constructor Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/McpServer-class Initializes a new instance of the McpServer class. ```APIDOC ## McpServer Constructor ### Description Creates an McpServer instance. ### Method CONSTRUCTOR ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart final server = McpServer(serverInfo); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Start Streamable HTTP Transport - Dart Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StreamableHTTPServerTransport/start The start method initializes the Streamable HTTP transport. It prevents the transport from being started multiple times by checking a '_started' flag. This method is part of the Transport interface but is a no-op for this transport type. ```dart @override Future start() async { if (_started) { throw StateError("Transport already started"); } _started = true; } ``` -------------------------------- ### handleSseConnection Method Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/SseServerManager/handleSseConnection Handles the initial GET request to establish an SSE connection. It sets up the SSE transport, manages active connections, and handles connection closures and errors. ```APIDOC ## GET /sse ### Description Handles the initial GET request to establish an SSE connection. It sets up the SSE transport, manages active connections, and handles connection closures and errors. ### Method GET ### Endpoint /sse ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Connection** (string) - `keep-alive` (Indicates the connection will be kept open for SSE) - **Content-Type** (string) - `text/event-stream` (Specifies the content type for SSE) #### Response Example (No specific JSON body for a successful SSE handshake, the connection is established for streaming events.) ### Error Handling - **Internal Server Error (500)**: Returned if there is a failure during SSE connection setup. - **Response Body**: `Failed to initialize SSE connection.` ``` -------------------------------- ### Dart StartSseOptions Constructor Definition Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StartSseOptions/StartSseOptions Defines the StartSseOptions constructor with its named parameters. It includes optional parameters for resumptionToken, onResumptionToken callback, replayMessageId, and a boolean shouldReconnect with a default value. ```dart const StartSseOptions({ 1. String? resumptionToken, 2. void onResumptionToken( 1. String token )?, 3. dynamic replayMessageId, 4. bool shouldReconnect = true, }) ``` -------------------------------- ### Start Message Processing Transport - Dart Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StreamableHttpClientTransport/start The start method initiates message processing on the transport layer. It checks if the transport has already been started to prevent duplicate initializations and creates a broadcast stream controller for managing the processing lifecycle. This method is crucial for setting up the communication channel. ```dart @override Future start() async { if (_abortController != null) { throw McpError( 0, "StreamableHttpClientTransport already started! If using Client class, note that connect() calls start() automatically.", ); } _abortController = StreamController.broadcast(); } ``` -------------------------------- ### Dart Get Reason Property Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/AbortSignal/reason This snippet shows the implementation of a getter named 'reason' in Dart. It is declared as 'dynamic' and is intended to return the reason provided when an operation is aborted, or null if no reason is given. ```dart dynamic get reason; ``` -------------------------------- ### Server Class Overview Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/Server-class Provides details about the Server class, its inheritance, annotations, constructors, properties, and methods. ```APIDOC ## Server Class An MCP server implementation built on top of a pluggable Transport. This server automatically handles the initialization flow initiated by the client. It extends the base Protocol class, providing server-specific logic and capability handling. ### Inheritance * Object * Protocol * Server ### Annotations * @Deprecated('Use McpServer instead unless you need to create a custom protocol implementation') ### Constructors #### Server(Implementation _serverInfo, {McpServerOptions? options}) Initializes this server with its implementation details and options. ### Properties * **fallbackNotificationHandler** ↔ `Future Function(JsonRpcNotification notification)?` - Fallback handler for incoming notification methods without a specific handler. (getter/setter pair, inherited) * **fallbackRequestHandler** ↔ `Future Function(JsonRpcRequest request)?` - Fallback handler for incoming request methods without a specific handler. (getter/setter pair, inherited) * **hashCode** → `int` - The hash code for this object. (no setter, inherited) * **onclose** ↔ `void Function()?` - Callback invoked when the underlying transport connection is closed. (getter/setter pair, inherited) * **onerror** ↔ `void Function(Error error)?` - Callback invoked when an error occurs in the protocol layer or transport. (getter/setter pair, inherited) * **oninitialized** ↔ `void Function()?` - Callback to be notified when the server is fully initialized. (getter/setter pair) * **runtimeType** → `Type` - A representation of the runtime type of the object. (no setter, inherited) * **transport** → `Transport?` - Gets the currently attached transport, or null if not connected. (no setter) ``` -------------------------------- ### StdioServerParameters Class Documentation Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StdioServerParameters-class Provides details on the constructors, properties, and methods of the StdioServerParameters class. ```APIDOC ## StdioServerParameters Class Configuration parameters for launching the stdio server process. ### Constructors #### StdioServerParameters ```dart StdioServerParameters({ required String command, List args = const [], Map? environment, ProcessStartMode stderrMode = io.ProcessStartMode.inheritStdio, String? workingDirectory, }) ``` Creates parameters for launching the stdio server. ### Properties - **args** (List) - Command line arguments to pass to the executable. - **command** (String) - The executable command to run to start the server process. - **environment** (Map? | null) - Environment variables to use when spawning the process. If null, the parent process environment will be inherited. - **stderrMode** (ProcessStartMode) - How to handle the stderr stream of the child process. Defaults to `io.ProcessStartMode.inheritStdio`, printing to the parent's stderr. Can be set to `io.ProcessStartMode.normal` to capture stderr via the stderr stream getter. - **workingDirectory** (String? | null) - The working directory to use when spawning the process. If null, inherits the current working directory. ### Methods - **noSuchMethod**(Invocation invocation) → dynamic - Invoked when a nonexistent method or property is accessed. - **toString**() → String - A string representation of this object. ### Operators - **operator ==**(Object other) → bool - The equality operator. ``` -------------------------------- ### Start Abstract Method for Message Processing (Dart) Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/Transport/start This abstract method initiates message processing on the transport layer. It handles necessary connection steps before processing begins. The method returns a Future that completes when the process is started. ```dart Future start(); ``` -------------------------------- ### ServerCapabilitiesPrompts Constructor Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/ServerCapabilitiesPrompts-class Constructs a ServerCapabilitiesPrompts object. Optionally indicates if the prompt list has changed. ```APIDOC ## ServerCapabilitiesPrompts Constructor ### Description Constructs a ServerCapabilitiesPrompts object. Optionally indicates if the prompt list has changed. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "listChanged": true } ``` ### Response #### Success Response (200) Represents the ServerCapabilitiesPrompts object. #### Response Example ```json { "listChanged": true } ``` ``` -------------------------------- ### Initialize InMemoryTaskStore and Start Cleanup - Dart Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/InMemoryTaskStore/InMemoryTaskStore The InMemoryTaskStore constructor initializes the task store and immediately starts a Time-To-Live (TTL) cleanup process. This ensures that expired tasks are automatically removed from memory. No specific dependencies are required beyond the Dart core libraries. ```dart InMemoryTaskStore() { _startTtlCleanup(); } ``` -------------------------------- ### TaskClient Constructor Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/TaskClient-class Initializes a new instance of the TaskClient class. ```APIDOC ## TaskClient Constructor ### Description Initializes a new instance of the TaskClient class. ### Method Constructor ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart final taskClient = TaskClient(mcpClient); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### SseServerManager Constructor Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/SseServerManager-class Initializes a new instance of the SseServerManager class. ```APIDOC ## SseServerManager Constructor ### Description Initializes a new instance of the SseServerManager class. ### Method Constructor ### Parameters #### Path Parameters - **mcpServer** (McpServer) - Required - The main MCP Server instance. - **ssePath** (String) - Optional - Path for establishing SSE connections. Defaults to '/sse'. - **messagePath** (String) - Optional - Path for sending messages to the server. Defaults to '/messages'. ### Request Example ```dart final sseManager = SseServerManager(myMcpServer, ssePath: '/custom-sse', messagePath: '/custom-messages'); ``` ### Response #### Success Response (Instance) - **SseServerManager** - An instance of the SseServerManager class. ``` -------------------------------- ### Initialize RegisteredPrompt Constructor Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/RegisteredPrompt/RegisteredPrompt This snippet shows the basic initialization of the RegisteredPrompt constructor. It is a simple constructor call without any arguments. ```dart RegisteredPrompt() ``` -------------------------------- ### ClientCapabilitiesTasksElicitationCreate Constructors Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/ClientCapabilitiesTasksElicitationCreate-class Provides information on how to create instances of the ClientCapabilitiesTasksElicitationCreate class. ```APIDOC ## ClientCapabilitiesTasksElicitationCreate() ### Description Creates a new instance of the ClientCapabilitiesTasksElicitationCreate class. ### Method Constructor ### Endpoint N/A ### Parameters None ### Request Example ```dart var instance = ClientCapabilitiesTasksElicitationCreate(); ``` ### Response #### Success Response (200) An instance of ClientCapabilitiesTasksElicitationCreate. #### Response Example ```dart ClientCapabilitiesTasksElicitationCreate() ``` ## ClientCapabilitiesTasksElicitationCreate.fromJson(Map json) ### Description Creates a ClientCapabilitiesTasksElicitationCreate instance from a JSON map. ### Method Factory Constructor ### Endpoint N/A ### Parameters - **json** (Map) - Required - A map representing the JSON data. ### Request Example ```dart var jsonMap = {'key': 'value'}; var instance = ClientCapabilitiesTasksElicitationCreate.fromJson(jsonMap); ``` ### Response #### Success Response (200) An instance of ClientCapabilitiesTasksElicitationCreate created from the provided JSON. #### Response Example ```dart ClientCapabilitiesTasksElicitationCreate.fromJson({'key': 'value'}) ``` ``` -------------------------------- ### GET /websites/pub_dev_mcp_dart/title Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/RegisteredTool/title Retrieves the title of the tool. The title is a nullable string representing the tool's name. ```APIDOC ## GET /websites/pub_dev_mcp_dart/title ### Description Retrieves the title of the tool. The title is a nullable string representing the tool's name. ### Method GET ### Endpoint /websites/pub_dev_mcp_dart/title ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **title** (String?) - The title of the tool. #### Response Example ```json { "title": "Example Tool Title" } ``` ``` -------------------------------- ### ClientCapabilitiesTasksElicitationCreate Methods Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/ClientCapabilitiesTasksElicitationCreate-class Details the methods available on the ClientCapabilitiesTasksElicitationCreate class. ```APIDOC ## noSuchMethod(Invocation invocation) → dynamic ### Description Invoked when a nonexistent method or property is accessed. ### Method Method ### Endpoint N/A ### Parameters - **invocation** (Invocation) - Required - The invocation details. ### Request Example ```dart var instance = ClientCapabilitiesTasksElicitationCreate(); try { instance.nonExistentMethod(); } catch (e) { print(e); } ``` ### Response #### Success Response (200) Dynamic result of the method invocation, or an error if the method does not exist. #### Response Example ```dart Error: NoSuchMethodError ``` ## toJson() → Map ### Description Serializes the ClientCapabilitiesTasksElicitationCreate object to a JSON map. ### Method Method ### Endpoint N/A ### Parameters None ### Request Example ```dart var instance = ClientCapabilitiesTasksElicitationCreate(); var jsonMap = instance.toJson(); ``` ### Response #### Success Response (200) A Map representing the JSON serialization of the object. #### Response Example ```json { "example": "value" } ``` ``` -------------------------------- ### Get Resource Template Property Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/RegisteredResourceTemplate/resourceTemplate Retrieves the registration details for the resource template. ```APIDOC ## GET /websites/pub_dev_mcp_dart/resourceTemplate ### Description Retrieves the registration details for the resource template. ### Method GET ### Endpoint /websites/pub_dev_mcp_dart/resourceTemplate ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **resourceTemplate** (ResourceTemplateRegistration) - The template registration details. #### Response Example ```json { "resourceTemplate": { "id": "string", "name": "string", "version": "string" } } ``` ``` -------------------------------- ### GET /websites/pub_dev_mcp_dart/enabled Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/RegisteredPrompt/enabled Retrieves the current enabled status of the prompt. This is a read-only property. ```APIDOC ## GET /websites/pub_dev_mcp_dart/enabled ### Description Retrieves the current enabled status of the prompt. This is a read-only property. ### Method GET ### Endpoint /websites/pub_dev_mcp_dart/enabled ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **enabled** (bool) - Indicates whether the prompt is currently enabled. #### Response Example ```json { "enabled": true } ``` ``` -------------------------------- ### UnknownResourceContents Constructor Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/UnknownResourceContents-class Initializes a new instance of the UnknownResourceContents class. ```APIDOC ## UnknownResourceContents Constructor ### Description Initializes a new instance of the UnknownResourceContents class. ### Method Constructor ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart UnknownResourceContents(uri: 'example.com/resource', mimeType: 'application/json') ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### ProtocolOptions Constructor Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/ProtocolOptions-class Creates protocol options with various configuration settings. ```APIDOC ## Constructor ProtocolOptions ### Description Creates protocol options with optional configurations for strict capabilities, debounced notifications, task management, and polling intervals. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **enforceStrictCapabilities** (bool) - Optional - Whether to restrict emitted requests to only those that the remote side has indicated they can handle, through their advertised capabilities. - **debouncedNotificationMethods** (List?) - Optional - An array of notification method names that should be automatically debounced. - **taskStore** (TaskStore?) - Optional - Optional task storage implementation. - **taskMessageQueue** (TaskMessageQueue?) - Optional - Optional task message queue implementation. - **defaultTaskPollInterval** (int?) - Optional - Default polling interval (in milliseconds) for task status checks. - **maxTaskQueueSize** (int?) - Optional - Maximum number of messages that can be queued per task. ### Request Example ```json { "enforceStrictCapabilities": true, "debouncedNotificationMethods": ["method1", "method2"], "taskStore": { /* TaskStore object */ }, "taskMessageQueue": { /* TaskMessageQueue object */ }, "defaultTaskPollInterval": 5000, "maxTaskQueueSize": 100 } ``` ### Response #### Success Response (200) Returns an instance of ProtocolOptions configured with the provided parameters. #### Response Example ```json { "enforceStrictCapabilities": true, "debouncedNotificationMethods": ["method1", "method2"], "taskStore": { /* TaskStore object */ }, "taskMessageQueue": { /* TaskMessageQueue object */ }, "defaultTaskPollInterval": 5000, "maxTaskQueueSize": 100 } ``` ``` -------------------------------- ### JsonRpcElicitRequest Class Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/JsonRpcElicitRequest-class This section details the JsonRpcElicitRequest class, used for server-to-client requests to get user input. ```APIDOC ## JsonRpcElicitRequest Class ### Description Represents a request sent from the server to the client to elicit user input. It inherits from JsonRpcRequest. ### Constructors 1. **JsonRpcElicitRequest** ```dart JsonRpcElicitRequest({required dynamic id, required ElicitRequest elicitParams, Map? meta}) ``` Creates a new JsonRpcElicitRequest. 2. **JsonRpcElicitRequest.fromJson** ```dart factory JsonRpcElicitRequest.fromJson(Map json) ``` Creates a JsonRpcElicitRequest from a JSON map. ### Properties - **id** (dynamic) - The request identifier. - **elicitParams** (ElicitRequest) - The parameters required for eliciting user input. - **meta** (Map?)- Optional metadata associated with the request. - **jsonrpc** (String) - The JSON-RPC version string. Always "2.0". - **method** (String) - The method to be invoked. - **params** (Map?) - The parameters for the method, if any. - **progressToken** (dynamic) - The progress token for out-of-band progress notifications. ### Methods - **toJson() → Map** Converts the message object to its JSON representation. - **toString() → String** Returns a string representation of this object. - **noSuchMethod(Invocation invocation) → dynamic** Invoked when a nonexistent method or property is accessed. ### Operators - **operator ==(Object other) → bool** Compares this object with another for equality. ``` -------------------------------- ### StreamableHttpClientTransport Methods Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StreamableHttpClientTransport-class Provides methods for managing the StreamableHttpClientTransport connection, including closing, sending messages, and starting the transport. ```APIDOC ## StreamableHttpClientTransport Methods ### Description Provides methods for managing the StreamableHttpClientTransport connection, including closing, sending messages, and starting the transport. ### Method Method ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```dart await transport.close(); await transport.finishAuth('auth_code'); await transport.send(JsonRpcMessage.request('method')); await transport.start(); await transport.terminateSession(); ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Get Completion Callback Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/ResourceTemplateRegistration/getCompletionCallback Retrieves the completion callback for a given variable name. ```APIDOC ## GET /completionCallback ### Description Retrieves the completion callback for a specific variable. ### Method GET ### Endpoint /completionCallback ### Parameters #### Query Parameters - **variableName** (String) - Required - The name of the variable for which to retrieve the completion callback. ### Response #### Success Response (200) - **callback** (CompleteResourceTemplateCallback) - The completion callback function associated with the variable name, or null if not found. #### Response Example ```json { "callback": "function() { ... }" } ``` ``` -------------------------------- ### Dart Prompt Constructor Implementation Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/Prompt/Prompt Provides the implementation for the Dart 'Prompt' constructor, initializing its properties with the provided arguments. ```dart const Prompt({ required this.name, this.description, this.arguments, this.icon, }); ``` -------------------------------- ### GET /websites/pub_dev_mcp_dart/enabled Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/RegisteredTool/enabled Retrieves the current enabled status of the tool. This property is a boolean value. ```APIDOC ## GET /websites/pub_dev_mcp_dart/enabled ### Description Retrieves the current enabled status of the tool. This property is a boolean value indicating whether the tool is currently active. ### Method GET ### Endpoint /websites/pub_dev_mcp_dart/enabled ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **enabled** (bool) - Indicates whether the tool is currently enabled. `true` if enabled, `false` otherwise. #### Response Example ```json { "enabled": true } ``` ``` -------------------------------- ### Server Constructor Implementation in Dart Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/Server/Server Initializes the Server with implementation details and optional configuration. It sets up handlers for JSON-RPC initialize, notificationsInitialized, and loggingSetLevel requests, utilizing provided options or defaults. ```dart Server(this._serverInfo, {McpServerOptions? options}) : _capabilities = options?.capabilities ?? const ServerCapabilities(), _instructions = options?.instructions, super(options) { setRequestHandler( Method.initialize, (request, extra) async => _oninitialize(request.initParams), (id, params, meta) => JsonRpcInitializeRequest.fromJson({ 'id': id, 'params': params, if (meta != null) '_meta': meta, }), ); setNotificationHandler( Method.notificationsInitialized, (notification) async => oninitialized?.call(), (params, meta) => JsonRpcInitializedNotification.fromJson({ 'params': params, if (meta != null) '_meta': meta, }), ); if (_capabilities.logging != null) { setRequestHandler( Method.loggingSetLevel, (request, extra) async { _loggingLevels[extra.sessionId] = request.setParams.level; return const EmptyResult(); }, (id, params, meta) => JsonRpcSetLevelRequest.fromJson({ 'id': id, 'params': params, if (meta != null) '_meta': meta, }), ); } } ``` -------------------------------- ### StdioClientTransport Methods Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/StdioClientTransport-class Methods available for the StdioClientTransport class, including closing the connection, sending messages, and starting the server process. ```APIDOC ## StdioClientTransport Methods ### Description Methods for managing the stdio client transport connection. ### Methods - **close()** (`Future`) - **Description**: Closes the transport connection by terminating the server process and cleaning up resources. - **Override**: Yes - **noSuchMethod**(Invocation invocation) - **Description**: Invoked when a nonexistent method or property is accessed. - **Inherited**: Yes - **send**(JsonRpcMessage message, {int? relatedRequestId}) - **Description**: Sends a JsonRpcMessage to the server process via its stdin. - **Override**: Yes - **start**() - **Description**: Starts the server process and establishes communication pipes. - **Override**: Yes - **toString**() - **Description**: A string representation of this object. - **Inherited**: Yes ``` -------------------------------- ### Get Task Result Source: https://pub.dev/documentation/mcp_dart/latest/mcp_dart/RequestTaskStore/getTaskResult Retrieves the result of a task based on its unique identifier. ```APIDOC ## GET /task/{taskId}/result ### Description Retrieves the result of a task using its unique identifier. ### Method GET ### Endpoint /task/{taskId}/result ### Parameters #### Path Parameters - **taskId** (String) - Required - The unique identifier of the task. ### Response #### Success Response (200) - **BaseResultData** (Object) - An object containing the task result data. #### Response Example ```json { "data": { "some_field": "some_value" }, "status": "success" } ``` ```