mcp_host library
Kernel sub-barrel for the reference MCP host adapters.
Hosts that want a mcp_server + mcp_client backed surface import
this barrel in addition to package:brain_kernel/brain_kernel.dart.
The main barrel exposes only the KernelServerHost /
KernelClientHost abstracts; this barrel surfaces the reference
impls (ServerBootstrap aka McpServerKernelHost,
McpClientKernelHost) plus the raw mcp_server / mcp_client
types so hosts can reach out to wire-shape APIs (custom prompts,
resource subscriptions, OAuth, etc).
Usage:
import 'package:brain_kernel/brain_kernel.dart';
import 'package:brain_kernel/mcp_host.dart';
final app = await KernelApp.boot(
workspaceId: 'studio',
kvStorage: kv,
serverHostFactory: ServerBootstrap.factory, // MCP server-backed
clientHost: McpClientKernelHost(), // outbound calls
);
Hosts that never expose a server transport omit serverHostFactory
(kernel falls back to in-process). Hosts that never make outbound
calls omit clientHost.
Classes
- ApiKeyValidator
- Simple API key validator
- AudioContent
- Audio content (spec 2025-03-26+).
- AuthContext
- Authorization context for MCP requests
- AuthMiddleware
- Authentication middleware for HTTP requests
- AuthResult
- Authentication result
- BooleanSchema
-
Boolean primitive schema (SEP-1034
default). - CachedResource
- Cached resource item for performance optimization
- CallToolResult
- Tool call result.
- CancellationToken
- Cancellation token for async operations
- Client
- Main MCP Client class that handles all client-side protocol operations
- ClientSession
- Client session information
- CompletionsCapability
-
Completions capability — server advertises support for argument
autocompletion via the
completion/completerequest (spec). - Content
- Base class for all MCP content types (2025-03-26 compliant)
- CreateMessageRequest
- Create message request for sampling
- CreateMessageResult
- Create message result from sampling
- DeprecationInfo
- Deprecation information
- ElicitationRequest
- A typed builder for the standard (form-mode) elicitation request params.
- ElicitationSchema
- Base type for elicitation primitive schema definitions.
- EnumSchema
-
Enum primitive schema (SEP-1330 single- and multi-select, SEP-1034
default). enumNames provides human-readable titles parallel to values; null means untitled (clients display the raw value). - ErrorCode
- Error codes for standardized error handling
- EventMessage
- Event message with optional ID for SSE.
- ExtensionTransportConnect
- Injected-transport seam companion to KernelClientHost.
-
Failure<
T, E extends Object> - Represents a failed result
- GetPromptResult
- Get prompt result
- ImageContent
- Image content representation
- InputRequiredResult
-
Draft
InputRequiredResult— sent by the server to signal that additional input is needed before the original request can complete. - 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.
- Logger
- Use a Logger to log debug messages.
- LoggingCapability
- Logging capability
- LogRecord
- A log entry representation used to propagate information from Logger to individual handlers.
- McpClientKernelHost
- McpErrorCodes
- MCP Error codes as defined in the specification
- McpMethodAuth
- MCP method authorization configuration
- McpMethods
- Standard MCP methods that must be implemented
- McpMrtr
-
Server-side helpers for the re-issued request's
InputResponseRequestParams(inputResponses+requestState). - McpProtocol
- MCP Protocol Version constants and definitions
- McpRequestMeta
-
Reverse-DNS
_metakeys and typed read/write helpers for the 2026-07-28 stateless core (SEP-2577). - McpResultType
-
Draft
ResultTypediscriminator values (schema.tsResultType). - McpServer
- Modern MCP Server factory with enhanced configuration and error handling
- McpServerConfig
- Configuration for creating MCP servers
- Message
- Message model for prompt system
- ModelHint
- Model hint for sampling
- ModelPreferences
- Model preferences for sampling
- NumberSchema
-
Number / integer primitive schema (SEP-1034
default). - OAuthTokenValidator
- OAuth 2.1 token validator
- PendingOperation
- Pending operation for cancellation support
- ProgressCapability
- Progress capability
- ProgressNotification
- Progress notification data (2025-03-26)
- Prompt
- Prompt definition
- PromptArgument
- Prompt argument definition
- PromptMessage
- Prompt message (2025-03-26)
- PromptsCapability
- Prompts capability
- RawElicitationSchema
- Escape hatch preserving an unrecognized primitive schema map verbatim.
- ReadResourceResult
- Resource read result
- Resource
- Resource definition
- ResourceContent
- Resource content representation
- ResourceContentInfo
- Resource content info (used in ReadResourceResult)
- ResourceLinkContent
- Resource link content (spec 2025-06-18+) — a tool result that points to a server resource by URI without inlining the content.
- ResourcesCapability
- Resources capability
- ResourceTemplate
- Resource template definition
- ResourceUsage
- Resource usage indicators
-
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
- RootsCapability
- Roots capability
- SamplingCapability
- Sampling capability
- SamplingTool
- A tool definition offered to the client's LLM during sampling (spec 2025-11-25 sampling tool calling, SEP-1577).
- Server
- Main MCP Server class that handles all server-side protocol operations
- ServerBootstrap
- ServerCapabilities
- Server capabilities configuration for MCP 2025-03-26 protocol
- ServerHealth
- Server health information
- ServerInterface
- Interface for server to expose key functionality for testing
- ServerTransport
- Abstract base class for server transport implementations
- SseClientTransport
- Transport implementation using Server-Sent Events (SSE) over HTTP
- SseServerTransport
- Transport implementation using Server-Sent Events (SSE) over HTTP
- SseStreamInfo
- SSE stream information for request-specific streams
- SseTransportConfig
- StdioClientTransport
- Transport implementation using standard input/output streams
- StdioServerTransport
- Transport implementation using standard input/output streams
- StdioTransportConfig
- StreamableHttpClientTransport
- Streamable HTTP client transport for MCP
- StreamableHttpServerConfig
- Configuration for StreamableHTTP server transport
- StreamableHttpServerTransport
- MCP 2025-03-26 StreamableHTTP Server Transport Implementation Supports both JSON responses and SSE streaming according to MCP standard
- StreamableHttpTransportConfig
- StringSchema
-
String primitive schema (SEP-1034
default). - SubscriptionFilter
-
Draft
SubscriptionFilter— the opt-in set of notification types a client requests on asubscriptions/listenstream. The server MUST NOT deliver a notification type the client did not request here. -
Success<
T, E extends Object> - Represents a successful result
- Task
-
State of an asynchronous task (ext-tasks
Task/DetailedTask). - TextContent
- Text content representation
- TokenValidator
- Token validation interface
- Tool
- Tool definition (2025-03-26 compliant)
- ToolAnnotationBuilder
- Tool annotation builder for creating standard annotations
- ToolAnnotationKeys
- Standard tool annotation keys defined in MCP 2025-03-26
- ToolAnnotationPresets
- Common tool annotation presets
- ToolAnnotationUtils
- Utility functions for working with tool annotations
- ToolChoice
- Controls how / whether the model selects tools during sampling (spec 2025-11-25 sampling tool calling, SEP-1577).
- ToolsCapability
- Tools capability
- TransportConfig
- Configuration for transport connections
- UrlElicitationRequest
-
URL-mode elicitation request (SEP-1036): the server asks the client to
open url so the user can complete an out-of-band interaction (e.g. an
OAuth consent). Produces
{ mode: "url", message, url }. Additive over the raw-map path.
Enums
- MCPContentType
- McpLogLevel
- Log levels for MCP protocol
- MessageRole
- Base content type enum for MCP
- PromptMessageRole
- Prompt message roles
- TaskStatus
- Lifecycle status of a Task.
- ToolPriority
- Tool priority levels
Extensions
-
FutureResultExtensions
on Future<
Result< T, E> > -
Extension methods for
Future<Result> - LoggerExtensions on Logger
- OAuthServerMethods on Server
Constants
- defaultLevel → const Level
- The default Level.
- getStreamKey → const String
- mcpProtocolVersionHeader → const String
- HTTP header carrying the MCP protocol version (2025-06-18+, and the sole version signal on the 2026-07-28 stateless path).
- tasksExtensionId → const String
-
Reverse-DNS identifier for the tasks extension, used as a key in
capabilities.extensions. Its value is an 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
Functions
-
attachStderrLogSink(
{Level? level}) → StreamSubscription< LogRecord> - Route all log records to stderr so a stdio-based MCP host cannot have its stdout — which carries the protocol JSON-RPC stream — corrupted by log output. Opt-in and idempotent: call it once during startup on the stdio transport. 2025-11-25 clarifies servers may emit logs at any level to stderr on the stdio transport.
-
connectExtension(
KernelClientHost? clientHost, {required String id, required ClientTransport transport}) → Future< KernelClientConnection> -
Canonical way to drive the extension-transport seam off a — possibly
null, possibly non-capable —
clientHost. Probes ExtensionTransportConnect and injectstransport, or throws a StateError if the host cannot. -
detachStderrLogSink(
) → Future< void> - Remove the stderr log sink installed by attachStderrLogSink. Safe to call when no sink is attached.
Typedefs
-
CompletionHandler
= Future<
Map< Function(Map<String, dynamic> >String, dynamic> ref, Map<String, dynamic> argument, Map<String, dynamic> ? context) -
Type definition for completion handler functions (spec
completion/complete). - IsCancelledCheck = bool Function()
- Callback type for checking if operation is cancelled
- MCPServer = McpServer
- ProgressCallback = void Function(double progress, String message)
- Callback type for tool execution progress updates
-
PromptHandler
= Future Function(Map<
String, dynamic> arguments) - Type definition for prompt handler functions
-
ResourceHandler
= Future Function(String uri, Map<
String, dynamic> params) - Type definition for resource handler functions
- SseServerConfig = SseTransportConfig
-
ToolHandler
= Future Function(Map<
String, dynamic> arguments) - Type definition for tool handler functions with cancellation and progress reporting
Exceptions / Errors
- CancelledException
- Exception thrown when an operation is cancelled
- McpError
- Error class for MCP-related errors