mcp_client library

Kernel sub-barrel for outbound MCP client usage.

mcp_client is exposed through a dedicated entry point (rather than the main brain_kernel.dart barrel) because its model classes — Content / TextContent / ImageContent / CallToolResult / transport configs — collide pervasively with mcp_server's same-named classes. Rolling them into the main barrel forces every domain consumer to disambiguate. Splitting the surfaces keeps the main barrel clean for the typical builder usage (server-side MCP + bundle + LLM) while still letting tools that genuinely need outbound clients (inspector probes, cross-server wiring) reach the types through the kernel.

Usage:

import 'package:brain_kernel/mcp_client.dart';

final result = await McpClient.createAndConnect(
  config: const McpClientConfig(...),
);
if (result.content.first is TextContent) { ... }

Domain code that imports both brain_kernel.dart (for the server / bundle types) and this file should use a prefix on one of them to silence the expected collisions on Content / etc.

Classes

AudioContent
Audio content (spec 2025-03-26+).
AuthenticatedEventSource
Authenticated EventSource implementation
AuthServerMetadata
Authorization server metadata (RFC8414)
BooleanElicitationField
A boolean field. Carries an optional defaultValue (SEP-1034).
CachedResource
Cached resource item for performance optimization
CallToolRequest
Call tool request
CallToolResult
Tool call result. Spec 2025-06-18 added structuredContent (paired with Tool.outputSchema).
CancelRequestNotification
Cancel request notification
Client
Main MCP Client class that handles all client-side protocol operations
ClientCapabilities
Client capabilities configuration
ClientInfo
Client information (2025-03-26 compliant).
ClientTransport
Abstract base class for client transport implementations
CompletionRequest
Completion request
CompletionResult
Completion result
CompressedEventSource
Compressed EventSource implementation
Connected
The connection is established and ready
Connecting
The connection is in the process of connecting
ConnectionError
The connection has failed with an error
ConnectionState
Represents the various states of an MCP connection
Content
Base class for all MCP content types (2025-03-26 compliant)
CreateMessageRequest
Create message request for sampling.
CreateMessageResult
Create message result from sampling.
Disconnected
The connection is disconnected
Disconnecting
The connection is in the process of disconnecting
DiscoverResult
Result of a server/discover call (2026-07-28 stateless core).
ElicitationFieldSchema
Base type for a single field inside an elicitation requestedSchema.
ElicitationRequest
Typed view over an elicitation/create request's params.
ElicitationResponse
Typed response to an elicitation request. Serializes to the spec { action, content? } shape.
EnumElicitationField
A single-select enum field. Carries the enumSchema (values + optional enumNames) and an optional defaultValue (SEP-1034).
EnumSchema
The enum descriptor shared by single- and multi-select elicitation fields (spec 2025-11-25). names mirrors enumNames positionally: when present the enum is titled (each value has a display label); when null the enum is untitled (display the raw value).
Failure<T, E extends Object>
Represents a failed result
GenericElicitationField
Fallback for a field shape this layer does not specialize. Preserves the raw JSON Schema fragment so nothing is lost.
GetPromptRequest
Get prompt request
GetPromptResult
Get prompt result
HeartbeatConfig
Heartbeat configuration
HeartbeatEventSource
Heartbeat-enabled EventSource implementation
HeartbeatStats
Heartbeat statistics
HttpOAuthClient
HTTP-based OAuth 2.1 client implementation
ImageContent
Image content representation
InitializeRequest
Initialize request
InitializeResult
Initialize result
InputRequiredResult
Draft InputRequiredResult — the server needs more input before the original request can complete. At least one of inputRequests / requestState is present; requestState is an OPAQUE blob the client MUST NOT interpret and echoes back verbatim on retry.
JsonRpcMessage
JSON-RPC message
Level
Levels to control logging output. Logging can be enabled to include all levels above certain Level. Levels are ordered using an integer value Level.value. The predefined Level constants below are sorted as follows (in descending order): Level.SHOUT, Level.SEVERE, Level.WARNING, Level.INFO, Level.CONFIG, Level.FINE, Level.FINER, Level.FINEST, and Level.ALL.
ListPromptsResult
List prompts result
ListResourcesResult
List resources result
ListToolsResult
List tools result
Logger
Use a Logger to log debug messages.
LogMessageNotification
Log message notification
LogRecord
A log entry representation used to propagate information from Logger to individual handlers.
McpClient
Modern MCP Client factory with enhanced error handling and configuration
McpClientConfig
Configuration for creating MCP clients
McpProtocol
MCP protocol versions and constants
McpRequestMeta
Reverse-DNS _meta key constants and typed accessors for the stateless core. All keys sit under the reserved io.modelcontextprotocol/ prefix.
McpResultType
Draft ResultType discriminator values (schema.ts ResultType).
Message
Message model for prompt system
ModelHint
Model hint for sampling
ModelPreferences
Model preferences for sampling
MultiSelectEnumElicitationField
A multi-select enum field (SEP-1330): a JSON Schema array whose items are an enum. Carries the shared enumSchema, an optional list defaultValue (SEP-1034), and array constraints.
NumberElicitationField
A numeric field (number or integer). Carries an optional defaultValue (SEP-1034).
OAuthClient
OAuth client interface
OAuthConfig
OAuth 2.1 authentication configuration
OAuthDiscoveryResult
Result of resolving a 401 challenge into concrete OAuth endpoints (RFC 9728 PRM + RFC 8414/OIDC authorization-server discovery).
OAuthError
OAuth error response
OAuthToken
OAuth 2.1 token response
OAuthTokenManager
OAuth token manager with automatic refresh
PendingOperation
Pending operation for cancellation support
ProgressNotification
Progress notification
ProgressUpdate
Progress update for long-running operations
Prompt
Prompt definition
PromptArgument
Prompt argument definition
PromptsListChangedNotification
Prompts list changed notification
ProtectedResourceMetadata
OAuth 2.0 Protected Resource Metadata (RFC 9728), served at /.well-known/oauth-protected-resource by a Resource Server.
ProtocolCapabilities
Protocol capabilities
ReadResourceRequest
Read resource request
ReadResourceResult
Resource read result
Resource
Resource definition
ResourceContent
Resource content representation
ResourceContentInfo
Resource content
ResourceLinkContent
Resource link content (spec 2025-06-18+).
ResourcesListChangedNotification
Resources list changed notification
ResourceTemplate
Resource template definition
ResourceUpdatedNotification
Resource updated notification
Result<T, E extends Object>
A sealed class representing the result of an operation that can succeed or fail
Results
Utility functions for working with Results
Root
Root definition for filesystem access
SamplingToolChoice
Builders for the sampling CreateMessageRequest.toolChoice directive (spec 2025-11-25+). The wire value is intentionally kept loose (see the field doc) — these helpers produce the two canonical shapes without forcing callers to hand-write maps.
Semaphore
Semaphore for controlling concurrent requests
ServerCapabilities
Server capabilities
ServerHealth
Server health information
ServerInfo
Server information (2025-03-26 compliant)
SseAuthClientTransport
SSE Transport with Bearer Token Authentication
SseClientTransport
Transport implementation using Server-Sent Events (SSE) over HTTP
SseCompressedClientTransport
SSE Transport with automatic compression support
SseHeartbeatClientTransport
SSE Transport with heartbeat monitoring
SseTransportConfig
StdioClientTransport
Transport implementation using standard input/output streams
StdioTransportConfig
StreamableHttpClientTransport
Streamable HTTP client transport for MCP
StreamableHttpTransportConfig
StringElicitationField
A free-text string field. Carries an optional defaultValue (SEP-1034).
Subscription
A live 2026-07-28 subscriptions/listen subscription handle (SEP-2577).
SubscriptionFilter
Draft SubscriptionFilter — the opt-in set of notification types the client requests on a subscriptions/listen stream. The server MUST NOT deliver a type not requested here.
SubscriptionNotification
A single notification delivered on a Subscription stream.
Success<T, E extends Object>
Represents a successful result
Task
A task handle / detailed state as returned by a CreateTaskResult or a tasks/get response.
TextContent
Text content representation
TokenLifecycleEvent
Token lifecycle event.
Tool
Tool definition. Spec 2025-06-18+ added outputSchema, _meta, and the title display name (separate from programmatic name). Spec 2025-11-25+ added icons.
ToolCallTracking
Class to hold result of a tracked tool call
ToolMetadata
Lightweight tool metadata (name + description only) Used for token-efficient LLM context in deferred loading mode
ToolRegistry
Cache layer for tool definitions Provides metadata extraction and full schema lookup LLM-agnostic: can be used without mcp_llm
ToolsListChangedNotification
Tools list changed notification
TransportConfig
Configuration for transport connections
WwwAuthenticateChallenge
A parsed WWW-Authenticate: Bearer … challenge (RFC 6750 / RFC 9728).

Enums

CompressionType
Compression types supported
ConnectionHealth
Connection health status
DisconnectReason
Reason for disconnection
ElicitationAction
The action a user took in response to an elicitation request.
ElicitationMode
Presentation mode of an elicitation request.
MCPContentType
McpLogLevel
Log levels for MCP protocol
MessageRole
Base content type enum for MCP
OAuthGrantType
OAuth 2.1 grant types supported by MCP
TaskStatus
Lifecycle status of a Task.
TokenEventType
Token lifecycle event types.

Extensions

ClientToolMetadataExtension on Client
Extension on Client for easy metadata access in deferred loading mode
FutureResultExtensions on Future<Result<T, E>>
Extension methods for Future<Result>
LoggerExtensions on Logger

Constants

defaultLevel → const Level
The default Level.
tasksExtensionId → const String
Reverse-DNS identifier for the tasks extension (a key in capabilities.extensions, empty settings object).

Properties

hierarchicalLoggingEnabled bool
Whether to allow fine-grain logging and configuration of loggers in a hierarchy.
getter/setter pair
recordStackTraceAtLevel Level
Automatically record stack traces for any message of this level or above.
getter/setter pair

Typedefs

MCPClient = McpClient

Exceptions / Errors

McpError
Error class for MCP-related errors