mcp_dart library

Support for Model Controller Protocol (MCP) SDK for Dart.

This package provides a Dart implementation of the Model Controller Protocol (MCP), which is designed to facilitate communication between clients and servers in a structured and extensible way.

The library exports key modules and types for building MCP-based applications, including server implementations, type definitions, and utilities.

Classes

AbortController
Controls an AbortSignal, allowing the initiator of an operation to signal abortion.
AbortSignal
Represents a signal that can be used to notify downstream consumers that an operation should be aborted.
Annotations
Optional annotations that can be attached to content and resources.
ArgumentCompletionInfo
Information about the argument being completed.
AudioContent
AuthInfo
Generic authentication info.
BaseResultData
Base class for specific MCP result types.
BasicAbortController
BlobResourceContents
Resource contents represented as binary data (Base64 encoded).
CallToolRequest
A request to call a tool.
CallToolResult
The server's response to a CallToolRequest.
CancelledNotification
Parameters for the notifications/cancelled notification.
CancelTaskRequest
Parameters for the tasks/cancel request.
ClientCapabilities
Capabilities a client may support.
ClientCapabilitiesRoots
Describes capabilities related to root resources (e.g., workspace folders).
ClientCapabilitiesSampling
Capabilities related to sampling.
ClientCapabilitiesTasks
Describes capabilities related to tasks.
ClientCapabilitiesTasksElicitation
ClientCapabilitiesTasksElicitationCreate
Capabilities related to tasks > elicitation.
ClientCapabilitiesTasksRequests
Task capabilities derived from spec: specifies which request types can be augmented with tasks.
ClientCapabilitiesTasksSampling
ClientCapabilitiesTasksSamplingCreateMessage
Capabilities related to tasks > sampling.
ClientElicitation
Describes capabilities related to elicitation (server-initiated user input).
ClientElicitationForm
Describes capabilities related to elicitation > form mode.
ClientElicitationUrl
Describes capabilities related to elicitation > URL mode.
CompletableDef
Definition for a completable argument.
CompletableField
A field that supports auto-completion.
CompleteRequest
Parameters for the completion/complete request.
CompleteResult
Result data for a successful completion/complete request.
CompletionResultData
Data structure containing completion results.
Content
Base class for content parts within prompts or tool results.
CreateMessageRequest
Parameters for the sampling/createMessage request.
CreateMessageResult
Result data for a successful sampling/createMessage request.
CreateTaskResult
Result data for a task creation response.
ElicitationCompleteNotification
Parameters for the notifications/elicitation/complete notification.
ElicitRequest
Parameters for the elicitation/create request.
ElicitResult
Result data for a successful elicitation/create response
EmbeddedResource
Content embedding a resource.
EmptyResult
A response that indicates success but carries no specific data.
EventStore
Interface for resumability support via event storage
ExperimentalMcpServerTasks
Experimental task-related functionality for the server.
FunctionToolCallback
A tool callback implemented as a simple function.
GetPromptRequest
Parameters for the prompts/get request.
GetPromptResult
Result data for a successful prompts/get request.
GetTaskRequest
Parameters for the tasks/get request.
ImageContent
Image content.
Implementation
Describes an MCP implementation (client or server).
InitializeRequest
Parameters for the initialize request.
InitializeResult
Result data for a successful initialize request.
InMemoryEventStore
Simple in-memory event store for resumability
InMemoryTaskMessageQueue
A queue for managing task-related messages, supporting waiters.
InMemoryTaskStore
An in-memory implementation of TaskStore.
InterfaceToolCallback
A tool callback implemented via a ToolTaskHandler interface.
IOStreamTransport
Transport implementation that uses standard I/O for communication.
JsonAllOf
A schema that validates against all of the given schemas.
JsonAny
A schema that accepts any value, potentially with additional constraints not captured by other types.
JsonAnyOf
A schema that validates against any of the given schemas.
JsonArray
A schema for array values.
JsonBoolean
A schema for boolean values.
JsonEnum
A schema for enum values.
JsonInteger
A schema for integer values.
JsonNot
A schema that validates against none of the given schemas.
JsonNull
A schema for null values.
JsonNumber
A schema for number values.
JsonObject
A schema for object values.
JsonOneOf
A schema that validates against exactly one of the given schemas.
JsonRpcCallToolRequest
JSON-RPC request to call a tool.
JsonRpcCancelledNotification
Notification sent by either side to indicate cancellation of a request.
JsonRpcCancelTaskRequest
Request sent from client to cancel a task.
JsonRpcCompleteRequest
Request sent from client to ask server for completion options for an argument.
JsonRpcCompletionListChangedNotification
Notification from server indicating the list of available completions has changed.
JsonRpcCreateMessageRequest
Request sent from server to client to sample an LLM.
JsonRpcElicitationCompleteNotification
Notification sent from server to client when URL mode elicitation completes.
JsonRpcElicitRequest
Request sent from server to client to elicit user input
JsonRpcError
Represents a response indicating an error occurred during a request.
JsonRpcErrorData
Represents the error object in a JSON-RPC error response.
JsonRpcGetPromptRequest
Request sent from client to get a specific prompt, potentially with template arguments.
JsonRpcGetTaskRequest
Request sent from client to get task status.
JsonRpcInitializedNotification
Notification sent from the client to the server after initialization is finished.
JsonRpcInitializeRequest
Request sent from client to server upon connection to begin initialization.
JsonRpcListPromptsRequest
Request sent from client to list available prompts and templates.
JsonRpcListResourcesRequest
Request sent from client to list available resources.
JsonRpcListResourceTemplatesRequest
Request sent from client to list available resource templates.
JsonRpcListRootsRequest
Request sent from server to client to get the list of root URIs.
JsonRpcListTasksRequest
Request sent from client to list available tasks.
JsonRpcListToolsRequest
JSON-RPC request to list tools.
JsonRpcLoggingMessageNotification
Notification of a log message passed from server to client.
JsonRpcMessage
Base class for all JSON-RPC messages (requests, notifications, responses, errors).
JsonRpcNotification
Base class for JSON-RPC notifications which do not expect a response.
JsonRpcPingRequest
A ping request, sent by either side to check liveness. Expects an empty result.
JsonRpcProgressNotification
Out-of-band notification informing the receiver of progress on a request.
JsonRpcPromptListChangedNotification
Notification from server indicating the list of available prompts has changed.
JsonRpcReadResourceRequest
Request sent from client to read a specific resource.
JsonRpcRequest
Base class for JSON-RPC requests that expect a response.
JsonRpcResourceListChangedNotification
Notification from server indicating the list of available resources has changed.
JsonRpcResourceUpdatedNotification
Notification from server indicating a subscribed resource has changed.
JsonRpcResponse
Represents a successful (non-error) response to a request.
JsonRpcRootsListChangedNotification
Notification from client indicating the list of roots has changed.
JsonRpcSetLevelRequest
Request sent from client to enable or adjust logging level from the server.
JsonRpcSubscribeRequest
Request sent from client to subscribe to updates for a resource.
JsonRpcTaskResultRequest
Request sent from client to retrieve task results.
JsonRpcTaskStatusNotification
Notification from receiver indicating a task status has changed.
JsonRpcToolListChangedNotification
Notification from server indicating the list of available tools has changed.
JsonRpcUnsubscribeRequest
Request sent from client to cancel a resource subscription.
JsonSchema
A builder for creating JSON Schemas in a type-safe way.
JsonString
A schema for string values.
ListPromptsRequest
Parameters for the prompts/list request. Includes pagination.
ListPromptsResult
Result data for a successful prompts/list request.
ListResourcesRequest
Parameters for the resources/list request. Includes pagination.
ListResourcesResult
Result data for a successful resources/list request.
ListResourceTemplatesRequest
Parameters for the resources/templates/list request. Includes pagination.
ListResourceTemplatesResult
Result data for a successful resources/templates/list request.
ListRootsResult
Result data for a successful roots/list request.
ListTasksRequest
Parameters for the tasks/list request. Includes pagination.
ListTasksResult
Result data for a successful tasks/list request.
ListToolsRequest
A request to list available tools.
ListToolsResult
The server's response to a ListToolsRequest.
Logger
LoggingMessageNotification
Parameters for the notifications/message (or logging/message) notification.
McpClient
An MCP client implementation built on top of a pluggable Transport.
McpClientOptions
Options for configuring the MCP McpClient.
McpIcon
A UI icon reference.
McpServer
High-level Model Context Protocol (MCP) server API.
McpServerOptions
Options for configuring the MCP McpServer.
McpUiAppResourceConfig
Resource configuration for registerAppResource.
McpUiAppToolConfig
Tool configuration for registerAppTool.
McpUiCsp
CSP settings declared by _meta.ui.csp.
McpUiExtensionCapability
Typed capability settings for io.modelcontextprotocol/ui.
McpUiPermissions
Permission settings declared by _meta.ui.permissions.
McpUiResourceMeta
Typed representation of _meta.ui on resources and resource content.
McpUiToolMeta
Typed representation of _meta.ui on tools.
Method
Standard MCP JSON-RPC methods.
ModelHint
Hints for model selection during sampling.
ModelPreferences
Server's preferences for model selection requested during sampling.
OAuthClientProvider
Represents an OAuth client provider for authentication
OAuthTokens
Represents OAuth tokens
Progress
Represents progress information for a long-running request.
ProgressNotification
Parameters for the notifications/progress notification.
Prompt
A prompt or prompt template offered by the server.
PromptArgument
Describes an argument accepted by a prompt template.
PromptArgumentDefinition
Definition of an argument for a prompt.
PromptMessage
Describes a message within a prompt structure.
PromptReference
Reference to a prompt or prompt template name.
Protocol
Implements MCP protocol framing on top of a pluggable transport, including features like request/response linking, notifications, and progress.
ProtocolOptions
Additional initialization options for the protocol handler.
ProtocolVersionAwareTransport
Optional capability for transports that can attach MCP protocol version headers to outbound requests.
QueuedMessage
A message queued for side-channel delivery.
ReadResourceRequest
Parameters for the resources/read request.
ReadResourceResult
Result data for a successful resources/read request.
Reference
Sealed class representing a reference for autocompletion targets.
RegisteredPrompt
Abstract interface for a registered prompt.
RegisteredResource
Abstract interface for a registered resource.
RegisteredResourceTemplate
Abstract interface for a registered resource template.
RegisteredTool
Abstract interface for a registered tool.
RelatedTaskMetadata
Metadata about a related task.
RequestHandlerExtra
Extra data given to request handlers when processing an incoming request.
RequestInfo
Generic request info.
RequestOptions
Options that can be given per request.
RequestTaskStore
Request-scoped TaskStore interface.
Resource
A known resource offered by the server.
ResourceAnnotations
Additional properties describing a Resource to clients.
ResourceContents
Sealed class representing the contents of a specific resource or sub-resource.
A resource reference that can be included in prompts or tool results.
ResourceReference
Reference to a resource or resource template URI.
ResourceTemplate
A template description for resources available on the server.
ResourceTemplateRegistration
Registration details for a resource template.
ResourceUpdatedNotification
Parameters for the notifications/resources/updated notification.
Root
Represents a root directory or file the server can operate on.
SamplingAudioContent
Audio content for sampling messages.
SamplingContent
Represents content parts within sampling messages.
SamplingImageContent
Image content for sampling messages.
SamplingMessage
Describes a message issued to or received from an LLM API during sampling.
SamplingTextContent
Text content for sampling messages.
SamplingToolResultContent
Tool result content for sampling messages.
SamplingToolUseContent
Tool use content for sampling messages.
Server
An MCP server implementation built on top of a pluggable Transport.
ServerCapabilities
Capabilities a server may support.
ServerCapabilitiesCompletions
Describes capabilities related to completions.
ServerCapabilitiesElicitation
Describes capabilities related to elicitation (server-initiated user input).
ServerCapabilitiesPrompts
Describes capabilities related to prompts.
ServerCapabilitiesResources
Describes capabilities related to resources.
ServerCapabilitiesTasks
ServerCapabilitiesTasksRequests
ServerCapabilitiesTasksTools
ServerCapabilitiesTasksToolsCall
Describes capabilities related to tasks.
ServerCapabilitiesTools
Describes capabilities related to tools.
ServerElicitationForm
Describes capabilities related to elicitation > form mode for the server.
ServerElicitationUrl
Describes capabilities related to elicitation > URL mode for the server.
ServerQueuedMessage
A message in the task queue, with server-specific extensions.
SetLevelRequest
Parameters for the logging/setLevel request.
SseServerManager
Manages Server-Sent Events (SSE) connections and routes HTTP requests.
SseServerTransport
Server transport for SSE: sends messages over a persistent SSE connection (HttpResponse) and receives messages from separate HTTP POST requests handled by handlePostMessage.
StartSseOptions
Options for starting or authenticating an SSE connection
StdioClientTransport
Client transport for stdio: connects to a server by spawning a process and communicating with it over stdin/stdout pipes.
StdioServerParameters
Configuration parameters for launching the stdio server process.
StdioServerTransport
Server transport for stdio: communicates with a MCP client by reading from the current process's standard input (io.stdin) and writing to standard output (io.stdout).
StreamableHttpClientTransport
Client transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. It will connect to a server using HTTP POST for sending messages and HTTP GET with Server-Sent Events for receiving messages.
StreamableHttpClientTransportOptions
Configuration options for the StreamableHttpClientTransport.
StreamableHttpReconnectionOptions
Configuration options for reconnection behavior of the StreamableHttpClientTransport.
StreamableHTTPServerTransport
Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification. It supports both SSE streaming and direct HTTP responses.
StreamableHTTPServerTransportOptions
Configuration options for StreamableHTTPServerTransport
StreamableMcpServer
A high-level server implementation that manages multiple MCP sessions over Streamable HTTP.
SubscribeRequest
Parameters for the resources/subscribe request.
Task
Represents a task in the system.
TaskClient
Helper to handle task-augmented tool calls and interactions.
TaskCreatedMessage
TaskCreation
Parameters for task creation when augmenting requests.
TaskErrorMessage
TaskMessageQueue
Interface for managing server-initiated messages for tasks.
TaskResultHandler
Handles execution and result retrieval for tasks, managing the queue loop.
TaskResultMessage
TaskResultRequest
Parameters for the tasks/result request.
TaskSession
Represents a session of a running task, allowing interaction with the server.
TaskStatusMessage
TaskStatusNotification
Parameters for the notifications/tasks/status notification.
TaskStore
Interface for storing and retrieving tasks.
TaskStreamMessage
Message yielded by the task stream helper.
TextContent
Text content.
TextResourceContents
Resource contents represented as text.
Tool
Definition for a tool that the client can call.
ToolAnnotations
Additional properties describing a Tool to clients.
ToolCallback
Base class for tool callbacks.
ToolChoice
Controls how the model uses tools during sampling.
ToolExecution
Describes how the tool should be executed.
ToolTaskHandler
A handler for a tool that creates and manages tasks.
Transport
Describes the minimal contract for a MCP transport that a client or server can communicate over.
UnknownContent
Represents unknown or passthrough content types.
UnknownResourceContents
Represents unknown or passthrough resource content types.
UnsubscribeRequest
Parameters for the resources/unsubscribe request.
URLElicitationRequiredErrorData
Data structure for URLElicitationRequiredError (-32042).

