{"repo_name": "csharp-sdk", "file_name": "/csharp-sdk/src/ModelContextProtocol.Core/Client/StdioClientSessionTransport.cs", "inference_info": {"prefix_code": "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics;\n\nnamespace ModelContextProtocol.Client;\n\n/// Provides the client side of a stdio-based session transport.\ninternal sealed class StdioClientSessionTransport : StreamClientSessionTransport\n{\n private readonly StdioClientTransportOptions _options;\n private readonly Process _process;\n private readonly Queue _stderrRollingLog;\n private int _cleanedUp = 0;\n\n public StdioClientSessionTransport(StdioClientTransportOptions options, Process process, string endpointName, Queue stderrRollingLog, ILoggerFactory? loggerFactory)\n : base(process.StandardInput.BaseStream, process.StandardOutput.BaseStream, encoding: null, endpointName, loggerFactory)\n {\n _process = process;\n _options = options;\n _stderrRollingLog = stderrRollingLog;\n }\n\n /// \n public override async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n try\n {\n await base.SendMessageAsync(message, cancellationToken);\n }\n catch (IOException)\n {\n // We failed to send due to an I/O error. If the server process has exited, which is then very likely the cause\n // for the I/O error, we should throw an exception for that instead.\n if (await GetUnexpectedExitExceptionAsync(cancellationToken).ConfigureAwait(false) is Exception processExitException)\n {\n throw processExitException;\n }\n\n throw;\n }\n }\n\n /// \n ", "suffix_code": "\n\n private async ValueTask GetUnexpectedExitExceptionAsync(CancellationToken cancellationToken)\n {\n if (!StdioClientTransport.HasExited(_process))\n {\n return null;\n }\n\n Debug.Assert(StdioClientTransport.HasExited(_process));\n try\n {\n // The process has exited, but we still need to ensure stderr has been flushed.\n#if NET\n await _process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);\n#else\n _process.WaitForExit();\n#endif\n }\n catch { }\n\n string errorMessage = \"MCP server process exited unexpectedly\";\n\n string? exitCode = null;\n try\n {\n exitCode = $\" (exit code: {(uint)_process.ExitCode})\";\n }\n catch { }\n\n lock (_stderrRollingLog)\n {\n if (_stderrRollingLog.Count > 0)\n {\n errorMessage =\n $\"{errorMessage}{exitCode}{Environment.NewLine}\" +\n $\"Server's stderr tail:{Environment.NewLine}\" +\n $\"{string.Join(Environment.NewLine, _stderrRollingLog)}\";\n }\n }\n\n return new IOException(errorMessage);\n }\n}\n", "middle_code": "protected override async ValueTask CleanupAsync(Exception? error = null, CancellationToken cancellationToken = default)\n {\n if (Interlocked.Exchange(ref _cleanedUp, 1) != 0)\n {\n return;\n }\n error ??= await GetUnexpectedExitExceptionAsync(cancellationToken).ConfigureAwait(false);\n try\n {\n StdioClientTransport.DisposeProcess(_process, processRunning: true, _options.ShutdownTimeout, Name);\n }\n catch (Exception ex)\n {\n LogTransportShutdownFailed(Name, ex);\n }\n await base.CleanupAsync(error, cancellationToken);\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "c_sharp", "sub_task_type": null}, "context_code": [["/csharp-sdk/src/ModelContextProtocol.Core/Client/StdioClientTransport.cs", "using Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics;\nusing System.Runtime.InteropServices;\nusing System.Text;\nusing System.Text.RegularExpressions;\n\n#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides a implemented via \"stdio\" (standard input/output).\n/// \n/// \n/// \n/// This transport launches an external process and communicates with it through standard input and output streams.\n/// It's used to connect to MCP servers launched and hosted in child processes.\n/// \n/// \n/// The transport manages the entire lifecycle of the process: starting it with specified command-line arguments\n/// and environment variables, handling output, and properly terminating the process when the transport is closed.\n/// \n/// \npublic sealed partial class StdioClientTransport : IClientTransport\n{\n private readonly StdioClientTransportOptions _options;\n private readonly ILoggerFactory? _loggerFactory;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// Configuration options for the transport, including the command to execute, arguments, working directory, and environment variables.\n /// Logger factory for creating loggers used for diagnostic output during transport operations.\n public StdioClientTransport(StdioClientTransportOptions options, ILoggerFactory? loggerFactory = null)\n {\n Throw.IfNull(options);\n\n _options = options;\n _loggerFactory = loggerFactory;\n Name = options.Name ?? $\"stdio-{Regex.Replace(Path.GetFileName(options.Command), @\"[\\s\\.]+\", \"-\")}\";\n }\n\n /// \n public string Name { get; }\n\n /// \n public async Task ConnectAsync(CancellationToken cancellationToken = default)\n {\n string endpointName = Name;\n\n Process? process = null;\n bool processStarted = false;\n\n string command = _options.Command;\n IList? arguments = _options.Arguments;\n if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) &&\n !string.Equals(Path.GetFileName(command), \"cmd.exe\", StringComparison.OrdinalIgnoreCase))\n {\n // On Windows, for stdio, we need to wrap non-shell commands with cmd.exe /c {command} (usually npx or uvicorn).\n // The stdio transport will not work correctly if the command is not run in a shell.\n arguments = arguments is null or [] ? [\"/c\", command] : [\"/c\", command, ..arguments];\n command = \"cmd.exe\";\n }\n\n ILogger logger = (ILogger?)_loggerFactory?.CreateLogger() ?? NullLogger.Instance;\n try\n {\n LogTransportConnecting(logger, endpointName);\n\n ProcessStartInfo startInfo = new()\n {\n FileName = command,\n RedirectStandardInput = true,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n WorkingDirectory = _options.WorkingDirectory ?? Environment.CurrentDirectory,\n StandardOutputEncoding = StreamClientSessionTransport.NoBomUtf8Encoding,\n StandardErrorEncoding = StreamClientSessionTransport.NoBomUtf8Encoding,\n#if NET\n StandardInputEncoding = StreamClientSessionTransport.NoBomUtf8Encoding,\n#endif\n };\n\n if (arguments is not null) \n {\n#if NET\n foreach (string arg in arguments)\n {\n startInfo.ArgumentList.Add(arg);\n }\n#else\n StringBuilder argsBuilder = new();\n foreach (string arg in arguments)\n {\n PasteArguments.AppendArgument(argsBuilder, arg);\n }\n\n startInfo.Arguments = argsBuilder.ToString();\n#endif\n }\n\n if (_options.EnvironmentVariables != null)\n {\n foreach (var entry in _options.EnvironmentVariables)\n {\n startInfo.Environment[entry.Key] = entry.Value;\n }\n }\n\n if (logger.IsEnabled(LogLevel.Trace))\n {\n LogCreateProcessForTransportSensitive(logger, endpointName, _options.Command,\n startInfo.Arguments,\n string.Join(\", \", startInfo.Environment.Select(kvp => $\"{kvp.Key}={kvp.Value}\")),\n startInfo.WorkingDirectory);\n }\n else\n {\n LogCreateProcessForTransport(logger, endpointName, _options.Command);\n }\n\n process = new() { StartInfo = startInfo };\n\n // Set up stderr handling. Log all stderr output, and keep the last\n // few lines in a rolling log for use in exceptions.\n const int MaxStderrLength = 10; // keep the last 10 lines of stderr\n Queue stderrRollingLog = new(MaxStderrLength);\n process.ErrorDataReceived += (sender, args) =>\n {\n string? data = args.Data;\n if (data is not null)\n {\n lock (stderrRollingLog)\n {\n if (stderrRollingLog.Count >= MaxStderrLength)\n {\n stderrRollingLog.Dequeue();\n }\n\n stderrRollingLog.Enqueue(data);\n }\n\n _options.StandardErrorLines?.Invoke(data);\n\n LogReadStderr(logger, endpointName, data);\n }\n };\n\n // We need both stdin and stdout to use a no-BOM UTF-8 encoding. On .NET Core,\n // we can use ProcessStartInfo.StandardOutputEncoding/StandardInputEncoding, but\n // StandardInputEncoding doesn't exist on .NET Framework; instead, it always picks\n // up the encoding from Console.InputEncoding. As such, when not targeting .NET Core,\n // we temporarily change Console.InputEncoding to no-BOM UTF-8 around the Process.Start\n // call, to ensure it picks up the correct encoding.\n#if NET\n processStarted = process.Start();\n#else\n Encoding originalInputEncoding = Console.InputEncoding;\n try\n {\n Console.InputEncoding = StreamClientSessionTransport.NoBomUtf8Encoding;\n processStarted = process.Start();\n }\n finally\n {\n Console.InputEncoding = originalInputEncoding;\n }\n#endif\n\n if (!processStarted)\n {\n LogTransportProcessStartFailed(logger, endpointName);\n throw new IOException(\"Failed to start MCP server process.\");\n }\n\n LogTransportProcessStarted(logger, endpointName, process.Id);\n\n process.BeginErrorReadLine();\n\n return new StdioClientSessionTransport(_options, process, endpointName, stderrRollingLog, _loggerFactory);\n }\n catch (Exception ex)\n {\n LogTransportConnectFailed(logger, endpointName, ex);\n\n try\n {\n DisposeProcess(process, processStarted, _options.ShutdownTimeout, endpointName);\n }\n catch (Exception ex2)\n {\n LogTransportShutdownFailed(logger, endpointName, ex2);\n }\n\n throw new IOException(\"Failed to connect transport.\", ex);\n }\n }\n\n internal static void DisposeProcess(\n Process? process, bool processRunning, TimeSpan shutdownTimeout, string endpointName)\n {\n if (process is not null)\n {\n try\n {\n processRunning = processRunning && !HasExited(process);\n if (processRunning)\n {\n // Wait for the process to exit.\n // Kill the while process tree because the process may spawn child processes\n // and Node.js does not kill its children when it exits properly.\n process.KillTree(shutdownTimeout);\n }\n }\n finally\n {\n process.Dispose();\n }\n }\n }\n\n /// Gets whether has exited.\n internal static bool HasExited(Process process)\n {\n try\n {\n return process.HasExited;\n }\n catch\n {\n return true;\n }\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} connecting.\")]\n private static partial void LogTransportConnecting(ILogger logger, string endpointName);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} starting server process. Command: '{Command}'.\")]\n private static partial void LogCreateProcessForTransport(ILogger logger, string endpointName, string command);\n\n [LoggerMessage(Level = LogLevel.Trace, Message = \"{EndpointName} starting server process. Command: '{Command}', Arguments: {Arguments}, Environment: {Environment}, Working directory: {WorkingDirectory}.\")]\n private static partial void LogCreateProcessForTransportSensitive(ILogger logger, string endpointName, string command, string? arguments, string environment, string workingDirectory);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} failed to start server process.\")]\n private static partial void LogTransportProcessStartFailed(ILogger logger, string endpointName);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} received stderr log: '{Data}'.\")]\n private static partial void LogReadStderr(ILogger logger, string endpointName, string data);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} started server process with PID {ProcessId}.\")]\n private static partial void LogTransportProcessStarted(ILogger logger, string endpointName, int processId);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} connect failed.\")]\n private static partial void LogTransportConnectFailed(ILogger logger, string endpointName, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} shutdown failed.\")]\n private static partial void LogTransportShutdownFailed(ILogger logger, string endpointName, Exception exception);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StreamClientSessionTransport.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing System.Text;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// Provides the client side of a stream-based session transport.\ninternal class StreamClientSessionTransport : TransportBase\n{\n internal static UTF8Encoding NoBomUtf8Encoding { get; } = new(encoderShouldEmitUTF8Identifier: false);\n\n private readonly TextReader _serverOutput;\n private readonly TextWriter _serverInput;\n private readonly SemaphoreSlim _sendLock = new(1, 1);\n private CancellationTokenSource? _shutdownCts = new();\n private Task? _readTask;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// \n /// The text writer connected to the server's input stream.\n /// Messages written to this writer will be sent to the server.\n /// \n /// \n /// The text reader connected to the server's output stream.\n /// Messages read from this reader will be received from the server.\n /// \n /// \n /// A name that identifies this transport endpoint in logs.\n /// \n /// \n /// Optional factory for creating loggers. If null, a NullLogger will be used.\n /// \n /// \n /// This constructor starts a background task to read messages from the server output stream.\n /// The transport will be marked as connected once initialized.\n /// \n public StreamClientSessionTransport(\n TextWriter serverInput, TextReader serverOutput, string endpointName, ILoggerFactory? loggerFactory)\n : base(endpointName, loggerFactory)\n {\n _serverOutput = serverOutput;\n _serverInput = serverInput;\n\n SetConnected();\n\n // Start reading messages in the background. We use the rarer pattern of new Task + Start\n // in order to ensure that the body of the task will always see _readTask initialized.\n // It is then able to reliably null it out on completion.\n var readTask = new Task(\n thisRef => ((StreamClientSessionTransport)thisRef!).ReadMessagesAsync(_shutdownCts.Token),\n this,\n TaskCreationOptions.DenyChildAttach);\n _readTask = readTask.Unwrap();\n readTask.Start();\n }\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// \n /// The server's input stream. Messages written to this stream will be sent to the server.\n /// \n /// \n /// The server's output stream. Messages read from this stream will be received from the server.\n /// \n /// \n /// The encoding used for reading and writing messages from the input and output streams. Defaults to UTF-8 without BOM if null.\n /// \n /// \n /// A name that identifies this transport endpoint in logs.\n /// \n /// \n /// Optional factory for creating loggers. If null, a NullLogger will be used.\n /// \n /// \n /// This constructor starts a background task to read messages from the server output stream.\n /// The transport will be marked as connected once initialized.\n /// \n public StreamClientSessionTransport(Stream serverInput, Stream serverOutput, Encoding? encoding, string endpointName, ILoggerFactory? loggerFactory)\n : this(\n new StreamWriter(serverInput, encoding ?? NoBomUtf8Encoding),\n#if NET\n new StreamReader(serverOutput, encoding ?? NoBomUtf8Encoding),\n#else\n new CancellableStreamReader(serverOutput, encoding ?? NoBomUtf8Encoding),\n#endif\n endpointName,\n loggerFactory)\n {\n Throw.IfNull(serverInput);\n Throw.IfNull(serverOutput);\n }\n\n /// \n public override async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n string id = \"(no id)\";\n if (message is JsonRpcMessageWithId messageWithId)\n {\n id = messageWithId.Id.ToString();\n }\n\n var json = JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage);\n\n using var _ = await _sendLock.LockAsync(cancellationToken).ConfigureAwait(false);\n try\n {\n // Write the message followed by a newline using our UTF-8 writer\n await _serverInput.WriteLineAsync(json).ConfigureAwait(false);\n await _serverInput.FlushAsync(cancellationToken).ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n LogTransportSendFailed(Name, id, ex);\n throw new IOException(\"Failed to send message.\", ex);\n }\n }\n\n /// \n public override ValueTask DisposeAsync() =>\n CleanupAsync(cancellationToken: CancellationToken.None);\n\n private async Task ReadMessagesAsync(CancellationToken cancellationToken)\n {\n Exception? error = null;\n try\n {\n LogTransportEnteringReadMessagesLoop(Name);\n\n while (true)\n {\n if (await _serverOutput.ReadLineAsync(cancellationToken).ConfigureAwait(false) is not string line)\n {\n LogTransportEndOfStream(Name);\n break;\n }\n\n if (string.IsNullOrWhiteSpace(line))\n {\n continue;\n }\n\n LogTransportReceivedMessageSensitive(Name, line);\n\n await ProcessMessageAsync(line, cancellationToken).ConfigureAwait(false);\n }\n }\n catch (OperationCanceledException)\n {\n LogTransportReadMessagesCancelled(Name);\n }\n catch (Exception ex)\n {\n error = ex;\n LogTransportReadMessagesFailed(Name, ex);\n }\n finally\n {\n _readTask = null;\n await CleanupAsync(error, cancellationToken).ConfigureAwait(false);\n }\n }\n\n private async Task ProcessMessageAsync(string line, CancellationToken cancellationToken)\n {\n try\n {\n var message = (JsonRpcMessage?)JsonSerializer.Deserialize(line.AsSpan().Trim(), McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonRpcMessage)));\n if (message != null)\n {\n await WriteMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n else\n {\n LogTransportMessageParseUnexpectedTypeSensitive(Name, line);\n }\n }\n catch (JsonException ex)\n {\n if (Logger.IsEnabled(LogLevel.Trace))\n {\n LogTransportMessageParseFailedSensitive(Name, line, ex);\n }\n else\n {\n LogTransportMessageParseFailed(Name, ex);\n }\n }\n }\n\n protected virtual async ValueTask CleanupAsync(Exception? error = null, CancellationToken cancellationToken = default)\n {\n LogTransportShuttingDown(Name);\n\n if (Interlocked.Exchange(ref _shutdownCts, null) is { } shutdownCts)\n {\n await shutdownCts.CancelAsync().ConfigureAwait(false);\n shutdownCts.Dispose();\n }\n\n if (Interlocked.Exchange(ref _readTask, null) is Task readTask)\n {\n try\n {\n await readTask.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken).ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n }\n catch (Exception ex)\n {\n LogTransportCleanupReadTaskFailed(Name, ex);\n }\n }\n\n SetDisconnected(error);\n LogTransportShutDown(Name);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/SseClientSessionTransport.cs", "using Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing ModelContextProtocol.Protocol;\nusing System.Diagnostics;\nusing System.Net.Http.Headers;\nusing System.Net.ServerSentEvents;\nusing System.Text.Json;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// The ServerSideEvents client transport implementation\n/// \ninternal sealed partial class SseClientSessionTransport : TransportBase\n{\n private readonly McpHttpClient _httpClient;\n private readonly SseClientTransportOptions _options;\n private readonly Uri _sseEndpoint;\n private Uri? _messageEndpoint;\n private readonly CancellationTokenSource _connectionCts;\n private Task? _receiveTask;\n private readonly ILogger _logger;\n private readonly TaskCompletionSource _connectionEstablished;\n\n /// \n /// SSE transport for a single session. Unlike stdio it does not launch a process, but connects to an existing server.\n /// The HTTP server can be local or remote, and must support the SSE protocol.\n /// \n public SseClientSessionTransport(\n string endpointName,\n SseClientTransportOptions transportOptions,\n McpHttpClient httpClient,\n Channel? messageChannel,\n ILoggerFactory? loggerFactory)\n : base(endpointName, messageChannel, loggerFactory)\n {\n Throw.IfNull(transportOptions);\n Throw.IfNull(httpClient);\n\n _options = transportOptions;\n _sseEndpoint = transportOptions.Endpoint;\n _httpClient = httpClient;\n _connectionCts = new CancellationTokenSource();\n _logger = (ILogger?)loggerFactory?.CreateLogger() ?? NullLogger.Instance;\n _connectionEstablished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);\n }\n\n /// \n public async Task ConnectAsync(CancellationToken cancellationToken = default)\n {\n Debug.Assert(!IsConnected);\n try\n {\n // Start message receiving loop\n _receiveTask = ReceiveMessagesAsync(_connectionCts.Token);\n\n await _connectionEstablished.Task.WaitAsync(_options.ConnectionTimeout, cancellationToken).ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n LogTransportConnectFailed(Name, ex);\n await CloseAsync().ConfigureAwait(false);\n throw new InvalidOperationException(\"Failed to connect transport\", ex);\n }\n }\n\n /// \n public override async Task SendMessageAsync(\n JsonRpcMessage message,\n CancellationToken cancellationToken = default)\n {\n if (_messageEndpoint == null)\n throw new InvalidOperationException(\"Transport not connected\");\n\n string messageId = \"(no id)\";\n\n if (message is JsonRpcMessageWithId messageWithId)\n {\n messageId = messageWithId.Id.ToString();\n }\n\n using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, _messageEndpoint);\n StreamableHttpClientSessionTransport.CopyAdditionalHeaders(httpRequestMessage.Headers, _options.AdditionalHeaders, sessionId: null, protocolVersion: null);\n var response = await _httpClient.SendAsync(httpRequestMessage, message, cancellationToken).ConfigureAwait(false);\n\n if (!response.IsSuccessStatusCode)\n {\n if (_logger.IsEnabled(LogLevel.Trace))\n {\n LogRejectedPostSensitive(Name, messageId, await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false));\n }\n else\n {\n LogRejectedPost(Name, messageId);\n }\n\n response.EnsureSuccessStatusCode();\n }\n }\n\n private async Task CloseAsync()\n {\n try\n {\n await _connectionCts.CancelAsync().ConfigureAwait(false);\n\n try\n {\n if (_receiveTask != null)\n {\n await _receiveTask.ConfigureAwait(false);\n }\n }\n finally\n {\n _connectionCts.Dispose();\n }\n }\n finally\n {\n SetDisconnected();\n }\n }\n\n /// \n public override async ValueTask DisposeAsync()\n {\n try\n {\n await CloseAsync().ConfigureAwait(false);\n }\n catch (Exception)\n {\n // Ignore exceptions on close\n }\n }\n\n private async Task ReceiveMessagesAsync(CancellationToken cancellationToken)\n {\n try\n {\n using var request = new HttpRequestMessage(HttpMethod.Get, _sseEndpoint);\n request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(\"text/event-stream\"));\n StreamableHttpClientSessionTransport.CopyAdditionalHeaders(request.Headers, _options.AdditionalHeaders, sessionId: null, protocolVersion: null);\n\n using var response = await _httpClient.SendAsync(request, message: null, cancellationToken).ConfigureAwait(false);\n\n response.EnsureSuccessStatusCode();\n\n using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);\n\n await foreach (SseItem sseEvent in SseParser.Create(stream).EnumerateAsync(cancellationToken).ConfigureAwait(false))\n {\n switch (sseEvent.EventType)\n {\n case \"endpoint\":\n HandleEndpointEvent(sseEvent.Data);\n break;\n\n case \"message\":\n await ProcessSseMessage(sseEvent.Data, cancellationToken).ConfigureAwait(false);\n break;\n }\n }\n }\n catch (Exception ex)\n {\n if (cancellationToken.IsCancellationRequested)\n {\n // Normal shutdown\n LogTransportReadMessagesCancelled(Name);\n _connectionEstablished.TrySetCanceled(cancellationToken);\n }\n else\n {\n LogTransportReadMessagesFailed(Name, ex);\n _connectionEstablished.TrySetException(ex);\n throw;\n }\n }\n finally\n {\n SetDisconnected();\n }\n }\n\n private async Task ProcessSseMessage(string data, CancellationToken cancellationToken)\n {\n if (!IsConnected)\n {\n LogTransportMessageReceivedBeforeConnected(Name);\n return;\n }\n\n try\n {\n var message = JsonSerializer.Deserialize(data, McpJsonUtilities.JsonContext.Default.JsonRpcMessage);\n if (message == null)\n {\n LogTransportMessageParseUnexpectedTypeSensitive(Name, data);\n return;\n }\n\n await WriteMessageAsync(message, cancellationToken).ConfigureAwait(false);\n }\n catch (JsonException ex)\n {\n if (_logger.IsEnabled(LogLevel.Trace))\n {\n LogTransportMessageParseFailedSensitive(Name, data, ex);\n }\n else\n {\n LogTransportMessageParseFailed(Name, ex);\n }\n }\n }\n\n private void HandleEndpointEvent(string data)\n {\n if (string.IsNullOrEmpty(data))\n {\n LogTransportEndpointEventInvalid(Name);\n return;\n }\n\n // If data is an absolute URL, the Uri will be constructed entirely from it and not the _sseEndpoint.\n _messageEndpoint = new Uri(_sseEndpoint, data);\n\n // Set connected state\n SetConnected();\n _connectionEstablished.TrySetResult(true);\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} accepted SSE transport POST for message ID '{MessageId}'.\")]\n private partial void LogAcceptedPost(string endpointName, string messageId);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} rejected SSE transport POST for message ID '{MessageId}'.\")]\n private partial void LogRejectedPost(string endpointName, string messageId);\n\n [LoggerMessage(Level = LogLevel.Trace, Message = \"{EndpointName} rejected SSE transport POST for message ID '{MessageId}'. Server response: '{responseContent}'.\")]\n private partial void LogRejectedPostSensitive(string endpointName, string messageId, string responseContent);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/StreamableHttpClientSessionTransport.cs", "using Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing System.Net.Http.Headers;\nusing System.Net.ServerSentEvents;\nusing System.Text.Json;\nusing ModelContextProtocol.Protocol;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// The Streamable HTTP client transport implementation\n/// \ninternal sealed partial class StreamableHttpClientSessionTransport : TransportBase\n{\n private static readonly MediaTypeWithQualityHeaderValue s_applicationJsonMediaType = new(\"application/json\");\n private static readonly MediaTypeWithQualityHeaderValue s_textEventStreamMediaType = new(\"text/event-stream\");\n\n private readonly McpHttpClient _httpClient;\n private readonly SseClientTransportOptions _options;\n private readonly CancellationTokenSource _connectionCts;\n private readonly ILogger _logger;\n\n private string? _negotiatedProtocolVersion;\n private Task? _getReceiveTask;\n\n private readonly SemaphoreSlim _disposeLock = new(1, 1);\n private bool _disposed;\n\n public StreamableHttpClientSessionTransport(\n string endpointName,\n SseClientTransportOptions transportOptions,\n McpHttpClient httpClient,\n Channel? messageChannel,\n ILoggerFactory? loggerFactory)\n : base(endpointName, messageChannel, loggerFactory)\n {\n Throw.IfNull(transportOptions);\n Throw.IfNull(httpClient);\n\n _options = transportOptions;\n _httpClient = httpClient;\n _connectionCts = new CancellationTokenSource();\n _logger = (ILogger?)loggerFactory?.CreateLogger() ?? NullLogger.Instance;\n\n // We connect with the initialization request with the MCP transport. This means that any errors won't be observed\n // until the first call to SendMessageAsync. Fortunately, that happens internally in McpClientFactory.ConnectAsync\n // so we still throw any connection-related Exceptions from there and never expose a pre-connected client to the user.\n SetConnected();\n }\n\n /// \n public override async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n // Immediately dispose the response. SendHttpRequestAsync only returns the response so the auto transport can look at it.\n using var response = await SendHttpRequestAsync(message, cancellationToken).ConfigureAwait(false);\n response.EnsureSuccessStatusCode();\n }\n\n // This is used by the auto transport so it can fall back and try SSE given a non-200 response without catching an exception.\n internal async Task SendHttpRequestAsync(JsonRpcMessage message, CancellationToken cancellationToken)\n {\n using var sendCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _connectionCts.Token);\n cancellationToken = sendCts.Token;\n\n using var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, _options.Endpoint)\n {\n Headers =\n {\n Accept = { s_applicationJsonMediaType, s_textEventStreamMediaType },\n },\n };\n\n CopyAdditionalHeaders(httpRequestMessage.Headers, _options.AdditionalHeaders, SessionId, _negotiatedProtocolVersion);\n\n var response = await _httpClient.SendAsync(httpRequestMessage, message, cancellationToken).ConfigureAwait(false);\n\n // We'll let the caller decide whether to throw or fall back given an unsuccessful response.\n if (!response.IsSuccessStatusCode)\n {\n return response;\n }\n\n var rpcRequest = message as JsonRpcRequest;\n JsonRpcMessageWithId? rpcResponseOrError = null;\n\n if (response.Content.Headers.ContentType?.MediaType == \"application/json\")\n {\n var responseContent = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);\n rpcResponseOrError = await ProcessMessageAsync(responseContent, rpcRequest, cancellationToken).ConfigureAwait(false);\n }\n else if (response.Content.Headers.ContentType?.MediaType == \"text/event-stream\")\n {\n using var responseBodyStream = await response.Content.ReadAsStreamAsync(cancellationToken);\n rpcResponseOrError = await ProcessSseResponseAsync(responseBodyStream, rpcRequest, cancellationToken).ConfigureAwait(false);\n }\n\n if (rpcRequest is null)\n {\n return response;\n }\n\n if (rpcResponseOrError is null)\n {\n throw new McpException($\"Streamable HTTP POST response completed without a reply to request with ID: {rpcRequest.Id}\");\n }\n\n if (rpcRequest.Method == RequestMethods.Initialize && rpcResponseOrError is JsonRpcResponse initResponse)\n {\n // We've successfully initialized! Copy session-id and protocol version, then start GET request if any.\n if (response.Headers.TryGetValues(\"Mcp-Session-Id\", out var sessionIdValues))\n {\n SessionId = sessionIdValues.FirstOrDefault();\n }\n\n var initializeResult = JsonSerializer.Deserialize(initResponse.Result, McpJsonUtilities.JsonContext.Default.InitializeResult);\n _negotiatedProtocolVersion = initializeResult?.ProtocolVersion;\n\n _getReceiveTask = ReceiveUnsolicitedMessagesAsync();\n }\n\n return response;\n }\n\n public override async ValueTask DisposeAsync()\n {\n using var _ = await _disposeLock.LockAsync().ConfigureAwait(false);\n\n if (_disposed)\n {\n return;\n }\n _disposed = true;\n\n try\n {\n await _connectionCts.CancelAsync().ConfigureAwait(false);\n\n try\n {\n // Send DELETE request to terminate the session. Only send if we have a session ID, per MCP spec.\n if (!string.IsNullOrEmpty(SessionId))\n {\n await SendDeleteRequest();\n }\n\n if (_getReceiveTask != null)\n {\n await _getReceiveTask.ConfigureAwait(false);\n }\n }\n catch (OperationCanceledException)\n {\n }\n finally\n {\n _connectionCts.Dispose();\n }\n }\n finally\n {\n // If we're auto-detecting the transport and failed to connect, leave the message Channel open for the SSE transport.\n // This class isn't directly exposed to public callers, so we don't have to worry about changing the _state in this case.\n if (_options.TransportMode is not HttpTransportMode.AutoDetect || _getReceiveTask is not null)\n {\n SetDisconnected();\n }\n }\n }\n\n private async Task ReceiveUnsolicitedMessagesAsync()\n {\n // Send a GET request to handle any unsolicited messages not sent over a POST response.\n using var request = new HttpRequestMessage(HttpMethod.Get, _options.Endpoint);\n request.Headers.Accept.Add(s_textEventStreamMediaType);\n CopyAdditionalHeaders(request.Headers, _options.AdditionalHeaders, SessionId, _negotiatedProtocolVersion);\n\n using var response = await _httpClient.SendAsync(request, message: null, _connectionCts.Token).ConfigureAwait(false);\n\n if (!response.IsSuccessStatusCode)\n {\n // Server support for the GET request is optional. If it fails, we don't care. It just means we won't receive unsolicited messages.\n return;\n }\n\n using var responseStream = await response.Content.ReadAsStreamAsync(_connectionCts.Token).ConfigureAwait(false);\n await ProcessSseResponseAsync(responseStream, relatedRpcRequest: null, _connectionCts.Token).ConfigureAwait(false);\n }\n\n private async Task ProcessSseResponseAsync(Stream responseStream, JsonRpcRequest? relatedRpcRequest, CancellationToken cancellationToken)\n {\n await foreach (SseItem sseEvent in SseParser.Create(responseStream).EnumerateAsync(cancellationToken).ConfigureAwait(false))\n {\n if (sseEvent.EventType != \"message\")\n {\n continue;\n }\n\n var rpcResponseOrError = await ProcessMessageAsync(sseEvent.Data, relatedRpcRequest, cancellationToken).ConfigureAwait(false);\n\n // The server SHOULD end the HTTP response body here anyway, but we won't leave it to chance. This transport makes\n // a GET request for any notifications that might need to be sent after the completion of each POST.\n if (rpcResponseOrError is not null)\n {\n return rpcResponseOrError;\n }\n }\n\n return null;\n }\n\n private async Task ProcessMessageAsync(string data, JsonRpcRequest? relatedRpcRequest, CancellationToken cancellationToken)\n {\n try\n {\n var message = JsonSerializer.Deserialize(data, McpJsonUtilities.JsonContext.Default.JsonRpcMessage);\n if (message is null)\n {\n LogTransportMessageParseUnexpectedTypeSensitive(Name, data);\n return null;\n }\n\n await WriteMessageAsync(message, cancellationToken).ConfigureAwait(false);\n if (message is JsonRpcResponse or JsonRpcError &&\n message is JsonRpcMessageWithId rpcResponseOrError &&\n rpcResponseOrError.Id == relatedRpcRequest?.Id)\n {\n return rpcResponseOrError;\n }\n }\n catch (JsonException ex)\n {\n LogJsonException(ex, data);\n }\n\n return null;\n }\n\n private async Task SendDeleteRequest()\n {\n using var deleteRequest = new HttpRequestMessage(HttpMethod.Delete, _options.Endpoint);\n CopyAdditionalHeaders(deleteRequest.Headers, _options.AdditionalHeaders, SessionId, _negotiatedProtocolVersion);\n\n try\n {\n // Do not validate we get a successful status code, because server support for the DELETE request is optional\n (await _httpClient.SendAsync(deleteRequest, message: null, CancellationToken.None).ConfigureAwait(false)).Dispose();\n }\n catch (Exception ex)\n {\n LogTransportShutdownFailed(Name, ex);\n }\n }\n\n private void LogJsonException(JsonException ex, string data)\n {\n if (_logger.IsEnabled(LogLevel.Trace))\n {\n LogTransportMessageParseFailedSensitive(Name, data, ex);\n }\n else\n {\n LogTransportMessageParseFailed(Name, ex);\n }\n }\n\n internal static void CopyAdditionalHeaders(\n HttpRequestHeaders headers,\n IDictionary? additionalHeaders,\n string? sessionId,\n string? protocolVersion)\n {\n if (sessionId is not null)\n {\n headers.Add(\"Mcp-Session-Id\", sessionId);\n }\n\n if (protocolVersion is not null)\n {\n headers.Add(\"MCP-Protocol-Version\", protocolVersion);\n }\n\n if (additionalHeaders is null)\n {\n return;\n }\n\n foreach (var header in additionalHeaders)\n {\n if (!headers.TryAddWithoutValidation(header.Key, header.Value))\n {\n throw new InvalidOperationException($\"Failed to add header '{header.Key}' with value '{header.Value}' from {nameof(SseClientTransportOptions.AdditionalHeaders)}.\");\n }\n }\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/StreamServerTransport.cs", "using Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing ModelContextProtocol.Protocol;\nusing System.Text;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Server;\n\n/// \n/// Provides an implemented using a pair of input and output streams.\n/// \n/// \n/// The class implements bidirectional JSON-RPC messaging over arbitrary\n/// streams, allowing MCP communication with clients through various I/O channels such as network sockets,\n/// memory streams, or pipes.\n/// \npublic class StreamServerTransport : TransportBase\n{\n private static readonly byte[] s_newlineBytes = \"\\n\"u8.ToArray();\n\n private readonly ILogger _logger;\n\n private readonly TextReader _inputReader;\n private readonly Stream _outputStream;\n\n private readonly SemaphoreSlim _sendLock = new(1, 1);\n private readonly CancellationTokenSource _shutdownCts = new();\n\n private readonly Task _readLoopCompleted;\n private int _disposed = 0;\n\n /// \n /// Initializes a new instance of the class with explicit input/output streams.\n /// \n /// The input to use as standard input.\n /// The output to use as standard output.\n /// Optional name of the server, used for diagnostic purposes, like logging.\n /// Optional logger factory used for logging employed by the transport.\n /// is .\n /// is .\n public StreamServerTransport(Stream inputStream, Stream outputStream, string? serverName = null, ILoggerFactory? loggerFactory = null)\n : base(serverName is not null ? $\"Server (stream) ({serverName})\" : \"Server (stream)\", loggerFactory)\n {\n Throw.IfNull(inputStream);\n Throw.IfNull(outputStream);\n\n _logger = loggerFactory?.CreateLogger(GetType()) ?? NullLogger.Instance;\n\n#if NET\n _inputReader = new StreamReader(inputStream, Encoding.UTF8);\n#else\n _inputReader = new CancellableStreamReader(inputStream, Encoding.UTF8);\n#endif\n _outputStream = outputStream;\n\n SetConnected();\n _readLoopCompleted = Task.Run(ReadMessagesAsync, _shutdownCts.Token);\n }\n\n /// \n public override async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (!IsConnected)\n {\n return;\n }\n\n using var _ = await _sendLock.LockAsync(cancellationToken).ConfigureAwait(false);\n\n string id = \"(no id)\";\n if (message is JsonRpcMessageWithId messageWithId)\n {\n id = messageWithId.Id.ToString();\n }\n\n try\n {\n await JsonSerializer.SerializeAsync(_outputStream, message, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonRpcMessage)), cancellationToken).ConfigureAwait(false);\n await _outputStream.WriteAsync(s_newlineBytes, cancellationToken).ConfigureAwait(false);\n await _outputStream.FlushAsync(cancellationToken).ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n LogTransportSendFailed(Name, id, ex);\n throw new IOException(\"Failed to send message.\", ex);\n }\n }\n\n private async Task ReadMessagesAsync()\n {\n CancellationToken shutdownToken = _shutdownCts.Token;\n Exception? error = null;\n try\n {\n LogTransportEnteringReadMessagesLoop(Name);\n\n while (!shutdownToken.IsCancellationRequested)\n {\n var line = await _inputReader.ReadLineAsync(shutdownToken).ConfigureAwait(false);\n if (string.IsNullOrWhiteSpace(line))\n {\n if (line is null)\n {\n LogTransportEndOfStream(Name);\n break;\n }\n\n continue;\n }\n\n LogTransportReceivedMessageSensitive(Name, line);\n\n try\n {\n if (JsonSerializer.Deserialize(line, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonRpcMessage))) is JsonRpcMessage message)\n {\n await WriteMessageAsync(message, shutdownToken).ConfigureAwait(false);\n }\n else\n {\n LogTransportMessageParseUnexpectedTypeSensitive(Name, line);\n }\n }\n catch (JsonException ex)\n {\n if (Logger.IsEnabled(LogLevel.Trace))\n {\n LogTransportMessageParseFailedSensitive(Name, line, ex);\n }\n else\n {\n LogTransportMessageParseFailed(Name, ex);\n }\n\n // Continue reading even if we fail to parse a message\n }\n }\n }\n catch (OperationCanceledException)\n {\n LogTransportReadMessagesCancelled(Name);\n }\n catch (Exception ex)\n {\n LogTransportReadMessagesFailed(Name, ex);\n error = ex;\n }\n finally\n {\n SetDisconnected(error);\n }\n }\n\n /// \n public override async ValueTask DisposeAsync()\n {\n if (Interlocked.Exchange(ref _disposed, 1) != 0)\n {\n return;\n }\n\n try\n {\n LogTransportShuttingDown(Name);\n\n // Signal to the stdin reading loop to stop.\n await _shutdownCts.CancelAsync().ConfigureAwait(false);\n _shutdownCts.Dispose();\n\n // Dispose of stdin/out. Cancellation may not be able to wake up operations\n // synchronously blocked in a syscall; we need to forcefully close the handle / file descriptor.\n _inputReader?.Dispose();\n _outputStream?.Dispose();\n\n // Make sure the work has quiesced.\n try\n {\n await _readLoopCompleted.ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n }\n catch (Exception ex)\n {\n LogTransportCleanupReadTaskFailed(Name, ex);\n }\n }\n finally\n {\n SetDisconnected();\n LogTransportShutDown(Name);\n }\n\n GC.SuppressFinalize(this);\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpSession.cs", "using Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing ModelContextProtocol.Client;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Collections.Concurrent;\nusing System.Diagnostics;\nusing System.Diagnostics.Metrics;\nusing System.Text.Json;\nusing System.Text.Json.Nodes;\n#if !NET\nusing System.Threading.Channels;\n#endif\n\nnamespace ModelContextProtocol;\n\n/// \n/// Class for managing an MCP JSON-RPC session. This covers both MCP clients and servers.\n/// \ninternal sealed partial class McpSession : IDisposable\n{\n private static readonly Histogram s_clientSessionDuration = Diagnostics.CreateDurationHistogram(\n \"mcp.client.session.duration\", \"Measures the duration of a client session.\", longBuckets: true);\n private static readonly Histogram s_serverSessionDuration = Diagnostics.CreateDurationHistogram(\n \"mcp.server.session.duration\", \"Measures the duration of a server session.\", longBuckets: true);\n private static readonly Histogram s_clientOperationDuration = Diagnostics.CreateDurationHistogram(\n \"mcp.client.operation.duration\", \"Measures the duration of outbound message.\", longBuckets: false);\n private static readonly Histogram s_serverOperationDuration = Diagnostics.CreateDurationHistogram(\n \"mcp.server.operation.duration\", \"Measures the duration of inbound message processing.\", longBuckets: false);\n\n /// The latest version of the protocol supported by this implementation.\n internal const string LatestProtocolVersion = \"2025-06-18\";\n\n /// All protocol versions supported by this implementation.\n internal static readonly string[] SupportedProtocolVersions =\n [\n \"2024-11-05\",\n \"2025-03-26\",\n LatestProtocolVersion,\n ];\n\n private readonly bool _isServer;\n private readonly string _transportKind;\n private readonly ITransport _transport;\n private readonly RequestHandlers _requestHandlers;\n private readonly NotificationHandlers _notificationHandlers;\n private readonly long _sessionStartingTimestamp = Stopwatch.GetTimestamp();\n\n private readonly DistributedContextPropagator _propagator = DistributedContextPropagator.Current;\n\n /// Collection of requests sent on this session and waiting for responses.\n private readonly ConcurrentDictionary> _pendingRequests = [];\n /// \n /// Collection of requests received on this session and currently being handled. The value provides a \n /// that can be used to request cancellation of the in-flight handler.\n /// \n private readonly ConcurrentDictionary _handlingRequests = new();\n private readonly ILogger _logger;\n\n // This _sessionId is solely used to identify the session in telemetry and logs.\n private readonly string _sessionId = Guid.NewGuid().ToString(\"N\");\n private long _lastRequestId;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// true if this is a server; false if it's a client.\n /// An MCP transport implementation.\n /// The name of the endpoint for logging and debug purposes.\n /// A collection of request handlers.\n /// A collection of notification handlers.\n /// The logger.\n public McpSession(\n bool isServer,\n ITransport transport,\n string endpointName,\n RequestHandlers requestHandlers,\n NotificationHandlers notificationHandlers,\n ILogger logger)\n {\n Throw.IfNull(transport);\n\n _transportKind = transport switch\n {\n StdioClientSessionTransport or StdioServerTransport => \"stdio\",\n StreamClientSessionTransport or StreamServerTransport => \"stream\",\n SseClientSessionTransport or SseResponseStreamTransport => \"sse\",\n StreamableHttpClientSessionTransport or StreamableHttpServerTransport or StreamableHttpPostTransport => \"http\",\n _ => \"unknownTransport\"\n };\n\n _isServer = isServer;\n _transport = transport;\n EndpointName = endpointName;\n _requestHandlers = requestHandlers;\n _notificationHandlers = notificationHandlers;\n _logger = logger ?? NullLogger.Instance;\n }\n\n /// \n /// Gets and sets the name of the endpoint for logging and debug purposes.\n /// \n public string EndpointName { get; set; }\n\n /// \n /// Starts processing messages from the transport. This method will block until the transport is disconnected.\n /// This is generally started in a background task or thread from the initialization logic of the derived class.\n /// \n public async Task ProcessMessagesAsync(CancellationToken cancellationToken)\n {\n try\n {\n await foreach (var message in _transport.MessageReader.ReadAllAsync(cancellationToken).ConfigureAwait(false))\n {\n LogMessageRead(EndpointName, message.GetType().Name);\n\n // Fire and forget the message handling to avoid blocking the transport.\n if (message.ExecutionContext is null)\n {\n _ = ProcessMessageAsync();\n }\n else\n {\n // Flow the execution context from the HTTP request corresponding to this message if provided.\n ExecutionContext.Run(message.ExecutionContext, _ => _ = ProcessMessageAsync(), null);\n }\n\n async Task ProcessMessageAsync()\n {\n JsonRpcMessageWithId? messageWithId = message as JsonRpcMessageWithId;\n CancellationTokenSource? combinedCts = null;\n try\n {\n // Register before we yield, so that the tracking is guaranteed to be there\n // when subsequent messages arrive, even if the asynchronous processing happens\n // out of order.\n if (messageWithId is not null)\n {\n combinedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n _handlingRequests[messageWithId.Id] = combinedCts;\n }\n\n // If we await the handler without yielding first, the transport may not be able to read more messages,\n // which could lead to a deadlock if the handler sends a message back.\n#if NET\n await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding);\n#else\n await default(ForceYielding);\n#endif\n\n // Handle the message.\n await HandleMessageAsync(message, combinedCts?.Token ?? cancellationToken).ConfigureAwait(false);\n }\n catch (Exception ex)\n {\n // Only send responses for request errors that aren't user-initiated cancellation.\n bool isUserCancellation =\n ex is OperationCanceledException &&\n !cancellationToken.IsCancellationRequested &&\n combinedCts?.IsCancellationRequested is true;\n\n if (!isUserCancellation && message is JsonRpcRequest request)\n {\n LogRequestHandlerException(EndpointName, request.Method, ex);\n\n JsonRpcErrorDetail detail = ex is McpException mcpe ?\n new()\n {\n Code = (int)mcpe.ErrorCode,\n Message = mcpe.Message,\n } :\n new()\n {\n Code = (int)McpErrorCode.InternalError,\n Message = \"An error occurred.\",\n };\n\n await SendMessageAsync(new JsonRpcError\n {\n Id = request.Id,\n JsonRpc = \"2.0\",\n Error = detail,\n RelatedTransport = request.RelatedTransport,\n }, cancellationToken).ConfigureAwait(false);\n }\n else if (ex is not OperationCanceledException)\n {\n if (_logger.IsEnabled(LogLevel.Trace))\n {\n LogMessageHandlerExceptionSensitive(EndpointName, message.GetType().Name, JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage), ex);\n }\n else\n {\n LogMessageHandlerException(EndpointName, message.GetType().Name, ex);\n }\n }\n }\n finally\n {\n if (messageWithId is not null)\n {\n _handlingRequests.TryRemove(messageWithId.Id, out _);\n combinedCts!.Dispose();\n }\n }\n }\n }\n }\n catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)\n {\n // Normal shutdown\n LogEndpointMessageProcessingCanceled(EndpointName);\n }\n finally\n {\n // Fail any pending requests, as they'll never be satisfied.\n foreach (var entry in _pendingRequests)\n {\n entry.Value.TrySetException(new IOException(\"The server shut down unexpectedly.\"));\n }\n }\n }\n\n private async Task HandleMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken)\n {\n Histogram durationMetric = _isServer ? s_serverOperationDuration : s_clientOperationDuration;\n string method = GetMethodName(message);\n\n long? startingTimestamp = durationMetric.Enabled ? Stopwatch.GetTimestamp() : null;\n\n Activity? activity = Diagnostics.ShouldInstrumentMessage(message) ?\n Diagnostics.ActivitySource.StartActivity(\n CreateActivityName(method),\n ActivityKind.Server,\n parentContext: _propagator.ExtractActivityContext(message),\n links: Diagnostics.ActivityLinkFromCurrent()) :\n null;\n\n TagList tags = default;\n bool addTags = activity is { IsAllDataRequested: true } || startingTimestamp is not null;\n try\n {\n if (addTags)\n {\n AddTags(ref tags, activity, message, method);\n }\n\n switch (message)\n {\n case JsonRpcRequest request:\n var result = await HandleRequest(request, cancellationToken).ConfigureAwait(false);\n AddResponseTags(ref tags, activity, result, method);\n break;\n\n case JsonRpcNotification notification:\n await HandleNotification(notification, cancellationToken).ConfigureAwait(false);\n break;\n\n case JsonRpcMessageWithId messageWithId:\n HandleMessageWithId(message, messageWithId);\n break;\n\n default:\n LogEndpointHandlerUnexpectedMessageType(EndpointName, message.GetType().Name);\n break;\n }\n }\n catch (Exception e) when (addTags)\n {\n AddExceptionTags(ref tags, activity, e);\n throw;\n }\n finally\n {\n FinalizeDiagnostics(activity, startingTimestamp, durationMetric, ref tags);\n }\n }\n\n private async Task HandleNotification(JsonRpcNotification notification, CancellationToken cancellationToken)\n {\n // Special-case cancellation to cancel a pending operation. (We'll still subsequently invoke a user-specified handler if one exists.)\n if (notification.Method == NotificationMethods.CancelledNotification)\n {\n try\n {\n if (GetCancelledNotificationParams(notification.Params) is CancelledNotificationParams cn &&\n _handlingRequests.TryGetValue(cn.RequestId, out var cts))\n {\n await cts.CancelAsync().ConfigureAwait(false);\n LogRequestCanceled(EndpointName, cn.RequestId, cn.Reason);\n }\n }\n catch\n {\n // \"Invalid cancellation notifications SHOULD be ignored\"\n }\n }\n\n // Handle user-defined notifications.\n await _notificationHandlers.InvokeHandlers(notification.Method, notification, cancellationToken).ConfigureAwait(false);\n }\n\n private void HandleMessageWithId(JsonRpcMessage message, JsonRpcMessageWithId messageWithId)\n {\n if (_pendingRequests.TryRemove(messageWithId.Id, out var tcs))\n {\n tcs.TrySetResult(message);\n }\n else\n {\n LogNoRequestFoundForMessageWithId(EndpointName, messageWithId.Id);\n }\n }\n\n private async Task HandleRequest(JsonRpcRequest request, CancellationToken cancellationToken)\n {\n if (!_requestHandlers.TryGetValue(request.Method, out var handler))\n {\n LogNoHandlerFoundForRequest(EndpointName, request.Method);\n throw new McpException($\"Method '{request.Method}' is not available.\", McpErrorCode.MethodNotFound);\n }\n\n LogRequestHandlerCalled(EndpointName, request.Method);\n JsonNode? result = await handler(request, cancellationToken).ConfigureAwait(false);\n LogRequestHandlerCompleted(EndpointName, request.Method);\n\n await SendMessageAsync(new JsonRpcResponse\n {\n Id = request.Id,\n Result = result,\n RelatedTransport = request.RelatedTransport,\n }, cancellationToken).ConfigureAwait(false);\n\n return result;\n }\n\n private CancellationTokenRegistration RegisterCancellation(CancellationToken cancellationToken, JsonRpcRequest request)\n {\n if (!cancellationToken.CanBeCanceled)\n {\n return default;\n }\n\n return cancellationToken.Register(static objState =>\n {\n var state = (Tuple)objState!;\n _ = state.Item1.SendMessageAsync(new JsonRpcNotification\n {\n Method = NotificationMethods.CancelledNotification,\n Params = JsonSerializer.SerializeToNode(new CancelledNotificationParams { RequestId = state.Item2.Id }, McpJsonUtilities.JsonContext.Default.CancelledNotificationParams),\n RelatedTransport = state.Item2.RelatedTransport,\n });\n }, Tuple.Create(this, request));\n }\n\n public IAsyncDisposable RegisterNotificationHandler(string method, Func handler)\n {\n Throw.IfNullOrWhiteSpace(method);\n Throw.IfNull(handler);\n\n return _notificationHandlers.Register(method, handler);\n }\n\n /// \n /// Sends a JSON-RPC request to the server.\n /// It is strongly recommended use the capability-specific methods instead of this one.\n /// Use this method for custom requests or those not yet covered explicitly by the endpoint implementation.\n /// \n /// The JSON-RPC request to send.\n /// The to monitor for cancellation requests. The default is .\n /// A task containing the server's response.\n public async Task SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken)\n {\n cancellationToken.ThrowIfCancellationRequested();\n\n Histogram durationMetric = _isServer ? s_serverOperationDuration : s_clientOperationDuration;\n string method = request.Method;\n\n long? startingTimestamp = durationMetric.Enabled ? Stopwatch.GetTimestamp() : null;\n using Activity? activity = Diagnostics.ShouldInstrumentMessage(request) ?\n Diagnostics.ActivitySource.StartActivity(CreateActivityName(method), ActivityKind.Client) :\n null;\n\n // Set request ID\n if (request.Id.Id is null)\n {\n request = request.WithId(new RequestId(Interlocked.Increment(ref _lastRequestId)));\n }\n\n _propagator.InjectActivityContext(activity, request);\n\n TagList tags = default;\n bool addTags = activity is { IsAllDataRequested: true } || startingTimestamp is not null;\n\n var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);\n _pendingRequests[request.Id] = tcs;\n try\n {\n if (addTags)\n {\n AddTags(ref tags, activity, request, method);\n }\n\n if (_logger.IsEnabled(LogLevel.Trace))\n {\n LogSendingRequestSensitive(EndpointName, request.Method, JsonSerializer.Serialize(request, McpJsonUtilities.JsonContext.Default.JsonRpcMessage));\n }\n else\n {\n LogSendingRequest(EndpointName, request.Method);\n }\n\n await SendToRelatedTransportAsync(request, cancellationToken).ConfigureAwait(false);\n\n // Now that the request has been sent, register for cancellation. If we registered before,\n // a cancellation request could arrive before the server knew about that request ID, in which\n // case the server could ignore it.\n LogRequestSentAwaitingResponse(EndpointName, request.Method, request.Id);\n JsonRpcMessage? response;\n using (var registration = RegisterCancellation(cancellationToken, request))\n {\n response = await tcs.Task.WaitAsync(cancellationToken).ConfigureAwait(false);\n }\n\n if (response is JsonRpcError error)\n {\n LogSendingRequestFailed(EndpointName, request.Method, error.Error.Message, error.Error.Code);\n throw new McpException($\"Request failed (remote): {error.Error.Message}\", (McpErrorCode)error.Error.Code);\n }\n\n if (response is JsonRpcResponse success)\n {\n if (addTags)\n {\n AddResponseTags(ref tags, activity, success.Result, method);\n }\n\n if (_logger.IsEnabled(LogLevel.Trace))\n {\n LogRequestResponseReceivedSensitive(EndpointName, request.Method, success.Result?.ToJsonString() ?? \"null\");\n }\n else\n {\n LogRequestResponseReceived(EndpointName, request.Method);\n }\n\n return success;\n }\n\n // Unexpected response type\n LogSendingRequestInvalidResponseType(EndpointName, request.Method);\n throw new McpException(\"Invalid response type\");\n }\n catch (Exception ex) when (addTags)\n {\n AddExceptionTags(ref tags, activity, ex);\n throw;\n }\n finally\n {\n _pendingRequests.TryRemove(request.Id, out _);\n FinalizeDiagnostics(activity, startingTimestamp, durationMetric, ref tags);\n }\n }\n\n public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n Throw.IfNull(message);\n\n cancellationToken.ThrowIfCancellationRequested();\n\n Histogram durationMetric = _isServer ? s_serverOperationDuration : s_clientOperationDuration;\n string method = GetMethodName(message);\n\n long? startingTimestamp = durationMetric.Enabled ? Stopwatch.GetTimestamp() : null;\n using Activity? activity = Diagnostics.ShouldInstrumentMessage(message) ?\n Diagnostics.ActivitySource.StartActivity(CreateActivityName(method), ActivityKind.Client) :\n null;\n\n TagList tags = default;\n bool addTags = activity is { IsAllDataRequested: true } || startingTimestamp is not null;\n\n // propagate trace context\n _propagator?.InjectActivityContext(activity, message);\n\n try\n {\n if (addTags)\n {\n AddTags(ref tags, activity, message, method);\n }\n\n if (_logger.IsEnabled(LogLevel.Trace))\n {\n LogSendingMessageSensitive(EndpointName, JsonSerializer.Serialize(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage));\n }\n else\n {\n LogSendingMessage(EndpointName);\n }\n\n await SendToRelatedTransportAsync(message, cancellationToken).ConfigureAwait(false);\n\n // If the sent notification was a cancellation notification, cancel the pending request's await, as either the\n // server won't be sending a response, or per the specification, the response should be ignored. There are inherent\n // race conditions here, so it's possible and allowed for the operation to complete before we get to this point.\n if (message is JsonRpcNotification { Method: NotificationMethods.CancelledNotification } notification &&\n GetCancelledNotificationParams(notification.Params) is CancelledNotificationParams cn &&\n _pendingRequests.TryRemove(cn.RequestId, out var tcs))\n {\n tcs.TrySetCanceled(default);\n }\n }\n catch (Exception ex) when (addTags)\n {\n AddExceptionTags(ref tags, activity, ex);\n throw;\n }\n finally\n {\n FinalizeDiagnostics(activity, startingTimestamp, durationMetric, ref tags);\n }\n }\n\n // The JsonRpcMessage should be sent over the RelatedTransport if set. This is used to support the\n // Streamable HTTP transport where the specification states that the server SHOULD include JSON-RPC responses in\n // the HTTP response body for the POST request containing the corresponding JSON-RPC request.\n private Task SendToRelatedTransportAsync(JsonRpcMessage message, CancellationToken cancellationToken)\n => (message.RelatedTransport ?? _transport).SendMessageAsync(message, cancellationToken);\n\n private static CancelledNotificationParams? GetCancelledNotificationParams(JsonNode? notificationParams)\n {\n try\n {\n return JsonSerializer.Deserialize(notificationParams, McpJsonUtilities.JsonContext.Default.CancelledNotificationParams);\n }\n catch\n {\n return null;\n }\n }\n\n private string CreateActivityName(string method) => method;\n\n private static string GetMethodName(JsonRpcMessage message) =>\n message switch\n {\n JsonRpcRequest request => request.Method,\n JsonRpcNotification notification => notification.Method,\n _ => \"unknownMethod\"\n };\n\n private void AddTags(ref TagList tags, Activity? activity, JsonRpcMessage message, string method)\n {\n tags.Add(\"mcp.method.name\", method);\n tags.Add(\"network.transport\", _transportKind);\n\n // TODO: When using SSE transport, add:\n // - server.address and server.port on client spans and metrics\n // - client.address and client.port on server spans (not metrics because of cardinality) when using SSE transport\n if (activity is { IsAllDataRequested: true })\n {\n // session and request id have high cardinality, so not applying to metric tags\n activity.AddTag(\"mcp.session.id\", _sessionId);\n\n if (message is JsonRpcMessageWithId withId)\n {\n activity.AddTag(\"mcp.request.id\", withId.Id.Id?.ToString());\n }\n }\n\n JsonObject? paramsObj = message switch\n {\n JsonRpcRequest request => request.Params as JsonObject,\n JsonRpcNotification notification => notification.Params as JsonObject,\n _ => null\n };\n\n if (paramsObj == null)\n {\n return;\n }\n\n string? target = null;\n switch (method)\n {\n case RequestMethods.ToolsCall:\n case RequestMethods.PromptsGet:\n target = GetStringProperty(paramsObj, \"name\");\n if (target is not null)\n {\n tags.Add(method == RequestMethods.ToolsCall ? \"mcp.tool.name\" : \"mcp.prompt.name\", target);\n }\n break;\n\n case RequestMethods.ResourcesRead:\n case RequestMethods.ResourcesSubscribe:\n case RequestMethods.ResourcesUnsubscribe:\n case NotificationMethods.ResourceUpdatedNotification:\n target = GetStringProperty(paramsObj, \"uri\");\n if (target is not null)\n {\n tags.Add(\"mcp.resource.uri\", target);\n }\n break;\n }\n\n if (activity is { IsAllDataRequested: true })\n {\n activity.DisplayName = target == null ? method : $\"{method} {target}\";\n }\n }\n\n private static void AddExceptionTags(ref TagList tags, Activity? activity, Exception e)\n {\n if (e is AggregateException ae && ae.InnerException is not null and not AggregateException)\n {\n e = ae.InnerException;\n }\n\n int? intErrorCode =\n (int?)((e as McpException)?.ErrorCode) is int errorCode ? errorCode :\n e is JsonException ? (int)McpErrorCode.ParseError :\n null;\n\n string? errorType = intErrorCode?.ToString() ?? e.GetType().FullName;\n tags.Add(\"error.type\", errorType);\n if (intErrorCode is not null)\n {\n tags.Add(\"rpc.jsonrpc.error_code\", errorType);\n }\n\n if (activity is { IsAllDataRequested: true })\n {\n activity.SetStatus(ActivityStatusCode.Error, e.Message);\n }\n }\n\n private static void AddResponseTags(ref TagList tags, Activity? activity, JsonNode? response, string method)\n {\n if (response is JsonObject jsonObject\n && jsonObject.TryGetPropertyValue(\"isError\", out var isError)\n && isError?.GetValueKind() == JsonValueKind.True)\n {\n if (activity is { IsAllDataRequested: true })\n {\n string? content = null;\n if (jsonObject.TryGetPropertyValue(\"content\", out var prop) && prop != null)\n {\n content = prop.ToJsonString();\n }\n\n activity.SetStatus(ActivityStatusCode.Error, content);\n }\n\n tags.Add(\"error.type\", method == RequestMethods.ToolsCall ? \"tool_error\" : \"_OTHER\");\n }\n }\n\n private static void FinalizeDiagnostics(\n Activity? activity, long? startingTimestamp, Histogram durationMetric, ref TagList tags)\n {\n try\n {\n if (startingTimestamp is not null)\n {\n durationMetric.Record(GetElapsed(startingTimestamp.Value).TotalSeconds, tags);\n }\n\n if (activity is { IsAllDataRequested: true })\n {\n foreach (var tag in tags)\n {\n activity.AddTag(tag.Key, tag.Value);\n }\n }\n }\n finally\n {\n activity?.Dispose();\n }\n }\n\n public void Dispose()\n {\n Histogram durationMetric = _isServer ? s_serverSessionDuration : s_clientSessionDuration;\n if (durationMetric.Enabled)\n {\n TagList tags = default;\n tags.Add(\"network.transport\", _transportKind);\n\n // TODO: Add server.address and server.port on client-side when using SSE transport,\n // client.* attributes are not added to metrics because of cardinality\n durationMetric.Record(GetElapsed(_sessionStartingTimestamp).TotalSeconds, tags);\n }\n\n // Complete all pending requests with cancellation\n foreach (var entry in _pendingRequests)\n {\n entry.Value.TrySetCanceled();\n }\n\n _pendingRequests.Clear();\n }\n\n#if !NET\n private static readonly double s_timestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;\n#endif\n\n private static TimeSpan GetElapsed(long startingTimestamp) =>\n#if NET\n Stopwatch.GetElapsedTime(startingTimestamp);\n#else\n new((long)(s_timestampToTicks * (Stopwatch.GetTimestamp() - startingTimestamp)));\n#endif\n\n private static string? GetStringProperty(JsonObject parameters, string propName)\n {\n if (parameters.TryGetPropertyValue(propName, out var prop) && prop?.GetValueKind() is JsonValueKind.String)\n {\n return prop.GetValue();\n }\n\n return null;\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} message processing canceled.\")]\n private partial void LogEndpointMessageProcessingCanceled(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} method '{Method}' request handler called.\")]\n private partial void LogRequestHandlerCalled(string endpointName, string method);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} method '{Method}' request handler completed.\")]\n private partial void LogRequestHandlerCompleted(string endpointName, string method);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} method '{Method}' request handler failed.\")]\n private partial void LogRequestHandlerException(string endpointName, string method, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} received request for unknown request ID '{RequestId}'.\")]\n private partial void LogNoRequestFoundForMessageWithId(string endpointName, RequestId requestId);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} request failed for method '{Method}': {ErrorMessage} ({ErrorCode}).\")]\n private partial void LogSendingRequestFailed(string endpointName, string method, string errorMessage, int errorCode);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} received invalid response for method '{Method}'.\")]\n private partial void LogSendingRequestInvalidResponseType(string endpointName, string method);\n\n [LoggerMessage(Level = LogLevel.Debug, Message = \"{EndpointName} sending method '{Method}' request.\")]\n private partial void LogSendingRequest(string endpointName, string method);\n\n [LoggerMessage(Level = LogLevel.Trace, Message = \"{EndpointName} sending method '{Method}' request. Request: '{Request}'.\")]\n private partial void LogSendingRequestSensitive(string endpointName, string method, string request);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} canceled request '{RequestId}' per client notification. Reason: '{Reason}'.\")]\n private partial void LogRequestCanceled(string endpointName, RequestId requestId, string? reason);\n\n [LoggerMessage(Level = LogLevel.Debug, Message = \"{EndpointName} Request response received for method {method}\")]\n private partial void LogRequestResponseReceived(string endpointName, string method);\n\n [LoggerMessage(Level = LogLevel.Trace, Message = \"{EndpointName} Request response received for method {method}. Response: '{Response}'.\")]\n private partial void LogRequestResponseReceivedSensitive(string endpointName, string method, string response);\n\n [LoggerMessage(Level = LogLevel.Debug, Message = \"{EndpointName} read {MessageType} message from channel.\")]\n private partial void LogMessageRead(string endpointName, string messageType);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} message handler {MessageType} failed.\")]\n private partial void LogMessageHandlerException(string endpointName, string messageType, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Trace, Message = \"{EndpointName} message handler {MessageType} failed. Message: '{Message}'.\")]\n private partial void LogMessageHandlerExceptionSensitive(string endpointName, string messageType, string message, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} received unexpected {MessageType} message type.\")]\n private partial void LogEndpointHandlerUnexpectedMessageType(string endpointName, string messageType);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} received request for method '{Method}', but no handler is available.\")]\n private partial void LogNoHandlerFoundForRequest(string endpointName, string method);\n\n [LoggerMessage(Level = LogLevel.Debug, Message = \"{EndpointName} waiting for response to request '{RequestId}' for method '{Method}'.\")]\n private partial void LogRequestSentAwaitingResponse(string endpointName, string method, RequestId requestId);\n\n [LoggerMessage(Level = LogLevel.Debug, Message = \"{EndpointName} sending message.\")]\n private partial void LogSendingMessage(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Trace, Message = \"{EndpointName} sending message. Message: '{Message}'.\")]\n private partial void LogSendingMessageSensitive(string endpointName, string message);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/AutoDetectingClientSessionTransport.cs", "using Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing ModelContextProtocol.Protocol;\nusing System.Net;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// A transport that automatically detects whether to use Streamable HTTP or SSE transport\n/// by trying Streamable HTTP first and falling back to SSE if that fails.\n/// \ninternal sealed partial class AutoDetectingClientSessionTransport : ITransport\n{\n private readonly SseClientTransportOptions _options;\n private readonly McpHttpClient _httpClient;\n private readonly ILoggerFactory? _loggerFactory;\n private readonly ILogger _logger;\n private readonly string _name;\n private readonly Channel _messageChannel;\n\n public AutoDetectingClientSessionTransport(string endpointName, SseClientTransportOptions transportOptions, McpHttpClient httpClient, ILoggerFactory? loggerFactory)\n {\n Throw.IfNull(transportOptions);\n Throw.IfNull(httpClient);\n\n _options = transportOptions;\n _httpClient = httpClient;\n _loggerFactory = loggerFactory;\n _logger = (ILogger?)loggerFactory?.CreateLogger() ?? NullLogger.Instance;\n _name = endpointName;\n\n // Same as TransportBase.cs.\n _messageChannel = Channel.CreateUnbounded(new UnboundedChannelOptions\n {\n SingleReader = true,\n SingleWriter = false,\n });\n }\n\n /// \n /// Returns the active transport (either StreamableHttp or SSE)\n /// \n internal ITransport? ActiveTransport { get; private set; }\n\n public ChannelReader MessageReader => _messageChannel.Reader;\n\n string? ITransport.SessionId => ActiveTransport?.SessionId;\n\n /// \n public Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (ActiveTransport is null)\n {\n return InitializeAsync(message, cancellationToken);\n }\n\n return ActiveTransport.SendMessageAsync(message, cancellationToken);\n }\n\n private async Task InitializeAsync(JsonRpcMessage message, CancellationToken cancellationToken)\n {\n // Try StreamableHttp first\n var streamableHttpTransport = new StreamableHttpClientSessionTransport(_name, _options, _httpClient, _messageChannel, _loggerFactory);\n\n try\n {\n LogAttemptingStreamableHttp(_name);\n using var response = await streamableHttpTransport.SendHttpRequestAsync(message, cancellationToken).ConfigureAwait(false);\n\n if (response.IsSuccessStatusCode)\n {\n LogUsingStreamableHttp(_name);\n ActiveTransport = streamableHttpTransport;\n }\n else\n {\n // If the status code is not success, fall back to SSE\n LogStreamableHttpFailed(_name, response.StatusCode);\n\n await streamableHttpTransport.DisposeAsync().ConfigureAwait(false);\n await InitializeSseTransportAsync(message, cancellationToken).ConfigureAwait(false);\n }\n }\n catch\n {\n // If nothing threw inside the try block, we've either set streamableHttpTransport as the\n // ActiveTransport, or else we will have disposed it in the !IsSuccessStatusCode else block.\n await streamableHttpTransport.DisposeAsync().ConfigureAwait(false);\n throw;\n }\n }\n\n private async Task InitializeSseTransportAsync(JsonRpcMessage message, CancellationToken cancellationToken)\n {\n var sseTransport = new SseClientSessionTransport(_name, _options, _httpClient, _messageChannel, _loggerFactory);\n\n try\n {\n LogAttemptingSSE(_name);\n await sseTransport.ConnectAsync(cancellationToken).ConfigureAwait(false);\n await sseTransport.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);\n\n LogUsingSSE(_name);\n ActiveTransport = sseTransport;\n }\n catch\n {\n await sseTransport.DisposeAsync().ConfigureAwait(false);\n throw;\n }\n }\n\n public async ValueTask DisposeAsync()\n {\n try\n {\n if (ActiveTransport is not null)\n {\n await ActiveTransport.DisposeAsync().ConfigureAwait(false);\n }\n }\n finally\n {\n // In the majority of cases, either the Streamable HTTP transport or SSE transport has completed the channel by now.\n // However, this may not be the case if HttpClient throws during the initial request due to misconfiguration.\n _messageChannel.Writer.TryComplete();\n }\n }\n\n [LoggerMessage(Level = LogLevel.Debug, Message = \"{EndpointName} attempting to connect using Streamable HTTP transport.\")]\n private partial void LogAttemptingStreamableHttp(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} streamable HTTP transport failed with status code {StatusCode}, falling back to SSE transport.\")]\n private partial void LogStreamableHttpFailed(string endpointName, HttpStatusCode statusCode);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} using Streamable HTTP transport.\")]\n private partial void LogUsingStreamableHttp(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Debug, Message = \"{EndpointName} attempting to connect using SSE transport.\")]\n private partial void LogAttemptingSSE(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} using SSE transport.\")]\n private partial void LogUsingSSE(string endpointName);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/McpClient.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing System.Text.Json;\n\nnamespace ModelContextProtocol.Client;\n\n/// \ninternal sealed partial class McpClient : McpEndpoint, IMcpClient\n{\n private static Implementation DefaultImplementation { get; } = new()\n {\n Name = DefaultAssemblyName.Name ?? nameof(McpClient),\n Version = DefaultAssemblyName.Version?.ToString() ?? \"1.0.0\",\n };\n\n private readonly IClientTransport _clientTransport;\n private readonly McpClientOptions _options;\n\n private ITransport? _sessionTransport;\n private CancellationTokenSource? _connectCts;\n\n private ServerCapabilities? _serverCapabilities;\n private Implementation? _serverInfo;\n private string? _serverInstructions;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The transport to use for communication with the server.\n /// Options for the client, defining protocol version and capabilities.\n /// The logger factory.\n public McpClient(IClientTransport clientTransport, McpClientOptions? options, ILoggerFactory? loggerFactory)\n : base(loggerFactory)\n {\n options ??= new();\n\n _clientTransport = clientTransport;\n _options = options;\n\n EndpointName = clientTransport.Name;\n\n if (options.Capabilities is { } capabilities)\n {\n if (capabilities.NotificationHandlers is { } notificationHandlers)\n {\n NotificationHandlers.RegisterRange(notificationHandlers);\n }\n\n if (capabilities.Sampling is { } samplingCapability)\n {\n if (samplingCapability.SamplingHandler is not { } samplingHandler)\n {\n throw new InvalidOperationException(\"Sampling capability was set but it did not provide a handler.\");\n }\n\n RequestHandlers.Set(\n RequestMethods.SamplingCreateMessage,\n (request, _, cancellationToken) => samplingHandler(\n request,\n request?.ProgressToken is { } token ? new TokenProgress(this, token) : NullProgress.Instance,\n cancellationToken),\n McpJsonUtilities.JsonContext.Default.CreateMessageRequestParams,\n McpJsonUtilities.JsonContext.Default.CreateMessageResult);\n }\n\n if (capabilities.Roots is { } rootsCapability)\n {\n if (rootsCapability.RootsHandler is not { } rootsHandler)\n {\n throw new InvalidOperationException(\"Roots capability was set but it did not provide a handler.\");\n }\n\n RequestHandlers.Set(\n RequestMethods.RootsList,\n (request, _, cancellationToken) => rootsHandler(request, cancellationToken),\n McpJsonUtilities.JsonContext.Default.ListRootsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListRootsResult);\n }\n\n if (capabilities.Elicitation is { } elicitationCapability)\n {\n if (elicitationCapability.ElicitationHandler is not { } elicitationHandler)\n {\n throw new InvalidOperationException(\"Elicitation capability was set but it did not provide a handler.\");\n }\n\n RequestHandlers.Set(\n RequestMethods.ElicitationCreate,\n (request, _, cancellationToken) => elicitationHandler(request, cancellationToken),\n McpJsonUtilities.JsonContext.Default.ElicitRequestParams,\n McpJsonUtilities.JsonContext.Default.ElicitResult);\n }\n }\n }\n\n /// \n public string? SessionId\n {\n get\n {\n if (_sessionTransport is null)\n {\n throw new InvalidOperationException(\"Must have already initialized a session when invoking this property.\");\n }\n\n return _sessionTransport.SessionId;\n }\n }\n\n /// \n public ServerCapabilities ServerCapabilities => _serverCapabilities ?? throw new InvalidOperationException(\"The client is not connected.\");\n\n /// \n public Implementation ServerInfo => _serverInfo ?? throw new InvalidOperationException(\"The client is not connected.\");\n\n /// \n public string? ServerInstructions => _serverInstructions;\n\n /// \n public override string EndpointName { get; }\n\n /// \n /// Asynchronously connects to an MCP server, establishes the transport connection, and completes the initialization handshake.\n /// \n public async Task ConnectAsync(CancellationToken cancellationToken = default)\n {\n _connectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n cancellationToken = _connectCts.Token;\n\n try\n {\n // Connect transport\n _sessionTransport = await _clientTransport.ConnectAsync(cancellationToken).ConfigureAwait(false);\n InitializeSession(_sessionTransport);\n // We don't want the ConnectAsync token to cancel the session after we've successfully connected.\n // The base class handles cleaning up the session in DisposeAsync without our help.\n StartSession(_sessionTransport, fullSessionCancellationToken: CancellationToken.None);\n\n // Perform initialization sequence\n using var initializationCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);\n initializationCts.CancelAfter(_options.InitializationTimeout);\n\n try\n {\n // Send initialize request\n string requestProtocol = _options.ProtocolVersion ?? McpSession.LatestProtocolVersion;\n var initializeResponse = await this.SendRequestAsync(\n RequestMethods.Initialize,\n new InitializeRequestParams\n {\n ProtocolVersion = requestProtocol,\n Capabilities = _options.Capabilities ?? new ClientCapabilities(),\n ClientInfo = _options.ClientInfo ?? DefaultImplementation,\n },\n McpJsonUtilities.JsonContext.Default.InitializeRequestParams,\n McpJsonUtilities.JsonContext.Default.InitializeResult,\n cancellationToken: initializationCts.Token).ConfigureAwait(false);\n\n // Store server information\n if (_logger.IsEnabled(LogLevel.Information))\n {\n LogServerCapabilitiesReceived(EndpointName,\n capabilities: JsonSerializer.Serialize(initializeResponse.Capabilities, McpJsonUtilities.JsonContext.Default.ServerCapabilities),\n serverInfo: JsonSerializer.Serialize(initializeResponse.ServerInfo, McpJsonUtilities.JsonContext.Default.Implementation));\n }\n\n _serverCapabilities = initializeResponse.Capabilities;\n _serverInfo = initializeResponse.ServerInfo;\n _serverInstructions = initializeResponse.Instructions;\n\n // Validate protocol version\n bool isResponseProtocolValid =\n _options.ProtocolVersion is { } optionsProtocol ? optionsProtocol == initializeResponse.ProtocolVersion :\n McpSession.SupportedProtocolVersions.Contains(initializeResponse.ProtocolVersion);\n if (!isResponseProtocolValid)\n {\n LogServerProtocolVersionMismatch(EndpointName, requestProtocol, initializeResponse.ProtocolVersion);\n throw new McpException($\"Server protocol version mismatch. Expected {requestProtocol}, got {initializeResponse.ProtocolVersion}\");\n }\n\n // Send initialized notification\n await this.SendNotificationAsync(\n NotificationMethods.InitializedNotification,\n new InitializedNotificationParams(),\n McpJsonUtilities.JsonContext.Default.InitializedNotificationParams,\n cancellationToken: initializationCts.Token).ConfigureAwait(false);\n\n }\n catch (OperationCanceledException oce) when (initializationCts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)\n {\n LogClientInitializationTimeout(EndpointName);\n throw new TimeoutException(\"Initialization timed out\", oce);\n }\n }\n catch (Exception e)\n {\n LogClientInitializationError(EndpointName, e);\n await DisposeAsync().ConfigureAwait(false);\n throw;\n }\n }\n\n /// \n public override async ValueTask DisposeUnsynchronizedAsync()\n {\n try\n {\n if (_connectCts is not null)\n {\n await _connectCts.CancelAsync().ConfigureAwait(false);\n _connectCts.Dispose();\n }\n\n await base.DisposeUnsynchronizedAsync().ConfigureAwait(false);\n }\n finally\n {\n if (_sessionTransport is not null)\n {\n await _sessionTransport.DisposeAsync().ConfigureAwait(false);\n }\n }\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} client received server '{ServerInfo}' capabilities: '{Capabilities}'.\")]\n private partial void LogServerCapabilitiesReceived(string endpointName, string capabilities, string serverInfo);\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"{EndpointName} client initialization error.\")]\n private partial void LogClientInitializationError(string endpointName, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"{EndpointName} client initialization timed out.\")]\n private partial void LogClientInitializationTimeout(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"{EndpointName} client protocol version mismatch with server. Expected '{Expected}', received '{Received}'.\")]\n private partial void LogServerProtocolVersionMismatch(string endpointName, string expected, string received);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Client/SseClientTransport.cs", "using Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Authentication;\nusing ModelContextProtocol.Protocol;\n\nnamespace ModelContextProtocol.Client;\n\n/// \n/// Provides an over HTTP using the Server-Sent Events (SSE) or Streamable HTTP protocol.\n/// \n/// \n/// This transport connects to an MCP server over HTTP using SSE or Streamable HTTP,\n/// allowing for real-time server-to-client communication with a standard HTTP requests.\n/// Unlike the , this transport connects to an existing server\n/// rather than launching a new process.\n/// \npublic sealed class SseClientTransport : IClientTransport, IAsyncDisposable\n{\n private readonly SseClientTransportOptions _options;\n private readonly McpHttpClient _mcpHttpClient;\n private readonly ILoggerFactory? _loggerFactory;\n\n private readonly HttpClient? _ownedHttpClient;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// Configuration options for the transport.\n /// Logger factory for creating loggers used for diagnostic output during transport operations.\n public SseClientTransport(SseClientTransportOptions transportOptions, ILoggerFactory? loggerFactory = null)\n : this(transportOptions, new HttpClient(), loggerFactory, ownsHttpClient: true)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a provided HTTP client.\n /// \n /// Configuration options for the transport.\n /// The HTTP client instance used for requests.\n /// Logger factory for creating loggers used for diagnostic output during transport operations.\n /// \n /// to dispose of when the transport is disposed;\n /// if the caller is retaining ownership of the 's lifetime.\n /// \n public SseClientTransport(SseClientTransportOptions transportOptions, HttpClient httpClient, ILoggerFactory? loggerFactory = null, bool ownsHttpClient = false)\n {\n Throw.IfNull(transportOptions);\n Throw.IfNull(httpClient);\n\n _options = transportOptions;\n _loggerFactory = loggerFactory;\n Name = transportOptions.Name ?? transportOptions.Endpoint.ToString();\n\n if (transportOptions.OAuth is { } clientOAuthOptions)\n {\n var oAuthProvider = new ClientOAuthProvider(_options.Endpoint, clientOAuthOptions, httpClient, loggerFactory);\n _mcpHttpClient = new AuthenticatingMcpHttpClient(httpClient, oAuthProvider);\n }\n else\n {\n _mcpHttpClient = new(httpClient);\n }\n\n if (ownsHttpClient)\n {\n _ownedHttpClient = httpClient;\n }\n }\n\n /// \n public string Name { get; }\n\n /// \n public async Task ConnectAsync(CancellationToken cancellationToken = default)\n {\n return _options.TransportMode switch\n {\n HttpTransportMode.AutoDetect => new AutoDetectingClientSessionTransport(Name, _options, _mcpHttpClient, _loggerFactory),\n HttpTransportMode.StreamableHttp => new StreamableHttpClientSessionTransport(Name, _options, _mcpHttpClient, messageChannel: null, _loggerFactory),\n HttpTransportMode.Sse => await ConnectSseTransportAsync(cancellationToken).ConfigureAwait(false),\n _ => throw new InvalidOperationException($\"Unsupported transport mode: {_options.TransportMode}\"),\n };\n }\n\n private async Task ConnectSseTransportAsync(CancellationToken cancellationToken)\n {\n var sessionTransport = new SseClientSessionTransport(Name, _options, _mcpHttpClient, messageChannel: null, _loggerFactory);\n\n try\n {\n await sessionTransport.ConnectAsync(cancellationToken).ConfigureAwait(false);\n return sessionTransport;\n }\n catch\n {\n await sessionTransport.DisposeAsync().ConfigureAwait(false);\n throw;\n }\n }\n\n /// \n public ValueTask DisposeAsync()\n {\n _ownedHttpClient?.Dispose();\n return default;\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/ProcessHelper.cs", "using System.Diagnostics;\nusing System.Runtime.InteropServices;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Helper class for working with processes.\n/// \ninternal static class ProcessHelper\n{\n private static readonly bool _isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);\n private static readonly TimeSpan _defaultTimeout = TimeSpan.FromSeconds(30);\n\n /// \n /// Kills a process and all of its child processes (entire process tree).\n /// \n /// The process to terminate along with its child processes.\n /// \n /// This method uses a default timeout of 30 seconds when waiting for processes to exit.\n /// On Windows, this uses the \"taskkill\" command with the /T flag.\n /// On non-Windows platforms, it recursively identifies and terminates child processes.\n /// \n public static void KillTree(this Process process) => process.KillTree(_defaultTimeout);\n\n /// \n /// Kills a process and all of its child processes (entire process tree) with a specified timeout.\n /// \n /// The process to terminate along with its child processes.\n /// The maximum time to wait for the processes to exit.\n /// \n /// On Windows, this uses the \"taskkill\" command with the /T flag to terminate the process tree.\n /// On non-Windows platforms, it recursively identifies and terminates child processes.\n /// The method waits for the specified timeout for processes to exit before continuing.\n /// This is particularly useful for applications that spawn child processes (like Node.js)\n /// that wouldn't be terminated automatically when the parent process exits.\n /// \n public static void KillTree(this Process process, TimeSpan timeout)\n {\n var pid = process.Id;\n if (_isWindows)\n {\n RunProcessAndWaitForExit(\n \"taskkill\",\n $\"/T /F /PID {pid}\",\n timeout,\n out var _);\n }\n else\n {\n var children = new HashSet();\n GetAllChildIdsUnix(pid, children, timeout);\n foreach (var childId in children)\n {\n KillProcessUnix(childId, timeout);\n }\n KillProcessUnix(pid, timeout);\n }\n\n // wait until the process finishes exiting/getting killed. \n // We don't want to wait forever here because the task is already supposed to be dieing, we just want to give it long enough\n // to try and flush what it can and stop. If it cannot do that in a reasonable time frame then we will just ignore it.\n process.WaitForExit((int)timeout.TotalMilliseconds);\n }\n\n private static void GetAllChildIdsUnix(int parentId, ISet children, TimeSpan timeout)\n {\n var exitcode = RunProcessAndWaitForExit(\n \"pgrep\",\n $\"-P {parentId}\",\n timeout,\n out var stdout);\n\n if (exitcode == 0 && !string.IsNullOrEmpty(stdout))\n {\n using var reader = new StringReader(stdout);\n while (true)\n {\n var text = reader.ReadLine();\n if (text == null)\n return;\n\n if (int.TryParse(text, out var id))\n {\n children.Add(id);\n // Recursively get the children\n GetAllChildIdsUnix(id, children, timeout);\n }\n }\n }\n }\n\n private static void KillProcessUnix(int processId, TimeSpan timeout)\n {\n RunProcessAndWaitForExit(\n \"kill\",\n $\"-TERM {processId}\",\n timeout,\n out var _);\n }\n\n private static int RunProcessAndWaitForExit(string fileName, string arguments, TimeSpan timeout, out string? stdout)\n {\n var startInfo = new ProcessStartInfo\n {\n FileName = fileName,\n Arguments = arguments,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n UseShellExecute = false,\n CreateNoWindow = true,\n };\n\n stdout = null;\n\n var process = Process.Start(startInfo);\n if (process == null)\n return -1;\n\n if (process.WaitForExit((int)timeout.TotalMilliseconds))\n {\n stdout = process.StandardOutput.ReadToEnd();\n }\n else\n {\n process.Kill();\n }\n\n return process.ExitCode;\n }\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Authentication/ClientOAuthProvider.cs", "using Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing System.Collections.Specialized;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Text.Json;\nusing System.Web;\n\nnamespace ModelContextProtocol.Authentication;\n\n/// \n/// A generic implementation of an OAuth authorization provider for MCP. This does not do any advanced token\n/// protection or caching - it acquires a token and server metadata and holds it in memory.\n/// This is suitable for demonstration and development purposes.\n/// \ninternal sealed partial class ClientOAuthProvider\n{\n /// \n /// The Bearer authentication scheme.\n /// \n private const string BearerScheme = \"Bearer\";\n\n private readonly Uri _serverUrl;\n private readonly Uri _redirectUri;\n private readonly string[]? _scopes;\n private readonly IDictionary _additionalAuthorizationParameters;\n private readonly Func, Uri?> _authServerSelector;\n private readonly AuthorizationRedirectDelegate _authorizationRedirectDelegate;\n\n // _clientName and _client URI is used for dynamic client registration (RFC 7591)\n private readonly string? _clientName;\n private readonly Uri? _clientUri;\n\n private readonly HttpClient _httpClient;\n private readonly ILogger _logger;\n\n private string? _clientId;\n private string? _clientSecret;\n\n private TokenContainer? _token;\n private AuthorizationServerMetadata? _authServerMetadata;\n\n /// \n /// Initializes a new instance of the class using the specified options.\n /// \n /// The MCP server URL.\n /// The OAuth provider configuration options.\n /// The HTTP client to use for OAuth requests. If null, a default HttpClient will be used.\n /// A logger factory to handle diagnostic messages.\n /// Thrown when serverUrl or options are null.\n public ClientOAuthProvider(\n Uri serverUrl,\n ClientOAuthOptions options,\n HttpClient? httpClient = null,\n ILoggerFactory? loggerFactory = null)\n {\n _serverUrl = serverUrl ?? throw new ArgumentNullException(nameof(serverUrl));\n _httpClient = httpClient ?? new HttpClient();\n _logger = (ILogger?)loggerFactory?.CreateLogger() ?? NullLogger.Instance;\n\n if (options is null)\n {\n throw new ArgumentNullException(nameof(options));\n }\n\n _clientId = options.ClientId;\n _clientSecret = options.ClientSecret;\n _redirectUri = options.RedirectUri ?? throw new ArgumentException(\"ClientOAuthOptions.RedirectUri must configured.\");\n _clientName = options.ClientName;\n _clientUri = options.ClientUri;\n _scopes = options.Scopes?.ToArray();\n _additionalAuthorizationParameters = options.AdditionalAuthorizationParameters;\n\n // Set up authorization server selection strategy\n _authServerSelector = options.AuthServerSelector ?? DefaultAuthServerSelector;\n\n // Set up authorization URL handler (use default if not provided)\n _authorizationRedirectDelegate = options.AuthorizationRedirectDelegate ?? DefaultAuthorizationUrlHandler;\n }\n\n /// \n /// Default authorization server selection strategy that selects the first available server.\n /// \n /// List of available authorization servers.\n /// The selected authorization server, or null if none are available.\n private static Uri? DefaultAuthServerSelector(IReadOnlyList availableServers) => availableServers.FirstOrDefault();\n\n /// \n /// Default authorization URL handler that displays the URL to the user for manual input.\n /// \n /// The authorization URL to handle.\n /// The redirect URI where the authorization code will be sent.\n /// The cancellation token.\n /// The authorization code entered by the user, or null if none was provided.\n private static Task DefaultAuthorizationUrlHandler(Uri authorizationUrl, Uri redirectUri, CancellationToken cancellationToken)\n {\n Console.WriteLine($\"Please open the following URL in your browser to authorize the application:\");\n Console.WriteLine($\"{authorizationUrl}\");\n Console.WriteLine();\n Console.Write(\"Enter the authorization code from the redirect URL: \");\n var authorizationCode = Console.ReadLine();\n return Task.FromResult(authorizationCode);\n }\n\n /// \n /// Gets the collection of authentication schemes supported by this provider.\n /// \n /// \n /// \n /// This property returns all authentication schemes that this provider can handle,\n /// allowing clients to select the appropriate scheme based on server capabilities.\n /// \n /// \n /// Common values include \"Bearer\" for JWT tokens, \"Basic\" for username/password authentication,\n /// and \"Negotiate\" for integrated Windows authentication.\n /// \n /// \n public IEnumerable SupportedSchemes => [BearerScheme];\n\n /// \n /// Gets an authentication token or credential for authenticating requests to a resource\n /// using the specified authentication scheme.\n /// \n /// The authentication scheme to use.\n /// The URI of the resource requiring authentication.\n /// A token to cancel the operation.\n /// An authentication token string or null if no token could be obtained for the specified scheme.\n public async Task GetCredentialAsync(string scheme, Uri resourceUri, CancellationToken cancellationToken = default)\n {\n ThrowIfNotBearerScheme(scheme);\n\n // Return the token if it's valid\n if (_token != null && _token.ExpiresAt > DateTimeOffset.UtcNow.AddMinutes(5))\n {\n return _token.AccessToken;\n }\n\n // Try to refresh the token if we have a refresh token\n if (_token?.RefreshToken != null && _authServerMetadata != null)\n {\n var newToken = await RefreshTokenAsync(_token.RefreshToken, resourceUri, _authServerMetadata, cancellationToken).ConfigureAwait(false);\n if (newToken != null)\n {\n _token = newToken;\n return _token.AccessToken;\n }\n }\n\n // No valid token - auth handler will trigger the 401 flow\n return null;\n }\n\n /// \n /// Handles a 401 Unauthorized response from a resource.\n /// \n /// The authentication scheme that was used when the unauthorized response was received.\n /// The HTTP response that contained the 401 status code.\n /// A token to cancel the operation.\n /// \n /// A result object indicating if the provider was able to handle the unauthorized response,\n /// and the authentication scheme that should be used for the next attempt, if any.\n /// \n public async Task HandleUnauthorizedResponseAsync(\n string scheme,\n HttpResponseMessage response,\n CancellationToken cancellationToken = default)\n {\n // This provider only supports Bearer scheme\n if (!string.Equals(scheme, BearerScheme, StringComparison.OrdinalIgnoreCase))\n {\n throw new InvalidOperationException(\"This credential provider only supports the Bearer scheme\");\n }\n\n await PerformOAuthAuthorizationAsync(response, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Performs OAuth authorization by selecting an appropriate authorization server and completing the OAuth flow.\n /// \n /// The 401 Unauthorized response containing authentication challenge.\n /// Cancellation token.\n /// Result indicating whether authorization was successful.\n private async Task PerformOAuthAuthorizationAsync(\n HttpResponseMessage response,\n CancellationToken cancellationToken)\n {\n // Get available authorization servers from the 401 response\n var protectedResourceMetadata = await ExtractProtectedResourceMetadata(response, _serverUrl, cancellationToken).ConfigureAwait(false);\n var availableAuthorizationServers = protectedResourceMetadata.AuthorizationServers;\n\n if (availableAuthorizationServers.Count == 0)\n {\n ThrowFailedToHandleUnauthorizedResponse(\"No authorization servers found in authentication challenge\");\n }\n\n // Select authorization server using configured strategy\n var selectedAuthServer = _authServerSelector(availableAuthorizationServers);\n\n if (selectedAuthServer is null)\n {\n ThrowFailedToHandleUnauthorizedResponse($\"Authorization server selection returned null. Available servers: {string.Join(\", \", availableAuthorizationServers)}\");\n }\n\n if (!availableAuthorizationServers.Contains(selectedAuthServer))\n {\n ThrowFailedToHandleUnauthorizedResponse($\"Authorization server selector returned a server not in the available list: {selectedAuthServer}. Available servers: {string.Join(\", \", availableAuthorizationServers)}\");\n }\n\n LogSelectedAuthorizationServer(selectedAuthServer, availableAuthorizationServers.Count);\n\n // Get auth server metadata\n var authServerMetadata = await GetAuthServerMetadataAsync(selectedAuthServer, cancellationToken).ConfigureAwait(false);\n\n // Store auth server metadata for future refresh operations\n _authServerMetadata = authServerMetadata;\n\n // Perform dynamic client registration if needed\n if (string.IsNullOrEmpty(_clientId))\n {\n await PerformDynamicClientRegistrationAsync(authServerMetadata, cancellationToken).ConfigureAwait(false);\n }\n\n // Perform the OAuth flow\n var token = await InitiateAuthorizationCodeFlowAsync(protectedResourceMetadata, authServerMetadata, cancellationToken).ConfigureAwait(false);\n\n if (token is null)\n {\n ThrowFailedToHandleUnauthorizedResponse($\"The {nameof(AuthorizationRedirectDelegate)} returned a null or empty token.\");\n }\n\n _token = token;\n LogOAuthAuthorizationCompleted();\n }\n\n private async Task GetAuthServerMetadataAsync(Uri authServerUri, CancellationToken cancellationToken)\n {\n if (!authServerUri.OriginalString.EndsWith(\"/\"))\n {\n authServerUri = new Uri(authServerUri.OriginalString + \"/\");\n }\n\n foreach (var path in new[] { \".well-known/openid-configuration\", \".well-known/oauth-authorization-server\" })\n {\n try\n {\n var wellKnownEndpoint = new Uri(authServerUri, path);\n\n var response = await _httpClient.GetAsync(wellKnownEndpoint, cancellationToken).ConfigureAwait(false);\n if (!response.IsSuccessStatusCode)\n {\n continue;\n }\n\n using var stream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);\n var metadata = await JsonSerializer.DeserializeAsync(stream, McpJsonUtilities.JsonContext.Default.AuthorizationServerMetadata, cancellationToken).ConfigureAwait(false);\n\n if (metadata is null)\n {\n continue;\n }\n\n if (metadata.AuthorizationEndpoint is null)\n {\n ThrowFailedToHandleUnauthorizedResponse($\"No authorization_endpoint was provided via '{wellKnownEndpoint}'.\");\n }\n\n if (metadata.AuthorizationEndpoint.Scheme != Uri.UriSchemeHttp &&\n metadata.AuthorizationEndpoint.Scheme != Uri.UriSchemeHttps)\n {\n ThrowFailedToHandleUnauthorizedResponse($\"AuthorizationEndpoint must use HTTP or HTTPS. '{metadata.AuthorizationEndpoint}' does not meet this requirement.\");\n }\n\n metadata.ResponseTypesSupported ??= [\"code\"];\n metadata.GrantTypesSupported ??= [\"authorization_code\", \"refresh_token\"];\n metadata.TokenEndpointAuthMethodsSupported ??= [\"client_secret_post\"];\n metadata.CodeChallengeMethodsSupported ??= [\"S256\"];\n\n return metadata;\n }\n catch (Exception ex)\n {\n LogErrorFetchingAuthServerMetadata(ex, path);\n }\n }\n\n throw new McpException($\"Failed to find .well-known/openid-configuration or .well-known/oauth-authorization-server metadata for authorization server: '{authServerUri}'\");\n }\n\n private async Task RefreshTokenAsync(string refreshToken, Uri resourceUri, AuthorizationServerMetadata authServerMetadata, CancellationToken cancellationToken)\n {\n var requestContent = new FormUrlEncodedContent(new Dictionary\n {\n [\"grant_type\"] = \"refresh_token\",\n [\"refresh_token\"] = refreshToken,\n [\"client_id\"] = GetClientIdOrThrow(),\n [\"client_secret\"] = _clientSecret ?? string.Empty,\n [\"resource\"] = resourceUri.ToString(),\n });\n\n using var request = new HttpRequestMessage(HttpMethod.Post, authServerMetadata.TokenEndpoint)\n {\n Content = requestContent\n };\n\n return await FetchTokenAsync(request, cancellationToken).ConfigureAwait(false);\n }\n\n private async Task InitiateAuthorizationCodeFlowAsync(\n ProtectedResourceMetadata protectedResourceMetadata,\n AuthorizationServerMetadata authServerMetadata,\n CancellationToken cancellationToken)\n {\n var codeVerifier = GenerateCodeVerifier();\n var codeChallenge = GenerateCodeChallenge(codeVerifier);\n\n var authUrl = BuildAuthorizationUrl(protectedResourceMetadata, authServerMetadata, codeChallenge);\n var authCode = await _authorizationRedirectDelegate(authUrl, _redirectUri, cancellationToken).ConfigureAwait(false);\n\n if (string.IsNullOrEmpty(authCode))\n {\n return null;\n }\n\n return await ExchangeCodeForTokenAsync(protectedResourceMetadata, authServerMetadata, authCode!, codeVerifier, cancellationToken).ConfigureAwait(false);\n }\n\n private Uri BuildAuthorizationUrl(\n ProtectedResourceMetadata protectedResourceMetadata,\n AuthorizationServerMetadata authServerMetadata,\n string codeChallenge)\n {\n var queryParamsDictionary = new Dictionary\n {\n [\"client_id\"] = GetClientIdOrThrow(),\n [\"redirect_uri\"] = _redirectUri.ToString(),\n [\"response_type\"] = \"code\",\n [\"code_challenge\"] = codeChallenge,\n [\"code_challenge_method\"] = \"S256\",\n [\"resource\"] = protectedResourceMetadata.Resource.ToString(),\n };\n\n var scopesSupported = protectedResourceMetadata.ScopesSupported;\n if (_scopes is not null || scopesSupported.Count > 0)\n {\n queryParamsDictionary[\"scope\"] = string.Join(\" \", _scopes ?? scopesSupported.ToArray());\n }\n\n // Add extra parameters if provided. Load into a dictionary before constructing to avoid overwiting values.\n foreach (var kvp in _additionalAuthorizationParameters)\n {\n queryParamsDictionary.Add(kvp.Key, kvp.Value);\n }\n\n var queryParams = HttpUtility.ParseQueryString(string.Empty);\n foreach (var kvp in queryParamsDictionary)\n {\n queryParams[kvp.Key] = kvp.Value;\n }\n\n var uriBuilder = new UriBuilder(authServerMetadata.AuthorizationEndpoint)\n {\n Query = queryParams.ToString()\n };\n\n return uriBuilder.Uri;\n }\n\n private async Task ExchangeCodeForTokenAsync(\n ProtectedResourceMetadata protectedResourceMetadata,\n AuthorizationServerMetadata authServerMetadata,\n string authorizationCode,\n string codeVerifier,\n CancellationToken cancellationToken)\n {\n var requestContent = new FormUrlEncodedContent(new Dictionary\n {\n [\"grant_type\"] = \"authorization_code\",\n [\"code\"] = authorizationCode,\n [\"redirect_uri\"] = _redirectUri.ToString(),\n [\"client_id\"] = GetClientIdOrThrow(),\n [\"code_verifier\"] = codeVerifier,\n [\"client_secret\"] = _clientSecret ?? string.Empty,\n [\"resource\"] = protectedResourceMetadata.Resource.ToString(),\n });\n\n using var request = new HttpRequestMessage(HttpMethod.Post, authServerMetadata.TokenEndpoint)\n {\n Content = requestContent\n };\n\n return await FetchTokenAsync(request, cancellationToken).ConfigureAwait(false);\n }\n\n private async Task FetchTokenAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n {\n using var httpResponse = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);\n httpResponse.EnsureSuccessStatusCode();\n\n using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);\n var tokenResponse = await JsonSerializer.DeserializeAsync(stream, McpJsonUtilities.JsonContext.Default.TokenContainer, cancellationToken).ConfigureAwait(false);\n\n if (tokenResponse is null)\n {\n ThrowFailedToHandleUnauthorizedResponse($\"The token endpoint '{request.RequestUri}' returned an empty response.\");\n }\n\n tokenResponse.ObtainedAt = DateTimeOffset.UtcNow;\n return tokenResponse;\n }\n\n /// \n /// Fetches the protected resource metadata from the provided URL.\n /// \n /// The URL to fetch the metadata from.\n /// A token to cancel the operation.\n /// The fetched ProtectedResourceMetadata, or null if it couldn't be fetched.\n private async Task FetchProtectedResourceMetadataAsync(Uri metadataUrl, CancellationToken cancellationToken = default)\n {\n using var httpResponse = await _httpClient.GetAsync(metadataUrl, cancellationToken).ConfigureAwait(false);\n httpResponse.EnsureSuccessStatusCode();\n\n using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);\n return await JsonSerializer.DeserializeAsync(stream, McpJsonUtilities.JsonContext.Default.ProtectedResourceMetadata, cancellationToken).ConfigureAwait(false);\n }\n\n /// \n /// Performs dynamic client registration with the authorization server.\n /// \n /// The authorization server metadata.\n /// Cancellation token.\n /// A task representing the asynchronous operation.\n private async Task PerformDynamicClientRegistrationAsync(\n AuthorizationServerMetadata authServerMetadata,\n CancellationToken cancellationToken)\n {\n if (authServerMetadata.RegistrationEndpoint is null)\n {\n ThrowFailedToHandleUnauthorizedResponse(\"Authorization server does not support dynamic client registration\");\n }\n\n LogPerformingDynamicClientRegistration(authServerMetadata.RegistrationEndpoint);\n\n var registrationRequest = new DynamicClientRegistrationRequest\n {\n RedirectUris = [_redirectUri.ToString()],\n GrantTypes = [\"authorization_code\", \"refresh_token\"],\n ResponseTypes = [\"code\"],\n TokenEndpointAuthMethod = \"client_secret_post\",\n ClientName = _clientName,\n ClientUri = _clientUri?.ToString(),\n Scope = _scopes is not null ? string.Join(\" \", _scopes) : null\n };\n\n var requestJson = JsonSerializer.Serialize(registrationRequest, McpJsonUtilities.JsonContext.Default.DynamicClientRegistrationRequest);\n using var requestContent = new StringContent(requestJson, Encoding.UTF8, \"application/json\");\n\n using var request = new HttpRequestMessage(HttpMethod.Post, authServerMetadata.RegistrationEndpoint)\n {\n Content = requestContent\n };\n\n using var httpResponse = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false);\n\n if (!httpResponse.IsSuccessStatusCode)\n {\n var errorContent = await httpResponse.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);\n ThrowFailedToHandleUnauthorizedResponse($\"Dynamic client registration failed with status {httpResponse.StatusCode}: {errorContent}\");\n }\n\n using var responseStream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);\n var registrationResponse = await JsonSerializer.DeserializeAsync(\n responseStream,\n McpJsonUtilities.JsonContext.Default.DynamicClientRegistrationResponse,\n cancellationToken).ConfigureAwait(false);\n\n if (registrationResponse is null)\n {\n ThrowFailedToHandleUnauthorizedResponse(\"Dynamic client registration returned empty response\");\n }\n\n // Update client credentials\n _clientId = registrationResponse.ClientId;\n if (!string.IsNullOrEmpty(registrationResponse.ClientSecret))\n {\n _clientSecret = registrationResponse.ClientSecret;\n }\n\n LogDynamicClientRegistrationSuccessful(_clientId!);\n }\n\n /// \n /// Verifies that the resource URI in the metadata exactly matches the original request URL as required by the RFC.\n /// Per RFC: The resource value must be identical to the URL that the client used to make the request to the resource server.\n /// \n /// The metadata to verify.\n /// The original URL the client used to make the request to the resource server.\n /// True if the resource URI exactly matches the original request URL, otherwise false.\n private static bool VerifyResourceMatch(ProtectedResourceMetadata protectedResourceMetadata, Uri resourceLocation)\n {\n if (protectedResourceMetadata.Resource == null || resourceLocation == null)\n {\n return false;\n }\n\n // Per RFC: The resource value must be identical to the URL that the client used\n // to make the request to the resource server. Compare entire URIs, not just the host.\n\n // Normalize the URIs to ensure consistent comparison\n string normalizedMetadataResource = NormalizeUri(protectedResourceMetadata.Resource);\n string normalizedResourceLocation = NormalizeUri(resourceLocation);\n\n return string.Equals(normalizedMetadataResource, normalizedResourceLocation, StringComparison.OrdinalIgnoreCase);\n }\n\n /// \n /// Normalizes a URI for consistent comparison.\n /// \n /// The URI to normalize.\n /// A normalized string representation of the URI.\n private static string NormalizeUri(Uri uri)\n {\n var builder = new UriBuilder(uri)\n {\n Port = -1 // Always remove port\n };\n\n if (builder.Path == \"/\")\n {\n builder.Path = string.Empty;\n }\n else if (builder.Path.Length > 1 && builder.Path.EndsWith(\"/\"))\n {\n builder.Path = builder.Path.TrimEnd('/');\n }\n\n return builder.Uri.ToString();\n }\n\n /// \n /// Responds to a 401 challenge by parsing the WWW-Authenticate header, fetching the resource metadata,\n /// verifying the resource match, and returning the metadata if valid.\n /// \n /// The HTTP response containing the WWW-Authenticate header.\n /// The server URL to verify against the resource metadata.\n /// A token to cancel the operation.\n /// The resource metadata if the resource matches the server, otherwise throws an exception.\n /// Thrown when the response is not a 401, lacks a WWW-Authenticate header,\n /// lacks a resource_metadata parameter, the metadata can't be fetched, or the resource URI doesn't match the server URL.\n private async Task ExtractProtectedResourceMetadata(HttpResponseMessage response, Uri serverUrl, CancellationToken cancellationToken = default)\n {\n if (response.StatusCode != System.Net.HttpStatusCode.Unauthorized)\n {\n throw new InvalidOperationException($\"Expected a 401 Unauthorized response, but received {(int)response.StatusCode} {response.StatusCode}\");\n }\n\n // Extract the WWW-Authenticate header\n if (response.Headers.WwwAuthenticate.Count == 0)\n {\n throw new McpException(\"The 401 response does not contain a WWW-Authenticate header\");\n }\n\n // Look for the Bearer authentication scheme with resource_metadata parameter\n string? resourceMetadataUrl = null;\n foreach (var header in response.Headers.WwwAuthenticate)\n {\n if (string.Equals(header.Scheme, \"Bearer\", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrEmpty(header.Parameter))\n {\n resourceMetadataUrl = ParseWwwAuthenticateParameters(header.Parameter, \"resource_metadata\");\n if (resourceMetadataUrl != null)\n {\n break;\n }\n }\n }\n\n if (resourceMetadataUrl == null)\n {\n throw new McpException(\"The WWW-Authenticate header does not contain a resource_metadata parameter\");\n }\n\n Uri metadataUri = new(resourceMetadataUrl);\n var metadata = await FetchProtectedResourceMetadataAsync(metadataUri, cancellationToken).ConfigureAwait(false)\n ?? throw new McpException($\"Failed to fetch resource metadata from {resourceMetadataUrl}\");\n\n // Per RFC: The resource value must be identical to the URL that the client used\n // to make the request to the resource server\n LogValidatingResourceMetadata(serverUrl);\n\n if (!VerifyResourceMatch(metadata, serverUrl))\n {\n throw new McpException($\"Resource URI in metadata ({metadata.Resource}) does not match the expected URI ({serverUrl})\");\n }\n\n return metadata;\n }\n\n /// \n /// Parses the WWW-Authenticate header parameters to extract a specific parameter.\n /// \n /// The parameter string from the WWW-Authenticate header.\n /// The name of the parameter to extract.\n /// The value of the parameter, or null if not found.\n private static string? ParseWwwAuthenticateParameters(string parameters, string parameterName)\n {\n if (parameters.IndexOf(parameterName, StringComparison.OrdinalIgnoreCase) == -1)\n {\n return null;\n }\n\n foreach (var part in parameters.Split(','))\n {\n string trimmedPart = part.Trim();\n int equalsIndex = trimmedPart.IndexOf('=');\n\n if (equalsIndex <= 0)\n {\n continue;\n }\n\n string key = trimmedPart.Substring(0, equalsIndex).Trim();\n\n if (string.Equals(key, parameterName, StringComparison.OrdinalIgnoreCase))\n {\n string value = trimmedPart.Substring(equalsIndex + 1).Trim();\n\n if (value.StartsWith(\"\\\"\") && value.EndsWith(\"\\\"\"))\n {\n value = value.Substring(1, value.Length - 2);\n }\n\n return value;\n }\n }\n\n return null;\n }\n\n private static string GenerateCodeVerifier()\n {\n var bytes = new byte[32];\n using var rng = RandomNumberGenerator.Create();\n rng.GetBytes(bytes);\n return Convert.ToBase64String(bytes)\n .TrimEnd('=')\n .Replace('+', '-')\n .Replace('/', '_');\n }\n\n private static string GenerateCodeChallenge(string codeVerifier)\n {\n using var sha256 = SHA256.Create();\n var challengeBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(codeVerifier));\n return Convert.ToBase64String(challengeBytes)\n .TrimEnd('=')\n .Replace('+', '-')\n .Replace('/', '_');\n }\n\n private string GetClientIdOrThrow() => _clientId ?? throw new InvalidOperationException(\"Client ID is not available. This may indicate an issue with dynamic client registration.\");\n\n private static void ThrowIfNotBearerScheme(string scheme)\n {\n if (!string.Equals(scheme, BearerScheme, StringComparison.OrdinalIgnoreCase))\n {\n throw new InvalidOperationException($\"The '{scheme}' is not supported. This credential provider only supports the '{BearerScheme}' scheme\");\n }\n }\n\n [DoesNotReturn]\n private static void ThrowFailedToHandleUnauthorizedResponse(string message) =>\n throw new McpException($\"Failed to handle unauthorized response with 'Bearer' scheme. {message}\");\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"Selected authorization server: {Server} from {Count} available servers\")]\n partial void LogSelectedAuthorizationServer(Uri server, int count);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"OAuth authorization completed successfully\")]\n partial void LogOAuthAuthorizationCompleted();\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"Error fetching auth server metadata from {Path}\")]\n partial void LogErrorFetchingAuthServerMetadata(Exception ex, string path);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"Performing dynamic client registration with {RegistrationEndpoint}\")]\n partial void LogPerformingDynamicClientRegistration(Uri registrationEndpoint);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"Dynamic client registration successful. Client ID: {ClientId}\")]\n partial void LogDynamicClientRegistrationSuccessful(string clientId);\n\n [LoggerMessage(Level = LogLevel.Debug, Message = \"Validating resource metadata against original server URL: {ServerUrl}\")]\n partial void LogValidatingResourceMetadata(Uri serverUrl);\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/Server/McpServer.cs", "using Microsoft.Extensions.DependencyInjection;\nusing Microsoft.Extensions.Logging;\nusing ModelContextProtocol.Protocol;\nusing System.Runtime.CompilerServices;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol.Server;\n\n/// \ninternal sealed class McpServer : McpEndpoint, IMcpServer\n{\n internal static Implementation DefaultImplementation { get; } = new()\n {\n Name = DefaultAssemblyName.Name ?? nameof(McpServer),\n Version = DefaultAssemblyName.Version?.ToString() ?? \"1.0.0\",\n };\n\n private readonly ITransport _sessionTransport;\n private readonly bool _servicesScopePerRequest;\n private readonly List _disposables = [];\n\n private readonly string _serverOnlyEndpointName;\n private string? _endpointName;\n private int _started;\n\n /// Holds a boxed value for the server.\n /// \n /// Initialized to non-null the first time SetLevel is used. This is stored as a strong box\n /// rather than a nullable to be able to manipulate it atomically.\n /// \n private StrongBox? _loggingLevel;\n\n /// \n /// Creates a new instance of .\n /// \n /// Transport to use for the server representing an already-established session.\n /// Configuration options for this server, including capabilities.\n /// Make sure to accurately reflect exactly what capabilities the server supports and does not support.\n /// Logger factory to use for logging\n /// Optional service provider to use for dependency injection\n /// The server was incorrectly configured.\n public McpServer(ITransport transport, McpServerOptions options, ILoggerFactory? loggerFactory, IServiceProvider? serviceProvider)\n : base(loggerFactory)\n {\n Throw.IfNull(transport);\n Throw.IfNull(options);\n\n options ??= new();\n\n _sessionTransport = transport;\n ServerOptions = options;\n Services = serviceProvider;\n _serverOnlyEndpointName = $\"Server ({options.ServerInfo?.Name ?? DefaultImplementation.Name} {options.ServerInfo?.Version ?? DefaultImplementation.Version})\";\n _servicesScopePerRequest = options.ScopeRequests;\n\n ClientInfo = options.KnownClientInfo;\n UpdateEndpointNameWithClientInfo();\n\n // Configure all request handlers based on the supplied options.\n ServerCapabilities = new();\n ConfigureInitialize(options);\n ConfigureTools(options);\n ConfigurePrompts(options);\n ConfigureResources(options);\n ConfigureLogging(options);\n ConfigureCompletion(options);\n ConfigureExperimental(options);\n ConfigurePing();\n\n // Register any notification handlers that were provided.\n if (options.Capabilities?.NotificationHandlers is { } notificationHandlers)\n {\n NotificationHandlers.RegisterRange(notificationHandlers);\n }\n\n // Now that everything has been configured, subscribe to any necessary notifications.\n if (transport is not StreamableHttpServerTransport streamableHttpTransport || streamableHttpTransport.Stateless is false)\n {\n Register(ServerOptions.Capabilities?.Tools?.ToolCollection, NotificationMethods.ToolListChangedNotification);\n Register(ServerOptions.Capabilities?.Prompts?.PromptCollection, NotificationMethods.PromptListChangedNotification);\n Register(ServerOptions.Capabilities?.Resources?.ResourceCollection, NotificationMethods.ResourceListChangedNotification);\n\n void Register(McpServerPrimitiveCollection? collection, string notificationMethod)\n where TPrimitive : IMcpServerPrimitive\n {\n if (collection is not null)\n {\n EventHandler changed = (sender, e) => _ = this.SendNotificationAsync(notificationMethod);\n collection.Changed += changed;\n _disposables.Add(() => collection.Changed -= changed);\n }\n }\n }\n\n // And initialize the session.\n InitializeSession(transport);\n }\n\n /// \n public string? SessionId => _sessionTransport.SessionId;\n\n /// \n public ServerCapabilities ServerCapabilities { get; } = new();\n\n /// \n public ClientCapabilities? ClientCapabilities { get; set; }\n\n /// \n public Implementation? ClientInfo { get; set; }\n\n /// \n public McpServerOptions ServerOptions { get; }\n\n /// \n public IServiceProvider? Services { get; }\n\n /// \n public override string EndpointName => _endpointName ?? _serverOnlyEndpointName;\n\n /// \n public LoggingLevel? LoggingLevel => _loggingLevel?.Value;\n\n /// \n public async Task RunAsync(CancellationToken cancellationToken = default)\n {\n if (Interlocked.Exchange(ref _started, 1) != 0)\n {\n throw new InvalidOperationException($\"{nameof(RunAsync)} must only be called once.\");\n }\n\n try\n {\n StartSession(_sessionTransport, fullSessionCancellationToken: cancellationToken);\n await MessageProcessingTask.ConfigureAwait(false);\n }\n finally\n {\n await DisposeAsync().ConfigureAwait(false);\n }\n }\n\n public override async ValueTask DisposeUnsynchronizedAsync()\n {\n _disposables.ForEach(d => d());\n await base.DisposeUnsynchronizedAsync().ConfigureAwait(false);\n }\n\n private void ConfigurePing()\n {\n SetHandler(RequestMethods.Ping,\n async (request, _) => new PingResult(),\n McpJsonUtilities.JsonContext.Default.JsonNode,\n McpJsonUtilities.JsonContext.Default.PingResult);\n }\n\n private void ConfigureInitialize(McpServerOptions options)\n {\n RequestHandlers.Set(RequestMethods.Initialize,\n async (request, _, _) =>\n {\n ClientCapabilities = request?.Capabilities ?? new();\n ClientInfo = request?.ClientInfo;\n\n // Use the ClientInfo to update the session EndpointName for logging.\n UpdateEndpointNameWithClientInfo();\n GetSessionOrThrow().EndpointName = EndpointName;\n\n // Negotiate a protocol version. If the server options provide one, use that.\n // Otherwise, try to use whatever the client requested as long as it's supported.\n // If it's not supported, fall back to the latest supported version.\n string? protocolVersion = options.ProtocolVersion;\n if (protocolVersion is null)\n {\n protocolVersion = request?.ProtocolVersion is string clientProtocolVersion && McpSession.SupportedProtocolVersions.Contains(clientProtocolVersion) ?\n clientProtocolVersion :\n McpSession.LatestProtocolVersion;\n }\n\n return new InitializeResult\n {\n ProtocolVersion = protocolVersion,\n Instructions = options.ServerInstructions,\n ServerInfo = options.ServerInfo ?? DefaultImplementation,\n Capabilities = ServerCapabilities ?? new(),\n };\n },\n McpJsonUtilities.JsonContext.Default.InitializeRequestParams,\n McpJsonUtilities.JsonContext.Default.InitializeResult);\n }\n\n private void ConfigureCompletion(McpServerOptions options)\n {\n if (options.Capabilities?.Completions is not { } completionsCapability)\n {\n return;\n }\n\n ServerCapabilities.Completions = new()\n {\n CompleteHandler = completionsCapability.CompleteHandler ?? (static async (_, __) => new CompleteResult())\n };\n\n SetHandler(\n RequestMethods.CompletionComplete,\n ServerCapabilities.Completions.CompleteHandler,\n McpJsonUtilities.JsonContext.Default.CompleteRequestParams,\n McpJsonUtilities.JsonContext.Default.CompleteResult);\n }\n\n private void ConfigureExperimental(McpServerOptions options)\n {\n ServerCapabilities.Experimental = options.Capabilities?.Experimental;\n }\n\n private void ConfigureResources(McpServerOptions options)\n {\n if (options.Capabilities?.Resources is not { } resourcesCapability)\n {\n return;\n }\n\n ServerCapabilities.Resources = new();\n\n var listResourcesHandler = resourcesCapability.ListResourcesHandler ?? (static async (_, __) => new ListResourcesResult());\n var listResourceTemplatesHandler = resourcesCapability.ListResourceTemplatesHandler ?? (static async (_, __) => new ListResourceTemplatesResult());\n var readResourceHandler = resourcesCapability.ReadResourceHandler ?? (static async (request, _) => throw new McpException($\"Unknown resource URI: '{request.Params?.Uri}'\", McpErrorCode.InvalidParams));\n var subscribeHandler = resourcesCapability.SubscribeToResourcesHandler ?? (static async (_, __) => new EmptyResult());\n var unsubscribeHandler = resourcesCapability.UnsubscribeFromResourcesHandler ?? (static async (_, __) => new EmptyResult());\n var resources = resourcesCapability.ResourceCollection;\n var listChanged = resourcesCapability.ListChanged;\n var subscribe = resourcesCapability.Subscribe;\n\n // Handle resources provided via DI.\n if (resources is { IsEmpty: false })\n {\n var originalListResourcesHandler = listResourcesHandler;\n listResourcesHandler = async (request, cancellationToken) =>\n {\n ListResourcesResult result = originalListResourcesHandler is not null ?\n await originalListResourcesHandler(request, cancellationToken).ConfigureAwait(false) :\n new();\n\n if (request.Params?.Cursor is null)\n {\n foreach (var r in resources)\n {\n if (r.ProtocolResource is { } resource)\n {\n result.Resources.Add(resource);\n }\n }\n }\n\n return result;\n };\n\n var originalListResourceTemplatesHandler = listResourceTemplatesHandler;\n listResourceTemplatesHandler = async (request, cancellationToken) =>\n {\n ListResourceTemplatesResult result = originalListResourceTemplatesHandler is not null ?\n await originalListResourceTemplatesHandler(request, cancellationToken).ConfigureAwait(false) :\n new();\n\n if (request.Params?.Cursor is null)\n {\n foreach (var rt in resources)\n {\n if (rt.IsTemplated)\n {\n result.ResourceTemplates.Add(rt.ProtocolResourceTemplate);\n }\n }\n }\n\n return result;\n };\n\n // Synthesize read resource handler, which covers both resources and resource templates.\n var originalReadResourceHandler = readResourceHandler;\n readResourceHandler = async (request, cancellationToken) =>\n {\n if (request.Params?.Uri is string uri)\n {\n // First try an O(1) lookup by exact match.\n if (resources.TryGetPrimitive(uri, out var resource))\n {\n if (await resource.ReadAsync(request, cancellationToken).ConfigureAwait(false) is { } result)\n {\n return result;\n }\n }\n\n // Fall back to an O(N) lookup, trying to match against each URI template.\n // The number of templates is controlled by the server developer, and the number is expected to be\n // not terribly large. If that changes, this can be tweaked to enable a more efficient lookup.\n foreach (var resourceTemplate in resources)\n {\n if (await resourceTemplate.ReadAsync(request, cancellationToken).ConfigureAwait(false) is { } result)\n {\n return result;\n }\n }\n }\n\n // Finally fall back to the handler.\n return await originalReadResourceHandler(request, cancellationToken).ConfigureAwait(false);\n };\n\n listChanged = true;\n\n // TODO: Implement subscribe/unsubscribe logic for resource and resource template collections.\n // subscribe = true;\n }\n\n ServerCapabilities.Resources.ListResourcesHandler = listResourcesHandler;\n ServerCapabilities.Resources.ListResourceTemplatesHandler = listResourceTemplatesHandler;\n ServerCapabilities.Resources.ReadResourceHandler = readResourceHandler;\n ServerCapabilities.Resources.ResourceCollection = resources;\n ServerCapabilities.Resources.SubscribeToResourcesHandler = subscribeHandler;\n ServerCapabilities.Resources.UnsubscribeFromResourcesHandler = unsubscribeHandler;\n ServerCapabilities.Resources.ListChanged = listChanged;\n ServerCapabilities.Resources.Subscribe = subscribe;\n\n SetHandler(\n RequestMethods.ResourcesList,\n listResourcesHandler,\n McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourcesResult);\n\n SetHandler(\n RequestMethods.ResourcesTemplatesList,\n listResourceTemplatesHandler,\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,\n McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult);\n\n SetHandler(\n RequestMethods.ResourcesRead,\n readResourceHandler,\n McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,\n McpJsonUtilities.JsonContext.Default.ReadResourceResult);\n\n SetHandler(\n RequestMethods.ResourcesSubscribe,\n subscribeHandler,\n McpJsonUtilities.JsonContext.Default.SubscribeRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult);\n\n SetHandler(\n RequestMethods.ResourcesUnsubscribe,\n unsubscribeHandler,\n McpJsonUtilities.JsonContext.Default.UnsubscribeRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult);\n }\n\n private void ConfigurePrompts(McpServerOptions options)\n {\n if (options.Capabilities?.Prompts is not { } promptsCapability)\n {\n return;\n }\n\n ServerCapabilities.Prompts = new();\n\n var listPromptsHandler = promptsCapability.ListPromptsHandler ?? (static async (_, __) => new ListPromptsResult());\n var getPromptHandler = promptsCapability.GetPromptHandler ?? (static async (request, _) => throw new McpException($\"Unknown prompt: '{request.Params?.Name}'\", McpErrorCode.InvalidParams));\n var prompts = promptsCapability.PromptCollection;\n var listChanged = promptsCapability.ListChanged;\n\n // Handle tools provided via DI by augmenting the handlers to incorporate them.\n if (prompts is { IsEmpty: false })\n {\n var originalListPromptsHandler = listPromptsHandler;\n listPromptsHandler = async (request, cancellationToken) =>\n {\n ListPromptsResult result = originalListPromptsHandler is not null ?\n await originalListPromptsHandler(request, cancellationToken).ConfigureAwait(false) :\n new();\n\n if (request.Params?.Cursor is null)\n {\n foreach (var p in prompts)\n {\n result.Prompts.Add(p.ProtocolPrompt);\n }\n }\n\n return result;\n };\n\n var originalGetPromptHandler = getPromptHandler;\n getPromptHandler = (request, cancellationToken) =>\n {\n if (request.Params is not null &&\n prompts.TryGetPrimitive(request.Params.Name, out var prompt))\n {\n return prompt.GetAsync(request, cancellationToken);\n }\n\n return originalGetPromptHandler(request, cancellationToken);\n };\n\n listChanged = true;\n }\n\n ServerCapabilities.Prompts.ListPromptsHandler = listPromptsHandler;\n ServerCapabilities.Prompts.GetPromptHandler = getPromptHandler;\n ServerCapabilities.Prompts.PromptCollection = prompts;\n ServerCapabilities.Prompts.ListChanged = listChanged;\n\n SetHandler(\n RequestMethods.PromptsList,\n listPromptsHandler,\n McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListPromptsResult);\n\n SetHandler(\n RequestMethods.PromptsGet,\n getPromptHandler,\n McpJsonUtilities.JsonContext.Default.GetPromptRequestParams,\n McpJsonUtilities.JsonContext.Default.GetPromptResult);\n }\n\n private void ConfigureTools(McpServerOptions options)\n {\n if (options.Capabilities?.Tools is not { } toolsCapability)\n {\n return;\n }\n\n ServerCapabilities.Tools = new();\n\n var listToolsHandler = toolsCapability.ListToolsHandler ?? (static async (_, __) => new ListToolsResult());\n var callToolHandler = toolsCapability.CallToolHandler ?? (static async (request, _) => throw new McpException($\"Unknown tool: '{request.Params?.Name}'\", McpErrorCode.InvalidParams));\n var tools = toolsCapability.ToolCollection;\n var listChanged = toolsCapability.ListChanged;\n\n // Handle tools provided via DI by augmenting the handlers to incorporate them.\n if (tools is { IsEmpty: false })\n {\n var originalListToolsHandler = listToolsHandler;\n listToolsHandler = async (request, cancellationToken) =>\n {\n ListToolsResult result = originalListToolsHandler is not null ?\n await originalListToolsHandler(request, cancellationToken).ConfigureAwait(false) :\n new();\n\n if (request.Params?.Cursor is null)\n {\n foreach (var t in tools)\n {\n result.Tools.Add(t.ProtocolTool);\n }\n }\n\n return result;\n };\n\n var originalCallToolHandler = callToolHandler;\n callToolHandler = (request, cancellationToken) =>\n {\n if (request.Params is not null &&\n tools.TryGetPrimitive(request.Params.Name, out var tool))\n {\n return tool.InvokeAsync(request, cancellationToken);\n }\n\n return originalCallToolHandler(request, cancellationToken);\n };\n\n listChanged = true;\n }\n\n ServerCapabilities.Tools.ListToolsHandler = listToolsHandler;\n ServerCapabilities.Tools.CallToolHandler = callToolHandler;\n ServerCapabilities.Tools.ToolCollection = tools;\n ServerCapabilities.Tools.ListChanged = listChanged;\n\n SetHandler(\n RequestMethods.ToolsList,\n listToolsHandler,\n McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,\n McpJsonUtilities.JsonContext.Default.ListToolsResult);\n\n SetHandler(\n RequestMethods.ToolsCall,\n callToolHandler,\n McpJsonUtilities.JsonContext.Default.CallToolRequestParams,\n McpJsonUtilities.JsonContext.Default.CallToolResult);\n }\n\n private void ConfigureLogging(McpServerOptions options)\n {\n // We don't require that the handler be provided, as we always store the provided log level to the server.\n var setLoggingLevelHandler = options.Capabilities?.Logging?.SetLoggingLevelHandler;\n\n ServerCapabilities.Logging = new();\n ServerCapabilities.Logging.SetLoggingLevelHandler = setLoggingLevelHandler;\n\n RequestHandlers.Set(\n RequestMethods.LoggingSetLevel,\n (request, destinationTransport, cancellationToken) =>\n {\n // Store the provided level.\n if (request is not null)\n {\n if (_loggingLevel is null)\n {\n Interlocked.CompareExchange(ref _loggingLevel, new(request.Level), null);\n }\n\n _loggingLevel.Value = request.Level;\n }\n\n // If a handler was provided, now delegate to it.\n if (setLoggingLevelHandler is not null)\n {\n return InvokeHandlerAsync(setLoggingLevelHandler, request, destinationTransport, cancellationToken);\n }\n\n // Otherwise, consider it handled.\n return new ValueTask(EmptyResult.Instance);\n },\n McpJsonUtilities.JsonContext.Default.SetLevelRequestParams,\n McpJsonUtilities.JsonContext.Default.EmptyResult);\n }\n\n private ValueTask InvokeHandlerAsync(\n Func, CancellationToken, ValueTask> handler,\n TParams? args,\n ITransport? destinationTransport = null,\n CancellationToken cancellationToken = default)\n {\n return _servicesScopePerRequest ?\n InvokeScopedAsync(handler, args, cancellationToken) :\n handler(new(new DestinationBoundMcpServer(this, destinationTransport)) { Params = args }, cancellationToken);\n\n async ValueTask InvokeScopedAsync(\n Func, CancellationToken, ValueTask> handler,\n TParams? args,\n CancellationToken cancellationToken)\n {\n var scope = Services?.GetService()?.CreateAsyncScope();\n try\n {\n return await handler(\n new RequestContext(new DestinationBoundMcpServer(this, destinationTransport))\n {\n Services = scope?.ServiceProvider ?? Services,\n Params = args\n },\n cancellationToken).ConfigureAwait(false);\n }\n finally\n {\n if (scope is not null)\n {\n await scope.Value.DisposeAsync().ConfigureAwait(false);\n }\n }\n }\n }\n\n private void SetHandler(\n string method,\n Func, CancellationToken, ValueTask> handler,\n JsonTypeInfo requestTypeInfo,\n JsonTypeInfo responseTypeInfo)\n {\n RequestHandlers.Set(method, \n (request, destinationTransport, cancellationToken) =>\n InvokeHandlerAsync(handler, request, destinationTransport, cancellationToken),\n requestTypeInfo, responseTypeInfo);\n }\n\n private void UpdateEndpointNameWithClientInfo()\n {\n if (ClientInfo is null)\n {\n return;\n }\n\n _endpointName = $\"{_serverOnlyEndpointName}, Client ({ClientInfo.Name} {ClientInfo.Version})\";\n }\n\n /// Maps a to a .\n internal static LoggingLevel ToLoggingLevel(LogLevel level) =>\n level switch\n {\n LogLevel.Trace => Protocol.LoggingLevel.Debug,\n LogLevel.Debug => Protocol.LoggingLevel.Debug,\n LogLevel.Information => Protocol.LoggingLevel.Info,\n LogLevel.Warning => Protocol.LoggingLevel.Warning,\n LogLevel.Error => Protocol.LoggingLevel.Error,\n LogLevel.Critical => Protocol.LoggingLevel.Critical,\n _ => Protocol.LoggingLevel.Emergency,\n };\n}\n"], ["/csharp-sdk/src/ModelContextProtocol.Core/McpEndpoint.cs", "using Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Reflection;\n\nnamespace ModelContextProtocol;\n\n/// \n/// Base class for an MCP JSON-RPC endpoint. This covers both MCP clients and servers.\n/// It is not supported, nor necessary, to implement both client and server functionality in the same class.\n/// If an application needs to act as both a client and a server, it should use separate objects for each.\n/// This is especially true as a client represents a connection to one and only one server, and vice versa.\n/// Any multi-client or multi-server functionality should be implemented at a higher level of abstraction.\n/// \ninternal abstract partial class McpEndpoint : IAsyncDisposable\n{\n /// Cached naming information used for name/version when none is specified.\n internal static AssemblyName DefaultAssemblyName { get; } = (Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()).GetName();\n\n private McpSession? _session;\n private CancellationTokenSource? _sessionCts;\n\n private readonly SemaphoreSlim _disposeLock = new(1, 1);\n private bool _disposed;\n\n protected readonly ILogger _logger;\n\n /// \n /// Initializes a new instance of the class.\n /// \n /// The logger factory.\n protected McpEndpoint(ILoggerFactory? loggerFactory = null)\n {\n _logger = loggerFactory?.CreateLogger(GetType()) ?? NullLogger.Instance;\n }\n\n protected RequestHandlers RequestHandlers { get; } = [];\n\n protected NotificationHandlers NotificationHandlers { get; } = new();\n\n public Task SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default)\n => GetSessionOrThrow().SendRequestAsync(request, cancellationToken);\n\n public Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n => GetSessionOrThrow().SendMessageAsync(message, cancellationToken);\n\n public IAsyncDisposable RegisterNotificationHandler(string method, Func handler) =>\n GetSessionOrThrow().RegisterNotificationHandler(method, handler);\n\n /// \n /// Gets the name of the endpoint for logging and debug purposes.\n /// \n public abstract string EndpointName { get; }\n\n /// \n /// Task that processes incoming messages from the transport.\n /// \n protected Task? MessageProcessingTask { get; private set; }\n\n protected void InitializeSession(ITransport sessionTransport)\n {\n _session = new McpSession(this is IMcpServer, sessionTransport, EndpointName, RequestHandlers, NotificationHandlers, _logger);\n }\n\n [MemberNotNull(nameof(MessageProcessingTask))]\n protected void StartSession(ITransport sessionTransport, CancellationToken fullSessionCancellationToken)\n {\n _sessionCts = CancellationTokenSource.CreateLinkedTokenSource(fullSessionCancellationToken);\n MessageProcessingTask = GetSessionOrThrow().ProcessMessagesAsync(_sessionCts.Token);\n }\n\n protected void CancelSession() => _sessionCts?.Cancel();\n\n public async ValueTask DisposeAsync()\n {\n using var _ = await _disposeLock.LockAsync().ConfigureAwait(false);\n\n if (_disposed)\n {\n return;\n }\n _disposed = true;\n\n await DisposeUnsynchronizedAsync().ConfigureAwait(false);\n }\n\n /// \n /// Cleans up the endpoint and releases resources.\n /// \n /// \n public virtual async ValueTask DisposeUnsynchronizedAsync()\n {\n LogEndpointShuttingDown(EndpointName);\n\n try\n {\n if (_sessionCts is not null)\n {\n await _sessionCts.CancelAsync().ConfigureAwait(false);\n }\n\n if (MessageProcessingTask is not null)\n {\n try\n {\n await MessageProcessingTask.ConfigureAwait(false);\n }\n catch (OperationCanceledException)\n {\n // Ignore cancellation\n }\n }\n }\n finally\n {\n _session?.Dispose();\n _sessionCts?.Dispose();\n }\n\n LogEndpointShutDown(EndpointName);\n }\n\n protected McpSession GetSessionOrThrow()\n {\n#if NET\n ObjectDisposedException.ThrowIf(_disposed, this);\n#else\n if (_disposed)\n {\n throw new ObjectDisposedException(GetType().Name);\n }\n#endif\n\n return _session ?? throw new InvalidOperationException($\"This should be unreachable from public API! Call {nameof(InitializeSession)} before sending messages.\");\n }\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} shutting down.\")]\n private partial void LogEndpointShuttingDown(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} shut down.\")]\n private partial void LogEndpointShutDown(string endpointName);\n}"], ["/csharp-sdk/src/ModelContextProtocol.Core/Protocol/TransportBase.cs", "using Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Logging.Abstractions;\nusing System.Diagnostics;\nusing System.Threading.Channels;\n\nnamespace ModelContextProtocol.Protocol;\n\n/// \n/// Provides a base class for implementing .\n/// \n/// \n/// \n/// The class provides core functionality required by most \n/// implementations, including message channel management, connection state tracking, and logging support.\n/// \n/// \n/// Custom transport implementations should inherit from this class and implement the abstract\n/// and methods\n/// to handle the specific transport mechanism being used.\n/// \n/// \npublic abstract partial class TransportBase : ITransport\n{\n private readonly Channel _messageChannel;\n private readonly ILogger _logger;\n private volatile int _state = StateInitial;\n\n /// The transport has not yet been connected.\n private const int StateInitial = 0;\n /// The transport is connected.\n private const int StateConnected = 1;\n /// The transport was previously connected and is now disconnected.\n private const int StateDisconnected = 2;\n\n /// \n /// Initializes a new instance of the class.\n /// \n protected TransportBase(string name, ILoggerFactory? loggerFactory)\n : this(name, null, loggerFactory)\n {\n }\n\n /// \n /// Initializes a new instance of the class with a specified channel to back .\n /// \n internal TransportBase(string name, Channel? messageChannel, ILoggerFactory? loggerFactory)\n {\n Name = name;\n _logger = loggerFactory?.CreateLogger(GetType()) ?? NullLogger.Instance;\n\n // Unbounded channel to prevent blocking on writes. Ensure AutoDetectingClientSessionTransport matches this.\n _messageChannel = messageChannel ?? Channel.CreateUnbounded(new UnboundedChannelOptions\n {\n SingleReader = true,\n SingleWriter = false,\n });\n }\n\n /// Gets the logger used by this transport.\n private protected ILogger Logger => _logger;\n\n /// \n public virtual string? SessionId { get; protected set; }\n\n /// \n /// Gets the name that identifies this transport endpoint in logs.\n /// \n /// \n /// This name is used in log messages to identify the source of transport-related events.\n /// \n protected string Name { get; }\n\n /// \n public bool IsConnected => _state == StateConnected;\n\n /// \n public ChannelReader MessageReader => _messageChannel.Reader;\n\n /// \n public abstract Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default);\n\n /// \n public abstract ValueTask DisposeAsync();\n\n /// \n /// Writes a message to the message channel.\n /// \n /// The message to write.\n /// The to monitor for cancellation requests. The default is .\n protected async Task WriteMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)\n {\n if (!IsConnected)\n {\n throw new InvalidOperationException(\"Transport is not connected.\");\n }\n\n if (_logger.IsEnabled(LogLevel.Debug))\n {\n var messageId = (message as JsonRpcMessageWithId)?.Id.ToString() ?? \"(no id)\";\n LogTransportReceivedMessage(Name, messageId);\n }\n\n bool wrote = _messageChannel.Writer.TryWrite(message);\n Debug.Assert(wrote || !IsConnected, \"_messageChannel is unbounded; this should only ever return false if the channel has been closed.\");\n }\n\n /// \n /// Sets the transport to a connected state.\n /// \n protected void SetConnected()\n {\n while (true)\n {\n int state = _state;\n switch (state)\n {\n case StateInitial:\n if (Interlocked.CompareExchange(ref _state, StateConnected, StateInitial) == StateInitial)\n {\n return;\n }\n break;\n\n case StateConnected:\n return;\n\n case StateDisconnected:\n throw new IOException(\"Transport is already disconnected and can't be reconnected.\");\n\n default:\n Debug.Fail($\"Unexpected state: {state}\");\n return;\n }\n }\n }\n\n /// \n /// Sets the transport to a disconnected state.\n /// \n /// Optional error information associated with the transport disconnecting. Should be if the disconnect was graceful and expected.\n protected void SetDisconnected(Exception? error = null)\n {\n int state = _state;\n switch (state)\n {\n case StateInitial:\n case StateConnected:\n _state = StateDisconnected;\n _messageChannel.Writer.TryComplete(error);\n break;\n\n case StateDisconnected:\n return;\n\n default:\n Debug.Fail($\"Unexpected state: {state}\");\n break;\n }\n }\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"{EndpointName} transport connect failed.\")]\n private protected partial void LogTransportConnectFailed(string endpointName, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Error, Message = \"{EndpointName} transport send failed for message ID '{MessageId}'.\")]\n private protected partial void LogTransportSendFailed(string endpointName, string messageId, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} transport reading messages.\")]\n private protected partial void LogTransportEnteringReadMessagesLoop(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} transport completed reading messages.\")]\n private protected partial void LogTransportEndOfStream(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Trace, Message = \"{EndpointName} transport received message. Message: '{Message}'.\")]\n private protected partial void LogTransportReceivedMessageSensitive(string endpointName, string message);\n\n [LoggerMessage(Level = LogLevel.Debug, Message = \"{EndpointName} transport received message with ID '{MessageId}'.\")]\n private protected partial void LogTransportReceivedMessage(string endpointName, string messageId);\n\n [LoggerMessage(Level = LogLevel.Trace, Message = \"{EndpointName} transport received unexpected message. Message: '{Message}'.\")]\n private protected partial void LogTransportMessageParseUnexpectedTypeSensitive(string endpointName, string message);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} transport message parsing failed.\")]\n private protected partial void LogTransportMessageParseFailed(string endpointName, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Trace, Message = \"{EndpointName} transport message parsing failed. Message: '{Message}'.\")]\n private protected partial void LogTransportMessageParseFailedSensitive(string endpointName, string message, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} transport message reading canceled.\")]\n private protected partial void LogTransportReadMessagesCancelled(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} transport message reading failed.\")]\n private protected partial void LogTransportReadMessagesFailed(string endpointName, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} shutting down.\")]\n private protected partial void LogTransportShuttingDown(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} shutdown failed.\")]\n private protected partial void LogTransportShutdownFailed(string endpointName, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} shutdown failed waiting for message reading completion.\")]\n private protected partial void LogTransportCleanupReadTaskFailed(string endpointName, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Information, Message = \"{EndpointName} shut down.\")]\n private protected partial void LogTransportShutDown(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} received message before connected.\")]\n private protected partial void LogTransportMessageReceivedBeforeConnected(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} endpoint event received out of order.\")]\n private protected partial void LogTransportEndpointEventInvalid(string endpointName);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} failed to parse event.\")]\n private protected partial void LogTransportEndpointEventParseFailed(string endpointName, Exception exception);\n\n [LoggerMessage(Level = LogLevel.Warning, Message = \"{EndpointName} failed to parse event. Message: '{Message}'.\")]\n private protected partial void LogTransportEndpointEventParseFailedSensitive(string endpointName, string message, Exception exception);\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/SseHandler.cs", "using Microsoft.AspNetCore.Http;\nusing Microsoft.Extensions.Hosting;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Collections.Concurrent;\nusing System.Diagnostics;\n\nnamespace ModelContextProtocol.AspNetCore;\n\ninternal sealed class SseHandler(\n IOptions mcpServerOptionsSnapshot,\n IOptionsFactory mcpServerOptionsFactory,\n IOptions httpMcpServerOptions,\n IHostApplicationLifetime hostApplicationLifetime,\n ILoggerFactory loggerFactory)\n{\n private readonly ConcurrentDictionary> _sessions = new(StringComparer.Ordinal);\n\n public async Task HandleSseRequestAsync(HttpContext context)\n {\n var sessionId = StreamableHttpHandler.MakeNewSessionId();\n\n // If the server is shutting down, we need to cancel all SSE connections immediately without waiting for HostOptions.ShutdownTimeout\n // which defaults to 30 seconds.\n using var sseCts = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted, hostApplicationLifetime.ApplicationStopping);\n var cancellationToken = sseCts.Token;\n\n StreamableHttpHandler.InitializeSseResponse(context);\n\n var requestPath = (context.Request.PathBase + context.Request.Path).ToString();\n var endpointPattern = requestPath[..(requestPath.LastIndexOf('/') + 1)];\n await using var transport = new SseResponseStreamTransport(context.Response.Body, $\"{endpointPattern}message?sessionId={sessionId}\", sessionId);\n\n var userIdClaim = StreamableHttpHandler.GetUserIdClaim(context.User);\n await using var httpMcpSession = new HttpMcpSession(sessionId, transport, userIdClaim, httpMcpServerOptions.Value.TimeProvider);\n\n if (!_sessions.TryAdd(sessionId, httpMcpSession))\n {\n throw new UnreachableException($\"Unreachable given good entropy! Session with ID '{sessionId}' has already been created.\");\n }\n\n try\n {\n var mcpServerOptions = mcpServerOptionsSnapshot.Value;\n if (httpMcpServerOptions.Value.ConfigureSessionOptions is { } configureSessionOptions)\n {\n mcpServerOptions = mcpServerOptionsFactory.Create(Options.DefaultName);\n await configureSessionOptions(context, mcpServerOptions, cancellationToken);\n }\n\n var transportTask = transport.RunAsync(cancellationToken);\n\n try\n {\n await using var mcpServer = McpServerFactory.Create(transport, mcpServerOptions, loggerFactory, context.RequestServices);\n httpMcpSession.Server = mcpServer;\n context.Features.Set(mcpServer);\n\n var runSessionAsync = httpMcpServerOptions.Value.RunSessionHandler ?? StreamableHttpHandler.RunSessionAsync;\n httpMcpSession.ServerRunTask = runSessionAsync(context, mcpServer, cancellationToken);\n await httpMcpSession.ServerRunTask;\n }\n finally\n {\n await transport.DisposeAsync();\n await transportTask;\n }\n }\n catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)\n {\n // RequestAborted always triggers when the client disconnects before a complete response body is written,\n // but this is how SSE connections are typically closed.\n }\n finally\n {\n _sessions.TryRemove(sessionId, out _);\n }\n }\n\n public async Task HandleMessageRequestAsync(HttpContext context)\n {\n if (!context.Request.Query.TryGetValue(\"sessionId\", out var sessionId))\n {\n await Results.BadRequest(\"Missing sessionId query parameter.\").ExecuteAsync(context);\n return;\n }\n\n if (!_sessions.TryGetValue(sessionId.ToString(), out var httpMcpSession))\n {\n await Results.BadRequest($\"Session ID not found.\").ExecuteAsync(context);\n return;\n }\n\n if (!httpMcpSession.HasSameUserId(context.User))\n {\n await Results.Forbid().ExecuteAsync(context);\n return;\n }\n\n var message = (JsonRpcMessage?)await context.Request.ReadFromJsonAsync(McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonRpcMessage)), context.RequestAborted);\n if (message is null)\n {\n await Results.BadRequest(\"No message in request body.\").ExecuteAsync(context);\n return;\n }\n\n await httpMcpSession.Transport.OnMessageReceivedAsync(message, context.RequestAborted);\n context.Response.StatusCode = StatusCodes.Status202Accepted;\n await context.Response.WriteAsync(\"Accepted\");\n }\n}\n"], ["/csharp-sdk/src/Common/CancellableStreamReader/CancellableStreamReader.cs", "// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses this file to you under the MIT license.\n\nusing System.Buffers;\nusing System.Buffers.Binary;\nusing System.Diagnostics;\nusing System.Diagnostics.CodeAnalysis;\nusing System.Text;\nusing ModelContextProtocol;\n\nnamespace System.IO;\n\n/// \n/// Netfx-compatible polyfill of System.IO.StreamReader that supports cancellation.\n/// \ninternal class CancellableStreamReader : TextReader\n{\n // CancellableStreamReader.Null is threadsafe.\n public static new readonly CancellableStreamReader Null = new NullCancellableStreamReader();\n\n // Using a 1K byte buffer and a 4K FileStream buffer works out pretty well\n // perf-wise. On even a 40 MB text file, any perf loss by using a 4K\n // buffer is negated by the win of allocating a smaller byte[], which\n // saves construction time. This does break adaptive buffering,\n // but this is slightly faster.\n private const int DefaultBufferSize = 1024; // Byte buffer size\n private const int DefaultFileStreamBufferSize = 4096;\n private const int MinBufferSize = 128;\n\n private readonly Stream _stream;\n private Encoding _encoding = null!; // only null in NullCancellableStreamReader where this is never used\n private readonly byte[] _encodingPreamble = null!; // only null in NullCancellableStreamReader where this is never used\n private Decoder _decoder = null!; // only null in NullCancellableStreamReader where this is never used\n private readonly byte[] _byteBuffer = null!; // only null in NullCancellableStreamReader where this is never used\n private char[] _charBuffer = null!; // only null in NullCancellableStreamReader where this is never used\n private int _charPos;\n private int _charLen;\n // Record the number of valid bytes in the byteBuffer, for a few checks.\n private int _byteLen;\n // This is used only for preamble detection\n private int _bytePos;\n\n // This is the maximum number of chars we can get from one call to\n // ReadBuffer. Used so ReadBuffer can tell when to copy data into\n // a user's char[] directly, instead of our internal char[].\n private int _maxCharsPerBuffer;\n\n /// True if the writer has been disposed; otherwise, false.\n private bool _disposed;\n\n // We will support looking for byte order marks in the stream and trying\n // to decide what the encoding might be from the byte order marks, IF they\n // exist. But that's all we'll do.\n private bool _detectEncoding;\n\n // Whether we must still check for the encoding's given preamble at the\n // beginning of this file.\n private bool _checkPreamble;\n\n // Whether the stream is most likely not going to give us back as much\n // data as we want the next time we call it. We must do the computation\n // before we do any byte order mark handling and save the result. Note\n // that we need this to allow users to handle streams used for an\n // interactive protocol, where they block waiting for the remote end\n // to send a response, like logging in on a Unix machine.\n private bool _isBlocked;\n\n // The intent of this field is to leave open the underlying stream when\n // disposing of this CancellableStreamReader. A name like _leaveOpen is better,\n // but this type is serializable, and this field's name was _closable.\n private readonly bool _closable; // Whether to close the underlying stream.\n\n // We don't guarantee thread safety on CancellableStreamReader, but we should at\n // least prevent users from trying to read anything while an Async\n // read from the same thread is in progress.\n private Task _asyncReadTask = Task.CompletedTask;\n\n private void CheckAsyncTaskInProgress()\n {\n // We are not locking the access to _asyncReadTask because this is not meant to guarantee thread safety.\n // We are simply trying to deter calling any Read APIs while an async Read from the same thread is in progress.\n if (!_asyncReadTask.IsCompleted)\n {\n ThrowAsyncIOInProgress();\n }\n }\n\n [DoesNotReturn]\n private static void ThrowAsyncIOInProgress() =>\n throw new InvalidOperationException(\"Async IO is in progress\");\n\n // CancellableStreamReader by default will ignore illegal UTF8 characters. We don't want to\n // throw here because we want to be able to read ill-formed data without choking.\n // The high level goal is to be tolerant of encoding errors when we read and very strict\n // when we write. Hence, default StreamWriter encoding will throw on error.\n\n private CancellableStreamReader()\n {\n Debug.Assert(this is NullCancellableStreamReader);\n _stream = Stream.Null;\n _closable = true;\n }\n\n public CancellableStreamReader(Stream stream)\n : this(stream, true)\n {\n }\n\n public CancellableStreamReader(Stream stream, bool detectEncodingFromByteOrderMarks)\n : this(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks, DefaultBufferSize, false)\n {\n }\n\n public CancellableStreamReader(Stream stream, Encoding? encoding)\n : this(stream, encoding, true, DefaultBufferSize, false)\n {\n }\n\n public CancellableStreamReader(Stream stream, Encoding? encoding, bool detectEncodingFromByteOrderMarks)\n : this(stream, encoding, detectEncodingFromByteOrderMarks, DefaultBufferSize, false)\n {\n }\n\n // Creates a new CancellableStreamReader for the given stream. The\n // character encoding is set by encoding and the buffer size,\n // in number of 16-bit characters, is set by bufferSize.\n //\n // Note that detectEncodingFromByteOrderMarks is a very\n // loose attempt at detecting the encoding by looking at the first\n // 3 bytes of the stream. It will recognize UTF-8, little endian\n // unicode, and big endian unicode text, but that's it. If neither\n // of those three match, it will use the Encoding you provided.\n //\n public CancellableStreamReader(Stream stream, Encoding? encoding, bool detectEncodingFromByteOrderMarks, int bufferSize)\n : this(stream, encoding, detectEncodingFromByteOrderMarks, bufferSize, false)\n {\n }\n\n public CancellableStreamReader(Stream stream, Encoding? encoding = null, bool detectEncodingFromByteOrderMarks = true, int bufferSize = -1, bool leaveOpen = false)\n {\n Throw.IfNull(stream);\n\n if (!stream.CanRead)\n {\n throw new ArgumentException(\"Stream not readable.\");\n }\n\n if (bufferSize == -1)\n {\n bufferSize = DefaultBufferSize;\n }\n\n if (bufferSize <= 0)\n {\n throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, \"Buffer size must be greater than zero.\");\n }\n\n _stream = stream;\n _encoding = encoding ??= Encoding.UTF8;\n _decoder = encoding.GetDecoder();\n if (bufferSize < MinBufferSize)\n {\n bufferSize = MinBufferSize;\n }\n\n _byteBuffer = new byte[bufferSize];\n _maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize);\n _charBuffer = new char[_maxCharsPerBuffer];\n _detectEncoding = detectEncodingFromByteOrderMarks;\n _encodingPreamble = encoding.GetPreamble();\n\n // If the preamble length is larger than the byte buffer length,\n // we'll never match it and will enter an infinite loop. This\n // should never happen in practice, but just in case, we'll skip\n // the preamble check for absurdly long preambles.\n int preambleLength = _encodingPreamble.Length;\n _checkPreamble = preambleLength > 0 && preambleLength <= bufferSize;\n\n _closable = !leaveOpen;\n }\n\n public override void Close()\n {\n Dispose(true);\n }\n\n protected override void Dispose(bool disposing)\n {\n if (_disposed)\n {\n return;\n }\n _disposed = true;\n\n // Dispose of our resources if this CancellableStreamReader is closable.\n if (_closable)\n {\n try\n {\n // Note that Stream.Close() can potentially throw here. So we need to\n // ensure cleaning up internal resources, inside the finally block.\n if (disposing)\n {\n _stream.Close();\n }\n }\n finally\n {\n _charPos = 0;\n _charLen = 0;\n base.Dispose(disposing);\n }\n }\n }\n\n public virtual Encoding CurrentEncoding => _encoding;\n\n public virtual Stream BaseStream => _stream;\n\n // DiscardBufferedData tells CancellableStreamReader to throw away its internal\n // buffer contents. This is useful if the user needs to seek on the\n // underlying stream to a known location then wants the CancellableStreamReader\n // to start reading from this new point. This method should be called\n // very sparingly, if ever, since it can lead to very poor performance.\n // However, it may be the only way of handling some scenarios where\n // users need to re-read the contents of a CancellableStreamReader a second time.\n public void DiscardBufferedData()\n {\n CheckAsyncTaskInProgress();\n\n _byteLen = 0;\n _charLen = 0;\n _charPos = 0;\n // in general we'd like to have an invariant that encoding isn't null. However,\n // for startup improvements for NullCancellableStreamReader, we want to delay load encoding.\n if (_encoding != null)\n {\n _decoder = _encoding.GetDecoder();\n }\n _isBlocked = false;\n }\n\n public bool EndOfStream\n {\n get\n {\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n if (_charPos < _charLen)\n {\n return false;\n }\n\n // This may block on pipes!\n int numRead = ReadBuffer();\n return numRead == 0;\n }\n }\n\n public override int Peek()\n {\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n if (_charPos == _charLen)\n {\n if (ReadBuffer() == 0)\n {\n return -1;\n }\n }\n return _charBuffer[_charPos];\n }\n\n public override int Read()\n {\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n if (_charPos == _charLen)\n {\n if (ReadBuffer() == 0)\n {\n return -1;\n }\n }\n int result = _charBuffer[_charPos];\n _charPos++;\n return result;\n }\n\n public override int Read(char[] buffer, int index, int count)\n {\n Throw.IfNull(buffer);\n Throw.IfNegative(index);\n Throw.IfNegative(count);\n\n return ReadSpan(new Span(buffer, index, count));\n }\n\n private int ReadSpan(Span buffer)\n {\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n int charsRead = 0;\n // As a perf optimization, if we had exactly one buffer's worth of\n // data read in, let's try writing directly to the user's buffer.\n bool readToUserBuffer = false;\n int count = buffer.Length;\n while (count > 0)\n {\n int n = _charLen - _charPos;\n if (n == 0)\n {\n n = ReadBuffer(buffer.Slice(charsRead), out readToUserBuffer);\n }\n if (n == 0)\n {\n break; // We're at EOF\n }\n if (n > count)\n {\n n = count;\n }\n if (!readToUserBuffer)\n {\n new Span(_charBuffer, _charPos, n).CopyTo(buffer.Slice(charsRead));\n _charPos += n;\n }\n\n charsRead += n;\n count -= n;\n // This function shouldn't block for an indefinite amount of time,\n // or reading from a network stream won't work right. If we got\n // fewer bytes than we requested, then we want to break right here.\n if (_isBlocked)\n {\n break;\n }\n }\n\n return charsRead;\n }\n\n public override string ReadToEnd()\n {\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n // Call ReadBuffer, then pull data out of charBuffer.\n StringBuilder sb = new StringBuilder(_charLen - _charPos);\n do\n {\n sb.Append(_charBuffer, _charPos, _charLen - _charPos);\n _charPos = _charLen; // Note we consumed these characters\n ReadBuffer();\n } while (_charLen > 0);\n return sb.ToString();\n }\n\n public override int ReadBlock(char[] buffer, int index, int count)\n {\n Throw.IfNull(buffer);\n\n Throw.IfNegative(index);\n Throw.IfNegative(count);\n if (buffer.Length - index < count)\n {\n throw new ArgumentException(\"invalid offset length.\");\n }\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n return base.ReadBlock(buffer, index, count);\n }\n\n // Trims n bytes from the front of the buffer.\n private void CompressBuffer(int n)\n {\n Debug.Assert(_byteLen >= n, \"CompressBuffer was called with a number of bytes greater than the current buffer length. Are two threads using this CancellableStreamReader at the same time?\");\n byte[] byteBuffer = _byteBuffer;\n _ = byteBuffer.Length; // allow JIT to prove object is not null\n new ReadOnlySpan(byteBuffer, n, _byteLen - n).CopyTo(byteBuffer);\n _byteLen -= n;\n }\n\n private void DetectEncoding()\n {\n Debug.Assert(_byteLen >= 2, \"Caller should've validated that at least 2 bytes were available.\");\n\n byte[] byteBuffer = _byteBuffer;\n _detectEncoding = false;\n bool changedEncoding = false;\n\n ushort firstTwoBytes = BinaryPrimitives.ReadUInt16LittleEndian(byteBuffer);\n if (firstTwoBytes == 0xFFFE)\n {\n // Big Endian Unicode\n _encoding = Encoding.BigEndianUnicode;\n CompressBuffer(2);\n changedEncoding = true;\n }\n else if (firstTwoBytes == 0xFEFF)\n {\n // Little Endian Unicode, or possibly little endian UTF32\n if (_byteLen < 4 || byteBuffer[2] != 0 || byteBuffer[3] != 0)\n {\n _encoding = Encoding.Unicode;\n CompressBuffer(2);\n changedEncoding = true;\n }\n else\n {\n _encoding = Encoding.UTF32;\n CompressBuffer(4);\n changedEncoding = true;\n }\n }\n else if (_byteLen >= 3 && firstTwoBytes == 0xBBEF && byteBuffer[2] == 0xBF)\n {\n // UTF-8\n _encoding = Encoding.UTF8;\n CompressBuffer(3);\n changedEncoding = true;\n }\n else if (_byteLen >= 4 && firstTwoBytes == 0 && byteBuffer[2] == 0xFE && byteBuffer[3] == 0xFF)\n {\n // Big Endian UTF32\n _encoding = new UTF32Encoding(bigEndian: true, byteOrderMark: true);\n CompressBuffer(4);\n changedEncoding = true;\n }\n else if (_byteLen == 2)\n {\n _detectEncoding = true;\n }\n // Note: in the future, if we change this algorithm significantly,\n // we can support checking for the preamble of the given encoding.\n\n if (changedEncoding)\n {\n _decoder = _encoding.GetDecoder();\n int newMaxCharsPerBuffer = _encoding.GetMaxCharCount(byteBuffer.Length);\n if (newMaxCharsPerBuffer > _maxCharsPerBuffer)\n {\n _charBuffer = new char[newMaxCharsPerBuffer];\n }\n _maxCharsPerBuffer = newMaxCharsPerBuffer;\n }\n }\n\n // Trims the preamble bytes from the byteBuffer. This routine can be called multiple times\n // and we will buffer the bytes read until the preamble is matched or we determine that\n // there is no match. If there is no match, every byte read previously will be available\n // for further consumption. If there is a match, we will compress the buffer for the\n // leading preamble bytes\n private bool IsPreamble()\n {\n if (!_checkPreamble)\n {\n return false;\n }\n\n return IsPreambleWorker(); // move this call out of the hot path\n bool IsPreambleWorker()\n {\n Debug.Assert(_checkPreamble);\n ReadOnlySpan preamble = _encodingPreamble;\n\n Debug.Assert(_bytePos < preamble.Length, \"_compressPreamble was called with the current bytePos greater than the preamble buffer length. Are two threads using this CancellableStreamReader at the same time?\");\n int len = Math.Min(_byteLen, preamble.Length);\n\n for (int i = _bytePos; i < len; i++)\n {\n if (_byteBuffer[i] != preamble[i])\n {\n _bytePos = 0; // preamble match failed; back up to beginning of buffer\n _checkPreamble = false;\n return false;\n }\n }\n _bytePos = len; // we've matched all bytes up to this point\n\n Debug.Assert(_bytePos <= preamble.Length, \"possible bug in _compressPreamble. Are two threads using this CancellableStreamReader at the same time?\");\n\n if (_bytePos == preamble.Length)\n {\n // We have a match\n CompressBuffer(preamble.Length);\n _bytePos = 0;\n _checkPreamble = false;\n _detectEncoding = false;\n }\n\n return _checkPreamble;\n }\n }\n\n internal virtual int ReadBuffer()\n {\n _charLen = 0;\n _charPos = 0;\n\n if (!_checkPreamble)\n {\n _byteLen = 0;\n }\n\n bool eofReached = false;\n\n do\n {\n if (_checkPreamble)\n {\n Debug.Assert(_bytePos <= _encodingPreamble.Length, \"possible bug in _compressPreamble. Are two threads using this CancellableStreamReader at the same time?\");\n int len = _stream.Read(_byteBuffer, _bytePos, _byteBuffer.Length - _bytePos);\n Debug.Assert(len >= 0, \"Stream.Read returned a negative number! This is a bug in your stream class.\");\n\n if (len == 0)\n {\n eofReached = true;\n break;\n }\n\n _byteLen += len;\n }\n else\n {\n Debug.Assert(_bytePos == 0, \"bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this CancellableStreamReader at the same time?\");\n _byteLen = _stream.Read(_byteBuffer, 0, _byteBuffer.Length);\n Debug.Assert(_byteLen >= 0, \"Stream.Read returned a negative number! This is a bug in your stream class.\");\n\n if (_byteLen == 0)\n {\n eofReached = true;\n break;\n }\n }\n\n // _isBlocked == whether we read fewer bytes than we asked for.\n // Note we must check it here because CompressBuffer or\n // DetectEncoding will change byteLen.\n _isBlocked = (_byteLen < _byteBuffer.Length);\n\n // Check for preamble before detect encoding. This is not to override the\n // user supplied Encoding for the one we implicitly detect. The user could\n // customize the encoding which we will loose, such as ThrowOnError on UTF8\n if (IsPreamble())\n {\n continue;\n }\n\n // If we're supposed to detect the encoding and haven't done so yet,\n // do it. Note this may need to be called more than once.\n if (_detectEncoding && _byteLen >= 2)\n {\n DetectEncoding();\n }\n\n Debug.Assert(_charPos == 0 && _charLen == 0, \"We shouldn't be trying to decode more data if we made progress in an earlier iteration.\");\n _charLen = _decoder.GetChars(_byteBuffer, 0, _byteLen, _charBuffer, 0, flush: false);\n } while (_charLen == 0);\n\n if (eofReached)\n {\n // EOF has been reached - perform final flush.\n // We need to reset _bytePos and _byteLen just in case we hadn't\n // finished processing the preamble before we reached EOF.\n\n Debug.Assert(_charPos == 0 && _charLen == 0, \"We shouldn't be looking for EOF unless we have an empty char buffer.\");\n _charLen = _decoder.GetChars(_byteBuffer, 0, _byteLen, _charBuffer, 0, flush: true);\n _bytePos = 0;\n _byteLen = 0;\n }\n\n return _charLen;\n }\n\n\n // This version has a perf optimization to decode data DIRECTLY into the\n // user's buffer, bypassing CancellableStreamReader's own buffer.\n // This gives a > 20% perf improvement for our encodings across the board,\n // but only when asking for at least the number of characters that one\n // buffer's worth of bytes could produce.\n // This optimization, if run, will break SwitchEncoding, so we must not do\n // this on the first call to ReadBuffer.\n private int ReadBuffer(Span userBuffer, out bool readToUserBuffer)\n {\n _charLen = 0;\n _charPos = 0;\n\n if (!_checkPreamble)\n {\n _byteLen = 0;\n }\n\n bool eofReached = false;\n int charsRead = 0;\n\n // As a perf optimization, we can decode characters DIRECTLY into a\n // user's char[]. We absolutely must not write more characters\n // into the user's buffer than they asked for. Calculating\n // encoding.GetMaxCharCount(byteLen) each time is potentially very\n // expensive - instead, cache the number of chars a full buffer's\n // worth of data may produce. Yes, this makes the perf optimization\n // less aggressive, in that all reads that asked for fewer than AND\n // returned fewer than _maxCharsPerBuffer chars won't get the user\n // buffer optimization. This affects reads where the end of the\n // Stream comes in the middle somewhere, and when you ask for\n // fewer chars than your buffer could produce.\n readToUserBuffer = userBuffer.Length >= _maxCharsPerBuffer;\n\n do\n {\n Debug.Assert(charsRead == 0);\n\n if (_checkPreamble)\n {\n Debug.Assert(_bytePos <= _encodingPreamble.Length, \"possible bug in _compressPreamble. Are two threads using this CancellableStreamReader at the same time?\");\n int len = _stream.Read(_byteBuffer, _bytePos, _byteBuffer.Length - _bytePos);\n Debug.Assert(len >= 0, \"Stream.Read returned a negative number! This is a bug in your stream class.\");\n\n if (len == 0)\n {\n eofReached = true;\n break;\n }\n\n _byteLen += len;\n }\n else\n {\n Debug.Assert(_bytePos == 0, \"bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this CancellableStreamReader at the same time?\");\n _byteLen = _stream.Read(_byteBuffer, 0, _byteBuffer.Length);\n Debug.Assert(_byteLen >= 0, \"Stream.Read returned a negative number! This is a bug in your stream class.\");\n\n if (_byteLen == 0)\n {\n eofReached = true;\n break;\n }\n }\n\n // _isBlocked == whether we read fewer bytes than we asked for.\n // Note we must check it here because CompressBuffer or\n // DetectEncoding will change byteLen.\n _isBlocked = (_byteLen < _byteBuffer.Length);\n\n // Check for preamble before detect encoding. This is not to override the\n // user supplied Encoding for the one we implicitly detect. The user could\n // customize the encoding which we will loose, such as ThrowOnError on UTF8\n // Note: we don't need to recompute readToUserBuffer optimization as IsPreamble\n // doesn't change the encoding or affect _maxCharsPerBuffer\n if (IsPreamble())\n {\n continue;\n }\n\n // On the first call to ReadBuffer, if we're supposed to detect the encoding, do it.\n if (_detectEncoding && _byteLen >= 2)\n {\n DetectEncoding();\n // DetectEncoding changes some buffer state. Recompute this.\n readToUserBuffer = userBuffer.Length >= _maxCharsPerBuffer;\n }\n\n Debug.Assert(charsRead == 0 && _charPos == 0 && _charLen == 0, \"We shouldn't be trying to decode more data if we made progress in an earlier iteration.\");\n if (readToUserBuffer)\n {\n charsRead = GetChars(_decoder, new ReadOnlySpan(_byteBuffer, 0, _byteLen), userBuffer, flush: false);\n }\n else\n {\n charsRead = _decoder.GetChars(_byteBuffer, 0, _byteLen, _charBuffer, 0, flush: false);\n _charLen = charsRead; // Number of chars in CancellableStreamReader's buffer.\n }\n } while (charsRead == 0);\n\n if (eofReached)\n {\n // EOF has been reached - perform final flush.\n // We need to reset _bytePos and _byteLen just in case we hadn't\n // finished processing the preamble before we reached EOF.\n\n Debug.Assert(charsRead == 0 && _charPos == 0 && _charLen == 0, \"We shouldn't be looking for EOF unless we have an empty char buffer.\");\n\n if (readToUserBuffer)\n {\n charsRead = GetChars(_decoder, new ReadOnlySpan(_byteBuffer, 0, _byteLen), userBuffer, flush: true);\n }\n else\n {\n charsRead = _decoder.GetChars(_byteBuffer, 0, _byteLen, _charBuffer, 0, flush: true);\n _charLen = charsRead; // Number of chars in CancellableStreamReader's buffer.\n }\n _bytePos = 0;\n _byteLen = 0;\n }\n\n _isBlocked &= charsRead < userBuffer.Length;\n\n return charsRead;\n }\n\n\n // Reads a line. A line is defined as a sequence of characters followed by\n // a carriage return ('\\r'), a line feed ('\\n'), or a carriage return\n // immediately followed by a line feed. The resulting string does not\n // contain the terminating carriage return and/or line feed. The returned\n // value is null if the end of the input stream has been reached.\n //\n public override string? ReadLine()\n {\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n if (_charPos == _charLen)\n {\n if (ReadBuffer() == 0)\n {\n return null;\n }\n }\n\n var vsb = new ValueStringBuilder(stackalloc char[256]);\n do\n {\n // Look for '\\r' or \\'n'.\n ReadOnlySpan charBufferSpan = _charBuffer.AsSpan(_charPos, _charLen - _charPos);\n Debug.Assert(!charBufferSpan.IsEmpty, \"ReadBuffer returned > 0 but didn't bump _charLen?\");\n\n int idxOfNewline = charBufferSpan.IndexOfAny('\\r', '\\n');\n if (idxOfNewline >= 0)\n {\n string retVal;\n if (vsb.Length == 0)\n {\n retVal = charBufferSpan.Slice(0, idxOfNewline).ToString();\n }\n else\n {\n retVal = string.Concat(vsb.AsSpan().ToString(), charBufferSpan.Slice(0, idxOfNewline).ToString());\n vsb.Dispose();\n }\n\n char matchedChar = charBufferSpan[idxOfNewline];\n _charPos += idxOfNewline + 1;\n\n // If we found '\\r', consume any immediately following '\\n'.\n if (matchedChar == '\\r')\n {\n if (_charPos < _charLen || ReadBuffer() > 0)\n {\n if (_charBuffer[_charPos] == '\\n')\n {\n _charPos++;\n }\n }\n }\n\n return retVal;\n }\n\n // We didn't find '\\r' or '\\n'. Add it to the StringBuilder\n // and loop until we reach a newline or EOF.\n\n vsb.Append(charBufferSpan);\n } while (ReadBuffer() > 0);\n\n return vsb.ToString();\n }\n\n public override Task ReadLineAsync() =>\n ReadLineAsync(default).AsTask();\n\n /// \n /// Reads a line of characters asynchronously from the current stream and returns the data as a string.\n /// \n /// The token to monitor for cancellation requests.\n /// A value task that represents the asynchronous read operation. The value of the TResult\n /// parameter contains the next line from the stream, or is if all of the characters have been read.\n /// The number of characters in the next line is larger than .\n /// The stream reader has been disposed.\n /// The reader is currently in use by a previous read operation.\n /// \n /// The following example shows how to read and print all lines from the file until the end of the file is reached or the operation timed out.\n /// \n /// using CancellationTokenSource tokenSource = new (TimeSpan.FromSeconds(1));\n /// using CancellableStreamReader reader = File.OpenText(\"existingfile.txt\");\n ///\n /// string line;\n /// while ((line = await reader.ReadLineAsync(tokenSource.Token)) is not null)\n /// {\n /// Console.WriteLine(line);\n /// }\n /// \n /// \n /// \n /// If this method is canceled via , some data\n /// that has been read from the current but not stored (by the\n /// ) or returned (to the caller) may be lost.\n /// \n public virtual ValueTask ReadLineAsync(CancellationToken cancellationToken)\n {\n // If we have been inherited into a subclass, the following implementation could be incorrect\n // since it does not call through to Read() which a subclass might have overridden.\n // To be safe we will only use this implementation in cases where we know it is safe to do so,\n // and delegate to our base class (which will call into Read) when we are not sure.\n if (GetType() != typeof(CancellableStreamReader))\n {\n return new ValueTask(base.ReadLineAsync()!);\n }\n\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n Task task = ReadLineAsyncInternal(cancellationToken);\n _asyncReadTask = task;\n\n return new ValueTask(task);\n }\n\n private async Task ReadLineAsyncInternal(CancellationToken cancellationToken)\n {\n if (_charPos == _charLen && (await ReadBufferAsync(cancellationToken).ConfigureAwait(false)) == 0)\n {\n return null;\n }\n\n string retVal;\n char[]? arrayPoolBuffer = null;\n int arrayPoolBufferPos = 0;\n\n do\n {\n char[] charBuffer = _charBuffer;\n int charLen = _charLen;\n int charPos = _charPos;\n\n // Look for '\\r' or \\'n'.\n Debug.Assert(charPos < charLen, \"ReadBuffer returned > 0 but didn't bump _charLen?\");\n\n int idxOfNewline = charBuffer.AsSpan(charPos, charLen - charPos).IndexOfAny('\\r', '\\n');\n if (idxOfNewline >= 0)\n {\n if (arrayPoolBuffer is null)\n {\n retVal = new string(charBuffer, charPos, idxOfNewline);\n }\n else\n {\n retVal = string.Concat(arrayPoolBuffer.AsSpan(0, arrayPoolBufferPos).ToString(), charBuffer.AsSpan(charPos, idxOfNewline).ToString());\n ArrayPool.Shared.Return(arrayPoolBuffer);\n }\n\n charPos += idxOfNewline;\n char matchedChar = charBuffer[charPos++];\n _charPos = charPos;\n\n // If we found '\\r', consume any immediately following '\\n'.\n if (matchedChar == '\\r')\n {\n if (charPos < charLen || (await ReadBufferAsync(cancellationToken).ConfigureAwait(false)) > 0)\n {\n if (_charBuffer[_charPos] == '\\n')\n {\n _charPos++;\n }\n }\n }\n\n return retVal;\n }\n\n // We didn't find '\\r' or '\\n'. Add the read data to the pooled buffer\n // and loop until we reach a newline or EOF.\n if (arrayPoolBuffer is null)\n {\n arrayPoolBuffer = ArrayPool.Shared.Rent(charLen - charPos + 80);\n }\n else if ((arrayPoolBuffer.Length - arrayPoolBufferPos) < (charLen - charPos))\n {\n char[] newBuffer = ArrayPool.Shared.Rent(checked(arrayPoolBufferPos + charLen - charPos));\n arrayPoolBuffer.AsSpan(0, arrayPoolBufferPos).CopyTo(newBuffer);\n ArrayPool.Shared.Return(arrayPoolBuffer);\n arrayPoolBuffer = newBuffer;\n }\n charBuffer.AsSpan(charPos, charLen - charPos).CopyTo(arrayPoolBuffer.AsSpan(arrayPoolBufferPos));\n arrayPoolBufferPos += charLen - charPos;\n }\n while (await ReadBufferAsync(cancellationToken).ConfigureAwait(false) > 0);\n\n if (arrayPoolBuffer is not null)\n {\n retVal = new string(arrayPoolBuffer, 0, arrayPoolBufferPos);\n ArrayPool.Shared.Return(arrayPoolBuffer);\n }\n else\n {\n retVal = string.Empty;\n }\n\n return retVal;\n }\n\n public override Task ReadToEndAsync() => ReadToEndAsync(default);\n\n /// \n /// Reads all characters from the current position to the end of the stream asynchronously and returns them as one string.\n /// \n /// The token to monitor for cancellation requests.\n /// A task that represents the asynchronous read operation. The value of the TResult parameter contains\n /// a string with the characters from the current position to the end of the stream.\n /// The number of characters is larger than .\n /// The stream reader has been disposed.\n /// The reader is currently in use by a previous read operation.\n /// \n /// The following example shows how to read the contents of a file by using the method.\n /// \n /// using CancellationTokenSource tokenSource = new (TimeSpan.FromSeconds(1));\n /// using CancellableStreamReader reader = File.OpenText(\"existingfile.txt\");\n ///\n /// Console.WriteLine(await reader.ReadToEndAsync(tokenSource.Token));\n /// \n /// \n /// \n /// If this method is canceled via , some data\n /// that has been read from the current but not stored (by the\n /// ) or returned (to the caller) may be lost.\n /// \n public virtual Task ReadToEndAsync(CancellationToken cancellationToken)\n {\n // If we have been inherited into a subclass, the following implementation could be incorrect\n // since it does not call through to Read() which a subclass might have overridden.\n // To be safe we will only use this implementation in cases where we know it is safe to do so,\n // and delegate to our base class (which will call into Read) when we are not sure.\n if (GetType() != typeof(CancellableStreamReader))\n {\n return base.ReadToEndAsync();\n }\n\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n Task task = ReadToEndAsyncInternal(cancellationToken);\n _asyncReadTask = task;\n\n return task;\n }\n\n private async Task ReadToEndAsyncInternal(CancellationToken cancellationToken)\n {\n // Call ReadBuffer, then pull data out of charBuffer.\n StringBuilder sb = new StringBuilder(_charLen - _charPos);\n do\n {\n int tmpCharPos = _charPos;\n sb.Append(_charBuffer, tmpCharPos, _charLen - tmpCharPos);\n _charPos = _charLen; // We consumed these characters\n await ReadBufferAsync(cancellationToken).ConfigureAwait(false);\n } while (_charLen > 0);\n\n return sb.ToString();\n }\n\n public override Task ReadAsync(char[] buffer, int index, int count)\n {\n Throw.IfNull(buffer);\n\n Throw.IfNegative(index);\n Throw.IfNegative(count);\n if (buffer.Length - index < count)\n {\n throw new ArgumentException(\"invalid offset length.\");\n }\n\n // If we have been inherited into a subclass, the following implementation could be incorrect\n // since it does not call through to Read() which a subclass might have overridden.\n // To be safe we will only use this implementation in cases where we know it is safe to do so,\n // and delegate to our base class (which will call into Read) when we are not sure.\n if (GetType() != typeof(CancellableStreamReader))\n {\n return base.ReadAsync(buffer, index, count);\n }\n\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n Task task = ReadAsyncInternal(new Memory(buffer, index, count), CancellationToken.None).AsTask();\n _asyncReadTask = task;\n\n return task;\n }\n\n public virtual ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default)\n {\n Debug.Assert(GetType() == typeof(CancellableStreamReader));\n\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n if (cancellationToken.IsCancellationRequested)\n {\n return new ValueTask(Task.FromCanceled(cancellationToken));\n }\n\n return ReadAsyncInternal(buffer, cancellationToken);\n }\n\n private protected virtual async ValueTask ReadAsyncInternal(Memory buffer, CancellationToken cancellationToken)\n {\n if (_charPos == _charLen && (await ReadBufferAsync(cancellationToken).ConfigureAwait(false)) == 0)\n {\n return 0;\n }\n\n int charsRead = 0;\n\n // As a perf optimization, if we had exactly one buffer's worth of\n // data read in, let's try writing directly to the user's buffer.\n bool readToUserBuffer = false;\n\n byte[] tmpByteBuffer = _byteBuffer;\n Stream tmpStream = _stream;\n\n int count = buffer.Length;\n while (count > 0)\n {\n // n is the characters available in _charBuffer\n int n = _charLen - _charPos;\n\n // charBuffer is empty, let's read from the stream\n if (n == 0)\n {\n _charLen = 0;\n _charPos = 0;\n\n if (!_checkPreamble)\n {\n _byteLen = 0;\n }\n\n readToUserBuffer = count >= _maxCharsPerBuffer;\n\n // We loop here so that we read in enough bytes to yield at least 1 char.\n // We break out of the loop if the stream is blocked (EOF is reached).\n do\n {\n Debug.Assert(n == 0);\n\n if (_checkPreamble)\n {\n Debug.Assert(_bytePos <= _encodingPreamble.Length, \"possible bug in _compressPreamble. Are two threads using this CancellableStreamReader at the same time?\");\n int tmpBytePos = _bytePos;\n int len = await tmpStream.ReadAsync(new Memory(tmpByteBuffer, tmpBytePos, tmpByteBuffer.Length - tmpBytePos), cancellationToken).ConfigureAwait(false);\n Debug.Assert(len >= 0, \"Stream.Read returned a negative number! This is a bug in your stream class.\");\n\n if (len == 0)\n {\n // EOF but we might have buffered bytes from previous\n // attempts to detect preamble that needs to be decoded now\n if (_byteLen > 0)\n {\n if (readToUserBuffer)\n {\n n = GetChars(_decoder, new ReadOnlySpan(tmpByteBuffer, 0, _byteLen), buffer.Span.Slice(charsRead), flush: false);\n _charLen = 0; // CancellableStreamReader's buffer is empty.\n }\n else\n {\n n = _decoder.GetChars(tmpByteBuffer, 0, _byteLen, _charBuffer, 0);\n _charLen += n; // Number of chars in CancellableStreamReader's buffer.\n }\n }\n\n // How can part of the preamble yield any chars?\n Debug.Assert(n == 0);\n\n _isBlocked = true;\n break;\n }\n else\n {\n _byteLen += len;\n }\n }\n else\n {\n Debug.Assert(_bytePos == 0, \"_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this CancellableStreamReader at the same time?\");\n\n _byteLen = await tmpStream.ReadAsync(new Memory(tmpByteBuffer), cancellationToken).ConfigureAwait(false);\n\n Debug.Assert(_byteLen >= 0, \"Stream.Read returned a negative number! This is a bug in your stream class.\");\n\n if (_byteLen == 0) // EOF\n {\n _isBlocked = true;\n break;\n }\n }\n\n // _isBlocked == whether we read fewer bytes than we asked for.\n // Note we must check it here because CompressBuffer or\n // DetectEncoding will change _byteLen.\n _isBlocked = (_byteLen < tmpByteBuffer.Length);\n\n // Check for preamble before detect encoding. This is not to override the\n // user supplied Encoding for the one we implicitly detect. The user could\n // customize the encoding which we will loose, such as ThrowOnError on UTF8\n // Note: we don't need to recompute readToUserBuffer optimization as IsPreamble\n // doesn't change the encoding or affect _maxCharsPerBuffer\n if (IsPreamble())\n {\n continue;\n }\n\n // On the first call to ReadBuffer, if we're supposed to detect the encoding, do it.\n if (_detectEncoding && _byteLen >= 2)\n {\n DetectEncoding();\n // DetectEncoding changes some buffer state. Recompute this.\n readToUserBuffer = count >= _maxCharsPerBuffer;\n }\n\n Debug.Assert(n == 0);\n\n _charPos = 0;\n if (readToUserBuffer)\n {\n n = GetChars(_decoder, new ReadOnlySpan(tmpByteBuffer, 0, _byteLen), buffer.Span.Slice(charsRead), flush: false);\n _charLen = 0; // CancellableStreamReader's buffer is empty.\n }\n else\n {\n n = _decoder.GetChars(tmpByteBuffer, 0, _byteLen, _charBuffer, 0);\n _charLen += n; // Number of chars in CancellableStreamReader's buffer.\n }\n } while (n == 0);\n\n if (n == 0)\n {\n break; // We're at EOF\n }\n } // if (n == 0)\n\n // Got more chars in charBuffer than the user requested\n if (n > count)\n {\n n = count;\n }\n\n if (!readToUserBuffer)\n {\n new Span(_charBuffer, _charPos, n).CopyTo(buffer.Span.Slice(charsRead));\n _charPos += n;\n }\n\n charsRead += n;\n count -= n;\n\n // This function shouldn't block for an indefinite amount of time,\n // or reading from a network stream won't work right. If we got\n // fewer bytes than we requested, then we want to break right here.\n if (_isBlocked)\n {\n break;\n }\n } // while (count > 0)\n\n return charsRead;\n }\n\n public override Task ReadBlockAsync(char[] buffer, int index, int count)\n {\n Throw.IfNull(buffer);\n\n Throw.IfNegative(index);\n Throw.IfNegative(count);\n if (buffer.Length - index < count)\n {\n throw new ArgumentException(\"invalid offset length.\");\n }\n\n // If we have been inherited into a subclass, the following implementation could be incorrect\n // since it does not call through to Read() which a subclass might have overridden.\n // To be safe we will only use this implementation in cases where we know it is safe to do so,\n // and delegate to our base class (which will call into Read) when we are not sure.\n if (GetType() != typeof(CancellableStreamReader))\n {\n return base.ReadBlockAsync(buffer, index, count);\n }\n\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n Task task = base.ReadBlockAsync(buffer, index, count);\n _asyncReadTask = task;\n\n return task;\n }\n\n public virtual ValueTask ReadBlockAsync(Memory buffer, CancellationToken cancellationToken = default)\n {\n Debug.Assert(GetType() == typeof(CancellableStreamReader));\n\n ThrowIfDisposed();\n CheckAsyncTaskInProgress();\n\n if (cancellationToken.IsCancellationRequested)\n {\n return new ValueTask(Task.FromCanceled(cancellationToken));\n }\n\n ValueTask vt = ReadBlockAsyncInternal(buffer, cancellationToken);\n if (vt.IsCompletedSuccessfully)\n {\n return vt;\n }\n\n Task t = vt.AsTask();\n _asyncReadTask = t;\n return new ValueTask(t);\n }\n\n private async ValueTask ReadBufferAsync(CancellationToken cancellationToken)\n {\n _charLen = 0;\n _charPos = 0;\n byte[] tmpByteBuffer = _byteBuffer;\n Stream tmpStream = _stream;\n\n if (!_checkPreamble)\n {\n _byteLen = 0;\n }\n\n bool eofReached = false;\n\n do\n {\n if (_checkPreamble)\n {\n Debug.Assert(_bytePos <= _encodingPreamble.Length, \"possible bug in _compressPreamble. Are two threads using this CancellableStreamReader at the same time?\");\n int tmpBytePos = _bytePos;\n int len = await tmpStream.ReadAsync(tmpByteBuffer.AsMemory(tmpBytePos), cancellationToken).ConfigureAwait(false);\n Debug.Assert(len >= 0, \"Stream.Read returned a negative number! This is a bug in your stream class.\");\n\n if (len == 0)\n {\n eofReached = true;\n break;\n }\n\n _byteLen += len;\n }\n else\n {\n Debug.Assert(_bytePos == 0, \"_bytePos can be non zero only when we are trying to _checkPreamble. Are two threads using this CancellableStreamReader at the same time?\");\n _byteLen = await tmpStream.ReadAsync(new Memory(tmpByteBuffer), cancellationToken).ConfigureAwait(false);\n Debug.Assert(_byteLen >= 0, \"Stream.Read returned a negative number! Bug in stream class.\");\n\n if (_byteLen == 0)\n {\n eofReached = true;\n break;\n }\n }\n\n // _isBlocked == whether we read fewer bytes than we asked for.\n // Note we must check it here because CompressBuffer or\n // DetectEncoding will change _byteLen.\n _isBlocked = (_byteLen < tmpByteBuffer.Length);\n\n // Check for preamble before detect encoding. This is not to override the\n // user supplied Encoding for the one we implicitly detect. The user could\n // customize the encoding which we will loose, such as ThrowOnError on UTF8\n if (IsPreamble())\n {\n continue;\n }\n\n // If we're supposed to detect the encoding and haven't done so yet,\n // do it. Note this may need to be called more than once.\n if (_detectEncoding && _byteLen >= 2)\n {\n DetectEncoding();\n }\n\n Debug.Assert(_charPos == 0 && _charLen == 0, \"We shouldn't be trying to decode more data if we made progress in an earlier iteration.\");\n _charLen = _decoder.GetChars(tmpByteBuffer, 0, _byteLen, _charBuffer, 0, flush: false);\n } while (_charLen == 0);\n\n if (eofReached)\n {\n // EOF has been reached - perform final flush.\n // We need to reset _bytePos and _byteLen just in case we hadn't\n // finished processing the preamble before we reached EOF.\n\n Debug.Assert(_charPos == 0 && _charLen == 0, \"We shouldn't be looking for EOF unless we have an empty char buffer.\");\n _charLen = _decoder.GetChars(_byteBuffer, 0, _byteLen, _charBuffer, 0, flush: true);\n _bytePos = 0;\n _byteLen = 0;\n }\n\n return _charLen;\n }\n\n private async ValueTask ReadBlockAsyncInternal(Memory buffer, CancellationToken cancellationToken)\n {\n int n = 0, i;\n do\n {\n i = await ReadAsyncInternal(buffer.Slice(n), cancellationToken).ConfigureAwait(false);\n n += i;\n } while (i > 0 && n < buffer.Length);\n\n return n;\n }\n\n private static unsafe int GetChars(Decoder decoder, ReadOnlySpan bytes, Span chars, bool flush = false)\n {\n Throw.IfNull(decoder);\n if (decoder is null || bytes.IsEmpty || chars.IsEmpty)\n {\n return 0;\n }\n\n fixed (byte* pBytes = bytes)\n fixed (char* pChars = chars)\n {\n return decoder.GetChars(pBytes, bytes.Length, pChars, chars.Length, flush);\n }\n }\n\n private void ThrowIfDisposed()\n {\n if (_disposed)\n {\n ThrowObjectDisposedException();\n }\n\n void ThrowObjectDisposedException() => throw new ObjectDisposedException(GetType().Name, \"reader has been closed.\");\n }\n\n // No data, class doesn't need to be serializable.\n // Note this class is threadsafe.\n internal sealed class NullCancellableStreamReader : CancellableStreamReader\n {\n public override Encoding CurrentEncoding => Encoding.Unicode;\n\n protected override void Dispose(bool disposing)\n {\n // Do nothing - this is essentially unclosable.\n }\n\n public override int Peek() => -1;\n\n public override int Read() => -1;\n\n public override int Read(char[] buffer, int index, int count) => 0;\n\n public override Task ReadAsync(char[] buffer, int index, int count) => Task.FromResult(0);\n\n public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken) =>\n cancellationToken.IsCancellationRequested ? new ValueTask(Task.FromCanceled(cancellationToken)) : default;\n\n public override int ReadBlock(char[] buffer, int index, int count) => 0;\n\n public override Task ReadBlockAsync(char[] buffer, int index, int count) => Task.FromResult(0);\n\n public override ValueTask ReadBlockAsync(Memory buffer, CancellationToken cancellationToken) =>\n cancellationToken.IsCancellationRequested ? new ValueTask(Task.FromCanceled(cancellationToken)) : default;\n\n public override string? ReadLine() => null;\n\n public override Task ReadLineAsync() => Task.FromResult(null);\n\n public override ValueTask ReadLineAsync(CancellationToken cancellationToken) =>\n cancellationToken.IsCancellationRequested ? new ValueTask(Task.FromCanceled(cancellationToken)) : default;\n\n public override string ReadToEnd() => \"\";\n\n public override Task ReadToEndAsync() => Task.FromResult(\"\");\n\n public override Task ReadToEndAsync(CancellationToken cancellationToken) =>\n cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.FromResult(\"\");\n\n private protected override ValueTask ReadAsyncInternal(Memory buffer, CancellationToken cancellationToken) =>\n cancellationToken.IsCancellationRequested ? new ValueTask(Task.FromCanceled(cancellationToken)) : default;\n\n internal override int ReadBuffer() => 0;\n }\n}"], ["/csharp-sdk/src/ModelContextProtocol.AspNetCore/StreamableHttpHandler.cs", "using Microsoft.AspNetCore.DataProtection;\nusing Microsoft.AspNetCore.Http;\nusing Microsoft.AspNetCore.Http.Features;\nusing Microsoft.AspNetCore.WebUtilities;\nusing Microsoft.Extensions.Logging;\nusing Microsoft.Extensions.Options;\nusing Microsoft.Net.Http.Headers;\nusing ModelContextProtocol.AspNetCore.Stateless;\nusing ModelContextProtocol.Protocol;\nusing ModelContextProtocol.Server;\nusing System.Collections.Concurrent;\nusing System.Diagnostics;\nusing System.IO.Pipelines;\nusing System.Security.Claims;\nusing System.Security.Cryptography;\nusing System.Text.Json;\nusing System.Text.Json.Serialization.Metadata;\n\nnamespace ModelContextProtocol.AspNetCore;\n\ninternal sealed class StreamableHttpHandler(\n IOptions mcpServerOptionsSnapshot,\n IOptionsFactory mcpServerOptionsFactory,\n IOptions httpServerTransportOptions,\n IDataProtectionProvider dataProtection,\n ILoggerFactory loggerFactory,\n IServiceProvider applicationServices)\n{\n private const string McpSessionIdHeaderName = \"Mcp-Session-Id\";\n private static readonly JsonTypeInfo s_errorTypeInfo = GetRequiredJsonTypeInfo();\n\n public ConcurrentDictionary> Sessions { get; } = new(StringComparer.Ordinal);\n\n public HttpServerTransportOptions HttpServerTransportOptions => httpServerTransportOptions.Value;\n\n private IDataProtector Protector { get; } = dataProtection.CreateProtector(\"Microsoft.AspNetCore.StreamableHttpHandler.StatelessSessionId\");\n\n public async Task HandlePostRequestAsync(HttpContext context)\n {\n // The Streamable HTTP spec mandates the client MUST accept both application/json and text/event-stream.\n // ASP.NET Core Minimal APIs mostly try to stay out of the business of response content negotiation,\n // so we have to do this manually. The spec doesn't mandate that servers MUST reject these requests,\n // but it's probably good to at least start out trying to be strict.\n var typedHeaders = context.Request.GetTypedHeaders();\n if (!typedHeaders.Accept.Any(MatchesApplicationJsonMediaType) || !typedHeaders.Accept.Any(MatchesTextEventStreamMediaType))\n {\n await WriteJsonRpcErrorAsync(context,\n \"Not Acceptable: Client must accept both application/json and text/event-stream\",\n StatusCodes.Status406NotAcceptable);\n return;\n }\n\n var session = await GetOrCreateSessionAsync(context);\n if (session is null)\n {\n return;\n }\n\n try\n {\n using var _ = session.AcquireReference();\n\n InitializeSseResponse(context);\n var wroteResponse = await session.Transport.HandlePostRequest(new HttpDuplexPipe(context), context.RequestAborted);\n if (!wroteResponse)\n {\n // We wound up writing nothing, so there should be no Content-Type response header.\n context.Response.Headers.ContentType = (string?)null;\n context.Response.StatusCode = StatusCodes.Status202Accepted;\n }\n }\n finally\n {\n // Stateless sessions are 1:1 with HTTP requests and are outlived by the MCP session tracked by the Mcp-Session-Id.\n // Non-stateless sessions are 1:1 with the Mcp-Session-Id and outlive the POST request.\n // Non-stateless sessions get disposed by a DELETE request or the IdleTrackingBackgroundService.\n if (HttpServerTransportOptions.Stateless)\n {\n await session.DisposeAsync();\n }\n }\n }\n\n public async Task HandleGetRequestAsync(HttpContext context)\n {\n if (!context.Request.GetTypedHeaders().Accept.Any(MatchesTextEventStreamMediaType))\n {\n await WriteJsonRpcErrorAsync(context,\n \"Not Acceptable: Client must accept text/event-stream\",\n StatusCodes.Status406NotAcceptable);\n return;\n }\n\n var sessionId = context.Request.Headers[McpSessionIdHeaderName].ToString();\n var session = await GetSessionAsync(context, sessionId);\n if (session is null)\n {\n return;\n }\n\n if (!session.TryStartGetRequest())\n {\n await WriteJsonRpcErrorAsync(context,\n \"Bad Request: This server does not support multiple GET requests. Start a new session to get a new GET SSE response.\",\n StatusCodes.Status400BadRequest);\n return;\n }\n\n using var _ = session.AcquireReference();\n InitializeSseResponse(context);\n\n // We should flush headers to indicate a 200 success quickly, because the initialization response\n // will be sent in response to a different POST request. It might be a while before we send a message\n // over this response body.\n await context.Response.Body.FlushAsync(context.RequestAborted);\n await session.Transport.HandleGetRequest(context.Response.Body, context.RequestAborted);\n }\n\n public async Task HandleDeleteRequestAsync(HttpContext context)\n {\n var sessionId = context.Request.Headers[McpSessionIdHeaderName].ToString();\n if (Sessions.TryRemove(sessionId, out var session))\n {\n await session.DisposeAsync();\n }\n }\n\n private async ValueTask?> GetSessionAsync(HttpContext context, string sessionId)\n {\n HttpMcpSession? session;\n\n if (HttpServerTransportOptions.Stateless)\n {\n var sessionJson = Protector.Unprotect(sessionId);\n var statelessSessionId = JsonSerializer.Deserialize(sessionJson, StatelessSessionIdJsonContext.Default.StatelessSessionId);\n var transport = new StreamableHttpServerTransport\n {\n Stateless = true,\n SessionId = sessionId,\n };\n session = await CreateSessionAsync(context, transport, sessionId, statelessSessionId);\n }\n else if (!Sessions.TryGetValue(sessionId, out session))\n {\n // -32001 isn't part of the MCP standard, but this is what the typescript-sdk currently does.\n // One of the few other usages I found was from some Ethereum JSON-RPC documentation and this\n // JSON-RPC library from Microsoft called StreamJsonRpc where it's called JsonRpcErrorCode.NoMarshaledObjectFound\n // https://learn.microsoft.com/dotnet/api/streamjsonrpc.protocol.jsonrpcerrorcode?view=streamjsonrpc-2.9#fields\n await WriteJsonRpcErrorAsync(context, \"Session not found\", StatusCodes.Status404NotFound, -32001);\n return null;\n }\n\n if (!session.HasSameUserId(context.User))\n {\n await WriteJsonRpcErrorAsync(context,\n \"Forbidden: The currently authenticated user does not match the user who initiated the session.\",\n StatusCodes.Status403Forbidden);\n return null;\n }\n\n context.Response.Headers[McpSessionIdHeaderName] = session.Id;\n context.Features.Set(session.Server);\n return session;\n }\n\n private async ValueTask?> GetOrCreateSessionAsync(HttpContext context)\n {\n var sessionId = context.Request.Headers[McpSessionIdHeaderName].ToString();\n\n if (string.IsNullOrEmpty(sessionId))\n {\n return await StartNewSessionAsync(context);\n }\n else\n {\n return await GetSessionAsync(context, sessionId);\n }\n }\n\n private async ValueTask> StartNewSessionAsync(HttpContext context)\n {\n string sessionId;\n StreamableHttpServerTransport transport;\n\n if (!HttpServerTransportOptions.Stateless)\n {\n sessionId = MakeNewSessionId();\n transport = new()\n {\n SessionId = sessionId,\n FlowExecutionContextFromRequests = !HttpServerTransportOptions.PerSessionExecutionContext,\n };\n context.Response.Headers[McpSessionIdHeaderName] = sessionId;\n }\n else\n {\n // \"(uninitialized stateless id)\" is not written anywhere. We delay writing the MCP-Session-Id\n // until after we receive the initialize request with the client info we need to serialize.\n sessionId = \"(uninitialized stateless id)\";\n transport = new()\n {\n Stateless = true,\n };\n ScheduleStatelessSessionIdWrite(context, transport);\n }\n\n var session = await CreateSessionAsync(context, transport, sessionId);\n\n // The HttpMcpSession is not stored between requests in stateless mode. Instead, the session is recreated from the MCP-Session-Id.\n if (!HttpServerTransportOptions.Stateless)\n {\n if (!Sessions.TryAdd(sessionId, session))\n {\n throw new UnreachableException($\"Unreachable given good entropy! Session with ID '{sessionId}' has already been created.\");\n }\n }\n\n return session;\n }\n\n private async ValueTask> CreateSessionAsync(\n HttpContext context,\n StreamableHttpServerTransport transport,\n string sessionId,\n StatelessSessionId? statelessId = null)\n {\n var mcpServerServices = applicationServices;\n var mcpServerOptions = mcpServerOptionsSnapshot.Value;\n if (statelessId is not null || HttpServerTransportOptions.ConfigureSessionOptions is not null)\n {\n mcpServerOptions = mcpServerOptionsFactory.Create(Options.DefaultName);\n\n if (statelessId is not null)\n {\n // The session does not outlive the request in stateless mode.\n mcpServerServices = context.RequestServices;\n mcpServerOptions.ScopeRequests = false;\n mcpServerOptions.KnownClientInfo = statelessId.ClientInfo;\n }\n\n if (HttpServerTransportOptions.ConfigureSessionOptions is { } configureSessionOptions)\n {\n await configureSessionOptions(context, mcpServerOptions, context.RequestAborted);\n }\n }\n\n var server = McpServerFactory.Create(transport, mcpServerOptions, loggerFactory, mcpServerServices);\n context.Features.Set(server);\n\n var userIdClaim = statelessId?.UserIdClaim ?? GetUserIdClaim(context.User);\n var session = new HttpMcpSession(sessionId, transport, userIdClaim, HttpServerTransportOptions.TimeProvider)\n {\n Server = server,\n };\n\n var runSessionAsync = HttpServerTransportOptions.RunSessionHandler ?? RunSessionAsync;\n session.ServerRunTask = runSessionAsync(context, server, session.SessionClosed);\n\n return session;\n }\n\n private static Task WriteJsonRpcErrorAsync(HttpContext context, string errorMessage, int statusCode, int errorCode = -32000)\n {\n var jsonRpcError = new JsonRpcError\n {\n Error = new()\n {\n Code = errorCode,\n Message = errorMessage,\n },\n };\n return Results.Json(jsonRpcError, s_errorTypeInfo, statusCode: statusCode).ExecuteAsync(context);\n }\n\n internal static void InitializeSseResponse(HttpContext context)\n {\n context.Response.Headers.ContentType = \"text/event-stream\";\n context.Response.Headers.CacheControl = \"no-cache,no-store\";\n\n // Make sure we disable all response buffering for SSE.\n context.Response.Headers.ContentEncoding = \"identity\";\n context.Features.GetRequiredFeature().DisableBuffering();\n }\n\n internal static string MakeNewSessionId()\n {\n Span buffer = stackalloc byte[16];\n RandomNumberGenerator.Fill(buffer);\n return WebEncoders.Base64UrlEncode(buffer);\n }\n\n private void ScheduleStatelessSessionIdWrite(HttpContext context, StreamableHttpServerTransport transport)\n {\n transport.OnInitRequestReceived = initRequestParams =>\n {\n var statelessId = new StatelessSessionId\n {\n ClientInfo = initRequestParams?.ClientInfo,\n UserIdClaim = GetUserIdClaim(context.User),\n };\n\n var sessionJson = JsonSerializer.Serialize(statelessId, StatelessSessionIdJsonContext.Default.StatelessSessionId);\n transport.SessionId = Protector.Protect(sessionJson);\n context.Response.Headers[McpSessionIdHeaderName] = transport.SessionId;\n return ValueTask.CompletedTask;\n };\n }\n\n internal static Task RunSessionAsync(HttpContext httpContext, IMcpServer session, CancellationToken requestAborted)\n => session.RunAsync(requestAborted);\n\n // SignalR only checks for ClaimTypes.NameIdentifier in HttpConnectionDispatcher, but AspNetCore.Antiforgery checks that plus the sub and UPN claims.\n // However, we short-circuit unlike antiforgery since we expect to call this to verify MCP messages a lot more frequently than\n // verifying antiforgery tokens from