Table of Contents

Method InitializeAsync

Namespace
LMKit.Mcp.Client
Assembly
LM-Kit.NET.dll

InitializeAsync(CancellationToken)

Asynchronously initializes the MCP session and returns the server's initialization response.

public Task<JsonDocument> InitializeAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

A cancellation token to cancel the initialization operation.

Returns

Task<JsonDocument>

A task that represents the asynchronous operation. The task result is a JsonDocument containing a copy of the server's JSON-RPC initialize response payload. Each call returns a fresh clone, so you can safely dispose of it without affecting the cached version.

Examples

var client = new McpClient("https://api.example.com/mcp");
client.SetBearerToken("your-token");

// Explicitly initialize and inspect server info
using var initResponse = await client.InitializeAsync();
var serverName = initResponse.RootElement
    .GetProperty("result")
    .GetProperty("serverInfo")
    .GetProperty("name")
    .GetString();

Console.WriteLine($"Connected to: {serverName}");

Remarks

If the client is already initialized, this method returns immediately with a cached copy of the initialization response. Otherwise, it performs the complete MCP handshake:

  1. Sends an initialize request to the server
  2. Receives and processes the server's response (including capabilities and protocol version)
  3. Sends a notifications/initialized message to confirm readiness
  4. Starts listening for server notifications via SSE (if supported)

You typically don't need to call this method explicitly, as the client initializes automatically on the first operation (e.g., listing tools or calling a tool). However, you may want to call it explicitly to:

  • Validate connectivity before performing operations
  • Pre-warm the connection
  • Access server metadata from the initialization response

Multiple concurrent callers share the same initialization task, ensuring the handshake only happens once even under high concurrency.

Exceptions

ObjectDisposedException

Thrown if the client has been disposed.

HttpRequestException

Thrown on HTTP failures, JSON-RPC errors, or malformed responses from the server.

OperationCanceledException

Thrown if the operation is canceled via cancellationToken.