Enums

AnnotationAudience
Allowed audience values for content/resource annotations.
ElicitationMode
Elicitation mode: 'form' for in-band structured data, 'url' for out-of-band interaction.
ErrorCode
Standard JSON-RPC error codes.
IconTheme
Theme hint for icon rendering.
IncludeContext
Context inclusion options for sampling requests.
LoggingLevel
Severity levels for log messages (syslog levels).
LogLevel
PromptMessageRole
Role associated with a prompt message (user or assistant).
SamplingMessageRole
Role in a sampling message exchange.
StopReason
Reasons why LLM sampling might stop.
TaskStatus
The current state of a task execution.
ToolChoiceMode
Tool selection mode for sampling requests.

Constants

defaultRequestTimeout → const Duration
The default request timeout duration.
jsonRpcVersion → const String
JSON-RPC protocol version string.
latestProtocolVersion → const String
The latest version of the Model Context Protocol supported.
legacyRelatedTaskMetadataKey → const String
Legacy metadata key retained for backward compatibility.
mcpUiExtensionId → const String
MCP extension identifier for UI capabilities.
mcpUiLegacyResourceUriMetaKey → const String
Legacy _meta key used to point tools at a UI resource.
mcpUiResourceMimeType → const String
MIME type used by MCP Apps HTML resources.
mcpUiResourceUriScheme → const String
URI scheme used by MCP Apps UI resources.
relatedTaskMetadataKey → const String
Metadata key for associating a request/notification with a task.
relatedTaskMetaKey → const String
Metadata key for linking a tool execution to a related task.
supportedProtocolVersions → const List<String>
List of supported Model Context Protocol versions.
taskInputKey → const String
Metadata key for the original task input arguments.
taskNameKey → const String
Metadata key for the original task name.

