Class McpClient
Provides a client for communicating with Model Context Protocol (MCP) servers over HTTP using JSON-RPC 2.0.
public sealed class McpClient : IDisposable
- Inheritance
-
McpClient
- Implements
- Inherited Members
Examples
Example: Connect to MCP server and discover tools
using LMKit.Mcp.Client;
using LMKit.Mcp.Tools;
using System;
using System.Threading.Tasks;
// Create MCP client pointing to a server
using var mcpClient = new McpClient("https://mcp.example.com/api");
// Optional: Set authentication
mcpClient.SetBearerToken("your-api-key");
// Initialize connection
await mcpClient.InitializeAsync();
Console.WriteLine($"Session ID: {mcpClient.SessionId}");
Console.WriteLine($"Protocol: {mcpClient.McpProtocolVersion}");
// Discover available tools
var tools = await mcpClient.GetToolsAsync();
Console.WriteLine($"Available tools: {tools.Count}");
foreach (var tool in tools)
{
Console.WriteLine($"- {tool.Name}: {tool.Description}");
}
Example: Register MCP tools with an Agent
using LMKit.Model;
using LMKit.Agents;
using LMKit.Agents.Tools;
using LMKit.Mcp.Client;
using System;
using System.Threading.Tasks;
LM model = LM.LoadFromModelID("llama-3.2-3b");
// Connect to MCP server
using var mcpClient = new McpClient("https://mcp.example.com/api");
await mcpClient.InitializeAsync();
// Create tool registry and import MCP tools
var tools = new ToolRegistry();
int toolCount = await tools.RegisterAsync(mcpClient);
Console.WriteLine($"Registered {toolCount} tools from MCP server");
// Build agent with MCP tools
Agent agent = new AgentBuilder()
.WithModel(model)
.WithPersona("MCP Assistant")
.WithInstruction("You can use MCP tools to help users.")
.WithTools(tools)
.Build();
// Execute agent with MCP tool access
using var executor = new AgentExecutor();
var result = await executor.ExecuteAsync(agent, "Use the available tools to help me.");
Console.WriteLine(result.Content);
Example: Handle MCP events
using LMKit.Mcp.Client;
using System;
using System.Threading.Tasks;
using var mcpClient = new McpClient("https://mcp.example.com/api");
// Subscribe to events for debugging/monitoring
mcpClient.Sending += (sender, e) =>
{
Console.WriteLine($"Sending request: {e.Method}");
};
mcpClient.Received += (sender, e) =>
{
Console.WriteLine($"Received response: {e.RequestId}");
};
mcpClient.AuthFailed += (sender, e) =>
{
Console.WriteLine($"Authentication failed: {e.Message}");
};
await mcpClient.InitializeAsync();
var tools = await mcpClient.GetToolsAsync();
Remarks
The McpClient handles the complete MCP lifecycle including:
- Establishing and maintaining sessions with MCP servers
- Discovering available tools, resources, and prompts
- Executing tool invocations and resource operations
- Automatic retry logic for transient failures (408, 429, 5xx errors)
- Content negotiation with fallback support
- Real-time server notifications via Server-Sent Events (SSE)
Basic Usage:
// Create a client
using var client = new McpClient("https://api.example.com/mcp");
// Set authentication if required
client.SetBearerToken("your-api-token");
// Initialize the connection (happens automatically on first operation)
await client.InitializeAsync();
// Use the client to discover and call tools
var tools = await client.ListToolsAsync();
var result = await client.CallToolAsync("tool-name", parameters);
The client automatically manages the session lifecycle. If the connection is lost or authentication changes, subsequent operations will re-initialize the session transparently.
Constructors
- McpClient(IMcpTransport)
Initializes a new MCP client using a custom transport implementation.
- McpClient(string, HttpClient)
Initializes a new MCP client using an externally provided HTTP client.
- McpClient(string, TimeSpan?)
Initializes a new MCP client with an internally managed HTTP client.
Properties
- ClientInfoName
Gets or sets the client name sent during MCP initialization.
- ClientInfoTitle
Gets or sets the client title (display name) sent during MCP initialization.
- ClientInfoVersion
Gets or sets the client version sent during MCP initialization.
- InitialAccept
Gets or sets the initial Accept header profile for HTTP requests.
- IsStdioTransport
Gets whether this client is using stdio transport.
- McpProtocolVersion
Gets the MCP protocol version currently in use for communication with the server.
- MinimumLogLevel
Gets the currently configured minimum log level.
- Prompts
Gets a cached view of the server's prompt catalog. On first access, this property blocks to fetch the catalog via GetPromptsAsync(CancellationToken). Use RefreshPrompts(CancellationToken) to force a fresh fetch.
- ResourceTemplates
Gets the cached list of resource templates. On first access, this property blocks to fetch the templates via GetResourceTemplatesAsync(CancellationToken).
- Resources
Gets a cached view of the server's resource catalog. On first access, this property blocks to fetch the catalog via GetResourcesAsync(CancellationToken).
- Roots
Gets the currently configured roots.
- ServerCapabilities
Gets the capabilities supported by the connected MCP server.
- SessionId
Gets the current session identifier for this MCP connection.
- SubscribedResources
Gets the list of currently subscribed resource URIs.
- Tools
Gets the cached tool list returned by
tools/list. If not yet fetched, this property synchronously fetches the list (blocking the current thread). Prefer using GetToolsAsync(CancellationToken) for asynchronous code paths.
- Transport
Gets the underlying transport instance, if using a custom transport.
- TransportType
Gets the transport type being used by this client.
- UserAgent
Gets or sets the User-Agent string sent with HTTP requests.
Methods
- AddRoot(McpRoot, bool)
Adds a root (synchronous wrapper).
- AddRoot(string, string, bool)
Adds a root from a path (synchronous wrapper).
- AddRootAsync(McpRoot, bool, CancellationToken)
Adds a root to the available roots list.
- AddRootAsync(string, string, bool, CancellationToken)
Adds a root from a local filesystem path.
- CancelRequest(long, string)
Sends a cancellation notification (synchronous wrapper).
- CancelRequestAsync(long, string, CancellationToken)
Sends a cancellation notification to the server for an in-progress request. The server SHOULD stop processing the request, but this is not guaranteed.
- ClearRoots(bool)
Clears all roots (synchronous wrapper).
- ClearRootsAsync(bool, CancellationToken)
Clears all roots.
- CreateProgressToken(Action<McpProgressEventArgs>)
Creates a progress token and registers a callback for progress updates. Use this to track long-running operations initiated via tool calls or other requests.
- Dispose()
Releases all resources used by the MCP client.
- ForStdio(StdioTransportOptions)
Creates an MCP client for a stdio-based MCP server with detailed options.
- ForStdio(string, string)
Creates an MCP client for a stdio-based MCP server.
- GetPrompt(string, IDictionary<string, object>, CancellationToken)
Retrieves a fully rendered prompt by name via
prompts/get(blocking wrapper).
- GetPromptAsync(string, IDictionary<string, object>, CancellationToken)
Retrieves a fully rendered prompt by name via
prompts/get.
- GetPromptCompletions(string, string, string, IDictionary<string, object>)
Gets argument completion suggestions for a prompt (synchronous wrapper).
- GetPromptCompletionsAsync(string, string, string, IDictionary<string, object>, CancellationToken)
Gets argument completion suggestions for a prompt.
- GetPrompts(CancellationToken)
Synchronously retrieves the server's prompt catalog. This is a blocking wrapper over GetPromptsAsync(CancellationToken) and returns the cached list thereafter.
- GetPromptsAsync(CancellationToken)
Retrieves the server's prompt catalog. Results are cached after the first call until invalidation or a manual refresh via RefreshPromptsAsync(CancellationToken).
- GetResourceCompletions(string, string, string, IDictionary<string, object>)
Gets argument completion suggestions for a resource URI template (synchronous wrapper).
- GetResourceCompletionsAsync(string, string, string, IDictionary<string, object>, CancellationToken)
Gets argument completion suggestions for a resource URI template.
- GetResourceTemplates(CancellationToken)
Retrieves resource templates (synchronous wrapper).
- GetResourceTemplatesAsync(CancellationToken)
Retrieves the list of resource templates from the server. Resource templates define parameterized URIs (RFC 6570) for dynamic resource access.
- GetResources(CancellationToken)
Retrieves the list of resources offered by the server (synchronous wrapper). Results are cached after the first call until invalidation or a manual refresh.
- GetResourcesAsync(CancellationToken)
Retrieves the list of resources offered by the server. Results are cached after the first call until invalidation or a manual refresh.
- GetTools(CancellationToken)
Retrieves the server’s tool catalog once via
tools/listand caches it for future access.
- GetToolsAsync(CancellationToken)
Retrieves and caches the server’s tool catalog via
tools/list. Concurrent callers share the same underlying fetch task.
- HasCapability(McpServerCapabilities)
Checks whether the server supports a specific capability.
- Initialize(CancellationToken)
Synchronously initializes the MCP session and returns the server's initialization response.
- InitializeAsync(CancellationToken)
Asynchronously initializes the MCP session and returns the server's initialization response.
- ReadResource(string, CancellationToken)
Reads the content of a specific resource from the server (synchronous wrapper).
- ReadResourceAsync(string, CancellationToken)
Reads the content of a specific resource from the server.
- RefreshPrompts(CancellationToken)
Clears the cached prompt catalog and fetches a fresh copy (blocking wrapper).
- RefreshPromptsAsync(CancellationToken)
Clears the cached prompt catalog and fetches a fresh copy from the server (async).
- RefreshResourceTemplatesAsync(CancellationToken)
Clears the cached resource templates and fetches a fresh copy.
- RefreshTools(CancellationToken)
Clears the cached tool list and fetches a fresh catalog via
tools/list.
- RefreshToolsAsync(CancellationToken)
Clears the cached tool list and fetches a fresh catalog via
tools/list.
- RemoveRoot(string, bool)
Removes a root (synchronous wrapper).
- RemoveRootAsync(string, bool, CancellationToken)
Removes a root from the available roots list.
- SendProgress(McpProgressToken, double, double?, string)
Sends a progress notification to the server (synchronous wrapper).
- SendProgressAsync(McpProgressToken, double, double?, string, CancellationToken)
Sends a progress notification to the server (for server-initiated requests). This is typically used when implementing sampling callbacks.
- SetBearerToken(string)
Sets or clears the Bearer token used for authentication with the MCP server.
- SetElicitationHandler(Func<McpElicitationRequest, McpElicitationResponse>)
Sets a synchronous handler function for elicitation requests.
- SetElicitationHandler(Func<McpElicitationRequest, CancellationToken, Task<McpElicitationResponse>>)
Sets a handler function for elicitation requests. This is an alternative to using the ElicitationRequested event.
- SetLogLevel(McpLogLevel)
Sets the minimum log level (synchronous wrapper).
- SetLogLevelAsync(McpLogLevel, CancellationToken)
Sets the minimum log level for server-side logging. The server will only send log messages at or above this level.
- SetSamplingHandler(Func<McpSamplingRequest, McpSamplingResponse>)
Sets a synchronous handler function for sampling requests.
- SetSamplingHandler(Func<McpSamplingRequest, CancellationToken, Task<McpSamplingResponse>>)
Sets a handler function for sampling requests. This is an alternative to using the SamplingRequested event.
- Shutdown(CancellationToken)
Synchronously shuts down the MCP client, clearing all cached state and preparing for potential reuse.
- ShutdownAsync(CancellationToken)
Asynchronously shuts down the MCP client, clearing all cached state and preparing for potential reuse.
- SubscribeToResource(string)
Subscribes to resource updates (synchronous wrapper).
- SubscribeToResourceAsync(string, CancellationToken)
Subscribes to updates for a specific resource. When the resource changes, the ResourceUpdated event will be raised.
- UnregisterProgressToken(McpProgressToken)
Unregisters a progress callback for the specified token. Call this when the operation is complete to clean up resources.
- UnsubscribeFromResource(string)
Unsubscribes from resource updates (synchronous wrapper).
- UnsubscribeFromResourceAsync(string, CancellationToken)
Unsubscribes from updates for a specific resource.
Events
- AuthFailed
Gets or sets a callback invoked when an authentication failure is detected.
- CancellationReceived
Occurs when a cancellation notification is received from the server.
- CatalogChanged
Raised when the server indicates that any catalog has changed (tools, resources, prompts, or roots). Fired after the client invalidates its local cache for that catalog.
- ElicitationRequested
Occurs when the server requests user input via elicitation. This event implements the MCP elicitation capability, allowing servers to request structured information from users through forms.
- LogMessageReceived
Occurs when a log message is received from the server.
- ProgressReceived
Occurs when a progress notification is received from the server.
- PromptsChanged
Raised when the server indicates that the prompt catalog has changed. Fired after the client invalidates its local prompt cache.
- Received
Gets or sets a callback invoked after receiving an HTTP response from the server.
- ResourceUpdated
Occurs when a subscribed resource has been updated on the server.
- ResourcesChanged
Raised when the server indicates that the resource catalog has changed. Fired after the client invalidates its local resource cache.
- RootsRequested
Occurs when the server requests the list of available roots. This event implements the MCP roots capability, allowing servers to discover which filesystem boundaries they can operate within.
- SamplingRequested
Occurs when the server requests LLM sampling from the client. This event implements the MCP sampling capability, allowing servers to request AI completions while the client maintains control over model access.
- Sending
Invoked immediately before sending an HTTP request to the server.
- ToolsChanged
Raised when the server indicates that the tool catalog has changed. Fired after the client invalidates its local tool cache.