Server class

Main MCP Server class that handles all server-side protocol operations

Implemented types
Available extensions

Constructors

Server({required String name, required String version, String? description, String? title, String? websiteUrl, List<McpIcon>? icons, String? instructions, ServerCapabilities capabilities = const ServerCapabilities(), int? pageSize, bool serverInfoInResults = true, Duration cacheTtl = Duration.zero, bool publicLists = false, Duration progressMinInterval = const Duration(milliseconds: 50), McpTaskStore? taskStore})
Creates a new MCP server with the specified parameters

Properties

cacheTtl → Duration
ttlMs on 2026-07-28 cacheable results (server/discover, the list operations, resources/read). Zero, the default, says "revalidate": only the server knows how long its data stays valid.
final
capabilities → ServerCapabilities
Server capabilities configuration
final
currentRequestCancelled → bool
Whether the request whose handler is running in the current zone has been cancelled by its client. Handlers check it to stop early.
no setter
currentTask → McpTaskContext?
The task whose work is running in the current zone, if any.
no setter
defaultCacheMaxAge → Duration
Default cache duration
final
description → String?
Spec 2025-11-25: optional human-readable description of the server (Implementation.description). Emitted inside serverInfo on initialize when non-null.
final
hashCode → int
The hash code for this object.
no setterinherited
icons → List<McpIcon>?
Icons for the server (serverInfo.icons, 2025-11-25+).
final
instructions → String?
Optional natural-language guidance about the server and its features (DiscoverResult.instructions on 2026-07-28). Surfaced by server/discover when set; the handshake initialize result does not carry it. Additive — null by default.
final
isAuthenticationEnabled → bool
Whether OAuth authentication is currently enabled.
no setter
isConnected → bool
Whether the server is currently connected
no setter
name → String
Name of the MCP server
final
onClientProgress ← void Function(String sessionId, Map<String, dynamic> params)?
no getter
onConnect → Stream<ClientSession>
Stream of session connection events
no setteroverride
onDisconnect → Stream<ClientSession>
Stream of session disconnection events
no setteroverride
onPromptsChanged → Stream<void>
Stream of prompts change events
no setter
onResourcesChanged → Stream<void>
Stream of resources change events
no setter
onResourceSubscribed → Stream<String>
Stream of resource subscription events (emits resource URI)
no setter
onResourceUnsubscribed → Stream<String>
Stream of resource unsubscription events (emits resource URI)
no setter
onToolsChanged → Stream<void>
Stream of tools change events
no setter
pageSize → int?
Items per page of tools/list, resources/list, resources/templates/list and prompts/list; null = one page.
final
progressMinInterval → Duration
The shortest gap between two progress notifications for one request (progress notifications are rate limited so a busy handler cannot flood the client).
final
protectedResourceMetadata → Map<String, dynamic>?
Spec 2025-06-18 (RFC 9728): metadata for the server as an OAuth 2.0 Protected Resource. Returns null until configureProtectedResource has been called.
no setter
publicLists → bool
Whether list and discover results are the same for every caller, so they may be cached across callers (cacheScope: "public"). Off by default: a server that filters lists per user must not say public.
final
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
serverInfoInResults → bool
Whether 2026-07-28 results carry _meta["io.modelcontextprotocol/serverInfo"] (the specification recommends it unless configured otherwise).
final
supportedProtocolVersions → List<String>
Protocol versions this server implements
final
taskStore → McpTaskStore
The tasks this server runs (it is their receiver).
final
title → String?
Display name (serverInfo.title, 2025-06-18+).
final
version → String
Version of the MCP server implementation
final
websiteUrl → String?
The server's website (serverInfo.websiteUrl, 2025-11-25+).
final

Methods