Functions

auth(OAuthClientProvider provider, {required Uri serverUrl, String? authorizationCode}) Future<AuthResult>
Performs authentication with the provided OAuth client
generateUUID() String
Generates a RFC4122 compliant UUID (version 4).
getUiCapability(Object? capabilities) McpUiExtensionCapability?
Returns MCP Apps extension settings from capabilities.
mergeCapabilities<T extends Map<String, dynamic>>(T base, T additional) → T
Merges two capability maps (potentially nested).
registerAppResource(McpServer server, String name, String uri, McpUiAppResourceConfig config, ReadResourceCallback readCallback) RegisteredResource
Registers an MCP Apps UI resource.
registerAppTool(McpServer server, String name, McpUiAppToolConfig config, ToolFunction callback) RegisteredTool
Registers an app tool and normalizes MCP Apps metadata.
resetMcpLogHandler() → void
Restores MCP SDK runtime logging to the default handler.
setMcpLogHandler(LogHandler handler) → void
Sets the log handler used by MCP SDK runtime logging.
silenceMcpLogs() → void
Silences all MCP SDK runtime logs.
withMcpUiExtension({Map<String, Map<String, dynamic>>? extensions, List<String> mimeTypes = const [mcpUiResourceMimeType]}) Map<String, Map<String, dynamic>>
Creates a capabilities map augmented with MCP UI extension settings.

Typedefs

AuthResult = String
Result of an authentication attempt
CallToolRequestParams = CallToolRequest
CancelledNotificationParams = CancelledNotification
Deprecated alias for CancelledNotification.
CancelTaskCallback = FutureOr<void> Function(String taskId, RequestHandlerExtra extra)
Callback to cancel a running task.
CancelTaskRequestParams = CancelTaskRequest
Deprecated alias for CancelTaskRequest.
Client = McpClient
Deprecated alias for McpClient.
ClientOptions = McpClientOptions
Deprecated alias for McpClientOptions.
CompleteCallback = FutureOr<List<String>> Function(String value)
Callback capable of providing completions for a partial value.
CompleteRequestParams = CompleteRequest
Deprecated alias for CompleteRequest.
CompleteResourceTemplateCallback = FutureOr<List<String>> Function(String currentValue)
Callback to complete a value within a resource template.
CreateMessageRequestParams = CreateMessageRequest
Deprecated alias for CreateMessageRequest.
Cursor = String
An opaque token used to represent a cursor for pagination.
DynamicStopReason = dynamic
Type alias allowing StopReason or a custom String reason.
ElicitationCompleteParams = ElicitationCompleteNotification
Deprecated alias for ElicitationCompleteNotification.
ElicitationInputSchema = JsonSchema
Legacy alias for JsonSchema used in elicitation requests.
ElicitRequestParams = ElicitRequest
Deprecated alias for ElicitRequest.
EventId = String
ID for events in SSE streams
GetPromptRequestParams = GetPromptRequest
Deprecated alias for GetPromptRequest.
GetTaskCallback = FutureOr<Task> Function(String taskId, RequestHandlerExtra extra)
Callback to get the status of a task.
GetTaskRequestParams = GetTaskRequest
Deprecated alias for GetTaskRequest.
InitializeRequestParams = InitializeRequest
Deprecated alias for InitializeRequest.
LegacyToolCallback = FutureOr<CallToolResult> Function({Map<String, dynamic>? args, RequestHandlerExtra? extra})
Legacy callback signature for tools (deprecated style).
ListPromptsRequestParams = ListPromptsRequest
Deprecated alias for ListPromptsRequest.
ListResourcesCallback = FutureOr<ListResourcesResult> Function(RequestHandlerExtra extra)
Callback to list available resources.
ListResourcesRequestParams = ListResourcesRequest
Deprecated alias for ListResourcesRequest.
ListResourceTemplatesRequestParams = ListResourceTemplatesRequest
Deprecated alias for ListResourceTemplatesRequest.
ListTasksCallback = FutureOr<ListTasksResult> Function(RequestHandlerExtra extra)
Callback to list available tasks.
ListTasksRequestParams = ListTasksRequest
Deprecated alias for ListTasksRequest.
ListToolsRequestParams = ListToolsRequest
LoggingMessageNotificationParams = LoggingMessageNotification
Deprecated alias for LoggingMessageNotification.
LogHandler = void Function(String loggerName, LogLevel level, String message)
ProgressCallback = void Function(Progress progress)
Callback for progress notifications.
ProgressNotificationParams = ProgressNotification
Deprecated alias for ProgressNotification.
ProgressToken = dynamic
A progress token, used to associate progress notifications with the original request.
PromptCallback = FutureOr<GetPromptResult> Function(Map<String, dynamic>? args, RequestHandlerExtra? extra)
Callback signature for prompts.
ReadResourceCallback = FutureOr<ReadResourceResult> Function(Uri uri, RequestHandlerExtra extra)
Callback to read a specific resource.
ReadResourceRequestParams = ReadResourceRequest
Deprecated alias for ReadResourceRequest.
ReadResourceTemplateCallback = FutureOr<ReadResourceResult> Function(Uri uri, TemplateVariables variables, RequestHandlerExtra extra)
Callback to read a resource template.
RequestId = dynamic
A uniquely identifying ID for a request in JSON-RPC.
ResourceMetadata = ({String? description, String? mimeType})
Metadata for a resource.
ResourceUpdatedNotificationParams = ResourceUpdatedNotification
Deprecated alias for ResourceUpdatedNotification.
ServerOptions = McpServerOptions
Deprecated alias for McpServerOptions.
SetLevelRequestParams = SetLevelRequest
Deprecated alias for SetLevelRequest.
StreamId = String
ID for SSE streams
SubscribeRequestParams = SubscribeRequest
Deprecated alias for SubscribeRequest.
TaskCreationParams = TaskCreation
Deprecated alias for TaskCreation.
TaskResultCallback = FutureOr<CallToolResult> Function(String taskId, RequestHandlerExtra extra)
Callback to get the result of a completed task.
TaskResultRequestParams = TaskResultRequest
Deprecated alias for TaskResultRequest.
TaskStatusNotificationParams = TaskStatusNotification
Deprecated alias for TaskStatusNotification.
TaskStatusString = String
A parsed specific task status string.
ToolFunction = FutureOr<CallToolResult> Function(Map<String, dynamic> args, RequestHandlerExtra extra)
Function signature for a tool implementation.
ToolInputSchema = JsonObject
Legacy alias for JsonObject used as tool input schema.
ToolOutputSchema = JsonObject
Legacy alias for JsonObject used as tool output schema.
UnsubscribeRequestParams = UnsubscribeRequest
Deprecated alias for UnsubscribeRequest.

Exceptions / Errors

AbortError
Error thrown when an operation is aborted via an AbortSignal.
McpError
Custom error class for MCP specific errors.
StreamableHttpError
Error thrown for Streamable HTTP issues
UnauthorizedError
Represents an unauthorized error