addCompletion({required String refType, required String refKey, required CompletionHandler handler}) → void
Register a completion handler for argument autocompletion (spec completion/complete).
addPrompt({required String name, required String description, required List<PromptArgument> arguments, required PromptHandler handler, String? title, List<Map<String, dynamic>>? icons, Map<String, dynamic>? meta}) → void
Add a prompt to the server
override
addPromptMap({required String name, required String description, required List<Map<String, dynamic>> arguments, required PromptHandler handler, String? title, List<Map<String, dynamic>>? icons, Map<String, dynamic>? meta}) → void
Map-based variant of addPrompt — accepts the prompt arguments as raw spec JSON ([{name, description, required?, default?}]). Sibling for adapters that hold the server as dynamic and so can't synthesise List<PromptArgument> at the call site.
addResource({required String uri, required String name, required String description, required String mimeType, Map<String, dynamic>? uriTemplate, required ResourceHandler handler, String? title, List<Map<String, dynamic>>? icons, Map<String, dynamic>? meta, int? size, Annotations? annotations}) → void
Add a resource to the server
override
addResourceTemplate(ResourceTemplate template) → void
Add a resource template
addRoot(Root root) → void
Add a server-side root entry to the local cache.
addTool({required String name, required String description, required Map<String, dynamic> inputSchema, required ToolHandler handler, String? title, Map<String, dynamic>? outputSchema, List<Map<String, dynamic>>? icons, Map<String, dynamic>? meta, ToolAnnotations? annotations, ToolExecution? execution}) → void
Add a tool to the server
override
addToolWithProgress(String name, String description, Map<String, dynamic> inputSchema, Future<CallToolResult> handler(Map<String, dynamic> arguments, {dynamic onProgress(double, String)?})) → void
Add a tool with progress support
cacheResource(String uri, ReadResourceResult content, [Duration? maxAge]) → void
Cache a resource
callTool(String name, Map<String, dynamic> arguments) → Future<CallToolResult>
Call a tool through its registered handler, in-process. The handler may return any value with the protocol's JSON form (toJson()), as on the wire, so a result built with another package's generated types arrives as this package's CallToolResult.
callToolWithCancellation(String name, Map<String, dynamic> arguments, String operationId) → Future<CallToolResult>
Call a tool with cancellation support
cancelOperation(String operationId) → void
Cancel an operation
clientTaskCancel(String sessionId, String taskId) → Future<Map<String, dynamic>>
tasks/cancel on a task the client runs.
clientTaskGet(String sessionId, String taskId) → Future<Map<String, dynamic>>
tasks/get on a task the client runs.
clientTaskResult(String sessionId, String taskId, {Duration timeout = const Duration(hours: 1)}) → Future<Map<String, dynamic>>
tasks/result on a task the client runs (waits for it to end).
configureMethodRateLimit(String method, RateLimitConfig config) → void
Configure rate limit for specific method
configureProtectedResource({required String resource, required List<String> authorizationServers, List<String>? scopesSupported, List<String>? bearerMethodsSupported, String? resourceDocumentation}) → void
Configure the OAuth Protected Resource metadata served at /.well-known/oauth-protected-resource (RFC 9728).
connect(ServerTransport transport) → void
Connect the server to a transport
describe() → Map<String, dynamic>
disableAuthentication() → void
Disable OAuth authentication.
disableRateLimiting() → void
Disable rate limiting
disconnect() → void
Disconnect the server from its transport
disconnectSession(String sessionId) → void
Disconnect a specific session
dispose() → void
Dispose server resources
enableAuthentication(TokenValidator validator, {List<String> publicPaths = const ['/health', '/ping'], List<String> defaultRequiredScopes = const [], bool strictMode = true, List<String> requiredScopes(String method, Map<String, dynamic>? params)?, bool scopeImplies(String granted, String needed)?}) → void
Enable OAuth authentication with the specified validator.
enableRateLimiting({RateLimitConfig? defaultConfig, Map<String, RateLimitConfig>? methodConfigs}) → void
Enable rate limiting with optional configuration
getCachedResource(String uri) → CachedResource?
Get cached resource if available
getHealth() → ServerHealth
Get server health information
override
getMetrics() → Map<String, dynamic>
Get complete metrics
getPrompt(String name, [Map<String, dynamic>? arguments]) → Future<GetPromptResult>
Get a prompt through its registered handler, in-process — the lookup prompts/get uses. The handler's result is read as on the wire.
getPrompts() → List<Prompt>
Get all registered prompts
override
getRateLimitStats() → Map<String, dynamic>
Get rate limit statistics
getResources() → List<Resource>
Get all registered resources
override
getSessions() → List<ClientSession>
Get all active sessions
override
getTools() → List<Tool>
Get all registered tools
override
hasSession(String sessionId) → bool
Check if session exists
incrementMetric(String name, [int amount = 1]) → void
Increment metric counter
invalidateCache(String uri) → void
Invalidate cache for a resource
isOperationCancelled(String operationId) → bool
Check if operation is cancelled
isPathWithinRoots(String sessionId, String path) → bool
Check if a path is within client roots
listRoots() → List<Root>
Get all server roots
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
notifyElicitationComplete(String sessionId, String elicitationId) → void
Tell the client that started URL-mode elicitation elicitationId that the interaction is complete (notifications/elicitation/complete, 2025-11-25). Only that client is told, and only about an id this server issued to it.
notifyProgress(String operationId, double progress, String message, {double? total}) → void
Send progress notification for a tool operation
notifyResourceUpdated(String uri, {Object? content}) → void
Send notifications/resources/updated for uri to the sessions subscribed to it (on 2026-07-28, to the subscriptions/listen streams that watch it).
pingClient(String sessionId, {Duration timeout = const Duration(seconds: 10)}) → Future<void>
Ping the client (ping, either party may send it). Completes when the client answers; throws TimeoutException (after sending notifications/cancelled) when it does not.
readResource(String uri, [Map<String, dynamic>? params]) → Future<ReadResourceResult>
Read a resource by URI through its registered handler — the same lookup resources/read uses (exact URI, then RFC 6570 templates that have a handler). A template registered without a handler has nothing to read. params reach the handler as the request params would.
registerOperation(String sessionId, String type) → PendingOperation
Register a pending operation for cancellation support
registerToolCall(String toolName, String sessionId, dynamic requestId, {Object? progressToken}) → String
Register a tool call and get an operation ID for progress/cancellation
removeCompletion({required String refType, required String refKey}) → void
Remove a completion handler.
removePrompt(String name) → void
Remove a prompt from the server
override
removeResource(String uri) → void
Remove a resource from the server
override
removeRoot(String uri) → void
Remove a server-side cached root entry (see addRoot for the direction caveat).
removeTool(String name) → void
Remove a tool from the server
override
requestClientElicitation(String sessionId, Map<String, dynamic> params, {Duration timeout = const Duration(seconds: 120)}) → Future<Map<String, dynamic>>
Server-initiated request: ask the connected client to elicit input from the user (spec 2025-06-18 elicitation/create).
requestClientRoots(String sessionId, {Duration timeout = const Duration(seconds: 30)}) → Future<List<Root>>
Server-initiated request: ask the connected client for its current list of filesystem / URI roots (spec roots/list).
requestClientSampling(String sessionId, Map<String, dynamic> params, {Duration timeout = const Duration(seconds: 60)}) → Future<Map<String, dynamic>>
Server-initiated request: ask the connected client's LLM to generate a completion (spec sampling/createMessage).
requestClientTask(String sessionId, String method, Map<String, dynamic> params, {int? ttl, Duration timeout = const Duration(seconds: 60)}) → Future<Map<String, dynamic>>
2025-11-25, server as requestor: send method (sampling/createMessage or elicitation/create) to the client as a task. Only when the client declared tasks.requests for it. Returns the client's task; follow it with clientTaskGet / clientTaskResult / clientTaskCancel.
sendLog(McpLogLevel level, String message, {String? logger, dynamic data}) → void
Send a logging notification to the client
sendProgressNotification(String sessionId, Object progressToken, double progress, [double? total, String? message]) → void
Send progress notification to the client
startTimer(String name) → Stopwatch
Start timer for a metric
stopTimer(String name) → void
Stop timer for a metric
toString() → String
A string representation of this object.
inherited

Operators

operator ==(Object other) → bool
The equality operator.
inherited